Uploading file to test as FormDataParam - java

So I have problem with testing my application. I am trying to do REST/HTTP test. Here is my code:
#Path("/ftpaction")
public class JerseyFileUpload {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response postMsg(#HeaderParam("FTP-Host") String Host, #HeaderParam("FTP-Port") String Port,
#HeaderParam("FTP-User") String User, #HeaderParam("FTP-Password") String Password,
#HeaderParam("FTP-Path") String Path, #FormDataParam("file") InputStream inputStream) {
try {
InformationHandler informationHandler = new InformationHandler(Path, Host, Port, User, Password);
CountriesStructure worker = new CountriesStructure();
worker.prepareCountriesStructure(inputStream, true, informationHandler);
} catch (UsernameOrPasswordException e) {
return Response.status(401).entity("Status 401.").build();
} catch (SocketException e) {
return Response.status(404).entity("Status 404.").build();
} catch (IOException e) {
return Response.status(400).entity("Status 400.").build();
} catch (JAXBException e) {
return Response.status(500).entity("Status 500.").build();
} catch (Exception e) {
return Response.status(500).entity("Status 500.").build();
}
return Response.status(200).entity("Success!").build();
}
}
And my test:
#RunWith(HttpJUnitRunner.class)
public class TestMain extends TestCase {
#Rule
public Destination destination = new Destination(this, "http://localhost:8080");
#Context
private Response response;
#HttpTest(method = Method.POST, path = "/JerseyWebApp/ftpaction/upload", content = "{}", file = "/CountriesList.txt", type = MediaType.MULTIPART_FORM_DATA, headers = {
#Header(name = "FTP-Host", value = "localhost"), #Header(name = "FTP-Port", value = "21"),
#Header(name = "FTP-User", value = "ftptest"), #Header(name = "FTP-Password", value = "test"),
#Header(name = "FTP-Path", value = "/test123"), #Header(name = "Accept-Encoding", value = "multipart/form-data")})
public void checkPost() {
System.out.println(response.getBody());
}
}
I have problem with reading file by test. I don't know what I have to do, because I am using file as "FormDataParam". Somebody have any idea how can I upload file to test as FormDataParam? Because like now it doesn't see my file and just return "Status 400".

Related

how to playback audio blob from Spring boot App

