vendredi 29 mai 2015

Telegram API : How keep ApiState to save signIn state

I used telegram api from this source : http://ift.tt/1BtMIMC But my problem is , how keep the user signed in. Because after the App stop need user renter Mobile phone and get activation code from SMS message. I have implemented Serializable for saving ApiState object. but this method not solved my problem. this is the code for my ApiState :

package engine;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

import org.telegram.api.TLConfig;
import org.telegram.api.TLDcOption;
import org.telegram.api.engine.storage.AbsApiState;
import org.telegram.mtproto.state.AbsMTProtoState;
import org.telegram.mtproto.state.ConnectionInfo;
import org.telegram.mtproto.state.KnownSalt;

/**
 * Created by ex3ndr on 13.01.14.
 */
public class MemoryApiState implements AbsApiState,java.io.Serializable {

    public HashMap<Integer, ConnectionInfo[]> connections = new HashMap<Integer, ConnectionInfo[]>();
    private HashMap<Integer, byte[]> keys = new HashMap<Integer, byte[]>();
    private HashMap<Integer, Boolean> isAuth = new HashMap<Integer, Boolean>();

    private int primaryDc = 1;

    public MemoryApiState(boolean isTest) {
        connections.put(1, new ConnectionInfo[]{
                new ConnectionInfo(1, 0, isTest ? "149.154.167.40" : "149.154.167.50", 443)
        });
    }

    @Override
    public synchronized int getPrimaryDc() {
        return primaryDc;
    }

    @Override
    public synchronized void setPrimaryDc(int dc) {
        primaryDc = dc;
    }

    @Override
    public synchronized boolean isAuthenticated(int dcId) {
        if (isAuth.containsKey(dcId)) {
            return isAuth.get(dcId);
        }
        return false;
    }

    @Override
    public synchronized void setAuthenticated(int dcId, boolean auth) {
        isAuth.put(dcId, auth);
    }

    @Override
    public synchronized void updateSettings(TLConfig config) {
        connections.clear();
        HashMap<Integer, ArrayList<ConnectionInfo>> tConnections = new HashMap<Integer, ArrayList<ConnectionInfo>>();
        int id = 0;
        for (TLDcOption option : config.getDcOptions()) {
            if (!tConnections.containsKey(option.getId())) {
                tConnections.put(option.getId(), new ArrayList<ConnectionInfo>());
            }
            tConnections.get(option.getId()).add(new ConnectionInfo(id++, 0, option.getIpAddress(), option.getPort()));
        }

        for (Integer dc : tConnections.keySet()) {
            connections.put(dc, tConnections.get(dc).toArray(new ConnectionInfo[0]));
        }
    }

    @Override
    public synchronized byte[] getAuthKey(int dcId) {
        return keys.get(dcId);
    }

    @Override
    public synchronized void putAuthKey(int dcId, byte[] key) {
        keys.put(dcId, key);
    }

    @Override
    public synchronized ConnectionInfo[] getAvailableConnections(int dcId) {
        if (!connections.containsKey(dcId)) {
            return new ConnectionInfo[0];
        }

        return connections.get(dcId);
    }

    @Override
    public synchronized AbsMTProtoState getMtProtoState(final int dcId) {
        return new AbsMTProtoState() {
            private KnownSalt[] knownSalts = new KnownSalt[0];

            @Override
            public byte[] getAuthKey() {
                return MemoryApiState.this.getAuthKey(dcId);
            }

            @Override
            public ConnectionInfo[] getAvailableConnections() {
                return MemoryApiState.this.getAvailableConnections(dcId);
            }

            @Override
            public KnownSalt[] readKnownSalts() {
                return knownSalts;
            }

            @Override
            protected void writeKnownSalts(KnownSalt[] salts) {
                knownSalts = salts;
            }
        };
    }

    @Override
    public synchronized void resetAuth() {
        isAuth.clear();
    }

    @Override
    public synchronized void reset() {
        isAuth.clear();
        keys.clear();
    }

    public void saveObject()
    {
        try
        {
           FileOutputStream fileOut =
           new FileOutputStream("apistate3.tmp");
           ObjectOutputStream out = new ObjectOutputStream(fileOut);
           out.writeObject(this);
           out.close();
           fileOut.close();
           System.out.printf("Serialized data is saved");
        }catch(IOException i)
        {
            i.printStackTrace();
        }
    }

    public MemoryApiState readObject()
    {
        try
        {
           FileInputStream fileIn = new FileInputStream("apistate3.tmp");
           ObjectInputStream in = new ObjectInputStream(fileIn);
           MemoryApiState obj = (MemoryApiState) in.readObject();
           in.close();
           fileIn.close();
           return obj;
        }catch(IOException i)
        {
           i.printStackTrace();
           return null;
        }catch(ClassNotFoundException c)
        {
           System.out.println("Employee class not found");
           c.printStackTrace();
           return null;
        }
    }

}

Does main method work differently in enums and classes?

In the following code :

enum Rank {
FIRST(20), SECOND(0), THIRD(8);
Rank(int value) {
System.out.print(value);
} 
}
public static void main (String[] args) {
}

This gives the following output: 2008 If however the main method is declared in some other class like this:

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

}

There is no output. What is the difference between main in enum and main in the class?

contacts not showing in activity

I am trying to show contacts in an activity but its not working. I review my code, But not able to understand whats the problem is. Here is my code:-

/deleted/

showfriendlist.xml

    <RelativeLayout xmlns:android="http://ift.tt/nIICcg"
        xmlns:tools="http://ift.tt/LrGmb4"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <ListView
            android:id="@+id/lst_contacts"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </RelativeLayout>

row header and column header for a particular cell in table

How to take corresponding row header and column header for a particular cell in table? I have table and i wanted to take the corresponding column header and row header of that cell when clicked

Error while loading raster files using GeoTools


I tried loading shape files using GeoTools.It is working fine.
But when i am trying to load the raster maps, i am getting some warning like Can't load a service for category "GridFormatFactorySpi"

Can any one throw some light on my issue?

Eclipse Marketplace not visible

Eclipse marketplace was not installed initially. Then I followed instructions here on SO and I restarted Eclipse several times in the meanwhile.

I have set up the Internet Proxy already (I needed to do so to install the Marketplace itself).

But still the Marketplace is not visible under the Help menu. I can also not start installations via Marketplace Drag-to-install buttons.

When I run eclipse -console I get the following messages, which I believe are not related to the problem:

org.eclipse.m2e.logback.configuration: The org.eclipse.m2e.logback.configuration bundle was activated before the state location was initialized.  Will retry after the state location is initialized.

osgi> org.eclipse.m2e.logback.configuration: Logback config file: C:\Users\___\workspace\tests\.metadata\.plugins\org.eclipse.m2e.logback.configuration\logback.1.5.0.20140606-0033.xml
org.eclipse.m2e.logback.configuration: Initializing logback
java.lang.ClassCastException: org.eclipse.osgi.internal.framework.EquinoxConfiguration$1 cannot be cast to java.lang.String
        at org.eclipse.m2e.logback.configuration.LogHelper.logJavaProperties(LogHelper.java:26)
        at org.eclipse.m2e.logback.configuration.LogPlugin.loadConfiguration(LogPlugin.java:189)
        at org.eclipse.m2e.logback.configuration.LogPlugin.configureLogback(LogPlugin.java:144)
        at org.eclipse.m2e.logback.configuration.LogPlugin.access$2(LogPlugin.java:107)
        at org.eclipse.m2e.logback.configuration.LogPlugin$1.run(LogPlugin.java:62)
        at java.util.TimerThread.mainLoop(Unknown Source)
        at java.util.TimerThread.run(Unknown Source)

I have read most of the "Question that may already have your answer" which were suggested by SO while writing this question, still no luck.

I'm working on Eclipse Luna SR1 4.4.1 on Windows 7 SP1 x64.

What else could I do to get the Eclipse Marketplace into my installation?

Send and Receive a complete file via cURL and Java

i'm trying to send a local file "test.properties" via curl to a server which is also running on my localhost. The test.properties file is basically just a txt-file and looks like this

#
#Tue May 12 16:17:01 CEST 2015
hostname=localhost
Resource_namespace=http\://localhost/resource/
url=localhost
Local_namespace=http\://localhost/

My cURL command looks like this:

curl -i -X POST --data-binary ssh.properties localhost:8080/sshService/PhysicalNodeAdapter-1/config

