Xstream with CDATA in server got IOException, but works in Eclipse - utf-8

I've searched and got the solution for adding CDATA tag for Axstream, and it worked well in Eclipse in my machine. However, after I deployed my code to tomcat server, it always failed with IOException at toXML(t, writer) or toXML(t), I've also tried to make the writer to "UTF-8", but still no luck.
My code for handle CDATA is:
XStream xstream = new XStream( new XppDriver(){
#Override
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out){
boolean cdata = false;
#Override
public void startNode(String name) {
super.startNode(name);
cdata = name.equalsIgnoreCase("imagestream");
}
#Override
protected void writeText(QuickWriter writer, String text) {
if(cdata && !text.isEmpty()){
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
}else {
writer.write(text);
}
}
};
}
});
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8")));
xstream.toXML(t,writer);
xml = outputStream.toString("UTF-8");

Related

Spring batch read file one by one. File content is not constant

MultiResourceItemReader reads all files sequentially.
I want once one file read completely, it should call processor/writer.it should not read next file.
Since file content is not constant, i can't go with chunk size.
Any idea on chunk policy to decide end of file content?
I think you should write a step which read/process/write only one file with a "single file item reader" (like FlatFileItemReader). And repeat the step while there are files remainig.
Spring batch gives you a feature to do so : conditional flows and in particular the programmatic flow decision which gives you a smart way to decide when to stop a loop between steps (when there is not file any more)
And since you will not be able to give a constant input file name to your reader, you should also have a look at Late binding section.
Hope this will be enough to help you. Please, make comments if you need more details.
Using MultiResourceItemReader, assigning multiple file reasources.
Using custom file reader as delegate, reading a file completely
For reading file completely, come up with a logic
#Bean
public MultiResourceItemReader<SimpleFileBean> simpleReader()
{
Resource[] resourceList = getFileResources();
if(resourceList == null) {
System.out.println("No input files available");
}
MultiResourceItemReader<SimpleFileBean> resourceItemReader = new MultiResourceItemReader<SimpleFileBean>();
resourceItemReader.setResources(resourceList);
resourceItemReader.setDelegate(simpleFileReader());
return resourceItemReader;
}
#Bean
SimpleInboundReader simpleFileReader() {
return new SimpleInboundReader(customSimpleFileReader());
}
#Bean
public FlatFileItemReader customSimpleFileReader() {
return new FlatFileItemReaderBuilder()
.name("customFileItemReader")
.lineMapper(new PassThroughLineMapper())
.build();
}
public class SimpleInboundReader implements ResourceAwareItemReaderItemStream{
private Object currentItem = null;
private FileModel fileModel = null;
private String fileName = null;
private boolean fileRead = false;
private ResourceAwareItemReaderItemStream<String> delegate;
public SimpleInboundReader(ResourceAwareItemReaderItemStream<String> delegate) {
this.delegate = delegate;
}
#Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
delegate.open(executionContext);
}
#Override
public void update(ExecutionContext executionContext) throws ItemStreamException {
delegate.update(executionContext);
}
#Override
public void close() throws ItemStreamException {
delegate.close();
}
#Override
public void setResource(Resource resource) {
fileName = resource.getFilename();
this.delegate.setResource(resource);
}
String getNextLine() throws UnexpectedInputException, ParseException, NonTransientResourceException, Exception {
return delegate.read();
}
#Override
public SimpleFileBean read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
SimpleFileBean simpleFileBean = null;
String currentLine = null;
currentLine=delegate.read();
if(currentLine != null) {
simpleFileBean = new SimpleFileBean();
simpleFileBean.getLines().add(currentLine);
while ((currentLine = getNextLine()) != null) {
simpleFileBean.getLines().add(currentLine);
}
return simpleFileBean;
}
return null;
}
}

How to return an Image to browser in rest API in JAVA?

