mardi 25 août 2015

Iterating through arraylist to solve aproblem

In my code below I am trying to find out "products" which has no child associated with it. I have a structure of products like parent and child. Products are in an arraylist:{A,B,C,D,E,F,G}. I represent these products(A,B,C..) as objects of class ProductionOrder:

public class ProductionOrder {

    public int id;
    public int parentId;


    public ProductionOrder(int ids,int parentIds) {
        id=ids;
        parentId=parentIds;
    }
}

I store each product(A,B,C..) with an id and its associated productId(If any). If it is a parent or if the product does not have a child and is standalone, I assign parentID as 0. if it is a child of some parent(A(Id=1)) , I assign A's child with parentID=1. Now I need to sort out all the child and standalone product and store it in a list and return it. Here is what I started, but need to think of a logic to iterate and get the childs:

import java.util.*;

public class ProductTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Hello");
        ArrayList<ProductionOrder> prod=new ArrayList<ProductionOrder>();
        ProductionOrder A=new ProductionOrder(1,0);
        prod.add(A);
        ProductionOrder F=new ProductionOrder(2,1);
        prod.add(F);
        ProductionOrder C=new ProductionOrder(3,1);
        prod.add(C);
        ProductionOrder E=new ProductionOrder(4,3);
        prod.add(E);
        ProductionOrder D=new ProductionOrder(5,0);
        prod.add(D);
        ProductionOrder B=new ProductionOrder(6,5);
        prod.add(B);
        ProductionOrder G=new ProductionOrder(7,0);
        prod.add(G);


        ArrayList<ProductionOrder> result=ProdOrder(prod);

    }


    static ArrayList<ProductionOrder> ProdOrder(ArrayList<ProductionOrder> prodord){

        ArrayList<ProductionOrder> child=new ArrayList<ProductionOrder>();

        // logic to get the child and the standalone product with no child like G


        return child;

    }




}



from Newest questions tagged java - Stack Overflow http://ift.tt/1NSnBtK
via IFTTT

Linking Java's jvm.lib with Visual C++ application produces exe that fails with can't find jvm.dll

I am porting an application that works in linux to Windows. The application uses libjvm to start a Java virtual machine and run some Java classes that interoperate with main code written in C++.

I have installed JDK1.8.0_60, and Visual Studio 2010.

I set the following properties under Configuration Properties -> VC++ Directories

Include Directories:
C:\Program Files\Java\jdk1.8.0_60\include\win32;C:\Program Files\Java\jdk1.8.0_60\include;$(IncludePath)

Library Directories:
C:\Program Files\Java\jdk1.8.0_60\lib;C:\Program Files\Java\jdk1.8.0_60\jre\bin\server;C:\Program Files\Java\jdk1.8.0_60\jre\lib\amd64;$(LibraryPath)

Under Linker -> Input -> Additional Dependancies:
jvm.lib;%(AdditionalDependencies)

Configuration Dropdown : Active(Debug)
Platform Dropdown : Active(x64)

The program compiles and links without errors.
When I run the program whether in Visual Studio or from the Command prompt the error pops up:

screenshot of error

I can find two copies of jvm.dll on my computer.

C:\Program Files\Java\jre1.8.0_60\bin\server\jvm.dll
C:\Program Files\Java\jdk1.8.0_60\jre\bin\server\jvm.dll

I tried adding those directories to the PATH with

set JVMDLLDIR="C:\Program Files\Java\jre1.8.0_60\bin\server";
set PATH=%LIBJVMDIR%;%PATH%
Simple.exe

It had no effect, the error was the same.

In linux I compile with the flag -Wl,--rpath /usr/lib/jvm/... so that linux can find the libjvm.so when my program runs. It would seem that a similiar option for Visual C++ is needed but I can not find one. Another alternative in linux would be to add the directory to the LD_LIBRARY_PATH environment variable, but again I have been unable to find a similiar option in windows.



from Newest questions tagged java - Stack Overflow http://ift.tt/1hZuy27
via IFTTT

How should I handle data averages? (Design)

I currently have a data set contained in a java class that can be used to compute a separate set of values (essentially a table of averages.) I am debating between three options:

  1. Create a method to calculate the averages in the current class.
  2. Create a new class that operates as a domain object and can compute the averages from the data in the data object.
  3. Create a new class that is instantiated at the same time as the data object that contains the averages.

What is the best way to handle this structure? (Thanks and sorry if this is too opinion based.)



from Newest questions tagged java - Stack Overflow http://ift.tt/1hZuy24
via IFTTT

OkHttp callback eats up exceptions - design flaw or common practice

OkHttp library Callback interface is declared as

public interface Callback {
  void onFailure(Request request, IOException e);
  void onResponse(Response response) throws IOException;
}

Unhandled exceptions from onResponse method will get eaten up by Call class as I have recently discovered in Callback failure for cancelled call in OkHttp

I have few questions related to that design.


First, wouldn't it be better have different declaration of onResponse method in order to force catching exceptions in onResponse rather than throwing them, since they will be eaten up.

Is this design flaw in OkHttp Callback interface or is this kind of code common practice in Java?


Second, when http request reaches onResponse callback method I would expect that canceling request at that point should be prohibited. I would say this is a bug. Am I right?



from Newest questions tagged java - Stack Overflow http://ift.tt/1NSnzCe
via IFTTT

How can I change the database (in the same server) that is used in sprigboot?

I have a MySQL installation with an IP = X.XX.XX.XXX:PORT. If I want to connect via java, I do:


    jdbc:http://mysqlX.XX.XX.XXX:PORT/software_database

Where software_store is a database in my server, and if I want to change to another database (in the same server) in order to change I do (MySQL query):


    use bookstore_database;

then, if I want to return to the first database I do:


    use software_database;

I'm currently working with SpringBoot, but when I do the above queries doesn't make the change. Any idea of how to switch between databases on the same server without disconnect and reconnect the whole database connection?

Thanks



from Newest questions tagged java - Stack Overflow http://ift.tt/1hZuzTQ
via IFTTT

struts 2- Unable to render XSLT view with no XSL stylesheet

I am using struts 2 application. Having issue with XSLT result type. below is my

Struts Config Snippet: XSLTResult (HashMap, no location XSL)

