Print the shortest path to the java console using orientdb - orientdb

I want to print in the Java console shortestpath between two vertices. I can not print anything or if you have any way to do that would appreciate it.
String subquery = "Select shortestpath(17:10, 17:14, BOTH) ";
Iterable<OrientVertex> result = orientDBGraph.command(new OSQLSynchQuery<OrientVertex>(subquery)).execute();
Assert.assertTrue(result.iterator().hasNext());
System.out.println(result);
for (OrientVertex d : result) {
System.out.println("Shortest path from " + ((OrientVertex) d.getProperty("$current")).getProperty("name") + " and "
+ ((Iterable<OrientVertex>) d.getProperty("$target")).iterator().next().getProperty("name") + " is: "
+ d.getProperty("path"));
}

Code:
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String dbName = "ytrewa";
OrientGraphFactory dbfactory = new OrientGraphFactory("remote:127.0.0.1:2424/"+dbName, "root", "root").setupPool(1, 50);
OrientGraph g = dbfactory.getTx();
try {
String query = "select expand(shortestPath) from (select shortestPath(#9:0,#9:1,BOTH))";
Iterable<OrientVertex> res = g.command(new OCommandSQL(query)).execute();
while(res.iterator().hasNext()){
OrientVertex v = res.iterator().next();
System.out.println("rid: "+v.getId().toString());
}
} finally {
g.shutdown();
}
}
}
Output:
rid: #9:0
rid: #10:0
rid: #12:0
rid: #9:1

Related

How to read datamatrix embedded in document?