I want to an image while I hit an API like localhost:8080:/getImage/app/path={imagePath}
While I hit this API it will return me an Image.
Is this possible?
Actually, I have tried this but it is giving me an ERROR.
Here is my code,
#GET
#Path("/app")
public BufferedImage getFullImage(#Context UriInfo info) throws MalformedURLException, IOException {
String objectKey = info.getQueryParameters().getFirst("path");
return resizeImage(300, 300, objectKey);
}
public static BufferedImage resizeImage(int width, int height, String imagePath)
throws MalformedURLException, IOException {
BufferedImage bufferedImage = ImageIO.read(new URL(imagePath));
final Graphics2D graphics2D = bufferedImage.createGraphics();
graphics2D.setComposite(AlphaComposite.Src);
// below three lines are for RenderingHints for better image quality at cost of
// higher processing time
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.drawImage(bufferedImage, 0, 0, width, height, null);
graphics2D.dispose();
System.out.println(bufferedImage.getWidth());
return bufferedImage;
}
My ERROR,
java.io.IOException: The image-based media type image/webp is not supported for writing
Is there any way to return an Image while hitting any URL in java?
You can use IOUtils. Here is code sample.
#RequestMapping(path = "/getImage/app/path/{filePath}", method = RequestMethod.GET)
public void getImage(HttpServletResponse response, #PathVariable String filePath) throws IOException {
File file = new File(filePath);
if(file.exists()) {
String contentType = "application/octet-stream";
response.setContentType(contentType);
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(file);
// copy from in to out
IOUtils.copy(in, out);
out.close();
in.close();
}else {
throw new FileNotFoundException();
}
}
i didn't test it due to i don't have the environment in this machine, but logically it should work like the following, read it as input stream and let your method returns #ResponseBody byte[]
#GET
#Path("/app")
public #ResponseBody byte[] getFullImage(#Context UriInfo info) throws MalformedURLException, IOException {
String objectKey = info.getQueryParameters().getFirst("path");
BufferedImage image = resizeImage(300, 300, objectKey);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
return IOUtils.toByteArray(is);
}
UPDATE
depending on #Habooltak Ana suggestion there is no need to create an input stream, the code should be look like the following
#GET
#Path("/app")
public #ResponseBody byte[] getFullImage(#Context UriInfo info) throws
MalformedURLException, IOException {
String objectKey = info.getQueryParameters().getFirst("path");
BufferedImage image = resizeImage(300, 300, objectKey);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", os);
return os.toByteArray();
}
Just return a file object with correct HTTP-Headers (Content-Type and Content-Disposition) will work in most cases/environments.
Pseudocode
File result = createSomeJPEG();
/*
e.g.
RenderedImage rendImage = bufferedImage;
File file = new File("filename.jpg");
ImageIO.write(rendImage, "jpg", file);
*/
response().setHeader("Content-Disposition", "attachment;filename=filename.jpg;");
response().setHeader("Content-Type", "image/jpeg");
return ok(result);
See also:
file downloading in restful web services
what's the correct way to send a file from REST web service to client?

How to access CSV data set config in my Java Request Sampler

