mercredi 5 août 2015

java.lang.IllegalArgumentException: Can not handle managed/back reference


I am having the following entity relationship

@Entity
@Table(name = "PRODUCTS")
public class Product implements Serializable {

@Id
@Column(name = "prod_id", nullable = false)
private String prodId;

@Column(name = "prod_name")
private String prodName;

@JsonManagedReference("prods")
@ManyToOne
@JoinColumn(name = "prod_id", referencedColumnName = "prod_id")
private ProductDetail productDetail;

@Entity
@Table(name = "PRODUCT_DETAILS")
public class ProductDetail implements Serializable {

@Id
@Column(name="prod_id", nullable = false)
private String prodId;

@JsonBackReference("prods")
@OneToMany(mappedBy = "productDetail")
private List<Product> productList;

And in REST service, I have

@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/mypath")
public Object update(Product product)  {
    System.out.println("params "+product.getProdName());
    return json;
}   

When I invoke update method using REST, I am getting error

java.lang.IllegalArgumentException: Can not handle managed/back reference 'prods': back reference type (java.util.List) not compatible with managed type (test.entity.Product)

How can I resolve this issue?

Edit 1

I have tried using

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
property="prodId")

However this resulted in the following error

org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain:



via Chebli Mohamed

java applet slow on window 7 (64bit) machine


I am running java applet on windows 7 64bit (firefox 39.0). It take 10 second to load(showing java process icon meanwhile ) where as it take 1 second to run on window 8 64bit machine(firefox 39.0). it's also fine on 32(bit) window 7.

Why it is slow on window 7(64bit).



via Chebli Mohamed

jar not launching - UnsatisfiedLinkError


I have exported my java project into a jar in my desktop (chose the option that creates a project.jar and a project_lib).

When I run java -jar project.jar on cmd, I get this exception:

    Exception in thread "main" java.lang.RuntimeException: Application launch error
    at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:122)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.UnsatisfiedLinkError: com.sun.glass.ui.win.WinApplication._invokeLater(Ljava/lang/Runnable;)V
    at com.sun.glass.ui.win.WinApplication._invokeLater(Native Method)
    at com.sun.glass.ui.Application.invokeLater(Application.java:338)
    at com.sun.javafx.tk.quantum.QuantumToolkit.defer(QuantumToolkit.java:620)
    at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:173)
    at com.sun.javafx.application.PlatformImpl.runAndWait(PlatformImpl.java:212)
    at com.sun.javafx.application.PlatformImpl.tkExit(PlatformImpl.java:320)
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:421)
    at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
    at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
    ... 1 more

I guess it is probably caused by my project's paths but I don't know how to fix this.

EDIT: It works fine in eclipse and in my /Desktop directory. Everywhere else, this exception is thrown.

EDIT2: This is the MANIFEST.MF file built:

Manifest-Version: 1.0
Class-Path: . wfmgr_lib/jfxrt.jar wfmgr_lib/junit.jar wfmgr_lib/org.ha
 mcrest.core_1.3.0.v201303031735.jar wfmgr_lib/gson-2.3.1.jar
Main-Class: main.screens.ScreenFramework

EDIT3: I have both jdk 7 and 8 installed. I set up my eclipse project so its compliance level is java-7, building compatible code for the latter.

I also tried using launcher4J and it only worked (in any directory) with the following configurations:

launch4J.log:

    Version:    3.8
    CmdLine:    C:\Users\a51217\Desktop\wfmgr_final\wfmgrexe.exe --l4j-debug
    WOW64:      yes
    Working dir:    C:\Users\a51217\Desktop\wfmgr_final\.
    Bundled JRE:    C:\Program Files\Java\jre7
    Check launcher: C:\Program Files\Java\jre7\bin\javaw.exe (OK)
    Substitute: PATH = C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\AXALTO\Access Client\v5\;C:\Program Files (x86)\AXALTO\Access Client\v5\;C:\Program Files (x86)\Common Files\Check Point\UIFramework 3.0\Bin\;C:\Program Files (x86)\CheckPoint\Endpoint Security\Endpoint Common\bin;C:\Users\a51217\Downloads\jdk-8u51\bin;C:\Users\a51217\Downloads\mysql-5.6.25-winx64\mysql-5.6.25-winx64/bin;C:\Users\a51217\Downloads\apache-tomcat-8.0.24\apache-tomcat-8.0.24\bin;C:\Users\a51217\Downloads\apache-maven-3.3.3-bin\apache-maven-3.3.3\bin;C:\Program Files\Java\jre7\bin;C:\Program Files\Java\jre7\bin
    Substitute: JAVA_HOME = C:\Users\a51217\Downloads\jdk-8u51
    Substitute: C:\Program Files\Java\jre7\lib\jfxrt.jar = 
    Add classpath:  .
    Add classpath:  wfmgr_lib\jfxrt.jar
    Add classpath:  wfmgr_lib\junit.jar
    Add classpath:  wfmgr_lib\org.hamcrest.core_1.3.0.v201303031735.jar
    Add classpath:  C:\Program Files\Java\jre7\lib
    Add classpath:  C:\Program Files\Java\jre7\bin
    Launcher:   C:\Program Files\Java\jre7\bin\javaw.exe
    Launcher args:  -Denv.path="C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\AXALTO\Access Client\v5\;C:\Program Files (x86)\AXALTO\Access Client\v5\;C:\Program Files (x86)\Common Files\Check Point\UIFramework 3.0\Bin\;C:\Program Files (x86)\CheckPoint\Endpoint Security\Endpoint Common\bin;C:\Users\a51217\Downloads\jdk-8u51\bin;C:\Users\a51217\Downloads\mysql-5.6.25-winx64\mysql-5.6.25-winx64/bin;C:\Users\a51217\Downloads\apache-tomcat-8.0.24\apache-tomcat-8.0.24\bin;C:\Users\a51217\Downloads\apache-maven-3.3.3-bin\apache-maven-3.3.3\bin;C:\Program Files\Java\jre7\bin;C:\Program Files\Java\jre7\bin" -Denv.java.home="C:\Users\a51217\Downloads\jdk-8u51" -Denv.c:\program.files\java\jre7\lib\jfxrt.jar="" -classpath "C:\Users\a51217\Desktop\wfmgr_final\wfmgrexe.exe;.;wfmgr_lib\jfxrt.jar;wfmgr_lib\junit.jar;wfmgr_lib\org.hamcrest.core_1.3.0.v201303031735.jar;C:\Program Files\Java\jre7\lib;C:\Program Files\Java\jre7\bin" main.screens.ScreenFramework
    Args length:    1008/32768 chars
    Exit code:  0


    Version:    3.8
    CmdLine:    C:\Users\a51217\Desktop\wfmgr_final\wfmgrexe.exe --l4j-debug
    WOW64:      yes
    Working dir:    C:\Users\a51217\Desktop\wfmgr_final\.
    Bundled JRE:    C:\Program Files\Java\jre7
    Check launcher: C:\Program Files\Java\jre7\bin\javaw.exe (OK)
    Substitute: PATH = C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\AXALTO\Access Client\v5\;C:\Program Files (x86)\AXALTO\Access Client\v5\;C:\Program Files (x86)\Common Files\Check Point\UIFramework 3.0\Bin\;C:\Program Files (x86)\CheckPoint\Endpoint Security\Endpoint Common\bin;C:\Users\a51217\Downloads\jdk-8u51\bin;C:\Users\a51217\Downloads\mysql-5.6.25-winx64\mysql-5.6.25-winx64/bin;C:\Users\a51217\Downloads\apache-tomcat-8.0.24\apache-tomcat-8.0.24\bin;C:\Users\a51217\Downloads\apache-maven-3.3.3-bin\apache-maven-3.3.3\bin;C:\Program Files\Java\jre7\bin;C:\Program Files\Java\jre7\bin
    Substitute: JAVA_HOME = C:\Users\a51217\Downloads\jdk-8u51
    Substitute: C:\Program Files\Java\jre7\lib\jfxrt.jar = 
    Add classpath:  .
    Add classpath:  wfmgr_lib\jfxrt.jar
    Add classpath:  wfmgr_lib\junit.jar
    Add classpath:  wfmgr_lib\org.hamcrest.core_1.3.0.v201303031735.jar
    Add classpath:  C:\Program Files\Java\jre7\lib
    Add classpath:  C:\Program Files\Java\jre7\bin
    Launcher:   C:\Program Files\Java\jre7\bin\javaw.exe
    Launcher args:  -Denv.path="C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\AXALTO\Access Client\v5\;C:\Program Files (x86)\AXALTO\Access Client\v5\;C:\Program Files (x86)\Common Files\Check Point\UIFramework 3.0\Bin\;C:\Program Files (x86)\CheckPoint\Endpoint Security\Endpoint Common\bin;C:\Users\a51217\Downloads\jdk-8u51\bin;C:\Users\a51217\Downloads\mysql-5.6.25-winx64\mysql-5.6.25-winx64/bin;C:\Users\a51217\Downloads\apache-tomcat-8.0.24\apache-tomcat-8.0.24\bin;C:\Users\a51217\Downloads\apache-maven-3.3.3-bin\apache-maven-3.3.3\bin;C:\Program Files\Java\jre7\bin;C:\Program Files\Java\jre7\bin" -Denv.java.home="C:\Users\a51217\Downloads\jdk-8u51" -Denv.c:\program.files\java\jre7\lib\jfxrt.jar="" -classpath "C:\Users\a51217\Desktop\wfmgr_final\wfmgrexe.exe;.;wfmgr_lib\jfxrt.jar;wfmgr_lib\junit.jar;wfmgr_lib\org.hamcrest.core_1.3.0.v201303031735.jar;C:\Program Files\Java\jre7\lib;C:\Program Files\Java\jre7\bin" main.screens.ScreenFramework
    Args length:    1008/32768 chars
    Exit code:  0


    Version:    3.8
    CmdLine:    C:\Users\a51217\Desktop\wfmgr_final\wfmgrexe.exe --l4j-debug
    WOW64:      yes
    Working dir:    C:\Users\a51217\Desktop\wfmgr_final\.
    Bundled JRE:    C:\Program Files\Java\jre7
    Check launcher: C:\Program Files\Java\jre7\bin\javaw.exe (OK)
    Substitute: PATH = C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\AXALTO\Access Client\v5\;C:\Program Files (x86)\AXALTO\Access Client\v5\;C:\Program Files (x86)\Common Files\Check Point\UIFramework 3.0\Bin\;C:\Program Files (x86)\CheckPoint\Endpoint Security\Endpoint Common\bin;C:\Users\a51217\Downloads\jdk-8u51\bin;C:\Users\a51217\Downloads\mysql-5.6.25-winx64\mysql-5.6.25-winx64/bin;C:\Users\a51217\Downloads\apache-tomcat-8.0.24\apache-tomcat-8.0.24\bin;C:\Users\a51217\Downloads\apache-maven-3.3.3-bin\apache-maven-3.3.3\bin;C:\Program Files\Java\jre7\bin;C:\Program Files\Java\jre7\bin
    Substitute: JAVA_HOME = C:\Users\a51217\Downloads\jdk-8u51
    Substitute: C:\Program Files\Java\jre7\lib\jfxrt.jar = 
    Add classpath:  .
    Add classpath:  wfmgr_lib\jfxrt.jar
    Add classpath:  wfmgr_lib\junit.jar
    Add classpath:  wfmgr_lib\org.hamcrest.core_1.3.0.v201303031735.jar
    Add classpath:  C:\Program Files\Java\jre7\lib
    Add classpath:  C:\Program Files\Java\jre7\bin
    Add classpath:  C:\Program Files\Java\jre7\lib\jfxrt.jar
    Launcher:   C:\Program Files\Java\jre7\bin\javaw.exe
    Launcher args:  -Denv.path="C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\AXALTO\Access Client\v5\;C:\Program Files (x86)\AXALTO\Access Client\v5\;C:\Program Files (x86)\Common Files\Check Point\UIFramework 3.0\Bin\;C:\Program Files (x86)\CheckPoint\Endpoint Security\Endpoint Common\bin;C:\Users\a51217\Downloads\jdk-8u51\bin;C:\Users\a51217\Downloads\mysql-5.6.25-winx64\mysql-5.6.25-winx64/bin;C:\Users\a51217\Downloads\apache-tomcat-8.0.24\apache-tomcat-8.0.24\bin;C:\Users\a51217\Downloads\apache-maven-3.3.3-bin\apache-maven-3.3.3\bin;C:\Program Files\Java\jre7\bin;C:\Program Files\Java\jre7\bin" -Denv.java.home="C:\Users\a51217\Downloads\jdk-8u51" -Denv.c:\program.files\java\jre7\lib\jfxrt.jar="" -classpath "C:\Users\a51217\Desktop\wfmgr_final\wfmgrexe.exe;.;wfmgr_lib\jfxrt.jar;wfmgr_lib\junit.jar;wfmgr_lib\org.hamcrest.core_1.3.0.v201303031735.jar;C:\Program Files\Java\jre7\lib;C:\Program Files\Java\jre7\bin;C:\Program Files\Java\jre7\lib\jfxrt.jar" main.screens.ScreenFramework
    Args length:    1049/32768 chars
    Exit code:  0

