CAMEL HTTP4 post request was rejected because no multipart boundary was found - file-upload

I'm using Camel-http4 because I simply need a producer, not expose a webservice. I simply need to push files up to an HTTP server, so this is a client implementation. the problem I am facing is the attempt to post returns an error.
CamelHttpResponseCode=403, CamelHttpResponseText=Forbidden
{"timestamp":"2018-05-03T20:36:20.571","traceId":"","path":"[POST] https://apm-query-svc-prod.apm-api.com/v2/t_series/upload%2520?throwExceptionOnFailure=false","errors":[{"httpStatusCode":"FORBIDDEN","code":"FORBIDDEN","message":"Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found","detail":null,"requestId":null}]}
Question, is there a way to do this with Camel-HTTP4 ? how is / can this be done? and thank you !!!
here is the route
<route
id="core.pr.upload.route"
autoStartup="false" >
<from uri="{{uploadEntranceEndpoint}}" />
<process ref="customerEntitesProcessor" />
<process ref="customerTokenProcessor" />
<process ref="uploadProcessor" />
<setHeader headerName="CamelHttpUri">
<simple>${header.UPLOADURL}?throwExceptionOnFailure=false</simple>
</setHeader>
<setHeader headerName="CamelHttpMethod">
<constant>POST</constant>
</setHeader>
<to uri="http4://apm-query-svc-prod.app-api.aws-usw02-pr.io:443/v2/t_series/upload?throwExceptionOnFailure=false" />
<log message="After POSTING FILE: ${body}" loggingLevel="INFO"/>
<to uri="{{afteruploadLocation}}" />
</route>
here is the class, I simply set the headers up and the URI is overridden with the one provided by Exchange.HTTP_URI.
public class UploadProcessor implements Processor {
private static final Logger LOG = LoggerFactory.getLogger(UploadProcessor.class);
#Override
public void process(Exchange exchange) throws Exception {
LOG.info("Entering Upload Processor ..." );
final String tenant = (String)exchange.getIn().getHeader("TENANT");
final String token = (String)exchange.getIn().getHeader("TOKEN");
final String uploadUrl = (String)exchange.getIn().getHeader("UPLOADURL");
final String custKey = (String)exchange.getIn().getHeader("CUSTKEY");
LOG.info("TENANT: " + tenant);
LOG.info("TOKEN: " + token);
LOG.info("UPLOADURL: " + uploadUrl);
LOG.info("CUSTKEY: " + custKey);
LOG.info("Uploading File for CustKey: " + custKey + " and Tenant: " + tenant);
StringBuilder authHeader = new StringBuilder("Bearer ");
authHeader.append(token);
LOG.info("Authorization: " + authHeader.toString());
exchange.setProperty("CamelCharsetName", "UTF-8"); //"CamelCharsetName" Exchange.CHARSET_NAME
exchange.getIn().setHeader("CamelHttpCharacterEncoding", "UTF-8"); //"CamelHttpCharacterEncoding" Exchange.HTTP_CHARACTER_ENCODING
exchange.getIn().setHeader("CamelAcceptContentType", "application/json"); //"CamelAcceptContentType" Exchange.ACCEPT_CONTENT_TYPE
exchange.getIn().setHeader("CamelHttpUri", uploadUrl); //"CamelHttpUri" Exchange.HTTP_URI
exchange.getIn().setHeader("CamelHttpMethod", "POST"); //"CamelHttpMethod" Exchange.HTTP_METHOD
exchange.getIn().setHeader("x-ge-csvformat", "ODB");
exchange.getIn().setHeader("Tenant", tenant);
exchange.getIn().setHeader("Content-Type", "multipart/form-data"); //"Content-Type" ; boundary=
exchange.getIn().setHeader("Authorization", authHeader.toString());
LOG.info("Exiting Upload Processor: Finish " );
}
}
this is my first HTTP introduction, not familiar with the multipart boundary, I'm hoping there is a kind a simple solution to this. :) thank you !!!
The solution wasn't that difficult at all, here is the final based on Ralf's answer. thanks all! the hard part was finding the import packages and that it has a dependency.
add to POM
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.1</version>
</dependency>
import java.lang.StringBuilder;
import java.net.URLEncoder;
import java.util.Base64;
import java.io.File;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.camel.LoggingLevel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
public class UploadProcessor implements Processor {
private static final Logger LOG = LoggerFactory.getLogger(UploadProcessor.class);
#Override
public void process(Exchange exchange) throws Exception {
LOG.info("Entering Upload Processor ..." );
final String tenant = (String)exchange.getIn().getHeader("TENANT");
final String token = (String)exchange.getIn().getHeader("TOKEN");
final String uploadUrl = (String)exchange.getIn().getHeader("UPLOADURL");
final String custKey = (String)exchange.getIn().getHeader("CUSTKEY");
LOG.info("TENANT: " + tenant);
LOG.info("TOKEN: " + token);
LOG.info("UPLOADURL: " + uploadUrl);
LOG.info("CUSTKEY: " + custKey);
LOG.info("Uploading File for CustKey: " + custKey + " and Tenant: " + tenant);
StringBuilder authHeader = new StringBuilder("Bearer ");
authHeader.append(token);
LOG.info("Authorization: " + authHeader.toString());
exchange.setProperty("CamelCharsetName", "UTF-8"); //"CamelCharsetName" Exchange.CHARSET_NAME
exchange.getIn().setHeader("CamelHttpCharacterEncoding", "UTF-8"); //"CamelHttpCharacterEncoding" Exchange.HTTP_CHARACTER_ENCODING
exchange.getIn().setHeader("CamelAcceptContentType", "application/json"); //"CamelAcceptContentType" Exchange.ACCEPT_CONTENT_TYPE
exchange.getIn().setHeader("CamelHttpUri", uploadUrl); //"CamelHttpUri" Exchange.HTTP_URI
exchange.getIn().setHeader("CamelHttpMethod", "POST"); //"CamelHttpMethod" Exchange.HTTP_METHOD
exchange.getIn().setHeader("x-ge-csvformat", "ODB");
exchange.getIn().setHeader("Tenant", tenant);
exchange.getIn().setHeader("Authorization", authHeader.toString());
// Process the file in the exchange body
File file = exchange.getIn().getBody(File.class);
String fileName = (String) exchange.getIn().getHeader(Exchange.FILE_NAME);
LOG.info("fileName: " + fileName);
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.addBinaryBody("file", file);
entity.addTextBody("name", fileName);
exchange.getIn().setBody(entity.build());
LOG.info("Exiting Upload Processor: Finish " );
}
}