I try to read a datamatrix which is embedded into a document.
This is for an opensource project which helps to create and read 2DCODE standard.
I try with this code :
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import org.junit.Test;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
public class ZxingTest {
#Test
public void test() {
readQRCode("sfr-facture-1048469311-1.jpg");
readQRCode("sfr-facture-1048469311-1.png");
}
public static void readQRCode(String fileName) {
System.out.println("Try reading " + fileName);
File file = new File(fileName);
BufferedImage image = null;
try {
image = ImageIO.read(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (image == null)
return;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
// hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, Arrays.asList(BarcodeFormat.DATA_MATRIX));
decode(image, hints);
}
public static void decode(BufferedImage tmpBfrImage, Hashtable<DecodeHintType, Object> hintsMap) {
if (tmpBfrImage == null)
throw new IllegalArgumentException("Could not decode image.");
LuminanceSource tmpSource = new BufferedImageLuminanceSource(tmpBfrImage);
BinaryBitmap tmpBitmap = new BinaryBitmap(new HybridBinarizer(tmpSource));
MultiFormatReader tmpBarcodeReader = new MultiFormatReader();
Result tmpResult;
String tmpFinalResult;
try {
if (hintsMap != null && !hintsMap.isEmpty())
tmpResult = tmpBarcodeReader.decode(tmpBitmap, hintsMap);
else
tmpResult = tmpBarcodeReader.decode(tmpBitmap);
// setting results.
tmpFinalResult = String.valueOf(tmpResult.getText());
System.out.println("tmpFinalResult=" + tmpFinalResult);
} catch (Exception tmpExcpt) {
tmpExcpt.printStackTrace();
}
}
}
and those images found on the net :
sfr-facture-1048469311-1.jpg
sfr-facture-1048469311-1.png
But I get this exception regardless of the image format: com.google.zxing.NotFoundException
May you advise me an lib which parses the page and detect the datamatrix coordinates for a pre-processing cropping?
Or a better a example of code which read the datamatrix?
I have a solution to my problem. I use opencv to locate any barcode then, after extraction according to the returned coordinates, I read them with zxing.
I based my solution the work of http://karthikj1.github.io/BarcodeLocalizer/
this the code i use :
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Reader;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import barcodelocalizer.Barcode;
import barcodelocalizer.CandidateResult;
import barcodelocalizer.ImageDisplay;
import barcodelocalizer.MatrixBarcode;
import barcodelocalizer.TryHarderFlags;
public class OpencvUtils {
private static boolean SHOW_INTERMEDIATE_STEPS = false;
private static boolean showImages = false;
public static String process_bufferedImage(BufferedImage bufferedImage) {
Barcode barcode;
String barcodeText = null;
// instantiate a class of type MatrixBarcode with the image filename
try {
barcode = new MatrixBarcode(bufferedImage, SHOW_INTERMEDIATE_STEPS, TryHarderFlags.VERY_SMALL_MATRIX);
// locateBarcode() returns a List<CandidateResult> with all possible candidate
// barcode regions from
// within the image. These images then get passed to a decoder(we use ZXing here
// but could be any decoder)
List<CandidateResult> results = barcode.locateBarcode();
System.out.println("Decoding buffered image " + results.size() + " candidate codes found");
String barcodeName = barcode.getName();
barcodeText = decodeBarcode(results, barcodeName, "Localizer");
} catch (IOException ioe) {
System.out.println("IO Exception when finding barcode " + ioe.getMessage());
}
return barcodeText;
}
public static String process_image(String imgFile) {
Barcode barcode;
String barcodeText = null;
// instantiate a class of type MatrixBarcode with the image filename
try {
barcode = new MatrixBarcode(imgFile, SHOW_INTERMEDIATE_STEPS, TryHarderFlags.VERY_SMALL_MATRIX);
// locateBarcode() returns a List<CandidateResult> with all possible candidate
// barcode regions from
// within the image. These images then get passed to a decoder(we use ZXing here
// but could be any decoder)
List<CandidateResult> results = barcode.locateBarcode();
System.out.println("Decoding " + imgFile + " " + results.size() + " candidate codes found");
String barcodeName = barcode.getName();
barcodeText = decodeBarcode(results, barcodeName, "Localizer");
} catch (IOException ioe) {
System.out.println("IO Exception when finding barcode " + ioe.getMessage());
}
return barcodeText;
}
private static String decodeBarcode(List<CandidateResult> candidateCodes, String filename, String caption) {
// decodes barcode using ZXing and either print the barcode text or says no
// barcode found
BufferedImage decodedBarcode = null;
String title = null;
Result result = null;
String barcodeText = null;
for (CandidateResult cr : candidateCodes) {
BufferedImage candidate = cr.candidate;
decodedBarcode = null;
LuminanceSource source = new BufferedImageLuminanceSource(candidate);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new MultiFormatReader();
Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
try {
result = reader.decode(bitmap, hints);
decodedBarcode = candidate;
title = filename + " " + caption + " - barcode text " + result.getText() + " " + cr.getROI_coords();
} catch (ReaderException re) {
}
if (decodedBarcode == null) {
title = filename + " - no barcode found - " + cr.getROI_coords();
if (showImages)
ImageDisplay.showImageFrame(candidate, title);
} else {
if (showImages)
ImageDisplay.showImageFrame(decodedBarcode, title);
System.out.println("Barcode text for " + filename + " is " + result.getText());
barcodeText = result.getText();
}
}
return barcodeText;
}
}
i added the method process_bufferedImage which process a java.awt.image.BufferedImage of a String filename.
And this sub-method to get the matrix of the BufferedImage bi.
protected Mat loadBufferedImage(BufferedImage bi) throws IOException {
// reads the BufferedImage passed in parameter
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bi, "png", byteArrayOutputStream);
byteArrayOutputStream.flush();
Mat mat = Imgcodecs.imdecode(new MatOfByte(byteArrayOutputStream.toByteArray()), Imgcodecs.IMREAD_UNCHANGED);
return mat;
}

Java, reflection convert field into JAXBElement

I am trying to perform logging of SOAPMessage.
This object contains both wrapper classes and JAXBElements, I am doing something like this
#Before("soapRequest()")
public void logBefore(JoinPoint joinPoint) {
Object[] signatureArgs = joinPoint.getArgs();
System.out.println("\n\n\n");
for (Object signatureArg : signatureArgs) {
StringBuilder sb = new StringBuilder();
try {
Field[] aClassFields = signatureArg.getClass().getDeclaredFields();
sb.append(signatureArg.getClass().getSimpleName() + " [ ");
for (Field f : aClassFields) {
f.setAccessible(true);
String fName = f.getName();
String value = "";
if(f.get(signatureArg) instanceof JAXBElement) {
log.info("is instance of");
JAXBElement val = (JAXBElement) f.get(signatureArg);
log.info(val.toString());
value = val.getValue().toString();
} else {
value = f.get(signatureArg).toString();
}
sb.append("(" + f.getType() + ") " + fName + " = " + value + ", ");
}
sb.append("]");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sb.toString());
}
}
However this line throws NPE:
if(f.get(signatureArg) instanceof JAXBElement) {
log.info("is instance of");
JAXBElement val = (JAXBElement) f.get(signatureArg);
log.info(val.toString());
value = val.getValue().toString();
}
How Can I check if the field is instance of JAXBElement and extract value from it?
Actually I think your NPE occurs in the then block at this line of code:
value = f.get(signatureArg).toString();
It happens if the field value is null because on null you cannot call toString(). By the way, this should happen for any null field, not just for JAXBElement. You do not need toString(), you can just remove it because when you print any object, it will automatically use its toString() representation where applicable.
In my opinion your code is also more complicated than necessary and with some restructuring and renaming variables the then block is no longer necessary at all. Here is my MCVE in plain Java + AspectJ (no Spring) for you:
package de.scrum_master.app;
import javax.xml.bind.JAXBElement;
public class Container {
private String name;
private JAXBElement jaxbElement;
public Container(String name, JAXBElement jaxbElement) {
this.name = name;
this.jaxbElement = jaxbElement;
}
}
package de.scrum_master.app;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
public class Application {
public void doSomething(int number, String text, Container myContainer) {}
public static void main(String[] args) {
Application application = new Application();
application.doSomething(11, "foo", new Container("bar", new JAXBElement(new QName("local"), String.class, "dummy")));
application.doSomething(11, "foo", new Container("bar", null));
}
}
package de.scrum_master.aspect;
import java.lang.reflect.Field;
import javax.xml.bind.JAXBElement;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class MyAspect {
#Pointcut("execution(* doSomething(..))")
private void soapRequest() {}
#Before("soapRequest()")
public void logBefore(JoinPoint joinPoint) {
System.out.println(joinPoint);
for (Object methodArg : joinPoint.getArgs()) {
StringBuilder sb = new StringBuilder();
try {
sb.append(methodArg.getClass().getSimpleName() + " [ ");
for (Field field : methodArg.getClass().getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(methodArg);
if (value instanceof JAXBElement) {
System.out.println(" -> is instance of");
JAXBElement jaxbElement = (JAXBElement) value;
System.out.println(" -> " + jaxbElement);
value = jaxbElement.getValue();
}
// Un-comment this in order to see the NPE
//else {
// value = field.get(methodArg).toString();
//}
sb.append("(" + field.getType() + ") " + fieldName + " = " + value + ", ");
}
sb.append("]");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(" " + sb);
}
}
}
The console log looks like this:
execution(void de.scrum_master.app.Application.doSomething(int, String, Container))
Integer [ (int) MIN_VALUE = -2147483648, (int) MAX_VALUE = 2147483647, (class java.lang.Class) TYPE = int, (class [C) digits = [C#8efb846, (class [C) DigitTens = [C#2a84aee7, (class [C) DigitOnes = [C#a09ee92, (class [I) sizeTable = [I#30f39991, (int) value = 11, (int) SIZE = 32, (int) BYTES = 4, (long) serialVersionUID = 1360826667806852920, ]
String [ (class [C) value = [C#4a574795, (int) hash = 0, (long) serialVersionUID = -6849794470754667710, (class [Ljava.io.ObjectStreamField;) serialPersistentFields = [Ljava.io.ObjectStreamField;#f6f4d33, (interface java.util.Comparator) CASE_INSENSITIVE_ORDER = java.lang.String$CaseInsensitiveComparator#23fc625e, ]
-> is instance of
-> javax.xml.bind.JAXBElement#4f023edb
Container [ (class java.lang.String) name = bar, (class javax.xml.bind.JAXBElement) jaxbElement = dummy, ]
execution(void de.scrum_master.app.Application.doSomething(int, String, Container))
Integer [ (int) MIN_VALUE = -2147483648, (int) MAX_VALUE = 2147483647, (class java.lang.Class) TYPE = int, (class [C) digits = [C#8efb846, (class [C) DigitTens = [C#2a84aee7, (class [C) DigitOnes = [C#a09ee92, (class [I) sizeTable = [I#30f39991, (int) value = 11, (int) SIZE = 32, (int) BYTES = 4, (long) serialVersionUID = 1360826667806852920, ]
String [ (class [C) value = [C#4a574795, (int) hash = 0, (long) serialVersionUID = -6849794470754667710, (class [Ljava.io.ObjectStreamField;) serialPersistentFields = [Ljava.io.ObjectStreamField;#f6f4d33, (interface java.util.Comparator) CASE_INSENSITIVE_ORDER = java.lang.String$CaseInsensitiveComparator#23fc625e, ]
Container [ (class java.lang.String) name = bar, (class javax.xml.bind.JAXBElement) jaxbElement = null, ]
See? Your error has gone. Un-comment the else block in order to see it re-appear, then remove the .toString() from the line and it goes away again. Maybe it helps you understand your error better.
By the way, I think the log output looks kinda ugly. Did you also notice that you print static fields too? You should probably filter them out. But I did not want to change more of your code because I still want you to recognise it.
The short version of your aspect without the additional debug logging for JAXBElement and without try - catch but a declared exception instead would be:
package de.scrum_master.aspect;
import java.lang.reflect.Field;
import javax.xml.bind.JAXBElement;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class MyAspect {
#Pointcut("execution(* doSomething(..))")
private void soapRequest() {}
#Before("soapRequest()")
public void logBefore(JoinPoint joinPoint) throws Throwable {
System.out.println(joinPoint);
for (Object methodArg : joinPoint.getArgs()) {
StringBuilder sb = new StringBuilder();
sb.append(methodArg.getClass().getSimpleName() + " [ ");
for (Field field : methodArg.getClass().getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(methodArg);
if (value instanceof JAXBElement)
value = ((JAXBElement) value).getValue();
sb.append("(" + field.getType() + ") " + fieldName + " = " + value + ", ");
}
sb.append("]");
System.out.println(" " + sb);
}
}
}

Jena Location Mapping failed to find configuration

i am working with Jena Text Search using SPARQL. It has succeed in compile time and run time but it doesn't show the desired result which is the result should show the URI and the intended text. It looks like error messages but i get the failed description below:
DEBUG org.apache.jena.util.LocationMapper - Failed to find configuration: file:location-mapping.rdf;file:location-mapping.n3;file:location-mapping.ttl;file:etc/location-mapping.rdf;file:etc/location-mapping.n3;file:etc/location-mapping.ttl
DEBUG org.apache.jena.riot.system.stream.JenaIOEnvironment - Failed to find configuration: location-mapping.ttl;location-mapping.rdf;location-mapping.n3;etc/location-mapping.rdf;etc/location-mapping.n3;etc/location-mapping.ttl
The full codes show below:
public class JenaTextSearch {
static {LogCtl.setLog4j();
BasicConfigurator.configure();}
static Logger log = LoggerFactory.getLogger("JenaTextSearch");
public static void main (String ...argv)
{
Dataset ds = createCode();
//loadData(ds, "data.ttl");
queryData(ds);
}
public static Dataset createCode()
{
//base data
Dataset ds1 = DatasetFactory.create();
Model defaultModel = ModelFactory.createDefaultModel();
defaultModel.read("to_index/data.ttl", "N-TRIPLES");
ds1.setDefaultModel(defaultModel);
//define the index mapping
EntityDefinition entDef = new EntityDefinition ("uri", "text", ResourceFactory.createProperty(App.URI_PREFIX,"content"));
Directory dir = null;
try {
dir = new SimpleFSDirectory(Paths.get("index")); //lucene index directory
}
catch (IOException e) {
e.printStackTrace();
}
//join together into a dataset
Dataset ds = TextDatasetFactory.createLucene(ds1, dir, new TextIndexConfig(entDef));
return ds1;
}
public static void queryData(Dataset dataset)
{
String prefix = "PREFIX email: <" + App.URI_PREFIX+">" +
"PREFIX text: <http://jena.apache.org/text#>";
long startTime = System.nanoTime();
System.out.println("Email's content contains 'good'");
String query = "SELECT * WHERE " +
"{?s text:query (email:content 'good')." +
"?s email:content ?text." +
"}" ;
dataset.begin(ReadWrite.READ);
try {
Query q = QueryFactory.create(prefix+"\n"+query);
QueryExecution qexec = QueryExecutionFactory.create(q, dataset);
QueryExecUtils.executeQuery(q, qexec);
}finally { dataset.end();}
long finishTime = System.nanoTime();
double time = (finishTime-startTime)/1.0e6;
System.out.println ("Query "+String.format("FINISH - %.2fms", time));
startTime = System.nanoTime();
System.out.println("Email's content contains 'bad'");
query = "SELECT * WHERE" +
"{(?s ?score ?lit) text:query (email:content 'bad' \"highlight:s:<em class='hiLite'> | e:</em>\")." +
"?s email:content ?text." +
"}" ;
dataset.begin(ReadWrite.READ);
try {
Query q = QueryFactory.create(prefix+"\n"+query);
QueryExecution qexec = QueryExecutionFactory.create(q, dataset);
QueryExecUtils.executeQuery(q, qexec);
} finally { dataset.end() ; }
finishTime = System.nanoTime();
time = (finishTime-startTime)/1.0e6;
System.out.println("Query "+String.format("FINISH - %.2fms", time));
}}
is that a library problem or something? i use Jena 3.9 and 3.13 because it can completely each other, i think. please devise me. thank you.

Error enlarging buttons on eclipse

Hello im trying to enlarge my buttons on eclipse. I found this code on the web that suppose to fix it
but it keeps giving me the error
Error: Could not find or load main class testEclipse.FixIcons
Any idea what can i do?
Im pretty new at this .. thanks
package testEclipse;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.imgscalr.Scalr;
import com.mortennobel.imagescaling.AdvancedResizeOp;
import com.mortennobel.imagescaling.ResampleOp;
/**
* Small utility to double the size of eclipse icons for QHD monitors.
*
* #author David Levy
* #since 2014/04/10
*
*/
public class FixIcons {
private static final Logger logger = Logger.getLogger(FixIcons.class);
public static final void main(String[] args) {
try {
Options options = new Options();
options.addOption(new Option("b", "baseDir", true,
"This is the base directory where we'll parse jars/zips"));
options.addOption(new Option("o", "outputDir", true,
"This is the base directory where we'll place output"));
for (Option o : new ArrayList<Option>(options.getOptions())) {
o.setRequired(true);
}
GnuParser parser = new GnuParser();
CommandLine commandLine = parser.parse(options, args);
String baseDirArg = "D:\\things\\tools\\eclipse";
logger.info("Base directory: " + baseDirArg);
String outputDirArg = "D:\\things\\tools\\eclipsetmp";
logger.info("Output directory: " + outputDirArg);
File base = new File(baseDirArg);
if (!base.exists() || !base.canRead() || !base.isDirectory()) {
logger.error("Unable to read from base directory");
return;
}
File output = new File(outputDirArg);
if (!output.exists() || !output.canRead() || !output.canWrite()
|| !output.isDirectory()) {
logger.error("Unable to write to output director");
return;
}
if (base.list() == null || base.list().length == 0) {
logger.error("The base directory is empty");
return;
}
if (output.list() != null && output.list().length != 0) {
logger.error("The output directory is not empty");
return;
}
processDirectory(base, output);
} catch (ParseException e) {
logger.error("Unable to parse arguments: " + e.getMessage());
} catch (Exception e) {
logger.error("Unexpected error: " + e.getMessage(), e);
}
}
public static void processDirectory(File directory, File outputDirectory)
throws Exception {
logger.info("Processing directory [" + directory.getAbsolutePath()
+ "]");
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
File targetDir = new File(outputDirectory.getAbsolutePath()
+ File.separator + file.getName());
logger.info("Creating directory: "
+ targetDir.getAbsolutePath());
targetDir.mkdir();
processDirectory(file, targetDir);
} else {
File targetFile = new File(outputDirectory.getAbsolutePath()
+ File.separator + file.getName());
if (file.getName().toLowerCase().endsWith(".zip")
|| file.getName().toLowerCase().endsWith(".jar")) {
logger.info("Processing archive file: "
+ file.getAbsolutePath());
ZipFile zipSrc = new ZipFile(file);
Enumeration<? extends ZipEntry> srcEntries = zipSrc.entries();
ZipOutputStream outStream = new ZipOutputStream(
new FileOutputStream(targetFile));
while (srcEntries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) srcEntries.nextElement();
logger.info("Processing zip entry [" + entry.getName()
+ "]");
ZipEntry newEntry = new ZipEntry(entry.getName());
try {
outStream.putNextEntry(newEntry);
} catch (Exception e) {
if (!e.getMessage().startsWith("duplicate entry: ")) {
logger.error("error: ", e);
} else {
logger.info(e.getMessage(), e);
}
outStream.closeEntry();
continue;
}
BufferedInputStream bis = new BufferedInputStream(
zipSrc.getInputStream(entry));
if (ImageType.findType(entry.getName()) != null) {
processImage(zipSrc.getName() + "!/" + entry.getName(), bis, outStream);
} else {
IOUtils.copy(bis, outStream);
}
outStream.closeEntry();
bis.close();
}
zipSrc.close();
outStream.close();
} else if (ImageType.findType(file.getName()) != null) {
logger.info("Processing image: " + file.getAbsolutePath());
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(file);
outStream = new FileOutputStream(targetFile);
processImage(file.getName(), inStream, outStream);
} finally {
IOUtils.closeQuietly(inStream);
IOUtils.closeQuietly(outStream);
}
} else {
logger.info("Processing : " + file.getAbsolutePath());
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(file);
outStream = new FileOutputStream(targetFile);
IOUtils.copy(inStream, outStream);
} finally {
IOUtils.closeQuietly(inStream);
IOUtils.closeQuietly(outStream);
}
}
}
}
}
public static void processImage(String fileName, InputStream input,
OutputStream output) throws IOException {
logger.info("Scaling image: " + fileName);
boolean imageWriteStarted = false;
try {
BufferedImage out = ImageIO.read(input);
int outWidth = out.getWidth() * 2;
int outHeight = out.getHeight() * 2;
BufferedImage rescaledOut = createResizedCopy(out, outWidth, outHeight);
ImageIO.write(rescaledOut, ImageType.findType(fileName).name(),
output);
} catch (Exception e) {
if (imageWriteStarted) {
throw new RuntimeException("Failed to scale image [" + fileName
+ "]: " + e.getMessage(), e);
} else {
logger.error(
"Unable to scale [" + fileName + "]: " + e.getMessage(),
e);
IOUtils.copy(input, output);
}
}
}
private static BufferedImage createResizedCopy(BufferedImage originalImage, int scaledWidth, int scaledHeight) {
try {
// Resample failed - maybe the image was too small, try another way (Scalr)
BufferedImage scaledBI = Scalr.resize(originalImage, Scalr.Method.ULTRA_QUALITY, scaledWidth, scaledHeight);
return scaledBI;
} catch (RuntimeException e) {
return scale(originalImage, 2.0);
}
}
private static BufferedImage scale(BufferedImage source,double ratio) {
int w = (int) (source.getWidth() * ratio);
int h = (int) (source.getHeight() * ratio);
BufferedImage bi = getCompatibleImage(w, h);
Graphics2D g2d = bi.createGraphics();
double xScale = (double) w / source.getWidth();
double yScale = (double) h / source.getHeight();
AffineTransform at = AffineTransform.getScaleInstance(xScale,yScale);
g2d.drawRenderedImage(source, at);
g2d.dispose();
return bi;
}
private static BufferedImage getCompatibleImage(int w, int h) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
return image;
}
}

Jersey REST consumer over https

I was using this Jersey annotated Rest consumer POJO without any issue over http, but then we had to start deploying our app over HTTPS.
I am getting a big fat 404, and I concluded, that everything else worked in the code (which is running over MULE beautifully btw) and my POJO simply doesn't consume HTTPS requests.
I suspect that
I am out of luck and Jersey doesn't speak https and I have to redo something here or revert back the part to http
There is a pretty little annotation that i add and voiala! all good.
Obviously, hoping for 2. here.
Here is the code:
package org.acme.api;
import java.net.UnknownHostException;
import java.util.List;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBList;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import com.mongodb.util.JSON;
import com.mongodb.DB;
/**
REST Web service implementation.
#author menashe#acme.org
*/
#Path("/")
public class Product {
MongoClient client = null;
DB db = null;
DBCollection products = null;
public Product() throws UnknownHostException {
this.client = new MongoClient(new ServerAddress("localhost", 27027));
this.db = this.client.getDB("dailysale");
this.products = this.db.getCollection("products");
}
#GET
#Produces("application/json")
#Path("/product/{productId}")
public String retrieveProduct(#PathParam("productId") Integer productId) {
String product;
try{
DBObject query = new BasicDBObject("productId", String.valueOf(productId));
product = this.products.findOne(query).toString();
} catch(Exception e) {
product = "{ error: 'We were not able to find product with Id: '" + productId + ". " + e.getLocalizedMessage() + " }";
}
return product;
}
#GET
#Produces("application/json")
#Path("/product/grid/{query}")
#HeaderParam("range")
public Response listProducts(#HeaderParam("range") String range, #PathParam("query") String query) {
Integer pageNum = 1;
Integer pageSize = 10;
Integer resultCount = null;
BasicDBList result = new BasicDBList();
Integer firstItem = (pageNum - 1 ) * pageSize;
Long allProductsCount = null;
Integer lastItem = null;
DBObject searchQuery = new BasicDBObject("$regex", query);
try {
DBCursor productListCursor = products.find(searchQuery).skip(firstItem).limit( pageSize );
List<DBObject> productList = productListCursor.toArray();
for(DBObject product : productList) {
result.add(this.itemToGridConverter(product));
}
resultCount = productList.size();
allProductsCount = products.count();
lastItem = firstItem + resultCount - 1;
} catch(Exception e) {
result = new BasicDBList();
result.add(new BasicDBObject("error", "We were not able to retrieve all products with pageSize: " + pageSize + " and pageNumber " + pageNum + ". " + e.getLocalizedMessage() ));
}
return Response.ok(result).header("Content-Range", "items " + firstItem + "-" + lastItem + "/" + allProductsCount).build();
}
#GET
#Produces("application/json")
#Path("/product/grid/")
#HeaderParam("range")
public Response listProducts(#HeaderParam("range") String range) {
Integer pageNum = 1;
Integer pageSize = 10;
Integer resultCount = null;
BasicDBList result = new BasicDBList();
Integer firstItem = (pageNum - 1 ) * pageSize;
Long allProductsCount = null;
Integer lastItem = null;
try {
DBCursor productListCursor = products.find().skip(firstItem).limit( pageSize ).sort( new BasicDBObject( "sku", 1)) ;
List<DBObject> productList = productListCursor.toArray();
for(DBObject product : productList) {
result.add(this.itemToGridConverter(product));
}
resultCount = productList.size();
allProductsCount = products.count();
lastItem = firstItem + resultCount - 1;
} catch(Exception e) {
result = new BasicDBList();
result.add(new BasicDBObject("error", "We were not able to retrieve all products with pageSize: " + pageSize + " and pageNumber " + pageNum + ". " + e.getLocalizedMessage() ));
}
return Response.ok( result ).header("Content-Range", "items " + firstItem + "-" + lastItem + "/" + allProductsCount).build();
}
#GET
#Produces("application/json")
#Path("/product/grid/?{sort}")
#HeaderParam("range")
public Response listProductsWithSort(#HeaderParam("range") String range, #PathParam("sort") String sorting) {
Response response = null;
return response;
}
#PUT
#Produces("application/json")
#Path("/product")
public String createProduct(String productJson) {
DBObject product = null;
String result;
try{
product = (DBObject)JSON.parse(productJson);
WriteResult wResult =this.products.insert(product);
result = wResult.toString();
}
catch(Exception e){
result = "{ error: 'We were not able to insert the product.' " + e.getLocalizedMessage() + " }";
}
return result;
}
#POST
#Produces("application/json")
#Path("/product/{productId}")
public String updateProduct(#PathParam("productId") Integer productId, String productJson) {
DBObject product = null;
DBObject query = new BasicDBObject();
String result = null;
try{
product = (DBObject)JSON.parse(productJson);
query.put("productId", productId.toString());
WriteResult wResult = this.products.update(query, product);
result = wResult.toString();
}
catch(Exception e){
result = "{ error: 'We were not able to update the product.' " + e.getLocalizedMessage() + " }";
}
return result;
}
#DELETE
#Produces("application/json")
#Path("/product/{productId}")
public String deleteProduct(#PathParam("productId") Integer productId) {
return "{ error: 'This function is not implemented [delete].' }";
}
private DBObject itemToGridConverter(DBObject product) {
DBObject item = new BasicDBObject();
BasicDBList images = (BasicDBList)product.get("images");
BasicDBObject firstImage = (BasicDBObject)images.get(0);
item.put("productId", product.get("productId"));
item.put("sku", product.get("sku"));
item.put("image", firstImage.get("imageurl"));
BasicDBList spec = (BasicDBList)product.get("productSpecifics");
BasicDBObject firstSpec = (BasicDBObject)spec.get(0);
BasicDBObject attributes = (BasicDBObject)product.get("productAttributes");
item.put("name", firstSpec.get("title"));
item.put("cost", "no source");
item.put("list_price", attributes.get("defaultsalePrice"));
item.put("qty_available", product.get("qtyonHand"));
item.put("condition", "no source");
item.put("active", "true".equals(product.get("active")) ? "Yes" : "No");
item.put("manufacturer", attributes.get("manufacturer"));
item.put("part_number", attributes.get("manufacturerPartNumber"));
item.put("date_created", product.get("_id"));
return item;
}
}
Thanks much.
UPDATE:
I fixed the issue by fixing the path. The issue was how MULE resolves scope boundaries and here the original #Path / was actually in the previous scope. Now that we changed the flow the #Path became /controllers/.
Uyodiin Mevin.