<action name="QueryDocuments" class="com.onbase.proxy.QueryDocuments">
      <result name="success" type="xslt">
      <param name="exposedValue">Hm</param>
      </result>
      <result name="error" type="xslt">
      <param name="exposedValue">Hm</param>
      </result>
 </action>


***Exception:***
Aug 25, 2015 1:10:10 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger error
SEVERE: Unable to render XSLT Template, 'null'
Error transforming result - [unknown location]
    at org.apache.struts2.views.xslt.XSLTResult$1.error(XSLTResult.java:351)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.postErrorToListener(TransformerImpl.java:811)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:754)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:359)
    at org.apache.struts2.views.xslt.XSLTResult.execute(XSLTResult.java:388)
    at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:362)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:266)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)
    at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.xml.transform.TransformerException: Operation not supported.
    ... 68 more

Using struts2-core-2.1.8.1.jar, xwork-core-2.1.6.jar.

Do we need to specify XSL stylesheet location in result?

Thanks



from Newest questions tagged java - Stack Overflow http://ift.tt/1hZuxLE
via IFTTT

Where to store form error message content

I am working on a jsp/servlet web application. I currently use a switch statement within my servlet to select the appropriate error message for each form field (according to the input) and then set that message as a request attribute.

I now want to internationalize the web page (have it available in another language). I was thinking to do this by having a separate directory for the other language and placing the jsps in the other language in that directory. Then a filter will redirect to the appropriate directory via a session attribute.

The problem is that my custom error messages are currently written in the servlet. I was not planning to reroute to different servlets according to the language (ie: same servlet will run for all languages). The only way that I can think of to do this would be to write each of the custom error messages on the jsp and then have the servlet set a request attribute that identifies the error type.

This solution would require adding a lot of text to the jsps (some fields have 10 different error messages and different messages depending on user type).

Any suggestions of a better approach for making the form error messages multi lingual are welcome. Also, if there are any general suggestions on a better way to internationalize my site altogether that is also welcome.

Thank you, .



from Newest questions tagged java - Stack Overflow http://ift.tt/1hZuxv8
via IFTTT

Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException

when i run my code, i get this exception:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1121)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:357)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2482)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2519)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2304)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:834)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:346)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
    at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
    at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155)
    at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:120)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)
    at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:51)
    at org.hibernate.tool.hbm2ddl.DatabaseExporter.<init>(DatabaseExporter.java:52)
    at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:367)
    at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:304)
    at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:293)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:517)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1857)
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Aug 25, 2015 8:23:45 PM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SCHWERWIEGEND: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: Could not open connection
    at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:431)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:457)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy76.create(Unknown Source)

I don't know where is the problem. But yesterday i worked fine.

my database.properties:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/streaming
jdbc.username=root
jdbc.password=password

hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.showsql=true
hibernate.hbm2ddl.auto=create

It is possible for me to run mysql directly from command line. Where is the problem? Was is wrong. I use spring 4 and hibernate with mysql as database language.

Has someone any ideas?

Thank.



from Newest questions tagged java - Stack Overflow http://ift.tt/1NSnz5h
via IFTTT

Spring Boot Custom Error Page Stack Trace

I have found on several locations how to use Spring boot to make a custom error page but I cannot seem to figure out how to make it show a stack trace.

This is what I have:

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {

    return new EmbeddedServletContainerCustomizer() {
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {

            ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/WEB-INF/jsp/app/404.jsp");
            ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/WEB-INF/jsp/app/500.jsp");

            container.addErrorPages(error404Page, error500Page);
        }
    };
}

Any ideas how I could figure this out or how to get the stack trace to begin with?



from Newest questions tagged java - Stack Overflow http://ift.tt/1Id9CcY
via IFTTT

Convert Json Rest to Java DTO

is there a way that I can take the DTO's from a REST api? I want to create my DTO's automaticaly from the JSON REST api. Is there some way?



from Newest questions tagged java - Stack Overflow http://ift.tt/1WQGOCe
via IFTTT

Merge ArrayLists of different types (but compatible) [Java]

I have a class we can call Super and a subclass (of Super) that we can call SubClass(SubClass extends Super). And then somewhere else I have two arraylists, one of type Super and another of type SubClass. (ArrayList< Super > a1, ArrayList< SubClass > a2)

And what I'd like to do is add all the elements from a2 into a1, since all a2 elements are indeed type Super. What I tried doing was using

a1.addAll(a2);

But when I use that it returns false (.addAll() returns true if the a1 gets modified at all, and false if not)

I'm sure it can be done simply by iterating through the a2 list and adding each element using a1.add() and a cast but I'd like to know if the addAll() can be used in such case to shrink the code a little, Thanks in advance!



from Newest questions tagged java - Stack Overflow http://ift.tt/1Id9zOj
via IFTTT

how to set HMA proxy in java application

Here is how i am setting the proxy in my application

    System.setProperty("java.net.useSystemProxies", "true");
    System.setProperty("http.proxyHost","HMA");
    System.setProperty("http.proxyPort","1111");
    System.setProperty("http.proxyUser",username);
    System.setProperty("http.proxyPassword",password);

    System.setProperty("https.proxyHost","HMA");
    System.setProperty("https.proxyPort","1111");
    System.setProperty("https.proxyUser",username);
    System.setProperty("https.proxyPassword",password);

My original ip is 192.***

After running this application i am getting 10.***

My HMA showing ip is 199.***

I am not getting the vpn ip.



from Newest questions tagged java - Stack Overflow http://ift.tt/1WQGMdB
via IFTTT

Can java objects access their instance methods when coding in groovy?

I have written two java classes, with a constructor and an instance method to return an JSON array. I want to access instance of these classes in groovy and call the getArray method on these objects I have instantiated. My problem is I do not know how to access those getArray methods?? Here is some code:

import JSONEncounterDesk;
import JSONHelpDesk;
import org.codehaus.groovy.grails.web.json.JSONObject

    class UsersController {

        def index() { 
            JSONEncounterDesk currEncounterDesk = new JSONEncounterDesk();
            JSONHelpDesk currHelpDesk = new JSONHelpDesk();

            return render(contentType: 'text/json') {
                ret
            }
        }
    }



from Newest questions tagged java - Stack Overflow http://ift.tt/1Id9BWB
via IFTTT

How to use wsdl url for java

