Nifi:transfer relationship not specified - groovy

I want to update xml data and write it in flowfile1 but for some reason my ExecuteScript processor can't specify transfer relationship here is my code, what should i change to make this task?:
Is it possbile that my code inside session.write can't cast xml data to ByteArray and can't write this in flowfile content? ( but it doesn't throw exception)
flowFile1 = session.putAttribute(flowFile1, "filename", "conf.xml");
session.write(flowFile1, new StreamCallback() {
#Override
public void process(InputStream inputStream1, OutputStream outputStream) throws IOException {
TransformerFactory transformerFactory1 = TransformerFactory.newInstance();
Transformer transformer1 = null;
try {
transformer1= transformerFactory1.newTransformer();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}
DOMSource source1 = new DOMSource(doc);
ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
StreamResult result = new StreamResult(bos1);
try {
transformer1.transform(source1, result);
} catch (TransformerException e) {
e.printStackTrace();
}
byte[] array1 = bos1.toByteArray();
outputStream.write(array1);
}
});
if(flowFile1!=null){
session.transfer(flowFile1, REL_SUCCESS);
}
else{
session.transfer(flowFile1, REL_FAILURE);
}
}catch (OverlappingFileLockException e) {
lock.release();
}
catch (FileNotFoundException e) {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.release();
ini.close();
}

session.write() returns a reference to a newer version of the flow file, but you are not storing it or transferring it. Later on, you end up trying to transfer a version that is not the latest. Try adding "flowFile1 = " to the beginning of your session.write() statement.

Related

How to copy content of generic object for specific object

