mercredi 1 juillet 2015

Java Rotate an Array

I have the following problem to test:

Rotate an array of n elements to the right by k steps. For instance, with n = 5 and k = 2, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. How many different ways do you know to solve this problem?

My solution in intermediate array: With Space is O(n) and time is O(n), I can create a new array and then copy elements to the new array. Then change the original array by using System.arraycopy().

public void rotate(int[] nums, int k) {
    if(k > nums.length) 
        k=k%nums.length;

    int[] result = new int[nums.length];

    for(int i=0; i < k; i++){
        result[i] = nums[nums.length-k+i];
    }

    int j=0;
    for(int i=k; i<nums.length; i++){
        result[i] = nums[j];
        j++;
    }

    System.arraycopy( result, 0, nums, 0, nums.length );
}

But there is better way we can do it with bubble rotate(like bubble sort) in O(1) space ?

Android Media Player Stuttering with CountDownTimer

I'm trying to make an app to teach someone how to count music. The media player is initialize to a 30 second sound clip of a persistent A note. I am using a countdown timer to tell my media player when to pause and play. The code below causes the first and last second of audio to stutter.

MediaPlayer myMediaPlayer = MediaPlayer.create(MusicCounting.this, R.raw.a_note);
CountDownTimer time = new CountDownTimer(4000,500) {
    @Override
    public void onTick(long millisUntilFinished) {
        if(myMediaPlayer.isPlaying()) {
            myMediaPlayer.pause();
        } else {
            myMediaPlayer.start();
        }
    }

    @Override
    public void onFinish() {
        myMediaPlayer.pause();
        myMediaPlayer.seekTo(0);
    }
};

time.start();

This code is for quarter notes and my eighth notes code looks identical except the second parameter for the countdown timer is 250. Any suggestions would be greatly appreciated. Thanks :)

mvn jetty:run not reflecting changes when run inside docker

I have a simple Tic-tac-toe Java web app http://ift.tt/1CIOMRA It is a Maven project. It uses Jetty to run the web app by doing mvn jetty:run While it is running locally, I can easily modify a JavaScript file and see the changes immediately when I refresh the browser. But, when I run it via Docker where I am mounting the source directory, similar change doesn't get reflected.

Note: I am mounting the source directory in docker-compose.yml file. And I see the change reflected in the file but jetty doesn't pick up the change.

Please Note: It needs JDK 7

To test on localhost:

  mvn clean install
  mvn jetty:run
  Open localhost:8080 to see the app.
  Add an alert(1); in `doInit` function in this JavaScript http://ift.tt/1C8q2aX
  Refresh the browser and you'll see an alert dialog

To test on Docker (using Docker compose):

    docker-compose up
    Add an alert(1); in `doInit` function in [this JavaScript][3]    
    ...Refresh browser, but the change is not reflected

What am I missing?

JNI: Bitmap from unsigned char* always null

I would like to pass an image (via jni) from C++ to an android application. I am starting from an unsigned char* array. This array is not corrupted whatsoever; I am even able to save it into a ppm file and display it properly on my laptop.

Then, I convert it to a jByteArray by using this function:

jbyteArray imgByte=as_byte_array(env,imgRaw,img.getRawImageSize());
...
jbyteArray as_byte_array(JNIEnv *env, unsigned char* buf, int len) {
    jbyteArray array = env->NewByteArray (len);
    env->SetByteArrayRegion (array, 0, len, reinterpret_cast<jbyte*>(buf));
    return array;
}

Afterward, I send this jByteArray to the java side. This variable has been properly populated, as I can see by printing its hex values on LogCat:

07-01 18:02:45.941    7017-8238/com.myapp.myapp W/C++ side﹕  798a95798b9677889371838d6b7d8664757e5d6e7860717b5e...
07-01 18:02:46.941    7017-8238/com.myapp.myapp W/Java side﹕ 798a95798b9677889371838d6b7d8664757e5d6e7860717b5e...

The final step would be to show it on an ImageView. To this end, I do the following code (taken from another question on SO):

public void setImageViewWithByteArray(final ImageView view, byte[] data) {
    final Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (bitmap==null) {
                Log.e(TAG,"Bitmap is NULL!");
                view.setImageResource(R.drawable.abc_btn_radio_material);
            }
            else {
                view.setImageBitmap(bitmap);
            }
        }
    });
}

but the bitmap variable is always null. What am I doing wrong? Is there a way to debug decodeByteArray?

Decrypt with Rijndael from c# to Java

I have this source code in c# and I need to translate this to Java:

    private byte[] DecryptAES(byte[] encrypted, byte[] key, byte[] IV)
    {
        RijndaelManaged myRijndael = new RijndaelManaged();
        byte[] fromEncrypt;
        //byte[] encrypted = Encoding.Default.GetBytes(texto);

        //Get a decryptor that uses the same key and IV as the encryptor.
        ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);

        //Now decrypt the previously encrypted message using the decryptor
        // obtained in the above step.
        MemoryStream msDecrypt = new MemoryStream(encrypted);
        CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

        fromEncrypt = new byte[encrypted.Length];

        //Read the data out of the crypto stream.
        csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

        //Convert the byte array back into a string.
        //roundtrip = Encoding.Default.GetString(fromEncrypt);

        return fromEncrypt;
    }

Could somebody help me please?

How to convert from Matrix to double Java (Java)

I have an object Matrix, where I stored a double[][] array. I want to return the values of the method Matrix.inverse().

How can I pass values from a Matrix object to a double[][] array?

double K[][] = {{1,5,3,4} , {1,10,4,3} , {1,40,232,4} , {32,434,23,5}};
Matrix GetInverse = new Matrix(K);

double returnValues[][] = GetInverse; // ---?----

The sum of all the multiples of 3 or 5 below N. Project Euler

So I'm doing the Project Euler challenge and I'm stuck at the first one, I'm using Java as pl. for example if we have to list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. We have to find the sum of all the multiples of 3 or 5 below N.

My code works on Eclipse but I get "Nice try, but you did not pass this test case." with stdout : No Response and when I submit the code I get Wrong Answer on all test cases, here's the code:

public class Solution {
    public static void main(String[] args) {
        for (int j = 0; j < args.length; j++) {
            int N = Integer.parseInt(args[j]);
            if (Somme(N) != 0) {
                System.out.println(Somme(N));
            }
        }
    }

    public static int Somme(int Nn) {
        int s = 0;
        for (int i = 0; i < Nn; i++) {
            if (((i % 3) == 0) || ((i % 5) == 0)
                && !(((i % 3) == 0) && ((i % 5) == 0))) {
                s = s + i;
            }
        }
        return (s);
    }
}

UPDATE : So, I looked more and it turns out that this is how it's supposed to be done:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution{
public static void main(String[] args) throws IOException {


    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String line = br.readLine();
    int Nbr = Integer.parseInt(line);


        for(int j=0; j<Nbr;j++)
        {
            BufferedReader br2 = new BufferedReader(new   InputStreamReader(System.in));
            String line2 = br2.readLine();
            String[] numbers = new String[Nbr];
            numbers[j]= line2;
            System.out.println(Somme(Long.parseLong(numbers[j])));
        }

        }


public static long Somme(long Nn) {
    long s = 0;
    for (int i = 0; i < Nn; i++) {
        if (((i % 3) == 0) || ((i % 5) == 0)) {
            s = s + i;
        }
    }
    return (s);
}

}

Now the only problem left is that I want it to be able to read ALL the numbers THEN display the sum, for now it reads one number and display the sum right after it, any ideas?

Grid Recursion Not Functioning

I'm trying to solve a problem on Project Euler (Project 16) using grid recursion and it isn't working out so well - I'm just ending up with what seems like an infinite loop. The goal is to count how many routes you can take to get from the top left of a 20x20 grid to the bottom right of the grid, so I start from the origin and placed a number in myGrid[20][20] that indicates it's at the bottom right corner.

private static int[][] myGrid;

public static int numRoutes(int x, int y){
    if (x < 0 || x >= 20 || y < 0 || y>= 20){
        return 0;
    }
    if (myGrid[x][y] == 1){
        return 1;
    }
    int count = 0;
    count += numRoutes(x+1, y);
    count += numRoutes(x, y+1);
    return count;
}

public static void main (String args[]) throws Exception{
    myGrid = new int[21][21];
    for (int i = 0; i < 21; i++){
        Arrays.fill(myGrid[i], 0);
    }
    myGrid[20][20] = 1;
    int num = numRoutes(0,0);
    System.out.println(num);
}

This comprises most of my recursion, and I think that I have all of the appropriate base cases. Any thoughts on what's going wrong?

Reusing part of Stream mapping and filtering to compose two different results

I'd like to know if there is a good way of reusing a common stream operation that varies in the end for different outputs. The example bellow is exactly what I'm trying to compact into a one-step operation:

public static DepartmentInfo extractDepartmentInfo(BaselinePolicy resource) throws ResourceProcessorError {
    Function<Exception, Exception> rpe = e -> new ResourceProcessorError(e.getMessage());
    List<String> parents = 
            Objects.requireNonNull(
                Exceptions.trying(
                    () -> Arrays.asList(Exceptions.dangerous(resource::getParentIds).expecting(CMException.class).throwing(rpe))
                                .stream()
                                .map(cId -> Exceptions.dangerous(cId, resource.getCMServer()::getPolicy).expecting(CMException.class).throwing(rpe))
                                .filter(policy -> PagePolicy.class.isAssignableFrom(policy.getClass()))
                                .map(PagePolicy.class::cast)
                                .filter(page -> Exceptions.dangerous(page,
                                                                     p -> Boolean.valueOf(p.getComponentNotNull(ComponentConstants.POLOPOLY_CLIENT, 
                                                                                                                ComponentConstants.IS_HOME_DEPARTMENT,
                                                                                                                Boolean.FALSE.toString())).booleanValue())
                                                          .expecting(CMException.class).throwing(rpe))
                                .map(page -> Exceptions.dangerous(page, p -> p.getExternalId().getExternalId()).expecting(CMException.class).throwing(rpe)), ResourceProcessorError.class)
                                .collect(Collectors.toList()));
    String externalId = parents.get(parents.size()-1).toString();
    List<String> list = 
        Objects.requireNonNull(
                Exceptions.trying(
                    () -> Arrays.asList(Exceptions.dangerous(resource::getParentIds).expecting(CMException.class).throwing(rpe))
                                .stream()
                                .map(cId -> Exceptions.dangerous(cId, resource.getCMServer()::getPolicy).expecting(CMException.class).throwing(rpe))
                                .filter(policy -> PagePolicy.class.isAssignableFrom(policy.getClass()))
                                .map(PagePolicy.class::cast)
                                .map(page -> 
                                    Exceptions.dangerous(page, 
                                            p -> p.getChildPolicy(PATH_SEGMENT) != null && 
                                                 StringUtils.hasLength(SingleValued.class.cast(p.getChildPolicy(PATH_SEGMENT)).getValue())? 
                                                 SingleValued.class.cast(p.getChildPolicy(PATH_SEGMENT)).getValue(): p.getName()).expecting(CMException.class).throwing(rpe))
                                .filter(val -> val != null && !val.isEmpty()), ResourceProcessorError.class)
                                .collect(Collectors.toList()));
    if(list.size() > 3) {
        list = list.subList(list.size() - 3, list.size()-1);
    }
    switch(list.size()) {
        case 0: {
            throw new ResourceProcessorError("br.com.oesp.XMLRender.error.noProduct");
        }
        case 1: {
            return DepartmentInfo.withProduct(list.get(0), externalId);
        }
        case 2: {
            return DepartmentInfo.withProduct(list.get(0), externalId).withDepartment(list.get(1));
        }
        default: {
            return DepartmentInfo.withProduct(list.get(0), externalId).withDepartment(list.get(1)).withSubDepartment(list.get(2));
        }
    }
}

Notice that the first step is repeated for both:

List<String> parents = 
        Objects.requireNonNull(
            Exceptions.trying(
                () -> Arrays.asList(Exceptions.dangerous(resource::getParentIds).expecting(CMException.class).throwing(rpe))
                            .stream()
                            .map(cId -> Exceptions.dangerous(cId, resource.getCMServer()::getPolicy).expecting(CMException.class).throwing(rpe))
                            .filter(policy -> PagePolicy.class.isAssignableFrom(policy.getClass()))
                            .map(PagePolicy.class::cast)

It's not only a problem for reading but specially because I'm redoing a heavy operation twice, meanwhile in a more imperative way I'd do it once.

Encoding HttpResponse UTF-8

I get HttpResponse from url by method:

public void getResponse(String url) {
    String response;
    String str;
    BufferedReader bf;
    GZIPInputStream gzip;
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        HttpGet httpGet = new HttpGet(url);

        httpResponse = httpClient.execute(httpGet);
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity, HTTP.UTF_8);

        System.out.println(response);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

but the response i got error like:

�P:�ˎ�#�I���!h����Ab���9�xQ�7۰=b��x<M����n�

I checked the content encoding of 'HttpEntity' is 'gzip'. So, Is there any suggestion to encode response to utf8?

Update: [SOLVED] I solved problem with method:

public void getResponse(String url) {
    String response;
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        HttpGet httpGet = new HttpGet(url);

        httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
            @Override
            public void process(final HttpResponse response,
               final HttpContext context) throws HttpException,
               IOException {
                    HttpEntity entity = response.getEntity();
                    Header encheader = entity.getContentEncoding();
                    if (encheader != null) {
                        HeaderElement[] codecs = encheader.getElements();
                        for (int i = 0; i < codecs.length; i++) {
                            if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                                response.setEntity(new GzipDecompressingEntity(entity));
                            return;
                            }
                        }
                    }
            }
        });

        httpResponse = httpClient.execute(httpGet);
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity, HTTP.UTF_8);

        System.out.println(response);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Attempting to intercept SSL handshake of Jersey client (using default HttpUrlConnection)

I am trying to intercept all SSL handshakes (so that I can get information on them as well as present visual information to users, much like the green lock in browsers) that happen through my Jersey client. Unfortunately it does not seem like Jersey is using my SSLSocketFactory implementation, because none of the createSocket methods are called. No errors occur, it is just that nothing gets logged. The code should be clear:

Invocation + Instantiation:

this.httpClient = getHttpsClient(new DefaultSSLContextProvider());
Invocation.Builder invBuilder = httpClient.target(API_URL_PRIVATE + API_VERSION_2 + "markets").request(MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.TEXT_HTML);
invBuilder.header("Content-Type", "application/x-www-form-urlencoded");
invBuilder.header("User-Agent", USER_AGENT);

Response response = invBuilder.get();
logger.debug("response: " + response);

httpClient:

public Client getHttpsClient(SSLContextProvider sslContextProvider) throws KeyStoreException
{
    ClientConfig config = new ClientConfig().connectorProvider(new HttpUrlConnectorProvider().connectionFactory(
            url ->
            {
                HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
                connection.setSSLSocketFactory(sslContextProvider.getSSLSocketFactory());
                return connection;
            }));

    return ClientBuilder.newBuilder()
            .sslContext(sslContextProvider.getSSLContext())
            .withConfig(config)
            .build();
}

DefaultSSLContextProvider:

public class DefaultSSLContextProvider implements SSLContextProvider
{
    private SSLContext sslContext;
    private ObservableSSLSocketFactory observableSSLSocketFactory;

    private static final Logger logger = LoggerFactory.getLogger(DefaultSSLContextProvider.class);

    public DefaultSSLContextProvider()
    {
        try
        {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
            sslContext = SSLContext.getInstance("SSL");
            KeyStore keyStore = getKeyStore();
            trustManagerFactory.init(keyStore);
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            observableSSLSocketFactory = new ObservableSSLSocketFactory(sslContext);
            HttpsURLConnection.setDefaultSSLSocketFactory(observableSSLSocketFactory);
            SSLContext.setDefault(sslContext);
        }
        catch (NoSuchAlgorithmException e)
        {
            throw new RuntimeException(e);
        }
        catch (KeyManagementException | KeyStoreException e)
        {
            logger.error("could not create DefaultSSLContextProvider", e);
            throw new IllegalStateException(e);
        }
    }

    @Override
    public SSLContext getSSLContext()
    {
        return sslContext;
    }

    @Override
    public SSLSocketFactory getSSLSocketFactory()
    {
        return observableSSLSocketFactory;
    }

    @Override
    public KeyStore getKeyStore()
    {
        // snip
    }
}

ObservableSSLSocketFactory:

/**
 * Based heavily on:
 * http://ift.tt/1C3j5HZ
 */
public class ObservableSSLSocketFactory extends SSLSocketFactory
{
    private final SSLContext sslContext;
    private final String[] preferredCipherSuites;
    private final String[] preferredProtocols;

    private static final Logger logger = LoggerFactory.getLogger(ObservableSSLSocketFactory.class);

    protected ObservableSSLSocketFactory(SSLContext sslContext)
    {
        logger.debug("CREATING OBSERVABLE SOCKET FACTORY!");
        this.sslContext = sslContext;
        preferredCipherSuites = getCiphers();
        preferredProtocols = getProtocols();
        logger.debug("Observable socket factory created");
        logger.debug("preferredCipherSuites: " + preferredCipherSuites);
        logger.debug("preferredProcotols: " + preferredProtocols);
    }

    @Override
    public String[] getDefaultCipherSuites()
    {
        return preferredCipherSuites;
    }

    @Override
    public String[] getSupportedCipherSuites()
    {
        return preferredCipherSuites;
    }

    public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException
    {
        logger.debug("creating ssl socket");
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(s, host, port, autoClose);

        sslSocket.addHandshakeCompletedListener(new HandshakeListener());
        sslSocket.setEnabledProtocols(preferredProtocols);
        sslSocket.setEnabledCipherSuites(preferredCipherSuites);

        return sslSocket;
    }

    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException
    {
        logger.debug("creating ssl socket");
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(address, port, localAddress, localPort);

        sslSocket.addHandshakeCompletedListener(new HandshakeListener());
        sslSocket.setEnabledProtocols(preferredProtocols);
        sslSocket.setEnabledCipherSuites(preferredCipherSuites);

        return sslSocket;
    }

    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException
    {
        logger.debug("creating ssl socket");
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        SSLSocket sslSocket = (SSLSocket)sslSocketFactory.createSocket(host, port, localHost, localPort);

        sslSocket.addHandshakeCompletedListener(new HandshakeListener());
        sslSocket.setEnabledProtocols(preferredProtocols);
        sslSocket.setEnabledCipherSuites(preferredCipherSuites);

        return sslSocket;
    }

    public Socket createSocket(InetAddress host, int port) throws IOException
    {
        logger.debug("creating ssl socket");
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        SSLSocket sslSocket = (SSLSocket)sslSocketFactory.createSocket(host, port);

        sslSocket.addHandshakeCompletedListener(new HandshakeListener());
        sslSocket.setEnabledProtocols(preferredProtocols);
        sslSocket.setEnabledCipherSuites(preferredCipherSuites);

        return sslSocket;
    }

    public Socket createSocket(String host, int port) throws IOException
    {
        logger.debug("creating ssl socket");
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        SSLSocket sslSocket = (SSLSocket)sslSocketFactory.createSocket(host, port);

        sslSocket.addHandshakeCompletedListener(new HandshakeListener());
        sslSocket.setEnabledProtocols(preferredProtocols);
        sslSocket.setEnabledCipherSuites(preferredCipherSuites);

        return sslSocket;
    }

    private String[] getProtocols()
    {
        // snip
    }

    private String[] getCiphers()
    {
        // snip
    }

    class HandshakeListener implements HandshakeCompletedListener
    {
        public HandshakeListener()
        {
            logger.debug("Created new HandshakeListener");
        }

        public void handshakeCompleted(HandshakeCompletedEvent e)
        {
            logger.debug("Handshake successful!");
            logger.debug("using cipher suite: " + e.getCipherSuite());
        }
    }

}