image4j.xml

<?xml version="1.0" encoding="UTF-8"?>
-<launch4jConfig> <dontWrapJar>false</dontWrapJar> <headerType>gui</headerType> <jar>C:\Users\a51217\Desktop\wfmgr.jar</jar> <outfile>C:\Users\a51217\Desktop\wfmgr_final\wfmgrexe.exe</outfile> <errTitle/> <cmdLine/> <chdir>.</chdir> <priority>normal</priority> <downloadUrl>http://ift.tt/KJJukw; <supportUrl/> <stayAlive>false</stayAlive> <restartOnCrash>false</restartOnCrash> <manifest/> <icon/> -<classPath> <mainClass>main.screens.ScreenFramework</mainClass> <cp>.</cp> <cp>wfmgr_lib/jfxrt.jar</cp> <cp>wfmgr_lib/junit.jar</cp> <cp>wfmgr_lib/org.hamcrest.core_1.3.0.v201303031735.jar</cp> <cp>C:\Program Files\Java\jre7\lib</cp> <cp>C:\Program Files\Java\jre7\bin</cp> <cp>C:\Program Files\Java\jre7\lib\jfxrt.jar</cp> </classPath> -<jre> <path>C:\Program Files\Java\jre7</path> <bundledJre64Bit>true</bundledJre64Bit> <bundledJreAsFallback>false</bundledJreAsFallback> <minVersion>1.6.0</minVersion> <maxVersion>1.9.0</maxVersion> <jdkPreference>preferJre</jdkPreference> <runtimeBits>64/32</runtimeBits> <opt>-Denv.path="%PATH%"</opt> <opt>-Denv.java.home="%JAVA_HOME%"</opt> <opt>-Denv.c:\program.files\java\jre7\lib\jfxrt.jar="%C:\Program Files\Java\jre7\lib\jfxrt.jar%"</opt> </jre> -<messages> <startupErr>An error occurred while starting the application.</startupErr> <bundledJreErr>This application was configured to use a bundled Java Runtime Environment but the runtime is missing or corrupted.</bundledJreErr> <jreVersionErr>This application requires a Java Runtime Environment</jreVersionErr> <launcherErr>The registry refers to a nonexistent Java Runtime Environment installation or the runtime is corrupted.</launcherErr> <instanceAlreadyExistsMsg>An application instance is already running.</instanceAlreadyExistsMsg> </messages> </launch4jConfig>



via Chebli Mohamed

What happens to an event and the memory it uses when it's fired an no handler is registered?


What happens to a Reactor-EventBus event and especially the memory itself and its data payload use when it's fired and there's no handler registered?

Is it going to be disposed? Or will those Event objects be collected in the ringbuffer?

My guess is that it will be disposed, but I'd like to be sure about that.



via Chebli Mohamed

Cut string inside " "


Suppose i have a

  string [] tag;

Lets say

 for tag[0] = {["I","am","fine","thank","you"]}
     tag[1] = {["hello","world"]}

how can i get all string out from the above string?? i wanna get "I" , "hello" individually

also as a newbie, wanna know how can i display "
when i type " " " error appears



via Chebli Mohamed

Silently stopping Liquibase at mid-update


Is there any way I can cancel a Liquibase update after I started it?

I've a list with around 5000 changesets, and I need to prevent all changesets from a specific point forward, to not be executed if a specific condition occurs in one of those scripts.

Since putting < preConditions > in all of the existing scripts, and to all the new ones that will be created until the end of days, is not a doable approach, I was looking into an alternative and already tried the following:

  • Created a < customChange > and throw an exception
  • Created an invalid < sql > statement
  • Added < stop /> in the < changeset >