I have to read data from a csv file which contains 10000+ records.
I want to use this data in JMeter to hit a web service.
I had written my code with the hard coded value. But I want to make it dynamic.
How can I access CSV data set config in my custom Java Request Sampler...?
How can I access the variable i declared in the CSV data set config in my java request sampler..?
Here is my full code :
#Override
public SampleResult runTest(JavaSamplerContext arg0)
{
SampleResult result = new SampleResult();
boolean success = true;
byte arr[] = new byte[] {1,49,45,1,2,(byte)214,1,1,98,0,6,0,0,9,24,0,0,0,0,0,0,0,0,0,0,0,0,0,127,(byte)255,0,21,0,16,0,75,1,0,0,58,32,2,7,0,0,4,4,0,85,81,98,0,5,14,(byte)158,0,2,0,0,0,0,0,88,82,50,69,49,83,49,86,48,67,48,0,0,1,97,75,0,84,30,12,7,17,5,7,50,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,4,6,0,0,48,49,48,48,49,48,51,48,0,0,0,0,0,0,0,0,0,0,70,48,10,29,22,85,0,1,(byte)134,(byte)160,(byte)255,(byte)255,(byte)158,(byte)170,0,0,0,67,0,0,0,0,2,0,0,12,0,12,0,12,0,12,0,13,0,12,0,13,0,12,0,13,0,12,0,13,0,13,0,12,0,12,0,12,0,12,0,13,0,12,0,13,0,13,0,12,0,13,0,13,0,12,0,13,0,13,0,12,0,13,0,13,0,13,0,12,0,13,0,13,0,13,0,14,0,13,0,12,0,13,0,13,0,13,0,13,0,12,0,13,0,13,0,13,0,14,0,13,0,13,0,13,0,12,0,13,0,13,2,(byte)158,2,(byte)159,2,(byte)241,2,(byte)234,5,48,5,68,8,90,7,(byte)193,6,15,4,10,3,100,4,(byte)224,7,47,6,72,4,(byte)170,4,4,4,7,5,16,6,107,6,114,5,(byte)195,4,(byte)179,2,(byte)198,0,13,0,13,0,13,0,14,0,13,0,13,0,14,0,13,0,14,0,13,0,13,0,14,0,13,0,13,0,14,0,13,0,14,0,13,0,14,0,13,0,14,0,13,0,13,0,101,0,99,0,(byte)129,0,(byte)129,2,81,2,(byte)224,1,(byte)153,0,(byte)30,0,31,0,14,0,13,0,14,0,13,0,14,0,14,0,13,0,14,0,13,0,14,0,14,0,21,0,86,0,98,0,51,0,72,0,104,0,(byte)144,0,(byte)175,0,(byte)174,0,(byte)174,2,20,4,(byte)132,4,103,5,96,0,126,0,14,0,14,0,14,0,14,0,14,0,15,0,14,0,14,0,14,0,14,0,14,0,85,1,41,1,104,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,13,0,14,0,13,0,14,0,13,0,14,0,13,0,14,0,14,0,13,0,14,0,13,0,13,0,13,0,13,0,13,0,12,0,13,0,13,0,14,0,13,0,13,0,13,0,13,0,13,0,13,0,13,0,14,0,13,0,13,0,14,0,13,0,13,0,14,0,13,0,13,0,13,0,13,0,13,0,(byte)226,0,(byte)223,0,(byte)223,0,15,0,14,0,13,0,115,0,(byte) 223,(byte)162,40,38,85,115,101,114,78,97,109,101,61,101,82,101,103,38,85,115,101,114,80,97,115,115,119,111,114,100,61,97,98,99,49,50,51};
try
{
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
result.sampleStart();
OutputStream os = con.getOutputStream();
os.write(arr);
os.flush();
os.close();
result.sampleEnd();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK)
{ //success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString().getBytes());
}
else
{
System.out.println("POST request not worked");
}
}
catch(Exception E)
{
}
//
result.setSuccessful(success);
return result;
}
#Override
public Arguments getDefaultParameters()
{
Arguments dp=new Arguments();
return dp;
}
#Override
public void setupTest(JavaSamplerContext context) {}
#Override
public void teardownTest(JavaSamplerContext context) {
}
Normally you should be able to access JMeter Variables like:
String myVar = JMeterContextService.getContext().getVariables().get("your_variable_name_here");
However if you don't want to have it hard-coded you might consider moving the configuration to Java Request Sampler GUI like:
String valueFromCsv = "";
String defaultValue = "insert_jmeter_variable_here";
#Override
public Arguments getDefaultParameters() {
Arguments dp = new Arguments();
dp.addArgument("hexData", "insert_jmeter_variable_here");
return dp;
}
#Override
public void setupTest(JavaSamplerContext context) {
valueFromCsv = context.getParameter("hexData", defaultValue );
}
This way you will be able to control the parameter value directly from JMeter GUI.
References:
JMeterContextService JavaDoc
Java Request Sampler documentation
Extending JMeter
Beanshell vs JSR223 vs Java JMeter Scripting: The Performance-Off You've Been Waiting For!
A full java sampler solution with CSV data:
courtesy - https://dzone.com/articles/implement-custom-jmeter-samplers
Created a class
public class VDCSampler extends AbstractJavaSamplerClient implements Serializable {
private static final String ARG1_IDATE = "idate";
private String attrib1;
#Override
public Arguments getDefaultParameters() {
Arguments defaultParameters = new Arguments();
defaultParameters.addArgument(ARG1_IDATE, attrib1);
return defaultParameters;
}
#Override
public void setupTest(JavaSamplerContext javaSamplerContext) {
attrib1 = javaSamplerContext.getParameter(ARG1_IDATE, attrib1);
}
#Override
public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
VDCFunctionalitySampling functionalityForSampling = new VDCFunctionalitySampling();
SampleResult sampleResult = new SampleResult();
sampleResult.sampleStart();
try {
String message = functionalityForSampling.testFunction(attrib1);
}
}