in my java application i need to use third party SMS services.they provied username and password and also 2 links regarding SOAP and WSDL. I do not have any idea about how to use those links and whats the process further.Please help me for learning next steps which i need to follow.



from Newest questions tagged java - Stack Overflow http://ift.tt/1WQGOlN
via IFTTT

How can I set Priority in java Threads?

I am a beginner of java programming. I wrote a java program with multiple threads. Now i want to set priority of this threads. How can it possible. Please help me.



from Newest questions tagged java - Stack Overflow http://ift.tt/1LytoHt
via IFTTT

Java External Program in Frame/Panel etc

This is probably pretty simple (or impossible ;D) but can I catch or embed an external program in a jPanel, jInternalFrame, jLabel or some other component ?

What I'm trying to do is run a Linux program via Runtime.getRuntime().exec (which opens in a border-less window) and display/interact with it in my JavaGUI.

Thanks for your help in advance :D.



from Newest questions tagged java - Stack Overflow http://ift.tt/1LytlM3
via IFTTT

How to import Suprema java classes?

Can any body help? I bought a Suprema sdk, so I want to use it in my web application through an applet. So I am using netbeans 8.0, when I run the java examples, I get errors that the packages do not exist. Thank in advance.



from Newest questions tagged java - Stack Overflow http://ift.tt/1LytnDs
via IFTTT

Why does my Eclipse load with phantom breakpoints and old errors?

So, I deleted a waypoint after using it a LONG time ago. Everything I load Eclipse, they are back. It's very wierd, some never reappear, and some reappear daily for months and months, until they disappear. I also sometimes load into old compile errors, many of which are completely irrelevant to their line, or not even on a line(in whitespace), and cleaning the project is mandatory each load.

I'm running Linux if it matters, but I recall this happening on my Windows too. I do copy my preferences from machine to machine.



from Newest questions tagged java - Stack Overflow http://ift.tt/1LytnDn
via IFTTT

How to stop an OSGI Application from command line

I do have a running osgi (equinox container) application. It will been started via a bash script. See felix gogo shell

java -jar ... _osgi.jar -console 1234 &

This all works pretty well and I also can stop it via

telnet localhost 1234
<osgi>stop 0

But what I am looking for is how can I embed this into a bash script to stop the osgi application.

I already tried this

stop 0 | telnet localhost 1234

but this doesn't work. So if someone has idea how to put this in a bash script, please let me know.



from Newest questions tagged java - Stack Overflow http://ift.tt/1JtUFo2
via IFTTT

why String in java does not override readObject?

I was studying effective java and In immutability(Item 15) it is written that: Make defensive copies (Item 39) in constructors, accessors, and readObject methods (Item 76).

And In Item 76 It is advised to override readObject and create a defensive copy of the mutable object by compromising final keyword. So i checked the String class in java and check whether they have done the same for final char value[]; but readObject is not overridden.

I am confused about this ? Please if answer.



from Newest questions tagged java - Stack Overflow http://ift.tt/1LytnmY
via IFTTT

Cannot use appcompat-v7

I have faced a big problem with android sdk. I wasted near 24hours to fix this problem. But I couldn't fix it (sorry for my bad English)

Here is problem I'm faced now.

  • I have used Eclipse for android development. Few days ago I downloaded Android Studio.

  • yesterday I created a 'hello world' project and Android Studio take too long time to build project

  • So I Ended A-Studio process from task manager. Also I end process named aapt.exe

  • After that I try to create project in Eclipse. Eclipse showing this error.

[2015-08-25 15:14:36 - appcompat_v7] WARNING: unable to write jarlist cache file C:\Users\sachintha\workspace\appcompat_v7\bin\jarlist.cache

  • also I can see error mark on appcompat_v7 -> resource folder.

  • When I try to create project in A-Studio it's showing this error and the letter 'R'-(resources) marked red color in MainActivity.

Error:Execution failed for task ':app:processDebugResources'. com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'D:\eclipse\adt-bundle-windows-x86_64-20140702\sdk\build-tools\21.0.2\aapt.exe'' finished with non-zero exit value 1

I tried to fix this with below steps

  • clear\rebuild projects

  • change eclipse workspace.

  • Deleting .Android folder for clear catch

  • Deleting .AndroidStudio folder and start Android-Studio as fresh install

  • reinstalling JDK

  • Delete and redownload android build tool 23, Android support repository and Android support library

I failed to fix this problem and I can only create projects min-sdk=14 or above.



from Newest questions tagged java - Stack Overflow http://ift.tt/1EgEcY0
via IFTTT

Adding words to collection [on hold]

Okay. I am supposed to write the code for a button that will add a word to some sort of collection. The demands is that the word can only be saved in the collection if the word is unique. Also if the user tries to add more than 10 words there will be thrown an exception "CollectionFullException". I dont need to write the code for the exception just show how i use it.

This is what i got, how much does it suck?

public class JFrameFormTest extends javax.swing.JFrame {
    DefaultListModel listModel = new DefaultListModel();

    /**
     * Creates new form JFrameFormTest
     */
    public JFrameFormTest() {
        initComponents();
        initWordList();
    }