All cases work, but they also throw thousands of log lines (that I can't have), because I need a silent stop.



via Chebli Mohamed

Java: Using created string as loop parameter?


In short, the user will input a number (say 1 through 3). This will decide which range of numbers the loop should search through.

switch(input){
case 1:
    searchTerm = "i<10 && i>5";
case 2:
    searchTerm = "i>=10 && i<19";
case 3:
    searchTerm = "i>19 && i<24";
}
while(searchTerm){
    //some function
}


Is this possible? I I've not been able to find a way to use a string as search parameters.

EDIT: I don't think I did a very good job of explaining why I needed this. What is one to do if there are different numbers of parameters? For example:

case 1:
    searchTerm = "i<5"
case 2:
    searchTerm = "i>25 && i<29"
case 3:
    searchTerm = "(i<50 && i>25) && (i>55 && i<75)"
case 4:
    searchTerm = "(i<20 && i>15) && (i>300 && i<325) && (i>360 && i<380)

Then how does one do it? Multiple loops that call the same function?



via Chebli Mohamed

Intellij Idea hint: Condition is always false - can that be true here? (Java)


I have the following code:

public String testExitPoints() {
    boolean myBoolean = false;
    try {
        if (getBoolean()) {
            return "exit 1";
        }
        if (getBoolean()) {
            throw new RuntimeException();
        }
    } finally {
        myBoolean = true;
    }
    if (getBoolean()) {
        return "exit 2";
    }
    return "exit 3";
}

public static boolean getBoolean() {
    Random rand = new Random();
    return rand.nextInt() > 100;
}

Now IntelliJ idea gives me for the second and third invocation of getBoolean() the following hint:

Condition 'getBoolean()' is always 'false'

Now to my understanding, that is not true, since getBoolean() can either be true or false, depending on the generated random value. Am I missing something here, or is that a bug in IntelliJ Idea?



via Chebli Mohamed

A regex that matches all L3_SW_xxxx,where xxxx are numbers


I am trying to create a java regex that matches all the words from a string that start with L3_SW_ and end with a set of numbers.The regex i came up with only matches the first word in the string.I am trying to get all the matches,but I can't figure it out.

My regex is : (L3_SW_)\d+

String sample :L3_SW_NORM_92 - L3_SW_NORM_100 L3_SW_691, L3_SW_694 L3_SW_844, L3_SW_845

L3_SW_882, L3_SW_883, L3_SW_884 L3_SW_790, L3_SW_3014, L3_SW_3015

The result i am getting :L3_SW_691



via Chebli Mohamed

Select text of li elements through JQuery


How can I select the text from list elements through JQuery.I want the same functionality as that of .select() in javascript,but that is only applicable to editable text areas/input boxes, can someone guide me ,for the same functionality with list elements

I want the list text to be selected on click



via Chebli Mohamed

org.apache.axis2.AxisFault: The system is attempting to engage a module that is not available: addressing


Hi I need to execute a jar file, but when I am executing, I get this error. Some help? I was googling lot of hours, but I can't find a solution.

org.apache.axis2.AxisFault: The system is attempting to engage a module that is not available: addressing
at org.apache.axis2.engine.AxisConfiguration.engageModule(AxisConfiguration.java:584)
at org.apache.axis2.engine.AxisConfiguration.engageGlobalModules(AxisConfiguration.java:705)
at org.apache.axis2.deployment.DeploymentEngine.engageModules(DeploymentEngine.java:831)
at org.apache.axis2.deployment.FileSystemConfigurator.engageGlobalModules(FileSystemConfigurator.java:142)
at org.apache.axis2.context.ConfigurationContextFactory.createConfigurationContext(ConfigurationContextFactory.java:94)
at org.apache.axis2.context.ConfigurationContextFactory.createConfigurationContextFromFileSystem(ConfigurationContextFactory.java:210)
at es.spee.meyss.proveedorcentro.application.ws.impl.ProveedorCentroTFWSStub.getContextConfiguration(ProveedorCentroTFWSStub.java:189)
at es.spee.meyss.proveedorcentro.application.ws.impl.ProveedorCentroTFWSStub.<init>(ProveedorCentroTFWSStub.java:185)
at es.spee.meyss.proveedorcentro.application.ws.impl.ProveedorCentroTFWSStub.<init>(ProveedorCentroTFWSStub.java:198)
at es.spee.meyss.proveedorcentro.cliente.business.services.impl.ProveedorCentroSvcImpl.getProveedorCentroWS(ProveedorCentroSvcImpl.java:149)
at es.spee.meyss.proveedorcentro.cliente.business.services.impl.ProveedorCentroSvcImpl.validarObtenerDatosCentro(ProveedorCentroSvcImpl.java:193)
at es.spee.meyss.proveedorcentro.cliente.business.services.impl.ProveedorCentroSvcImpl.validarObtenerDatosCentro(ProveedorCentroSvcImpl.java:170)
at es.spee.meyss.proveedorcentro.validador.ProveedorCentroTFValidador.validarObtenerDatosCentro(ProveedorCentroTFValidador.java:159)
at es.spee.meyss.proveedorcentro.validador.ProveedorCentroTFValidador.main(ProveedorCentroTFValidador.java:49)



via Chebli Mohamed

SwipeView change the content of 2 pages


I'm new to android programming

I've created a new activity with swipe views, and added some code.

I have now two swipeable pages, but with the same content, how can i change the content of the second swipe page.

Do I have to create a new activity or just to redirect it to another xml?

import java.util.Locale;

import android.graphics.Bitmap;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;


public class ListItemClicked extends ActionBarActivity {

static Bundle extras;

SectionsPagerAdapter mSectionsPagerAdapter;
static ImageLoader imageLoader;
static DisplayImageOptions options;




ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_item_clicked);


    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    extras = getIntent().getExtras();

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    //Setup the ImageLoader, we'll use this to display our images
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
    imageLoader = ImageLoader.getInstance();
    imageLoader.init(config);

    //Setup options for ImageLoader so it will handle caching for us.
    options = new DisplayImageOptions.Builder()
            .cacheInMemory()
            .cacheOnDisc()
            .build();

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main_activity2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    return id == R.id.action_settings || super.onOptionsItemSelected(item);

}



public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
            case 0:
                return getString(R.string.title_section4).toUpperCase(l);
            case 1:
                return getString(R.string.title_section5).toUpperCase(l);
        }
        return null;
    }
}


public static class PlaceholderFragment extends Fragment {


    private static final String ARG_SECTION_NUMBER = "section_number";


    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {

        View rootView = inflater.inflate(R.layout.fragment_list_item_clicked, container, false);


        TextView pDate = (TextView) rootView.findViewById(R.id.textView);
        pDate.setText( extras.getString("pdate") );


        TextView ptitle = (TextView) rootView.findViewById(R.id.section_label);
        ptitle.setText(extras.getString("pname"));


        TextView pnText = (TextView) rootView.findViewById(R.id.textView2);
        pnText.setText( extras.getString("pText"));




        //Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
        ImageLoadingListener listener = new ImageLoadingListener(){



            @Override
            public void onLoadingStarted(String arg0, View arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onLoadingCancelled(String arg0, View arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
                // i/ndicator.setVisibility(View.INVISIBLE);
               // iconImg.setVisibility(View.VISIBLE);
            }
            @Override
            public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
                // TODO Auto-generated method stub

            }

        };

        //Load the image and use our options so caching is handled.
        final ImageView iconImg = (ImageView) rootView.findViewById(R.id.imageView);
        imageLoader.displayImage( extras.getString("pImage"), iconImg, options, listener);



        return rootView;
    }
}

}

thanks!



via Chebli Mohamed

Internet explorer : Authentication with a smart card


I am using windows/Internet explorer. What are the steps to create an html page for authentication using a smart card. Is there any middleware/active X needed ? And if so, how can one use it to authenticate and get informations about the card holder ?

Thank you



via Chebli Mohamed

What should pe POJO for given JSON


I am integrating 3rd party REST API.I have written pojo for given json. Form 3rd party I am getting response in form of json as

"custom_fields": {
            "Field_68092": {
                "type": "char", 
                "required": true, 
                "value": "1", 
                "label": "orderId"
            }
        }

I tried with following POJO

public class Field_68092 {
    private String type;
    private String value;
    private String label;
    private boolean required;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public boolean isRequired() {
        return required;
    }

    public void setRequired(boolean required) {
        this.required = required;
    }
}

and custom filed's pojo is

public class Custom_fields {
    private Field_68092 Field_68092;

    public Field_68092 getField_68092() {
        return Field_68092;
    }

    public void setField_68092(Field_68092 field_68092) {
        Field_68092 = field_68092;
    }
}

Field_68092 every time coming null. can some one help me to find ut what is wrong with POJO structure?



via Chebli Mohamed

Dynamically change Logback level for web app running on tomcat


I have a logback.xml in the resources folder of my java web application which is running on Tomcat 7. Is there a way to change the debug level of some class of the application dynamically as the application is running?

The standard thing to do it is a normal java jar running from the CLI is to just edit logback.xml with say vim and after a while the log is updated. Is this possible with tomcat as I tried it and id does not seem to work.

Is there any better way?



via Chebli Mohamed

Maven 4.0.0 Swagger 1.3.12 build fails


I'm trying to get maven to build with swagger. But I get this error:

Failed to execute goal com.github.kongchen:swagger-maven-plugin:2.3.4:generate (default) on project web: Execution default of goal com.github.kongchen:swagger-maven-plugin:2.3.4:generate failed: An API incompatibility was encountered while executing com.github.kongchen:swagger-maven-plugin:2.3.4:generate: java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/LockModeType

The pom.xml dependency:

    <dependency>
        <groupId>com.wordnik</groupId>
        <artifactId>swagger-annotations</artifactId>
        <scope>compile</scope>
        <version>1.3.12</version>
        <exclusions>
            <exclusion>
                <groupId>javax.ws.rs</groupId>
                <artifactId>jsr311-api</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

The pom.xml Plugin:

<plugin>
            <groupId>com.github.kongchen</groupId>
            <artifactId>swagger-maven-plugin</artifactId>
            <version>2.3.4</version>
            <configuration>
                <apiSources>
                    <apiSource>
                        <supportSpringMvc>false</supportSpringMvc>
                        <locations>package.rest</locations>
                        <apiVersion>0.1</apiVersion>
                        <basePath>/api</basePath>
                        <outputTemplate>${basedir}/swaggerTempl/strapdown.html.mustache</outputTemplate>
                        <mustacheFileRoot>${basedir}/swaggerTempl</mustacheFileRoot>
                        <outputPath>${project.build.directory}/swaggerFolder/document.html</outputPath>
                        <swaggerDirectory>${project.build.directory}/swaggerFolder</swaggerDirectory>
                    </apiSource>
                </apiSources>
            </configuration>
            <executions>
                <execution>
                    <phase>compile</phase>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

Can anyone help me? What do I have to change to build it correctly? Do I have to install swagger on my PC? These folders don't exist, do I have to create them or should maven/swagger do it automatically?:

${basedir}/swaggerTempl/strapdown.html.mustache

${basedir}/swaggerTempl



via Chebli Mohamed

ASTRewrite for a QuickFix: How to position the cursor?