I am storing an audio blob(recorded voice) in angular and then I am calling a spring boot API to store it in azure blob storage as so:
submit(){
const blob = this.audioRecording.getblob();
this.blobOutgoing = new FormData();
this.blobOutgoing.append('file', blob);
this.blobOutgoing.append('name', this.name);
this.blobOutgoing.append('email', this.email);
this.blobOutgoing.append('uid', this.uid);
this.pronunciationAPIService.saveEmployeeNameAlternate(this.blobOutgoing)
.subscribe((response: any) => {
console.log(response);
})
}
public void insertEmpoyeeRecord(Employee employee) {
try {
Statement stmt = getStatement();
System.out.println("Connected to the YugabyteDB Cluster successfully.");
// stmt.execute("DROP TABLE IF EXISTS employee");
/*stmt.execute("CREATE TABLE IF NOT EXISTS employee" +
" (id int primary key, name varchar, age int, language text)");*/
// System.out.println("Created table employee");
String insertStr = "INSERT INTO employees.employees VALUES ('"+employee.getUid()+"','"+employee.getEmail()+"','"+employee.getName()+"','"+employee.getUid()+"')";
String deleteStr = "DELETE FROM employees.employees WHERE email='"+employee.getEmail()+"' or uid='"+employee.getUid()+"'";
stmt.execute(deleteStr);
stmt.execute(insertStr);
----------> blobService.uploadFile(employee.getMultipartFile(), employee.getUid()); <----------------------------------
System.out.println("EXEC: " + insertStr);
ResultSet rs = stmt.executeQuery("select * from employees.employees");
while (rs.next()) {
System.out.println(String.format("Query returned: uid = %s, email = %s, name = %s, blob = %s",
rs.getString("uid"), rs.getString("email"), rs.getString("name"), rs.getString("audio")));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void uploadFile(MultipartFile multipartFile, String audioFilenameRequest){
// String localFolderPath = "C:\\Users\\erman\\Downloads\\audiofolder\\";
try {
byte[] bytes = multipartFile.getBytes();
System.out.println("lenght:: " + bytes.length);
String audioFileName = audioFilenameRequest;
CloudBlobContainer containerReference = getCloudBlobContainer();
//Getting a blob reference
CloudBlockBlob blockBlobReference = containerReference.getBlockBlobReference(audioFileName);
//Creating blob and uploading file to it
//System.out.println("Uploading the sample file, Absolute path: "+sourceFile.getAbsolutePath() );
blockBlobReference.uploadFromByteArray(bytes,0,bytes.length);
System.out.println("upload to Azure cloud blob is done!!!!");
// blockBlobReference.upload
/* Path path = Paths.get(localFolderPath + multipartFile.getOriginalFilename());
Files.write(path,bytes);*/
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (StorageException e) {
e.printStackTrace();
}
}
And then I try to retrieve from Angular by calling another Spring boot API:
playAudioFromBlob(){
this.pronunciationAPIService
.pronounceName(this.employee)
.subscribe((response: Array<Employee>) => {
console.log(response);
response.forEach( (employee) => {
let blob = new Blob(employee.blobByte, {type: "audio/webm"});
console.log(employee.blob);
const audioURL = URL.createObjectURL(blob);
let audio = new Audio(audioURL)
audio.controls = true;
audio.play();
})
});
}
public List<Employee> searchEmployeeByUid(String uid){
Employee employee = null;
try {
System.out.println("Connected to the YugabyteDB Cluster successfully.");
Statement stmt = getStatement();
String selectStr = "SELECT uid,email,name,audio FROM employees.employees WHERE uid='"+uid+"'";
stmt.execute(selectStr);
System.out.println("EXEC: " + selectStr);
ResultSet rs = stmt.executeQuery(selectStr);
while (rs.next()) {
employee = new Employee();
employee.setUid(rs.getString("uid"));
employee.setEmail(rs.getString("email"));
employee.setName(rs.getString("name"));
employee.setBlob(rs.getString("audio"));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
byte[] blob = blobService.downloadFile(employee.getBlob());
employee.setBlobByte(blob);
return employee;
}
public byte[] downloadFile(String audioFileName) {
File downloadedFile = null;
byte[] audioByteArray = new byte[472179];
try {
// byte[] bytes = multipartFile.getBytes();
// String audioFileName = multipartFile.getOriginalFilename();
CloudBlobContainer containerReference = getCloudBlobContainer();
//Getting a blob reference
CloudBlockBlob blockBlobReference = containerReference.getBlockBlobReference(audioFileName);
// downloadedFile = new File(audioFileName);
//byte [] b = new byte[472179];
blockBlobReference.downloadToByteArray(audioByteArray,0);
System.out.println("download from Azure cloud blob is done!!!!:: Size : " + audioByteArray.length);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (StorageException e) {
e.printStackTrace();
}
return audioByteArray;
}
public class Employee {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBlob() {
return blob;
}
public void setBlob(String blob) {
this.blob = blob;
}
public MultipartFile getMultipartFile() {
return blobOutgoing;
}
public void setMultipartFile(MultipartFile multipartFile) {
this.blobOutgoing = multipartFile;
}
private String name;
private String uid;
private String email;
private String blob;
private MultipartFile blobOutgoing;
public byte[] getBlobByte() {
return blobByte;
}
public void setBlobByte(byte[] blobByte) {
this.blobByte = blobByte;
}
private byte[] blobByte;
}
The problem is when converting the byte[] stream to a blob in angular I get the error:
Failed to construct 'Blob': The provided value cannot be converted to a sequence
I think I am getting this issue because I am not properly writing or reading the blob. I use ng-audio-recorder for the audio recordings in Angular. ng-audio-recorder builds the blob in audio webm
update: perhaps a more simplified question is how can you play back the byte[] stream in multipartfile in angular?
The initial argument (Parameter) must be presented in the sequence.
let blob = new Blob(employee.blobByte, {type: "audio/webm"}); console.log(employee.blob);
In place of this replace with the below one.
let blob=new Blob([employee.blobByte] ,{type: "audio/webm"}); console.log(employee.blob);

DCM4CHE, Network operations,Handling a C-Move call

Hi I'm trying to make a PACS server using Java. dcm4che appears to be quite popular. But I'm unable to find any good examples about it.
As a starting point I inspected dcmqrscp and it successfully stores a DICOM image. But I cannot manage to handle a C-MOVE call. Here's my CMove handler. It finds requested the DICOM file adds a URL and other stuff, it doesn't throw any exception yet client doesn't receive any files.
private final class CMoveSCPImpl extends BasicCMoveSCP {
private final String[] qrLevels;
private final QueryRetrieveLevel rootLevel;
public CMoveSCPImpl(String sopClass, String... qrLevels) {
super(sopClass);
this.qrLevels = qrLevels;
this.rootLevel = QueryRetrieveLevel.valueOf(qrLevels[0]);
}
#Override
protected RetrieveTask calculateMatches(Association as, PresentationContext pc, final Attributes rq, Attributes keys) throws DicomServiceException {
QueryRetrieveLevel level = QueryRetrieveLevel.valueOf(keys, qrLevels);
try {
level.validateRetrieveKeys(keys, rootLevel, relational(as, rq));
} catch (Exception e) {
e.printStackTrace();
}
String moveDest = rq.getString(Tag.MoveDestination);
final Connection remote = new Connection("reciverAE",as.getSocket().getInetAddress().getHostAddress(), 11113);
if (remote == null)
throw new DicomServiceException(Status.MoveDestinationUnknown, "Move Destination: " + moveDest + " unknown");
List<T> matches = DcmQRSCP.this.calculateMatches(keys);
if (matches.isEmpty())
return null;
AAssociateRQ aarq;
Association storeas = null;
try {
aarq = makeAAssociateRQ(as.getLocalAET(), moveDest, matches);
storeas = openStoreAssociation(as, remote, aarq);
} catch (Exception e) {
e.printStackTrace();
}
BasicRetrieveTask<T> retrieveTask = null;
retrieveTask = new BasicRetrieveTask<T>(Dimse.C_MOVE_RQ, as, pc, rq, matches, storeas, new BasicCStoreSCU<T>());
retrieveTask.setSendPendingRSPInterval(getSendPendingCMoveInterval());
return retrieveTask;
}
private Association openStoreAssociation(Association as, Connection remote, AAssociateRQ aarq)
throws DicomServiceException {
try {
return as.getApplicationEntity().connect(as.getConnection(),
remote, aarq);
} catch (Exception e) {
throw new DicomServiceException(
Status.UnableToPerformSubOperations, e);
}
}
private AAssociateRQ makeAAssociateRQ(String callingAET,
String calledAET, List<T> matches) {
AAssociateRQ aarq = new AAssociateRQ();
aarq.setCalledAET(calledAET);
aarq.setCallingAET(callingAET);
for (InstanceLocator match : matches) {
if (aarq.addPresentationContextFor(match.cuid, match.tsuid)) {
if (!UID.ExplicitVRLittleEndian.equals(match.tsuid))
aarq.addPresentationContextFor(match.cuid,
UID.ExplicitVRLittleEndian);
if (!UID.ImplicitVRLittleEndian.equals(match.tsuid))
aarq.addPresentationContextFor(match.cuid,
UID.ImplicitVRLittleEndian);
}
}
return aarq;
}
private boolean relational(Association as, Attributes rq) {
String cuid = rq.getString(Tag.AffectedSOPClassUID);
ExtendedNegotiation extNeg = as.getAAssociateAC().getExtNegotiationFor(cuid);
return QueryOption.toOptions(extNeg).contains(
QueryOption.RELATIONAL);
}
}
I added the code below to send a DICOM file as a response:
String cuid = rq.getString(Tag.AffectedSOPClassUID);
String iuid = rq.getString(Tag.AffectedSOPInstanceUID);
String tsuid = pc.getTransferSyntax();
try {
DcmQRSCP.this.as=as;
File f = new File("D:\\dcmqrscpTestDCMDir\\1.2.840.113619.2.30.1.1762295590.1623.978668949.886\\1.2.840.113619.2.30.1.1762295590.1623.978668949.887\\1.2.840.113619.2.30.1.1762295590.1623.978668949.888");
FileInputStream in = new FileInputStream(f);
InputStreamDataWriter data = new InputStreamDataWriter(in);
// !1! as.cmove(cuid,1,keys,tsuid,"STORESCU");
as.cstore(cuid,iuid,1,data,tsuid,rspHandlerFactory.createDimseRSPHandler(f));
} catch (Exception e) {
e.printStackTrace();
}
Throws this exception
org.dcm4che3.net.NoRoleSelectionException: No Role Selection for SOP Class 1.2.840.10008.5.1.4.1.2.2.2 - Study Root Query/Retrieve Information Model - MOVE as SCU negotiated
You should add a role to the application instance like:
applicationEntity.addTransferCapability(
new TransferCapability(null, "*", TransferCapability.Role.SCP, "*"));

ERROR: java.lang.OutOfMemoryError: unable to create new native thread in Loop

Im getting a not so rare error, which happens to many, the thing is that im not using threads in my app. Its just a loop, one task after the other, so i dont understand why im getting out of threads.
Basically for each line of the text file i make a GET request to an api, so i obtain some json data...
Here is the error log:
106
105
104
103
102
ene 06, 2016 4:08:39 PM org.jboss.netty.channel.DefaultChannelFuture
ADVERTENCIA: An exception was thrown by ChannelFutureListener.
java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:714)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:950)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1368)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.start(AbstractNioWorker.java:160)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.executeInIoThread(AbstractNioWorker.java:306)
at org.jboss.netty.channel.socket.nio.NioWorker.executeInIoThread(NioWorker.java:38)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.executeInIoThread(AbstractNioWorker.java:290)
at org.jboss.netty.channel.socket.nio.NioWorker.executeInIoThread(NioWorker.java:38)
at org.jboss.netty.channel.socket.nio.AbstractNioChannelSink.execute(AbstractNioChannelSink.java:34)
at org.jboss.netty.channel.Channels.fireExceptionCaughtLater(Channels.java:504)
at org.jboss.netty.channel.AbstractChannelSink.exceptionCaught(AbstractChannelSink.java:47)
at org.jboss.netty.channel.Channels.close(Channels.java:821)
at org.jboss.netty.channel.AbstractChannel.close(AbstractChannel.java:194)
at org.jboss.netty.channel.ChannelFutureListener$2.operationComplete(ChannelFutureListener.java:52)
at org.jboss.netty.channel.DefaultChannelFuture.notifyListener(DefaultChannelFuture.java:399)
at org.jboss.netty.channel.DefaultChannelFuture.notifyListeners(DefaultChannelFuture.java:385)
at org.jboss.netty.channel.DefaultChannelFuture.setFailure(DefaultChannelFuture.java:352)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.connect(NioClientSocketPipelineSink.java:404)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.processSelectedKeys(NioClientSocketPipelineSink.java:361)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.run(NioClientSocketPipelineSink.java:277)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
ERROR en getML():/orders/1045232034
com.mercadolibre.sdk.MeliException: java.util.concurrent.ExecutionException: java.net.ConnectException: unable to create new native thread to https://api.mercadolibre.com/orders/1045232034?access_token=APP_USR-1978251743308541-010613-c60e34a2a34d0fd5b8c936ccfb3e3732__K_I__-113746522
at com.nubimedia.app.ml.Melis.get(Melis.java:264)
at com.nubimedia.app.ml.Melis.getML(Melis.java:168)
at com.nubimedia.app.ModelML.encontrarMailsLog(ModelML.java:217)
at com.nubimedia.app.Pruebas.main(Pruebas.java:11)
Caused by: java.util.concurrent.ExecutionException: java.net.ConnectException: unable to create new native thread to https://api.mercadolibre.com/orders/1045232034?access_token=APP_USR-1978251743308541-010613-c60e34a2a34d0fd5b8c936ccfb3e3732__K_I__-113746522
at com.ning.http.client.providers.netty.NettyResponseFuture.abort(NettyResponseFuture.java:297)
at com.ning.http.client.providers.netty.NettyConnectListener.operationComplete(NettyConnectListener.java:104)
at org.jboss.netty.channel.DefaultChannelFuture.notifyListener(DefaultChannelFuture.java:399)
at org.jboss.netty.channel.DefaultChannelFuture.notifyListeners(DefaultChannelFuture.java:390)
at org.jboss.netty.channel.DefaultChannelFuture.setFailure(DefaultChannelFuture.java:352)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.connect(NioClientSocketPipelineSink.java:404)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.processSelectedKeys(NioClientSocketPipelineSink.java:361)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.run(NioClientSocketPipelineSink.java:277)
at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: unable to create new native thread to https://api.mercadolibre.com/orders/1045232034?access_token=APP_USR-1978251743308541-010613-c60e34a2a34d0fd5b8c936ccfb3e3732__K_I__-113746522
at com.ning.http.client.providers.netty.NettyConnectListener.operationComplete(NettyConnectListener.java:100)
... 10 more
Caused by: java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:714)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:950)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1368)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.start(AbstractNioWorker.java:160)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.register(AbstractNioWorker.java:131)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.connect(NioClientSocketPipelineSink.java:401)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.processSelectedKeys(NioClientSocketPipelineSink.java:361)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.run(NioClientSocketPipelineSink.java:277)
... 3 more
Hubo un error
101
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:714)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:950)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1368)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at com.ning.http.client.providers.jdk.JDKAsyncHttpProvider.execute(JDKAsyncHttpProvider.java:159)
at com.ning.http.client.providers.jdk.JDKAsyncHttpProvider.execute(JDKAsyncHttpProvider.java:121)
at com.ning.http.client.AsyncHttpClient.executeRequest(AsyncHttpClient.java:512)
at com.ning.http.client.AsyncHttpClient$BoundRequestBuilder.execute(AsyncHttpClient.java:234)
at com.nubimedia.app.ml.Melis.get(Melis.java:262)
at com.nubimedia.app.ml.Melis.getML(Melis.java:168)
at com.nubimedia.app.ModelML.encontrarMailsLog(ModelML.java:217)
at com.nubimedia.app.Pruebas.main(Pruebas.java:11)
And here is the code:
public static void main(String[] args) throws IOException, MeliException {
ModelML.getInstance().encontrarMailsLog(731);
}
public void encontrarMailsLog(int max) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("/Users/fabrizioguespe/Downloads/catalina.out"));
Set<String> resources=new TreeSet<String>();
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if(line.equals("Nueva Request!")){
String cliente=br.readLine();
String resource=br.readLine();
resources.add(cliente+"-"+resource);
}
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
} finally {
br.close();
}
Log.log(resources.size()+" Para procesar");
int i=resources.size();
for(String s: resources){
i--;
Log.log(i+"");
if(max>0)
if(i>max)continue;
String cliente=s.split("-")[0];
String resource=s.split("-")[1];
//Log.log("Cliente: "+cliente+" "+resource);
ModelML.getInstance().procesarRequest(Melis.getML(resource, null,cliente,false),resource);
}
}
UPDATED: As suggested, and makes sense. I may be doing async request, using the SDK provided by the API
Here is the class
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.mercadolibre.sdk.AuthorizationFailure;
import com.mercadolibre.sdk.MeliException;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.Response;
import com.nubimedia.app.ModelML;
import com.nubimedia.app.util.HibernateUtil;
import com.nubimedia.app.util.Log;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class Melis {
public static String apiUrl = "https://api.mercadolibre.com";
private String accessToken;
private String refreshToken;
private Long clientId;
private String clientSecret;
//public static Map<String,UserML> clientes=new HashMap<String,UserML>();
public static UserML getCliente(String id) {//Solo para inicializar la aplicacion
Session s=HibernateUtil.getSessionFactory().openSession();
s.beginTransaction();
Query query = s.createQuery("from UserML where id = :id");
query.setString("id", id);
UserML q = (UserML) query.uniqueResult();
s.flush();
s.getTransaction().commit();
s.close();
return q;
}
public static List<UserML> getClientes() {
Session s=HibernateUtil.getSessionFactory().openSession();
s.beginTransaction();
Query query = s.createQuery("from UserML");
#SuppressWarnings("unchecked")
List<UserML> q = (List<UserML>) query.list();
s.flush();
s.getTransaction().commit();
s.close();
return q;
}
public static String preguntarML(String item,String pregunta,String idcliente){
UserML cliente=getCliente(idcliente);
if(cliente==null)return null;
Melis m = new Melis(Long.parseLong(ModelML.ml_appid),ModelML.ml_secret,cliente.getToken(),cliente.getToken());
String params="{\"text\":\""+pregunta.trim()+"\",\"item_id\":\""+item+"\"}";
String json=Melis.postML("/questions/"+item+"?access_token="+m.getAccessToken(), null, cliente, params);
return json;
}
public static String postML(String resource,FluentStringsMap params,UserML cliente,String json){
try {
Melis m = new Melis(Long.parseLong(ModelML.ml_appid),ModelML.ml_secret,cliente.getToken(),cliente.getRefresh_token());
if(params==null){
params = new FluentStringsMap();
params.add("access_token", m.getAccessToken());
}
Response respuesta = m.post(resource, params,json);
String jsons=respuesta.getResponseBody();
//jsons=new String(json.getBytes("ISO-8859-1"),"UTF-8");
return jsons;
} catch (Exception e) {
Log.log("ERROR en getML():"+resource);
e.printStackTrace();
}
return null;
}
public static String getUserId(String json){
try{
JsonParser parser = new JsonParser();
JsonObject venta= (JsonObject)parser.parse(json);
if(venta.isJsonNull())return null;
return venta.get("id").getAsString();
}catch(Exception e){
e.printStackTrace();
Log.log("ERROR al parsear json VENTA mercadolibre: ");
}
return null;
}
public static String setToken(String token,String refresh_token,String idcliente) {
UserML a=getCliente(idcliente);
if(a==null)return null;
a.setToken(token);
a.setRefresh_token(refresh_token);
a.setLast_modif(new Date());
Session s=HibernateUtil.getSessionFactory().openSession();
s.beginTransaction();
s.saveOrUpdate(a);
s.flush();
s.getTransaction().commit();
s.close();
return null;
}
public static String getML2(String resource){
Client client = Client.create();
WebResource webResource = client.resource(apiUrl+resource);
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
if (response.getStatus() != 200)
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
return response.getEntity(String.class);
}
public static String remokeAccess(String idcliente){
try {
UserML cliente=getCliente(idcliente);
if(cliente==null)return null;
String resource="/users/"+cliente+"/applications/"+ModelML.ml_appid+"?access_token="+cliente.getToken();
Melis m = new Melis(Long.parseLong(ModelML.ml_appid),ModelML.ml_secret,cliente.getToken());
FluentStringsMap params = new FluentStringsMap();
params.add("access_token", m.getAccessToken());
Response respuesta = m.delete(resource, params);
String json=respuesta.getResponseBody();
json=new String(json.getBytes("ISO-8859-1"),"UTF-8");
return json;
} catch (Exception e) {
Log.log("ERROR en removkeAccess():"+idcliente);
e.printStackTrace();
}
return null;
}
public static String getML(String resource,FluentStringsMap params,String idcliente,boolean access_final){
try {
UserML cliente=getCliente(idcliente);
if(cliente==null)return null;
Melis m = new Melis(Long.parseLong(ModelML.ml_appid),ModelML.ml_secret,cliente.getToken(),cliente.getRefresh_token());
if(params==null){
params = new FluentStringsMap();
params.add("access_token", m.getAccessToken());
}
if(access_final)resource+="?access_token="+cliente.getToken();
Response respuesta = m.get(resource, params);
String json=respuesta.getResponseBody();
json=new String(json.getBytes("ISO-8859-1"),"UTF-8");
return json;
} catch (Exception e) {
Log.log("ERROR en getML():"+resource);
e.printStackTrace();
}
return null;
}
private AsyncHttpClient http;
{
AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder()
.setUserAgent("MELIJAVASDK0.0.1").build();
http = new AsyncHttpClient(cf);
}
public Melis(Long clientId, String clientSecret ) {
this.clientId = clientId;
this.clientSecret = clientSecret;
}
public Melis(Long clientId, String clientSecret, String accessToken) {
this.accessToken = accessToken;
this.clientId = clientId;
this.clientSecret = clientSecret;
}
public Melis(Long clientId, String clientSecret, String accessToken, String refreshToken) {
this.accessToken = accessToken;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.refreshToken = refreshToken;
}
public String getAccessToken() {
return this.accessToken;
}
public Response get(String path) throws MeliException {
return get(path, new FluentStringsMap());
}
private BoundRequestBuilder prepareGet(String path, FluentStringsMap params) {
return http.prepareGet(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params);
}
private BoundRequestBuilder prepareDelete(String path,
FluentStringsMap params) {
return http.prepareDelete(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params);
}
private BoundRequestBuilder preparePost(String path,
FluentStringsMap params, String body) {
return http.preparePost(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params)
.setHeader("ContentType", "application/json").setBody(body)
.setBodyEncoding("UTF8");
}
private BoundRequestBuilder preparePut(String path,
FluentStringsMap params, String body) {
return http.preparePut(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params)
.setHeader("ContentType", "application/json").setBody(body)
.setBodyEncoding("UTF8");
}
private BoundRequestBuilder preparePost(String path, FluentStringsMap params) {
return http.preparePost(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params);
}
public Response get(String path, FluentStringsMap params) throws MeliException {
BoundRequestBuilder r = prepareGet(path, params);
Response response;
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
if (params.containsKey("access_token") && this.hasRefreshToken() && response.getStatusCode() == 401) {
try {
refreshAccessToken();
} catch (AuthorizationFailure e1) {
Log.log("ERROR al refrescar token");
return response;
}
params.replace("access_token", this.accessToken);
r = prepareGet(path, params);
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
}
return response;
}
public void refreshAccessToken() throws AuthorizationFailure {
FluentStringsMap params = new FluentStringsMap();
params.add("grant_type", "refresh_token");
params.add("client_id", String.valueOf(this.clientId));
params.add("client_secret", this.clientSecret);
params.add("refresh_token", this.refreshToken);
BoundRequestBuilder req = preparePost("/oauth/token", params);
parseToken(req);
}
public String getAuthUrl(String callback) {
try {
return "https://auth.mercadolibre.com.ar/authorization?response_type=code&client_id="
+ this.clientId
+ "&redirect_uri="
+ URLEncoder.encode(callback, "UTF8");
} catch (UnsupportedEncodingException e) {
return "https://auth.mercadolibre.com.ar/authorization?response_type=code&client_id="
+ this.clientId + "&redirect_uri=" + callback;
}
}
public String authorize(String code, String redirectUri) throws AuthorizationFailure {
FluentStringsMap params = new FluentStringsMap();
params.add("grant_type", "authorization_code");
params.add("client_id", String.valueOf(this.clientId));
params.add("client_secret", this.clientSecret);
params.add("code", code);
params.add("redirect_uri", redirectUri);
BoundRequestBuilder r = preparePost("/oauth/token", params);
return parseToken(r);
}
private String parseToken(BoundRequestBuilder r) throws AuthorizationFailure {
Response response = null;
String responseBody = "";
try {
response = r.execute().get();
responseBody = response.getResponseBody();
} catch (InterruptedException e) {
throw new AuthorizationFailure(e);
} catch (ExecutionException e) {
throw new AuthorizationFailure(e);
} catch (IOException e) {
throw new AuthorizationFailure(e);
}
JsonParser p = new JsonParser();
JsonObject object;
try {
object = p.parse(responseBody).getAsJsonObject();
} catch (JsonSyntaxException e) {
throw new AuthorizationFailure(responseBody);
}
if (response.getStatusCode() == 200) {
this.accessToken = object.get("access_token").getAsString();
this.refreshToken = object.get("refresh_token").getAsString();
String user_ID = object.get("user_id").getAsString();
Melis.setToken(this.accessToken, this.refreshToken,user_ID);//PERSISTO
return object.toString();
} else return object.get("message").getAsString();
}
private boolean hasRefreshToken() {
return this.refreshToken != null && !this.refreshToken.isEmpty();
}
public Response post(String path, FluentStringsMap params, String body)
throws MeliException {
BoundRequestBuilder r = preparePost(path, params, body);
Response response;
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
if (params.containsKey("access_token") && this.hasRefreshToken() && response.getStatusCode() == 401) {
try {
refreshAccessToken();
} catch (AuthorizationFailure e1) {
return response;
}
params.replace("access_token", this.accessToken);
r = preparePost(path, params, body);
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
}
return response;
}
public Response put(String path, FluentStringsMap params, String body)
throws MeliException {
BoundRequestBuilder r = preparePut(path, params, body);
Response response;
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
if (params.containsKey("access_token") && this.hasRefreshToken()
&& response.getStatusCode() == 401) {
try {
refreshAccessToken();
} catch (AuthorizationFailure e1) {
return response;
}
params.replace("access_token", this.accessToken);
r = preparePut(path, params, body);
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
}
return response;
}
public Response delete(String path, FluentStringsMap params)
throws MeliException {
BoundRequestBuilder r = prepareDelete(path, params);
Response response;
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
if (params.containsKey("access_token") && this.hasRefreshToken()
&& response.getStatusCode() == 401) {
try {
refreshAccessToken();
} catch (AuthorizationFailure e1) {
return response;
}
params.replace("access_token", this.accessToken);
r = prepareDelete(path, params);
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
}
return response;
}
public BoundRequestBuilder head(String path) {
return null;
}
public BoundRequestBuilder options(String path) {
return null;
}
}
Disclaimer: AsyncHttpClient author here
First, I don't know why the answer above was validated, it's wrong.
I suspect that you're creating tons of Melis instances. But you completely missed the point that an AsyncHttpClient instance must be used as a singleton (except for very specific use cases).
As every Melis instance creates its own AsyncHttpClient instance, you end up creating tons of them, and you blow off resource usage.
Note that your AsyncHttpClient instance(s) must be closed when you shut your application down so underlying resources get freed.
This is not a memory problem, but an operating system resource problem,this has nothing to do with programming, or linux.