I need a support in this code, I have a method that I get generic object and a String, so according to the String I get I want to copy the contents of the generic object to
specific object, one observation that Object TypeA don't have same fields that TypeB. for example:
Thanks in advance
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Authorize("Receiving")
#Path("/Print")
public Response LabelPrint(#Context HttpServletRequest request,
final Object generic
,#QueryParam("Type") final String Type) {
if ( Typex.compareTo("X")) {
TypeA typeA = generic;
...
} else {
TypeB typeB = generic;
...
}
return buildResponse(OK);
}
I tried that away, but unsuccessfully
if (labelType.compareTo("X")) {
TypeA x = new TypeA();
BeanUtils.copyProperties(x, generic);
}
else {
TypeA y = new TypeA();
BeanUtils.copyProperties(y, generic);
}
I managed to do it that away, receiving how String
public Response LabelPrint(#Context HttpServletRequest request,
final String objetcForImpression
,#QueryParam("Type") final String Type) {
if ( Typex.compareTo("X")) {
try {
ObjectMapper objetcForImpression = new ObjectMapper();
TypeA typeA = objetcForImpression.readValue(objetcForImpression, TypeA.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
...
} else {
try {
ObjectMapper objetcForImpression = new ObjectMapper();
TypeB typeB = objetcForImpression.readValue(objetcForImpression, TypeA.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return buildResponse(OK);
}

retrofit2.0.0+okhttp3 download logging output OOM

addInterceptor ->HttpLoggingInterceptor bug-->OOM
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//设置缓存路径
File httpCacheDirectory = new File(MyApplication.mContext.getCacheDir(), "responses");
//设置缓存 10M
Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
OkHttpClient client = null;
final TrustManager[] trustManager = new TrustManager[]{
new X509TrustManager() {
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}
};
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManager, new SecureRandom());
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
client = new OkHttpClient.Builder().addInterceptor(interceptor).sslSocketFactory(sslSocketFactory).addInterceptor(new BaseInterceptor()).hostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}).cache(cache).build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
_instance = new Retrofit.Builder().baseUrl(ConstantUtils.HOST)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()).client(client).build();
}
return _instance.create(ICommonService.class);
RetrofitUtils.generateCommonService().down().subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ResponseBody>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
LogUtils.e("errorrrrrrrrrr");
}
#Override
public void onNext(ResponseBody responseBody) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
byte[] by = responseBody.bytes();
File file = new File(BaseApplication.getContext().getFilesDir(), "download.apk");
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(by);
LogUtils.e("length=======>",file.length()+"");
mainView.updateApk(file);
}catch (IOException e){
e.printStackTrace();
}finally {
if (bos != null)
{
try
{
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (fos != null)
{
try
{
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
LogUtils.e("success=========");
}
});
When you use HttpLoggingInterceptor.Level.BODY , then you try to download large file , will save all body in memory for log.
That's easy let to OOM .
Try to remove log body or just logging NONE , basic or header and try again.
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//设置缓存路径
Try this .
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
//设置缓存路径

send a JSON request with JSONObject as parameter?

I want to make an android-json request to a webservice with httpClient.
The method which i try to call is "authenticate"
The request should have the following structure:
{"id":"ID","method":"authenticate","params":{"user":"ANDROID",
"password":"PASSWORD", "client":"CLIENT"},"jsonrpc":"2.0"}
mandatory parameter: ?school=SCHOOLNAME
This is what i have tried:
class MyAsnycTask extends AsyncTask<String, String, String>{
protected String doInBackground(String... params) {
String apiUrl = "https://arche.webuntis.com/WebUntis/jsonrpc.do";
JSONObject jsonParams = new JSONObject();
JSONObject params1 = new JSONObject();
HttpClient client = new DefaultHttpClient();
// Prepare a request object
HttpPost post = new HttpPost(apiUrl);
post.setHeader("Content-type", "application/json");
try {
params1.put("?school","litec");
params1.put("user", "40146720133271");
params1.put("password", "1234567");
jsonParams.put("id", "ID");
jsonParams.put("method", "authenticate");
jsonParams.put("params", params1);
jsonParams.put("jsonrpc", "2.0");
StringEntity se = new StringEntity(jsonParams.toString());
post.setEntity(se);
} catch (JSONException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Execute the request
try {
HttpResponse response = client.execute(post);
Log.d("log_response: ", response.getStatusLine().toString());
// Get hold the response entity
HttpEntity entity = response.getEntity();
// if the response does not enclose the entity, there is no need
// to worry about it
if(entity != null){
// a simple JSON Response read
InputStream instream = entity.getContent();
String result;
// convert content of response to bufferedreader
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
instream.close();
}catch(IOException exp){
exp.printStackTrace();
}
}
result = sb.toString();
Log.d("Result of the Request: ", result);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "OK";
}
protected String doInBackground(String result) {
return result;
// TODO Auto-generated method stub
}
}
After executing this, i get the request:
{"jsonrpc":"2.0","id":"error","error":{"message":"invalid schoolname","code":-8500}}
So its telling me that our schoolname is false.
So what can i do, is my way to pass parameters wrong ?
I saw your question some time ago, but I was not able to answer. I'm working with the WebUntis API as well, and I dont know if you solved the error, but it is a simple error in the url. As mentionend in the API, the mandatory paramter for the method 'authenthicate' is ?school=SCHULNAME. Your Url in the code is 'https://arche.webuntis.com/WebUntis/jsonrpc.do', but the mandatory parameter SCHULNAME is not given. Your Url should look like this: https://arche.webuntis.com/WebUntis/jsonrpc.do?school=SCHULNAME. Maybe you have to add the length of your request. E.g. if you use the method authenthicate: {"id":"ID","method":"authenticate","params":{"user":"USR", "password":"PW", "client":"MyApp"},"jsonrpc":"2.0"}
In this case length would be 109. I hope this helped, even if the question is over a month old. For other Googlers: If you are not using an AsyncTask, you have to return true, not ok.
EDIT:
The code looks like this (I haven't tested this yet, I hope it works):
class MyAsnycTask extends AsyncTask<String, String, String>{
protected String doInBackground(String... params) {
String apiUrl = "https://arche.webuntis.com/WebUntis/jsonrpc.do?school=SCHULNAME"; //Changes here
JSONObject jsonParams = new JSONObject();
JSONObject params1 = new JSONObject();
HttpClient client = new DefaultHttpClient();
// Prepare a request object
HttpPost post = new HttpPost(apiUrl);
post.setHeader("Content-type", "application/json");
try {
params1.put("user", "40146720133271");
params1.put("password", "1234567");
params1.put("client", "seriouslysAndroidApp"); //You can change the name
jsonParams.put("id", "ID");
jsonParams.put("method", "authenticate");
jsonParams.put("params", params1);
jsonParams.put("jsonrpc", "2.0");
StringEntity se = new StringEntity(jsonParams.toString());
post.setHeader("Content-length",""+se.getContentLength()); //header has to be set after jsonparams are complete
post.setEntity(se);
} catch (JSONException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Execute the request
try {
HttpResponse response = client.execute(post);
Log.d("log_response: ", response.getStatusLine().toString());
// Get hold the response entity
HttpEntity entity = response.getEntity();
// if the response does not enclose the entity, there is no need
// to worry about it
if(entity != null){
// a simple JSON Response read
InputStream instream = entity.getContent();
String result;
// convert content of response to bufferedreader
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
instream.close();
}catch(IOException exp){
exp.printStackTrace();
}
}
result = sb.toString();
Log.d("Result of the Request: ", result);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "OK";
}
protected String doInBackground(String result) {
return result;
// TODO Auto-generated method stub
}

How to use CatalogResolver in JAXB

Here is a method to do that, but I'm not sure if it is a reasonable way.
final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
CatalogManager.getStaticManager().setIgnoreMissingProperties(true);
final CatalogResolver entityResolver = new CatalogResolver(true);
try {
entityResolver.getCatalog().parseCatalog(new URL("file:///catalog.cat"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sf.setResourceResolver(new LSResourceResolver() {
#Override
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
if (publicId == null) {
publicId = namespaceURI;
}
return new LSInputSAXWrapper(entityResolver.resolveEntity(publicId, systemId));
}
});

how to read a text file stored in mobile using j2me midp2.0?

HI ALL,
I am working in j2me midp2.0 environment.My application wants to read a text file which is stored in mobile device.How to read the text file programatically using j2me.Please give me idea to get this.What is the root folder in mobile to place the text file for accessible from j2me Application environment.
Saravanan.P
You need javax.microedition.io.file.FileConnection
Get root folder:
try {
Enumeration roots = FileSystemRegistry.listRoots();
while(roots.hasMoreElements()) {
System.out.println("Root: file:///"+(String)roots.nextElement());
}
} catch(Exception e) {
}
write to file
public void write(String root) {
FileConnection fc = null;
String fName = "test.txt";
try {
fc = (FileConnection) Connector.open(root + fName, Connector.READ_WRITE);
if(!fc.exists()) {
fc.create();
}
DataOutputStream dos = fc.openDataOutputStream();
dos.writeUTF("test-test");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fc.close();
} catch (IOException e) { }
}
}
read from file
public void read(String root) {
FileConnection fc = null;
try {
fc= (FileConnection) Connector.open(root + "test.txt", Connector.READ);
DataInputStream dis = fc.openDataInputStream();
String data = dis.readUTF();
System.out.println(data);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fc.close();
} catch (IOException e) { }
}
}
Better u use FileConnection.
FileConnection fc=(FileConnection)Connector.ope(url);

Resources