I work on a Eclipse Plugin and create a QuickFix using ASTRewrite. Briefly it's constructed in the following way:

public class MyQFXProcessor implements IQuickFixProcessor {
    public IJavaCompletionProposal[] getCorrections(IInvocationContext context,
                                                    IProblemLocation[] locations) {
        AST ast = context.getASTRoot().getAST();
        ASTRewrite rw = ASTRewrite.create(ast);
        ASTNode replacement = astRoot.getAST().newSimpleName("Test");
        rewrite.replace(context.getCoveringNode(), replacement);
        IJavaCompletionProposal p = new ASTRewriteCorrectionProposal("My QFX",
                                                     context.getCompilationUnit(), rw, 10);
        return new IJavaCompletionProposal[]{p};
    }
}

This works fine so far. But what I didn't manage to achieve yet is to set the desired cursor position after the proposal is applied. For example this is how it's solved in JDT for add argument quick fix:

enter image description here

enter image description here

I think there should be an API for doing that, because Eclipse uses this kind of behavior for different use-cases (in auto-completion among others). Does anybody have an idea how to implement that?



via Chebli Mohamed

Inject Spel parameter on annotation parameter (like what is done with @Value on a field)


I'm using this annotation provided by spring-starter-elastic-searchto create a document and I would like to inject the parameter indexname dynamically:

@Entity
@Document(indexName = "myindex")
public class StockQuotation 

In another bean I have successfully done that by using @Valueon a field:

@Value("${elasticsearch.index.name}")
public String indexName;

However, I have tried to inject it in the same way in the annotation and the translation is not done:

@Entity
@Document(indexName = "${elasticsearch.index.name}")
public class StockQuotation

As I get this exception:

Caused by: org.elasticsearch.indices.IndexMissingException: [${elasticsearch.index.name}] missing

What would be the appropriate approach to do this?

Thanks



via Chebli Mohamed

Custom extended Android DatePickerDialog without title


I've an extended DatePickerDialog, but I'm not able to hide the title (on 5.+).

I tried the requestWindowFeature function on some places, but I don't know where the right is.

public MyDatePickerDialog(Context context, OnDateSetListener listener, Reklamation reklamation, int year, int monthOfYear, int dayOfMonth) {
    super(context, listener, year, monthOfYear, dayOfMonth);
    // Check if we're running on Android 5.0 or higher
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Log.d(getClass().getSimpleName(), "noTitle:" + requestWindowFeature(Window.FEATURE_NO_TITLE));
    }
}



via Chebli Mohamed

Spring declaration for interfaces with the same implementation


I have a problem with Spring.

I have two separate interfaces, findUnconditionalDiscountValuesStrategy and findConditionalDiscountValuesStrategy. These interfaces are implemented in the same class MmfgFindPricingWithCurrentPriceFactoryStrategy.

This is declared in the spring configuration file like this:

<alias name="mmfgFindPricingWithCurrentPriceFactoryStrategy" alias="currentFactoryFindPricingStrategy"/>
<bean id="mmfgFindPricingWithCurrentPriceFactoryStrategy" class="com.mmfg.mmfgacceleratorcore.order.strategies.calculation.impl.MmfgFindPricingWithCurrentPriceFactoryStrategy" parent="abstractBusinessService">
    <property name="findPricingWithCurrentPriceFactoryStrategy" ref="original-currentFactoryFindPricingStrategy"/>
    <property name="configurationService" ref="configurationService"/>
    <property name="mmfgSessionService" ref="mmfgSessionService"/>
    <property name="mmfgUtilsDao" ref="mmfgUtilsDao" />
</bean>

Now, I use the two interfaces in a class

private FindUnconditionalDiscountValuesStrategy findUnconditionalDiscountValuesStrategy;
private FindConditionalDiscountValuesStrategy findConditionalDiscountValueStrategy;

with getter and setter (getter protected and setter @Required).

Now I have declared this class in this way in the spring configuration file:

<bean id="mmfgOrderCalculationStrategy" class="com.mmfg.mmfgacceleratorcore.order.strategies.calculation.impl.DefaultMmfgOrderCalculationStrategy">
    <property name="findUnconditionalDiscountValuesStrategy" ref="currentFactoryFindPricingStrategy"/>
    <property name="findConditionalDiscountValuesStrategy" ref="currentFactoryFindPricingStrategy"/>
    <property name="modelService" ref="modelService" />
    <property name="commonI18NService" ref="commonI18NService" />
    <property name="calculationService" ref="calculationService"/>
</bean>

the ref is the same for the two interfaces, because the implementation class is the same.

But at runtime I obtain this error:

org.springframework.beans.factory.BeanInitializationException: Property 'findConditionalDiscountValueStrategy' is required for bean 'mmfgOrderCalculationStrategy'

How I have to declare the ref in the two properties?



via Chebli Mohamed

Impact of Daemon Thread Or Normal Thread When Application is Running in Development mode


What is the impact for using Daemon threads or Normal Threads in my Play Application. I am having some Akka Scheduler, and Quarts Schedulers. These are being start When Application start. My App is running in Dev mode, and whenever i made changes to my Source Code, it restart's / Auto Reload application that Cause Thread DeadLock. What is the best way to stopping these Threads.

  1. Is it good to use Daemon Threads here ?
  2. Will System.exit(0) will be Useful here ?
  3. Is any Other way to stopping these running/waiting threads that are sleeping for a particular time in scheduling ?

I'm trying to do something like:

Akka.system().scheduler().schedule(Duration.create(2000, TimeUnit.MILLISECONDS), Duration.create(60000, TimeUnit.MILLISECONDS),
                () -> {
                    String url = Play.application().configuration().getString("localloadbalancer.ip");
                    url = url + "initCallOut";
                    Logger.info("Calling initcall from global.java::" + url);
                    HttpClient client = HttpClientBuilder.create().build();
                    HttpGet request = new HttpGet(url);
                    try {
                        HttpResponse response = client.execute(request);
                        int statusCode = response.getStatusLine().getStatusCode();
                        Logger.info("Status Code::" + statusCode);
                        if (statusCode == 200) {
                         //   Do stuff here
                        } else {
                         //    retry
                        }
                    } catch (IOException ex) {
                        Logger.error("Error in Initcall::" + ex.getMessage());
                    }
                }, Akka.system().dispatcher());

// Quartz scheduler starting here

   try {
     QuartzScheduler.startScheduler();
   }
   catch (Exception ex){
     System.out.println("Scheduler Exception::"+ex.getMessage());
   }



via Chebli Mohamed

Understanding Java code and make it jQuery. (loginpage)


I'm trying to understand a login-procedure to a balance-only login page at a bank. There is already a project that has the procedure in Java, but i'm not too familiar with it so I cant fully understand it. (http://ift.tt/1IkcNmO)

I would like to make it in jQuery.

My attempt is:

<html>
<head>
<script src="http://ift.tt/1HheyD3"></script>
</head>
<script>
var user_id="8311117173";
var password="secret";
var pemUrl="http://ift.tt/1IkcNmQ";
var loginUrl="http://ift.tt/1IkcPuY";
var epochTime=Date.now();
$.ajax({
    async: false,
    cache: false,
    type: 'post',
    data: ({
        'p_tranid':epochTime,
        'p_errorScreen':'LOGON_REPOST_ERROR',
        'n_bank':'',
        'empty_pwd':'',
        'username': user_id,
        'password': password
    }),
    url: loginUrl,
    success: function (response) {
        console.log(response);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(XMLHttpRequest.responseText);
        console.log(XMLHttpRequest);
        console.log(textStatus);
        console.log(errorThrown);
    }
});
</script>
</html>

The response should include "LOGON_OK", but it does not.

I've seen that in the Java-code, there is something about a certificate-file (http://ift.tt/1KQ3lv4) The code that I'm talking about is below. What is the procedure that I'm missing?

protected LoginPackage preLogin() throws BankException, IOException {
    urlopen = new Urllib(context, CertificateReader.getCertificates(context, R.raw.cert_okq8));
    Date d = new Date();
    List<NameValuePair> postData = new ArrayList<NameValuePair>();
    response = urlopen
            .open("http://ift.tt/1IkcNmQ");
    //p_tranid is the epoch time in milliseconds
    postData.add(new BasicNameValuePair("p_tranid", Long.toString(d.getTime())));
    postData.add(new BasicNameValuePair("p_errorScreen", "LOGON_REPOST_ERROR"));
    postData.add(new BasicNameValuePair("n_bank", ""));
    postData.add(new BasicNameValuePair("empty_pwd", ""));
    postData.add(new BasicNameValuePair("user_id", getUsername().toUpperCase()));
    postData.add(new BasicNameValuePair("password", getPassword()));
    return new LoginPackage(urlopen, postData, response,
            "http://ift.tt/1IkcPuY");
}



via Chebli Mohamed

Why is one TimerTask slowing down another?


I have got a Timer Task, which updates all player positions:

public void run(){
    {updateWatcher = new TimerTask() {
        public void run() {
            update(0.1);
        }
    };

    t.scheduleAtFixedRate(updateWatcher, 5, 5);}

And I also have another TimerTask right under that one, which updates all projectile positions:

UpdateWatcher = new TimerTask() { //Different variable. Note the capital U.
        public void run() {
            for (Bullet b : bullets){
                b.update();
            }
        }
    };
    t.scheduleAtFixedRate(UpdateWatcher, 5, 5);
}

However, the second TimerTask is slowing down the first one. If I delete the iteration, like this:

UpdateWatcher = new TimerTask() {
        public void run() {

        }
    };
    t.scheduleAtFixedRate(UpdateWatcher, 5, 5);
}