And my Java-Method on the recieving server looks like this:

  @POST
  @Path("/{adapterName}/config")
  @Consumes("*/*")
  @Produces("text/html")
  public Response updateConfig(@PathParam("adapterName") String     
  adapterName, String configInput) {
   AbstractAdapter adapter = getAdapterInstance(adapterName);
    Log.fatal("CONFIG", configInput);
   try {
    adapter.updateConfig(adapterName,configInput);
    return Response.status(Response.Status.OK.getStatusCode()).build();
} catch (ProcessingException e) {
    processProcessingRequestException(e);
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
return Response.status(Response.Status.CONFLICT.getStatusCode()).build();
}

I just need a curl command that sends one file via http to an server. The server takes the file and saves it 1:1 on the hard-disk

But i really don't get it. Tried different commands and different "@Consumes" but didn't work out...

Edit: I forgot to say i don't want it URL-Encoded. It should be in the Body of the POST-package

Caching Google calendar credentials or service

I have the following code to build a Google calendar service with the Java API (using a service account):

/**
 * Return a google Calendar object for interacting with the calendar API.
 * Return null if it can't be built for any reason
 */
private Calendar buildGoogleCalendarService() throws GeneralSecurityException, IOException {
    String googleUsername = this.getGoogleUsername();
    if (googleUsername == null) {
        return null;
    }
    String path = AuthManager.class.getClassLoader().getResource("").getPath();
    File privateKey = new File(path + "/google_key.p12");
    if (!privateKey.exists()) {
        logger.error("Google private key not found at " + privateKey.getAbsolutePath());
        return null;
    }
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
            .setJsonFactory(jsonFactory).setServiceAccountId(AppProperties.googleAppEmailAddress)
            .setServiceAccountPrivateKeyFromP12File(privateKey)
            .setServiceAccountScopes(Collections.singleton(CalendarScopes.CALENDAR))
            .setServiceAccountUser(googleUsername).build();
    Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName(AppProperties.appName).build();
    return service;
}

It works fine with some basic testing, the question is how long will the credentials / service be able to be re-used for? i.e. how many API requests can you make using it before regenerating? This server application may process a high volume of API calls and last for some months between reboots.

Doing some timing, the credential building stage (GoogleCredential credential = new GoogleCredential.Builder()...) takes the most time, approx. a quarter of a second, I'll try caching that to start with and see how it goes but any answers appreciated.

SessionFactory calling openSession throws noSuchMethoderror exception

I am using hibernate 3.2.5.GA, when invoking openSession of SessionFactory, it returns Session object of type org.hibernate.classic.Session :

public org.hibernate.classic.Session openSession() throws HibernateException;

I am also using Spring Batch 2.2.7.RELEASE, when setting SessionFacotry in HibernateItemReaderHelper, an exception is thrown when openSession in invoked because it expects Session of Type : org.hibernate.Session:

java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session;

Anyone knows a solution to this?

P.S. I can not upgrade the Hibernate.

Need a regex in java to check a alphanumeric string [on hold]

I have a function that accept a alphanumeric String as parameter, i have to check if the string is in a required format the format is as follows.

first 4 characters alphabet then 2 numeric then 3 alphabet then 4 numeric then 2 alphabet

I need a regex who can verify if the given string is in required format

How to pass object between pages in Primefaces

In datatable, by clicking datatable element per row, is there a basic solution to pass this clicked object to next page? Which scope annotation is proper for this?

java.lang.IllegalArgumentException: Cannot determine the graph element type because the document class is null.

Hello I'm creating a widget for Samsung Gear. Im using Tizen IDE for wearable. I followed their youtube tutoria: How to Create a Basic Integrated Gear Application.

I tried Build Project in Tizen IDE and there was a build error:

Errors occurred during the build. Errors running builder 'Web Widget Builder' on project 'SimpleSAPConsumer'. Build Error : Cannot determine the graph element type because the document class is null. Probably this is a projection, use the EXPAND() function Build Error : Cannot determine the graph element type because the document class is null. Probably this is a projection, use the EXPAND() function

Then Error Log said:

eclipse.buildId=
java.version=1.7.0_67
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en
Command-line arguments:  -os win32 -ws win32 -arch x86_64

Error
Fri May 29 17:01:28 SGT 2015
Build Error :

java.lang.IllegalArgumentException: Cannot determine the graph element type because the document class is null. Probably this is a projection, use the EXPAND() function
        at com.tinkerpop.blueprints.impls.orient.OrientElementIterator.next(OrientElementIterator.java:49)
        at com.tinkerpop.blueprints.impls.orient.OrientElementIterator.next(OrientElementIterator.java:13)
        at org.tizen.common.builder.dependency.DependencyInDB.getVertexFromDB(DependencyInDB.java:236)
        at org.tizen.common.builder.dependency.DependencyInDB.containsVertex(DependencyInDB.java:254)
        at org.tizen.common.builder.BuildProcess.removeResource(BuildProcess.java:413)
        at org.tizen.common.builder.BuildProcess.build(BuildProcess.java:282)
        at org.tizen.web.project.builder.WebBuilder.build(WebBuilder.java:252)
        at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728)
        at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
        at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199)
        at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239)
        at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292)
        at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
        at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295)
        at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351)
        at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374)
        at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143)
        at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241)
        at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

java swing - how to change window background

I was trying to make a button that switches the window background from default to red. I haven't found any preset colors to match the default so i tried to get it from panel.getBackground when i created it. I have an error at line 11, i don't know how to check the current background color.

JPanel panel = new JPanel();
    panel.setBounds(0, 0, 434, 262);
    frame.getContentPane().add(panel);
    panel.setLayout(null);
    panel.setVisible(true);
    Color c=panel.getBackground();

    JButton btnRed = new JButton("Red");
    btnRed.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(panel.getBackground(c));{
                panel.setBackground(Color.RED);
            }
            else{
                panel.setBackground(c);
            }
        }
    });

get a specific value from arraylist element java

i have an arraylist where it has certain number of elements, each consisting of two values (day,cents) company.getAnnouncements().get(0)

The above code will retrieve the first element in the arraylist, but i only want the cents component of that element. How would you do this??

Java determine the return type at Runtime

I read various links on SO but I am unable to grasp the answers related to it.

I have a problem as such

public dynamicreturn/dynamicothertype test(){
    if(A)
       return dynamictype;
    else
       return dynamicothertype;
}

how to achieve it?Small guidance or any links would be very helpful.

Selective usage of Spring Security's CSRF filter

Disclaimer: My question is somewhat similar to this question and this question, but I have tried all the answers suggested in those threads and already spent few days struggling with the problem.

I am introducing Spring Security 3.2.6 in my existing application (JSP, Servlet only) and I am using Java configuration. My application will be used both by browsers and non-browser clients. I want all the browser requests to URLs (i.e. /webpages/webVersion/ and /webpages/webVersion2/) to be CSRF enabled and all the other requests to be CSRF disabled. Non-browser clients never access above two URLs, whereas the browser application may also access CSRF disabled URLs.

I have tried a variety of options:

  1. Enable Spring Security only on the aformentioned URLs:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/","/resources/****").permitAll()
            .antMatchers("/webpages/webVersion/****", "/webpages/webVersion2/****").authenticated()
            .antMatchers("/webpages/****").permitAll()
            .anyRequest().anonymous()
            .and()
            .formLogin().loginPage("/webpages/webVersion/login/newLogin.jsp").failureUrl("/webpages/webVersion/login/newLogin.jsp?error=true").loginProcessingUrl("/j_spring_security_check")
            .usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/webpages/webVersion/login/loginSuccess.jsp", true).permitAll()
            .and()
            .logout().logoutUrl("/webpages/webVersion/logout.jsp").permitAll()
            .and().exceptionHandling().accessDeniedPage("/webpages/webVersion/404-error-page.jsp")
            .and()
            .csrf();
    } 
    
    

    This didn't work as I observe that CSRF is enabled for all of the URLs.

  2. Tried using CSRFProtectionMatcher:

    .csrf().requireCsrfProtectionMatcher(csrfRequestMatcher); 
    
    

    CSRF is enabled for intended URLs only, but even /resources/** and /webpages/** URLs need to be checked inside matches function. Seems to be a bit much considering it will be for all requests.

  3. Tried using another version of the configure method:

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().regexMatchers(".*?/jsp/(?!webVersion|webVersion2).*?");
    }
    
    

    I am not sure whether I did it correctly but this didn't produce the results I wanted.


Which of the above approach is the correct (Spring Security) way of doing what I want? How can I achieve the desired behavior from my Spring Security configuration?

Login button facebook android doesn't redirect to new activity

When i run my Android app, and click approve to the give permissions it not get redirected to the MainActivity. The "Logged in" message doesn't shows up in the Catlog. I have read the Facebook developers guide, and compared my code to different topics here at Stack. I can't see i have done anything wrong.

I would be very glad for help.

public class Login extends Activity {

/**
 * Called when the activity is first created.
 */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_login);
    final CallbackManager callbackManager = CallbackManager.Factory.create();
    LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setReadPermissions("public_profile", "email", "user_friends");


    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            callbackManager.onActivityResult(requestCode, resultCode, data);
        }



        @Override
        public void onSuccess(LoginResult loginResult) {

            Intent i = new Intent(Login.this, MainActivity.class);
            startActivity(i);
            System.out.print("Logged in");

        }

        @Override
        public void onCancel() {
            // App code

        }

        @Override
        public void onError(FacebookException exception) {
            // App code
            Log.i("Error" , "Error");
            }


        });
    }
}

Deep linking unable to get data in Activity - Android?

I am enabling deep linking in App. It is working pretty fine. but I am facing problem when the app is already opened in background.

Case 1 - if my activity is set to "singleTop" and running in the background, so,the moment I open the link from browser it redirects to the same activity and call onNewIntent().

but I am not getting any data in onNewIntent()

onNewIntent(){
    Uri data = getIntent().getData();
    // data = null
}

Case 2- if I remove "singleTop" then everything works fine, but creating more instances of Activity.

Did anybody face this issue? How can we solve the Case 1 issue?

Regex to find instance of a number in a string

I have a string that is like the following

32686_8 is number 2

I am new to using regex and want some help. I want two different patterns, firstly to find

32686_8

and then another one to find

2

hope you can help :)

MapReduce output key in ascending order

I have a written a MapReduce code for which both keys and values are integers. The output is like this:

   Key    Value
1      78
128    12
174    26
2      44
2957   123
975    91

Is there a way that the output will be sorted by key in ascending order? such that the output looks like this:

1      78
2      44
128    12
174    26
975    91
2957   123

Do I need to use conf.setComparator ? If yes, how can I do that?

UnsatisfiedLinkError when invoking JProfiler