Spring Email Using Velocity Template Engine

I'm new using Spring framework and also Velocity, because that I wanna apologize if I'm missing something basic.
When I try to do something like this:
#Override
public void envia(final Usuario usuario) {
// TODO Auto-generated method stub
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setTo(usuario.getEmail());
message.setFrom("pirado2#gmail.com"); // could be parameterized...
Map model = new HashMap();
model.put("user", usuario);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
"/templates/registration-confirmation.vm",
"UTF-8",
model);
message.setText(text, true);
}
};
this.mailSender.send(preparator);
}
I get this error:
ERROR [VelocityEngine ] ResourceManager : unable to find resource '/templates/registration-confirmation.vm' in any resource loader.
How can I find my vm file though ?
thanks.

Distributed cache not working

I am storing a small amount of data (few MBs) in a distributed cache and using that to perform anti join with two big files. For few lines of data in cache , the functionality is working fine, but when the cache is having more data in production it's not able to do the job but its not throwing any error as well. Just that only few records (around 20%) are getting joined and others are just getting ignored. So is there any upper limit of number of records that can be stored in the distributed cache? Why its working for some of the records and ignoring the rest? Any suggestion will be extremely helpful.
Bellow is my code
public class MyMapper extends Mapper<LongWritable, Text, Text, TextPair> {
Text albumKey = new Text();
Text photoKey = new Text();
private HashSet<String> photoDeleted = new HashSet<String>();
private HashSet<String> albDeleted = new HashSet<String>();
Text interKey = new Text();
private TextPair interValue = new TextPair();
private static final Logger LOGGER = Logger.getLogger(SharedStreamsSlMapper.class);
protected void setup(Context context) throws IOException, InterruptedException {
int count=0;
Path[] cacheFiles = DistributedCache.getLocalCacheFiles(context.getConfiguration());
System.out.println(cacheFiles.length);
LOGGER.info(cacheFiles+"****");
try {
if (cacheFiles != null && cacheFiles.length > 0) {
for (Path path : cacheFiles) {
String line;
String[] tokens;
BufferedReader joinReader = new BufferedReader(new FileReader(path.toString()));
System.out.println(path.toString());
// BufferedReader joinReader = new BufferedReader(new FileReader("/Users/Kunal_Basak/Desktop/ss_test/dsitCache/part-m-00000"));
try {
while ((line = joinReader.readLine()) != null) {
count++;
tokens = line.split(SSConstants.TAB, 2);
if(tokens.length<2){
System.out.println("WL");
continue;
}
if (tokens[0].equals("P")) {
photoDeleted.add(tokens[1]);
}
else if (tokens[0].equals("A")) {
albDeleted.add(tokens[1]);
}
}
}
finally {
joinReader.close();
}
}
}
}
catch (IOException e) {
System.out.println("Exception reading DistributedCache: " + e);
}
System.out.println(count);
System.out.println("albdeleted *****"+albDeleted.size());
System.out.println("photo deleted *****"+photoDeleted.size());
LOGGER.info("albdeleted *****"+albDeleted.size());
LOGGER.info("albdeleted *****"+albDeleted.size());
}
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
try{
//my mapper code
}
}
}
According to this blog article:
The local.cache.size parameter controls the size of the
DistributedCache.
By default, it’s set to 10 GB.
So if you have more than 10GB in the cache, that may be your problem.

Resources