    private void initWordList() {
        lstWords.setModel(listModel);

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
        List l = new List();
        l.setWord(txt.Word.getText();

        int index = listModel.getSize();
        if (index > 10) {
            .
            listModel.addElement(s.toString());
        } else {
            JOptionPane.showMessageDialog(null, "List full");
        }



from Newest questions tagged java - Stack Overflow http://ift.tt/1Lytlvo
via IFTTT

GPS Coords being always 0.0-0.0 using LocationListener in a Android App

I need to develop an app for android for a university task and a part of it consists in sending the GPS coords of the device to my database. Here's the class that I'm using to get the coords

public class MyLocationListener implements LocationListener {

double latitude;
double  longitude;


public MyLocationListener(Context myContext){
    LocationManager locationManager = (LocationManager) myContext.getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}

public  double getLatitude(){
    return latitude; }

public  double getLongitude(){
    return longitude; }

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

   latitude =  location.getLatitude();
    longitude =  location.getLongitude();

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

}

That is called inside InterfaceActivity.java, using this:

        MyLocationListener ggwp = new MyLocationListener(InterfaceActivity.this);
    HttpDevices elenco = new HttpDevices(LoginIstance.getIst().getLog()[0],LoginIstance.getIst().getLog()[1],LoginIstance.getIst().getID(),String.valueOf(ggwp.getLatitude()),String.valueOf(ggwp.getLongitude()));

And finally HttpDevices is an asynttask that "runs" http messages to my database, using this code:

            HttpPost httppost = new HttpPost("http://ift.tt/1UbmTJY"+usr+"&pass="+pss+"&id="+id+"&lat="+lat+"&long="+log);

But the coords send to the database are always 0.0 - 0.0 , and I can't even try the code an debug it on the emulator ( blue stack ) because it doesn't have gps coords. Tried it on my Moto G but they are just 0. I tried spamming that string (connessione.php etc.. ) in my broweser giving random values for lat and long and yes, it works. It updates the database and shows the coords in my app, so the problem should be in the java. Any tips? I've searched alot in google/stackoverflow and didnt' find anything, it's the first time I encouter a problem that requires me to post here. Hope you can help me! Thank youu!

Edit: in case you want to take a look at my whole code there is a github link: http://ift.tt/1EgEePF



from Newest questions tagged java - Stack Overflow http://ift.tt/1UbmTK2
via IFTTT

How to show data from a Databse in Spring and Thymeleaf

I am creating a webapp with Spring and Thymeleaf and I want to create a page where an admin can search for users and then it would display a table of users with the matching name and their roles. I have no idea where to start and help would be much appreciated.

Thanks



from Newest questions tagged java - Stack Overflow http://ift.tt/1LytleS
via IFTTT

MongoDB: Odd write performance

I have been running into odd write performance as well using MongoDB 3.0.5 and mongo java driver 2.13.1. If the application has been idle for a given amount of time, the next write will take about 17 seconds, then any further writes are immediate. Preceding read is mere milliseconds. So, as observed, with exact same record count and size. There are only a few dozen records, and they are all rather small. Using default Write Concern, which is ACKNOWLEDGE.

Idle. Read ~10ms. Write 17 seconds. Read ~10ms. Write ~25ms.

Code sample is simple, with a rudimentary timer for above results:

Long timer = System.currentTimeMillis();
Stack<BasicDBObject> stack = new Stack<>();
DBCursor cloneCursor = cloneMongo.getCollection("ourCollection").find();
while (cloneCursor.hasNext())
{
    BasicDBObject cloneRec = (BasicDBObject) cloneCursor.next();
    if (cloneRec.containsField("name"))
    {
    if (cloneRec.getString("name").equals("project"))
    {
        cloneRec.put("default", destProject.getID());
    }
    }
    stack.add(cloneRec);
}
Util.print("Clone - Clone Read:"+(System.currentTimeMillis() - timer), 1);
DBCollection collection = cloneMongo.getCollection("sds_structure_" + destProject.getName());
BulkWriteOperation bulkOp = collection.initializeUnorderedBulkOperation();
Util.print("Clone - Clone DestConnect:"+(System.currentTimeMillis() - timer), 1);
while (!stack.isEmpty())
{
    bulkOp.insert(stack.pop());
}
bulkOp.execute();
Util.print("Clone - Clone Write:"+(System.currentTimeMillis() - timer), 1);

We have observed this exact pattern on Platter Disks, FusionIO drives, and 15kRPM SAS Drives, so I am dubious it is IO performance. If we set the write concern to JOURNALED, we consistently get 17 Second writes on all attempts.

The interim solution I found works is to periodically (~10 secs) write junk (even increment a value in an existing record) to a junk collection. This seems to fool the system, avoiding whatever is causing it to 'fall asleep'.

What settings in MongoDB or changes to our logic can avoid these abysmally slow initial writes?



from Newest questions tagged java - Stack Overflow http://ift.tt/1Lytn6n
via IFTTT

Scala - InvalidClassException: no valid constructor

I created a Serializable version of Guava's ImmutableRangeMap and Builder in Scala in order to use in my Spark application. I have a zero argument constructor in my SerializableImmutableRangeClass as well, so why do I get InvalidClassException: no valid constructor when I run my Spark application?

Here is my SerializableImmutableRangeClass object and class:

object SerializableImmutableRangeMap extends Serializable {
  final class SerializableBuilder[K <: Comparable[_], V]() extends Serializable {
    val keyRanges: RangeSet[K] = TreeRangeSet.create()
    val rangeMap: RangeMap[K, V] = TreeRangeMap.create()

    def put(range: Range[K], value: V): SerializableBuilder[K, V] = {
      checkNotNull(range)
      checkNotNull(value)
      checkArgument(!range.isEmpty(), "Range must not be empty, but was %s", range)
      if (!keyRanges.complement().encloses(range)) {
        // it's an error case; we can afford an expensive lookup
        for (entry: Entry[Range[K], V] <- JavaConversions.asScalaSet(rangeMap.asMapOfRanges().entrySet())) {
          val key: Range[K] = entry.getKey()
          if (key.isConnected(range) && !key.intersection(range).isEmpty()) {
            throw new IllegalArgumentException(
                "Overlapping ranges: range " + range + " overlaps with entry " + entry)
          }
        }
      }
      keyRanges.add(range)
      rangeMap.put(range, value)
      this
    }

    def putAll(rangeMap: RangeMap[K, _ <: V]): SerializableBuilder[K, V] = {
      for (entry <- JavaConversions.asScalaSet(rangeMap.asMapOfRanges().entrySet())) {
        put(entry.getKey(), entry.getValue())
      }
      this
    }

    def build(): SerializableImmutableRangeMap[K, V] ={
      val map: java.util.Map[Range[K], V] = rangeMap.asMapOfRanges()
      val rangesBuilder: ImmutableList.Builder[Range[K]] = new ImmutableList.Builder[Range[K]](map.size())
      val valuesBuilder: ImmutableList.Builder[V] = new ImmutableList.Builder[V](map.size())
      for (entry: Entry[Range[K], V] <- JavaConversions.asScalaSet(map.entrySet())) {
        rangesBuilder.add(entry.getKey())
        valuesBuilder.add(entry.getValue())
      }
      return new SerializableImmutableRangeMap[K, V](rangesBuilder.build(), valuesBuilder.build())
    }
  }

def builder[K <: Comparable[_], V](): SerializableBuilder[K, V] = {
    new SerializableBuilder[K, V]()
  }
}

class SerializableImmutableRangeMap[K <: Comparable[_], V](ranges: ImmutableList[Range[K]], values: ImmutableList[V]) extends ImmutableRangeMap[K, V](ranges, values) with Serializable {
  def this() {
    this(ImmutableList.of(), ImmutableList.of())
  }
}

And the stack trace:

java.io.InvalidClassException: com.google.common.collect.SerializableImmutableRangeMap; no valid constructor
        at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:150)
        at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:768)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1775)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1993)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1993)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1993)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1993)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1707)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1345)
        at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1993)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1993)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1993)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
        at scala.collection.immutable.$colon$colon.readObject(List.scala:362)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1017)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1896)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1993)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1993)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
        at org.apache.spark.serializer.JavaDeserializationStream.readObject(JavaSerializer.scala:68)
        at org.apache.spark.serializer.JavaSerializerInstance.deserialize(JavaSerializer.scala:94)
        at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:60)
        at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:41)
        at org.apache.spark.scheduler.Task.run(Task.scala:64)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:203)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)