I am trying to Integrate Jprofiler 8.1.4 with jenkins using offline profiling API of JProfiler. Below is the program written to

  • Start JProfiler Recording.
  • Save Snapshot.
  • Stop JProfiler Recording.

    import java.io.File; import java.io.IOException;

    public class TestJenJPIntegration { public static Connection connObj = null; public static void recordCPUdata() throws java.io.IOException, InterruptedException{

        File fileObj;
        fileObj = new File("C:\\Perl\\firstSnap.jps");
        com.jprofiler.api.agent.Controller.startCPURecording(true);
                System.out.println("CPU recording started..");
    
                   Controller.saveSnapshot(fileObj);
        System.out.println("Saved snapshot");
    
                   Controller.stopCPURecording();
        System.out.println("CPU recording stopped..");    
    
    }
    
    public static void main(String[] args) throws IOException, InterruptedException {
          try {
    
            recordCPUdata();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    }
    
    

    }

The Jprofiler tool works fine manually to start recording, save snapshot and stop recording. But when i Execute the Program I get the following Error Message UnsatisfiedLinkError :

  • I used the Demo Server Profiling which was available in the JProfiler itself. And I am Profiling in the same system where the Demo Application runs.
  • NOTE: The server and client are using the same JProfilerTI.dll would this be a problem.

java.lang.UnsatisfiedLinkError: com.jprofiler.agent.InterceptionCallee.registerI nterceptions0(Z[Lcom/jprofiler/agent/util/h;Ljava/lang/reflect/Field;Ljava/lang/ reflect/Field;Ljava/lang/reflect/Field;Ljava/lang/reflect/Field;Ljava/lang/refle ct/Field;Ljava/lang/reflect/Field;Ljava/lang/reflect/Field;Ljava/lang/reflect/Fi eld;Ljava/lang/reflect/Field;Ljava/lang/Class;Ljava/lang/reflect/Method;Ljava/la ng/reflect/Method;)V at com.jprofiler.agent.InterceptionCallee.registerInterceptions0(Native Method) at com.jprofiler.agent.InterceptionCallee.registerInterceptions(ejt:152)

        at com.jprofiler.agent.probe.y.a(ejt:181)
        at com.jprofiler.agent.probe.y.a(ejt:37)
        at com.jprofiler.agent.Agent.initStatic(ejt:320)
        at com.jprofiler.agent.Agent.<clinit>(ejt:98)
        at com.jprofiler.agent.ControllerImpl.startCPURecording(ejt:53)
        at com.jprofiler.api.agent.Controller.startCPURecording(ejt:108)
        at TestJenJPIntegration.recordCPUdata(TestJenJPIntegration.java:24)
        at TestJenJPIntegration.main(TestJenJPIntegration.java:45)
JProfiler> Native library not found. Ignoring controller call.

/Users Printed Statement/

CPU recording started..

Exception in thread "_jprofiler_offline_comm" java.lang.UnsatisfiedLinkError: co
m.jprofiler.agent.ControllerImpl.saveSnapshot0([BLjava/lang/Object;)V
        at com.jprofiler.agent.ControllerImpl.saveSnapshot0(Native Method)
        at com.jprofiler.agent.ControllerImpl.access$100(ejt:18)
        at com.jprofiler.agent.h.run(ejt:186)

/Users Printed Statement/ Saved snapshot

JProfiler> Native library not found. Ignoring controller call.

/Users Printed Statement/ CPU recording stopped..

Polymorphism and DTO object creation

I develop application which contains few tiers. We have DAO layer which returns model objects. We also have mappers which instantiate DTO objects and send them to clients. Entities are mapped to DTOs in Controller layer. I've introduced inheritance in few entity classes. Let's assume sth like on image below

class diagram (not enough reputation points to past image directly)

I ask DAO for list of animals from the concrete ZOO. Then I get list List animals, but they are of concrete type because Animal is abstract and we cannot have just Animal in the database. I would like to create DTOs from this model objects. I have to use mapper in which I have if .. else statements checking type of each animal and then creating proper DTO, sth like

if (animal instanceof Dog) {
  .. create dog dto
} else if (animal instance of Cat) {
  .. create cat dto
} .. and so on

This code does not look nice. It would be nice to use polymorphism and call some method on each animal to produce DTO, but it is bad to have logic in domain model creating DTO objects just to communication. How do you resolve such situations?

Edit: To be more specific, I want to have DTO like 1. DogDTO which contains only fields color and name 2. FishDTO which contains only numberOfFins Not one big AnimalDTO with all possible attributes

What is "Error 4" in Android Web service SOAP?

I developped an Java Web Service and I invoke him from a Android appplication. However, when I call the method from the Android application that used the Web service I get as return value '4' and in the Web service I obtain 'Error 4'. I want to know what is causing this problem and how I could fixed it. Here I put the error I get in my web service:

    [ERROR] 4
java.lang.ArrayIndexOutOfBoundsException: 4
    at org.apache.axis2.databinding.utils.BeanUtil.deserialize(BeanUtil.java:630)
    at org.apache.axis2.rpc.receivers.RPCUtil.processRequest(RPCUtil.java:153)
    at org.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:206)
    at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:117)
    at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:40)
    at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:114)
    at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:181)
    at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:172)
    at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:146)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

SnakeYaml: handling multiline strings

I'm trying to use snakeYaml to save multiline strings (code snippets) in human-readable form. My scala code:

val code ="""// test
      |println("Hello world!")
      |exit(1)
    """.stripMargin

  val map: java.util.Map[String, String] = new java.util.HashMap[String, String]()
  map.put("Code", code)
  System.out.println(code)

  val options = new DumperOptions()
  options.setDefaultScalarStyle(ScalarStyle.PLAIN)

  val yamal = new Yaml(options)

  System.out.println(yamal.dump(map))

produces yaml:

Code: "// test\r\nprintln(\"Hello world!\")\r\nexit(1)\r\n\r\n        "

but should produce something like below. Playing with different options didn't help so far.

Code: | 
// test
println("Hello world!")
exit(1)

Link entities to existing tables without code

Assume that we have java entities already implemented annotated with Jpa annotations. We also have an existed data base lightly different to the schema described by the entities above. how I can link the data base with my entities without the code. Otherwise, how can i proceed from the begin when implementin my entities to make this stuff configurable ( give to user the possiblity of specifying the names of columns corresponding to the fields of each entity in an externalized configuration file). NB: I use hibernate as an ORM.

Quartz cron shedule is not triggered where expected to run every hour

The following expression is not triggered, but I expect it to be triggered every hour like 14:00, 15:00, 16:00

"0 0 0/1 * * ?"

Java: Deserialize a json to object in rest template using "@class" in json -SpringBoot

I have to instantiate a class which extends the abstract class from JSON using information in @class as shown below.

"name": {
  "health": "xxx",
  "animal": {
    "_class": "com.example.Dog",
    "height" : "20"
    "color" : "white"
  }
},

Here the abstract class is animal and dog extends the animal class. So using the information in @class, can we instantiate dog directly. Also this is the response I am getting in restTemplate

ResponseEntity<List<SomeListName>> response = restTemplate.exchange("http://ift.tt/1dBuJPs", HttpMethod.GET, request, responseType);

The following error is coming when this line is executed. Since the POJO classes are auto-generated, I cannot use annotations like @JsonTypeInfo

I am using Spring boot and maven. This error is coming in console.

Could not read JSON: Can not construct instance of "MyPOJO", problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information

Jaxb 2 counts of IllegalAnnotationExceptions

I keep getting this error and my application won't start, should I have this in a try { block ?

Unmarshal