The player moves at the correct speed. However, as soon as I re-add the code (using Eclipse de-bugging to add it live), the delayed task executes a lot less often, causing players to be moving more than 10 times slower than usual.

What could be causing this, and how could I fix it?



via Chebli Mohamed

Ran into error "If a class has @XmlElement property, it cannot have @XmlValue property."


I know this looks like a common issue and I looked through sf but it'd appear that not many of the cases fit my shoe.

In my case, it's about the two forms of data under one xsd definition.

XSD:

  <xs:element name="Person">
    <xs:complexType mixed="true">
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element ref="name"/>
        <xs:element ref="address1"/>
        <xs:element ref="address2"/>
        <xs:element ref="address3"/>
      </xs:choice>
      <xs:attribute name="Key" type="xs:NCName"/>
    </xs:complexType>
  </xs:element>

And the xml based on it has two types of data:

1

<Person Key="Y">some name</Person>

2.

<Person>
<name>some name</name>
<address1>some where</address1>
<address2>some road</address2>
<address3>some house</address3>
</Person>

So if I use Eclipse to generate the java bean it would look like this:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "content"
})
@XmlRootElement(name = "Person")
public class Person{

    @XmlElementRefs({
        @XmlElementRef(name = "name", type = JAXBElement.class, required = false),
        @XmlElementRef(name = "address1", type = JAXBElement.class, required = false),
        @XmlElementRef(name = "address2", type = JAXBElement.class, required = false),
        @XmlElementRef(name = "address3", type = JAXBElement.class, required = false)
    })
    @XmlMixed
    protected List<Serializable> content;
    @XmlAttribute(name = "Key")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NCName")
    protected String key;

It will work without any errors whatsoever, but in a very ugly way since all the string attributes like name and address will be wrapped up as a Serializable/JAXBElement, which is really unnecessary in my opinion.

So I tried to modify the xsd by:

  1. change <xs:choice> to <xs:sequence>;
  2. Removed mixed = "true".

    Just to get a normal java bean with attributes like this:

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "name",
        "address1",
        "address2",
        "address3"
    }) @XmlRootElement(name = "Person")
        public class Person{
    
            @XmlElement(name = "name", required = true)
            protected String name;
            @XmlElement(name = "address1", required = true)
            protected String address1;
            @XmlElement(name = "address2", required = true)
            protected String address2;
            @XmlElement(name = "address3", required = true)
            protected String address3;
            @XmlAttribute(name = "Key")
            @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
            @XmlSchemaType(name = "NCName")
            protected String key;
    
    

As expected, the 1st type of data <Person Key="Y">some name</Person> wouldn't be able to get content "some name" as the java bean does not contain attribute "content" anymore.

But When I manually added "content" with annotation @XmlValue, it threw the error "If a class has @XmlElement property, it cannot have @XmlValue property."

So finally I get to my question:), to work in a more elegant way as I proposed, what can we do here?



via Chebli Mohamed

How to add html/js query to gwt app using gwt-rpc?


We have a web client built with GWT that talks to a server via gwt-rpc. One part of the app will now use html/js to replace the GWT GUI and we want that part to talk to the server but not via gwt-rpc. What ways are there to migrate a gwt-rpc call to something that will work with a none a gwt client? Today we send and receive java collections that contain object graphs like a list of order objects that have them self order detail objects and so on.

Thanks



via Chebli Mohamed

I want to enter one by one lettter of a string into textarea with some time delay between the entering of the characters in selenium webdriver


I have a string = "AOl_Db_View" and I want to enter all the characters of the string into a textarea field on a web page.

Also there should be time delay of 3 sec while entering the characters into the text area



via Chebli Mohamed

Magnolia 5.4 upgrade java.nio.file.InvalidPathException on publishing/unpublishing


When I tried to upgrade to magnolia 5.4 from 5.3.9 or download magnolia bundle with tomcat from official website and just run it, on publishing/unpublishing I receive:

Exception in thread "Thread-68" java.nio.file.InvalidPathException: Illegal char <:> at index 48: C:\dev\apache-tomcat-8.0.21\webapps\mg-auth\/jcr:system/jcr:versionStorage/af/72/95/af72957c-bb65-4132-881c-205eee9e68f3/1.12
    at sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
    at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94)
    at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255)
    at java.nio.file.Paths.get(Paths.java:84)
    at info.magnolia.resourceloader.file.FileSystemResourceOrigin.getPath(FileSystemResourceOrigin.java:241)
    at info.magnolia.resourceloader.file.FileSystemResourceOrigin.hasPath(FileSystemResourceOrigin.java:139)
    at info.magnolia.resourceloader.util.Functions$1.apply(Functions.java:60)
    at info.magnolia.resourceloader.util.Functions$1.apply(Functions.java:57)
    at com.google.common.collect.Iterators$7.computeNext(Iterators.java:652)
    at com.google.common.collect.AbstractIterator.tryToComputeNext(AbstractIterator.java:143)
    at com.google.common.collect.AbstractIterator.hasNext(AbstractIterator.java:138)
    at com.google.common.collect.TransformedIterator.hasNext(TransformedIterator.java:43)
    at com.google.common.collect.Iterators.addAll(Iterators.java:361)
    at com.google.common.collect.Lists.newArrayList(Lists.java:160)
    at com.google.common.collect.Lists.newArrayList(Lists.java:144)
    at info.magnolia.resourceloader.layered.LayeredResourceOrigin.getByPath(LayeredResourceOrigin.java:96)
    at info.magnolia.resourceloader.layered.RelayerResourceVisitor.visitFile(RelayerResourceVisitor.java:60)
    at info.magnolia.resourceloader.jcr.JcrResourceOrigin$1.onEvent(JcrResourceOrigin.java:330)
    at info.magnolia.cms.util.ObservationUtil$ObservationBasedDelayedExecutor$1.run(ObservationUtil.java:253)
    at info.magnolia.cms.util.DelayedExecutor$RunnableWrapper.run(DelayedExecutor.java:103)
    at EDU.oswego.cs.dl.util.concurrent.ClockDaemon$RunLoop.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:745)

I am very puzzled by the path structure and by the reason why the resource loader tries to resolve this path.



via Chebli Mohamed

SMTP not getting connected


Here is my java code to send email, whenever i run the code it shows javax.mail.MessagingException: Could not connect to SMTP host: ipaddress, port: 25; I even tried changing the port number, still same error.. can anyone help me.. (i have included mail.jar and activation.jar to project)

public static void main(String arfs[]) throws UnknownHostException
{
    InetAddress address = InetAddress.getLocalHost(); 
                 String to="gggg@gmail.com";
                String from="vvvvv@gmail.com";
                String host=address.getHostAddress();

                Properties properties = System.getProperties();  
                properties.setProperty("mail.smtp.host",host);
                properties.setProperty("mail.smtp.port", "25");
                Session session = Session.getDefaultInstance(properties);  

                try{  
                     MimeMessage message = new MimeMessage(session);  
                     message.setFrom(new InternetAddress("vvvv@gmail.com"));  
                     message.addRecipient(Message.RecipientType.TO,new InternetAddress("ggggg@gmail.com"));  
                     message.setSubject("test email");  
                     message.setText("hello");  
                     Transport.send(message);  
                     System.out.println("message sent successfully....");  

                    }
                catch(MessagingException mex)
                {
                    mex.printStackTrace();
                }

        }



via Chebli Mohamed

How Can I extract the .dat file(contain image) using java API


if i using HMEFContentsExtractor in POI jar, it can extract html only it is not able extract the image content form winmail.dat(attchment mail sent from oulook), is there any jar file to do this & explain how to use that.

   HMEFContentsExtractor ext = new HMEFContentsExtractor(new File(winmailFilename));
   File dir = new File(directoryName);
   File rtf = new File(dir, "message.rtf");
   if(! dir.exists()) {
       throw new FileNotFoundException("Output directory "+dir.getName()+" not found");   }
   HMEFMessage msg = new HMEFMessage(new FileInputStream(winmailFilename));
   msg.getAttachments();ext.extractMessageBody(rtf);



via Chebli Mohamed

Dsiable Cache Abstraction from Code Based upon Some Configuration parameters


I am using Redis cache abstraction in my Spring boot application. Going through many things i have come to one requirement , I want to make Caching enable or disable based upon some configuration. following is the code where i use cache:

@Override
@Cacheable(value = IC_CACHE, key = "#id")
public IssueCategory getIssueCategoriesById(Integer id) {
    return issueCategoriesRepo.findById(id);
}

And here is how i configure it:

  @Bean
public RedisConnectionFactory redisConnectionFactory(@Value("${redis.host}") String redisHost,
        @Value("${redis.port}") Integer redisPort) {
    JedisConnectionFactory cf = new JedisConnectionFactory();
    cf.setHostName(redisHost);
    cf.setPort(redisPort);
   return cf;
}

@Bean(name = "redisTemplate")
RedisTemplate<Object,Object> redisTemplate() {
    final RedisTemplate<Object,Object> template = new RedisTemplate<Object,Object>();
    template.setConnectionFactory(applicationContext.getBean(RedisConnectionFactory.class));
    return template;
}