from Newest questions tagged java - Stack Overflow http://ift.tt/1LytleI
via IFTTT

Maven property visibilily to plugins

There appear to be some subtleties regarding properties in Maven that trip me up. I'm trying to use the jboss-as-maven-plugin, in particular mvn jboss-as:deploy.

Running this first invokes all phases up to package. At validate, I have the buildnumber maven plugin config'd to create the build number. It runs successfully:

[INFO] Storing buildNumber: 25-Aug-2015-5 at timestamp: 1440522013153

At some later phase, this:

<finalName>${project.artifactId}-${project.version}-r${buildNumber}</finalName>

kicks in, apparently successfully, because the .ear I'm building is given the correct filename:

[INFO] Building jar: /home/johndoe/myproj/target/Myproj-1.2.3-SNAPSHOT-r25-Aug-2015-5.ear

Then, when the jboss-as-maven-plugin tries to pick up the file in order to deploy it, it apparently can't resolve the 'buildNumber' property, and complains:

[ERROR] Failed to execute goal org.jboss.as.plugins:jboss-as-maven-plugin:7.7.Final:deploy (default-cli) on project Quark: Error executing FORCE_DEPLOY: /home/johndoe/myproj/target/Myproj-1.2.3-SNAPSHOT-r${buildNumber}.ear (No such file or directory) -> [Help 1]

Apparently the plugin managed to resolve the other parts that make up the filename, ${project.artifactId} and ${project.version}, but fails to do the same with ${buildNumber} .

Do I need to put something into the pom that tells the buildnumber plugin to 'export' that property, or similar?



from Newest questions tagged java - Stack Overflow http://ift.tt/1WQDxCP
via IFTTT

Java: How to sum all numbers in loop?

How do I sum all the numbers that the loop prints out? (x)

public static void main(String [] args) {

for (int i = 0; i < 500; i++) {
        int x = 3*i + 5*i;
        if (x < 1000) {
            System.out.println(x);
        }
    }



from Newest questions tagged java - Stack Overflow http://ift.tt/1WQDxmz
via IFTTT

Groupby time stamp in java, translate from python code?

[Demo-Site, 10.227.147.98, CustomerDetailsByRegion, 17:05:15, 2015-08-19]
[Demo-Site, 10.152.114.217, TableauCustomers, 08:03:32, 2015-08-20]
[Demo-Site, 10.208.213.179, TableauCustomers, 10:14:55, 2015-08-20]
[poc, 10.237.232.199, App, 11:06:36, 2015-08-20]
[poc, 10.237.232.199, blah, 11:07:18, 2015-08-20]

Is there a way in java to get the site name aggregated by time interval of 30 mins?

Output should be

[[Demo-site, 17-1730, 1, 2015-08-19], 
[Demo-site, 8-830, 1, 2015-08-20],
[Demo-site, 10-1030, 1, 2015-08-20], 
[Poc, 11-11:30, 2, 2015-08-20]]

I did it in python using a groupby and itemgetter, I am new to java so not too sure. If it helps here is the python code.

def join_array(data):
    out = []
    for _, v in groupby(sorted(data, key=itemgetter(0, 3)),key=itemgetter(0,3)):
        v = list(v)    
        ips = ", ".join([sub[1] for sub in v])
        tmes = ", ".join([sub[2] for sub in v])
        out.append([v[0][0], ips, tmes, v[0][-1]])
    return out



from Newest questions tagged java - Stack Overflow http://ift.tt/1WQDzur
via IFTTT

create array list of instances of annotated classes

I have a problem with creating an arraylist of instances. I got a Set<Class<?>> and then I check if they implement a specific interface. If they do I want to add an instance of this class to an arraylist of the specific interface.

This is my code:

ArrayList<MyInterface> list = new ArrayList<>();
for (Class clazz : annotatedClasses) {
    if(MyInterface.class.isAssignableFrom(clazz)) {
        Object instance = clazz.getConstructor().newInstance();
        list.add(object); //ERROR: Object != MyInterface
    }
}

How can I solve this?



from Newest questions tagged java - Stack Overflow http://ift.tt/1fE8MPK
via IFTTT

Print HW.java coded in Windows-1250 to windows console

I have an albanian HelloWorld.java :

package com.getjavajob.training.algo05.lesson02;

public class HelloWorldAlbanian {
    public static void main(String[] args) {
        System.out.println("Përshëndetje botë!");
    }
}

File encoded in ISO-8859-1, and I need to print it in windows console in ISO-8859-1 or in Windows-1250. "ë"-symbol codes in ISO-8859-1 and Windolws-1250 are not different.

windows console codes:

Windows-1250  1250
ISO-8859-1    28591

Here is my console out:

C:\>chcp 28591
Текущая кодовая страница: 28591

C:\>"C:\Program Files\Java\jdk1.7.0_79\bin\javac" -cp . -d . -encoding ISO-8859-
1 "C:\HelloWorldAlbanian.java"

C:\>"C:\Program Files\Java\jdk1.7.0_79\bin\java" -cp . -DconsoleEncoding=ISO-885
9-1 "com/getjavajob/training/algo05/lesson02/HelloWorldAlbanian"
P?rsh?ndetje bot?!

How to print "ë"?

P.S. I must not make some changes in file.



from Newest questions tagged java - Stack Overflow http://ift.tt/1WQDxmp
via IFTTT

a code to output largest number from array

I wrote this basic code, confident it was going to work. I see think it should work but for some reason it hasn't lol I was wondering if you guys can tell me what i did wrong. This is just a code to output the largest amount in an array. I have already created the array.

    int index = array.length -1;
    int i, n, largest;

    largest = array[0];


    for(i=0;i < index;i++)
        if(array[i] > array[i + 1])
            largest = array[i];
               System.out.println(array[i]);

Any help on what i did wrong?



from Newest questions tagged java - Stack Overflow http://ift.tt/1fE8KYe
via IFTTT

Is this Hashset usage thread safe?

I have a static HashMap which will cache objects identifed by unique integers; it will be accessed from multiple threads. I will have multiple instances of the type HashmapUser running in different threads, each of which will want to utilize the same HashMap (which is why it's static).

Generally, the HashmapUsers will be retrieving from the HashMap. Though if it is empty, it needs to be populated from a Database. Also, in some cases the HashMap will be cleared because it needs the data has change and it needs to be repopulated.

So, I just make all interactions with the Map syncrhonized. But I'm not positive that this is safe, smart, or that it works for a static variable.

Is the below implementation of this thread safe? Any suggestions to simplify or otherwise improve it?

public class HashmapUser {

  private static HashMap<Integer, AType> theMap = new HashSet<>();

  public HashmapUser() {
    //....
  }

  public void performTask(boolean needsRefresh, Integer id) {
    //....

    AType x = getAtype(needsRefresh, id);

    //....
  }

  private synchronized AType getAtype(boolean needsRefresh, Integer id) {
    if (needsRefresh) {
      theMap.clear();
    }

    if (theMap.size() == 0) {
      // populate the set
    }

    return theMap.get(id);
  }
}



from Newest questions tagged java - Stack Overflow http://ift.tt/1fE8MPF
via IFTTT

How to retrieve and modify HTML content from WebView with Http Post

i am developing an android app that shows some part of a HTML page.for the first step i use this code provided in question How to retrieve HTML content from WebView.

  • Full html picture

part 1

  • That part i want to show

    part 2

    /* An instance of this class will be registered as a JavaScript interface */
    class MyJavaScriptInterface
    {
        @SuppressWarnings("unused")
        public void processHTML(String html)
        {
            // process the html as needed by the app
        }
    }
    
    final WebView browser = (WebView)findViewById(R.id.browser);
    /* JavaScript must be enabled if you want it to work, obviously */
    browser.getSettings().setJavaScriptEnabled(true);
    
    /* Register a new JavaScript interface called HTMLOUT */
    browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
    
    /* WebViewClient must be set BEFORE calling loadUrl! */
    browser.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url)
        {
            /* This call inject JavaScript into the page which just finished loading. */
            browser.loadUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
        }
    });
    
    /* load a web page */
    browser.loadUrl("http://ift.tt/1Id3G3G"); 
    
    

