Feeds:
Posts
Comments

Archive for the ‘JAVA/J2EE’ Category

cd ~/wildfly-10.1.0.Final/modules/

~/jdk1.8.0_131/bin/java -cp ./system/layers/base/org/jboss/logging/main/jboss-logging-3.3.0.Final.jar:./system/layers/base/org/picketbox/main/picketbox-4.9.6.Final.jar org.picketbox.datasource.security.SecureIdentityLoginModule your-password-string

Encoded password:

-224b0dffed3998dfd6eb091793d10850b2ef7287d7b50175

 

edit wildfly configuration file such as standalone.xml as follows:

  1. add security domain with the above generated encoded password

                <security-domain name=”encrypted-ds-name” cache-type=”default”>

                    <authentication>

                        <login-module code=”org.picketbox.datasource.security.SecureIdentityLoginModule” flag=”required”>

                            <module-option name=”username” value=”user-name”/>

                            <module-option name=”password” value=”

-224b0dffed3998dfd6eb091793d10850b2ef7287d7b50175

“/>

                        </login-module>

                    </authentication>

                </security-domain>

2. add data source

                <datasource jndi-name=”java:jboss/datasources/db-oracle” pool-name=”db-oracle” enabled=”true” use-java-context=”true”>

                    <connection-url>jdbc:oracle:thin:@xxx.com:1521/testdb</connection-url>

                    <driver>oracle</driver>

                    <security>

                        <security-domain>encrypted-ds-name</security-domain>

                    </security>

                </datasource>

Read Full Post »

host:~ zcai$ /usr/libexec/java_home -v 1.8

/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home

keytool -list -keystore jre/lib/security/cacerts > ~/java_cacerts.txt

Enter keystore password:  changeit
Take a look at java_cacerts.txt. See if it includes the same certificate that is present in the browser by searching for a matching serial number. In the java_cacerts.txt file, the serial number will be in lowercase and without the ":" colon character. If it is not present, then this could be the reason for the error, and we can fix this by adding the certificate found in the browser.

Show certificate and save it to ~/Downloads/ldaps_ca.txt

openssl s_client -showcerts -connect shdc2.seres.local:636

vi ~/Downloads/ldaps_ca.txt

keytool -import -alias ldaps_ca -keystore ./jre/lib/security/cacerts -file 

You will be prompted for a password, use ‘changeit’

~/Downloads/ldaps_ca.txt 

reference:

http://magicmonster.com/kb/prg/java/ssl/pkix_path_building_failed.html

Read Full Post »

public class MyConfig {

public static Properties appProperties() throws IOException {

//method 1: in application configuration, the configuration file my-config.properties is in src/main/resources

//refer to https://stackoverflow.com/questions/2161054/where-to-place-and-how-to-read-configuration-resource-files-in-servlet-based-app

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

InputStream inStream = classLoader.getResourceAsStream(“ngs16s-config.properties”);

Properties properties = new Properties();

properties.load(inStream);

//method 2: in container configuration, the configuration file my-config.properties is in $WILDFLY_HOME/standalone/configuration
//https://stackoverflow.com/questions/27953261/wildfly-reading-properties-from-configuration-directory

String fileName = System.getProperty(“jboss.server.config.dir”) + “/my-config.properties”;

Properties properties = new Properties();

FileInputStream fis = new FileInputStream(fileName);

properties.load(fis);

}

}

my-config.properties file has key-value pairs separated by tab, such as
my_property_name  my_property_value

How to use it:

String myProperty = MyConfig.appProperties().getProperty(“my_property_name”)

Read Full Post »

my SQL note

  1. modify Oracle table column example
    alter table batch modify(column_name number(3,0));

Read Full Post »

List<InputPart> inPart = formParts.get(“file”);

// “file” should

// match the name

// attribute of your

// HTML file input

for (InputPart inputPart : inPart) {

// Retrieve headers, read the Content-Disposition header to

// obtain the original name of the file

MultivaluedMap<String, String> headers = inputPart.getHeaders();

String[] contentDispositionHeader = headers.getFirst(“Content-Disposition”).split(“;”);

for (String name : contentDispositionHeader) {

if ((name.trim().startsWith(“filename”))) {

String[] tmp = name.split(“=”);

fileName = tmp[1].trim().replaceAll(“\””, “”);

}

}

}

Read Full Post »

working example:

String [] cmd ={“/bin/sh”,“-c”,“sleep 60;nohup ls -l /Users/zcai/Downloads > /Users/zcai/Downloads/tmp.txt &”};

ProcessBuilder builder = new ProcessBuilder(cmd);

Read Full Post »

The problem description is here:

https://stackoverflow.com/questions/12955266/ajax-call-to-download-file-returned-from-restful-service

Here is a solution:

@SuppressWarnings(“unchecked”)

@GET

@Path(“/download/{name}”)

@Produces(MediaType.TEXT_PLAIN)

public Response getXByName(@PathParam(“nameame”) final String name) {

Query query = entityManager.createQuery(“SELECT b.x FROM B b WHERE …”);

List<String> results = query.getResultList();

final StringBuilder sb = new StringBuilder();

results.forEach(x->sb.append(x).append(“\n”));

return Response

.ok(sb.toString(), MediaType.APPLICATION_OCTET_STREAM)

.header(“Content-Disposition”, “attachment; filename = test_text_file.txt”

.build();

}

}

The above resful API does not work when invoked in javascript/AJAX. The following is a solution to make it work in AJAX.

$.ajax({

        url: your_url,

        type: GET,

        contentType: “application/json; charset=utf-8”,

        headers: {

            ‘Authorization’ : “Bearer “ + authorization_token,

        },

        success: function(response) {//response is the data to be saved to a file to your local           disk

        var windowUrl = window.URL || window.webkitURL;

        var url = windowUrl.createObjectURL(new Blob([response], {type: ‘text/plain’}));

        var anchor = document.createElement(‘a’);

        anchor.href = url;

        anchor.download = “file_name”;

        anchor.click();

        windowUrl.revokeObjectURL(url);

        }

});

javascript cannot download a file and save it to your local disk for security reason. Here I create a blob from the data and an object URL, then create an anchor element and use javascript to simulate the behavior of clicking to download the file from the blob URL.

Read Full Post »

This link explained it:

https://stackoverflow.com/questions/11063567/java-cdi-persistencecontext-and-thread-safety/13607626#13607626

Here I provide some test results and more details.

Repository1.java

import javax.ejb.Stateless;

import javax.inject.Inject;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

import javax.ws.rs.Path;

@Stateless

@Path(“/test”)

public class Repository1 {

@Inject

private Repository2 rep2;

@PersistenceContext(unitName = “yourunitname”)

private EntityManager entityManager;

@Path(“/test”)

public void doSomething() {

System.out.println(“Repository1—“ + this.toString() + “—“ + System.identityHashCode(entityManager) + “—“ + entityManager.getClass().getSimpleName() + “—“ + entityManager.getDelegate() + “—“ + entityManager.getDelegate().hashCode());

rep2.doSomethingAgainInTheSameTransaction();

}

}

 

Repository2.java

import javax.ejb.Stateless;

import javax.ejb.TransactionAttribute;

import javax.ejb.TransactionAttributeType;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

@Stateless

public class Repository2 {

@PersistenceContext(unitName = “yourunitname”)

private EntityManager entityManager;

//@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)

public void doSomethingAgainInTheSameTransaction() {

System.out.println(“Repository2—“ + this.toString() + “—————“ + System.identityHashCode(entityManager) + “—“ + entityManager.getClass().getSimpleName() + “—“ + entityManager.getDelegate() + “—“ + entityManager.getDelegate().hashCode());

}

}

when you run Repository1.doSomething(), it will start a transaction and call rep2.doSomethingAgainInTheSameTransaction(), because the defaultTransactionAttributeType of rep2.doSomethingAgainInTheSameTransaction() is REQUIRED so rep2.doSomethingAgainInTheSameTransaction() will run under the same transaction of Repository1.doSomething(). Under the same transaction, persistenceContext and entityManager should be the same. If you compare the output in the two classes, the entityManager.getDelegate().hashCode() is the same, but System.identityHashCode(entityManager) is different. That is because when the instances of Repository1 and Repository2 are initiated, entityManager is injected by container, but the injected entityManager is NOT the EntityManager object, it is the proxy of an entityManager, so System.identityHashCode(entityManager)  is different in the two classes, which injected two different objects of entityManager proxy to entityManager and the two different objects of entityManager proxy delegate calls to the same EntityManager object or Hibernate Session in this case, so entityManager.getDelegate().hashCode() is the same.

If you uncomment this line//@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) in  Repository2.java and run it again, both entityManager.getDelegate().hashCode() and System.identityHashCode(entityManager) are different. Because rep2.doSomethingAgainInTheSameTransaction() runs in a separate transaction and this transaction has a different persistenceContext and entityManager(different entityManager proxy which delegates calls to a different EntityManager object or Hibernate Session in this case).

Read Full Post »

jpa locking

some good introduction to different locking types:

http://lostincoding.blogspot.com/2015/11/differences-in-jpa-entity-locking-modes.html

http://www.byteslounge.com/tutorials/locking-in-jpa-lockmodetype

https://stackoverflow.com/questions/13581603/jpa-and-optimistic-locking-modes

https://docs.oracle.com/javaee/7/tutorial/persistence-locking001.htm

Read Full Post »

        <subsystem xmlns=”urn:jboss:domain:transactions:3.0″>

            <core-environment node-identifier=”younameit”>

                <process-id>

                    <uuid/>

                </process-id>

            </core-environment>

            <recovery-environment socket-binding=”txn-recovery-environment” status-socket-binding=”txn-status-manager”/>

        </subsystem>

in standalone.xml add node-identifier=”younameit” to core-environment

Read Full Post »

Older Posts »