Serialize the map on every iteration

I have a ConcurrentHashMap which stores ID and timestamp when this ID was updated.
This data is to be persistent as application restart should be aware of the previous state of the data when shut-down was called.
I am currently serializing the map to a file on shut-down and loading it back when the application restarts.

However I can foresee that the serialization on shutdown would fail when the disk is full. And this would mean data-loss which is unacceptable.
I thought of using a DB to store the data but then it would add network weight on every update.

The only thing that comes to my mind right now is to serialize the map on every update. This would ensure that most of the data is persistent in case of disk full also even in case of Unexpected shutdown.

I am aware that this is a heavy operation and am open for alternative solutions.

Also note, this map may hold over 1200K entries…

Thanks in advance

MySQL connection via Android error

i have a littel Problem with my Android Project.
I want to fill a list whith data from my mysql database, but android would not connect to it.

Here’s my code:

MySQLConnector:

 private static Connection con = null;

private static String dbHost = "85.214.101.213"; // changed the ip :)
private static String dbPort = "3306"; // Port -- Standard: 3306
private static String dbName = "ticketsystem"; // Datenbankname
private static String dbUser = "admin"; // Datenbankuser
private static String dbPass = "root"; // Datenbankpasswort

public static void conect() {
    try {
        Class.forName("com.mysql.jdbc.Driver"); // Datenbanktreiber für JDBC

        System.out.println("jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName + "?" + "user="
                + dbUser + "&" + "password=" + dbPass);

        con = DriverManager.getConnection("jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName + "?" + "user="
                + dbUser + "&" + "password=" + dbPass);




    } catch (ClassNotFoundException e) {
        System.out.println("Treiber nicht gefunden");
    } catch (SQLException e) {
        System.out.println(e);
        System.out.println("Verbindung nicht moglich");
        System.out.println("SQLException: " + e.getMessage());
        System.out.println("SQLState: " + e.getSQLState());
        System.out.println("VendorError: " + e.getErrorCode());
    }


}

SQLManager:

public SQLManager() {
    MySQLConnection.conect();
    Log.e("test", "nach conect");
    con = MySQLConnection.getCon();
}


 p public String[] getFreeEvents() {

    ArrayList<String> mList = new ArrayList();

    try
    {
        PreparedStatement ps = con.prepareStatement(" SELECT `EventID`,`Name`,`Zeit`,`Ort` FROM `event` WHERE `freeTickets` >= ?");

        ps.setInt(1, 0);
        ResultSet rs = ps.executeQuery();
        while (rs.next())
        {
            int EventID = rs.getInt("EventID");
            String Name = rs.getString("Name");
            String Zeit = rs.getString("Zeit");
            String Ort = rs.getString("Ort");

            String info = Name +"," + Zeit + ","+Ort  ;

            mList.add(info);
            System.out.println(info);
        }


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

    String[] array = mList.toArray(new String[0]);
    return array;
}

And the Class form the Android activity:

  Button b;
ListView list;
EditText vor;
TextView nach;
SQLManager man = new SQLManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_ticket);
    setContentView(R.layout.activity_main);
    b = findViewById(R.id.button);
    b.setOnClickListener(this);
    list = findViewById(R.id.list);
    list.setAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, man.getFreeEvents())); //here is the SQL request...
    vor = findViewById(R.id.editText);
    nach = findViewById(R.id.editText2);
}

My probem is that Android could not open a connction.
i have added the Permission request in the Android Manifest:

 <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

So at least i get this error:

I/System.out: `com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.´
I/System.out: Verbindung nicht moglich
I/System.out: SQLException: Could not create connection to database server.
I/System.out: SQLState: 08001
I/System.out: VendorError: 0
E/test: nach conect
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: ml.gottfried.myapp, PID: 10440
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{ml.gottfried.myapp/ml.gottfried.myapp.NewTicket}: java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.PreparedStatement java.sql.Connection.prepareStatement(java.lang.String)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                   Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.PreparedStatement java.sql.Connection.prepareStatement(java.lang.String)' on a null object reference
                      at ml.gottfried.myapp.SQLManager.getFreeEvents(SQLManager.java:82)
                      at ml.gottfried.myapp.NewTicket.onCreate(NewTicket.java:43)
                      at android.app.Activity.performCreate(Activity.java:6679)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
                      at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:154) 
                      at android.app.ActivityThread.main(ActivityThread.java:6119) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

I hope you can help me

Thanks 🙂

PS: If you have any quesstions ask them 🙂

java filterFile DSL example

I want to use filterFile inside my camel route.

I have route like this:

from(String.format("sftp://%s@%s:%d/%s?password=%s&delete=true&readLock=changed&delay=%s,
                systemSettingsService.getSystemSettings().getSftpUserName(),
                systemSettingsService.getSystemSettings().getSftpHost(),
                systemSettingsService.getSystemSettings().getSftpPort(),
                systemSettingsService.getSystemSettings().getSftpSourcePathDestWorking(),
                systemSettingsService.getSystemSettings().getSftpPassword(),
                systemSettingsService.getSystemSettings().getSftpPollPeriod()))...

I have read file2 doc

Here is written:

Camel 2.18: Filters the file based on Simple language. For example to filter on file size, you can use ${file}:size > 5000.

But I don’t understand where should I use this simple language.

How to make an HTTPS-ready RESTful Java client with Jersey client

I followed this tutorial on how to make a Restful WS using jersey and it run smoothly using http.

http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/

Then, I decided to make the tomcat server (HTTPS) secured so I followed this tutorial:

https://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html

From there, I browsed for references on how I can make the client – server calling work again but to no success.

I tried putting these:

        System.setProperty("javax.net.ssl.keyStore", "C:/Program Files/Java/jdk1.7.0_79/keystore/keyStoreFile.jks");
        System.setProperty("javax.net.ssl.keyStorePassword", "changeit");

and still no success.

Logs:

com.sun.jersey.api.client.ClientHandlerException: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching localhost found
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149)
    at com.sun.jersey.api.client.Client.handle(Client.java:648)
    at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670)
    at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
    at com.sun.jersey.api.client.WebResource$Builder.get(WebResource.java:503)
    at com.mkyong.client.JerseyClientGet.main(JerseyClientGet.java:18)
Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching localhost found
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1904)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:279)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:273)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1446)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:209)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:901)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:837)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1023)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1332)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1359)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1343)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1301)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:240)
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:147)
    ... 5 more
Caused by: java.security.cert.CertificateException: No name matching localhost found
    at sun.security.util.HostnameChecker.matchDNS(HostnameChecker.java:208)
    at sun.security.util.HostnameChecker.match(HostnameChecker.java:93)
    at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:347)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:203)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1428)
    ... 19 more

Can I get Jetty to rewrite Cookie paths?

We’ve got a lot of applications based on Jetty. For historical reasons; these have been sitting behind Apache servers. One of the duties of Apache has been rewrites, and we want to move to using just Jetty. But we are hitting some snags when it comes to porting it. Specifically Cookie path rewrites. Is it even possible in Jetty?

The original config for Apache looks like this:

ProxyPassMatch          ^/${basePattern}/${market}/(${appContextName}/.*)                http://127.0.0.1:8080/app/${symbol_dollar}1 retry=0
ProxyPassReverse        /                                                             http://127.0.0.1:8080/

ProxyPassInterpolateEnv on
ProxyPassReverseCookiePath /appCookiePath /${basePattern}/${market}/${appContextName} interpolate

I’ve looked at the code for both Rule (from the rewrite API) as well as Jetty Handlers. I can’t really find anything in those APIs that would let me rewrite the Cookies… Any pointers?

How pass value from a method to another in a servlet

 private void ajouterActeurFilm(HttpServletRequest request, HttpServletResponse response) throws Exception{

        String nom= request.getParameter("acteurRecherche");

        ArrayList<Celebrite> listeActeurs= dao.RechercherActeur(nom);           

        RequestDispatcher dispatcher
                = request.getRequestDispatcher("/WEB-INF/AjouterActeurFilm.jsp");
        dispatcher.forward(request, response);

    }

    private void ajouterActeur(HttpServletRequest request, HttpServletResponse response) throws Exception{

        String id=request.getParameter("idMedia");            

         RequestDispatcher dispatcher
                = request.getRequestDispatcher("/WEB-INF/AjouterActeurFilm.jsp");
        dispatcher.forward(request, response);

    }

Hello everybody , i’m a beginner in java and i would like to know is is possible to pass the value “id” from the method “ajouterActeur” to “ajouterActeurFilm”

Thank you in advance

Parsing JsonArray With JsonObject?

Hello how to get data from Json Array in another Json array i have get data till attachments but attachment doesnt work, i still getting the error on the line code

java

   private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("items");
            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject post = (JSONObject) feedArray.get(i);
                PostItem searchItem = new PostItem();
                searchItem.setId(post.getString("id"));
                searchItem.setName(post.getString("title"));
                searchItem.setDescription(Utils.getSummaryFromHTML(post.getString("content"), 140));

                searchItem.setContent(post.getString("content"));
                if (response.has("images")) {
                    searchItem.setImage(response.getJSONObject("images").getString("url"));
                } else {
                    searchItem.setImage(Utils.getFirstImage(post.getString("content"), Boolean.valueOf(false)));
                }

                searchItem.setTimeStamp(post.getString("updated"));
                if (post.has("labels")) {
                    JSONArray labels = post.getJSONArray("labels");
                    List<String> cat = new ArrayList();
                    for (int ix = 0; ix < labels.length(); ix++) {
                        cat.add(labels.getString(ix));
                    }
                    searchItem.setCategory(Utils.join(cat, ","));
                }
                searchItem.setUrl(post.getString("url"));
                this.feedItems.add(searchItem);
            }
            this.listView.setVisibility(View.VISIBLE);
            this.listAdapter.notifyDataSetChanged();
            this.isLoadingProgress = false;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

error line

PostItem searchItem = new PostItem();

error line

thank you

Immutable class using static factories

I’m studying Effective Java by Joshua Bloch, where he explains about different ways of achieving immutable class. To prevent subclassing, one way is to use final. The more sophisticated way for it is to make constructor private, thus preventing outside access, and using static factories for object creation.

However, I don’t understand this statement:

public class Complex {
    private final double re;
    private final double im;

    private Complex(double re, double im) {
        this.re = re;
        this.im = im;
    }

    public static Complex valueOf(double re, double im) {
        return new Complex(re, im);
    }
}

It is most flexible because it allows the use of multiple package-private implementation classes.

I understand that it’s not possible for an outside client to subclass it in absence of a public/protected constructor, but do not understand what is being conveyed by the term ‘multiple package private implementation classes’.

AutoIT from Java environment with Jacob – but WITHOUT registering any DLL

i figured out how to make use of AutoIT from Java environment under windows 7 and 10 with support of JACOB (https://sourceforge.net/projects/jacob-project/), a JAVA COM Bridge. I did it exactly the way described here and it works fine so far:
https://ron190blog.wordpress.com/2014/01/23/automatisation-of-your-desktop-with-autoitx4java-autoit-and-java-com-bridge/

Unfortunately, i have no grants to register any dll on that target machine. Registering a dll requires admin rights. Is there any way to use AutoIT from JAVA without registering the dll? Any idea?

Best regards,
Teimo