but when a user click on a button in second picture a HTTP post method will be called and this will be the result HTML
enter image description here

my question is how retrieve and modify the Post Result Html before showing to user? and show something like this enter image description here



from Newest questions tagged java - Stack Overflow http://ift.tt/1LyqdzH
via IFTTT

NullPointerException when trying to use method from custom JPanel

I am trying to make a GUI for my game I created a while back, and I am running into a slight issue while running it.

I want to have the output print to a JTextField in an extended JPanel. However, when I run it, it comes up with this error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Classic.print(Classic.java:509)
    at Classic.play(Classic.java:43)
    at Karma.actionPerformed(Karma.java:134)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Here is the applicable code:

(I will skip Karma.java:134 since this is just the play button.)

Classic.java

public class Classic extends Game {
    private static JFrame gui;
    private static GUIClassic newContentPane;
    ...
    public void play() {
        invokeLater(Classic::startGUI);
        //The next line is "Classic.java:43
        //length, difficulty, and log are all strings that were initialized when the game was instantiated
        print("Selected Options:\nLength: " + length + "\nDifficulty: " + difficulty + "\nOutput Log? " + log + "\n");
        ...
    }
    private static void startGUI() {
        gui = new JFrame("Karma :: Classic Mode");
        gui.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        newContentPane = new GUIClassic();
        newContentPane.setOpaque(true);
        gui.setContentPane(newContentPane);
        gui.pack();
        gui.setVisible(true);
    }
    private static void print(String text) {
        newContentPane.appendOutput(text);
    }

GUIClassic.java (The class used for the content pane)

public class GUIClassic extends JPanel implements ActionListener {
    private JTextArea output;
    ...
    public void appendOutput(String addition) {
        output.append(addition + "\n");
    }

Interestingly enough, the GUI does pop up and stay up after the exception occurs. It just doesn't print the output to the JTextArea and gets stuck.

If you need more code for context, let me know please and I will add it.



from Newest questions tagged java - Stack Overflow http://ift.tt/1WQDx61
via IFTTT

Error in implementation of merge sort in java?

I made the following code in java for merge sort but in the output I'm getting output: -
0 0 0 0 0 0
I have tried debugging it for the past two hours. Where am I going wrong here?

public class MergeSort {

public static void Mergesort(int[] a){
int n=a.length;
if(n<2)
    return;
int mid=n/2;
int[] left=new int[mid];
int[] right=new int[n-mid];
for(int i=0;i<mid-1;i++)
    {left[i]=a[i];}
for(int i=mid;i<n-1;i++)
    {right[i-mid]=a[i];}
Mergesort(left);
Mergesort(right);
merge(left,right,a);
}

public static void merge(int[]x,int[] y,int[] z){
int p=x.length;
int q=y.length;
int i=0;int j=0;int k=0;
while(i<p&&j<q){
    if(x[i]<=y[j])
        z[k++]=x[i++];

    else
        z[k++]=y[j++];      
}
while(i<p) z[k++]=x[i++];   
while(j<q) z[k++]=y[j++];


}



public static void main(String[] args) {

    int[] arr={9,10,8,5,1,0};
    Mergesort(arr);
    for(int l=0;l<arr.length;l++)
    {       System.out.println(arr[l]);}


}

}

Output is 0 0 0 0 0 0 I think there is something wrong with the partitioning !



from Newest questions tagged java - Stack Overflow http://ift.tt/1WQDx5X
via IFTTT

Add UTF8 Filter for Servlet

Hi I used Initializer and it worked well.

public class Initializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext)
            throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebAppConfig.class);
        servletContext.addListener(new ContextLoaderListener(ctx));

        ctx.setServletContext(servletContext);


        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);

        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("encodingFilter",
                new CharacterEncodingFilter());
        filterRegistration.setInitParameter("encoding", "UTF-8");
        filterRegistration.setInitParameter("forceEncoding", "true");
        filterRegistration.addMappingForUrlPatterns(null,true,"/*");
    }

