Nifi: how to remove session based on atribute value in nifi - groovy

I want to remove session in case i get certain data from file i have code like this,but i got errors "flowfile has already marked for removal", what should i change to get rid of extra errors?
In case of session rollback flowfile will dissapear in queues also?
2.should i use rollback instead of remove()?
NodeList childNodes = nodeGettingChanged.getChildNodes();
for (int i = 0; i != childNodes.getLength(); ++i) {
Node child = childNodes.item(i);
if (!(child instanceof Element))
continue;
if (child.getNodeName().equals("runAs")) {
if(child.getFirstChild().getTextContent()=="false"){
session.remove(flowFile1);
File deleteExtraFile =new File("C://Users//s.tkhilaishvili//Desktop//try2//nifi-1.3.0//1//conf.xml");
boolean delete=deleteExtraFile.delete();
}
else {
child.getFirstChild().setNodeValue("false");
}
}
}
Document finalXmlDocument = xmlDocument;
session.write(flowFile1, new StreamCallback() {
public void process(InputStream inputStream, OutputStream outputStream) throws IOException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}
DOMSource source = new DOMSource(finalXmlDocument);
ffStream.close();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult result = new StreamResult(bos);
try {
transformer.transform(source, result);
} catch (TransformerException e) {
e.printStackTrace();
}
byte[] array = bos.toByteArray();
outputStream.write(array);
}
});
session.remove(flowFile);
session.transfer(flowFile1, REL_SUCCESS);
}

If you are executing session.remove(flowFile1) then later trying to transfer it to REL_SUCCESS, you will get that error. It looks like you already have an if-clause checking the firstChild for "false", perhaps you could put the transfer in an else-clause, such that it will only be transferred if it wasn't removed.

Related

How to print from Android Studio Barcode printer

Barcode I want to send a barcode to the printer. I tried it in PDF, JPEG, PNG format. It prints a blank page on all of them.I couldn't find any results on google.
I need to do it without using Printer Helper, if possible
public class yazdır extends AsyncTask<Void , Void,Void> {
#Override
protected Void doInBackground(Void... arg0) {
DataOutputStream outToServer;
Socket clientSocket;
File filename;
PrintHelper photoPrinter = new PrintHelper(getActivity());
photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
for (int i=0;i<=adet;i++) {
try {
String path = Environment.getExternalStorageDirectory().toString();
filename = new File(path + "/folder/subfolder/image.png");
FileInputStream fileInputStream = new FileInputStream(filename);
InputStream is = fileInputStream;
clientSocket = new Socket("192.168.1.31", 9100);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
byte[] buffer = new byte[1024];
int size;
while ((size=is.read(buffer)) !=-1){
outToServer.write(buffer,0,size);
}
outToServer.flush();
} catch (ConnectException connectException) {
Log.e(TAG, connectException.toString(), connectException);
return null;
} catch (UnknownHostException e1) {
Log.e(TAG, e1.toString(), e1);
return null;
} catch (IOException e1) {
Log.e(TAG, e1.toString(), e1);
return null;
} finally {
}
}
return null;}
}
When I send it to a regular printer. Says document is printing and cancels printing.

Error java.lang.IllegalStateException: Unable to obtain OutputStream because Writer is already in use