File file = new File("xmlFiles/ipAdresses.xml");

            JAXBContext jaxbContext = JAXBContext.newInstance(IpAdressListXmlHandler.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            IpAdressListXmlHandler xmlList = (IpAdressListXmlHandler) jaxbUnmarshaller.unmarshal(file);
            System.out.println(xmlList);

no file, I deleted it

the class

@XmlRootElement
public class JAXBHandler {

    private String serverid;
    private String clientFileDir;
    private String serverFileDirectory;
    private int port;



    public void setPort(int port) {
        this.port = port;
    }


    public void setClientFileDir(String dir) {
        this.clientFileDir = dir;
    }




    public void setServerFileDirectory(String serverDir) {
        this.serverFileDirectory = serverDir;
    }


    public void setServerId(String serverId) {
        this.serverid = serverId;
    }


    @XmlElement
    public String getServerid() {
        return serverid;
    }
    @XmlElement
    public String getClientFileDir() {
        return clientFileDir;
    }
    @XmlElement
    public String getServerFileDirectory() {
        return serverFileDirectory;
    }
    @XmlElement
    public int getPort() {
        return port;
    }

I hope this is something simple, been fondling with this all night(seriously)

Get configuration string from server

My app needs to get a configuration string from a server on each start. I thought of creating a blank HTML page containing just this string. The app would then execute an http_get request to get that string from the server.

Is there a more elegant and free solution? (I don't have a webserver and most free websites embed ads or headers/footers into the html).

Multi threading with Swing progress bar

I am running out of ideas how to make my progress bar responsive during performing RMI connection, so I have decided to ask You for help.

Here's the code :

Thread performLogin = new Thread(new Runnable()
{

    @Override
    public void run()
    {
        LoginResult = TryLogin();
    }
});

performLogin.start();
WaiterFrame.setVisible(true);
SetProgressDialog();

try
{
    performLogin.join();
}
catch(InterruptedException exc)
{
    System.err.println(exc.getLocalizedMessage());
}

if (LoginResult)
{ ... }


WaiterFrame.setVisible(false);
this.dispose();

Progress bar is unresponsive - does not animate as it should while performing performLogin thread. I was trying to run progress bar frame on the other thread too, but result was the same (as well as using Eventqueue.invokelater()).

Could not resolve artifact error with Maven

When I build a module using Maven, I get the following error: Can anyone please let me know what this error means exactly?

[ERROR] Failed to execute goal com.dsths.common:container-maven-plugin:1.2.1:dis
t (build-distributions) on project pmDist: Unable to create distribution: Could
not resolve artifact: com.dsths.awdprovidermatching:pmConfig:jar:default-externa
l-jetty:1.0.2-SNAPSHOT:COMPILE -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
ch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please rea
d the following articles:
[ERROR] [Help 1] http://ift.tt/1sqyjQT
xception

How to run junits in play after Starting play application

I have a bunch of JUnit tests and wanted to execute them. The tests access my Play application host:port to call the REST API.

I use the following command to run the tests:

./activator  -Dhttp.port=8090 -Dhttps.port=8091  test

I also tried this way:

D:\sigma-idp\auth>activator  -Dhttp.port=8090 -Dhttps.port=8091  
[info] Loading project definition from D:\sigma-idp\auth\project
[info] Set current project to auth (in build file:/D:/sigma-idp/auth/)
[auth] $ test

But the problem here is that the application is not started yet and JUnit test tries to connect to the Play app to access my rest API. I am not sure why test did not start the application.

How can I start my play app before the JUnit test are fired?

Now I can execute tests only when the app is started using Eclipse.

Please suggest!

Error : org.apache.hadoop.mapred.InvalidInputException: Input path does not exist

I am new in nutch and solr integration.

I want to crawl new urls so I installed both solr version 4.6.0 and nutch version 1.6 in ubuntu.First I start with some configuration but i still get this error:

org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: File:/home/cloudera/apache-nutch-1.6/bin/20150529030452/crawl_fetch

Input path does not exist: file:/home/cloudera/apache-nutch-1.6/bin /20150529030452/crawl_parse

Input path does not exist: file:/home/cloudera/apache-nutch-1.6/bin/20150529030452/parse_data

Input path does not exist: file:/home/cloudera/apache-nutch-1.6/bin/20150529030452/parse_text

In the file logs I get this error:

2015-05-29 03:05:41,153 ERROR security.UserGroupInformation -PriviledgedActionException as:cloudera

cause:org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: file:/home/cloudera/apache-nutch-1.6/bin/20150529030452/crawl_fetch

Input path does not exist: file:/home/cloudera/apache-nutch-1.6/bin/20150529030452/crawl_parse

Input path does not exist: file:/home/cloudera/apache-nutch-1.6/bin/20150529030452/parse_data

Input path does not exist: file:/home/cloudera/apache-nutch-1.6/bin/20150529030452/parse_text

2015-05-29 03:05:41,153 ERROR solr.SolrIndexer - org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: file:/home/cloudera/apache-nutch-1.6/bin/20150529030452/crawl_fetch

Input path does not exist: file:/home/cloudera/apache-nutch-1.6/bin/20150529030452/crawl_parse

Input path does not exist: file:/home/cloudera/apache-nutch-1.6/bin/20150529030452/parse_data

Input path does not exist: file:/home/cloudera/apache-nutch-1.6/bin/20150529030452/parse_text

Whats the meaning of this, can you please explain whats the issue and how can I solve it.

I will highly appreciate your help.

CallObjectMethod does not return a string

My aim is to create an instance of a Java class in C++, and then call methods defined in the Java class.

Here is a summary of my Java class :

EXICodec.java

public class EXICodec {
    ...
    private static String inputXML;
    ...
    public EXICodec()
    {
        System.out.println("Constructor");  
        this.inputXML = "string";
        ...
    }
    ...
    public static void setInputXML(String inXML)
    {
        inputXML = inXML;
    }
    ...
    public static  String getInputXML()
    {
        return inputXML;
    }

Here is a summary of the C++ code used to interact with that class :

JavaInterface.hh

class JavaInterface
{
    private:
        JNIEnv*     JNIEnvironment;
        JavaVM*     javaVM;
        jclass      javaClass;
        jobject     javaClassInstance;

        jmethodID   IDconstructor;
        jmethodID   IDsetInputXML;
        jmethodID   IDgetInputXML;

    public:
        JavaInterface();                    
        void init_context( void);               
        void init_class( void);
        void init_methods( void);                   

        void setInputXML( std::string);
        std::string getInputXML( void);
}

JavaInterface.cc

void JavaInterface::init_context(){..}    //initiate the JNIEnvironment & javaVM attributes
void JavaInterface::init_class(){..}      //initiate the javaClass attribute
void JavaInterface::init_methods()
{
     this->IDconstructor = this->JNIEnvironment->GetMethodID(this->javaClass, "<init>", "()V");
     if (this->IDconstructor == NULL) 
     {
         throw std::runtime_error("JAVA_INIT_METHOD_EXCEPTION");
     }

     this->IDsetInputXML = this->JNIEnvironment->GetStaticMethodID(this->javaClass, "setInputXML", "(Ljava/lang/String;)V");
     if (this->IDsetInputXML == NULL) 
     {
         throw std::runtime_error("JAVA_INIT_METHOD_EXCEPTION");
     }

     this->IDgetInputXML = this->JNIEnvironment->GetStaticMethodID(this->javaClass, "getInputXML", "()Ljava/lang/String;");
}
     if (this->IDgetInputXML == NULL) 
     {
         throw std::runtime_error("JAVA_INIT_METHOD_EXCEPTION");
     }

void JavaInterface::j_constructor()
{
    this->javaClassInstance = this->JNIEnvironment->NewObject(this->javaClass, this->IDconstructor);      
    if (this->javaClassInstance == NULL) 
    {
        throw std::runtime_error("JAVA_CONSTRUCTOR_CALL_EXCEPTION");
    }
}

void JavaInterface::j_setInputXML( std::string str)
{   
    jstring argument = this->JNIEnvironment->NewStringUTF(str.c_str());
    this->JNIEnvironment->CallVoidMethod(this->javaClassInstance, this->IDsetInputXML, argument);
}

std::string JavaInterface::j_getInputXML()
{
    jstring javaString = NULL;

    // ---> PROBLEM HERE : javaString is still NULL after the line below : <---
    javaString = (jstring)this->JNIEnvironment->CallObjectMethod(this->javaClassInstance, this->IDgetInputXML, 0);  

    // jString to char*
    const char *nativeString = this->JNIEnvironment->GetStringUTFChars(javaString, JNI_FALSE);
    // char* to std::string
    std::string str(nativeString);

    this->JNIEnvironment->ReleaseStringUTFChars(javaString, nativeString);

    return str;
}   

So my problem is that the call of CallObjectMethod does not return anything. I tried to change the Java method to static but it did not change.

More generally, how would you return a string from Java to C++? Maybe my starting idea is bad.

Why node_crypto is giving different result than Java Cypher?

I'm trying to understand why encrypted data changes when using Java or Node.js to encrypt it, I need to adapt node.js code to make it return exactly the same encrypted data that I have on Java. (Note that I cannot modify the java snippet)

Node.js Implementation:

var crypto = require('crypto');

console.log("\n\n============");
var cKey = new Buffer("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "utf-8");
var cIv = new Buffer("1111111111111111", "utf-8");
var cData = "x";
console.log(cKey);
console.log(cIv);
console.log("UTF-8 Data: " + cData);

var cipher = crypto.createCipheriv("aes-256-cbc", cKey, cIv);
var cipherText = cipher.update(cData, 'utf8', 'hex') + cipher.final('hex');

console.log("Our data: " + cipherText);

The previous snippet will print the following result:

<Buffer 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41>
<Buffer 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31>
UTF-8 Data: x
Our data: 0eddfe1857248c7057904455d189cf31

Java Implementation:

AesSymmetricKey key = new AesSymmetricKey("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".getBytes());
byte[] data = "x".getBytes();
byte[] iv = "1111111111111111".getBytes();
byte[] encrypted = new EncryptionService().encryptAesData(data, iv, key);
Cipher cipher = Cipher.getInstance("AES");
IvParameterSpec ivspec = new IvParameterSpec(initializationVector);
            cipher.init(Cipher.ENCRYPT_MODE, key, ivspec);
byte[] result = cipher.doFinal(data);
_print(result);

That snippet will print:

17b0ccd594229baa6dabd5e850e07fdf

Please note that I compared bytes for data, iv and key and those are exactly the same.

How can I modify node's snippet to make it return the same bytes of java's?

Installing Hadoop 2.6.0 on Ubuntu 12.04

I downloaded hadoop 2.6.0 from apache mirrors and trying to build it from source and trying to follow link. I have java 1.7 and maven 3.0.4 installed.

When i started building hadoop it gave me error saying hadoop-common its unable to download. So i downloaded it from a separate pom then i came across.

[ERROR] Failed to execute goal org.apache.hadoop:hadoop-maven-plugins:2.6.0:protoc (compile-protoc) on project hadoop-common: org.apache.maven.plugin.MojoExecutionException: protoc version is 'libprotoc 2.4.1', expected version is '2.5.0' -> [Help 1]

When i searched for help i got the above link mentioned. I am stuck at step where we are trying to configure protobuf when i run the command "./configure..." i get the error

 bash: ./configure: No such file or directory

Kindly suggest a better way or please give step by step so that its clear enough to follow. kindly help me.

the maven run failed with following details:

[WARNING] [protoc, --version] failed with error code 1
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO] 
[INFO] Apache Hadoop Main ................................ SUCCESS [1.258s]
[INFO] Apache Hadoop Project POM ......................... SUCCESS [0.430s]
[INFO] Apache Hadoop Annotations ......................... SUCCESS [1.802s]
[INFO] Apache Hadoop Project Dist POM .................... SUCCESS [0.446s]
[INFO] Apache Hadoop Assemblies .......................... SUCCESS [0.228s]
[INFO] Apache Hadoop Maven Plugins ....................... SUCCESS [1.479s]
[INFO] Apache Hadoop MiniKDC ............................. SUCCESS [1.115s]
[INFO] Apache Hadoop Auth ................................ SUCCESS [2.244s]
[INFO] Apache Hadoop Auth Examples ....................... SUCCESS [0.896s]
[INFO] Apache Hadoop Common .............................. FAILURE [0.351s]
[INFO] Apache Hadoop NFS ................................. SKIPPED
[INFO] Apache Hadoop KMS ................................. SKIPPED
[INFO] Apache Hadoop Common Project ...................... SKIPPED
[INFO] Apache Hadoop HDFS ................................ SKIPPED
[INFO] Apache Hadoop HttpFS .............................. SKIPPED
[INFO] Apache Hadoop HDFS BookKeeper Journal ............. SKIPPED
[INFO] Apache Hadoop HDFS-NFS ............................ SKIPPED
[INFO] Apache Hadoop HDFS Project ........................ SKIPPED
[INFO] hadoop-yarn ....................................... SKIPPED
[INFO] hadoop-yarn-api ................................... SKIPPED
[INFO] hadoop-yarn-common ................................ SKIPPED
[INFO] hadoop-yarn-server ................................ SKIPPED
[INFO] hadoop-yarn-server-common ......................... SKIPPED
[INFO] hadoop-yarn-server-nodemanager .................... SKIPPED
[INFO] hadoop-yarn-server-web-proxy ...................... SKIPPED
[INFO] hadoop-yarn-server-applicationhistoryservice ...... SKIPPED
[INFO] hadoop-yarn-server-resourcemanager ................ SKIPPED
[INFO] hadoop-yarn-server-tests .......................... SKIPPED
[INFO] hadoop-yarn-client ................................ SKIPPED
[INFO] hadoop-yarn-applications .......................... SKIPPED
[INFO] hadoop-yarn-applications-distributedshell ......... SKIPPED
[INFO] hadoop-yarn-applications-unmanaged-am-launcher .... SKIPPED
[INFO] hadoop-yarn-site .................................. SKIPPED
[INFO] hadoop-yarn-registry .............................. SKIPPED
[INFO] hadoop-yarn-project ............................... SKIPPED
[INFO] hadoop-mapreduce-client ........................... SKIPPED
[INFO] hadoop-mapreduce-client-core ...................... SKIPPED
[INFO] hadoop-mapreduce-client-common .................... SKIPPED
[INFO] hadoop-mapreduce-client-shuffle ................... SKIPPED
[INFO] hadoop-mapreduce-client-app ....................... SKIPPED
[INFO] hadoop-mapreduce-client-hs ........................ SKIPPED
[INFO] hadoop-mapreduce-client-jobclient ................. SKIPPED
[INFO] hadoop-mapreduce-client-hs-plugins ................ SKIPPED
[INFO] Apache Hadoop MapReduce Examples .................. SKIPPED
[INFO] hadoop-mapreduce .................................. SKIPPED
[INFO] Apache Hadoop MapReduce Streaming ................. SKIPPED
[INFO] Apache Hadoop Distributed Copy .................... SKIPPED
[INFO] Apache Hadoop Archives ............................ SKIPPED
[INFO] Apache Hadoop Rumen ............................... SKIPPED
[INFO] Apache Hadoop Gridmix ............................. SKIPPED
[INFO] Apache Hadoop Data Join ........................... SKIPPED
[INFO] Apache Hadoop Ant Tasks ........................... SKIPPED
[INFO] Apache Hadoop Extras .............................. SKIPPED
[INFO] Apache Hadoop Pipes ............................... SKIPPED
[INFO] Apache Hadoop OpenStack support ................... SKIPPED
[INFO] Apache Hadoop Amazon Web Services support ......... SKIPPED
[INFO] Apache Hadoop Client .............................. SKIPPED
[INFO] Apache Hadoop Mini-Cluster ........................ SKIPPED
[INFO] Apache Hadoop Scheduler Load Simulator ............ SKIPPED
[INFO] Apache Hadoop Tools Dist .......................... SKIPPED
[INFO] Apache Hadoop Tools ............................... SKIPPED
[INFO] Apache Hadoop Distribution ........................ SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 11.698s
[INFO] Finished at: Fri May 29 14:15:45 IST 2015
[INFO] Final Memory: 49M/342M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.hadoop:hadoop-maven-plugins:2.6.0:protoc (compile-protoc) on project hadoop-common: org.apache.maven.plugin.MojoExecutionException: protoc version is 'libprotoc 2.4.1', expected version is '2.5.0' -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://ift.tt/1bGwP7h
[ERROR] 
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :hadoop-common

Template class in Java

Suppose that there is a class called Test like this

public class Test<A extends X, B extends Y> {
    public int testing(long n) {
       a(new Good(n));
       return 1;
   }
}

I want to use this class as Test<Good, Bad>. Good class is constructed by long type, but this doesn't work because a function in testing requires A type, not Good. In this case what can I do to use A type?

Single process blocking queue

I am writing an application that communicates with hardware. While the application can receive and process multiple requests simultaneously in parallel, the hardware cannot!

The hardware requires these parallel requests to basically be organised into a linear request chain each one executed one after the other.

I also have a requirement to be able to prioritise requests given that some of are background processes with no urgency and some are live and need to be jumped to the front of the queue for immediate processing.

I don't have much experience with queues however I would be surprised if such a library didn't already exist.

How to get types, in Clojure, from classes declared by Java?

The following code

(-> (.getField (Class/forName
                "ccg.flow.processnodes.text.retrievers.Dictionary.Dictionary")
     "wordsTuples") .getType)

tells me that wordsTuples is a java.util.ArrayList. But what I would like to be able to learn is that it is an ArrayList with elements of type String[], since it happens to be declared like this:

public class Dictionary extends ProcessNode {
    public ArrayList<String[]> wordsTuples;

    public ArrayList<String> words;
...

Is there a way to obtain the type hint information programmatically within Clojure?

jUnit change behavior of a method

I have to make some jUnit tests for some methods and I can't change the source code. Is there any possibility to change the behavior of a function without change source code? Look a straight-forward example: Class A and B are source code (can't change them). I want to change behavior of run() method from A when I call it in B through testing() in Junit test. Any ideas?

public class A {
    public String run(){
        return "test";
    } 
}

public class B {
    public void testing() {
        String fromA = new A().run(); //I want a mocked result here
        System.out.println(fromA);
    }
}

public class C {
    @Test
    public void jUnitTest() {
        new B().testing();
        // And here i want to call testing method from B but with a "mock return" from run()         
    }
}

Passing undefined to Nashorn Javascript in Scala/Java

I need to evaluate this function in Javascript from Scala/Java

function hello(a, b) {
    return a+b;
}

I did this basic code:

val factory = new ScriptEngineManager(null)
val engine = factory.getEngineByName("JavaScript")

val body =
  """
    |function hello(a, b) {
    |    return a+b;
    |}
  """.stripMargin
engine match {
  case engine: Invocable =>
    engine.eval(body)
    println(engine.invokeFunction("hello", null, 1: java.lang.Double))
}

For the parameter a I'm passing a null and I get a 1.0 as a result. If I hack my javascript (I DON'T WONT TO DO THIS) and I make it:

function hello(a, b) {
    if (a === null) {
        a = undefined;
    }
    return a+b;
}

I get the expected NaN.

The correct solution would be passing an undefined to the invokeFunction: How do I do this?

I'm puzzling in hibernate and mysql when commit the transaction

I am facing a problem that when I use hibernate+spring+mysql to commiting my data from pages to database,the transaction didn't commit. Or perhaps my configuration is somewhere wrong.

The following is my configuration and code:

1.spring-config.xml(The configuration of spring)

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/webtest?charset=UTF-8" />
        <property name="user" value="root" />
        <property name="password" value="kevin" />
        <property name="initialPoolSize" value="5"/>
        <property name="minPoolSize" value="5"/>
        <property name="maxPoolSize" value="15" />
        <property name="checkoutTimeout" value="1000" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.kevin" />
        <property name="namingStrategy">
            <bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">select</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
                <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop>
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
                <!-- <prop key="connection.autocommit">true</prop> -->
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
        <property name="sessionFactory"><ref bean="sessionFactory"/></property>
    </bean>

    <tx:annotation-driven />
</bean>

2.User.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 *@author kevin
 *@date 2015年5月29日 上午11:24:17
 *
 **/
@Entity
@Table(name="sys_user")
public class User implements Serializable{

    private static final long serialVersionUID = -8693332653054586507L;
    @Id
    @Column(name="user_id")
    private String id;
    @Column(name="user_real_name")
    private String name;
    @Column(name="user_education")
    private String edu;
    getter()setter()...
}

3.UserService.java

@Service
public class UserService {

    @Resource
    private UserDao userDao;

    @org.springframework.transaction.annotation.Transactional
    public boolean createUser(User user) {
        try {
            user.setId(String.valueOf(new Date().getTime()));
            userDao.add(user);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

4.UserDao.java

@Repository
public class UserDao extends BaseDao<User, String>{
    public UserDao() {
        super(User.class);
    }
}

5.BaseDao.java

public abstract class BaseDao<T, PK extends Serializable> {
    private SessionFactory sessionFactory;
    private Class<T> cls;

    public BaseDao(Class<T> t) {
        cls = t;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    @Resource
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    //@Transactional
    public void add(T t) throws Exception {
        sessionFactory.getCurrentSession().save(t);
        //sessionFactory.getCurrentSession().flush();
    }
}

The code above is just a test code, but it cannot persist to the database. Of course, if I use session.flush(),it can commit to the database,but I think it is not a good way, because it cannot ensure the consistent of the transaction.

So I am puzzling heavy what wrong with my test and code.

Android Base64 Encoding and Apache codec decoding

We are using following method for encoding a string using ANDROID Base64.NO_CLOSE

    public static String encrypt(String inputString, byte[] keyBytes) {
    Calendar cal = Calendar.getInstance();
    int mDay = cal.get(Calendar.DAY_OF_MONTH);
    // System.out.println("Day of month :::" + mDay);
    String encryptedString = "";
    Key publicKey = null;
    try {
        Random generator = new Random(mDay);
        int num = (generator.nextInt()) % 100;
        String salt = "WEER563784" + num;
        inputString += salt;
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        publicKey = keyFactory.generatePublic(publicKeySpec);
    } catch (Exception e) {
        System.out.println("Exception rsaEncrypt:::::::::::::::::  "
                + e.getMessage());
        e.printStackTrace();
    }
    // Encode the original data with RSA public key
    byte[] encodedBytes = null;
    try {
        Cipher c = Cipher.getInstance("RSA");
        c.init(Cipher.ENCRYPT_MODE, publicKey);
        encodedBytes = c.doFinal(inputString.getBytes());
        encryptedString = Base64.encodeToString(encodedBytes,
                Base64.NO_CLOSE);
        System.out.println(encryptedString);
    } catch (Exception e) {
        System.out.println("Exception rsaEncrypt:::::::::::::::::  "
                + e.getMessage());
        e.printStackTrace();
    }

    return encryptedString;
}

The generated encrypted string is being decrypted outside Android app using following method

public static String decrypt(String inputString, byte[] keyBytes) {
        String resultStr = null;
        Calendar cal = Calendar.getInstance();
        int mDay = cal.get(Calendar.DAY_OF_MONTH);
        Random generator = new Random(mDay);
        int num = (generator.nextInt()) % 100;
        String salt = "qqq" + num;
        PrivateKey privateKey = null;
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyBytes);
            privateKey = keyFactory.generatePrivate(privateKeySpec);
        } catch (Exception e) {
            System.out.println("Exception privateKey:::::::::::::::::  "
                    + e.getMessage());
        }
        byte[] decodedBytes = null;
        try {
            Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            // Cipher c = Cipher.getInstance("RSA");
            c.init(Cipher.DECRYPT_MODE, privateKey);
            // decodedBytes = c.doFinal(Base64.decodeBase64(inputString));
            decodedBytes = c.doFinal(Base64InputStream());

        } catch (Exception e) {
            System.out.println("Exception privateKey1:::::::::::::::::  "
                    + e.getMessage());
            e.printStackTrace();
        }
        if (decodedBytes != null) {
            resultStr = new String(decodedBytes);
            System.out.println("resultStr:::" + resultStr + ":::::");
            resultStr = resultStr.replace(salt, "");
        }
        return resultStr;

    }

We are getting following exceptions

javax.crypto.BadPaddingException: Decryption error
    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:365)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
    at javax.crypto.Cipher.doFinal(Cipher.java:2087)
    at RSAEncryption.decrypt(RSAEncryption.java:41)
    at RSAEncryption.main(RSAEncryption.java:108)

So the questions are

1) Is it possible to decrypt the encrypted string using ANDROID Base64.NO_CLOSE, outside Android, i mean directly in the IDE?

2) In one of post I found that string encrypted using ANDROID Base64.NO_WRAP can be decrypted outside Android env, is this a correct understanding?

Thanks a lot for you your help in advance.

Regards, Amit

JComboBox set start index to "1"

Is there an easy way to set the start index of an JComboBox to "1" or "2"? If you start your application the index is normal set to "0" but I want to start with index "1" instead.

Edit:

JComboBox variableBox_1 = new JComboBox();
        for (int i = 0; i < dataModel.getVariableNames().size(); i++) {
            variableBox_1.addItem(dataModel.getVariableNames().get(i));
        }
        JPanel comBoxPanel1 = new JPanel(new BorderLayout());
        JLabel comBoxLabel1 = new JLabel("X:");
        comBoxPanel1.add(variableBox_1, BorderLayout.CENTER);
        comBoxPanel1.add(comBoxLabel1, BorderLayout.WEST);
        optionPanel.add(comBoxPanel1);
        variableBox_1.addActionListener((ActionEvent e) -> {
            sp.setVariableNumberX(variableBox_1.getSelectedIndex());
            hg1.setVariableNumber(variableBox_1.getSelectedIndex());
            sp.setXvariableText(dataModel.getVariableNames().get(variableBox_1.getSelectedIndex()));
        });

Jboss Failed to instantiate class "org.jboss.logmanager.handlers.PeriodicRotatingFileHandle

When I tried jbosseap6.3 install as service. I got below error. Anyone have any idea on the below error. Any one shed light means it is very helpful for me.

java.lang.IllegalArgumentException: Failed to instantiate class "org.jboss.logmanager.handlers.PeriodicRotatingFileHandler" for handler "FILE"
    at org.jboss.logmanager.config.AbstractPropertyConfiguration$ConstructAction.validate(AbstractPropertyConfiguration.java:119)
    at org.jboss.logmanager.config.LogContextConfigurationImpl.doPrepare(LogContextConfigurationImpl.java:338)
    at org.jboss.logmanager.config.LogContextConfigurationImpl.prepare(LogContextConfigurationImpl.java:291)
    at org.jboss.logmanager.config.LogContextConfigurationImpl.commit(LogContextConfigurationImpl.java:300)
    at org.jboss.logmanager.PropertyConfigurator.configure(PropertyConfigurator.java:542)
    at org.jboss.logmanager.PropertyConfigurator.configure(PropertyConfigurator.java:97)
    at org.jboss.as.logging.logmanager.ConfigurationPersistence.configure(ConfigurationPersistence.java:149)
    at org.jboss.logmanager.LogManager.readConfiguration(LogManager.java:300)
    at org.jboss.logmanager.LogManager.readConfiguration(LogManager.java:262)
    at java.util.logging.LogManager$3.run(LogManager.java:399)
    at java.util.logging.LogManager$3.run(LogManager.java:396)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.logging.LogManager.readPrimordialConfiguration(LogManager.java:396)
    at java.util.logging.LogManager.access$800(LogManager.java:145)
    at java.util.logging.LogManager$2.run(LogManager.java:345)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.logging.LogManager.ensureLogManagerInitialized(LogManager.java:338)
    at java.util.logging.LogManager.getLogManager(LogManager.java:378)
    at org.jboss.modules.Main.main(Main.java:443)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at org.jboss.logmanager.config.AbstractPropertyConfiguration$ConstructAction.validate(AbstractPropertyConfiguration.java:117)
    ... 18 more
Caused by: java.io.FileNotFoundException: C:\jboss-eap-6.3\standalone\log\server.log (The process cannot access the file because it is being used by another process)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at org.jboss.logmanager.handlers.FileHandler.setFile(FileHandler.java:154)
    at org.jboss.logmanager.handlers.PeriodicRotatingFileHandler.setFile(PeriodicRotatingFileHandler.java:105)
    at org.jboss.logmanager.handlers.FileHandler.setFileName(FileHandler.java:192)
    at org.jboss.logmanager.handlers.FileHandler.<init>(FileHandler.java:122)
    at org.jboss.logmanager.handlers.PeriodicRotatingFileHandler.<init>(PeriodicRotatingFileHandler.java:73)
    ... 23 more
Shutdown JBossEAP6.3.0 service [2015-05-29 09:58:27]

How to get cursor result using Spring Jdbc?

All I am new to Spring. I am trying to call store procedure which is returning result in the form of cursor.I tried with rowMapper also even with OracleTypes.CURSOR. But every time I am getting error.I am using Oracle Database. Please guide me. Where I am doing wrong.I tried all the jdbc option to pass the parameter but not able to figure out.

Procedure

create or replace PROCEDURE SELECT_DETAILS
(IN_Logged_User_ID NUMBER)
AS
cursor SELECT_ALL_DATA is
    select
        type,
        type_desc,
        file_format,
        decode(active_flg, 'Y',1,0) as active_flg,
        to_char(modified_date, 'mm/dd/yyyy hh24miss') as modified_date
    from dtt
    order by doc_type;
ERR_MSG varchar2(600);
APP_ERROR exception;
Err_no       NUMBER;
BEGIN
  IF Err_no = -1 THEN
  RAISE APP_ERROR;
     RETURN;
  END IF;

    BufferMgr.ClearBuffer;
    BufferMgr.MaxColumns(6);
    for dttRow in SELECT_ALL_DATA
    loop
        BufferMgr.PutColumn(dttRow.doc_type);
        BufferMgr.PutColumn(dttRow.doc_type);
        BufferMgr.PutColumn(dttRow.doc_type_desc);
        BufferMgr.PutColumn(dttRow.def_file_format);
        BufferMgr.PutColumn(dttRow.active_flg);
        BufferMgr.PutColumn(dttRow.modified_date);
        BufferMgr.NewRow;
    end loop;

    exception
    when APP_ERROR then
        Rollback;
        BufferMgr.PutColumn('!@#$' || ERR_MSG);
        BufferMgr.NewRow;
        RAISE BufferMgr.app_errors_exit;
    when others then
        Rollback;
        BufferMgr.PutColumn('!@#$' || TrackORAError(SQLCODE,SQLERRM));
        BufferMgr.NewRow;
        RAISE BufferMgr.app_errors_exit;
END;

Java

public Map<?, ?> simpleProcedureCall(String procedureName,Long loginId){
        SimpleJdbcCall procReader = new SimpleJdbcCall(jdbcTemplate);
        procReader.withProcedureName(procedureName).declareParameters(new SqlOutParameter("SELECT_ALL_DATA",OracleTypes.CURSOR, new DocTypeMapper()),
                new SqlParameter("IN_Logged_User_ID", Types.NUMERIC));
        SqlParameterSource inParams = new MapSqlParameterSource().addValue("IN_LOGGED_USER_ID", loginId,Types.NUMERIC);
        Map<String, Object> simpleJdbcCallResult =  procReader.execute(inParams);
        return simpleJdbcCallResult;
    }

    private class DocTypeMapper implements RowMapper<DocumentType> 
    {
        @Override
        public DocumentType mapRow(ResultSet rs, int rowNum) throws SQLException {

             DocumentType docTypeObject = new DocumentType();
             docTypeObject.setDocType(rs.getString("type"));
             docTypeObject.setDescription("type_desc");
             docTypeObject.setFileFormat("file_format");
             docTypeObject.setIsActive("active_flg");
             docTypeObject.setLastModified("modified_date");
            return docTypeObject;
        }  

    }

error.

Caused by: org.springframework.jdbc.BadSqlGrammarException: CallableStatementCallback; bad SQL grammar [{call SELECT_DETAILS()}]; nested exception is java.sql.SQLException: ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'SELECT_DETAILS'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored

    at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:1137)
    at org.springframework.jdbc.core.JdbcTemplate.call(JdbcTemplate.java:1173)
    at org.springframework.jdbc.core.simple.AbstractJdbcCall.executeCallInternal(AbstractJdbcCall.java:378)
    at org.springframework.jdbc.core.simple.AbstractJdbcCall.doExecute(AbstractJdbcCall.java:341)
    at org.springframework.jdbc.core.simple.SimpleJdbcCall.execute(SimpleJdbcCall.java:190)
    at com.apple.ist.nfa.shared.dao.ProcedureExecutorDAO.simpleProcedureCall(ProcedureExecutorDAO.java:56)
    at com.apple.ist.nfa.service.controller.impl.DocumentService.getDocumentType(DocumentService.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:137)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:296)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:250)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:237)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:356)
    ... 30 more