As I said, no exceptions or errors occur (and indeed the original request goes through with no problem (HTTP 200), however the only things that are logged are:

00:01:37.867 DEBUG [ObservableSSLSocketFactory] CREATING OBSERVABLE SOCKET FACTORY!
00:01:38.072 DEBUG [ObservableSSLSocketFactory] Observable socket factory created
00:01:38.073 DEBUG [ObservableSSLSocketFactory] preferredCipherSuites: [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
00:01:38.073 DEBUG [ObservableSSLSocketFactory] preferredProcotols: [TLSv1, TLSv1.1, TLSv1.2]
00:01:39.435 DEBUG [Exchange] response: InboundJaxrsResponse{context=ClientResponse{method=GET, uri=http://ift.tt/1kEo45v, status=200, reason=OK}}

Nothing from createSocket()'s or the HandshakeCompletedListener.

Any help would be greatly appreciated.

I added some additional log statements, and the situation is indeed strange. The Jersey client is in fact calling the HttpUrlConnectorProvider implementation, and in fact an instance of ObservableSSLSocketFactory is set on the connection, it appears that when the connect method is called on the HttpsURLConnection, it does not use the socket factory.

Converting netbeans java application with multiple classes into .exe

I have made a java application on netbeans. Ive tried converting it into .exe with the help of various softwares like exe4j and launch4j. But the problem is, these softwares take only 1 main class. My application has 3. Thus my application doesnt connect to the databsae !

How can I extract a .jar file from the IBM jdk?

I'm trying to obtain an IBM jdk .jar file (ibmjcefw.jar specifically) as it is a dependency that is failing in my openshift gear since our openshift on-premise installation doesn't use the IBM jdk. I have no idea where to find this single file, much less from where...

I tried downloading an IBM JRE archive from:

http://ift.tt/1JyrW73

as I thought I might find it inside but pretty new to all things java and couldn't even unzip the archive :-(

Any help / pointers would be greatly appreciated.

how to refresh the content of the jtable if you're using notepad to putting data in the jtable

table.repaint(); and tableModel.fireTableDataChanged(); doesn't work. I tried both of those function but the jtable wouldn't refresh. The notepad with more lines in it stays in the jTable when a lesser lined notepad is called.

I'm using BufferedReader and FileReader to read it from the notepad.

Is there anyway to refresh the table into its default then show the data from the notepad again? Thank you.

Why does a non-empty List throw a Null Pointer Exception?

I have an List array 'details'.

List<HistoryDetails> details

where HistoryDetails is an object containing strings.

When I check the size it gives me a positive value.

details.size()

But when I try to access an element it throws a null pointer exception.

details.get(0).getFirstElement();


Attempt to invoke virtual method 'java.lang.String com.HistoryDetails.getFirstElement()' on a null object reference

I am invoking the element at the very next line to where I check the size. Hence, nothing should be reset. What could be wrong?

How can I force a Python ScriptEngine to flush its cache of imported modules?

I am using a Python ScriptEngine in my Java application to execute a Python script that imports various other Python scripts. Once the main script successfully completes and the eval method returns, I set the engine object reference to null and call the garbage collector. Next I go and edit one of the scripts that was imported by the main script and save it. Next I run the method to execute the main Python script as before by creating a new ScriptEngine object and calling eval, but when the main script runs it does not pick up the changes to the imported script that I made. Obviously the imported scripts are being cached somewhere by something, maybe Jython? I do not want to call reload in the Python script. There must be a way to tell whatever is doing the caching to flush or clear itself. Anyone found a solution to this problem? I am using NetBeans 8.0.2, Java 1.8 update 45, and Jython 2.7 on Windows 7.

Does collect operation on Stream close the stream and underlying resources?

Does below code need to be wrapped in try-with-resources to make sure underlying file is closed?

`List<String> rows = Files.lines(inputFilePath).collect(Collectors.toList());`

How to convert a class object to Fragment class object in android?

I have a function switchContent which takes parameters as Fragment and string. I also have a class ProductListFragment. I want to pass a object of ProductlistFragment to the function switchContent. How can I do that ?

switchContent(pdtListFragment, ProductListFragment.ARG_ITEM_ID);

Here I am getting error:

The method switchContent(Fragment, String) in the type MainActivity is not applicable for the arguments (ProductListFragment, String)

The following is the code:

package com.example.sp;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class ProductListFragment extends Fragment implements
OnItemClickListener, OnItemLongClickListener{

    public static final String ARG_ITEM_ID = "product_list";

      Activity activity;
      ListView productListView;
      List<Product> products;
      ProductListAdapter productListAdapter;
      SharedPreference sharedPreference;

      @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            activity = getActivity();
            sharedPreference = new SharedPreference();
        }


      @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_product_list, container,
                    false);
            findViewsById(view);

            setProducts();

            productListAdapter = new ProductListAdapter(activity, products);
            productListView.setAdapter(productListAdapter);
            productListView.setOnItemClickListener(this);
            productListView.setOnItemLongClickListener(this);
            return view;
        }

      private void setProducts() {

            Product product1 = new Product(1, "Dell XPS", "Dell XPS Laptop", 60000);
            Product product2 = new Product(2, "HP Pavilion G6-2014TX",
                    "HP Pavilion G6-2014TX Laptop", 50000);
            Product product3 = new Product(3, "ProBook HP 4540",
                    "ProBook HP 4540 Laptop", 45000);
            Product product4 = new Product(4, "HP Envy 4-1025TX",
                    "HP Envy 4-1025TX Laptop", 46000);
            Product product5 = new Product(5, "Dell Inspiron",
                    "Dell Inspiron Laptop", 48000);
            Product product6 = new Product(6, "Dell Vostro", "Dell Vostro Laptop",
                    50000);
            Product product7 = new Product(7, "IdeaPad Z Series",
                    "Lenovo IdeaPad Z Series Laptop", 40000);
            Product product8 = new Product(8, "ThinkPad X Series",
                    "Lenovo ThinkPad X Series Laptop", 38000);
            Product product9 = new Product(9, "VAIO S Series",
                    "Sony VAIO S Series Laptop", 39000);
            Product product10 = new Product(10, "Series 5",
                    "Samsung Series 5 Laptop", 50000);

            products = new ArrayList<Product>();
            products.add(product1);
            products.add(product2);
            products.add(product3);
            products.add(product4);
            products.add(product5);
            products.add(product6);
            products.add(product7);
            products.add(product8);
            products.add(product9);
            products.add(product10);
        }

      private void findViewsById(View view) {
            productListView = (ListView) view.findViewById(R.id.list_product);
        }

    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View view, int position,
            long arg3) {

         ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);

            String tag = button.getTag().toString();
            if (tag.equalsIgnoreCase("grey")) {
                sharedPreference.addFavorite(activity, products.get(position));
                Toast.makeText(activity,
                        activity.getResources().getString(R.string.add_favr),
                        Toast.LENGTH_SHORT).show();

                button.setTag("red");
                button.setImageResource(R.drawable.heart_red);
            } else {
                sharedPreference.removeFavorite(activity, products.get(position));
                button.setTag("grey");
                button.setImageResource(R.drawable.heart_grey);
                Toast.makeText(activity,
                        activity.getResources().getString(R.string.remove_favr),
                        Toast.LENGTH_SHORT).show();
            }

            return true;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         Product product = (Product) parent.getItemAtPosition(position);
            Toast.makeText(activity, product.toString(), Toast.LENGTH_LONG).show();

    }

    @Override
    public void onResume() {
        getActivity().setTitle(R.string.app_name);
        getActivity().getActionBar().setTitle(R.string.app_name);
        super.onResume();
    }

}

Array generated by a method

How can I generate an array of specified length by a method?

In short, what's an elegant replacement of this code:

Result generate() {
    // logic
}

Result[] results(int length) {
    Result[] results = new Result[length];
    for (int i = 0; i < results.length; i++) results[i] = generate();
    return results;
}

Play Framework Database and Java Persistence

I am very, very new to the Play! framework (for Java), and because I will need it to do a database project in my class, I have to learn it as fast as possible, so please bear with me if I ask some dumb questions here. I'm following a tutorial, but I have a problem. I have searched everywhere, but I couldn't find answers.

1) In the tutorial, all the actions in the controller are defined as static methods, but when I declare methods as static and run the app, I receive error that they are not a member of controller. I know the solution is to remove static, but I was wondering why is there this difference?

2) This is my main problem: in the tutorial, when connecting to the database:

  • He creates a class and adds javax.persistence.Entity annotation
  • The class extends play.db.ebean.Model class
  • He adds the javax.persistence.Id annotation to the ID field

My problem is that I don't have access to these classes. Can anyone suggest a solution please? I'm really stock!

Thank you in advance

Serialization: good or bad in a multi-thread environment to maintain a cache?

Which is a better approach : using serialization to create a cache or simply writing objects values in the form of string arrays to a file using delimiters? As I recently was told that serialization makes a different thread to process and should not be used in a multi-threaded environment/application where there are timing constraints and you need faster processing and less interruption! So Is it true, that serialization is in efficient in a big multi-threaded java project ?

Using Akka with Eclipse (Java)

I am able to include the required jar files and run my Akka code. But I want to generate the correct folder structure for using Akka using eclipse. I am not able to understand how should I go about it. Should I install SBT first, then some eclipse plugin. How can I run akka microkernal for my Akka Java code. Step by step of what do to in order to achieve that would be useful.

Multiple Dateformat

i am task to change the dateformat according to the user's language. Currently the website runs in Chinese and English, However i am unable to change the format of the mask according to the user's language.

  <h:outputText styleClass="outputText"
                        id="index_output_todate" value="#{msg.index_output_todate}">
                    </h:outputText>
                    <p:calendar
                        value="#{pc_Index.w_message.am_todate_filter}"
                        id="index_input_todate" styleClass="calendar" maxlength="10"
                        pattern="#{pc_Index.dateDisplayFormat}" onfocus="$(this).mask('9999年99月99日');">
                        <p:watermark for="index_input_todate" value="#{pc_Index.watermarkDateDisplayFormat}" />
                        <f:convertDateTime pattern="#{pc_Index.dateDisplayFormat}" />
                    </p:calendar>