I'm trying to download an Excel in a liferay portlet but when I'm going to get the outPutPortletStream I obtain the next exception:
java.lang.IllegalStateException: Unable to obtain OutputStream because Writer is already in use
This is the method I'm using to download the Excel:
public static void descargaFichero(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws Exception {
HttpServletRequest request = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(resourceRequest));
OutputStreamWriter osWriter = null;
BufferedWriter bWriter = null;
OutputStream outputStream = null;
InputStream is = null;
InputStreamReader isr = null;
File tempFile = null;
try {
String idDescarga = request.getParameter("id-descarga");
String rutaFicheroDescarga = Encriptador.decrypt(ConstantesFlujos.CLAVE_ENCRIPTADO_JSON, idDescarga);
String extension = FileUtil.getExtension(rutaFicheroDescarga);
String nombreArchivo = String.format("%s%s.%s",
ConstantesFlujos.PREFIJO_NOMBRE_FICHERO_RENOVACION,
fechaDesglosada(),
extension);
if(GestorLog.isInfoEnabled(clase)){
GestorLog.info(clase, String.format("Descargando fichero temporal: '%s' a '%s'", rutaFicheroDescarga, nombreArchivo));
}
if (extension.equalsIgnoreCase("xls")) {
resourceResponse.setContentType("application/vnd.ms-excel");
} else {
resourceResponse.setContentType("application/octet-stream");
}
((PortletResponse) resourceResponse).addProperty("Content-disposition", String.format("atachment; filename=%s", nombreArchivo));
tempFile = new File(rutaFicheroDescarga);
outputStream = resourceResponse.getPortletOutputStream();
osWriter = new OutputStreamWriter(outputStream, "ISO-8859-1");
char[] buf = new char[8192];
is = new FileInputStream(tempFile);
isr = new InputStreamReader(is, "ISO-8859-1");
int c = 0;
while ((c = isr.read(buf, 0, buf.length)) > 0) {
osWriter.write(buf, 0, c);
osWriter.flush();
}
} catch(Exception e){
GestorLog.error(clase, "Error en el metodo descargaFichero: " + e.getMessage());
throw e;
} finally {
if (isr != null) {
isr.close();
}
if (is != null) {
is.close();
}
if (bWriter != null) {
bWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (tempFile != null) {
tempFile.delete();
}
}
}
And I get the error in the line:
outputStream = resourceResponse.getPortletOutputStream();
This might be due to resourceResponse.addProperty being called before accessing the stream. Those operations can be nasty, as two parties will now try to write data to the output.
An easy way to omit all problems is to just delegate it all to the portal: PortletResponseUtil.sendFile exists in a couple of different variations, e.g.
PortletResponseUtil.sendFile(
resourceRequest,
resourceResponse,
fileName,
inputStream,
contentLength,
contentType,
contentDispositionType); // e.g. HttpHeaders.CONTENT_DISPOSITION_ATTACHMENT

Nifi: can't recognize groovy xmlSlurper structure

[enter image description here][1]I have nifi 1.3.0. Is it possible that groovy version which is implemented in nifi can't recognize lambdas? Here is my code, how can I change it to make work inside nifi processor?
is it possible that processor doesn;t work properly because i don't use session.tranfer i mean don't produce any flowfile?
def static addDays(def date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(date));
c.add(Calendar.DATE, 1); // number of days to add
String m = sdf.format(c.getTime()); // dt is now the new date
return m;
}
def flowFile=session.get()
ArrayList<String> value = new ArrayList<>();
if(flowFile!=null){
value.add(flowFile.getAttribute('filename');
session.remove(flowFile);
}
File file = new File("C://Users//user//Desktop//try2//nifi-1.3.0//4//conf2.xml");
String content = "";
String material = "";
BufferedReader s;
BufferedWriter w;
RandomAccessFile ini = new RandomAccessFile(file, "rwd");
FileLock lock = ini.getChannel().lock();
DocumentBuilder dBuilder;
Document document, doc;
String date="",data="";
try {
String sCurrentLine;
s = new BufferedReader(Channels.newReader(ini.getChannel(), "UTF-8"));
while ((sCurrentLine = s.readLine()) != null) {
content += sCurrentLine;
}
ini.seek(0);
def xml = new XmlParser().parseText(content)
for(int i=0;i<value.size();i++) {
date = value.get(i).substring(0, 10);
xml.rs.borderCross.details.findAll({ p ->
p.runAs[0].text() == "false" && p.start[0].text() == date.toString()
}).each({ p ->
p.start[0].value = addDays( p.start[0].text())
p.runAs[0].value = "true"
})
}
def stringWriter = new StringWriter()
new XmlNodePrinter(new PrintWriter(stringWriter)).print(xml)
def newXml = stringWriter.toString()
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
InputStream stream1 = new ByteArrayInputStream(newXml.toString().getBytes("UTF-8"));
DocumentBuilderFactory dbFactory1 = DocumentBuilderFactory.newInstance();
dBuilder = dbFactory1.newDocumentBuilder();
document = dBuilder.parse(stream1);
DOMSource source=new DOMSource(document);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult result1 = new StreamResult(bos);
try {
transformer.transform(source, result1);
} catch (TransformerException e) {
e.printStackTrace();
}
byte[] array = bos.toByteArray();
data = bos.toString();
if (!data.isEmpty()) {
ini.setLength(0);
w = new BufferedWriter(Channels.newWriter(ini.getChannel(), "UTF-8"));
w.write(data);
lock.release();
w.close();
}
else{
ini.setLength(0);
w = new BufferedWriter(Channels.newWriter(ini.getChannel(), "UTF-8"));
w.write(content);
lock.release();
w.close();
}
}catch (FileNotFoundException e) {
TimeUnit.SECONDS.sleep(50000);
} catch (IOException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (OverlappingFileLockException e) {
TimeUnit.SECONDS.sleep(50000);
lock.release(); ;
} catch (Exception e) {
e.printStackTrace();
} finally {
//lock.release();
ini.close();
}
Those aren't Java lambdas, they are Groovy closures. At first glance that looks correct, what error(s) are you getting? You may need to put the closures in parentheses before chaining them:
def xml = new XmlParser().parseText(content)
for(int i=0;i<value.size();i++) {
date = value.get(i).substring(0, 10);
xml.rs.borderCross.details.findAll({ p ->
p.runAs[0].text() == "false" && p.start[0].text() == date.toString()
}).each({ p ->
p.start[0].value = addDays( p.start[0].text())
p.runAs[0].value = "true"
})
}

Modified a model by Jena, how to reload this owl file to Protege

As shown in the title, I read owl file which is generated by Protege to Jena, modified it by adding some NamedIndividuals, and I wanted to read the modified file by Protege. Things went on well until I open this owl file with Protege. Protege just can not read it!
I tried every "RDF/XML", "RDF/XML - ABBREV", "N - TRIPLE", "TTL", and still nothing.
One good news is that when I use "RDF/XML - ABBREV" and delete all the NamedIndividual I added, Protege works.
But I want my Individuals!!!
public class Pizza00 {
public static void main(String[] args) throws IOException{
String SOURCE = "http://www.seaice.com/ontologies/seaice.owl";
String NS = SOURCE + "#";
OntModel m = ModelFactory.createOntologyModel();
try {
m.read(new FileInputStream("G:/Protege/owl files/SeaIce.owl"), null);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
reason rec = new reason();
rec = readFileByLines("G:/data/seaice_property.txt");
int i;
OntClass tmp = m.getOntClass(NS + "SeaIceProperty");
for(i = 1; i <= rec.line - 1; i ++){
m.createIndividual(NS + rec.s[i], tmp);
}
m.write(System.out);
OutputStream out = new FileOutputStream("G:/Protege/owl files/SeaIce - by jena.owl");
m.write(out, "RDF/XML-ABBREV", null);
out.close();
}
static class reason{
String[] s= new String[1000];
int line;
}
public static reason readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
reason x = new reason();
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
x.s[x.line] = tempString;
x.line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return x;
}
}
As you mention in the comments, the error is
this line <j.0:SeaIceProperty
rdf:about="seaice.com/ontologies/seaice.owl#Optical Band Imagery"/>
error occurs.
And the error by Protege is
org.semanticweb.owlapi.rdf.syntax.RDFParserException:
[line=30:column=101] IRI 'seaice.com/ontologies/seaice.owl#Optical
Band Imagery' cannot be resolved against curent base IRI
file:/G:/Protege/owl%20files/SeaIce%20-%20by%20jena.owl
The not-quite IRI seaice.com/ontologies/seaice.owl#Optical Band Imagery is relative, and can't be resolved against the current base IRI, which is a file IRI: file:/G:/Protege/owl%20files/SeaIce%20-%20by%20jena.owl. The easiest way to fix this is to use absolute IRIs when you are creating your named individuals.

save data from servlet to recordstore in j2me

I am developing an j2me application which is communicating with the database using servlet.
I want to store the data received from servlet into record store and display it.how this can be achieved?Please provide code examples.
Thank you in advance
public void viewcon()
{
StringBuffer sb = new StringBuffer();
try {
HttpConnection c = (HttpConnection) Connector.open(url);
c.setRequestProperty("User-Agent","Profile/MIDP-1.0, Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);
DataOutputStream os = (DataOutputStream)c.openDataOutputStream();
os.flush();
os.close();
// Get the response from the servlet page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
}
// return sb;
showAlert(sb.toString());//display data received from servlet
is.close();
c.close();
} catch (Exception e) {
showAlert(e.getMessage());
}
}
Put this function call where you show the response data alert
writeToRecordStore(sb.toString().getBytes());
The function definition is as below:
private static String RMS_NAME = "NETWORK-DATA-STORAGE";
private boolean writeToRecordStore(byte[] inStream) {
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore(RMS_NAME, true);
if (null != rs) {
//Based on your logic either ADD or SET the record
rs.addRecord(inStream, 0, inStream.length);
return true;
} else {
return false;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
return false;
} finally {
try {
if (null != rs) {
rs.closeRecordStore();
}
} catch (RecordStoreException recordStoreException) {
} finally {
rs = null;
}
}
}
After you have saved the data, read the records store RMS-NAME and check the added index to get the response data.
.
NOTE: The assumption is the network response data is to be appended to the record store. If you want to set it to a particular record modify the method writeToRecordStore(...) accordingly.
//this code throws exception in display class.
try
{
byte[] byteInputData = new byte[5];
int length = 0;
// access all records present in record store
for (int x = 1; x <= rs.getNumRecords(); x++)
{
if (rs.getRecordSize(x) > byteInputData.length)
{
byteInputData = new byte[rs.getRecordSize(x)];
}
length = rs.getRecord(x, byteInputData, 0);
}
alert =new Alert("reading",new String(byteInputData,0,length),null,AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}

Resources