Search Results

Search found 163 results on 7 pages for 'throwable'.

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

  • errorPage directive works, but error-page in web.xml doesn't?

    - by danb
    I get jsp exceptions causing a forward to my error page when I put this at the top of my JSPs... <%@ page errorPage="/error.page" %> but when I try to do it globally with web.xml like so: <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/error.page</location> </error-page> I just get a blank page... I've also tried putting /error.jsp in the location element.. but no love with that either.. I am triggering an exception with a jsp that just contains this: <%if(true)throw new RuntimeException("test exception");%> I do see the exception in the console from tomcat but I just can't get that error page to show without a directive on every jsp... am I missing something simple here?

    Read the article

  • how to use a wav file in eclipse

    - by AlphaAndOmega
    I've been trying to add audio to a project I've been doing. I found some code on here for html that is also supposed to work with file but it keeps saying "Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source) at LoopSound.main(LoopSound.java:15)" the code public class LoopSound { public static void main(String[] args) throws Throwable { File file = new File("c:\\Users\\rabidbun\\Pictures\\10177-m-001.wav"); Clip clip = AudioSystem.getClip(); // getAudioInputStream() also accepts a File or InputStream AudioInputStream wav = AudioSystem.getAudioInputStream( file ); clip.open(wav); // loop continuously clip.loop(-1000); SwingUtilities.invokeLater(new Runnable() { public void run() { // A GUI element to prevent the Clip's daemon Thread // from terminating at the end of the main() JOptionPane.showMessageDialog(null, "Close to exit!"); } }); } } What is wrong with the code?

    Read the article

  • Java application return codes

    - by doele
    I have a Java program that processes one file at a time. This Java program is called from a wrapper script which logs the return code from the Java program. There are 2 types of errors. Expected errors and unexpected errors. In both cases I just need to log them. My wrapper knows about 3 different states. 0-OK, 1-PROCESSING_FAILED, 2- ERROR. Is this a valid approach? Here is my approach: enum ReturnCodes {OK,PROCESSING_FAILED,ERROR}; public static void main(String[] args) { ... proc.processMyFile(); ... System.exit(ReturnCodes.OK.ordinal()); } catch (Throwable t) { ... System.exit(ReturnCodes.ERROR.ordinal()); } private void processMyFile() { try { ... }catch( ExpectedException e) { ... System.exit(ReturnCodes.PROCESSING_FAILED.ordinal()); } }

    Read the article

  • Issues with timed out downloads via TomCat?

    - by Ira Baxter
    We get, in our opinion, a lot of failed download attempts and want to understand why. We offer downloads via an email link (typical): http://www.semanticdesigns.com/deliverEval/<productname> This is processed by Tomcat on Linux via a jsp file, with the following code: response.addHeader( "Content-Disposition", "attachment; filename=" + fileTail ); response.addHeader( "Content-Type", "application/x-msdos-program" ); byte[] buf = new byte[8192]; int read; try { java.io.FileInputStream input = new java.io.FileInputStream( filename ); java.io.OutputStream o = response.getOutputStream(); while( ( read = input.read( buf, 0, 8192 ) ) != -1 ){ o.write( buf, 0, read ); } o.flush(); } catch( Exception e ){ util.fatalError( request.getRequestURI(), "Error sending file '" + filename + "' to client", e ); throw e; } We get a lot of reported errors (about 50% error rate): URI --- /deliverEval/download.jsp Code Message: Error sending file '/home/sd/ShippingMasters/DMS/Domains/C/GCC3/Tools/TestCoverage/SD_C~GCC3_TestCoverage.1.6.12.exe' to client Stack Trace ----------- null at org.apache.coyote.tomcat5.OutputBuffer.realWriteBytes(byte[], int, int) (Unknown Source) at org.apache.tomcat.util.buf.ByteChunk.append(byte[], int, int) (Unknown Source) at org.apache.coyote.tomcat5.OutputBuffer.writeBytes(byte[], int, int) (Unknown Source) at org.apache.coyote.tomcat5.OutputBuffer.write(byte[], int, int) (Unknown Source) at org.apache.coyote.tomcat5.CoyoteOutputStream.write(byte[], int, int) (Unknown Source) at org.apache.jsp.deliverEval.download_jsp._jspService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) (Unknown Source) at org.apache.jasper.runtime.HttpJspBase.service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) (Unknown Source) at javax.servlet.http.HttpServlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) (Unknown Source) at org.apache.jasper.servlet.JspServletWrapper.service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean) (Unknown Source) at org.apache.jasper.servlet.JspServlet.serviceJspFile(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.Throwable, boolean) (Unknown Source) at org.apache.jasper.servlet.JspServlet.service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) (Unknown Source) at javax.servlet.http.HttpServlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) (Unknown Source) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse) (Unknown Source) at org.apache.catalina.core.ApplicationFilterChain.doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse) (Unknown Source) at org.apache.catalina.core.StandardWrapperValve.invoke(org.apache.catalina.Request, org.apache.catalina.Response, org.apache.catalina.ValveContext) (Unknown Source) We don't understand why this rate should be so high. Is there any way to get more information about the cause of the error? It is useful to know that these are pretty big documents, 3-50 megabytes. They reside on the Linux server so reading them is just a local disk read, and is unlikely to be a contributor to the problem. But sheer size might be an issue for the recipients browser? Is this kind of error rate typical for downloads? My personal experience downloading other's documents suggests no; our internal attempts show this to be very reliable, but we're operating on our internal network for such experiments so we're missing the complexity of the intervening internet.

    Read the article

  • Connection drop problem with Hibernate-mysql-c3p0

    - by user344788
    hi all, This is an issue which I have seen all across the web. I will bring it up again as till now I don't have a fix for the same. I am using hibernate 3. mysql 5 and latest c3p0 jar. I am getting a broken pipe exception. Following is my hibernate.cfg file. com.mysql.jdbc.Driver org.hibernate.dialect.MySQLDialect <property name="hibernate.show_sql">true</property> <property name="hibernate.use_sql_comments">true</property> <property name="hibernate.current_session_context_class">thread</property> <property name="connection.autoReconnect">true</property> <property name="connection.autoReconnectForPools">true</property> <property name="connection.is-connection-validation-required">true</property> <!--<property name="c3p0.min_size">5</property> <property name="c3p0.max_size">20</property> <property name="c3p0.timeout">1800</property> <property name="c3p0.max_statements">50</property> --><property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider </property> <property name="hibernate.c3p0.acquireRetryAttempts">30</property> <property name="hibernate.c3p0.acquireIncrement">5</property> <property name="hibernate.c3p0.automaticTestTable">C3P0TestTable</property> <property name="hibernate.c3p0.idleConnectionTestPeriod">36000</property> <property name="hibernate.c3p0.initialPoolSize">20</property> <property name="hibernate.c3p0.maxPoolSize">100</property> <property name="hibernate.c3p0.maxIdleTime">1200</property> <property name="hibernate.c3p0.maxStatements">50</property> <property name="hibernate.c3p0.minPoolSize">10</property>--> My connection pooling is occurring fine. During the day it is fine , but once i keep it idle over the night ,next day I find it giving me broken connection error. public class HibernateUtil { private static Logger log = Logger.getLogger(HibernateUtil.class); //private static Log log = LogFactory.getLog(HibernateUtil.class); private static Configuration configuration; private static SessionFactory sessionFactory; static { // Create the initial SessionFactory from the default configuration files try { log.debug("Initializing Hibernate"); // Read hibernate.properties, if present configuration = new Configuration(); // Use annotations: configuration = new AnnotationConfiguration(); // Read hibernate.cfg.xml (has to be present) configuration.configure(); // Build and store (either in JNDI or static variable) rebuildSessionFactory(configuration); log.debug("Hibernate initialized, call HibernateUtil.getSessionFactory()"); } catch (Throwable ex) { // We have to catch Throwable, otherwise we will miss // NoClassDefFoundError and other subclasses of Error log.error("Building SessionFactory failed.", ex); throw new ExceptionInInitializerError(ex); } } /** * Returns the Hibernate configuration that was used to build the SessionFactory. * * @return Configuration */ public static Configuration getConfiguration() { return configuration; } /** * Returns the global SessionFactory either from a static variable or a JNDI lookup. * * @return SessionFactory */ public static SessionFactory getSessionFactory() { String sfName = configuration.getProperty(Environment.SESSION_FACTORY_NAME); System.out.println("Current s name is "+sfName); if ( sfName != null) { System.out.println("Looking up SessionFactory in JNDI"); log.debug("Looking up SessionFactory in JNDI"); try { System.out.println("Returning new sssion factory"); return (SessionFactory) new InitialContext().lookup(sfName); } catch (NamingException ex) { throw new RuntimeException(ex); } } else if (sessionFactory == null) { System.out.println("calling rebuild session factory now"); rebuildSessionFactory(); } return sessionFactory; } /** * Closes the current SessionFactory and releases all resources. * <p> * The only other method that can be called on HibernateUtil * after this one is rebuildSessionFactory(Configuration). */ public static void shutdown() { log.debug("Shutting down Hibernate"); // Close caches and connection pools getSessionFactory().close(); // Clear static variables sessionFactory = null; } /** * Rebuild the SessionFactory with the static Configuration. * <p> * Note that this method should only be used with static SessionFactory * management, not with JNDI or any other external registry. This method also closes * the old static variable SessionFactory before, if it is still open. */ public static void rebuildSessionFactory() { log.debug("Using current Configuration to rebuild SessionFactory"); rebuildSessionFactory(configuration); } /** * Rebuild the SessionFactory with the given Hibernate Configuration. * <p> * HibernateUtil does not configure() the given Configuration object, * it directly calls buildSessionFactory(). This method also closes * the old static variable SessionFactory before, if it is still open. * * @param cfg */ public static void rebuildSessionFactory(Configuration cfg) { log.debug("Rebuilding the SessionFactory from given Configuration"); if (sessionFactory != null && !sessionFactory.isClosed()) sessionFactory.close(); if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null) { log.debug("Managing SessionFactory in JNDI"); cfg.buildSessionFactory(); } else { log.debug("Holding SessionFactory in static variable"); sessionFactory = cfg.buildSessionFactory(); } configuration = cfg; } } Above is my code for the session factory. And I have only select operations . And below is the method which is used most often to execute my select queries. One tricky thing which I am not understanding is in my findById method i am using this line of code getSession().beginTransaction(); without which it gives me an error saying that this cannot happpen without a transaction. But nowhere I am closing this transaction. And thers no method to close a transaction apart from commit or rollback (as far as i know) which are not applicable for select statements. public T findById(ID id, boolean lock) throws HibernateException, DAOException { log.debug("findNyId invoked with ID ="+id+"and lock ="+lock); T entity; getSession().beginTransaction(); if (lock) entity = (T) getSession().load(getPersistentClass(), id, LockMode.UPGRADE); else entity = (T) getSession().load(getPersistentClass(), id); return entity; } Can anyone please suggest what can I do ? I have tried out almost every solution available via googling, on stackoverlow or on hibernate forums with no avail. (And increasing wait_timeout on mysql is not a valid option in my case).

    Read the article

  • "ERROR:Could not find java.nio.file.Paths" when using Oracle JDK 1.7

    - by Ankit
    I want to try out some features rolled out in Oracle's new JDK 1.7. I followed the post:- Oracle JDK 1.7 but the post doesn't seem to help. I was trying to fetch out the structure for java.nio.file.Paths class file but got the following error:- buffer@ankit:~$ javap java.nio.file.Paths ERROR:Could not find java.nio.file.Paths However i can easily get the information about class structures till JAVA SE 1.6, here is an example:- buffer@ankit:~$ javap java.lang.Object Compiled from "Object.java" public class java.lang.Object{ public java.lang.Object(); public final native java.lang.Class getClass(); public native int hashCode(); public boolean equals(java.lang.Object); protected native java.lang.Object clone() throws java.lang.CloneNotSupportedException; public java.lang.String toString(); public final native void notify(); public final native void notifyAll(); public final native void wait(long) throws java.lang.InterruptedException; public final void wait(long, int) throws java.lang.InterruptedException; public final void wait() throws java.lang.InterruptedException; protected void finalize() throws java.lang.Throwable; static {}; } Running java -version gives the following result:- buffer@ankit:~$ java -version java version "1.7.0_09" Java(TM) SE Runtime Environment (build 1.7.0_09-b05) Java HotSpot(TM) 64-Bit Server VM (build 23.5-b02, mixed mode) SYSTEM INFORMATION buffer@ankit:~$ sudo update-alternatives --config java [sudo] password for buffer: There are 4 choices for the alternative java (providing /usr/bin/java). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java 1061 auto mode 1 /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java 1061 manual mode 2 /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java 1051 manual mode 3 /usr/lib/jvm/jdk1.7.0_09/ 1 manual mode * 4 /usr/lib/jvm/jdk1.7.0_09/bin/java 1 manual mode buffer@ankit:~$ sudo update-alternatives --config javac There are 2 choices for the alternative javac (providing /usr/bin/javac). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-6-openjdk-amd64/bin/javac 1061 auto mode 1 /usr/lib/jvm/java-6-openjdk-amd64/bin/javac 1061 manual mode * 2 /usr/lib/jvm/jdk1.7.0_09/bin/javac 1 manual mode buffer@ankit:~$ sudo update-alternatives --config javaws There are 3 choices for the alternative javaws (providing /usr/bin/javaws). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/javaws 1061 auto mode 1 /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/javaws 1061 manual mode 2 /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/javaws 1060 manual mode * 3 /usr/lib/jvm/jdk1.7.0_09/bin/javaws 1 manual mode The directory structure of /usr/lib/jvm/ is as follows:- buffer@ankit:~$ ls -l /usr/lib/jvm/ total 24 lrwxrwxrwx 1 root root 24 Dec 2 2011 default-java -> java-1.6.0-openjdk-amd64 drwxr-xr-x 4 root root 4096 Nov 8 16:24 java-1.5.0-gcj-4.6 lrwxrwxrwx 1 root root 24 Dec 2 2011 java-1.6.0-openjdk -> java-1.6.0-openjdk-amd64 lrwxrwxrwx 1 root root 20 Oct 25 00:01 java-1.6.0-openjdk-amd64 -> java-6-openjdk-amd64 lrwxrwxrwx 1 root root 20 Oct 25 06:59 java-1.7.0-openjdk-amd64 -> java-7-openjdk-amd64 lrwxrwxrwx 1 root root 24 Dec 2 2011 java-6-openjdk -> java-1.6.0-openjdk-amd64 drwxr-xr-x 7 root root 4096 Nov 8 16:24 java-6-openjdk-amd64 drwxr-xr-x 3 root root 4096 Nov 8 16:24 java-6-openjdk-common drwxr-xr-x 5 root root 4096 Nov 8 05:48 java-7-openjdk-amd64 drwxr-xr-x 3 root root 4096 Nov 8 05:48 java-7-openjdk-common drwxr-xr-x 8 buffer buffer 4096 Sep 25 09:08 jdk1.7.0_09 Any help would be highly appreciated.

    Read the article

  • Examples of bad variable names and reasons [on hold]

    - by user470184
    I'll start with a class in the jdk package : public final class Sdp { should be : public final class SocketsDirectProtocol { Sdp is class name, this is ambigious, should be : Class<?> cl = Class.forName("java.net.SdpSocketImpl", true, null); should be : Class<?> clazz = Class.forName("java.net.SdpSocketImpl", true, null); cl is ambiguous private static void setAccessible(final AccessibleObject o) { should be : private static void setAccessible(final AccessibleObject accessibleObject) { There are various other examples in this class, do you have similar and/or differing examples of variables that were named badly ? package com.oracle.net; public final class Sdp { private Sdp() { } /** * The package-privage ServerSocket(SocketImpl) constructor */ private static final Constructor<ServerSocket> serverSocketCtor; static { try { serverSocketCtor = (Constructor<ServerSocket>) ServerSocket.class.getDeclaredConstructor(SocketImpl.class); setAccessible(serverSocketCtor); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } /** * The package-private SdpSocketImpl() constructor */ private static final Constructor<SocketImpl> socketImplCtor; static { try { Class<?> cl = Class.forName("java.net.SdpSocketImpl", true, null); socketImplCtor = (Constructor<SocketImpl>)cl.getDeclaredConstructor(); setAccessible(socketImplCtor); } catch (ClassNotFoundException e) { throw new AssertionError(e); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } private static void setAccessible(final AccessibleObject o) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { o.setAccessible(true); return null; } }); } /** * SDP enabled Socket. */ private static class SdpSocket extends Socket { SdpSocket(SocketImpl impl) throws SocketException { super(impl); } } /** * Creates a SDP enabled SocketImpl */ private static SocketImpl createSocketImpl() { try { return socketImplCtor.newInstance(); } catch (InstantiationException x) { throw new AssertionError(x); } catch (IllegalAccessException x) { throw new AssertionError(x); } catch (InvocationTargetException x) { throw new AssertionError(x); } } /** * Creates an unconnected and unbound SDP socket. The {@code Socket} is * associated with a {@link java.net.SocketImpl} of the system-default type. * * @return a new Socket * * @throws UnsupportedOperationException * If SDP is not supported * @throws IOException * If an I/O error occurs */ public static Socket openSocket() throws IOException { SocketImpl impl = createSocketImpl(); return new SdpSocket(impl); } /** * Creates an unbound SDP server socket. The {@code ServerSocket} is * associated with a {@link java.net.SocketImpl} of the system-default type. * * @return a new ServerSocket * * @throws UnsupportedOperationException * If SDP is not supported * @throws IOException * If an I/O error occurs */ public static ServerSocket openServerSocket() throws IOException { // create ServerSocket via package-private constructor SocketImpl impl = createSocketImpl(); try { return serverSocketCtor.newInstance(impl); } catch (IllegalAccessException x) { throw new AssertionError(x); } catch (InstantiationException x) { throw new AssertionError(x); } catch (InvocationTargetException x) { Throwable cause = x.getCause(); if (cause instanceof IOException) throw (IOException)cause; if (cause instanceof RuntimeException) throw (RuntimeException)cause; throw new RuntimeException(x); } } /** * Opens a socket channel to a SDP socket. * * <p> The channel will be associated with the system-wide default * {@link java.nio.channels.spi.SelectorProvider SelectorProvider}. * * @return a new SocketChannel * * @throws UnsupportedOperationException * If SDP is not supported or not supported by the default selector * provider * @throws IOException * If an I/O error occurs. */ public static SocketChannel openSocketChannel() throws IOException { FileDescriptor fd = SdpSupport.createSocket(); return sun.nio.ch.Secrets.newSocketChannel(fd); } /** * Opens a socket channel to a SDP socket. * * <p> The channel will be associated with the system-wide default * {@link java.nio.channels.spi.SelectorProvider SelectorProvider}. * * @return a new ServerSocketChannel * * @throws UnsupportedOperationException * If SDP is not supported or not supported by the default selector * provider * @throws IOException * If an I/O error occurs */ public static ServerSocketChannel openServerSocketChannel() throws IOException { FileDescriptor fd = SdpSupport.createSocket(); return sun.nio.ch.Secrets.newServerSocketChannel(fd); } }

    Read the article

  • Non-blocking I/O using Servlet 3.1: Scalable applications using Java EE 7 (TOTD #188)

    - by arungupta
    Servlet 3.0 allowed asynchronous request processing but only traditional I/O was permitted. This can restrict scalability of your applications. In a typical application, ServletInputStream is read in a while loop. public class TestServlet extends HttpServlet {    protected void doGet(HttpServletRequest request, HttpServletResponse response)         throws IOException, ServletException {     ServletInputStream input = request.getInputStream();       byte[] b = new byte[1024];       int len = -1;       while ((len = input.read(b)) != -1) {          . . .        }   }} If the incoming data is blocking or streamed slower than the server can read then the server thread is waiting for that data. The same can happen if the data is written to ServletOutputStream. This is resolved in Servet 3.1 (JSR 340, to be released as part Java EE 7) by adding event listeners - ReadListener and WriteListener interfaces. These are then registered using ServletInputStream.setReadListener and ServletOutputStream.setWriteListener. The listeners have callback methods that are invoked when the content is available to be read or can be written without blocking. The updated doGet in our case will look like: AsyncContext context = request.startAsync();ServletInputStream input = request.getInputStream();input.setReadListener(new MyReadListener(input, context)); Invoking setXXXListener methods indicate that non-blocking I/O is used instead of the traditional I/O. At most one ReadListener can be registered on ServletIntputStream and similarly at most one WriteListener can be registered on ServletOutputStream. ServletInputStream.isReady and ServletInputStream.isFinished are new methods to check the status of non-blocking I/O read. ServletOutputStream.canWrite is a new method to check if data can be written without blocking.  MyReadListener implementation looks like: @Overridepublic void onDataAvailable() { try { StringBuilder sb = new StringBuilder(); int len = -1; byte b[] = new byte[1024]; while (input.isReady() && (len = input.read(b)) != -1) { String data = new String(b, 0, len); System.out.println("--> " + data); } } catch (IOException ex) { Logger.getLogger(MyReadListener.class.getName()).log(Level.SEVERE, null, ex); }}@Overridepublic void onAllDataRead() { System.out.println("onAllDataRead"); context.complete();}@Overridepublic void onError(Throwable t) { t.printStackTrace(); context.complete();} This implementation has three callbacks: onDataAvailable callback method is called whenever data can be read without blocking onAllDataRead callback method is invoked data for the current request is completely read. onError callback is invoked if there is an error processing the request. Notice, context.complete() is called in onAllDataRead and onError to signal the completion of data read. For now, the first chunk of available data need to be read in the doGet or service method of the Servlet. Rest of the data can be read in a non-blocking way using ReadListener after that. This is going to get cleaned up where all data read can happen in ReadListener only. The sample explained above can be downloaded from here and works with GlassFish 4.0 build 64 and onwards. The slides and a complete re-run of What's new in Servlet 3.1: An Overview session at JavaOne is available here. Here are some more references for you: Java EE 7 Specification Status Servlet Specification Project JSR Expert Group Discussion Archive Servlet 3.1 Javadocs

    Read the article

  • Axis2 embedded in my web app is not working

    - by Shamik
    OKay I lost alsmost the whole day on this. I have a webapp where I would like to add AXIS2 and start working. I added AxisServlets in the web.xml file like - <servlet> <servlet-name>AxisServlet</servlet-name> <display-name>Apache-Axis Servlet</display-name> <servlet-class>org.apache.axis2.transport.http.AxisServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>AxisServlet</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping> I also added Services.xml file like <service name="ReportViewerService"> <description> This is a sample Web Service for illustrating Attachments API of Axis2 </description> <parameter name="ServiceClass">myclass</parameter> <operation name="getReport"> <actionMapping>urn:getReport</actionMapping> <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/> </operation> </service> The directory structure is as mentioned here WEB-ING | - conf | |- axis2.xml |-lib | |- all libs |-services |-ReportViewerService | - META-INF |-services.xml |- web.xml The problem is - after all of these, the service endpoint will not come, I can not see the WSDL file http://localhost:8080/BOReportingServer/services/ReportViewerService?wsdl -- this gives an exception like - Throwable occurred: javax.servlet.ServletException: File &quot;/axis2-web/listSingleService.jsp&quot; not found

    Read the article

  • Parse.com REST API in Java (NOT Android)

    - by Orange Peel
    I am trying to use the Parse.com REST API in Java. I have gone through the 4 solutions given here https://parse.com/docs/api_libraries and have selected Parse4J. After importing the source into Netbeans, along with importing the following libraries: org.slf4j:slf4j-api:jar:1.6.1 org.apache.httpcomponents:httpclient:jar:4.3.2 org.apache.httpcomponents:httpcore:jar:4.3.1 org.json:json:jar:20131018 commons-codec:commons-codec:jar:1.9 junit:junit:jar:4.11 ch.qos.logback:logback-classic:jar:0.9.28 ch.qos.logback:logback-core:jar:0.9.28 I ran the example code from https://github.com/thiagolocatelli/parse4j Parse.initialize(APP_ID, APP_REST_API_ID); // I replaced these with mine ParseObject gameScore = new ParseObject("GameScore"); gameScore.put("score", 1337); gameScore.put("playerName", "Sean Plott"); gameScore.put("cheatMode", false); gameScore.save(); And I got that it was missing org.apache.commons.logging, so I downloaded that and imported it. Then I ran the code again and got Exception in thread "main" java.lang.NoSuchMethodError: org.slf4j.spi.LocationAwareLogger.log(Lorg/slf4j/Marker;Ljava/lang/String;ILjava/lang/String;Ljava/lang/Throwable;)V at org.apache.commons.logging.impl.SLF4JLocationAwareLog.debug(SLF4JLocationAwareLog.java:120) at org.apache.http.client.protocol.RequestAddCookies.process(RequestAddCookies.java:122) at org.apache.http.protocol.ImmutableHttpProcessor.process(ImmutableHttpProcessor.java:131) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:193) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:85) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57) at org.parse4j.command.ParseCommand.perform(ParseCommand.java:44) at org.parse4j.ParseObject.save(ParseObject.java:450) I could probably fix this with another import, but I suppose then something else would pop up. I tried the other libraries with similar results, missing a bunch of libraries. Has anyone actually used REST API successfully in Java? If so, I would be grateful if you shared which library/s you used and anything else required to get it going successfully. I am using Netbeans. Thanks.

    Read the article

  • Problem calling Request using RequestBuilder

    - by Tushar Ahirrao
    Hi My Code is String url = "http: gd.geobytes.com/gd?after=-1&variables=GeobytesCountry,GeobytesCity"; RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL .encode(url)); try { Request request = builder.sendRequest(null, new RequestCallback() { public void onError(Request request, Throwable exception) { Couldn't connect to server (could be timeout, SOP violation, etc.) } public void onResponseReceived(Request request, Response response) { System.out.println(response.getText() + "Response"); if (200 == response.getStatusCode()) { Window.alert(response.getText()); } else { Window.alert(response.getText()); } } }); } catch (RequestException e) { e.printStackTrace(); } i receive following error com.google.gwt.http.client.RequestPermissionException: The URL http://gd.geobytes.com/gd?after=-1&variables=GeobytesCountry,GeobytesCity is invalid or violates the same-origin security restriction at com.google.gwt.http.client.RequestBuilder.doSend(RequestBuilder.java:378) at com.google.gwt.http.client.RequestBuilder.sendRequest(RequestBuilder.java:254) at com.ip.client.IpAddressTest.onModuleLoad(IpAddressTest.java:46) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.google.gwt.dev.shell.ModuleSpace.onLoad(ModuleSpace.java:369) at com.google.gwt.dev.shell.OophmSessionHandler.loadModule(OophmSessionHandler.java:185) at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:380) at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:222) at java.lang.Thread.run(Thread.java:619) Caused by: com.google.gwt.http.client.RequestException: (NS_ERROR_DOM_BAD_URI): Access to restricted URI denied

    Read the article

  • bug with varargs and overloading?

    - by pstanton
    There seems to be a bug in the Java varargs implementation. Java can't distinguish the appropriate type when a method is overloaded with different types of vararg parameters. It gives me an error The method ... is ambiguous for the type ... Consider the following code: public class Test { public static void main(String[] args) throws Throwable { doit(new int[]{1, 2}); // <- no problem doit(new double[]{1.2, 2.2}); // <- no problem doit(1.2f, 2.2f); // <- no problem doit(1.2d, 2.2d); // <- no problem doit(1, 2); // <- The method doit(double[]) is ambiguous for the type Test } public static void doit(double... ds) { System.out.println("doubles"); } public static void doit(int... is) { System.out.println("ints"); } } the docs say: "Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called." however they don't mention this error, and it's not the programmers that are finding it difficult, it's the compiler. thoughts?

    Read the article

  • Android RestTemplate Ok on emulator but fails on real device

    - by Hossein
    I'm using spring RestTemplate and it works perfect on emulator but if I run my app on real device I get HttpMessageNotWritableException ............ nested exception is java.net.SocketException: Broken pipe Here is some lines of my code(keep in mind my app works perfect on emulator) ............ LoggerUtil.logToFile(TAG, "url is [" + url + "]"); LoggerUtil.logToFile(TAG, "NetworkInfo - " + connectivityManager.getActiveNetworkInfo()); ResponseEntity<T> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, clazz); ............. I know my device's network works perfect because all other applications on my device are working and also using device browser I'm able to connect to my server so my server is available. My server is up and running and my device is able to connect to my server so why I get java.net.SocketException: Broken pipe ?!!!!!!! Before I call restTemplate.exchange() I log NetworkInfo and it looks ok -type: WIFI -status: CONNECTED/CONNECTED -isAvailable: true Thanks in advance. Update: It is really weird Even if I use HttpURLConnection, it works perfectly on emulator but on real device I get 400 Bad Request Here is my code HttpURLConnection con = null; try { String url = ....; LoggerUtil.logToFile(TAG, "url [" + url + "]" ); con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Connection", "Keep-Alive"); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.connect(); LoggerUtil.logToFile(TAG, "con.getResponseCode is " + con.getResponseCode()); LoggerUtil.logToFile(TAG, "con.getResponseMessage is " + con.getResponseMessage()); } catch(Throwable t){ LoggerUtil.logToFile(TAG, "*** failed [" + t + "]" ); } in log file I see con.getResponseCode is 400 con.getResponseMessage is Bad Request

    Read the article

  • GWT JsonpRequestBuilder Timeout issue

    - by Anthony Kong
    I am getting time out from using JsonpRequestBuilder. The entry point code goes like this: // private static final String SERVER_URL = "http://localhost:8094/data/view/"; private static final String SERVER_URL = "http://www.google.com/calendar/feeds/[email protected]/public/full?alt=json-in-script&callback=insertAgenda&orderby=starttime&max-results=15&singleevents=true&sortorder=ascending&futureevents=true"; private static final String SERVER_ERROR = "An error occurred while " + "attempting to contact the server. Please check your network " + "connection and try again."; /** * This is the entry point method. */ public void onModuleLoad() { JsonpRequestBuilder requestBuilder = new JsonpRequestBuilder(); // requestBuilder.setTimeout(10000); requestBuilder.requestObject(SERVER_URL, new Jazz10RequestCallback()); } class Jazz10RequestCallback implements AsyncCallback<Article> { @Override public void onFailure(Throwable caught) { Window.alert("Failed to send the message: " + caught.getMessage()); } @Override public void onSuccess(Article result) { // TODO Auto-generated method stub Window.alert(result.toString()); } The article class is simply: import com.google.gwt.core.client.JavaScriptObject; public class Article extends JavaScriptObject { protected Article() {}; } The gwt page, however, always hit the onFailure() callback and show this alert: Failed to send the message. Timeout while calling <url>. Fail to see anything on the Eclipse plugin console. I tried the url and it works perfectly. Would appreciate any tip on debugging technique or suggestion

    Read the article

  • Dynamic if statement evaluation problem with string comparison

    - by Mani
    I tried the example given in this thread to create if statement dynamically using BeanShell. But it is not working fine. Instead of using "age" variable as integer, i have used string in the below example. I am getting "fail" as answer instead of "success". Can anyone help me? /* To change this template, choose Tools | Templates and open the template in the editor. */ import java.lang.reflect.*; import bsh.Interpreter; public class Main { public static String d; public static void main(String args[]) { try { String age = "30"; String cond = "age==30"; Interpreter i = new Interpreter(); i.set("age", age); System.out.println(" sss" + i.get("age")); if((Boolean)i.eval(cond)) { System.out.println("success"); } else { System.out.println("fail"); } } catch (Throwable e) { System.err.println(e); } } } Thanks, Mani

    Read the article

  • J2ME web service client

    - by Wasim
    Hi all , I started to use the Netbeans 6.8 web service client wizard . I created a web service (.Net web service) witch return an object Data. The Data class , contains fileds with many types : int , string , double , Person object and array of Person object. I created the J2ME client code through the wizard and every thing seems ok . I see in the Netbeans project the service and the stub . When I try to call my web service method , say Data GetData() ; Then I have a problem with parsing the returned data from the web service and the client data object . As follows : After finishing to call the web service method , in the stub code : public Data helloWorld() throws java.rmi.RemoteException { Object inputObject[] = new Object[] { }; Operation op = Operation.newInstance( _qname_operation_HelloWorld, _type_HelloWorld, _type_HelloWorldResponse ); _prepOperation( op ); op.setProperty( Operation.SOAPACTION_URI_PROPERTY, "http://tempuri.org/HelloWorld" ); Object resultObj; try { resultObj = op.invoke( inputObject ); } catch( JAXRPCException e ) { Throwable cause = e.getLinkedCause(); if( cause instanceof java.rmi.RemoteException ) { throw (java.rmi.RemoteException) cause; } throw e; } return Data_fromObject((Object[])resultObj); } private static Data Data_fromObject( Object obj[] ) { if(obj == null) return null; Data result = new Data(); result.setIntData(((Integer )obj[0]).intValue()); result.setStringData((String )obj[1]); result.setDoubleData(((Double )obj[2]).doubleValue()); return result; } I debug the code and in Run time resultObj has one element witc is an array of the Data object , so in parsing the values in the Data_fromObject method it expect many cells like we see in the code obj[0] , obj[1] , obj [2] but in realtime it has obj[0][0] , obj[0][1] , obj[0][2] What can be the problem , how can check the code generation issue ? Is it a problem with the web service side. Please help. Thanks in advance...

    Read the article

  • Intercepting method with Spring AOP using only annotations

    - by fish
    In my Spring context file I have something like this: <bean id="userCheck" class="a.b.c.UserExistsCheck"/> <aop:config> <aop:aspect ref="userCheck"> <aop:pointcut id="checkUser" expression="execution(* a.b.c.d.*.*(..)) &amp;&amp; args(a.b.c.d.RequestObject)"/> <aop:around pointcut-ref="checkUser" method="checkUser"/> </aop:aspect> </aop:config> a.b.c.UserExistsCheck looks like this: @Aspect public class UserExistsCheck { @Autowired private UserInformation userInformation; public Object checkUser(ProceedingJoinPoint pjp) throws Throwable { int userId = ... //get it from the RequestObject passed as a parameter if (userExists(userId)) { return pjp.proceed(); } else { return new ResponseObject("Invalid user); } } And the class that is being intercepted with this stuff looks like this: public class Klazz { public ResponseObject doSomething(RequestObject request) {...} } This works. UserExistCheck is executed as desired before the call is passed to Klazz. The problem is that this is the only way I got it working. To get this working by using annotations instead of the context file seems to be just too much for my small brain. So... how exactly should I annotate the methods in UserExistsCheck and Klazz? And do I still need something else too? Another class? Still something in the context file?

    Read the article

  • Bluetooth connection. Problem with sony ericsson.

    - by Hugi
    I have bt client and server. Then i use method Connector.open, client connects to the port, but passed so that my server does not see them. Nokia for all normal, but with sony ericsson i have this problem. On bt adapter open one port (com 5). Listings Client /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.util.Vector; import javax.bluetooth.*; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; import java.io.*; /** * @author ????????????? */ public class Client extends MIDlet implements DiscoveryListener, CommandListener { private static Object lock=new Object(); private static Vector vecDevices=new Vector(); private ServiceRecord[] servRec = new ServiceRecord[INQUIRY_COMPLETED]; private Form form = new Form( "Search" ); private List voteList = new List( "Vote list", List.IMPLICIT ); private List vote = new List( "", List.EXCLUSIVE ); private RemoteDevice remoteDevice; private String connectionURL = null; protected int stopToken = 255; private Command select = null; public void startApp() { //view form Display.getDisplay(this).setCurrent(form); try { //device search print("Starting device inquiry..."); getAgent().startInquiry(DiscoveryAgent.GIAC, this); try { synchronized(lock){ lock.wait(); } }catch (InterruptedException e) { e.printStackTrace(); } //device count int deviceCount=vecDevices.size(); if(deviceCount <= 0) { print("No Devices Found ."); } else{ remoteDevice=(RemoteDevice)vecDevices.elementAt(0); print( "Server found" ); //create uuid UUID uuid = new UUID(0x1101); UUID uuids[] = new UUID[] { uuid }; //search service print( "Searching for service..." ); getAgent().searchServices(null,uuids,remoteDevice,this); } } catch( Exception e) { e.printStackTrace(); } } //if deivce discovered add to vecDevices public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) { //add the device to the vector try { if(!vecDevices.contains(btDevice) && btDevice.getFriendlyName(true).equals("serverHugi")){ vecDevices.addElement(btDevice); } } catch( IOException e ) { } } public synchronized void servicesDiscovered(int transID, ServiceRecord[] servRecord) { //for each service create connection if( servRecord!=null && servRecord.length>0 ){ print( "Service found" ); connectionURL = servRecord[0].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false); //connectionURL = servRecord[0].getConnectionURL(ServiceRecord.AUTHENTICATE_NOENCRYPT,false); } if ( connectionURL != null ) { showVoteList(); } } public void serviceSearchCompleted(int transID, int respCode) { //print( "serviceSearchCompleted" ); synchronized(lock){ lock.notify(); } } //This callback method will be called when the device discovery is completed. public void inquiryCompleted(int discType) { synchronized(lock){ lock.notify(); } switch (discType) { case DiscoveryListener.INQUIRY_COMPLETED : print("INQUIRY_COMPLETED"); break; case DiscoveryListener.INQUIRY_TERMINATED : print("INQUIRY_TERMINATED"); break; case DiscoveryListener.INQUIRY_ERROR : print("INQUIRY_ERROR"); break; default : print("Unknown Response Code"); break; } } //add message at form public void print( String msg ) { form.append( msg ); form.append( "\n\n" ); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } //get agent :))) private DiscoveryAgent getAgent() { try { return LocalDevice.getLocalDevice().getDiscoveryAgent(); } catch (BluetoothStateException e) { throw new Error(e.getMessage()); } } private synchronized String getMessage( final String send ) { StreamConnection stream = null; DataInputStream in = null; DataOutputStream out = null; String r = null; try { //open connection stream = (StreamConnection) Connector.open(connectionURL); in = stream.openDataInputStream(); out = stream.openDataOutputStream(); out.writeUTF( send ); out.flush(); r = in.readUTF(); print( r ); in.close(); out.close(); stream.close(); return r; } catch (IOException e) { } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { } } return r; } } private synchronized void showVoteList() { String votes = getMessage( "c_getVotes" ); voteList.append( votes, null ); select = new Command( "Select", Command.OK, 4 ); voteList.addCommand( select ); voteList.setCommandListener( this ); Display.getDisplay(this).setCurrent(voteList); } private synchronized void showVote( int index ) { String title = getMessage( "c_getVote_"+index ); vote.setTitle( title ); vote.append( "Yes", null ); vote.append( "No", null ); vote.setCommandListener( this ); Display.getDisplay(this).setCurrent(vote); } public void commandAction( Command c, Displayable d ) { if ( c == select && d == voteList ) { int index = voteList.getSelectedIndex(); print( ""+index ); showVote( index ); } } } Use BlueCove in this program. Server /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication4; import java.io.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.bluetooth.*; import javax.microedition.io.*; import javaapplication4.Connect; /** * * @author ????????????? */ public class SampleSPPServer { protected static int endToken = 255; private static Lock lock=new ReentrantLock(); private static StreamConnection conn = null; private static StreamConnectionNotifier streamConnNotifier = null; private void startServer() throws IOException{ //Create a UUID for SPP UUID uuid = new UUID("1101", true); //Create the service url String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server"; //open server url StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString ); while ( true ) { Connect ct = new Connect( streamConnNotifier.acceptAndOpen() ); ct.getMessage(); } } /** * @param args the command line arguments */ public static void main(String[] args) { //display local device address and name try { LocalDevice localDevice = LocalDevice.getLocalDevice(); localDevice.setDiscoverable(DiscoveryAgent.GIAC); System.out.println("Name: "+localDevice.getFriendlyName()); } catch( Throwable e ) { e.printStackTrace(); } SampleSPPServer sampleSPPServer=new SampleSPPServer(); try { //start server sampleSPPServer.startServer(); } catch( IOException e ) { e.printStackTrace(); } } } Connect /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication4; import java.io.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.bluetooth.*; import javax.microedition.io.*; /** * * @author ????????????? */ public class Connect { private static DataInputStream in = null; private static DataOutputStream out = null; private static StreamConnection connection = null; private static Lock lock=new ReentrantLock(); public Connect( StreamConnection conn ) { connection = conn; } public synchronized void getMessage( ) { Thread t = new Thread() { public void run() { try { in = connection.openDataInputStream(); out = connection.openDataOutputStream(); String r = in.readUTF(); System.out.println("read:" + r); if ( r.equals( "c_getVotes" ) ) { out.writeUTF( "vote1" ); out.flush(); } if ( r.equals( "c_getVote_0" ) ) { out.writeUTF( "Vote1" ); out.flush(); } out.close(); in.close(); } catch (Throwable e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } try { connection.close(); } catch( IOException e ) { } } } }; t.start(); } }

    Read the article

  • Can't get past 2542 Threads in Java on 4GB iMac OSX 10.6.3 Snow Leopard (32bit)

    - by fuzzy lollipop
    I am running the following program trying to figure out how to configure my JVM to get the maximum number of threads my machine can support. For those that might not know, Snow Leopard ships with Java 6. I tried starting it with defaults, and the following command lines, I always get the Out of Memory Error at Thread 2542 no matter what the JVM options are set to. java TestThreadStackSizes 100000 java -Xss1024 TestThreadStackSizes 100000 java -Xmx128m -Xss1024 TestThreadStackSizes 100000 java -Xmx2048m -Xss1024 TestThreadStackSizes 100000 java -Xmx2048m -Xms2048m -Xss1024 TestThreadStackSizes 100000 no matter what I pass it, I get the same results, Out of Memory Error at 2542 public class TestThreadStackSizes { public static void main(final String[] args) { Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(final Thread t, final Throwable e) { System.err.println(e.getMessage()); System.exit(1); } }); int numThreads = 1000; if (args.length == 1) { numThreads = Integer.parseInt(args[0]); } for (int i = 0; i < numThreads; i++) { try { Thread t = new Thread(new SleeperThread(i)); t.start(); } catch (final OutOfMemoryError e) { throw new RuntimeException(String.format("Out of Memory Error on Thread %d", i), e); } } } private static class SleeperThread implements Runnable { private final int i; private SleeperThread(final int i) { this.i = i; } public void run() { try { System.out.format("Thread %d about to sleep\n", this.i); Thread.sleep(1000 * 60 * 60); } catch (final InterruptedException e) { throw new RuntimeException(e); } } } } Any ideas on now I can affect these results?

    Read the article

  • Connection details & timeouts in a java web service client

    - by f1sh
    Hello fellow Coders, I have to implement a webservice client to a given WSDL file. I used the SDK's 'wsimport' tool to create Java classes from the WSDL as well as a class that wrap's the webservice's only method (enhanceAddress(auth, param, address)) into a simple java method. So far, so good. The webservice is functional and returning results correcty. The code looks like this: try { EnhancedAddressList uniservResponse = getWebservicePort().enhanceAddress(m_auth, m_param, uniservAddress); //Where the Port^ is the HTTP Soap 1.2 Endpoint }catch (Throwable e) { throw new AddressValidationException("Error during uniserv webservice request.", e); } The Problem now: I need to get Information about the connection and any error that might occur in order to populate various JMX values (such as COUNT_READ_TIMEOUT, COUNT_CONNECT_TIMEOUT, ...) Unfortunately, the method does not officially throw any Exceptions, so in order to get details about a ConnectException, i need to use getCause() on the ClientTransportException that will be thrown. Even worse: I tried to test the read timeout value, but there is none. I changed the service's location in the wsdl file to post the request to a php script that simply waits forever and does not return. Guess what: The web service client does not time out but waits forever as well (I killed the app after 30+ minutes of waiting). That is not an option for my application as i eventually run out of tcp connections if some of them get 'stuck'. The enhanceAddress(auth, param, address) method is not implemented but annotated with javax.jws.* Annotations, meaning that i cannot see/change/inspect the code that is actually executed. Do i have any option but to throw the whole wsimport/javax.jsw-stuff away and implement my own soap client?

    Read the article

  • How can I implement a proper counter bean with EJB 3.0?

    - by Aaron Digulla
    I have this entity bean: import javax.persistence.*; @Entity public class CounterTest { private int id; private int counter; @Id public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCounter() { return counter; } public void setCounter(int counter) { this.counter = counter; } } and this stateful bean to increment a counter: import java.rmi.RemoteException; import javax.ejb.*; import javax.persistence.*; @Stateful public class CounterTestBean implements CounterTestRemote { @PersistenceContext(unitName = "JavaEE") EntityManager manager; public void initDB() { CounterTest ct = new CounterTest(); ct.setNr(1); ct.setWert(1); manager.persist(ct); } public boolean testCounterWithLock() { try { CounterTest ct = manager.find(CounterTest.class, 1); manager.lock(ct, LockModeType.WRITE); int wert = ct.getWert(); ct.setWert(wert + 1); manager.flush(); return true; } catch (Throwable t) { return false; } } } When I call testCounterWithLock() from three threads 500 times each, the counter gets incremented between 13 and 1279 times. How do I fix this code so that it is incremented 1500 times?

    Read the article

  • thread reaches end but isn't removed

    - by pstanton
    I create a bunch of threads to do some processing: new Thread("upd-" + id){ @Override public void run(){ try{ doSomething(); } catch (Throwable e){ LOG.error("error", e); } finally{ LOG.debug("thread death"); } } }.start(); I know i should be using a threadPool but i need to understand the following problem before i change it: I'm using eclipse's debugger and looking at the threads in the debug pane which lists active threads. Many of them complete as you would expect, and are removed from the debug pane, however some seem to stay in the list of active threads even though the log shows the "thread death" entry for these. When i attempt to debug these threads, they either do not pause for debugging or show an error dialog: "A timeout occurred while retrieving stack frames for thread: upd-...". there is some synchronization going on within the doSomething() call but i'm fairly sure it's ok and since the "thread death" log is being called i'm assuming these threads aren't deadlocked in that method. i don't do any Thread.join()s, however i do call a third party API but doubt they do either. Can anyone think of another reason these threads are lingering? Thanks. EDIT: I created this test to check the Garbage Collection theory: Thread thread = new Thread("!!!!!!!!!!!!!!!!") { @Override public void run() { System.out.println("running"); ThreadUs.sleepQuiet(5000); System.out.println("finished"); // <-- thread removed from list here } }; thread.start(); ThreadUs.sleepQuiet(10000); System.out.println(thread.isAlive()); // <-- thread already removed from list but hasn't been GC'd ThreadUs.sleepQuiet(10000); this proves that it is nothing to do with garbage collection as eclipse removes the thread from the thread list as soon as it completes and isn't waiting for the object to be de-referenced/GC'd.

    Read the article

  • Asynchronous callback - gwt

    - by sprasad12
    Hi, I am using gwt and postgres for my project. On the front end i have few widgets whose data i am trying to save on to tables at the back-end when i click on "save project" button(this also takes the name for the created project). In the asynchronous callback part i am setting more than one table. But it is not sending the data properly. I am getting the following error: org.postgresql.util.PSQLException: ERROR: insert or update on table "entitytype" violates foreign key constraint "entitytype_pname_fkey" Detail: Key (pname)=(Project Name) is not present in table "project". But when i do the select statement on project table i can see that the project name is present. Here is how the callback part looks like: oksave.addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event) { if(erasync == null) erasync = GWT.create(EntityRelationService.class); AsyncCallback<Void> callback = new AsyncCallback<Void>(){ @Override public void onFailure(Throwable caught) { } @Override public void onSuccess(Void result){ } }; erasync.setProjects(projectname, callback); for(int i = 0; i < boundaryPanel.getWidgetCount(); i++){ top = new Integer(boundaryPanel.getWidget(i).getAbsoluteTop()).toString(); left = new Integer(boundaryPanel.getWidget(i).getAbsoluteLeft()).toString(); if(widgetTitle.startsWith("ATTR")){ type = "regular"; erasync.setEntityAttribute(name1, name, type, top, left, projectname, callback); } else{ erasync.setEntityType(name, top, left, projectname, callback); } } } Question: Is it wrong to set more than one in the asynchronous callback where all the other tables are dependent on a particular table? when i say setProjects in the above code isn't it first completed and then moved on to the next one? Please any input will be greatly appreciated. Thank you.

    Read the article

  • Dymanic if statement evaluation problem with string comparison

    - by Mani
    I tried the example given in http://forums.sun.com/thread.jspa?threadID=780576&tstart=67605 to create if statement dynamically. But it is not working fine. Instead of using "age" variable as integer, i have used string in the below example. I am getting "fail" as answer instead of "success". Can anyone help me? / To change this template, choose Tools | Templates and open the template in the editor. / import java.lang.reflect.*; import bsh.Interpreter; public class Main { public static String d; public static void main(String args[]) { try { String age = "30"; String cond = "age==30"; Interpreter i = new Interpreter(); i.set("age", age); System.out.println(" sss" + i.get("age")); if((Boolean)i.eval(cond)) { System.out.println("success"); } else { System.out.println("fail"); } } catch (Throwable e) { System.err.println(e); } } } Thanks, Mani

    Read the article

  • Spring - Transaction Readonly

    - by AAK
    Hello Gurus! Just wanted your expert opinions on declarative transaction management for Spring. Here is my setup - A. DAO Layer is Plain old JDBC using jdbcTemplete (No hibernate etc) B. Service Layer is POJO with declarative trasnactions as follows - save*, readonly=false, rollback for Throwable Things work fine with above setup. However when I say get*, readonly=true I see errors in my log file saying - Database connection cannot be marked as readonly. This happens for all get* methods in Service Layer. Now my questions - A. Do I have to say get* as readonly? All my get* methods are pure read DB operations. I do not wish to run them in any transaction context. How serious is the above error? B. When I remove the get* confiiguration, I do not see the errors, morever all my simple get* operations are performed without transactions. Is this the way to go? C. Why would anyone want to have transactional methods where readonly = true? Is there any practical significance of this configuration? Thank you! As always your resposes are much appreciated!

    Read the article

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