Related

glassfish 5.0 not start

This is my code
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/echo")
public class EchoServer {
#OnMessage
public String echo(String incomingMessage) {
return "I got this (" + incomingMessage + ")"
+ " so I am sending it back !";
}
}
but it throws this error, I don't know which XML is incorrect.
Exception during lifecycle processing
java.lang.RuntimeException: org.xml.sax.SAXParseExceptionpublicId:
http://www.oracle.com/technetwork/java/index.html; lineNumber: 7;
columnNumber: 41; Deployment descriptor file META-INF/application.xml in
archive [MXONE_ear_exploded]. s4s-elt-character: Non-whitespace characters
are not allowed in schema elements other than 'xs:appinfo' and
'xs:documentation'. Saw 'var _U = "undefined";
var g_HttpRelativeWebRoot = "/ocom/";'.
How to solve it?
The error is because you have older schema namespace for application.xml
All new schemas are at http://xmlns.jcp.org/xml/ns/javaee/. Most older schemas remain in the http://java.sun.com/xml/ns/javaee/ namespace.
Make sure you use newer one.

Error Rampart Receiver

I'm trying to send a information for a securite webservice but I am with the following error when he gotta tell me the answer
[ERROR] Expected encrypted part missing
org.apache.axis2.AxisFault: Expected encrypted part missing
at org.apache.rampart.handler.RampartReceiver.setFaultCodeAndThrowAxisFault(RampartReceiver.java:186)
at org.apache.rampart.handler.RampartReceiver.invoke(RampartReceiver.java:99)
at org.apache.axis2.engine.Phase.invokeHandler(Phase.java:335)
at org.apache.axis2.engine.Phase.invoke(Phase.java:308)
at org.apache.axis2.engine.AxisEngine.invoke(AxisEngine.java:250)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:156)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:357)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:414)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:150)
at tutorial.somar.Soma001SNAPSHOTStub.add(Soma001SNAPSHOTStub.java:190)
at tutorial.somar.teste2.main(teste2.java:65)
Caused by: org.apache.rampart.RampartException: Expected encrypted part missing
at org.apache.rampart.PolicyBasedResultsValidator.validateEncrSig(PolicyBasedResultsValidator.java:276)
at org.apache.rampart.PolicyBasedResultsValidator.validate(PolicyBasedResultsValidator.java:153)
at org.apache.rampart.RampartEngine.process(RampartEngine.java:280)
at org.apache.rampart.handler.RampartReceiver.invoke(RampartReceiver.java:92)
... 10 more
Exception in thread "main" org.apache.axis2.AxisFault: Expected encrypted part missing
at org.apache.rampart.handler.RampartReceiver.setFaultCodeAndThrowAxisFault(RampartReceiver.java:186)
at org.apache.rampart.handler.RampartReceiver.invoke(RampartReceiver.java:99)
at org.apache.axis2.engine.Phase.invokeHandler(Phase.java:335)
at org.apache.axis2.engine.Phase.invoke(Phase.java:308)
at org.apache.axis2.engine.AxisEngine.invoke(AxisEngine.java:250)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:156)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:357)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:414)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:150)
at tutorial.somar.Soma001SNAPSHOTStub.add(Soma001SNAPSHOTStub.java:190)
at tutorial.somar.teste2.main(teste2.java:65)
Caused by: org.apache.rampart.RampartException: Expected encrypted part missing
at org.apache.rampart.PolicyBasedResultsValidator.validateEncrSig(PolicyBasedResultsValidator.java:276)
at org.apache.rampart.PolicyBasedResultsValidator.validate(PolicyBasedResultsValidator.java:153)
at org.apache.rampart.RampartEngine.process(RampartEngine.java:280)
at org.apache.rampart.handler.RampartReceiver.invoke(RampartReceiver.java:92)
... 10 more
I'm using maven on the server:
here is the services.xml
<module ref="rampart"/>
<parameter name="ServiceClass" locked="false">tutorial.somar.SecureService</parameter>
<operation name="add">
<messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
<sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
<wsp:Policy>
<sp:MustSupportRefKeyIdentifier/>
<sp:MustSupportRefIssuerSerial/>
</wsp:Policy>
</sp:Wss10>
<sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
<sp:Body/>
</sp:SignedParts>
<sp:EncryptedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
<sp:Body/>
</sp:EncryptedParts>
<ramp:RampartConfig xmlns:ramp="http://ws.apache.org/rampart/policy">
<ramp:user>serverkey</ramp:user>
<ramp:encryptionUser>clientkey</ramp:encryptionUser>
<ramp:passwordCallbackClass>tutorial.somar.PWCBHandler</ramp:passwordCallbackClass>
<ramp:signatureCrypto>
<ramp:crypto provider="org.apache.ws.security.components.crypto.Merlin">
<ramp:property name="org.apache.ws.security.crypto.merlin.keystore.type">JKS</ramp:property>
<ramp:property name="org.apache.ws.security.crypto.merlin.file">server.keystore</ramp:property>
<ramp:property name="org.apache.ws.security.crypto.merlin.keystore.password">nosecret</ramp:property>
</ramp:crypto>
</ramp:signatureCrypto>
<ramp:encryptionCrypto>
<ramp:crypto provider="org.apache.ws.security.components.crypto.Merlin">
<ramp:property name="org.apache.ws.security.crypto.merlin.keystore.type">JKS</ramp:property>
<ramp:property name="org.apache.ws.security.crypto.merlin.file">server.keystore</ramp:property>
<ramp:property name="org.apache.ws.security.crypto.merlin.keystore.password">nosecret</ramp:property>
</ramp:crypto>
</ramp:encryptionCrypto>
</ramp:RampartConfig>
</wsp:All>
and the SecureService.java
public int add(int a, int b) {
System.out.println(a+b);
return a+b;
}
my WS-client is like this:
public class teste2 {
private static Policy loadPolicy(String name) throws XMLStreamException{
ClassLoader loader = teste2.class.getClassLoader();
InputStream resource = loader.getResourceAsStream(name);
StAXOMBuilder builder = new StAXOMBuilder(resource);
return PolicyEngine.getPolicy(builder.getDocumentElement());
}
public static void main (String[] args) throws XMLStreamException, RemoteException{
/*if(args.length < 4){
System.out.println("Usage:\n java " +
"com.sosnoski.ws.library.adb.WebServiceClient protocol host port path");
System.exit(1);
}*/
//String target = args[0] + "://" + args[1] + ":" + args[2] + args[3];
String target = "http://localhost:8070/axis2/services/soma-0.0.1-SNAPSHOT";
System.out.println("Connecting to " + target);
ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem("client-repo", null);
Soma001SNAPSHOTStub stub = new Soma001SNAPSHOTStub(ctx ,target);
//FacebookStub stub = new FacebookStub(target);
ServiceClient client = stub._getServiceClient();
Options options = client.getOptions();
Policy policy = loadPolicy("signencr-policy-client.xml");
//Policy policy = loadPolicy("policy.xml");
//Policy policy = loadPolicy("sign-policy-client.xml");
options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, policy);
options.setUserName("libuser");
options.setPassword("books");
client.engageModule("rampart");
int a = 4;
int b = 4;
Add n = new Add();
n.setA(a);
n.setB(b);
AddResponse result = stub.add(n);
System.out.println(a + " + " + b + " = " + result.get_return());
}
}
I'm using axis2 1.7.1, rampart 1.7.0
I solve the problem... I just change that line
<sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never"/>
for that
<sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
<wsp:Policy>
<sp:RequireThumbprintReference/>
</wsp:Policy>
</sp:X509Token>
peace.