Caused by: java.sql.SQLException: ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'SELECT_DETAILS'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored

Facebook Integration using java

I am using a facebook4j to send a post on my Facebook wall. While doing so, I am facing an error. The error is showing in my console is when running my code. I have checked my appid, appSecret and accesstoken values which are also correct.

Here is the code I am using to send the message:

public static void  sendMessage(){
        Facebook facebook = new FacebookFactory().getInstance();
        String appId = "XXXXX";
        String appSecret = "XXXXXXXXXXX";
        facebook.setOAuthAppId(appId, appSecret);
        String commaSeparetedPermissions ="user_friends,user_groups,user_photos,user_videos,user_birthday,user_status,user_likes,user_activities,user_location";
        facebook.setOAuthPermissions(commaSeparetedPermissions);
        String accessToken = "XXXXXXXXXXXXXX";
        facebook.setOAuthAccessToken(new AccessToken(accessToken, null));

        try {
            facebook.postStatusMessage("Hello World from Facebook4J From Java Programming....");
        } catch (FacebookException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

I am getting the below error in my console:

FacebookException [statusCode=400, response=HttpResponse{statusCode=400, responseAsString='{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
', is=sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@335678, streamConsumed=true}, errorType=OAuthException, errorMessage=An active access token must be used to query information about the current user., errorCode=2500]
    at facebook4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:189)

Can someone point out my error?

How can i select all the check boxes on single click while every check box has unique name using java script please provide code

![enter image description here][1]


  [1]: http://ift.tt/1J7M6Er
How can i select all the check boxes on single click while every check box has unique name using java script please provide code
How can i select all the check boxes on single click while every check box has unique name using java script please provide code

How can i select all the check boxes on single click while every check box has unique name using java script please provide code How can i select all the check boxes on single click while every check box has unique name using java script please provide code

 </div><!-- /.box-header -->
                <div class="box-body">
                 <form name="permissionfrm" method="post" id="permissionfrm">
                 <input type="hidden" name="permission" id="permission" value="assignpermission" />
                  <table id="example1" class="table table-bordered table-striped">
                    <thead>
                     <tr>
                      <th>Give All Permissions
                      </th><td><input type="checkbox" name="addadmin" id="addadmin" value="Check All" onClick="this.value=check(this.form.list)"/></td>
                      </tr>
                      <tr>
                        <th>Add</th>
                        <th>Edit</th>
                        <th>View</th>
                        <th>Delete</th>
                      </tr>
                     </thead>
                    <tbody>

java final variables and performance

Is it good, if the java code is oversaturated with final variables? I think about performance. As far as I know, the final variables are thread safe. So, for each initialization on final variable jvm must synchronize its value among all threads. If I use final variables in every case where I want the variable to be non-modifiable, will it strike performance?

I expect and afraid that final variables will DECREASE the performance.

How do you get the font and graphic of a column header in a JTable

I am trying to get the graphic and font of a column header in a JTable. To do this I am using the code

Graphics g = myTable.getColumnModel().getColumn(i).getGraphics();
Font f = myTable.getColumnModel().getColumn(i).getFont();

However that produces a can't find symbol error Can't find symbol error

The full code for this program is

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.lang.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.text.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.*;
import java.lang.Object.*;
import javax.swing.text.*;
import java.awt.FontMetrics;
import java.awt.Font;
import java.awt.Graphics;


public class JtableIe
{
    JFrame myMainWindow = new JFrame("Compare Tables");

    JPanel  firstPanel = new JPanel();

    JScrollPane myScrollTable;
    JTable myTable;
    JTextField srchFld1;
    JTextField srchFld2;
    TableRowSorter sorter;
    JLabel srchLbl1 = new JLabel();
    JLabel srchLbl2 = new JLabel();
    DefaultTableModel model;

    int testMaxMinSize = 0;

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String []fontFamilies = ge.getAvailableFontFamilyNames();

    public void runGUI()
    {
        myMainWindow.setBounds(10, 10, 1296, 756);

        myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        myMainWindow.setLayout(new GridLayout(1,1));

        createFirstPanel();

        myMainWindow.getContentPane().add(firstPanel);

        myMainWindow.setVisible(true);
    }

    public void createFirstPanel()
    {
        firstPanel.setLayout(null);

        srchLbl1.setLocation(0,0);
        srchLbl1.setSize(150,26);
        srchLbl1.setText("Name Search:");
        firstPanel.add(srchLbl1);

        srchLbl2.setLocation(660,0);
        srchLbl2.setSize(150,26);
        srchLbl2.setText("ID Search:");
        firstPanel.add(srchLbl2);

        String[] aHeaders = {"Name","ID","Number 1","Number 2","Time","Date"};
        Object[][] aData = new Object[5][6];

        ///////Data////////
        aData[0][0] = "John";
        aData[0][1] = "JS96";
        aData[0][2] = "1";
        aData[0][3] = "186";
        aData[0][4] = "1h 23m";
        aData[0][5] = getJavaDate("12/11/2015");

        aData[1][0] = "David";
        aData[1][1] = "DB36";
        aData[1][2] = "2";
        aData[1][3] = "111852";
        aData[1][4] = "2h 55m";
        aData[1][5] = getJavaDate("12/11/2020");

        aData[2][0] = "Daniel";
        aData[2][1] = "DK73";
        aData[2][2] = "3";
        aData[2][3] = "2921";
        aData[2][4] = "1h 55m";
        aData[2][5] = getJavaDate("12/11/2014");

        aData[3][0] = "Janis";
        aData[3][1] = "JW84";
        aData[3][2] = "4";
        aData[3][3] = "6512";
        aData[3][4] = "12h 26m";
        aData[3][5] = getJavaDate("13/11/2015");

        aData[4][0] = "Adam";
        aData[4][1] = "AF98";
        aData[4][2] = "5";
        aData[4][3] = "7524";
        aData[4][4] = "5h 47m";
        aData[4][5] = getJavaDate("11/11/2015");
        //////////////
        model = new DefaultTableModel(aData, aHeaders)
        {
            @Override
            public Class<?> getColumnClass(int column) 
            {
                switch (column)
                {
                    case 5: return Date.class;
                    default: return Object.class;
                }
            }

            @Override
            public boolean isCellEditable(int row, int column) 
            {
               return false;//all cells false
            }
        };

        myTable = new JTable(model);

        myTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        myTable.setAutoCreateRowSorter(true);

        sorter = new TableRowSorter(myTable.getModel());
        List sortKeys = new ArrayList();
        sortKeys.add(new RowSorter.SortKey(5, SortOrder.ASCENDING));
        sorter.setSortKeys(sortKeys);
        setRenderers();
        myTable.setRowSorter(sorter);

        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment( SwingConstants.CENTER );
        myTable.setDefaultRenderer(Object.class, centerRenderer);

        DefaultRowSorter sorter = (DefaultRowSorter) myTable.getRowSorter();

        setMinPrefMax();

        myScrollTable = new JScrollPane(myTable); 
        myScrollTable.setSize(1296,756); 
        myScrollTable.setLocation(0,25); 
        System.out.println("Creating compare table");

        srchFld1 = new JTextField(10);
        srchFld1.setSize(550,26); 
        srchFld1.setLocation(100,0);
        srchFld1.setToolTipText("Enter Name");
        firstPanel.add(srchFld1);

        srchFld2 = new JTextField(10);
        srchFld2.setSize(550,26); 
        srchFld2.setLocation(740,0);
        srchFld2.setToolTipText("Enter ID");
        firstPanel.add(srchFld2);

        //////////////////////
        Document doc = srchFld1.getDocument();
        DocumentListener listener = new DocumentListener() 
        {

            @Override
            public void insertUpdate(DocumentEvent e) 
            {
                newFilter();
            }

            @Override
            public void removeUpdate(DocumentEvent e) 
            {
                newFilter();
            }

            @Override
            public void changedUpdate(DocumentEvent e) 
            {
                newFilter();
            }
        };
        doc.addDocumentListener(listener);

        ///////////////
        Document docb = srchFld2.getDocument();
        DocumentListener listenerb = new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) 
            {
                newFilter();
            }

            @Override
            public void removeUpdate(DocumentEvent e) 
            {
                newFilter();
            }

            @Override
            public void changedUpdate(DocumentEvent e) 
            {
                newFilter();
            }
        };
        docb.addDocumentListener(listenerb);
        ///////////////

        firstPanel.add(myScrollTable);
    }

    public void setMinPrefMax()
    {
        for (int i = 0; i < myTable.getColumnCount(); i++) 
        {
            String Hello = myTable.getColumnModel().getColumn(i).getHeaderValue()+"";
            System.out.println(Hello);
            Graphics g = myTable.getColumnModel().getColumn(i).getGraphics();
            Font f = myTable.getColumnModel().getColumn(i).getFont();
            FontMetrics metrics = g.getFontMetrics(f);
            int minLength = metrics.stringWidth(Hello)+10;
            System.out.println(minLength);
            myTable.getColumnModel().getColumn(i).setMinWidth(minLength);
        }
    }

    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");

    private void setRenderers() 
    {
        DateRenderer dr = new DateRenderer();
        dr.setHorizontalAlignment(SwingConstants.CENTER);
        myTable.setDefaultRenderer(Date.class, dr);
    }

    private Date getJavaDate(String s) 
    {
        try 
        {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Date d = sdf.parse(s);
            return d;
        } 

        catch (ParseException ex) 
        {
            Logger.getLogger(TableBasic.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    private void newFilter()
    {
        RowFilter rf = null;
        try 
        {
            List<RowFilter<Object,Object>> filters = new ArrayList<RowFilter<Object,Object>>(2);
            filters.add(RowFilter.regexFilter("(?i)"+srchFld1.getText(), 0));
            filters.add(RowFilter.regexFilter("(?i)"+srchFld2.getText(), 1));
            rf = RowFilter.andFilter(filters);
        } 
        catch (java.util.regex.PatternSyntaxException e) 
        {
            return;
        }
        sorter.setRowFilter(rf);
    }

    public static void main(String[] args)
    {
        JtableIe ji = new JtableIe();
        ji.runGUI();
    }

    private class DateRenderer extends DefaultTableCellRenderer 
    {

        private static final long serialVersionUID = 1L;

        @Override
        public Component getTableCellRendererComponent(JTable myTable, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(myTable, value, isSelected, hasFocus, row, column);
            if (!(value instanceof Date)) {
                return this;
            }
            setText(DATE_FORMAT.format((Date) value));
            return this;
        }
    }
}

And the code for TableBasic is

import java.awt.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.table.*;

public class TableBasic {

    private JFrame frame = new JFrame();
    private  String[] columnNames = {"Date", "String", "Long", "Boolean"};
    private Object[][] data = {
        {getJavaDate("13-11-2020"), "A", new Double(1), Boolean.TRUE},
        {getJavaDate("13-11-2018"), "B", new Double(2), Boolean.FALSE},
        {getJavaDate("12-11-2015"), "C", new Double(9), Boolean.TRUE},
        {getJavaDate("12-11-2015"), "D", new Double(4), Boolean.FALSE}
    };
    private DefaultTableModel model = new DefaultTableModel(data, columnNames) {
        @Override
        public Class<?> getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }
    };
    private JTable table = new JTable(model);
    private JScrollPane scrollPane = new JScrollPane(table);
    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");

    public TableBasic() {
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        table.setAutoCreateRowSorter(true);
        setRenderers();
        // DefaultRowSorter has the sort() method
        table.getRowSorter().toggleSortOrder(0);
        frame.add(scrollPane);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void setRenderers() {
        //TableColumnModel m = table.getColumnModel();
        //"Integer", "String", "Interger", "Double", "Boolean", "Double", "String", "Boolean", "Date"
        table.setDefaultRenderer(Date.class, new DateRenderer());
    }

    private Date getJavaDate(String s) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            Date d = sdf.parse(s);
            return d;

        } catch (ParseException ex) {
            Logger.getLogger(TableBasic.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                TableBasic frame = new TableBasic();
            }
        });
    }

    private class DateRenderer extends DefaultTableCellRenderer {

        private static final long serialVersionUID = 1L;

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (!(value instanceof Date)) {
                return this;
            }
            setText(DATE_FORMAT.format((Date) value));
            return this;
        }
    }
}