Then I changed it to another:

public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {


    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{WebAppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{WebAppConfig.class};
    }
}

But I can't add to it this method:

public void onStartup(ServletContext servletContext) {
        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("encodingFilter",
                new CharacterEncodingFilter());
        filterRegistration.setInitParameter("encoding", "UTF-8");
        filterRegistration.setInitParameter("forceEncoding", "true");
        filterRegistration.addMappingForUrlPatterns(null, true, "/*");
    }

Because the application falls. What am I doing wrong? How to add this filter to a new Initializer to force it work? Thank you.



from Newest questions tagged java - Stack Overflow http://ift.tt/1Id1dWW
via IFTTT

Java regular expression two digit number of group

I test how Java will interprets (one)(one)(one)(one)(one)(one)(one)(one)(one)(one)(two)\11 - it will try to match first group and the literal "1" at the end or it will try to match 11-th group. So it trying to match 11-th group if there is 11-th. But how can I strongly defined this behaviour ? I mean how should I tell that I want to match 11 group always (so when there is no 11 group there is no match). I don't know if this is practicalquestion, I'm just curious. Thanks in advance.



from Newest questions tagged java - Stack Overflow http://ift.tt/1LynpTf
via IFTTT

Accessing a Scala method "default()" from Java code

It appears that I'm unable to access a Scala method default() from Java code.

scala> class A {
     | def default = 3
     | }
defined class A

scala> :javap -public A
Compiled from "<console>"
public class A {
  public int default();
  public A();
}

Trying to access default() in Java code yields all kind of syntax errors. Is there a workaround like Scala's backticks to handle Java keywords?



from Newest questions tagged java - Stack Overflow http://ift.tt/1LynpT7
via IFTTT

ImageView centerCrop overflows ImageView bounds?

I have the following layout:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4"
    android:layout_gravity="top|center"
    android:background="@drawable/rounded_corner"
    android:layout_marginTop="50dp"
    android:layout_width="250dp"
    android:layout_height="350dp">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="270dp"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"
        android:src="@drawable/card_image"
        android:layout_gravity="top"
        android:layout_marginTop="0dp"/>

</FrameLayout>

The image should fill the image with its rectangle and scale it keeping its aspect ratio. It works fine when I do not move the view:

enter image description here

But, when I move the view, the image is drawn outside of its bounds:

enter image description here

I am using this library to move the card.

How do I prevent that the ImageView draws its image outside its bounds?



from Newest questions tagged java - Stack Overflow http://ift.tt/1Id1edJ
via IFTTT

Custom annotation on method argument is not being executed

I have implemented a custom annotation @Password to perform validation on an argument of my method setPassword(). The annotation is defined like this:

// Password.java
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import javax.validation.*;