Upload File to Quickbooks online with IDS V3

I would like to upload a file to QuickBooks Online using IDS V3.
I followed the steps described here
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/020_key_concepts/attachments.
Here is my source code
URL url = new URL("https://quickbooks.api.intuit.com/v3/company/My_company_ID/upload");
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.setDoOutput(true);
request.setRequestMethod("POST");
HttpParameters para = new HttpParameters();
//String status = URLEncoder.encode("中 文","utf-8").replaceAll("\\+", "%20");
//para.put("status", status);
String boundary = "---------------------------37531613912423";
//String content = "--"+boundary+"\r\nContent-Disposition: form-data; name=\"status\"\r\n\r\n";
String pic = "\r\n--"+boundary+"\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"postpic.gif\"\r\nContent-Type: image/gif\r\n\r\n";
byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();
File f = new File("/Users/cnanfack/Documents/oml_map1.gif");
FileInputStream stream = new FileInputStream(f);
byte[] file = new byte[(int)f.length()];
stream.read(file);
String lineEnd = "\r\n";
String header = "Content-Disposition: form-data; name=\"file_metadata_0\""+lineEnd
+"Content-Type: application/xml; charset=UTF-8"+lineEnd
+"Content-Transfer-Encoding: 8bit"+lineEnd;
String attachable = header+"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Attachable xmlns=\"http://schema.intuit.com/finance/v3\" domain=\"QBO\" sparse=\"false\">"
+"<EntityRef type=\"Bill\">285</EntityRef>"
+"<Size>4099</Size>"
+"<ContentType>image/gif</ContentType>"
+"<FileName>postpic.gif</FileName>"
+"</Attachable>";
request.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
//request.setRequestProperty("Content-Length", String.valueOf(boundary.getBytes().length+"test".getBytes().length+pic.getBytes().length+f.length()+end_data.length));
//consumer.setAdditionalParameters(para);
consumer.sign(request);
OutputStream ot = request.getOutputStream();
ot.write(end_data);
ot.write(attachable.getBytes());
ot.write(end_data);
//ot.write(status.getBytes());
ot.write(pic.getBytes());
ot.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
ot.write(file);
ot.write(end_data);
ot.flush();
ot.close();
System.err.println("Sending request...");
request.connect();
System.err.println("Response: " + request.getResponseCode() + " "
+ request.getResponseMessage());
BufferedReader reader =new BufferedReader(new InputStreamReader(request.getInputStream()));
String b = null;
while((b = reader.readLine())!=null){
System.err.println(b);
}
The returned result:
Response: 200 OK
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2013-11-10T20:24:27.823-08:00"/>
But I don't see the file on Quickbooks Online.
Maybe I miss something. Can someone help me?
Thank you in advance
I had tried this Upload endpoint call using Java Devkit. It is working fine. PFB details.
- Request URI : https://quickbooks.api.intuit.com/v3/company/688779980/upload? Http
- Method : POST Content-Disposition: form-data; name="file_metadata_2bddf"
- Content-Type: application/xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Attachable xmlns="http://schema.intuit.com/finance/v3">
<FileName>images.jpg</FileName>
<ContentType>image/jpeg</ContentType>
<Lat>25.293112341223</Lat>
<Long>-21.3253249834</Long>
<PlaceName>Fake Place</PlaceName>
<Note>Attachable note 900a49e1</Note>
<Tag>Attachable tag 900a49e1</Tag>
</Attachable>
Response XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2013-11-12T05:58:25.296-08:00">
<AttachableResponse>
<Attachable domain="QBO" sparse="false">
<Id>100000000000543524</Id>
<SyncToken>0</SyncToken>
<MetaData>
<CreateTime>2013-11-12T05:58:26-08:00</CreateTime>
<LastUpdatedTime>2013-11-12T05:58:26-08:00</LastUpdatedTime>
</MetaData>
<FileName>images.jpg</FileName>
<FileAccessUri>/v3/company/688779980/download/100000000000543524</FileAccessUri>
<TempDownloadUri>https://intuit-qbo-prod-19.s3.amazonaws.com/688779980%2Fattachments%2Fimages-1384264705362.jpg?Expires=1384265606&AWSAccessKeyId=AKIAJEXDXKNYCBUNCCCQ&Signature=ESZPzeO%2B5YWxw8VOWMVMBRnvIdw%3D</TempDownloadUri>
<Size>58616</Size>
<ContentType>image/jpeg</ContentType>
<Lat>25.293112341223</Lat>
<Long>-21.3253249834</Long>
<PlaceName>Fake Place</PlaceName>
<Note>Attachable note 8219e79a</Note>
<Tag>Attachable tag 8219e79a</Tag>
<ThumbnailFileAccessUri>/v3/company/688779980/attachable-thumbnail/100000000000543524</ThumbnailFileAccessUri>
</Attachable>
</AttachableResponse>
</IntuitResponse>
From the ThumnailFileAccessUri property I got the following attachment URI which I had used for Download endpoint.
/v3/company/688779980/attachable-thumbnail/100000000000543524
Download Endpoint(GET)-
https://quickbooks.api.intuit.com/v3/company/688779980/download/100000000000543521
JAVA/.Net SDK download link - https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits
Hope it will be useful.
EDIT- Adding Java code snippet
public static void executeUploadForImageFilePoc(DataService service) throws ParseException, FMSException, FileNotFoundException {
System.out.println("executeUploadForImageFile");
String uuid = UUID.randomUUID().toString().substring(0, 8);
Attachable attachable1 = new Attachable();
//attachable.setSize(new Long("34234"));
attachable1.setLat("25.293112341223");
attachable1.setLong("-21.3253249834");
attachable1.setPlaceName("Fake Place");
attachable1.setNote("Attachable note " + uuid);
attachable1.setTag("Attachable tag " + uuid);
Attachable attachable = attachable1;
attachable.setFileName("images.jpg");
attachable.setContentType("image/jpeg");
File file = new File("C:\\images_new.jpg");
InputStream in = new FileInputStream(file);
//Upload endpoint call
Attachable attachableOutput = service.upload(attachable, in);
//Check return XML
attachable.getFileAccessUri();
System.out.println(attachableOutput.getFileAccessUri());
System.out.println(attachableOutput.getFileName());
//Download endpoint call
InputStream output = service.download(attachableOutput);
try {
BufferedImage bImageFromConvert = ImageIO.read(output);
ImageIO.write(bImageFromConvert, "jpg", new File("C:\\images_new_manas.jpg"));
} catch (IOException e) {
throw new FMSException("Error while reading the upload file.", e);
}
}
Thanks
I have a working code in dotnet. See if it works for you:
DataService.DataService commonServiceQBO= new DataService.DataService(qboContextoAuth);
string imagePath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "\\", "Services\\Resource\\image.jpg");
System.IO.FileInfo file = new System.IO.FileInfo(imagePath);
Attachable attachable = new Attachable();
attachable.AttachableRef = new AttachableRef[1];
attachable.AttachableRef[0].EntityRef = new ReferenceType();
attachable.AttachableRef[0].EntityRef.type = "Bill";
attachable.AttachableRef[0].EntityRef.Value = "12";
attachable.Lat = "25.293112341223";
attachable.Long = "-21.3253249834";
attachable.PlaceName = "Fake Place";
attachable.Note = "Attachable note123 ";
attachable.Tag = "Attachable tag123 ";
using (System.IO.FileStream fs = file.OpenRead())
{
attachable.ContentType = "image/jpeg";
attachable.FileName = file.Name;
Attachable attachableUploaded = commonServiceQBO.Upload(attachable, fs);
}
For download use:
byte[] responseByte = service.Download(attachableUploaded);