@Bean
public CacheManager cacheManager() {
    RedisCacheManager redisCacheManager = new PieRedisCacheManager(
            (RedisTemplate<?, ?>) applicationContext.getBean("redisTemplate"));
    redisCacheManager.setUsePrefix(true);
    return redisCacheManager;
}

Say I have a variable in properties file which says :

rediscache=disable

Is there a way to disable cache at all based upon that configuration??

so that In the first code where i use @cacheable, code should directly get data from database

Please Advice.



via Chebli Mohamed

New to Java: Install Gson from Github?? Eclipse


I'm just starting to learn Java and I need Gson for a new project that I'm working on.

I feel like I'm missing something with all the installation instructions that I find online--all of them refer to three jar files that I should be able to extract from a zip file. But when I look at Gson on github i can't find any .jar files!

http://ift.tt/1JGQnf8

Once I find the jar files, I'm just supposed to include them in the buildpath for the project I'm working on right?

I'm working on this project using Eclipse.

Can someone help me with a very simple step-by-step explanation of how to start including these libraries for a complete noob to programming like me?

Also, once I include the .jar files in the buildpath for a project, can I just call the functions?

THANKS!



via Chebli Mohamed

Merging two sorted Arraylists into one sorted Arraylist


My code should merge two already sorted arraylists into one sorted arraylist and if one of the arraylists used is not sorted then it should return null.

public class MergeSorted {
public static void merge(ArrayList<Integer> a, ArrayList<Integer> b) {

    for (int i = 0, j = 0; j < b.size(); i++) {
        if (i == a.size() || a.get(i) > a.get(j)) {
            a.add(i, b.get(j++));
        }
    }
}  
}

This is what I attempted but can't get the idea of returning null if they are not equal, Im new to java and this is my second week so please be patient with me. I know I should have an if statement checking if they are sorted and an else but what should I include inside the if?



via Chebli Mohamed

Java - PKCS7 without external libraries


How can I create an encrypted container PKCS#7 withoud using BouncyCastle or another libraries? Container should contain the signature and should not contain certification chain. Data compression and encryption are not used. Container must be encoded in PEM format (OpenSSL).

I tried the code from this link: http://ift.tt/1N9rDO4 but it didn't worked as I expected - I can't see the original message when I use Base64 decoding on it's content (I have an example of correct PKCS#7 and I can take the original message from it).

Maybe I just need to change some operations in the code from link, I tried something with AlgorithmId's, but it didn't worked out.

Thanks!



via Chebli Mohamed

XPath contains returning IndexOutOfBounds Exception


I am new to Xpath. What is the following piece of code checking for ? Does it check for both these class "a b" when retrieving span elements.

HtmlSpan resultsSpan =  (HtmlSpan) page.getByXPath("//span[contains(@class,'a b')]").get(0);

Thanks



via Chebli Mohamed

Hibernate entity virtual column error?


I have defined a virtual column distanceInKm in my Entity for some distance calculation and giving response to the user along with distanceInKm which is a virtual column not a column in my table,and it's working well (case 1).

now am using the same entity for fetching all the values from the table but am getting com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'restaurant0_.distanceInKm' in 'field list'.(case 2)

I came to know the usage of @Transiant annotation for virtual columns which is used for calculation.but if am using that the virtual column will not be serialized/added to user response in (case 1).i need to implement both the API ie , Case 1 & Case 2 by using one entity

 @Entity
    @Table(name = "restaurants")
    public class Restaurants implements Serializable {

        private static final long serialVersionUID = 1L;

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "restaurant_id")
        private int restaurantId;

        @Column(name = "restaurant_name")
        private String restaurantName;

        @Column(name = "category_id")
        private Integer categoryId;

        @Column(name = "image_url")
        private String imageUrl;

        private Float longitude;

        private Float latitude;

        @Column(name = "contact_name")
        private String contactName;

        @Column(name = "primary_phone")
        private String primaryPhone;

        @Column(name = "secondary_phone")
        private String secondaryPhone;

        private String fax;

        private String address1;

        private String address2;

        @Column(insertable = false, updatable = false)
        private String distanceInKm;/*Virtual column*/

}

Help is appreciated.



via Chebli Mohamed

How to bump a version to a module and its dependents in Maven


I have a multimodule project where some modules depends on others:

This is a example dependency tree of submodules in my project.

mycompany:dependency1
            \
          mycompany:dependency2
                      \
                    mycompany:dependency3

I need to bump the version number to dependency3, then update dependency2 pom with the new version of dependency3. Since dependency2 has changed I need to bump it too, and repeat these changes recursively to the root.

Notice that I don't want to bump all submodules of a project, just one of them and its dependents

I have tried mvn versions plugin:

mvn versions:set -DnewVersion=1.0.1 -DgroupId=mycompany -DartifactId=dependency3

But it just bump dependency3 and updates dependency version of dependency3 in dependency2 pom.

I have tried -amd parameter with no result.

Is possible to do it via a command line? Or any alternative way to do it?



via Chebli Mohamed

HttpURLConnection getResponseMessage() language and codification


I am writing an android library, which uses HttpURLConnection for implementing a REST client. When the getResponseMessage() is called, a string with the error code and response message is returned. The problem I cannot resolve is that this message is returned in Spanish using a codification other than UTF-8. AFAIK, everything in the computer is configured to use English, OS X, Android Studio, etc. Does anyone know how to change this to English and UTF-8? Thanks in advance.

Edit:

1) Android minimum API level 15, target 22.

2) My main problem is with the language, not with codification. If I understood right, Strings in Java are always internally in UTF-16 and I change to UTF-8 when needed. Sorry.

3) When debugging, only the error code member variable (errorResponse) of the HttpURLConnection instance has a value (405), and the instance error message variable member (errorMessage) seems empty.

4) My computer has region Spain, and primary language English (US). The phone is in English. Default locale before getting the response message is "en_US".



via Chebli Mohamed

How to stream Data in with java websockets


I read some tutorials or tried it so now I have some JS code that connects with my java websocket and when I click on a button it sends some test string to the websocket and reciev some other.

Now I wanna have some realtime stream so in the string that the JS code recieves is the current time in milliseconds how can I achiev that I get don't know every second get the new time ? Maybe it would be an better idea to use normal time then instead of milliseconds so I can change this.

My codes so far Javascript

var websocket;
$(document).ready(function(){
    websocket = new WebSocket("ws://localhost:8080/TimeStreamingTestartID-1.0-SNAPSHOT/websockets/simplestockmarket")

    websocket.onopen = function(){ 
    alert("SUCESS: REGISTERED!!");
    }

$("#start").click(function(){

    websocket.send("Test")
    websocket.onmessage = function(erg){
    console.log(erg);
    }

});

});

My java WebSocket code

@ServerEndpoint("/websockets/simplestockmarket")
public class SimpleStockMarketWSServerEndpoint {

@OnOpen
public void open(Session session) {


}



   @OnMessage
    public void message(Session session,String message) {

        try {


session.getBasicRemote().sendText(Long.toString(System.currentTimeMillis())+" <- time, message from client -> "+message);
        } catch (IOException e) {
            e.printStackTrace();
        }

}

@OnClose
public void close(Session session) {

}
}

I know it's not finished yet but I wanna achiev this streaming before I do the rest like closing the connection again. If I missed something important please tell me and I will add it.



via Chebli Mohamed

Apache Cayenne: NullPointerException when commitChanges


I'm trying commitChanges, but catch java.lang.NullPointerException. log:

...  
INFO: --- transaction started.
авг 04, 2015 12:33:59 PM org.apache.cayenne.access.dbsync.CreateIfNoSchemaStrategy processSchemaUpdate
INFO: Full or partial schema detected, skipping tables creation
авг 04, 2015 12:33:59 PM org.apache.cayenne.log.CommonsJdbcEventLogger logQuery
INFO: SELECT NEXT_ID FROM AUTO_PK_SUPPORT WHERE TABLE_NAME = 'ARTIST'
авг 04, 2015 12:33:59 PM org.apache.cayenne.log.CommonsJdbcEventLogger logSelectCount
INFO: === returned 1 row. - took 16 ms.
авг 04, 2015 12:33:59 PM org.apache.cayenne.log.CommonsJdbcEventLogger logQueryError
INFO: *** error.
java.lang.NullPointerException
    at com.relx.jdbc.jdbc2.LinterStatementImpl.getUpdateCount(LinterStatementImpl.java:419)
    at org.apache.cayenne.access.jdbc.SQLTemplateAction.execute(SQLTemplateAction.java:190)
    at org.apache.cayenne.access.jdbc.SQLTemplateAction.performAction(SQLTemplateAction.java:124)
    at org.apache.cayenne.access.DataNodeQueryAction.runQuery(DataNodeQueryAction.java:87)
    at org.apache.cayenne.access.DataNode.performQueries(DataNode.java:280)
    at org.apache.cayenne.dba.JdbcPkGenerator.longPkFromDatabase(JdbcPkGenerator.java:310)
    at org.apache.cayenne.dba.JdbcPkGenerator.generatePk(JdbcPkGenerator.java:268)
    at org.apache.cayenne.access.DataDomainInsertBucket.createPermIds(DataDomainInsertBucket.java:171)
    at org.apache.cayenne.access.DataDomainInsertBucket.appendQueriesInternal(DataDomainInsertBucket.java:76)
    at org.apache.cayenne.access.DataDomainSyncBucket.appendQueries(DataDomainSyncBucket.java:78)
    at org.apache.cayenne.access.DataDomainFlushAction.preprocess(DataDomainFlushAction.java:188)
    at org.apache.cayenne.access.DataDomainFlushAction.flush(DataDomainFlushAction.java:144)
    at org.apache.cayenne.access.DataDomain.onSyncFlush(DataDomain.java:853)
    at org.apache.cayenne.access.DataDomain$2.transform(DataDomain.java:817)
    at org.apache.cayenne.access.DataDomain.runInTransaction(DataDomain.java:877)
    at org.apache.cayenne.access.DataDomain.onSyncNoFilters(DataDomain.java:814)
    at org.apache.cayenne.access.DataDomain$DataDomainSyncFilterChain.onSync(DataDomain.java:1031)
    at org.apache.cayenne.access.DataDomain.onSync(DataDomain.java:785)
    at org.apache.cayenne.access.DataContext.flushToParent(DataContext.java:817)
    at org.apache.cayenne.access.DataContext.commitChanges(DataContext.java:756)
    at CayenneTest2.main(CayenneTest2.java:61)