Note

The code causing the errors is in the for loop inside the method called setMinPrefMax()

mercredi 6 mai 2015

jhipster bookstore tutorial - Only display the footer view at runtime

I'm trying to start using hipster. I've completed the installation and tried to recreate the same bookstore app like in the demo video. Everything went well (installation, app creation, app startup, DB schema creation) but when I access the application in the browser, I only the text "This is your footer". I don't have the header and the body like in the demo. There is no error in the console. I assume something is wrong with AngularJS but I don't know what.

I'm on Mac OS 10.10 JDK 1.8._45 eclipse Luna (I've successfully imported the generated hipster project as a Maven project)

If you have any suggestion on where to investigate. Thanks.

Insert special character into a string variable

I am new in java and i am trying to solve this problem.

How to save string ( /[\+]+/.test(elements[i]) ) ? elements[i].replace(\"+\",\"_\") : elements[i];" + into a variable

Sorry for bad english

Thankyou.

Error generating PMD report in eclipse

I've tried to generate an XML report by right-clicking the project > PMD> Generate Reports

After which this error dialog box appears.

An internal error occurred during: "RenderReport". java.lang.NullPointerException

Please help. How to fix this?

GWT & superdevmode

Hope I will find the key guy here :)

First, I am very new in gwt/java....so, please forgive me if my question in somehow malformed or out of scope.