Use property file in a JAR

After a lot of property file articles and comments I am really lost.
All I want is to retrieve values and to overwrite them - and I want to use that with a jar-file.
If I compile in eclipse it works perfectly but the moment I compile I got the famous "property file not found"-exception.
FileInputStream in = new FileInputStream(ClassLoader.getSystemResource("client.properties").getPath());
Properties props = new Properties();
props.load(in);
in.close();
The exception I got is the following:
C:\Users\thomas\Desktop>java -jar erp_auer_client_v0_1.jar
java.io.FileNotFoundException: file:\C:\Users\thomas\Desktop\erp_auer_client_v0_
1.jar!\client.properties (Die Syntax f³r den Dateinamen, Verzeichnisnamen oder d
ie Datentrõgerbezeichnung ist falsch)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at global_functions.helperFunctions.getPathBARTENDEREXE(helperFunctions.
java:361)
at client.programmeinstellungen.ProgrammEinstellungenManagement.<init>(P
rogrammEinstellungenManagement.java:59)
at client.main.MainOverview$11.mousePressed(MainOverview.java:275)
The german part (Die Syntax f³r den Dateinamen, Verzeichnisnamen oder d
ie Datentrõgerbezeichnung ist falsch) means "The syntax for the filename, directory name or disk name is wrong".
Do you have an idea what that could be?
Alright, I tried it myself and realized that it is a little more trickier than I thought initially. However, I think that in your scenario you can just use something like bellow. I tested in windows and linux and worked fine for me:
package mypackage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.Properties;
public class MyMainClass {
public static void main(String[] args) throws URISyntaxException {
/*
*
* MyMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
* In Linux it returns null
*
* ClassLoader.getSystemClassLoader().getResource(".").getPath() + "MyProperty.properties";
* In Linux it returns {JRE_PATH}/lib/ext/pulse-java.jar
* In Windows it returns {JAR_FILE_PATH}
*/
String propertyFilePath = "MyProperty.properties";
Properties props = new Properties();
try {
FileInputStream in = new FileInputStream(propertyFilePath);
props.load(in);
in.close();
} catch (Exception e) {
File f = new File(propertyFilePath);
System.err.println("Could not read file: " + f.getAbsolutePath());
}
System.out.println("Fetching property value of [now]: " + props.get("now"));
String now = new Date().toString();
System.out.println("Storing property [now]: " + now);
props.setProperty("now", now);
try {
OutputStream out = new FileOutputStream(propertyFilePath);
props.store(out, "Saving value of [now]");
} catch (Exception e) {
File f = new File(propertyFilePath);
System.err.println("Could not write file: " + f.getAbsolutePath());
}
}
}