Marshalling list of elements in REST

I have a problem with sending ArrayList from server to my client using JAX-rs. I've got 4 classes:
Demo - there is starting REST server
FileDetails - there are 3 fields storing data
ConfigFiles - it has few methods for files and there is a list of FileDetails objects
RestServer - there is method GET
I've got the following code:
#XmlRootElement(name="FileDetails")
#Path("/easy")
public class RestSerwer {
#GET
#Path("/temporary")
#Produces("text/temporary")
public String methodGet() {
ConfigFiles cf = ConfigFiles.getInstance();
List<FileDetails> files = cf.getList();
try {
JAXBContext ctx = JAXBContext.newInstance(ArrayList.class, FileDetails.class);
Marshaller m = ctx.createMarshaller();
StringWriter sw = new StringWriter();
m.marshal(files, sw);
return sw.toString();
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
}
At client side I've got GetRest:
public class GetRest{
HttpClient client = null;
GetMethod method = null;
private String url = null;
public GetRest(String url) {
this.url = url;
}
public String getBody(String urlDetail){
client = new HttpClient();
method = new GetMethod(url + urlDetail);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
client.executeMethod(method);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] responseBody = null;
try {
responseBody = method.getResponseBody();
} catch (IOException e) {
e.printStackTrace();
}finally{
method.releaseConnection();
}
String str = new String(responseBody);
return str;
}
public String getFiles(){
return getBody("/easy/temporary");
}
}
When I try:
GetRest getRestClass = new GetRest("http://localhost:8185");
//List<FileDetails> cf = new ArrayList<FileDetails>();
String xxxx = getRestClass.getFiles(); // TODO
It throws:
Caused by: com.sun.istack.internal.SAXException2: unable to marshal type "java.util.ArrayList" as an element because it is missing an #XmlRootElement annotation
At server side.
Anybody can help me?
Thanks
You basically have 2 possibilities: Create you own class which is a wrapper on top of the List or write your own provider and inject it in jersey so that it knows how to marshall/unmarshall the arraylist. Here is a simple code for the first solution:
#XmlRootElement
public class MyListWrapper {
#XmlElement(name = "List")
private List<String> list;
public MyListWrapper() {/*JAXB requires it */
}
public MyListWrapper(List<String> stringList) {
list = stringList;
}
public List<String> getStringList() {
return list;
}
}

How to write unit test for CommonsMultipartFile with Mock in Spring

I am using spring 3.0 org.springframework.web.multipart.commons.CommonsMultipartFile for file uploading. i want write down unit test case for file upload using Mockito.
Following is my controller class
private RegistrationService registrationService;
#RequestMapping(method = RequestMethod.POST)
public String create(Registration registration, BindingResult result,ModelMap model)
throws NumberFormatException, Exception {
File uploadedFile = uploadFile(registration);
List<Registration> userDetails = new ArrayList<Registration>();
processUploadedFile(uploadedFile,userDetails);
model.addAttribute("userDetails", userDetails);
return "Registration";
}
private File uploadFile(Registration registration) {
Date dt = new Date();
SimpleDateFormat format = new SimpleDateFormat("MM_dd_yyyy_HH_mm_ss");
File uploadedFile = new File(uploadFileLocation
+ registration.getFileData().getOriginalFilename() + "."
+ format.format(dt));
try {
registration.getFileData().transferTo(uploadedFile);
} catch (IllegalStateException e) {
logger.error("Error occurred while uploading file", e);
} catch (IOException e) {
logger.error("Error occurred while uploading file", e);
}
return uploadedFile;
}
private void processUploadedFile(File uploadedFile, List<Registration> userDetails)
throws NumberFormatException, Exception {
registrationService.processFile(uploadedFile, userDetails);
}
Registration class
public class Registration {
private String name;
private CommonsMultipartFile fileData;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CommonsMultipartFile getFileData() {
return fileData;
}
public void setFileData(CommonsMultipartFile fileData) {
this.fileData = fileData;
}
}
My Service class method
public void processFile(File uploadedFile,
List<Registration> userDetails) throws NumberFormatException,
Exception {
String record = "";
try {
FileWriter fstream = new FileWriter(outputFileLocation
+ uploadedFile.getName());
BufferedWriter out = new BufferedWriter(fstream);
BufferedReader br = new BufferedReader(new FileReader(
uploadedFile.getAbsolutePath()));
while ((record = br.readLine()) != null) {
String[] requesterUser = record.split(",");
if (insertUserToDB(requesterUser, userDetails) > 0)
out.write(record + ", Yes");
else
out.write(record + ", No");
out.newLine();
}
out.flush();
out.close();
} catch (FileNotFoundException e) {
logger.error("Error occured while processing file", e);
} catch (IOException e) {
logger.error("Error occured while processing file", e);
}
}
How to Unit Test it?I am new to Mockito.
Edit
I have write down Test method for testing above code, but it return null for multipartFile. How should I test above service class processFile method?
#Test
public void testProcessFile() {
private static final String TEST_FILE = "c:\\user.csv";
MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
MockMultipartHttpServletRequest mockMultipartHttpServletRequest = (MockMultipartHttpServletRequest)request;
MultipartFile multipartFile = (MultipartFile) mockMultipartHttpServletRequest.getFile(TEST_FILE);
Registration registration=new Registration();
registration.setFileData(multipartFile);
RegistrationService.processFile(uploadedFile, userDetails);
}
I am new to JUnit and mockito. Any help or pointer really appreciated.
You might want to consider using Spring's Mock implementation (org.springframework.mock.web.MockMultipartFile) rather than creating a mock using Mockito.
Heinrich Filter is right, but you also need to change the type for the field fileData from CommonsMulitPartFile to org.springframework.web.multipart.MultipartFile. (This is the super interface above CommonsMulitPartFile and MockMultipartFile.
If you have done this, then you can create a mock of the multipart file itselfe with an mock object that is provided by spring
MockMultipartFile mockMultipartFile = new MockMultipartFile(
"fileData",
fileName,
"text/plain",
content);

Categories