Based on samples found in the net, I developped a gwt webapp....that's works fine (so far) when it is started in superdevmode from eclipse (through jetty). A browser can access my webpage from local/remote computer (bindaddress=0.0.0.0).

Issues are coming when trying to deploy it with TomCat. Indeed, webpage is accessible, but at some point, there is a redirection to port 9786. I guess this is a normal situation since it is built in superdevmode (unless bad asumption here). If I set the development mode in eclipse to Classic mode. It does not work even in eclipse.

From my point of view, having a web server listening on port 9786 is not a proper implementation....So, I am trying to get rid of this port (probably a matter of dev mode).

Any idea, question, remark, or whatever would be welcome....cause I am getting stucked! Obviously, I will be happy to provide more info if needed for resolution.

Txs a lot for your help.

Reference to undefined variable jrebel_args

Getting following error while trying to run Struts 2 app on server (Apache Tomcat 7, Eclipse - Kepler). Previously I installed jRebel from Eclipse marketplace and then uninstalled it.

How can I get rid of jRebel_args ?.

I searched for jrebel_args all over the Application, don't have any occurrence.

enter image description here

Can't import a project to eclipse (Facebook SDK)

I downloaded the Facebook SDK from here: http://ift.tt/1faJH8z and I can't import it to eclipse. I had no problem with the previous version which I downloaded from the same page a while ago.

I'm stuck here, I don't know what to do.

enter image description here

How can i write two or more test cases while creating script for IOS using Appium tool

I am using appium 1.3.1. I wrote a test script using the java for IOS application & uses two @test Annotation with priority.But after the successful completion of one of the Test the execution get stop. Here is the code :

@Test(priority=1) public void test1() throws Exception{ driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[2]/UIAButton[3]")).click(); driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[2]/UIAButton[4]")).click(); System.out.println("ABC"); } @Test(priority=2) public void test2() throws Exception{ driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[2]/UIATableView[1]/UIATableCell[1]/UIASwitch[1]")).click(); driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[2]/UIATableView[1]/UIATableCell[2]/UIASwitch[1]")).click(); driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[2]/UIATableView[1]/UIATableCell[3]/UIASwitch[1]")).click(); System.out.println("XYZ"); }

Android SDK manager linux permission issue

The problem is I can't install anything with the sdk manager if I'm not root. The "android" tool runs but I get permissions error. However when I try to run it as root I get this:

java.lang.NullPointerException
at java.io.File.<init>(File.java:277)
at com.android.sdklib.internal.avd.AvdManager.parseAvdInfo(AvdManager.java:1616)
at com.android.sdklib.internal.avd.AvdManager.buildAvdList(AvdManager.java:1577)
at com.android.sdklib.internal.avd.AvdManager.<init>(AvdManager.java:350)
at com.android.sdklib.internal.avd.AvdManager.getInstance(AvdManager.java:373)
at com.android.sdklib.internal.repository.updater.UpdaterData.initSdk(UpdaterData.java:254)
at com.android.sdklib.internal.repository.updater.UpdaterData.<init>(UpdaterData.java:122)
at com.android.sdkuilib.internal.repository.SwtUpdaterData.<init>(SwtUpdaterData.java:61)
at com.android.sdkuilib.internal.repository.ui.SdkUpdaterWindowImpl2.<init>(SdkUpdaterWindowImpl2.java:104)
at com.android.sdkuilib.repository.SdkUpdaterWindow.<init>(SdkUpdaterWindow.java:88)
at com.android.sdkmanager.Main.showSdkManagerWindow(Main.java:407)
at com.android.sdkmanager.Main.doAction(Main.java:390)
at com.android.sdkmanager.Main.run(Main.java:150)
at com.android.sdkmanager.Main.main(Main.java:116)

I'm runnin Archlinux 64 bit btw

Python import error in bayesoptimization

The code is :

import bayesopt
from bayesoptmodule import BayesOptContinuous
import numpy as np

from time import clock

# Function for testing.
def testfunc(Xin):
    total = 5.0
    for value in Xin:
        total = total + (value -0.33)*(value-0.33)

    return total

# Class for OO testing.
class BayesOptTest(BayesOptContinuous):
    def evaluateSample(self,Xin):
        return testfunc(Xin)


# Let's define the parameters
# For different options: see parameters.h and cpp
# If a parameter is not define, it will be automatically set
# to a default value.
params = {}
params['n_iterations'] = 50
params['n_iter_relearn'] = 5
params['n_init_samples'] = 2

print ("Callback implementation")

n = 5                     # n dimensions
lb = np.zeros((n,))
ub = np.ones((n,))

start = clock()
mvalue, x_out, error = bayesopt.optimize(testfunc, n, lb, ub, params)

print ("Result", mvalue, "at", x_out)
print ("Running time:", clock() - start, "seconds")
raw_input('Press INTRO to continue')

print ("OO implementation")
bo_test = BayesOptTest(n)
bo_test.parameters = params
bo_test.lower_bound = lb
bo_test.upper_bound = ub

start = clock()
mvalue, x_out, error = bo_test.optimize()

print ("Result", mvalue, "at", x_out)
print ("Running time:", clock() - start, "seconds")
raw_input('Press INTRO to continue')

print ("Callback discrete implementation")
x_set = np.random.rand(100,n)
start = clock()

mvalue, x_out, error = bayesopt.optimize_discrete(testfunc, x_set, params)

print ("Result", mvalue, "at", x_out)
print ("Running time:", clock() - start, "seconds")

value = np.array([testfunc(i) for i in x_set])
print ("Optimum", value.min(), "at", x_set[value.argmin()])

When I run the Python program I get the error like this: File "G:\workspace\Independentstudy\src\demo\demo_quad.py", line 27, in import bayesopt ImportError: No module named 'bayesopt
I have used the Eclipse IDE and PyDev and Python 3 the bayesopt is a c++ file i have included in pythonpath by going to properties > pythonpath. I have read the tutorial regarding this.