Detail Hudson test reports

Is there any way to force Hudson to give me more detailed test results - e.g. I'm comparing two strings and I want to know where they differ.
Is there any way to do this?
Thank you for help.
You should not hope Hudson give the detail information, it just shows the testing messages generated by junit.
You could show the expected string and actual string when failing asserting equals between those two strings.
For example,
protected void compareFiles(File newFile, String referenceLocation, boolean lineNumberMatters) {
BufferedReader reader = null;
BufferedReader referenceReader = null;
List<String> expectedLines = new ArrayList<String>();
try {
referenceReader = new BufferedReader(new InputStreamReader(FileLocator.openStream(Activator.getDefault().getBundle(), new Path("data/regression/" + referenceLocation), false))); //$NON-NLS-1$
expectedLines = getLinesFromReader(referenceReader);
} catch (Exception e) {
assertFalse("Exception occured during reading reference data: " + e, true); //$NON-NLS-1$
}
List<String>foundLines = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(newFile));
foundLines = getLinesFromReader(reader);
} catch (Exception e) {
assertFalse("Exception occured during reading file: " + e, true); //$NON-NLS-1$
}
boolean throwException = expectedLines.size() != foundLines.size();
if (throwException) {
StringBuffer buffer = new StringBuffer("\n" + newFile.toString()); //$NON-NLS-1$
for (String line: foundLines)
buffer.append(line + "\n"); //$NON-NLS-1$
assertEquals("The number of lines in the reference(" + referenceLocation + ") and new output(" + newFile.getAbsolutePath()+ ") did not match!" + buffer, expectedLines.size(), foundLines.size()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
if (!lineNumberMatters) {
Collections.sort(expectedLines);
Collections.sort(foundLines);
}
/** Either the line matches character by character or it matches regex-wise, in that order */
for (int i=0;i<expectedLines.size(); i++)
assertTrue("Found errors in file (" + newFile + ")! " + foundLines.get(i) + " vs. " + expectedLines.get(i), foundLines.get(i).equals(expectedLines.get(i)) || foundLines.get(i).matches(expectedLines.get(i))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
Hudson supports JUnit directly. On your job configuration page, near the end, should be an option to "Publish JUnit test results report".
I'm not too familiar with JUnit itself, but I guess it produces (or has the ability to produce) and put results in an xml file. You just need to put the path of to the xml file (relative to the workspace) in the text box.
Once you do that, and create a build, you'll have a detailed report on your project page. You should then be able to click your way through the results for each test.