Table AUTO_PK_SUPPORT was created and filled Apache Cayenne. Why throw the Exception?



via Chebli Mohamed

how make a point-to-point VoIP in android


I am searching for a way to make a point-to-point VoIP call between two Android devices without having any intermediate server (SIP server).devices have access to internet. Is this possible?

  • we know the IP address of the devices
  • should we create a local sip account ? if yes How ?


via Chebli Mohamed

How to get speed and acceleration from trajectory data?


I am using Java to develop a project. I have got some trajectory data by applying a spatial query. My question is, how can I get speed and acceleration for these trajectory data? Does java has useful library to do so? for more information: points has (x,y,z,t) enter image description here



via Chebli Mohamed

Convert a string like hh:mm:ss to milliseconds


How to convert "00:02:58" (hh:mm:ss) to milliseconds?



via Chebli Mohamed

netbeans: bundle files to nbm


This Question refers to How to bundle additional (data) files with a Netbeans module?. I have two Pyhtonscripts, which I want to integrate in the created NBM, so they can be executed from within the plugin.

I tried all the solutions from the Question above (except the Maven part), as well as putting the files in every possible location inside the project, but it had no influence.

I think the last part of this tutorial -"Updating the Sources"- would do the trick. Am I on the right path? I did include the code in my build-init.xml, but (I don't know if I set the Locations right) there was no improvement at all.



via Chebli Mohamed

Task Scheduling using threads in java


I am currently working on a DB integrated daily file transfer scheduling form application for operational business use. In order to be able to control and have access to specific schedules, I have decided to create a thread for each schedule so that a specific schedule could be stopped, or restarted on demand. To achieve this, I have written a separate class which includes a custom thread class and its constructor, a main class to create and run an instance of thread and another class that includes the runnable method of daily scheduling. In order to be able to access specific threads, I have tried to implement a ConcurrentHashMap to synchronise the hashcodes and the names of the threads created, along with a ThreadGroup. When I create a thread, I am able to pass the name and the hashcode of the thread to the ConcurrentHashMap, along with the ThreadGroup. However, when I create the second or the third thread, I have discovered that the specified names and the hashcodes of the threads that have been specified are changing. The class that I have explained above could be seen below.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.logging.Level;
import java.util.logging.Logger;
import static sun.misc.ThreadGroupUtils.getRootThreadGroup;

public class ThreadRun
{
   static String name, s, d;
   static int h = 0;
   static int m = 0;
   ThreadGroup tg = Thread.currentThread().getThreadGroup();
   Thread[] threads;

   public void start (String n, String src, String dest, int hour, int min) 
   {
            name = n;
            s = src;
            d = dest;
            h = hour;
            m = min;
            MyThread mt = new MyThread(tg,name,s,d,h,m);
            mt.setName(name);
            mt.start ();
            System.out.println("Thread: " + mt.getName() + "is started!");
            getThread();

      }

   Thread[] getAllThreads(ThreadGroup tg) {
   // tg = Thread.currentThread().getThreadGroup();
    final ThreadMXBean thbean = ManagementFactory.getThreadMXBean( );
    int nAlloc = thbean.getThreadCount( ) + 1;
    int n = 0;
    Thread[] threads;
    do {
        nAlloc *= 2;
        threads = new Thread[ nAlloc ];
        n = tg.enumerate( threads, true );
    } while ( n == nAlloc );
    return java.util.Arrays.copyOf( threads, n );
} //getting all the active threads to an array

   void getThread() //getting a specific thread
   {
    final Thread[] threads = getAllThreads(tg);
    for ( Thread thread : threads )
      System.out.println("ThreadName = " + thread.getName());
}

  static class MyThread extends Thread{

      MyThread(ThreadGroup tg, String name, String src, String dest, int hour, int min)
      {
            super(tg,name);
      }

      @Override
         public void run () // run thread
        {
            ScheduleControl sc = new ScheduleControl();
            sc.scheduleDaily();
         //System.out.println ("My name is: " + getName ());
        }

 //SCHEDULE ZAMAZEENGO

class ScheduleControl {
   ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(20);       

   public void scheduleDaily() {
     final Runnable task = new Runnable() {


         @Override
       public void run() 
       { 
           try {
               t(s,d,h,m);
           } catch (IOException ex) {
               Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex);
           }
       }
     };

        LocalDateTime localNow = LocalDateTime.now();
        ZoneId currentZone = ZoneId.of("CET");
        ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);

        ZonedDateTime zonedNext5 = zonedNow.withHour(h).withMinute(m).withSecond(0);

        if(zonedNow.compareTo(zonedNext5) > 0)
        zonedNext5 = zonedNext5.plusDays(1);


        Duration duration = Duration.between(zonedNow, zonedNext5);
        long initalDelay = duration.getSeconds();

        System.out.println("Schedule is started at\n" + LocalDateTime.now().getHour()+ ":" + LocalDateTime.now().getMinute());
        //System.out.println("Initial delay: " + initalDelay/60/60);
        final ScheduledFuture<?> scheduleHandle =
        scheduler.scheduleAtFixedRate(task, initalDelay , 24*60*60, SECONDS);

        scheduler.schedule(new Runnable() {
       @Override
       public void run() 
       {
           scheduleHandle.cancel(true);
       }
     }, 60*60, SECONDS);
   }


public Runnable t (String source, String destin, int h, int m) throws IOException
       {
           File srcF = new File(""+source);
           File destF = new File(""+destin);
           copyFolder(srcF,destF);
           System.out.println("Schedule finished at: " +LocalDateTime.now().getHour() + ":" +LocalDateTime.now().getMinute() + ":" +LocalDateTime.now().getSecond());
           return null;
       }
        public void copyFolder(File src, File dest)
        throws IOException{

        if(src.isDirectory()){

            //if directory not exists, create it
            if(!dest.exists()){
               dest.mkdir();
               System.out.println("Directory copied from " 
                              + src + "  to " + dest);
            }

            //list all the directory contents
            String files[] = src.list();

            for (String file : files) {
               //construct the src and dest file structure
               File srcFile = new File(src, file);
               File destFile = new File(dest, file);
               //recursive copy
               copyFolder(srcFile,destFile);
            }
        }
        else
        {
            OutputStream out;
                try ( //if file, then copy it
                //Use bytes stream to support all file types

                        InputStream in = new FileInputStream(src)) {
                    out = new FileOutputStream(dest);
                    byte[] buffer = new byte[1024];
                    int length;
                    //copy the file content in bytes
                    while ((length = in.read(buffer)) > 0){
                        out.write(buffer, 0, length);
                }
                }
                out.close();
                System.out.println("File copied from " + src + " to " + dest);
            }
        }
    }
  }
}

I have activated two different schedules for each to be run by a thread. The output of the active threads could be seen

Thread: Test 1 is started!
ThreadName = AWT-EventQueue-0
ThreadName = DestroyJavaVM
ThreadName = Test 1
Schedule is started at 12:
Thread: Test 2 is started!
ThreadName = AWT-EventQueue-0
ThreadName = DestroyJavaVM
ThreadName = pool-1-thread-1
ThreadName = pool-1-thread-2
ThreadName = Test 2
Schedule is started at
12:25

As it could be seen in the output above, there are three (3) threads instead of two and the specified name has been changed. I would like to be able to have static names and hashcodes for specific operation so that I can stop, pause, resume or delete by accessing each specifically. Thus I wonder what might be causing the problem, or what I have implemented in a wrong way.



via Chebli Mohamed

How to write a java program to filter all commented lines and print only java coding lines?


I tried using regular expression to filter the single and multi-line comments from my text file. I am able to filter all the comments like //it works

/*
* welcome
*/
/* hello*/

but I am not able to remove the following comment

/*
sample
*/

This is my code:

import java.io.*;
import java.lang.*;


class TestProg
{
public static void main(String[] args) throws IOException {
    removeComment();
}
static void removeComment() throws IOException
{
    try {
        BufferedReader br = new BufferedReader(new FileReader("d:\\data.txt"));
        String line;
        while((line = br.readLine()) != null){
            if(line.contains("/*") && line.contains("*/") || line.contains("//")) {

                System.out.println(line.replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)","")); 
            }
            else if(line.contains("/*") || line.contains("*") || line.contains("*/")) {

                continue;
            }
            else
                System.out.println(line); 
        }
        br.close();
    }

    catch(IOException e) {
        System.out.println("OOPS! File could not read!");
    }
}
}

Please help me to solve this...

Thanks in advance.



via Chebli Mohamed

Loss of messages in HandlerThread


I have a class that extends a HandlerThread class for creating a bitmap from photo on the device in GridView when it's needed but from time to time instead of creating a bitmap of photo it fils a GridView item(ImageView) with nothing and i cant understand why this is happening. Help please =)

HandlerThread class:

public class ThumbnailDownloader<Token> extends HandlerThread {
private static final String TAG = "ThumbnailDownloader";
private static final int MESSAGE_CREATE_BITMAP = 0;

private Handler mHandler;
private Map<Token, String> requestMap =
        Collections.synchronizedMap(new HashMap<Token, String>());
private Handler mResponseHandler;
private Listener<Token> mListener;

public interface Listener<Token>{
    void onThumbnailDownloaded(Token token, Bitmap thumbnail);
}

public void setListener(Listener<Token> listener){
    mListener = listener;
}

public ThumbnailDownloader(Handler responseHandler){
    super(TAG);
    mResponseHandler = responseHandler;
}

public void queueThumbnail(Token token, String path){
    Log.i(TAG, "Got an PATH: " + path);
    requestMap.put(token, path);

    mHandler
            .obtainMessage(MESSAGE_CREATE_BITMAP, token)
            .sendToTarget();
}

private void handleRequest(final Token token){
    final String path = requestMap.get(token);
    final Bitmap bitmap = PictureUtils.getScaledBitmap(path,
            GalleryFragment.getImageViewWidth(),
            GalleryFragment.getImageViewHeight());

    mResponseHandler.post(new Runnable() {
        @Override
        public void run() {
            if (requestMap.get(token) != path){
                return;
            }
            requestMap.remove(token);
            mListener.onThumbnailDownloaded(token, bitmap);
        }
    });
}

@Override
protected void onLooperPrepared() {
    mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MESSAGE_CREATE_BITMAP){
                Token token = (Token) msg.obj;
                Log.i(TAG, "Got a request for drawable: " + requestMap.get(token));
                handleRequest(token);
            }
        }
    };
}

public void clearQueue() {
    mHandler.removeMessages(MESSAGE_CREATE_BITMAP);
    requestMap.clear();
}

}

GridView class:

public class GalleryFragment extends Fragment {
private ArrayList<String> mPathList;
private GalleryHolderAdapter mAdapter;
private GridView mGridView;
private PhotoList mList;
private static int imageViewHeight;
private static int imageViewWidth;

private ThumbnailDownloader<ImageView> mThumbnailThread;
private static final  String TAG = "GalleryFragment";

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mThumbnailThread = new ThumbnailDownloader<ImageView>(new Handler());

    mThumbnailThread.setListener(new ThumbnailDownloader.Listener<ImageView>() {
        @Override
        public void onThumbnailDownloaded(ImageView imageView, Bitmap thumbnail) {
            if (isVisible()) {
                imageView.setImageBitmap(thumbnail);
            }
        }
    });

    mThumbnailThread.start();
    mThumbnailThread.getLooper();
}

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

    mPathList = new PhotoList().getPathList();
    mList = new PhotoList();

    mGridView = (GridView) view.findViewById(R.id.gridView);

    mAdapter = new GalleryHolderAdapter(getActivity(),mPathList);

    mGridView.setAdapter(mAdapter);

    FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.button_add_photo);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction()
                    .replace(R.id.main_content_frame, new CameraFragment())
                    .commit();
        }
    });

    mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(getActivity(), PhotoPagerActivity.class);
            intent.putExtra("PATH_PAGER", mPathList.get(position));
            startActivity(intent);
        }
    });

    return view;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    imageViewHeight = mAdapter.imageViewMaxHeight;
    imageViewWidth = mAdapter.imageViewMaxWidth;

    System.gc();
}

public static int getImageViewHeight(){
    return imageViewHeight;
}

public static int getImageViewWidth() {
    return imageViewWidth;
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    mThumbnailThread.clearQueue();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mThumbnailThread.quit();
}

public class GalleryHolderAdapter extends BaseAdapter {
    private Context mContext;
    private ArrayList<String> mPathList;
    private ViewHolder holder;
    public int imageViewMaxHeight;
    public int imageViewMaxWidth;

    public GalleryHolderAdapter(Context context, ArrayList<String> items) {
        mContext = context;
        mPathList = items;
    }

    @Override
    public int getCount() {
        return mPathList.size();
    }

    @Override
    public Object getItem(int position) {
        return mPathList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        if (convertView == null){
            LayoutInflater inflater = LayoutInflater.from(mContext);
            convertView = inflater.inflate(R.layout.gallary_item, parent, false);

            holder = new ViewHolder();
            holder.mImageView = (ImageView) convertView.findViewById(R.id.gallary_item_imageView);
            holder.mLocationImage = (ImageView) convertView.findViewById(R.id.location_enabler_image_view);

            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }

        imageViewHeight = holder.mImageView.getMaxHeight();
        imageViewWidth = holder.mImageView.getMaxWidth();

        mThumbnailThread.queueThumbnail(holder.mImageView, mPathList.get(position));

        return convertView;
    }

    public class ViewHolder {
        ImageView mImageView;
        ImageView mLocationImage;
    }
}

}

And a class that makes a bitmap:

public class PictureUtils {
private static final String TAG = "PictureUtils";

    public static Bitmap getScaledBitmap
            (String path, int bestWidth, int bestHeight){
        // Чтение размеров изображения на диске
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        float srcWidth = options.outWidth;
        float srcHeight = options.outHeight;

        int inSampleSize = 1;
        if(srcHeight > bestHeight || srcWidth > bestWidth){
            if(srcWidth > srcHeight){
                inSampleSize = Math.round(srcHeight / bestHeight);
            }else {
                inSampleSize = Math.round(srcWidth / bestWidth);
            }
        }
        options = new BitmapFactory.Options();
        options.inSampleSize = inSampleSize;
        options.inPreferredConfig = Bitmap.Config.RGB_565;

        return BitmapFactory.decodeFile(path, options);
    }

public static Bitmap createDrawableFromView(Activity activity, View view) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    view.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
    view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
    view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
    view.buildDrawingCache();
    Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);

    return bitmap;
}

    public static void cleanImageView(ImageView view){
        if (!(view.getDrawable() instanceof BitmapDrawable))
            return;
        // Стирание изображения для экономии памяти
        BitmapDrawable drawable = (BitmapDrawable) view.getDrawable();
        drawable.getBitmap().recycle();
        view.setImageDrawable(null);
        System.gc();
    }
}



via Chebli Mohamed

Java - How to create automatic multiline label?


I am using Netbeans designer.

Is there any way how to create a multiline label which works automatically? I know that it supports html and you can add tags for a new line, but I have really a lot of text I need to display and it would take so much time to add tags everywhere at the right place etc.

I already tried TextArea workaround, it worked pretty much well except it ignored setting fonts.



via Chebli Mohamed

How to use Jersey's internal routing mechanism to extract a class/method reference?


I have a Jersey 1.8 application running. Jersey is running as a Servlet.

I need to write a servlet filter that given a plain request/response, is able to figure out which REST resource/method will respond to the request and extract values from annotations.

For example, imagine I have the following resource:

@Path("/foo")
@MyAnnotation("hello")
public class FooResource {
   @GET
   @Path("/bar")
   @MyOtherAnnotation("world")
   public Response bar(){ 
      ... 
   }
}

When a request GET /foo/bar comes in, I need my servlet filter to be able to extract the values "hello" and "world" from MyAnnotation and MyOtherAnnotation before Jersey's own servlet processes the request.

This filter logic should be able to work for all requests and all resources registered.

Is there a way to access Jersey's internal routing mechanism to obtain a class/method reference where Jersey will dispatch the request?

I'm open to other suggestions as well, but ideally nothing like trying to hack my own routing mechanism by reading the @Path annotations myself.



via Chebli Mohamed

Hibernate gives 'table is not mapped' Exception


I configured package which contains pojo entity class which defined tables.

However, I see errors from below query

public interface TargetRepository extends CrudRepository<TargetEntity, String> {
    @Query("SELECT a, b FROM target_table")
    public List<Object> selectTargets();
}

org.hibernate.hql.internal.ast.QuerySyntaxException: target_table is not mapped

How can I fix it?



via Chebli Mohamed

How to validate input in my Person class


public class Person {
private String name;
private String email;
private String password;

public Person(String name, String email, String password) {
    setName(name);
    setEmail(email);
    setPassword(password);
}

public void setName(String name) {
    if (name == null || name.isEmpty()) {
        throw new IllegalArgumentException("Invalid name");
    }

    this.name = name;   
}

public void setEmail(String email) {
    /* Validate email, throw exception */

    this.email = email;
}

public void setPassword(String password) {
    /* Validate password, throw exception */

    this.password = password;
}

}

  1. Best way to validate email adresses, passwords (e.g. 8 characters, at least one upper-case character, one digit, ...) and throw an exception if necessary. The same way I did with name ?

  2. Netbeans complaints about using setters in the constructor ? If I wouldn't and just assign the value directly (this.name = name), I need to validate the input twice (ones's in the cunstroctor and in one's the setter).



via Chebli Mohamed