Search Results

Search found 116 results on 5 pages for 'getresource'.

Page 4/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • NullPointerException when accessing image files in a .jar file

    - by user548240
    Hi, I have pretty much tried everything but still have this same problem. I have the following setup: I have a images.jar containing a folder called 'images' in which there are multiple image files. I add images.jar to the java build path of the project in eclipse, and i've been trying to use the following code to access the individual images in the jar: URL url = this.getClass().getResource("images/a.png"); ImageIcon icon = new ImageIcon (url); Unfortunately, the URL object is always NULL. I don't think this has anything to do with where I put images.jar file as it is added to the classpath in eclipse. I have also tried using the path '/images/a.png', but still the same problem. Any suggestion would be extremely welcome! Thanks.

    Read the article

  • Why download popup window in browser not showing up when using JAX-RS v.s. standard servlet?

    - by masato-san
    When I try using standard servlet approach, in my browser the popup window shows up asking me whether to open .xls file or save it. I tried the exactly same code via JAX-RS and the browser popup won't show up somehow. Has anyone encounter this mystery? Standard servlet that works: package local.test.servlet; import java.io.IOException; import java.net.URL; import java.net.URLDecoder; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import local.test.jaxrs.ExcellaTestResource; import org.apache.poi.ss.usermodel.Workbook; import org.bbreak.excella.core.BookData; import org.bbreak.excella.core.exception.ExportException; import org.bbreak.excella.reports.exporter.ExcelExporter; import org.bbreak.excella.reports.exporter.ReportBookExporter; import org.bbreak.excella.reports.model.ConvertConfiguration; import org.bbreak.excella.reports.model.ReportBook; import org.bbreak.excella.reports.model.ReportSheet; import org.bbreak.excella.reports.processor.ReportProcessor; @WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"}) public class ExcelServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //C:\Users\m-takayashiki\.netbeans\6.9\config\GF3\domain1 // ================== ?????? ======================= URL templateFileUrl = ExcellaTestResource.class.getResource("?????????.xls"); // /C:/Users/m-takayashiki/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/?????????.xls System.out.println(templateFileUrl.getPath()); String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8"); String outputFileDir = "MasatoExcelHorizontalOutput"; ReportProcessor reportProcessor = new ReportProcessor(); ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE); ReportSheet outputSheet = new ReportSheet("??????"); outputBook.addReportSheet(outputSheet); // ======================================================== // --------------- ?????? ------------------------- reportProcessor.addReportBookExporter(new OutputStreamExporter(response)); System.out.println("wtf???"); reportProcessor.process(outputBook); System.out.println("done!!"); } catch(Exception e) { System.out.println(e); } } //end doGet() @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }//end class class OutputStreamExporter extends ReportBookExporter { private HttpServletResponse response; public OutputStreamExporter(HttpServletResponse response) { this.response = response; } @Override public String getExtention() { return null; } @Override public String getFormatType() { return ExcelExporter.FORMAT_TYPE; } @Override public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException { System.out.println(book.getFirstVisibleTab()); System.out.println(book.getSheetName(0)); //TODO write to stream try { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls"); book.write(response.getOutputStream()); response.getOutputStream().close(); System.out.println("booya!!"); } catch(Exception e) { System.out.println(e); } } }//end class JAX-RS way that won't display popup: package local.test.jaxrs; import java.net.URL; import java.net.URLDecoder; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.Path; import javax.ws.rs.GET; import javax.ws.rs.Produces; import org.apache.poi.ss.usermodel.Workbook; import org.bbreak.excella.core.BookData; import org.bbreak.excella.core.exception.ExportException; import org.bbreak.excella.reports.exporter.ExcelExporter; import org.bbreak.excella.reports.exporter.ReportBookExporter; import org.bbreak.excella.reports.model.ConvertConfiguration; import org.bbreak.excella.reports.model.ReportBook; import org.bbreak.excella.reports.model.ReportSheet; import org.bbreak.excella.reports.processor.ReportProcessor; @Path("excellaTest") public class ExcellaTestResource { @Context private UriInfo context; @Context private HttpServletResponse response; @Context private HttpServletRequest request; public ExcellaTestResource() { } @Path("horizontalProcess") @GET //@Produces("application/vnd.ms-excel") @Produces("application/vnd.ms-excel") public void getProcessHorizontally() { try { //C:\Users\m-takayashiki\.netbeans\6.9\config\GF3\domain1 // ================== ?????? ======================= URL templateFileUrl = this.getClass().getResource("?????????.xls"); // /C:/Users/m-takayashiki/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/?????????.xls System.out.println(templateFileUrl.getPath()); String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8"); String outputFileDir = "MasatoExcelHorizontalOutput"; ReportProcessor reportProcessor = new ReportProcessor(); ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE); ReportSheet outputSheet = new ReportSheet("??????"); outputBook.addReportSheet(outputSheet); // ======================================================== // --------------- ?????? ------------------------- reportProcessor.addReportBookExporter(new OutputStreamExporter(response)); System.out.println("wtf???"); reportProcessor.process(outputBook); System.out.println("done!!"); } catch(Exception e) { System.out.println(e); } //return response; return; } }//end class class OutputStreamExporter extends ReportBookExporter { private HttpServletResponse response; public OutputStreamExporter(HttpServletResponse response) { this.response = response; } @Override public String getExtention() { return null; } @Override public String getFormatType() { return ExcelExporter.FORMAT_TYPE; } @Override public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException { //TODO write to stream try { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls"); book.write(response.getOutputStream()); response.getOutputStream().close(); System.out.println("booya!!"); } catch(Exception e) { System.out.println(e); } } }//end class

    Read the article

  • Hidden exceptions

    - by user12617285
    Occasionally you may find yourself in a Java application environment where exceptions in your code are being caught by the application framework and either silently swallowed or converted into a generic exception. Either way, the potentially useful details of your original exception are inaccessible. Wouldn't it be nice if there was a VM option that showed the stack trace for every exception thrown, whether or not it's caught? In fact, HotSpot includes such an option: -XX:+TraceExceptions. However, this option is only available in a debug build of HotSpot (search globals.hpp for TraceExceptions). And based on a quick skim of the HotSpot source code, this option only prints the exception class and message. A more useful capability would be to have the complete stack trace printed as well as the code location catching the exception. This is what the various TraceException* options in in Maxine do (and more). That said, there is a way to achieve a limited version of the same thing with a stock standard JVM. It involves the use of the -Xbootclasspath/p non-standard option. The trick is to modify the source of java.lang.Exception by inserting the following: private static final boolean logging = System.getProperty("TraceExceptions") != null; private void log() { if (logging && sun.misc.VM.isBooted()) { printStackTrace(); } } Then every constructor simply needs to be modified to call log() just before returning: public Exception(String message) { super(message); log(); } public Exception(String message, Throwable cause) { super(message, cause); log(); } // etc... You now need to compile the modified Exception.java source and prepend the resulting class to the boot class path as well as add -DTraceExceptions to your java command line. Here's a console session showing these steps: % mkdir boot % javac -d boot Exception.java % java -DTraceExceptions -Xbootclasspath/p:boot -cp com.oracle.max.vm/bin test.output.HelloWorld java.util.zip.ZipException: error in opening zip file at java.util.zip.ZipFile.open(Native Method) at java.util.zip.ZipFile.(ZipFile.java:127) at java.util.jar.JarFile.(JarFile.java:135) at java.util.jar.JarFile.(JarFile.java:72) at sun.misc.URLClassPath$JarLoader.getJarFile(URLClassPath.java:646) at sun.misc.URLClassPath$JarLoader.access$600(URLClassPath.java:540) at sun.misc.URLClassPath$JarLoader$1.run(URLClassPath.java:607) at java.security.AccessController.doPrivileged(Native Method) at sun.misc.URLClassPath$JarLoader.ensureOpen(URLClassPath.java:599) at sun.misc.URLClassPath$JarLoader.(URLClassPath.java:583) at sun.misc.URLClassPath$3.run(URLClassPath.java:333) at java.security.AccessController.doPrivileged(Native Method) at sun.misc.URLClassPath.getLoader(URLClassPath.java:322) at sun.misc.URLClassPath.getLoader(URLClassPath.java:299) at sun.misc.URLClassPath.getResource(URLClassPath.java:168) at java.net.URLClassLoader$1.run(URLClassLoader.java:194) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at sun.misc.Launcher$ExtClassLoader.findClass(Launcher.java:229) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at java.lang.ClassLoader.loadClass(ClassLoader.java:295) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) java.security.PrivilegedActionException at java.security.AccessController.doPrivileged(Native Method) at sun.misc.URLClassPath$JarLoader.ensureOpen(URLClassPath.java:599) at sun.misc.URLClassPath$JarLoader.(URLClassPath.java:583) at sun.misc.URLClassPath$3.run(URLClassPath.java:333) at java.security.AccessController.doPrivileged(Native Method) at sun.misc.URLClassPath.getLoader(URLClassPath.java:322) ... It's worth pointing out that this is not as useful as direct VM support for tracing exceptions. It has (at least) the following limitations: The trace is shown for every exception, whether it is thrown or not. It only applies to subclasses of java.lang.Exception as there appears to be bootstrap issues when the modification is applied to Throwable.java. It does not show you where the exception was caught. It involves overriding a class in rt.jar, something should never be done in a non-development environment.

    Read the article

  • Java, two JPanel on JFrame - Settings JPanel, StartMenu JPanel [on hold]

    - by Andy Tyurin
    There is my first question and I welcome community! I'm making a simple game and have some problems with Start menu. I have three buttons on my JPanel StartMenu and when I click "Settings" button, new JPanel will be open, but I don't know why buttons from StartMenu JPanel appeared in my Settings JPanel. My "Settings" JPanel has one ugly button "Back" in center and ugly grey background. I made some screens to see a problem. Start Menu JPanel when game launched Settings JPanel when button clicked Settings JPanel when mouse was over settings window There is code of StartMenu class: public class StartMenu extends JPanel { private GameButton startGameButton = new GameButton("Start game"); private GameButton settingsGameButton = new GameButton("Settings"); private GameButton exitGameButton = new GameButton("Exit game"); private Image bgImage = new ImageIcon(getClass().getClassLoader().getResource("ru/andydevs/astraLaserForce/bg.png")).getImage(); private int posX; private int posY; final private int WIDTH=(int)Game.SCREEN_DIMENSION.getWidth()/3; final private int HEIGHT=(int)Game.SCREEN_DIMENSION.getHeight()/2; public StartMenu() { setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); setSize(new Dimension(WIDTH, HEIGHT)); posX=(int)Game.SCREEN_DIMENSION.getWidth()/2-WIDTH/2; posY=(int)Game.SCREEN_DIMENSION.getHeight()/2-HEIGHT/2; setBounds(posX, posY,WIDTH,HEIGHT); c.ipadx=95; c.ipady=15; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(20,0,0,0); c.gridy=0; add(startGameButton, c); c.gridy=1; c.insets = new Insets(20,0,0,0); System.out.println(settingsGameButton.getWidth()); add(settingsGameButton, c); c.gridy=2; c.insets = new Insets(20,0,0,0); add(exitGameButton, c); settingsGameButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GameOptionsPanel gop = new GameOptionsPanel(); Game.container.add(gop); Game.container.setComponentZOrder(gop, 0); Game.container.revalidate(); Game.container.repaint(); } }); exitGameButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Main.currentGame.stop(); } }); } public void paintComponent(Graphics g) { g.drawImage(bgImage,0,0,WIDTH,HEIGHT,null); } } There is code of Settings JPanel public class GameOptionsPanel extends GamePanel { private GameButton backButton = new GameButton("Back"); private GameOptionsPanel that; public GameOptionsPanel() { super((int) (Game.SCREEN_DIMENSION.getWidth()/3), (int) (Game.SCREEN_DIMENSION.getHeight()/2), new Color(50,50,50)); that=this; setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill=gbc.HORIZONTAL; add(backButton); backButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Game.container.remove(that); Game.container.revalidate(); Game.container.repaint(); } }); } } I glad to see some suggestions. Thanks.

    Read the article

  • Extending Zend View Helper Placeholder

    - by Sonny
    I was reading the manual about basic placeholder usage, and it has this example: class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { // ... protected function _initSidebar() { $this->bootstrap('View'); $view = $this->getResource('View'); $view->placeholder('sidebar') // "prefix" -> markup to emit once before all items in collection ->setPrefix("<div class=\"sidebar\">\n <div class=\"block\">\n") // "separator" -> markup to emit between items in a collection ->setSeparator("</div>\n <div class=\"block\">\n") // "postfix" -> markup to emit once after all items in a collection ->setPostfix("</div>\n</div>"); } // ... } I want to acommplish almost exactly that, but I'd like to conditionally add more class values to the repeating divs, at time of rendering if possible, when all the content is in the placeholder. One thing I specifically want to do is add the class of "first" to the first element and "last" to the last element. I assume that I'll have to extend the Zend_View_Helper_Placeholder class to accomplish this.

    Read the article

  • Zend Framework subdomain+subfolder router rewrite problem

    - by zf_novice
    I'm new to Zend Framwork and this is an issue I've been struggling for several hours already... I'm trying to chain Hostname and standard Route in order to get url with subdomain+subfolders ie.: http:// lang.mydomain.com/myapplication/public/controller http:// lang.mydomain.com/myapplication/public/controller/action (sorry for the empty space in the address, this site won't allow links) Basically what I have done in Bootstrap is: // add language to default route $routePath = new Zend_Controller_Router_Route( ':controller/:action/*', array('controller'=>'index','action' => 'index','module'=>'default') ); $routeHostname = new Zend_Controller_Router_Route_Hostname( ':lang.mydomain.com', array('lang'=>$lang) ); $frontController = $this->getResource('FrontController'); $router = $frontController->getRouter(); $router->addRoute('default', $routeHostname->chain($routePath)) $frontController->setRouter($router); it finds the route ok, but every time I generate url in view or layout by $this-url() <?php echo $this->url( array( 'controller'=> 'guestbook', 'action' => 'sign', 'lang' => Zend_Registry::get('lang'), ), 'default', true) ?>"> I get http:// lang.mydomain.com/controller instead of http:// lang.mydomain.com/myapplication/public/controller I've been trying to set baseUrl on front controller but no luck... Also I've tried the static route with myapplication/public or following standard route: 'myapplication/public/:controller/:action/*' - it result with "An error occurred Page not found Exception information: Message: No route matched the request" and empty request Is there any way to assembly subdomain with subfolder in Zend Framwork?? EDIT: I changed above to: $frontController->setBaseUrl('.'); // add language to default route $routePath = new Zend_Controller_Router_Route( 'quickstart/public/:controller/:action/*', array( 'controller'=>'index', 'action' => 'index', 'module'=>'default', ) ); and it works form me, although I'm not sure whether it's been correct approach...

    Read the article

  • load class not in classpath dynamically in web application - without using custom classloader

    - by swdeveloper
    I am developing a web application. The web application generates java classes on the fly. For example it generates class com.people.Customer.java In my code, I dynamically compile this to get com.people.Customer.class and store in some directory say repository/com/people/Customer.class which is not on the classpath of my application server.My application server(I am using WebSphere Application Server/Apache Tomcat etc) picks up the classes from the WEB-INF/classes directory. The Classloader would use this to load the classes. After compilation I need to load this class so that it becomes accessible to other classes using it after its creation. 4.When I use Thread.currentThread().getContextClassLoader().loadClass(com.people.Customer) obviously the Classloader is not able to load the class, since its not on the classpath(not in WEB-INF/classes). Due to similar reasons, getResource(..) or getResourceAsStream(..) also does not work. I need a way to : Read the class Customer.class maybe as a stream (or any other way would do) and then load it. Following are the constraints: I cannot add the repository folder to the WEB-INF/classes folder. I cannot create a new Custom ClassLoader. If I create a new ClassLoader and this loads the class, it will not be accessible to its parent ClassLoader. Is there any way of achieving this? If not this, in the worse case, is there a way of overriding the default class loader with a custom class loader for web applications the same classloader should be used to load applications throughout entire lifecycle of my web application. Appreciate any solution :)

    Read the article

  • Pentaho - Reporting Tool - Is the .prpt file (report template file) contains datasource information

    - by Yatendra Goel
    I am new Pentaho Reporting Tool. I have the following question: When I created a report using Pentaho Report Designer, it output a report file having .prpt extension. After that I found an example on internet where the following code were used to display the report in html format:| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ResourceManager manager = new ResourceManager(); manager.registerDefaults(); String reportPath = "file:" + this.getServletContext().getRealPath("sampleReport.prpt"); try { Resource res = manager.createDirectly(new URL(reportPath), MasterReport.class); MasterReport report = (MasterReport) res.getResource(); HtmlReportUtil.createStreamHTML(report, response.getOutputStream()); } catch (Exception e) { e.printStackTrace(); } } And the report got printed successfully. So as we haven't specified any datasource information here, I think that the .prpt file contains that information in it. If that's true than Isn't Jasper is better Reporting tool than Pentaho because when we display Jasper reports, we have to provide datasource details also so in that way our report is flexible and is not bound to any particular database.

    Read the article

  • How do you invoke a python script inside a jar file using python ?

    - by Trevor
    I'm working on an application that intersperses a bunch of jython and java code. Due to the nature of the program (using wsadmin) we are really restricted to Python 2.1 We currently have a jar containing both java source and .py modules. The code is currently invoked using java, but I'd like to remove this in favor of migrating as much functionality as possible to jython. The problem I have is that I want to either import or execute python modules inside the existing jar file from a calling jython script. I've tried a couple of different ways without success. My directory structure looks like: application.jar |-- com |--example |-- action |-- MyAction.class |-- pre_myAction.py The 1st approach I tried was to do imports from the jar. I added the jar to my sys.path and tried to import the module using both import com.example.action.myAction and import myAction. No success however, even when I put init.py files into the directory at each level. The 2nd approach I tried was to load the resource using the java class. So I wrote the below code: import sys import os import com.example.action.MyAction as MyAction scriptName = str(MyAction.getResource('/com/example/action/myAction.py')) scriptStr = MyAction.getResourceAsStream('/com/example/action/myAction.py') try: print execfile(scriptStr) except: print "failed 1" try: print execfile(scriptName) except: print "failed 2" Both of these failed. I'm at a bit of a loss now as to how I should proceed. Any ideas ? cheers, Trevor

    Read the article

  • how to fix: ctags null expansion of name pattern "\1"

    - by bua
    Hi, As the title points I have problem with ctags when trying to parse user-defined language. Basically I've followed those instructions. The quickest and easiest way to do this is by defining a new language using the program options. In order to have Swine support available every time I start ctags, I will place the following lines into the file $HOME/.ctags, which is read in every time ctags starts: --langdef=swine --langmap=swine:.swn --regex-swine=/^def[ \t]*([a-zA-Z0-9_]+)/\1/d,definition/ The first line defines the new language, the second maps a file extension to it, and the third defines a regular expression to identify a language definition and generate a tag file entry for it. I've tried different flags: b,e for regex. My definition of tag is: --regex-q=/^[ \t]*[^[:space:]]*[:space:]*:[:space:]*{/\l/f,function/b When I replace \1 with anything else (ascii caracter set ), It works. the output is: (--regex-q=/^[ \t]*[^[:space:]]*[:space:]*:[:space:]*{/my function name/f,function/b) !_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/ !_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/ !_TAG_PROGRAM_AUTHOR Darren Hiebert /[email protected]/ !_TAG_PROGRAM_NAME Exuberant Ctags // !_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/ !_TAG_PROGRAM_VERSION 5.8 // my function name file.q /^.ras.getLocation:{[u]$/;" f my function name file.q /^.a.getResource:{[u; pass]$/;" f my function name file.q /^.a.init:{$/;" f my function name file.q /^.a.kill:{[u; force]$/;" f my function name file.q /^.asdf.status:{[what; u]$/;" f my function name file.q /^.pc:{$/;" f Why \1 doesn't work? (I've tried all 1-9)

    Read the article

  • How to use log4j for a axis2 webservice

    - by KItis
    I have created a simple axis2 webservice to understand logging functionality in a webservice. in this sample webservice, when a client calls this webservice, first it reads the log4j.property file. then i can see the logs being printed on console. but i have included file appender too into the property file. but i can not file the log file any where in my sample webapplication. i am using tomcat to run the webservice. following is webservice interface method called by client. package test; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class WSInterface { static final Logger logger = Logger.getLogger(WSInterface.class); public String log4jTest(String input){ InputStream inputStream = this.getClass().getClassLoader() .getResourceAsStream(input); Properties properties = new Properties(); System.out.println("InputStream is: " + inputStream); //load the inputStream using the Properties try { properties.load(inputStream); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } PropertyConfigurator.configure(properties); logger.debug("Hello World!"); Class myclass = WSInterface.class; String url = myclass.getResource("WSInterface.class").toString(); String output = ""; return url; } }

    Read the article

  • Loading velocity template inside a jar file

    - by Rafael
    I have a project where I want to load a velocity template to complete it with parameters. The whole application is packaged as a jar file. What I initially thought of doing was this: VelocityEngine ve = new VelocityEngine(); URL url = this.getClass().getResource("/templates/"); File file = new File(url.getFile()); ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "file"); ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, file.getAbsolutePath()); ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true"); ve.init(); VelocityContext context = new VelocityContext(); if (properties != null) { stringfyNulls(properties); for (Map.Entry<String, Object> property : properties.entrySet()) { context.put(property.getKey(), property.getValue()); } } final String templatePath = templateName + ".vm"; Template template = ve.getTemplate(templatePath, "UTF-8"); String outFileName = File.createTempFile("p2d_report", ".html").getAbsolutePath(); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outFileName))); template.merge(context, writer); writer.flush(); writer.close(); And this works fine when I run it in eclipse. However, once I package the program and try to run it using the command line I get an error because the file could not be found. I imagine the problem is in this line: ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, file.getAbsolutePath()); Because in a jar the absolute file does not exist, since it's inside a zip, but I couldn't yet find a better way to do it. Anyone has any ideas?

    Read the article

  • Zend Framework: Zend_DB Error

    - by Sergio E.
    I'm trying to learn ZF, but got strange error after 20 minutes :) Fatal error: Uncaught exception 'Zend_Db_Adapter_Exception' with message 'Configuration array must have a key for 'dbname' that names the database instance' What does this error mean? I got DB information in my config file: resources.db.adapter=pdo_mysql resources.db.host=localhost resources.db.username=name resources.db.password=pass resources.db.dbname=name Any suggestions? EDIT: This is my model file /app/models/DbTable/Bands.php: class Model_DbTable_Bands extends Zend_Db_Table_Abstract { protected $_name = 'zend_bands'; } Index controller action: public function indexAction() { $albums = new Model_DbTable_Bands(); $this->view->albums = $albums->fetchAll(); } EDIT All codes: bootstrap.php protected function _initAutoload() { $autoloader = new Zend_Application_Module_Autoloader(array( 'namespace' => '', 'basePath' => dirname(__FILE__), )); return $autoloader; } protected function _initDoctype() { $this->bootstrap('view'); $view = $this->getResource('view'); $view->doctype('XHTML1_STRICT'); } public static function setupDatabase() { $config = self::$registry->configuration; $db = Zend_Db::factory($config->db); $db->query("SET NAMES 'utf8'"); self::$registry->database = $db; Zend_Db_Table::setDefaultAdapter($db); Zend_Db_Table_Abstract::setDefaultAdapter($db); } IndexController.php class IndexController extends Zend_Controller_Action { public function init() { /* Initialize action controller here */ } public function indexAction() { $albums = new Model_DbTable_Bands(); $this->view->albums = $albums->fetchAll(); } } configs/application.ini, changed database and provided password: [development : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 db.adapter = PDO_MYSQL db.params.host = localhost db.params.username = root db.params.password = pedro db.params.dbname = test models/DbTable/Bands.php class Model_DbTable_Bands extends Zend_Db_Table_Abstract { protected $_name = 'cakephp_bands'; public function getAlbum($id) { $id = (int)$id; $row = $this->fetchRow('id = ' . $id); if (!$row) { throw new Exception("Count not find row $id"); } return $row->toArray(); } }

    Read the article

  • Java applet loading images from external jars

    - by Mathias
    I have a jar on a server, and users should be able to develop extensions for it. Therefore the jars main class should be extended and some resources should be added to a second user created jar which will be loaded from another server or locally. Now I have problems accessing the resources (images) from the user loaded jars. Heres is the structure: My Server: game.jar containing game.class images.class ... image1.png (...) Local: user.jar containing: user.class extends game userimage.png The extension is loaded via Greasemonkey, it modifies the "archive" attribute to "/home/username/user.jar, game.jar" and the "code" attribute to "user.class". The user should be able to overwrite already defined images. If the image does not exist in game.jar, it is loaded correctly from user.jar. But the images loaded early in the game are always loaded from the game.jar, others seem to be overwritten correctly by the user. Is there a way to make sure they are always loaded in the correct order? This might be because of some caching mechanism. Because Greasemonkey removes the game from the page, changes the archive and code and reinsert it, the game is loaded without a mod for a brief second. In that time, images are loaded as expected from game jar, but those are the ones not being overwritable by the user. But how to avoid it? Another thing: If I overwrite the "run" method in user.class, the game is unable to load any image at all. Not from the user.jar and not from the game.jar. Java doesn't find the image, as the URL object "getClass().getResource(imagename)" returns with null. I tried to overwrite the image.class, but that doesn't fix the problem, unless I overwrite every class from game.class involved into calling the image.class

    Read the article

  • Magento: Attribute always returns default value in catalog view, works fine in product view

    - by colinodell
    I've created a new Yes/No attribute for products. I've extended the Product model to do some custom logic and the custom functions are working everywhere. When I initially tried getting the custom attribute value, I ran into some issue. Magento wasn't loading it for me, so calls to $product-getMyAttributeName() did nothing. In the product views, I got it working with this additional function: public function getAttrVal($attr_name) { return $this->getResource()->getAttribute($attr_name)->getFrontend()->getValue($this); } So that worked great when viewing a product on the frontend. It would fetch the assigned value if set, or the default if not. When I view any Category (grid of all products in that category), the same exact code is being executed. But my getAttrVal() function always returns the default value, even if I've explicitly set this value for my product. I can't, for the life of me, figure out why the attribute loads correctly in the Product view but the Category view always grabs the default value, despite running the same exact code. Any thoughts?

    Read the article

  • Error Reading Image

    - by javawarrior
    When I tried to open a simple smile.png image using package com.java3d.java3d.graphics; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class Texture { public static Render floor = loadBitMap("smile.png"); public Texture(){} public static Render loadBitMap(String fileName) { try { BufferedImage image = ImageIO.read(Thread.currentThread().getContextClassLoader().getResource(fileName)); System.out.print(image==null); int width = image.getWidth(); System.out.println(width); int height = image.getHeight(); System.out.println(height); System.out.println(image.getRGB(4, 4)); Render result = new Render(width, height); image.getRGB(0, 0, width, height, result.pixels, 0, width); return result; } catch (Exception e) { System.out.println("CRASH!"); throw new RuntimeException(e); } } } it returns every pixel as -1; what could be causing this problem? Here is the image:

    Read the article

  • Velocity engine fails to load template from a remote shared folder

    - by performanceuser
    I have following code File temlateFile = new File( "D:/config/emails/MailBody.vm" ); temlateFile.exists(); VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file"); velocityEngine.setProperty("file.resource.loader.class", FileResourceLoader.class.getName()); velocityEngine.setProperty("file.resource.loader.path", temlateFile.getParentFile().getAbsolutePath()); velocityEngine.init(); template = velocityEngine.getTemplate( temlateFile.getName() ); This works because it is loading a file from local file system. Once I change the first like to: File temlateFile = new File( "//remote/config/emails/MailBody.vm" ); It doesn't work. org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'MailBody.vm' at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:474) at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352) at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533) at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1514) at org.apache.velocity.app.VelocityEngine.getTemplate(VelocityEngine.java:373) at com.actuate.iserver.mail.VelocityContent.<init>(VelocityContent.java:33) at com.actuate.iserver.mail.VolumeCreationMail.<init>(VolumeCreationMail.java:40) at com.actuate.iserver.mail.VolumeCreationMail.main(VolumeCreationMail.java:67) In both cases temlateFile.exists() always return true. Any ideas?

    Read the article

  • Please Critique Code (Java, Java2D, javax.swing.Timer)

    - by Trizicus
    Learn by practice right? Please critique and suggest anything! Thanks :) import java.awt.EventQueue; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.JFrame; public class MainWindow { public static void main(String[] args) { new MainWindow(); } JFrame frame; GraphicsPanel gp = new GraphicsPanel(); MainWindow() { EventQueue.invokeLater(new Runnable() { public void run() { frame = new JFrame("Graphics Practice"); frame.setSize(680, 420); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gp.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); gp.addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) {} public void mouseMoved(MouseEvent e) {} }); frame.add(gp); } }); } } GraphicsPanel: import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.Timer; public class GraphicsPanel extends JPanel { Test t; Timer test; GraphicsPanel() { t = new Test(); setLayout(new BorderLayout()); add(t, BorderLayout.CENTER); test = new Timer(17, new Gameloop(this)); test.start(); } class Gameloop implements ActionListener { GraphicsPanel gp; Gameloop(GraphicsPanel gp) { this.gp = gp; } public void actionPerformed(ActionEvent e) { try { t.incX(); gp.repaint(); } catch (Exception ez) { } } } } Test: import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JComponent; public class Test extends JComponent { Toolkit tk; Image img; int x, y; Test() { tk = Toolkit.getDefaultToolkit(); img = tk.getImage(getClass().getResource("images.jpg")); this.setPreferredSize(new Dimension(15, 15)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(Color.red); g2d.drawString("x: " + x, 350, 50); g2d.drawImage(img, x, 80, null); g2d.dispose(); } public void incX() { x++; } }

    Read the article

  • zend_application showing blank page

    - by daniel
    Hi, I'm using Zend_Application to bootstrap my app. class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { public static $frontController = null; public static $registry = null; protected function _initEnvironment() { ini_set('display_errors', true); //date_default_timezone_set('Europe/London'); } protected function _initRegistry() { self::$registry = new Zend_Registry(array(), ArrayObject::ARRAY_AS_PROPS); Zend_Registry::setInstance(self::$registry); } protected function _initConfiguration() { $config = new Zend_Config_Ini( BASE_PATH . '/data/server/settings.ini', APPLICATION_ENV ); self::$registry->configuration = $config; } protected function _initLogging() { $config = self::$registry->configuration; $logger = new Zend_Log(new Zend_Log_Writer_Stream($config->logging->file)); Zend_Registry::set('logger', $logger); } protected function _initFrontController() { self::$frontController = Zend_Controller_Front::getInstance(); self::$frontController->throwExceptions(true); self::$frontController->returnResponse(true); self::$frontController->setControllerDirectory( APPLICATION_PATH .'/controllers' ); self::$frontController->setParam('registry', self::$registry); return self::$frontController; } protected function _initView() { $config = self::$registry->configuration; $view = new Zend_View; $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer($view); Zend_Controller_Action_HelperBroker::addHelper($viewRenderer); Zend_Layout::startMvc( array( 'layoutPath' => APPLICATION_PATH . "/layouts/scripts", 'layout' => "layout" ) ); return $view; } protected function _initDatabase() { $config = self::$registry->configuration; $params = array('host' => $config->database->hostname, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->database); $db = Zend_Db::factory($config->database->type, $params); Zend_Registry::set('db', $db); } protected function _initPlaceholders() { $view = $this->getResource('View'); $view->doctype('XHTML1_STRICT'); $view->headTitle('Greplin') ->setSeparator(' / '); $view->headLink()->prependStylesheet('/src/css/header.css'); $view->headScript()->prependFile('/js/site.js'); return $view; } } When I run the app I get a blank page. Filenames / paths are intact. If I add die() to the bottom of my layout.phtml, I get the page. Something is resetting the headers and sending a blank page. My error reporting is on and I get unrelated errors. What could this be?! Thanks!

    Read the article

  • How can I set an image for background of GUI interface?

    - by enriched
    hey everyone, im having some troubles displaying the background image for a GUI interface in java. Here is what i have at the moment, and with current stage of code it shows default(gray) background. import javax.swing.*; import java.awt.event.*; import java.util.Scanner; import java.awt.*; import java.io.File; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; ////////////////////////////////// // 3nriched Games Presents: // // MIPS The Mouse!! // ////////////////////////////////// public class mipsMouseGUI extends JFrame implements ActionListener { private static String ThePDub = ("mouse"); //the password JPasswordField pass; JPanel panel; JButton btnEnter; JLabel lblpdub; public mipsMouseGUI() { BufferedImage image = null; try { //attempts to read picture from the folder image = ImageIO.read(getClass().getResource("/mousepics/mousepic.png")); } catch (IOException e) { //catches exceptions e.printStackTrace(); } ImagePanel panel = new ImagePanel(new ImageIcon("/mousepics/neonglowOnwill.png").getImage()); setIconImage(image); //sets icon picture setTitle("Mips The Mouse Login"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pass = new JPasswordField(5); //sets password length to 5 pass.setEchoChar('@'); //hide characters as @ symbol pass.addActionListener(this); //adds action listener add(panel); //adds panel to frame btnEnter = new JButton("Enter"); //creates a button btnEnter.addActionListener(this);// Register the action listener. lblpdub = new JLabel(" Your Password: "); // label that says enter password panel.add(lblpdub, BorderLayout.CENTER);// adds label and inputbox panel.add(pass, BorderLayout.CENTER); // to panel and sets location panel.add(btnEnter, BorderLayout.CENTER); //adds button to panel pack(); // packs controls and setLocationRelativeTo(null); // Implicit "this" if inside JFrame constructor. setVisible(true);// makes them visible (duh) } public void actionPerformed(ActionEvent a) { Object source = a.getSource(); //char array that holds password char[] passy = pass.getPassword(); //characters array to string String p = new String(passy); //determines if user entered correct password if(p.equals(ThePDub)) { JOptionPane.showMessageDialog(null, "Welcome beta user: USERNAME."); } else JOptionPane.showMessageDialog(null, "You have enter an incorrect password. Please try again."); } public class ImagePanel extends JPanel { private BufferedImage img; public ImagePanel(String img) { this(new ImageIcon(img).getImage()); } public ImagePanel(Image img) { Dimension size = new Dimension(img.getWidth(null), img.getHeight(null)); } public void paintComponent(Graphics g) { g.drawImage(img, 0, 0, null); } } }

    Read the article

  • Secure WS client with UsernameToken(SOAP security header)

    - by user79163
    Hi, I'm trying to secure my WS client to be able to call the WS. My code looks like this: SendSmsService smsService = new SendSmsService(); SendSms sendSMS = smsService.getSendSms(); BindingProvider stub = (BindingProvider)sendSMS; //Override endpoint with local copy of wsdl. String URL ="";//here is the wsdl url Map<String,Object> requestContext = stub.getRequestContext(); requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, URL); //Set usernametoken URL fileURL = loader.getResource("client-config.xml"); File file = new File(fileURL.getFile()); FileInputStream clientConfig = null; try { clientConfig = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } XWSSecurityConfiguration config = null; try { config = SecurityConfigurationFactory.newXWSSecurityConfiguration(clientConfig); } catch (Exception e) { e.printStackTrace(); log.warn("Exception: "+e.getMessage()); } requestContext.put(XWSSecurityConfiguration.MESSAGE_SECURITY_CONFIGURATION, config); //Invoke the web service String requestId = null; try { requestId = sendSMS.sendSms(addresses, senderName, charging, message, receiptRequest); } catch (PolicyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } and the config file looks like this: <xwss:JAXRPCSecurity xmlns:xwss="http://java.sun.com/xml/ns/xwss/config" optimize="true"> <xwss:Service> <xwss:SecurityConfiguration dumpMessages="true" xmlns:xwss="http://java.sun.com/xml/ns/xwss/config"> <xwss:UsernameToken name="username" password="password> </xwss:SecurityConfiguration> </xwss:Service> <xwss:SecurityEnvironmentHandler> util.SecurityEnvironmentHandler </xwss:SecurityEnvironmentHandler> </xwss:JAXRPCSecurity> The SecurityEnviromentHandler is a dummy class that implements javax.security.auth.callback.CallbackHandler. Authentication must be in compliance with Oasis Web Services Security Username Token Profile 1.0. But I'm constantly getting "Security header not valid" error. Where am I going wrong, can anyone tell me. I used wsimport(JAX_WS 2.1 to generate classes for my client) Note:Only thing I know about this WS is WSDL URL and user&pass for authentication

    Read the article

  • How to make a pause before continuing method

    - by user1766728
    Now, I know that this has been asked, but I need to know how to do this NOT on html or anything. Heres my code, not including all of the other java files. package rtype; import java.awt.Image; import java.awt.event.KeyEvent; import java.util.ArrayList; import javax.swing.ImageIcon; public class aa { private int xd; private int yd; private int dx; private int dy; private int x; private int y; private Image image; private ArrayList missiles; private final int CRAFT_SIZE = 70; public aa() { ImageIcon ii = new ImageIcon(this.getClass().getResource("/aa.png")); image = ii.getImage(); missiles = new ArrayList(); x = 10; y = 10; xd = -14; yd = 140; } public void move() { if(y >=xd) y += dx; else if(y < xd) y += 1; if(y <=yd) y += dy; else if(y > yd) y += -1; } public int getX() { return x; } public int getY() { return y; } public Image getImage() { return image; } public ArrayList getMissiles() { return missiles; } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_SPACE) { fire(); } if (key == KeyEvent.VK_UP) { dy = -1; } if (key == KeyEvent.VK_DOWN) { dy = 1; } if (key == KeyEvent.VK_RIGHT) { yd++; } if (key == KeyEvent.VK_LEFT) { yd--; } if (key == KeyEvent.VK_W) { xd++; } if (key == KeyEvent.VK_S) { xd--; } } public void fire() { try{ missiles.add(new Missle(x + CRAFT_SIZE, y + CRAFT_SIZE)); }catch(Exception e){} } public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_UP) { dy = 0; } if (key == KeyEvent.VK_DOWN) { dy = 0; } } } So, at the method, fire(), I want to make it delay between shots. HOW? sorry if this is n00bish

    Read the article

  • Turning on collision crashes game

    - by MomentumGaming
    I am getting a null pointer excecption to both my sprite and level. I am working on my mob class, and when I try to move him and the move function is called, the game crashes after checking collision with a null pointer excecption. Taking out the one line that actually checks if the tile located in front of it fixes the problem. Also, if i keep collision ON but don't move the position of the mob (the spider) the game works fine. I will have collision, and the spider appears on the screen, only problem is, getting it to move causes this nasty error that i just can't fix. true Exception in thread "Display" java.lang.NullPointerException at com.apcompsci.game.entity.mob.Mob.collision(Mob.java:67) at com.apcompsci.game.entity.mob.Mob.move(Mob.java:38) at com.apcompsci.game.entity.mob.spider.update(spider.java:58) at com.apcompsci.game.level.Level.update(Level.java:55) at com.apcompsci.game.Game.update(Game.java:128) at com.apcompsci.game.Game.run(Game.java:106) at java.lang.Thread.run(Unknown Source) Here is my renderMob mehtod: public void renderMob(int xp,int yp,Sprite sprite,int flip) { xp -= xOffset; yp-=yOffset; for(int y = 0; y<32; y++) { int ya = y + yp; int ys = y; if(flip == 2||flip == 3)ys = 31-y; for(int x = 0; x<32; x++) { int xa = x + xp; int xs = x; if(flip == 1||flip == 3)xs = 31-x; if(xa < -32 || xa >=width || ya<0||ya>=height) break; if(xa<0) xa =0; int col = sprite.pixels[xs+ys*32]; if(col!= 0x000000) pixels[xa+ya*width] = col; } } } My spider class which determines the sprite and where I control movement, also rendering the spider onto the screen, when I increment ya to move the sprite, I get the crash, but without ya++, it runs flawlessly with a spider sprite on screen: package com.apcompsci.game.entity.mob; import com.apcompsci.game.entity.mob.Mob.Direction; import com.apcompsci.game.graphics.Screen; import com.apcompsci.game.graphics.Sprite; import com.apcompsci.game.level.Level; public class spider extends Mob{ Direction dir; private Sprite sprite; private boolean walking; public spider(int x, int y) { this.x = x <<4; this.y = y <<4; sprite = sprite.spider_forward; } public void update() { int xa = 0, ya = 0; ya++; if(ya<0) { sprite = sprite.spider_forward; dir = Direction.UP; } if(ya>0) { sprite = sprite.spider_back; dir = Direction.DOWN; } if(xa<0) { sprite = sprite.spider_side; dir = Direction.LEFT; } if(xa>0) { sprite = sprite.spider_side; dir = Direction.LEFT; } if(xa!= 0 || ya!= 0) { System.out.println("true"); move(xa,ya); walking = true; } else{ walking = false; } } public void render(Screen screen) { screen.renderMob(x, y, sprite, 0); } } This is th mob class that contains the move() method that is called in the spider class above. This move method calls the collision method. tile and sprite comes up null in the debugger: package com.apcompsci.game.entity.mob; import java.util.ArrayList; import java.util.List; import com.apcompsci.game.entity.Entity; import com.apcompsci.game.entity.projectile.DemiGodProjectile; import com.apcompsci.game.entity.projectile.Projectile; import com.apcompsci.game.graphics.Sprite; public class Mob extends Entity{ protected Sprite sprite; protected boolean moving = false; protected enum Direction { UP,DOWN,LEFT,RIGHT } protected Direction dir; public void move(int xa,int ya) { if(xa != 0 && ya != 0) { move(xa,0); move(0,ya); return; } if(xa>0) dir = Direction.RIGHT; if(xa<0) dir = Direction.LEFT; if(ya>0)dir = Direction.DOWN; if(ya<0)dir = Direction.UP; if(!collision(xa,ya)){ x+= xa; y+=ya; } } public void update() { } public void shoot(int x, int y, double dir) { //dir = Math.toDegrees(dir); Projectile p = new DemiGodProjectile(x, y,dir); level.addProjectile(p); } public boolean collision(int xa,int ya) { boolean solid = false; for(int c = 0; c<4; c++) { int xt = ((x+xa) + c % 2 * 14 - 8 )/16; int yt = ((y+ya) + c / 2 * 12 +3 )/16; if(level.getTile(xt, yt).solid()) solid = true; } return solid; } public void render() { } } Finally, here is the method in which i call the add() method for the spider to add it to the level: protected void loadLevel(String path) { try{ BufferedImage image = ImageIO.read(SpawnLevel.class.getResource(path)); int w = width =image.getWidth(); int h = height = image.getHeight(); tiles = new int[w*h]; image.getRGB(0, 0, w,h, tiles,0, w); } catch(IOException e){ e.printStackTrace(); System.out.println("Exception! Could not load level file!"); } add(new spider(20,45)); } I don't think i need to include the level class but just in case, I have provided a gistHub link for better context. It contains all of the full classes listed above , plus my entity class and maybe another. Thanks for the help if you decide to do so, much appreciated! Also, please tell me if i'm in the wrong section of stackeoverflow, i figured that since this is the gamign section that it belonged but debugging code normally goes into the general section.

    Read the article

  • OData &ndash; The easiest service I can create: now with updates

    - by Jon Dalberg
    The other day I created a simple NastyWord service exposed via OData. It was read-only and used an in-memory backing store for the words. Today I’ll modify it to use a file instead of a list and I’ll accept new nasty words by implementing IUpdatable directly. The first thing to do is enable the service to accept new entries. This is done at configuration time by adding the “WriteAppend” access rule: 1: public class NastyWords : DataService<NastyWordsDataSource> 2: { 3: // This method is called only once to initialize service-wide policies. 4: public static void InitializeService(DataServiceConfiguration config) 5: { 6: config.SetEntitySetAccessRule("*", EntitySetRights.AllRead | EntitySetRights.WriteAppend); 7: config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; 8: } 9: }   Next I placed a file, NastyWords.txt, in the “App_Data” folder and added a few *choice* words to start. This required one simple change to our NastyWordDataSource.cs file: 1: public NastyWordsDataSource() 2: { 3: UpdateFromSource(); 4: } 5:   6: private void UpdateFromSource() 7: { 8: var words = File.ReadAllLines(pathToFile); 9: NastyWords = (from w in words 10: select new NastyWord { Word = w }).AsQueryable(); 11: }   Nothing too shocking here, just reading each line from the NastyWords.txt file and exposing them. Next, I implemented IUpdatable which comes with a boat-load of methods. We don’t need all of them for now since we are only concerned with allowing new values. Here are the methods we must implement, all the others throw a NotImplementedException: 1: public object CreateResource(string containerName, string fullTypeName) 2: { 3: var nastyWord = new NastyWord(); 4: pendingUpdates.Add(nastyWord); 5: return nastyWord; 6: } 7:   8: public object ResolveResource(object resource) 9: { 10: return resource; 11: } 12:   13: public void SaveChanges() 14: { 15: var intersect = (from w in pendingUpdates 16: select w.Word).Intersect(from n in NastyWords 17: select n.Word); 18:   19: if (intersect.Count() > 0) 20: throw new DataServiceException(500, "duplicate entry"); 21:   22: var lines = from w in pendingUpdates 23: select w.Word; 24:   25: File.AppendAllLines(pathToFile, 26: lines, 27: Encoding.UTF8); 28:   29: pendingUpdates.Clear(); 30:   31: UpdateFromSource(); 32: } 33:   34: public void SetValue(object targetResource, string propertyName, object propertyValue) 35: { 36: targetResource.GetType().GetProperty(propertyName).SetValue(targetResource, propertyValue, null); 37: }   I use a simple list to contain the pending updates and only commit them when the “SaveChanges” method is called. Here’s the order these methods are called in our service during an insert: CreateResource – here we just instantiate a new NastyWord and stick a reference to it in our pending updates list. SetValue – this is where the “Word” property of the NastyWord instance is set. SaveChanges – get the list of pending updates, barfing on duplicates, write them to the file and clear our pending list. ResolveResource – the newly created resource will be returned directly here since we aren’t dealing with “handles” to objects but the actual objects themselves. Not too bad, eh? I didn’t find this documented anywhere but a little bit of digging in the OData spec and use of Fiddler made it pretty easy to figure out. Here is some client code which would add a new nasty word: 1: static void Main(string[] args) 2: { 3: var svc = new ServiceReference1.NastyWordsDataSource(new Uri("http://localhost.:60921/NastyWords.svc")); 4: svc.AddToNastyWords(new ServiceReference1.NastyWord() { Word = "shat" }); 5:   6: svc.SaveChanges(); 7: }   Here’s all of the code so far for to implement the service: 1: using System; 2: using System.Collections.Generic; 3: using System.Data.Services; 4: using System.Data.Services.Common; 5: using System.Linq; 6: using System.ServiceModel.Web; 7: using System.Web; 8: using System.IO; 9: using System.Text; 10:   11: namespace ONasty 12: { 13: [DataServiceKey("Word")] 14: public class NastyWord 15: { 16: public string Word { get; set; } 17: } 18:   19: public class NastyWordsDataSource : IUpdatable 20: { 21: private List<NastyWord> pendingUpdates = new List<NastyWord>(); 22: private string pathToFile = @"path to your\App_Data\NastyWords.txt"; 23:   24: public NastyWordsDataSource() 25: { 26: UpdateFromSource(); 27: } 28:   29: private void UpdateFromSource() 30: { 31: var words = File.ReadAllLines(pathToFile); 32: NastyWords = (from w in words 33: select new NastyWord { Word = w }).AsQueryable(); 34: } 35:   36: public IQueryable<NastyWord> NastyWords { get; private set; } 37:   38: public void AddReferenceToCollection(object targetResource, string propertyName, object resourceToBeAdded) 39: { 40: throw new NotImplementedException(); 41: } 42:   43: public void ClearChanges() 44: { 45: pendingUpdates.Clear(); 46: } 47:   48: public object CreateResource(string containerName, string fullTypeName) 49: { 50: var nastyWord = new NastyWord(); 51: pendingUpdates.Add(nastyWord); 52: return nastyWord; 53: } 54:   55: public void DeleteResource(object targetResource) 56: { 57: throw new NotImplementedException(); 58: } 59:   60: public object GetResource(IQueryable query, string fullTypeName) 61: { 62: throw new NotImplementedException(); 63: } 64:   65: public object GetValue(object targetResource, string propertyName) 66: { 67: throw new NotImplementedException(); 68: } 69:   70: public void RemoveReferenceFromCollection(object targetResource, string propertyName, object resourceToBeRemoved) 71: { 72: throw new NotImplementedException(); 73: } 74:   75: public object ResetResource(object resource) 76: { 77: throw new NotImplementedException(); 78: } 79:   80: public object ResolveResource(object resource) 81: { 82: return resource; 83: } 84:   85: public void SaveChanges() 86: { 87: var intersect = (from w in pendingUpdates 88: select w.Word).Intersect(from n in NastyWords 89: select n.Word); 90:   91: if (intersect.Count() > 0) 92: throw new DataServiceException(500, "duplicate entry"); 93:   94: var lines = from w in pendingUpdates 95: select w.Word; 96:   97: File.AppendAllLines(pathToFile, 98: lines, 99: Encoding.UTF8); 100:   101: pendingUpdates.Clear(); 102:   103: UpdateFromSource(); 104: } 105:   106: public void SetReference(object targetResource, string propertyName, object propertyValue) 107: { 108: throw new NotImplementedException(); 109: } 110:   111: public void SetValue(object targetResource, string propertyName, object propertyValue) 112: { 113: targetResource.GetType().GetProperty(propertyName).SetValue(targetResource, propertyValue, null); 114: } 115: } 116:   117: public class NastyWords : DataService<NastyWordsDataSource> 118: { 119: // This method is called only once to initialize service-wide policies. 120: public static void InitializeService(DataServiceConfiguration config) 121: { 122: config.SetEntitySetAccessRule("*", EntitySetRights.AllRead | EntitySetRights.WriteAppend); 123: config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; 124: } 125: } 126: } Next time we’ll allow removing nasty words. Enjoy!

    Read the article

  • PostgreSQL, Ubuntu, NetBeans IDE (Part 3)

    - by Geertjan
    To complete the picture, let's use the traditional (that is, old) Hibernate mechanism, i.e., via XML files, rather than via the annotations shown yesterday. It's definitely trickier, with many more places where typos can occur, but that's why it's the old mechanism. I do not recommend this approach. I recommend the approach shown yesterday. The other players in this scenario include PostgreSQL, as outlined in the previous blog entries in this series. Here's the structure of the module, replacing the code shown yesterday: Here's the Employee class, notice that it has no annotations: import java.io.Serializable; import java.util.Date; public class Employees implements Serializable {         private int employeeId;     private String firstName;     private String lastName;     private Date dateOfBirth;     private String phoneNumber;     private String junk;     public int getEmployeeId() {         return employeeId;     }     public void setEmployeeId(int employeeId) {         this.employeeId = employeeId;     }     public String getFirstName() {         return firstName;     }     public void setFirstName(String firstName) {         this.firstName = firstName;     }     public String getLastName() {         return lastName;     }     public void setLastName(String lastName) {         this.lastName = lastName;     }     public Date getDateOfBirth() {         return dateOfBirth;     }     public void setDateOfBirth(Date dateOfBirth) {         this.dateOfBirth = dateOfBirth;     }     public String getPhoneNumber() {         return phoneNumber;     }     public void setPhoneNumber(String phoneNumber) {         this.phoneNumber = phoneNumber;     }     public String getJunk() {         return junk;     }     public void setJunk(String junk) {         this.junk = junk;     } } And here's the Hibernate configuration file: <?xml version="1.0"?> <!DOCTYPE hibernate-configuration PUBLIC       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration>     <session-factory>         <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>         <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/smithdb</property>         <property name="hibernate.connection.username">smith</property>         <property name="hibernate.connection.password">smith</property>         <property name="hibernate.connection.pool_size">1</property>         <property name="hibernate.default_schema">public"</property>         <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>         <property name="hibernate.current_session_context_class">thread</property>         <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>         <property name="hibernate.show_sql">true</property>         <mapping resource="org/db/viewer/employees.hbm.xml"/>     </session-factory> </hibernate-configuration> Next, the Hibernate mapping file: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC       "-//Hibernate/Hibernate Mapping DTD 3.0//EN"       "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping>     <class name="org.db.viewer.Employees"            table="employees"            schema="public"            catalog="smithdb">         <id name="employeeId" column="employee_id" type="int">             <generator class="increment"/>         </id>         <property name="firstName" column="first_name" type="string" />         <property name="lastName" column="last_name" type="string" />         <property name="dateOfBirth" column="date_of_birth" type="date" />         <property name="phoneNumber" column="phone_number" type="string" />         <property name="junk" column="junk" type="string" />             </class>     </hibernate-mapping> Then, the HibernateUtil file, for providing access to the Hibernate SessionFactory: import java.net.URL; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.SessionFactory; public class HibernateUtil {     private static final SessionFactory sessionFactory;         static {         try {             // Create the SessionFactory from standard (hibernate.cfg.xml)             // config file.             String res = "org/db/viewer/employees.cfg.xml";             URL myURL = Thread.currentThread().getContextClassLoader().getResource(res);             sessionFactory = new AnnotationConfiguration().configure(myURL).buildSessionFactory();         } catch (Throwable ex) {             // Log the exception.             System.err.println("Initial SessionFactory creation failed." + ex);             throw new ExceptionInInitializerError(ex);         }     }         public static SessionFactory getSessionFactory() {         return sessionFactory;     }     } Finally, the "createKeys" in the ChildFactory: @Override protected boolean createKeys(List list) {     Session session = HibernateUtil.getSessionFactory().getCurrentSession();     Transaction transac = null;     try {         transac = session.beginTransaction();         Query query = session.createQuery("from Employees");         list.addAll(query.list());     } catch (HibernateException he) {         Exceptions.printStackTrace(he);         if (transac != null){             transac.rollback();         }     } finally {         session.close();     }     return true; } Note that Constantine Drabo has a similar article here. Run the application and the result should be the same as yesterday.

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >