Feeds:
Posts
Comments

Archive for August, 2017

use the -F option of curl:
-F/--form <name=value> Specify HTTP multipart POST data

if there are multiple form fields, use multiple -F options.

for more details, refer to https://curl.haxx.se/docs/manpage.html#-F

example curl command line to upload a file:

curl -F “testFieldName=testFieldValue” -F “file=@/Users/zcai/Downloads/test_file.txt” –header “Authorization: Bearer your_token_string” http://hostname:port/webapp/rest/file/upload/testMethod

You can set any header information. The example above shows the Authorization token.

Java JAS-RS backend:

@POST

@Consumes(MediaType.MULTIPART_FORM_DATA)

@Path(“/upload/testMethod)

public Response uploadFile(MultipartFormDataInput multipart) {

InputStream is = null;

    BufferedReader in = null;

    String testFieldName = “”;

    String fileName = “”;

   

try {

//get original file name, refer to https://stackoverflow.com/questions/26333298/multipartform-how-to-get-the-original-file-name

    Map<String, List<InputPart>> formParts = multipart.getFormDataMap();

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

    for (InputPart inputPart : inPart) {

        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(“\””,“”);          

          }

        }

    }

//get form file inputstream   

is = multipart.getFormDataPart(“file”, InputStream.class, null);

in = new BufferedReader(new InputStreamReader(is));

//get form input field

testFieldName = multipart.getFormDataPart(testFieldName, String.class, null);

    String line = in.readLine();

       List<String> fileContent = new ArrayList<String>();

    while ((line = in.readLine()) != null) {

    System.out.println(line);

    }

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

in.close();

is.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return Response.ok().entity(fileName + ” has been uploaded to database successfully.\n”).build();

}

Read Full Post »

in root pom.xml

<build>

<pluginManagement>

<plugins>

<plugin>

</plugin>

<plugin>

<groupId>external.atlassian.jgitflow</groupId>

<artifactId>jgitflowmavenplugin</artifactId>

<version>1.0-m5.1</version>

<configuration>

<enableSshAgent>false</enableSshAgent>

<autoVersionSubmodules>true</autoVersionSubmodules>

<pushFeatures>true</pushFeatures>

<pushReleases>true</pushReleases>

<pushHotfixes>true</pushHotfixes>

<noDeploy>true</noDeploy>

<allowUntracked>true</allowUntracked>

<username>git (or bitbucket ) name</username>

<password>password</password>

<flowInitContext>

<masterBranchName>master</masterBranchName>

<developBranchName>development</developBranchName>

<featureBranchPrefix>feature-</featureBranchPrefix>

<releaseBranchPrefix>release-</releaseBranchPrefix>

<hotfixBranchPrefix>hotfix-</hotfixBranchPrefix>

<versionTagPrefix>your-web-app-</versionTagPrefix>

</flowInitContext>

</configuration>

</plugin>

</plugins>

</pluginManagement>

</build>

 

in ear pom.xml

<profiles>

<profile>

<!– When built in OpenShift the ‘openshift‘ profile will be used when

invoking mvn. –>

<!– Use this profile for any OpenShift specific customization your app

will need. –>

<!– By default that is to put the resulting archive into the ‘deployments’

folder. –>

<!– http://maven.apache.org/guides/mini/guide-building-for-different-environments.html –>

<id>openshift</id>

<build>

<plugins>

<plugin>

<artifactId>maven-ear-plugin</artifactId>

<version>${version.ear.plugin}</version>

<configuration>

<outputDirectory>deployments</outputDirectory>

</configuration>

</plugin>

<plugin>

<groupId>external.atlassian.jgitflow</groupId>

<artifactId>jgitflowmavenplugin</artifactId>

<configuration>

<enableSshAgent>false</enableSshAgent>

<autoVersionSubmodules>true</autoVersionSubmodules>

<pushFeatures>true</pushFeatures>

<pushReleases>false</pushReleases>

<pushHotfixes>true</pushHotfixes>

<noDeploy>true</noDeploy>

<allowUntracked>true</allowUntracked>

<username>git (or bitbucket ) name</username>

<password>password</password>

<flowInitContext>

<masterBranchName>master</masterBranchName>

<developBranchName>development</developBranchName>

<featureBranchPrefix>feature-</featureBranchPrefix>

<releaseBranchPrefix>release-</releaseBranchPrefix>

<hotfixBranchPrefix>hotfix-</hotfixBranchPrefix>

<versionTagPrefix>your-web-app-</versionTagPrefix>

</flowInitContext>

</configuration>

</plugin>

</plugins>

</build>

</profile>

</profiles>

when running it in eclipse, jgitflow:release-start -DallowSnapshots=true worked well, but jgitflow:release-finish -DallowSnapshots=true had the error like ” EMBEDDED/bin/mvn: No such file or directory”. .

The solution is to download a standalone maven and run it using command lines:

apache-maven-3.3.9/bin/mvn jgitflow:release-start -DallowSnapshots=true

apache-maven-3.3.9/bin/mvn jgitflow:release-finish -DallowSnapshots=true

Another solution is to user external maven instead of embedded one:

In eclipse, click on “Run configuration…”,  configure Maven runtime, add external maven.

After successfully running release-finish, go to bitbucket, under the “tag” tab you will find the release your-web-app-versionNumber

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 »