I need the date format of the mask to be 9999年99月99日 when the user login as a zh_CN user or a date format of DD/MM/YYYY for en_UK user. Is there a way to do this?

I had already set the locale

 public String getDateDisplayFormat() {  

    String locale = getUserLocale();
    String DATEFORMAT_UK = "dd/MM/yyyy";
    String DATEFORMAT_US = "mm/dd/yyyy";
    String DATEFORMAT_CN = "yyyy年MM月dd日";
    String _s = DATEFORMAT_UK;
    if(!isEmptyNull(locale) && locale.equals("en_US")) {
        _s = DATEFORMAT_US;
    }
    else if(!isEmptyNull(locale) && locale.equals("zh_CN")) {
        _s = DATEFORMAT_CN;
    }
    return _s;
}

Clients unable to send data to server

I am unable to find any error and i just cant get this to work. The program is mean to run a server and have clients able to send data to each other. This problem is that I just cant get any data sent. I followed this tutorial(https://www.youtube.com/watch?v=_1ThWf9Fkfo) so that it could be multi-threaded but i just cant make it work.

Server class:

import java.io.*;
import java.net.*;


public class Server {

    static ServerSocket serverSocket;
    static Socket socket;
    static DataOutputStream out;
    static Users[] user = new Users[10];
    static DataInputStream in;

    public static void main(String[] args) throws Exception {
        System.out.println("Starting Server.");
        serverSocket=new ServerSocket(7777);
        System.out.println("Server Started.");

        while(true){

        socket = serverSocket.accept();
        for (int i = 0; i <10; i++){
        System.out.println("Connection from: " + socket.getInetAddress());
        out = new DataOutputStream(socket.getOutputStream());
        in = new DataInputStream(socket.getInputStream());
        if (user[i] == null) {
        user[i] = new Users(out, in, user);
            Thread thread = new Thread();
        thread.start();
        break;
        }
    }
    }
}
}

class Users implements Runnable{
    DataOutputStream out;
    DataInputStream in;
    Users[] user = new Users[10];

    public Users(DataOutputStream out, DataInputStream in, Users[] user){
        this.out = out;
        this.in = in;
        this.user =user;

    }

    public void run() {
        while(true) {
        try {
            String message = in.readUTF();
            for (int i = 0;i<10;i++) {
                if(user[i] != null) {
                    user[i].out.writeUTF(message);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
}

Client Class:

import java.net.*;
import java.util.Scanner;
import java.io.*;



public class Client {
    static Socket socket;
    static DataInputStream in;
    static DataOutputStream out;

    public static void main(String[] args) throws Exception {
        System.out.println("Connecting...");
        socket = new Socket("localhost",7777);
        System.out.println("Connection Succesful");
        in = new DataInputStream(socket.getInputStream());
        out = new DataOutputStream(socket.getOutputStream());
        Input input = new Input(in);
        Thread thread = new Thread(input);
        thread.start();
        Scanner sc = new Scanner(System.in);
        while(true) {
            String sendMessage = sc.nextLine();
            out.writeUTF(sendMessage);

    }
}
}


class Input implements Runnable{

    private DataInputStream in;

    public Input(DataInputStream in) {
        this.in = in;
    }

    public void run() {
        while(true){
            String message;
            try {
                message = in.readUTF();
                System.out.println(message);
            } catch (IOException e) {
                e.printStackTrace();
            }


        }

    }


}

I am pretty sure that it is the clients not being able to send

Android application becomes slow after multiple callbacks - what's wrong here?

I have an application that parses through a user's facebook messages, and due to an extremely annoying limitation by the facebook API that only lets you receive 25 messages per API call, I have to use some weird quasi-recursive method to parse through the messages so I can handle pagination. My issue arose when I attempted to make my application sleep in the scenario where we exceeded requests before trying again.

I noticed that the app would shoot out really fast, parsing through several api calls per second. But as the app dragged on and the requests hit several hundreds, it slowed to a crawl of like maybe 1 per 5 seconds. Does anybody see what is slowing me down here?

Relevant portions of my code:

I start the parsing from a service, which basically makes the initial request for 25 messages (and the links to every one after that) and calls retrieveMsgs().

@Override
public int onStartCommand(Intent intent, int flags, int startID){

    if(intent!=null) {
        id = intent.getStringExtra("id");
    }

    Session session = Session.getActiveSession();
    new Request(session, id + "/comments", null, HttpMethod.GET, new Request.Callback() {
        @Override
        public void onCompleted(Response response) {
        try {
            JSONArray msgs = response.getGraphObject().getInnerJSONObject().getJSONArray("data");
            populateData(msgs);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Request next = response.getRequestForPagedResults(Response.PagingDirection.NEXT);
        retrieveMsgs(next);
        }
    }).executeAsync();
    return START_STICKY;
}

and this calls retrieveMsgs, which will call itself until it finishes parsing each 25 message array from the Facebook API. It basically parses the 25 messages and then checks to see if it received a link to the next page, and quits if it doesn't.

public void retrieveMsgs(final Request next) {
    Log.i("api calls", apiCalls+"");

    if (next != null) {
        next.setCallback(new Request.Callback() {
            public void onCompleted(Response response) {
                try {
                    if (response.getGraphObject() == null) {
                        // we exceeded our limit, sleep for a bit before trying again
                        try {
                            Thread.sleep(240000);
                        }
                        catch(Exception e){

                        }
                        retrieveMsgs(next);      // restart the method call
                        Log.i("hello", "is this slowing us down?");
                        return;
                    }

                    JSONArray msgs = response.getGraphObject().getInnerJSONObject().getJSONArray("data");
                    populateData(msgs);

                    Request next2 = response.getRequestForPagedResults(Response.PagingDirection.NEXT);

                    if (next2 != null) {
                        apiCalls++;
                        retrieveMsgs(next2);
                    } else {
                        showDoneNotif();
                    }} catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        next.executeAsync();

    }

}

I have difficulty tracking code through inner classes and callbacks and whatnot, so I'd really appreciate it if anybody could explain what is potentially going wrong here. The slowdown really kills the viability of the app after 20,000 messages or so, and with potentially hundreds of thousands of messages per conversation, I can't reasonably move on from this.

When would you implement and infinite loop in java?

Is there any practical application for and ifinite loops in java code, and if so what?

For example:

while(true){
    //statements, but the loop is never set to false
}

When could you use this?

running error java.exe compiler in processing IDE

Getting Error while running on Andriod Device:

Hi I am getting the error(RUNNING ERROR IN JAVAC.EXE COMPILER) in windows-7 32-bit and I am using processing 2.2.1. I have downloaded all the files in andriod sdk except images.

Error displayed in processing

BUILD FAILED C:\Users\Acer\AppData\Local\Android\android-sdk\tools\ant\build.xml:716: The following error occurred while executing this line:

C:\Users\Acer\AppData\Local\Android\android-sdk\tools\ant\build.xml:730: Error running javac.exe compiler

I have set all the path variables ANDRIOD_HOME,JAVA_HOME,ANT_HOME,ADB_HOME,PATH

enter code here


ANDRIOD_HOME=C:\Users\Acer\AppData\Local\Android\android-sdk\tools\proguard\bin

ANT_HOME=C:\Users\Acer\AppData\Local\Android\android-sdk\tools\ant

ADB_HOME= C:\Users\Acer\AppData\Local\Android\android-sdk\platform-tools

JAVA_HOME=C:\ProgramFiles\Java\jdk1.7.0_67\bin;

PATH =C:\ProgramData\Oracle\Java\javapath;

%JAVA_HOME%;%ANT_HOME%;ADB_HOME%;%ANDROID_HOME%


I am trying to fix this problem more than 10 days can any one help me![Error displayed while building][10]

Are there source files, or only class files, in EAR projects?

Suppose I have an EJB project called X and a JSP project called Y. Consequently I have X.jar and Y.war . I create an EAR project called Z, adding X and Y as dependencies.

  1. Will/should the source files for projects X and Y be stored in Z's project directory?

  2. What exactly will project Z store about X and Y besides references to them in application.xml ?

Edit: These projects are in Eclipse.

Null pointer exception from final variable within runnable

I have code that runs a portfolio of algorithms on a given problem, and then as soon as one algorithm finds the answer to a problem, the program continues. The other algorithms in the portfolio get voluntary signals to terminate, and the main thread of execution goes on.

One user of this code is sending me a stacktrace with a NullPointerException on the line "resultReference.set(solverResult);" As you can see from the code below, resultReference is a final variable and is initialized immediately. I don't see how it could possibly ever become null. I've spent a long time trying to reproduce the problem on my end to no avail. The line numbers on the user's stacktrace match up with the line numbers on my code. The user reports having seen the error on 3 different occasions, but infrequently (this does not happen every time a problem is solved), so maybe its some sort of race condition. This is with jdk 1.8_25.

Am I right in assuming that this error should be impossible because the variable is final? I'm not sure what to make of this stack trace and wanted some reassuring that it should be impossible.

public class ParallelSolver {

private final ListeningExecutorService executorService;
private final AtomicReference<Throwable> error;
private final List<Solver> solvers;
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ParallelSolver.class);

public ParallelSolver(int threadPoolSize, List<Solvers> solvers) {
    executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(threadPoolSize));
    error = new AtomicReference<>();
    this.solvers = solvers;
}

public SolverResult solve(Problem p) {
    final AtomicReference<SolverResult> resultReference = new AtomicReference<>();
    final List<Future> futures = new ArrayList<>();
    final Semaphore workDone = new Semaphore(0);
    try {
        // Submit one job per each solver in the portfolio
        solvers.forEach(solver -> {
            final ListenableFuture<Void> future = executorService.submit(() -> {
                SolverResult solverResult = solver.solve(p);
                if (solverResult.isConclusive()) {
                    log.debug("Signalling the blocked thread to wake up!");
                     // NPE HERE ON THIS LINE
                    resultReference.set(solverResult);
                    workDone.release(solvers.size());
                }
                log.debug("Releasing a single permit as the work for this thread is done.");
                workDone.release(1);
                log.debug("Job ending...");
                return null;
            });
            futures.add(future);
            Futures.addCallback(future, new FutureCallback<Void>() {
                @Override
                public void onSuccess(Void result) {

                }

                @Override
                public void onFailure(Throwable t) {
                    if (t instanceof CancellationException) {
                        return;
                    }
                    error.compareAndSet(null, t);
                    // Wake up the main thread (if it's still sleeping)
                    workDone.release(solvers.size());
                }
            });
        });
        // Wait for a thread to complete solving and signal you, or all threads to timeout
        log.debug("Main thread going to sleep");
        workDone.acquire(solvers.size());
        log.debug("Main thread waking up, checking for errors then cancelling futures");
        checkForErrors();
        // cancel any still to be launched futures
        futures.forEach(future -> future.cancel(false));
        log.debug("Returning now");
        return resultReference.get() == null ? SolverResult.createTimeoutResult() : resultReference.get();
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while running parallel job", e);
    }
}

/**
 * We want a fail-fast policy, but java executors aren't going to throw the exception on the main thread.
 * We can't call Future.get() and check for errors, because that might block.
 * So we set a variable when an error occurs, and check it here.
 */
private void checkForErrors() {
    if (error.get() != null) {
        log.error("Error occured while executing a task", error.get());
        throw new RuntimeException("Error occurred while executing a task", error.get());
    }
}

Creating an ArrayList from data in a text file

I am trying to write a program that uses two classes to find the total $ amount from a text file of retail transactions. The first class must read the file, and the second class must perform the calculations. The problem I am having is that in the first class, the ArrayList only seems to get the price of the last item in the file. Here is the input (which is in a text file):

$69.99 3 Shoes

$79.99 1 Pants

$17.99 1 Belt

And here is my first class:

class ReadInputFile {
static ArrayList<Double> priceArray = new ArrayList<>();
static ArrayList<Double> quantityArray = new ArrayList<>();

static String  priceSubstring = new String();
static String quantitySubstring = new String();

public void gatherData () {

String s = "C:\\filepath";   
try {


      FileReader inputFile = new FileReader(s);

      BufferedReader bufferReader = new BufferedReader(inputFile);

      String line;

      String substring = " ";

      while ((line = bufferReader.readLine()) != null)


      substring = line.substring(1, line.lastIndexOf(" ") + 1);



     priceSubstring = substring.substring(0,substring.indexOf(" "));

      quantitySubstring = substring.substring(substring.indexOf(" ") + 1 , substring.lastIndexOf(" ") );


      double price = Double.parseDouble(priceSubstring);
      double quantity = Double.parseDouble(quantitySubstring);

      priceArray.add(price);
      quantityArray.add(quantity);

      System.out.println(priceArray);


} catch (IOException e) {
     e.printStackTrace();
}
}

The output and value of priceArray is [17.99], but the desired output is [69.99,79.99,17.99].

Not sure where the problem is, but thanks in advance for any help!

JUnit testing a method with JOptionPane.showMessageDialog

I have made a game where a user and an AI takes turns "rolling" a dice. The game automatically takes the AI's turn and returns to the user's turn. I used JOptionPane.showMessageDialog to popup a dialog box notifying the user that it is their turn. So all this is working properly but when I execute a JUnit test class to test the hold() method the popup comes up. Is there a way to suppress the popup or automatically close the window in a JUnit Test class?

    public void hold() {

    this.swapWhoseTurn();           
    this.setChanged();
    this.notifyObservers();

    if (this.getCurrentPlayer().getIsMyTurn() == this.getComputerPlayer().getIsMyTurn()) {
        this.theComputer.takeTurn();
        this.hold();
        HumanPlayerPanel.turnAlert();
    }

The turnAlert is a static method in another class called HumanPlayerPanel. Here is the code.

    public static void turnAlert() {
    JOptionPane.showMessageDialog(null, "It is your turn");
    }

I saw that I can call doClick method on the OK_Option button but I'm not too sure how to find that button. Any help is appreciated.

Java HashMap containsKey method returning false only when built into JAR - true otherwise

I have a call to a HashMap's containsKey method that I expect to return true. It returns true if I compile my program to .class files and run it like that, but if I build a JAR then the same call returns false for reasons I cannot comprehend.

I've debugged both the .class and the JAR versions (the JAR using a remote connection as described in http://ift.tt/1KtRoe6 ) and in both cases the HashMap appears to contain the Key I'm trying to check.

The HashMap uses URI objects as keys. Here are the contents of the variables as shown in each debug session:

When run as a .class file

HashMap Key: java.net.URI = file:/E:/SSD%20App%20Libraries/Google%20Drive/Programming/Bet%20Matching/Java%20Sim/target/classes/simfiles/paytables/

URIToCheck: java.net.URI = file:///E:/SSD%20App%20Libraries/Google%20Drive/Programming/Bet%20Matching/Java%20Sim/target/classes/simfiles/paytables/

Result: GameTreeItemsMap.containsKey(URIToCheck) is true

When run as a JAR

HashMap Key: java.net.URI = jar:file:/E:/SSD%20App%20Libraries/Google%20Drive/Programming/Bet%20Matching/Java%20Sim/out/artifacts/JavaSim_jar/Java%20Sim.jar!/simfiles/paytables/

URIToCheck: java.net.URI = jar:file:///E:/SSD%2520App%2520Libraries/Google%2520Drive/Programming/Bet%2520Matching/Java%2520Sim/out/artifacts/JavaSim_jar/Java%2520Sim.jar!/simfiles/paytables/

Result: GameTreeItemsMap.containsKey(URIToCheck) is false

I would expect the method to return true in both cases. Do URIs somehow behave differently inside a JAR? What's going on?

Thanks in advance for any help!

Using inner join on hibernate returning token uknown

I'm having some trouble with hibernate. I'm trying to create a query to return the number of consults foreach medical ward, i just run the sql on pgAdmin and everything was well, but when i tried to create the same sql on hibernate, this has return some erros. Here the code.

SQL:

select a.cod_ala ,count(cod_consulta) as max from Consulta as c 
    inner join Medico as m on m.cod_medico = c.cod_medico
    inner join Ala as a on a.cod_ala = m.cod_ala
group by a.cod_ala  

Java:

public void getConsultasAla() {
    String sql = "select a.cod_ala, count(cod_consulta) as max from Consulta as c" 
    +" inner join Medico as m on m.cod_medico = c.cod_medico"           
    +" inner join Ala as a on a.cod_ala = m.cod_ala"
    +" group by a.cod_ala";



    Query query;
    System.out.println(sql);
    this.session = GeneralController.getSession();

    query = this.session.createQuery(sql);
    List list = query.list();
    int i = 0;
    while(list.iterator().hasNext()) {
        System.out.println(list.get(i++));
    }

}

Errors:

jul 01, 2015 8:43:14 PM org.hibernate.hql.internal.ast.ErrorCounter reportError
ERROR: line 1:149: unexpected token: on
jul 01, 2015 8:43:14 PM org.hibernate.hql.internal.ast.ErrorCounter reportError
ERROR: line 1:149: unexpected token: on
line 1:149: unexpected token: on
    at org.hibernate.hql.internal.antlr.HqlBaseParser.fromJoin(HqlBaseParser.java:1694)
    at org.hibernate.hql.internal.antlr.HqlBaseParser.fromClause(HqlBaseParser.java:1349)
    at org.hibernate.hql.internal.antlr.HqlBaseParser.selectFrom(HqlBaseParser.java:1055)
    at org.hibernate.hql.internal.antlr.HqlBaseParser.queryRule(HqlBaseParser.java:701)
    at org.hibernate.hql.internal.antlr.HqlBaseParser.selectStatement(HqlBaseParser.java:294)
    at org.hibernate.hql.internal.antlr.HqlBaseParser.statement(HqlBaseParser.java:157)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:266)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:180)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1778)
    at org.hibernate.control.ConsultsController.getConsultasAla(ConsultsController.java:473)
    at org.menu.MenuConsulta.MenuConsultas(MenuConsulta.java:97)
    at org.hibernate.MainApp.menuPrincipal(MainApp.java:80)
    at org.hibernate.MainApp.main(MainApp.java:145)

Exception in thread "main" org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: on near line 1, column 98 [select a.cod_ala, count(cod_consulta) as max from org.model.Consulta as c inner join Medico as m on m.cod_medico = c.cod_medico inner join Ala as a on a.cod_ala = m.cod_ala group by a.cod_ala]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
    at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
    at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:79)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:276)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:180)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1778)
    at org.hibernate.control.ConsultsController.getConsultasAla(ConsultsController.java:473)
    at org.menu.MenuConsulta.MenuConsultas(MenuConsulta.java:97)
    at org.hibernate.MainApp.menuPrincipal(MainApp.java:80)
    at org.hibernate.MainApp.main(MainApp.java:145)

PS: Sorry for bad grammar, english is my second language

Can I overwrite an attribute of a superclass in Java? [duplicate]

This question already has an answer here:

I've faced a very curious question in my last work with Java. I want an attribute of the superclass to be accessed only by the class itself and it's daughters. As you know, nor private neither protected modifier offers me this solution. So I've declared the same attribute at both the parent and the daughter class.

But it took me to strange paths. Here's an example:

public class Father{

    private int variable = 0;

    void showVariable(){
        System.out.print(variable);
    }

}

class daughter extends Father{

    private int variable = 5;

    void showDaugtherVariable(){
        System.out.println(variable);
    }
}

class main{
    public static void main(String[] args){

        daughter daughter = new daughter();
        daughter.showDaugtherVariable();
        daughter.showVariable();
    }
 }

What is printed:

5
0

As you see, I can work with variable as I want. It seems that I've succesfully overwrited it. But if I work with it with a superclass method, It uses the superclass value...as if it was keeping two variables with the same name for the daughter class, one of them inherited by the father.

Why this behavior?

Using a javascript variable as a parameter in a java method called in a template expansion within css

I'm trying to pass a variable pulled from a javascript file as a parameter for a java method in a template expansion. The variable is the file path of an image I want to display on the web page. When I try to display the plain image, I can call it using

"${ImageUrl}"

which returns the whole file. However, the file is in an external filesystem, so what I want to do is call a method that can go fetch the correct file and handle that as necessary and pass the file path as the parameter in that method. However, when I call

"${getImage(ImageUrl}"

my java file reads ImageUrl as the text "ImageUrl".

Is there a way to call the method and pass in the correct javascript variable as a parameter?

Thanks

C++ and Java Learn Online for Free. Anybody knows a good and efficient website? [on hold]

I am wondering if you could suggest some websites that offer free lesson in C++ or Java. I cannot afford going into school and such to learn more. Thanks in advance guys!

Spring Batch partitioning a step

I have multiple CSV files to read. I want the processing to be done one file at a time. Rather than reading all the records till it reaches commit level.

I have put together a job which uses partition but on running the job I see that there are two entries for every row. As if the job is running twice.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
    xmlns:context="http://ift.tt/GArMu7" xmlns:p="http://ift.tt/1jdM0fE"
    xmlns:batch="http://ift.tt/1fayA4Z" xmlns:mvc="http://ift.tt/1bHqwjR"
    xmlns:xsi="http://ift.tt/ra1lAU"
    xsi:schemaLocation="http://ift.tt/GArMu6  
http://ift.tt/1cnl1uo  
http://ift.tt/GArMu7  
http://ift.tt/1ldEMZY  
http://ift.tt/1bHqwjR  
http://ift.tt/1kF4x7W  
http://ift.tt/1fayA4Z   
http://ift.tt/1snNyHz">

    <import resource="classpath:/database.xml" />



     <bean id="asyncTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor" >
     <property name="concurrencyLimit" value="1"></property>
     </bean>  

     <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <property name="corePoolSize" value="5" />
    </bean>

     <bean id="partitioner" class="org.springframework.batch.core.partition.support.MultiResourcePartitioner" scope="step">
        <property name="resources" value="file:#{jobParameters[filePath]}/*.dat" />
    </bean>

    <bean id="multiResourceReader"
        class="org.springframework.batch.item.file.MultiResourceItemReader"
        scope="step">
        <property name="resources" value="file:#{jobParameters[filePath]}/*.dat"></property>
        <property name="delegate" ref="logItFileReader"></property>
    </bean>



    <batch:job id="remediationJob">
        <batch:step id="partitionedStep" >
            <batch:partition step="readWriteContactsPartitionedStep" partitioner="partitioner">
                <batch:handler task-executor="asyncTaskExecutor" />
            </batch:partition>
        </batch:step>
    </batch:job>

    <batch:step id="readWriteContactsPartitionedStep">
        <batch:tasklet>
            <batch:transaction-attributes isolation="READ_UNCOMMITTED"/>
            <batch:chunk reader="multiResourceReader" writer="rawItemDatabaseWriter" commit-interval="10" skip-policy="pdwUploadSkipPolicy"/>
        <batch:listeners>
                    <batch:listener ref="customItemReaderListener"></batch:listener>
                    <batch:listener ref="csvLineSkipListener"></batch:listener>
                    <batch:listener ref="getCurrentResourceChunkListener"></batch:listener>

                </batch:listeners>
        </batch:tasklet>    
    </batch:step>


    <bean id="logItFileReader" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
        <!-- Read a csv file -->

        <property name="strict" value="false"></property>
        <property name="lineMapper">
            <bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
                <!-- split it -->
                <property name="lineTokenizer">
                    <bean
                        class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
                        <property name="delimiter" value="@##@" />
                        <property name="strict" value="true" />
                    </bean>
                </property>
                <property name="fieldSetMapper">
                    <!-- map to an object -->
                    <bean class="org.kp.oppr.remediation.batch.vo.CSVDataVOFieldMapper">

                    </bean>
                </property>
            </bean>
        </property>
    </bean>

    <bean id="rawItemDatabaseWriter" class="org.kp.oppr.remediation.batch.csv.RawItemDatabaseWriter"
        scope="step">
    </bean>

    <bean id="pdwUploadSkipPolicy"
        class="org.springframework.batch.core.step.skip.AlwaysSkipItemSkipPolicy" />

    <bean id="csvDataVO" class="org.kp.oppr.remediation.batch.vo.CSVDataVO"
        scope="prototype"></bean>


    <!-- BATCH LISTENERS -->

    <bean id="pdwFileMoverListener"
        class="org.kp.oppr.remediation.batch.listener.PdwFileMoverListener"
        scope="step">
    </bean>

    <bean id="csvLineSkipListener"
        class="org.kp.oppr.remediation.batch.listener.CSVLineSkipListener"
        scope="step">
    </bean>

    <bean id="customItemReaderListener"
        class="org.kp.oppr.remediation.batch.listener.CustomItemReaderListener"></bean>

     <bean id="getCurrentResourceChunkListener" 
          class="org.kp.oppr.remediation.batch.listener.GetCurrentResourceChunkListener">
        <property name="proxy" ref ="multiResourceReader" />
    </bean>
    <!-- 
    <bean id="stepListener" class="org.kp.oppr.remediation.batch.listener.ExampleStepExecutionListener">
        <property name="resources" ref="multiResourceReader"/>
    </bean>
     -->
    <!-- Skip Policies -->

</beans>  

Is there something I am missing here ?

Hibernate cannot find suitable driver for Derby in Spring MVC webapp

I wonder if anyone can explain to me why a Spring and Hibernate webapp works perfectly well in two environments but fails in another? I'm using NetBeans 8.0.X with Tomcat 8.0.3.0 and Apache Derby 10.X.

My application's dispatcherservlet is as follows:

<beans xmlns="http://ift.tt/GArMu6"
   xmlns:context="http://ift.tt/GArMu7"
   xmlns:mvc="http://ift.tt/1bHqwjR" 
   xmlns:tx="http://ift.tt/OGfeU2"       
   xmlns:xsi="http://ift.tt/ra1lAU"  
   xsi:schemaLocation="http://ift.tt/GArMu6 
                       http://ift.tt/1cnl1uo 
                       http://ift.tt/GArMu7 
                       http://ift.tt/1ldEMZY 
                       http://ift.tt/1bHqwjR                            
                       http://ift.tt/1kF4x7W                           
                       http://ift.tt/OGfeU2    
                       http://ift.tt/KC395X">

<!-- Uses annotations in classes for JavaBeans. XML is an alternative. -->
<mvc:annotation-driven />   

<!-- Base package. -->
<context:component-scan base-package="library" />    

<!-- Model. -->
<bean id="person" class="library.model.Person" />
<bean id="book" class="library.model.Book" />        

<!-- Spring Controllers. -->
<bean id="adminController" class="library.controller.admin.AdminController" />    
<bean id="personController" class="library.controller.PersonController" />      
<bean id="bookController" class="library.controller.BookController" /> 
<bean id="exceptionController" class="library.controller.ExceptionController" />     

<!-- Spring Interceptors. -->
<mvc:interceptors>
    <bean id="clientInterceptor" class="library.interceptor.ClientInterceptor" />
</mvc:interceptors>

<!-- Spring Services. -->
<bean id="personServiceImpl" class="library.service.PersonServiceImpl" />    
<bean id="bookServiceImpl" class="library.service.BookServiceImpl" />      

<!-- Spring Repositories. -->
<bean id="personDAOImpl" class="library.dao.PersonDAOImpl" />    
<bean id="bookDAOImpl" class="library.dao.BookDAOImpl" />       

<!-- Spring Validators. -->
<bean id="personValidator" class="library.validator.PersonValidator" />    
<bean id="bookValidator" class="library.validator.BookValidator" />     

<!-- Spring ViewResolver. -->               
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
         <value>/WEB-INF/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>   

<!-- Spring MesssageSource. -->         
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename"> 
        <value>/WEB-INF/classes/messages</value>    
    </property>    
</bean>

<!-- Spring Properties file for Library. -->      
<bean id="propertiesFactory" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="location">  
         <value>classpath:library.properties</value>             
    </property>
</bean>      

<!-- Hibernate DataSource. -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">   
    <property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver" />        
    <!--property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" /-->
    <property name="url" value="jdbc:derby://localhost:1527/Library" />
    <property name="username" value="username" />
    <property name="password" value="password" />            
</bean>   

<!-- Hibernate Interceptors. -->
<bean id="serverInterceptor" class="library.interceptor.ServerInterceptor" />

<!-- Hibernate SessionFactory. -->    
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">    
    <property name="dataSource" ref="dataSource"></property>                  
    <property name="hibernateProperties">
        <props>    
           <prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>                     
           <!--prop key="hibernate.dialect">org.hibernate.dialect.DerbyTenSixDialect</prop-->
           <prop key="hibernate.show_sql">false</prop>               

           <!-- What to do with the database schema. -->
           <prop key="hbm2ddl.auto">validate</prop>    
           <!-- validate:    validate the schema, makes no changes to the database.
                update:      update the schema.
                create:      creates the schema, destroying previous data.
                create-drop: drop the schema at the end of the session. -->                 
        </props>            
    </property>                                                                                                                                
    <property name="entityInterceptor">
        <ref bean="serverInterceptor" />            
    </property>                                                                                                                                             
    <property name="packagesToScan">
        <list>
            <value>library.model</value>                
        </list>
    </property>          
</bean>

<!-- Hibernate TransactionManagment. -->
<tx:annotation-driven />                
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
   <property name="sessionFactory" ref="sessionFactory" />
</bean>  

And the errors given when the application builds and fails in the one environment is:

WARN|01 07 2015|16 26 31|http-nio-8080-exec-73|org.hibernate.engine.jdbc.internal.JdbcServicesImpl| - HHH000342: Could not obtain connection to query metadata : No suitable driver found for jdbc:derby://localhost:1527/Library
INFO|01 07 2015|16 26 31|http-nio-8080-exec-73|org.hibernate.dialect.Dialect| - HHH000400: Using dialect: org.hibernate.dialect.DerbyTenSixDialect
INFO|01 07 2015|16 26 34|http-nio-8080-exec-73|org.hibernate.engine.jdbc.internal.LobCreatorBuilder| - HHH000422: Disabling contextual LOB creation as connection was null
ERROR|01 07 2015|16 26 41|http-nio-8080-exec-73|org.springframework.web.context.ContextLoader| - Context initialization failed

Which is then causing the wiring of the dependencies to fail.

What do these messages mean?

The application is using Spring 4.0.2 with hibernate-core-4.3.10.jar. All dependencies are identical between the three environments and a listing of them follows:

30 Jun 2015  20 26           445,288 antlr-2.7.7.jar
30 Jun 2015  20 26             4,467 aopalliance-1.0.jar
30 Jun 2015  20 26           160,519 commons-dbcp-1.4.jar
30 Jun 2015  20 26            62,050 commons-logging-1.1.3.jar
30 Jun 2015  20 26         2,834,700 derby.jar
30 Jun 2015  20 26           582,639 derbyclient.jar
30 Jun 2015  20 26           313,898 dom4j-1.6.1.jar
30 Jun 2015  20 26            75,311 hibernate-commons-annotations-4.0.4.Final.jar
30 Jun 2015  20 26         5,280,098 hibernate-core-4.3.10.Final.jar
30 Jun 2015  20 27           113,371 hibernate-jpa-2.1-api-1.0.0.Final.jar
30 Jun 2015  20 26            38,605 jackson-annotations-2.4.0.jar
30 Jun 2015  20 26           225,306 jackson-core-2.4.1.jar
30 Jun 2015  20 27           228,552 jackson-core-asl-1.9.7.jar
30 Jun 2015  20 26         1,074,275 jackson-databind-2.4.1.jar
30 Jun 2015  20 26           786,084 jackson-mapper-lgpl-1.9.13.jar
30 Jun 2015  20 26            76,551 jandex-1.1.0.Final.jar
30 Jun 2015  20 26           714,194 javassist-3.18.1-GA.jar
30 Jun 2015  20 26           162,126 javax.persistence-2.1.0.jar
30 Jun 2015  20 26            57,183 jboss-logging-3.1.3.GA.jar
30 Jun 2015  20 26            11,558 jboss-logging-annotations-1.2.0.Beta1.jar
30 Jun 2015  20 27            27,717 jboss-transaction-api_1.2_spec-1.0.0.Final.jar
30 Jun 2015  20 26            20,682 jstl-1.1.2.jar
30 Jun 2015  20 26            15,071 jta-1.1.jar
30 Jun 2015  20 26           367,444 log4j-1.2.14.jar
30 Jun 2015  20 27            52,150 persistence-api-1.0.jar
30 Jun 2015  20 27            36,364 spring-annotation-base-1.0.2.jar
30 Jun 2015  20 26           352,730 spring-aop-4.0.2.RELEASE.jar
30 Jun 2015  20 26           669,044 spring-beans-4.0.2.RELEASE.jar
30 Jun 2015  20 26           974,272 spring-context-4.0.2.RELEASE.jar
30 Jun 2015  20 26           960,994 spring-core-4.0.2.RELEASE.jar
30 Jun 2015  20 26           204,780 spring-expression-4.0.2.RELEASE.jar
30 Jun 2015  20 26           419,614 spring-jdbc-4.0.2.RELEASE.jar
30 Jun 2015  20 26           366,844 spring-orm-4.0.2.RELEASE.jar
30 Jun 2015  20 26           248,204 spring-tx-4.0.2.RELEASE.jar
30 Jun 2015  20 26           665,015 spring-web-4.0.2.RELEASE.jar
30 Jun 2015  20 26           660,329 spring-webmvc-4.0.2.RELEASE.jar
30 Jun 2015  20 26           393,259 standard-1.1.2.jar

Java 8 Streams: Analyze same list elements

Code explains better:

Test Case

@org.junit.Test
public void test() {
    List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

    System.out.println(withoutStreams(values)); // Output: 1,9
    System.out.println(withStreamSol1Error(values)); // Compile time error
    System.out.println(withStreamSol2(values)); // Output: 1,9
}

Required Solution (Without Stream):

private List<Integer> withoutStreams(List<Integer> values) {
    // List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

    for (int index1 = 0; index1 < values.size(); index1++) {
        int value1 = values.get(index1);
        if (value1 == 10)
            return Arrays.asList(value1);
        for (int index2 = index1 + 1; index2 < values.size(); index2++) {
            int value2 = values.get(index2);

            if ((value1 + value2) == 10) {
                return Arrays.asList(value1, value2);
            }
        }
    }

    return Collections.emptyList();
}

My Attempt : With Stream: (Compile time error - mismatch)

private List<Integer> withStreamSol1Error(List<Integer> values) {
    List<Integer> exactEqual = values.stream().filter(value -> value.intValue() == 10).limit(1)
            .collect(Collectors.toList());

    // Compile Time Error
    if (exactEqual.isEmpty()) {
        IntStream.range(0, values.size() - 1)
                .forEachOrdered(index -> IntStream.range(index + 1, values.size() - 1)
                        .filter(index2 -> values.get(index) + values.get(index2) == 10).limit(1)
                        .collect(Collectors.toList()));
    }

    return Collections.emptyList();
}

With Stream (Working)

private List<Integer> withStreamSol2(List<Integer> values) {
    List<Integer> exactEqual = values.stream().filter(value -> value.intValue() == 10).limit(1)
            .collect(Collectors.toList());

    int index1 = 0;
    final List<Integer> result = new ArrayList<>();
    if (exactEqual.isEmpty()) {
        values.stream().forEach(value1 -> {
            if(!result.isEmpty()) // Query: How can stop outer forEach
                return;

            result.add(value1);
            result.addAll(values.stream().skip(index1).filter(value2 -> (value1 + value2) == 10).limit(1)
                    .collect(Collectors.toList()));
        });
    }

    return result;
}

Can anyone suggest a good solution for this problem?

fails to convert ppt into pdf using jacob.jar

I use jacob 1.17-M2, I set java.library.path to c:\windows\system32 and I've put jacob-1.17-M2-x64.dll into c:\window\system32 before. My box is Windows 2008 R2 Enterprise.

    System.setProperty( "java.library.path", "c:\\windows\\system32" );
    log.info(System.getProperty("java.library.path"));
    ActiveXComponent app = new ActiveXComponent("PowerPoint.Application");
    //app.setProperty("Visible", msofalse);
    Dispatch ppts = app.getProperty("Presentations").toDispatch();      
    Dispatch ppt = Dispatch.call(ppts,
                                "Open",
                                inputFile,
                                true,//ReadOnly
                                true,//Untitled
                                false//WithWindow
                                ).toDispatch();     
    Dispatch.call(ppt,
                "SaveAs",
                pdfFile,
                ppSaveAsPDF 
                );              
    Dispatch.call(ppt, "Close");        
    app.invoke("Quit");

this cannot works in tomcat windows installer Distribution, but can work in tomcat zip Distribution. What's the problem?

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo After tapping button to hit second screen activity

Trying to make a memory matching game with a grid of ImageButtons that change to an image after tapping, I can't get the second screen activity to start. It crashes and gives me the logs I posted below. I also attached my manifest, and activity for the second screen.I know that the second screen activity worked when I don't have the buttons initialized globally and comment out the functions. I am a begginner please help!

Android manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
    package="eagle.abhishekravi.abhishek.eagle" >

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".secondScreen"
        android:label="Operation"
        android:theme = "@style/AppTheme">

        </activity>
</application>

</manifest>

MainActivity

public void Secondscreen(View view) {

    Intent getNameScreenIntent;
    getNameScreenIntent = new Intent(this, secondScreen.class);
    startActivity(getNameScreenIntent);
    //finish();


}

SecondScreen

package eagle.abhishekravi.abhishek.eagle;




public class secondScreen extends Activity implements View.OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.layout);
    Intent activityThatCalled = getIntent();
    Collections.shuffle(Arrays.asList(res));
    iconRandomizer();



};
//initialize all buttons in game
ImageButton b1 = (ImageButton) findViewById(R.id.b1);
ImageButton b2 = (ImageButton) findViewById(R.id.b2);
ImageButton b3 = (ImageButton) findViewById(R.id.b3);
ImageButton b4 = (ImageButton) findViewById(R.id.b4);
ImageButton b5 = (ImageButton) findViewById(R.id.b5);
ImageButton b6 = (ImageButton) findViewById(R.id.b6);
ImageButton b7 = (ImageButton) findViewById(R.id.b7);
ImageButton b8 = (ImageButton) findViewById(R.id.b8);
ImageButton b9 = (ImageButton) findViewById(R.id.b9);
ImageButton b10 = (ImageButton) findViewById(R.id.b10);
ImageButton b11 = (ImageButton) findViewById(R.id.b11);
ImageButton b12 = (ImageButton) findViewById(R.id.b12);
ImageButton b13 = (ImageButton) findViewById(R.id.b13);
ImageButton b14 = (ImageButton) findViewById(R.id.b14);
ImageButton b15 = (ImageButton) findViewById(R.id.b15);
ImageButton b16 = (ImageButton) findViewById(R.id.b16);
ImageButton b17 = (ImageButton) findViewById(R.id.b17);
ImageButton b18 = (ImageButton) findViewById(R.id.b18);
ImageButton b19 = (ImageButton) findViewById(R.id.b19);
ImageButton b20 = (ImageButton) findViewById(R.id.b20);


//drawables
int res[] = new int[] {R.drawable.brownbars,R.drawable.centeredorangedot,     

R.drawable.dots, R.drawable.greenlines, R.drawable.lightbulb, 

R.drawable.orangedots, R.drawable.orangelines, R.drawable.tree,
R.drawable.yellow, R.drawable.yellowwithred};   

public void iconRandomizer() {




    b1.setOnClickListener(this);
    b2.setOnClickListener(this);
    b3.setOnClickListener(this);
    b4.setOnClickListener(this);
    b5.setOnClickListener(this);
    b6.setOnClickListener(this);
    b7.setOnclickListener(this);

}





public void onClick(View v){
    switch (v.getId()){
        case R.id.b1:
            b1.setImageResource(res[0]);
            break;
        case R.id.b2:
            b2.setImageResource(res[1]);
            break;
        case R.id.b3:
            b3.setImageResource(res[2]);
            break;
        case R.id.b4:
            b4.setImageResource(res[3]);
            break;
        case R.id.b5:
            b5.setImageResource(res[4]);
            break;
        case R.id.b6:
            b6.setImageResource(res[5]);
            break;
        case R.id.b7:
            b7.setImageResource(res[6]);
            break;
        case R.id.b8:
            b8.setImageResource(res[7]);
            break;
        case R.id.b9:
            b9.setImageResource(res[8]);
            break;
        case R.id.b10:
            b10.setImageResource(res[9]);
            break;
        case R.id.b11:
            b11.setImageResource(res[0]);
            break;
        case R.id.b12:
            b12.setImageResource(res[1]);
            break;
        case R.id.b13:
            b13.setImageResource(res[2]);
            break;
        case R.id.b14:
            b14.setImageResource(res[3]);
            break;
        case R.id.b15:
            b15.setImageResource(res[4]);
            break;
        case R.id.b16:
            b16.setImageResource(res[5]);
            break;
        case R.id.b17:
            b17.setImageResource(res[6]);
            break;
        case R.id.b18:
            b18.setImageResource(res[7]);
            break;
        case R.id.b19:
            b19.setImageResource(res[8]);
            break;
        case R.id.b20:
            b20.setImageResource(res[9]);
            break;
    }


}





}

How to write a piece of java code that will consume lots of memories and the memories can be released if needed

I wrote such a piece of code:

public class TestClass {
    private static List<String> stringList = new ArrayList<>();
    long num;

    public void testHighLoad() {

        stringList.clear();
        for (int i = 0; i < num; i++) {         
            String string = getRandomString(10000);
            stringList.add(string);
        }
    }

    public void setNum (int num) {
        this.num = num;
    }
 }

And I can call it like this to make it cost high memories:

testClass.setNum(500000);
testClass.testHighLoad();

But then if I call it in this way, it cannot release the memory:

testClass.setNum(0);
testClass.testHighLoad();

Same coordinates displayed even when element moving

Edit from my previous post (deleted) since I was wrong on the issue:

I use this code to display a grid (each box of the grid has an ID like A2,C8 etc) and to display the ID of each Box containing a fiducial marker (http://ift.tt/MyZNy5). I use the last if statement to verify if there is a fiducial marker or not in the box:

if( ( a>= x &&  a <= (x + videoScale)) && //check horizontal
        (b >= y &&  b <= (y + videoScale))){
    //coordinates are within a box, do something about it
    System.out.println(coordinates[k][l]); 
}

The console always displays "A0" when a fiducial is detected, even if it has never been placed in A0, or when it is moved elsewhere.

Here is the whole code:

import TUIO.*;
TuioProcessing tuioClient;

int cols = 15, rows = 15;
boolean[][] states = new boolean[cols][rows];
String[][] coordinates = new String[cols][rows]; 
int videoScale = 50;

// these are some helper variables which are used
// to create scalable graphical feedback
int x, y, i, j, k, l;
float cursor_size = 15;
float object_size = 60;
float table_size = 760;
float scale_factor = 1;
PFont font;

boolean verbose = false; // print console debug messages
boolean callback = true; // updates only after callbacks



void setup(){
    size(500,500);
    noCursor();

    noStroke();
    fill(0);

    // periodic updates
    if (!callback) {
        frameRate(60); //<>//
        loop();
    } else noLoop(); // or callback updates 

    font = createFont("Arial", 18);
    scale_factor = height/table_size;

    // finally we create an instance of the TuioProcessing client
    // since we add "this" class as an argument the TuioProcessing class expects
    // an implementation of the TUIO callback methods in this class (see below)
    tuioClient  = new TuioProcessing(this);

}
void draw(){
    // Begin loop for columns
    for ( k = 0; k < cols; k++) {
        // Begin loop for rows
        for ( l = 0; l < rows; l++) {

            // Scaling up to draw a rectangle at (x,y)
            int x = k*videoScale;
            int y = l*videoScale;

            fill(255);
            stroke(0);


            for (int i = 0; i < cols; i++) {
                for (int j = 0; j < rows; j++) { 

                    coordinates[i][j] = String.valueOf((char)(i+65)) + String.valueOf(j).toUpperCase();

                }
            }

            rect(x,y,videoScale,videoScale); 


            textFont(font,18*scale_factor);
            float obj_size = object_size*scale_factor; 
            float cur_size = cursor_size*scale_factor; 

            ArrayList<TuioObject> tuioObjectList = tuioClient.getTuioObjectList();
            for (int i=0;i<tuioObjectList.size();i++) {
                TuioObject tobj= tuioObjectList.get(i);
                stroke(0);
                fill(0,0,0);
                pushMatrix();
                translate(tobj.getScreenX(width),tobj.getScreenY(height));
                rotate(tobj.getAngle());
                rect(-20,-20,20,obj_size);
                popMatrix();
                fill(255);
                text(""+tobj.getSymbolID(), tobj.getScreenX(width), tobj.getScreenY(height));
                System.out.println(tobj.getSymbolID ()+ " " + tobj.getX());
                float a = tobj.getX ();
                float b = tobj.getY ();
                System.out.println(a + " " + b);

                if( ( a>= x &&  a <= x + videoScale) && //check horizontal
                        (b >= y &&  b <= y + videoScale)){
                    //coordinates are within a box, do something about it
                    System.out.println(coordinates[k][l]); 
                }
            } 
        }
        rect(x,y,videoScale,videoScale);
    }
}


// --------------------------------------------------------------
// called at the end of each TUIO frame
void refresh(TuioTime frameTime) {
    if (verbose) println("frame #"+frameTime.getFrameID()+" ("+frameTime.getTotalMilliseconds()+")");
    if (callback) redraw();
}

Does my statement seem wrong ?

Thanks for your help and for taking the time to read

How to add submenu to MenuItem

I'm trying to add submenu to a MenuItem which exists in a popup menu in system tray. Is there any way to achieve this? I've found some solutions about submenus but they use JMenuItem, and TrayIcon only accepts PopupMenu which only accepts MenuItems.

Trying to achieve this with MenuItem:

Image

imagehtmlemail sending as text/plain

we have some code that uses imagehtmlemail, from apache commons. From most machines it works perfectly, sends out a html email with an embedded image - but from some machines - with exactly the same code, exactly the same smtp server, and inside the same networks - it sends the multipart email as normal - but each of the parts is marked as text/plain - as opposed to having a text/html and text/plain section when it works. And of course the users get a page full of html markup as the result.

I can't see how this is possible. In code we are using setHtmlMsg of course - and from other machines the same code works - so it must be something environmental or configuration on the machine itself - but nothing I can determine. Any ideas of either what could be the problem, or what I should check?

Java constructor (anti-pattern) super-classing String

The intention of the following design is to allow String values to be (in effect) subclassed to enable a number of what would be conflicting constructor methods to be established (e.g. the method signatures would be the same even though the parameter names would be different).

Kindly consider the following design:

Id Interface (an empty - marker interface)

public interface Id {}

Classes Interface (an empty - marker interface)

public interface Classes {}

Title Interface (an empty - marker interface)

public interface Title {}

Tool Class

public Tool(Id id) throws Exception
{
    this.span = new Span();

    this.span.addAttribute(new Attribute(Attribute.ID, (String)((Object) id)));
}

public Tool(Classes classes) throws Exception
{
    this.span = new Span();
    this.span.addAttribute(new Attribute(Attribute.CLASS, (String)((Object) classes)));
}

public Tool(Title title) throws Exception
{
    this.span = new Span();
    this.span.addAttribute(new Attribute(Attribute.TITLE, (String)((Object) title)));
}

public Tool(Id id, Classes classes, Title title) throws Exception
{
    this.span = new Span();
    this.span.addAttribute(new Attribute(Attribute.ID, (String)((Object) id)));
    this.span.addAttribute(new Attribute(Attribute.CLASS, (String)((Object) classes)));
    this.span.addAttribute(new Attribute(Attribute.TITLE, (String)((Object) title)));
}

public void Test() throws Exception
{
    Tool hammer = new Tool((Id)((Object)"hammer"));
    Tool poweredTool = new Tool((Classes)((Object)"tool powered"));
    Tool tool = new Tool((Id)((Object)"invention"), (Classes)((Object)"tool powered"), (Title)((Object)"define a new tool"));
}

The approach requires an interface per parameter "type" and the down cast / up cast from the specific interface "type" to Object and then to String...

I am uncomfortable with the approach and I'm hoping that there's a design pattern out there that would alleviate my desire to subclass String (solely for the purpose of constructor method differentiation)...

I have a variadic method that takes an arbitrary collection of name value pairs to provide an alternative to the fixed parameter constructors, but the constructors shown above are the most common combinations and therefore as a convenience to the programmer they are presently being contemplated as being provided...

Thanks!

Write string value to the arduino or the serial port using java

I am trying to write string data to my serial port, but now I cannot write the string value to the arduino serial port. Can anyone help me to solve this.

This is my Java code:

portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
        portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            if (portId.getName().equals("COM9")) {
                try {
                    serialPort = (SerialPort)
                    portId.open("SimpleWriteApp", 2000);
                } catch (PortInUseException e) {
                    System.out.println("Error1 is "+ e);
                }
                try {
                    outputStream = serialPort.getOutputStream();
                } catch (IOException e) {
                    System.out.println("Error2 is "+ e);
                }
                try {
                    serialPort.setSerialPortParams(9600,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
                } catch (UnsupportedCommOperationException e) {
                    System.out.println("Error3 is "+ e);
                }
                try {
                    String number = "1";
                    byte arduino[] = number.getBytes();
                    for(int i=0; i<arduino.length; i++){
                        outputStream.write(arduino[i]);
                    }
                    outputStream.flush();
                } catch (IOException e) {
                    System.out.println("Error is4 "+ e);
                }

            }
        }
    }