@Target({METHOD, FIELD, PARAMETER, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordValidator.class)
@Documented
public @interface Password {
    String message() default PasswordValidator.message;
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

And the current implementation of the validator is this:

// PasswordValidator.java
package utils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PasswordValidator implements ConstraintValidator<Password, String> {

    /* Default error message */
    final static public String message = "error.invalid.password";

    /**
    * Validator init
    * Can be used to initialize the validation based on parameters
    * passed to the annotation.
    */
    public void initialize(Password constraintAnnotation) {
        System.out.println("in initialize()");
    }

    public boolean isValid(String string, ConstraintValidatorContext constraintValidatorContext) {
        System.out.println("in isValid()");
        return false;
    }
}

Note that in the current implementation isValid() always returns false. The reason will be apparent shortly.

My usage of the validator is in a class User. For brevity I won't post the whole source here, but the relevant parts are:

package models;

import utils.Password;
// other imports omitted


@Entity
@Table(name = "users", schema="public")
public class User {

    @Required
    private String password;

    ...

    public void setPassword(@Password String clearPassword) {
        try {
            this.password = HashHelper.createPassword(clearPassword);
        } catch (AppException e) {
            e.printStackTrace();
        }
    }

    ...
}

The basic idea is that I use the User class to store a hashed password for a user, but before setting the hashed password, I (would like to) run validation on the unhashed password (i.e. clearPassword).

The problem I am having is that this validation is not taking place. In the current implementation, it should (according to my understanding) always throw a ConstraintViolationException because isValid() always returns false, but this is not the case.

I have checked that the annotation is being attached to the method argument by calling (in another part of the application) something along the lines of:

Method method = user.getClass().getMethod("setPassword", new Class[] { String.class });
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
System.out.println(method.getName() + ": " + parameterAnnotations[0][0]);

which produces the following output:

setPassword:@utils.Password(message=error.invalid.password, payload=[], groups=[])

So this tells me the annotation is being applied to the method argument. But I can't understand why I'm not getting the ConstraintViolationException when I actually call the method. I also never see the output "in initialize()" or "in isValid()" that I added to these methods as a check to see if they're being fired.

As another test, I also added the @Password annotation to the member variable password in User.class. This causes the ConstraintViolationException to be thrown as expected, e.g. when I try to persist a User object.

Can anyone shed light as to why the annotation on the method argument is not working properly? Thanks in advance!



from Newest questions tagged java - Stack Overflow http://ift.tt/1LynrdF
via IFTTT

Dataproviders and Asserts

When using DataProviders, on TestNG, my test method has asserts that will fail since the data passed in navigates to a different url. Is there a way to work around this, i.e. a way for the data to only be injected to certain/specific asserts?


Instead of testing one scenario with different data, I am instead testing multiple scenarios with different data which is where my conflict arises.


@DataProvider(name = "VINNumbers")
public String[][] VINNumbers() {
    return new String[][] {
            {"2T1BU4ECC834670"},
            {"1GKS2JKJR543989"},
            {"2FTDF0820A04457"}
    };
}

@Test(dataProvider = "VINNumbers")
public void shouldNavigateToCorrespondingVinEnteredIn(String VIN) {

    driver.get(findYourCarPage.getURL() + VIN);
    Assert.assertTrue(reactSRP.dealerListingMSRPIsDisplayed());
}

The assert test whether or not the page has an MSRP displayed, but not all dataproviders will have an MSRP displayed so it will fail. The only dataprovider that has it is the first array. Is there a way for dataproviders to be called to specific asserts?



from Newest questions tagged java - Stack Overflow http://ift.tt/1Id1edz
via IFTTT

Is there a way to write a part from memory to a file

I am trying to develop some code that will probably run multiple weeks on a HPC environment. The problem is that chances are rather small that I'll be able to monopolise a cluster to run my program as a whole and therefore I am thinking about ways to store my progress into some file system.

As I was thinking, I wondered whether there wouldn't be a way to take some snapshot from the memory my application is using and store that in some file. I have this feeling this should be the simplest way to just stop processing and start again whenever you want, because you could just load that file into memory and continue working as if nothing happened.

I started searching around on the internet trying to find something about this, but as I don't really know the term (I suppose there is a term) for this and I didn't get any further than billions of ways to write objects to files as efficient as possible. I didn't get any further, because I find it hard to understand what those writers are really doing. I don't believe though that those writers and streams perform something as I described above... (please correct me if I mistake!)

My question thus could be formulated as follows:
Is there any way to do something like this in java? If not, does there exist anything that approaches the idea or performance of what I tried to describe?



from Newest questions tagged java - Stack Overflow http://ift.tt/1LynqXh
via IFTTT

Android file upload, package or native code

I have looked and searched, but I can't find a good answer. I need to upload files to a server. I can't seem to find a good package or tutorial that helps me to do this. I know how to do the upload on the server end (PHP), but not how to do this with Android.



from Newest questions tagged java - Stack Overflow http://ift.tt/1JhpEEz
via IFTTT

How the line "Outter.this.x" works?

class Outter
{
    int x=20;
    class Inner
    {    int x=30;
        void show()
        {
            System.out.println(Outter.this.x);
        }
     }
      public static void main(String... s)
      {

       Outter k=new Outter();
       Outter.Inner m=k.new Inner();
       m.show();
      }
}



from Newest questions tagged java - Stack Overflow http://ift.tt/1IcYmNI
via IFTTT

In Android, which Java version should I compile the code for, and how to set it for Ant?

When building an Android application, which Java version should I compile the code for? I'd guess this depends on the "minSdkVersion"? And if so, where can I find the required Java version for each "minSdkVersion"?

And once I determine the Java version I want, how do I set it? I build my project using Ant (from the command line). Currently it seems to always use 1.5 because the "build.xml" file imports "${sdk.dir}/tools/ant/build.xml" which contains:

<property name="java.target" value="1.5" />
<property name="java.source" value="1.5" />
...

<javac ... source="${java.source}" target="${java.target}" ... >

Should I change it there? Is there a way to set it per project?

And is there a way to set the Java version if I build using Eclipse?



from Newest questions tagged java - Stack Overflow http://ift.tt/1EgyTrz
via IFTTT

Why it is null when I'm calling a get method of one class from another class using reference i.e it prints out null

I want to execute the getName() which contains the return method of name but it is printing out "null"

public void getAllVisits() 
   {
       Visit v = new Visit();
       for (int i = 0; i < myVisits.size(); i++)
       {
           System.out.println(v.getName());
           System.out.println(v.getAmount());
           System.out.println(v.getDate());
       }
   }



from Newest questions tagged java - Stack Overflow http://ift.tt/1IcYmxi
via IFTTT

Generating a triangle in JAVA

This is the triangle model to be generated

Using nested loops, the following pattern is to be generated for a user input value.

public static void main(String[] args) 
    {
        int integer_input;
        Scanner input= new Scanner(System.in); 
        System.out.println("Enter a number: ");
        integer_input = input.nextInt();

        /*Nested Loops here.. */
    }



from Newest questions tagged java - Stack Overflow http://ift.tt/1LykNod
via IFTTT

Converting a binary value stored as a string ("10011") to a byte representation (0b00010011) in Java?

Odd question, but a framework I was provided contains a hash table where the return values are Strings. The strings are representative of binary values I need to work with. For example, I put in the key "F", and it will return a string with 0s and 1s, such as "10011". I need to work with that number, 10011, as binary, and eventually store it as binary. How do I go about turning "10011" into a byte 00010011?



from Newest questions tagged java - Stack Overflow http://ift.tt/1IcYmgR
via IFTTT

How do you implement one to many relationships in Clean Architecture

I'm having problems using Clean Architecture. For those of you who have read Fernando Cejas' blog post, my question is based on it, and his code.

His example project has only one Domain Object a User. And everything is clear with POJOs. Where I am having a problem is, let's say that the user has books. A one to many relationship. How would you deal with this in Clean Architecture?

Just like him I have a few layers, so 3 classes per Domain Object (User, UserModel, UserEntity) and a repository per Domain Object (UserDataRepository). Our new example would also have Book, BookModel, BookEntity and BookDataRepository.

I also have use case classes with CRUD variations.

The problem for me is at the UI/Presenter level. At this point in the program I have a UserModel object AND a list of BookModels. I do not have userModel.getBooks(). I do not have userModel.save() (which would save all the book changes too).

To accentuate the problem, to make this analogy look even more like my actual use case, I also have the list of all the pages in the books! :) So when I save the User, I want to save to books, and all the pages for every book that might have been modified.

How would I go about this?

Second BONUS question : In my real world problem, I have classes that derive from a base class. To use the above analogy: LeftPage and RightPage would derive from PageBase. A Book has a list. However LeftPage and RightPage both have their separate repositories, separate use cases, etc. (But this doesn't work) How do I save a list ?? Do I have to make a separate use case SavePages which would have a :

if (pages.elementAt(i) instanceof LeftPage) { SaveLeftPage saveLeft = new..... } else { SaveRightPage saveRight = new..... }

I don't think that I can use Polymorphism because in all the documentation that I have seen, the Models don't know of the use cases.

I hope that you can help, thank you very much for your time :)

-MIke



from Newest questions tagged java - Stack Overflow http://ift.tt/1EgySUz
via IFTTT