Sending Input Value to java Class - java

This is my class.
package com.example.ali.pdftoepub;
import android.util.Log;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import com.itextpdf.text.pdf.parser.Vector;
public class SemTextExtractionStrategy implements TextExtractionStrategy {
private String text;
#Override
public void beginTextBlock() {
}
#Override
public void renderText(TextRenderInfo renderInfo) {
text = renderInfo.getFont().getPostscriptFontName();
}
#Override
public void endTextBlock() {
}
#Override
public void renderImage(ImageRenderInfo renderInfo) {
}
#Override
public String getResultantText() {
return text;
}
}
This is my using way of my class.
String text = PdfTextExtractor.getTextFromPage(reader, 1, semTextExtractionStrategy)
Can i send an integer parameter to this class?

You can add an attribute to your class and set it before passing the semTextExtractionStrategy object to the PdfTextExtractor.getTextFromPage.
Something like:
public class SemTextExtractionStrategy implements TextExtractionStrategy
{
private String text;
private int myInt;
public void setMyInt(int i){
this.myInt = i;
}
......
The you can use myInt in the inner methods.
semTextExtractionStrategy.setMyInt(5);
String text = PdfTextExtractor.getTextFromPage(reader, 1, semTextExtractionStrategy)

Related

Limit instance construction to an external factory

The pattern I'm aiming for is to put all the classes that I want clients to use - like model objects, interfaces and factories - in a "client" package and put the private implementation in an impl package that is inaccessible to clients.
I only want clients to access my API using interfaces and I want to prevent them from instantiating private implementation classes directly.
What follows is a simple example. It works but am wondering if there's a better way - I'd imagine that this is a commonly used pattern?
package client;
public interface Plant {
String getScientificName();
String getCommonName();
}
package client;
import impl.PlantImpl;
import java.util.function.BiFunction;
public final class PlantFactory {
private BiFunction<String, String, Plant> delegate;
public PlantFactory() {
PlantImpl.registerFactory(this);
}
public void setFactory(BiFunction<String, String, Plant> factory) {
delegate = factory;
}
public Plant newInstance(String scientificName, String commonName) {
return delegate.apply(scientificName, commonName);
}
}
package impl;
import client.Plant;
import client.PlantFactory;
import java.util.function.BiFunction;
public final class PlantImpl implements Plant {
private final String scientificName;
private final String commonName;
private PlantImpl(String scientificName, String commonName) {
this.scientificName = scientificName;
this.commonName = commonName;
}
#Override
public String getScientificName() {
return scientificName;
}
#Override
public String getCommonName() {
return commonName;
}
public static void registerFactory(PlantFactory plantFactory) {
plantFactory.setFactory(new Factory());
}
static class Factory implements BiFunction<String, String, Plant> {
#Override
public Plant apply(String scientificName, String commonName) {
return new PlantImpl(scientificName, commonName);
}
}
}
import client.Plant;
import client.PlantFactory;
public final class PlantViewer {
public static void main(String[] args) {
// Doesn't compile due to private constructor
// Plant wattle = new PlantImpl("Acacia longifolia", "Sydney Golden Wattle");
PlantFactory plantFactory = new PlantFactory();
Plant grevillea = plantFactory.newInstance("Grevillea caleyi", "Caley's Grevillea");
System.out.println("Plant name is " + grevillea.getCommonName());
}
}

how to implement public AbstractEntryProcessor(boolean applyOnBackup){} in 5.x.x for the backup in Hazelcast

Help me in the following code and how to used the backup on the Hazelcast
migration of the hazelcast 3.x.x to 5.x.x
package com.hazelcast.map;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.HazelcastInstanceAware;
import com.hazelcast.nio.serialization.impl.BinaryInterface;
import java.util.Map;
// Interface AbstractEntryProcessor
#BinaryInterface
public abstract class AbstractEntryProcessor<K,V> implements EntryProcessor<K,V> {
private final EntryBackupProcessor<K,V> entryBackupProcessor;
// Non Parameterize Constructor
public AbstractEntryProcessor() {
this(true);
}
// Parameterize Constructor AbstractEntryProcessor
public AbstractEntryProcessor(boolean applyOnBackup) {
if (applyOnBackup) {
entryBackupProcessor = new EntryBackupProcessorImpl();
} else {
entryBackupProcessor = null;
}
}
//EntryBackupProcessor
#Override
public final EntryBackupProcessor getBackupProcessor() {
return entryBackupProcessor;
}
// class EntryBackupProcessorImpl
private class EntryBackupProcessorImpl implements EntryBackupProcessor<k,V>, HazelcastInstanceAware {
// generated for EntryBackupProcessorImpl which doesn't implement HazelcastInstanceAware
static final long serialVersionUID = -5081502753526394129L;
#Override
public void processBackup(Map.Entry<K,V> entry) {
process(entry);
}
#Override
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
final AbstractEntryProcessor<k,V> outer = AbstractEntryProcessor.this;
if (outer instanceof HazelcastInstanceAware) {
((HazelcastInstanceAware) outer).setHazelcastInstance(hazelcastInstance);
}
}
}
}
How to used the backup methods in 5.x.x versons of series
how to used the backup in the above question ?
This should work:
public abstract class AbstractEntryProcessor implements EntryProcessor, HazelcastInstanceAware {
protected transient HazelcastInstance hazelcastInstance;
private final boolean applyOnBackup;
// Non Parameterize Constructor
public AbstractEntryProcessor() {
this(true);
}
// Parameterize Constructor AbstractEntryProcessor
public AbstractEntryProcessor(boolean applyOnBackup) {
this.applyOnBackup = applyOnBackup;
}
//EntryBackupProcessor
#Override
public final EntryProcessor getBackupProcessor() {
if (!applyOnBackup || this instanceof ReadOnly) {
return null;
}
return this;
}
#Override
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
this.hazelcastInstance = hazelcastInstance;
}
}

Retrofit Get Data Object

I have a data like this, and i want get report and criteria data.
{
"response_code": 200,
"message": "Your report data has been loaded.",
"data": {
"report": [
{
"id_report": 1,
"report_name": "report name A"
},
{
"id_report": 2,
"report_name": "report name B"
}
],
"criteria": [
{
"id_criteria": 1,
"criteria_name": "criteria name A"
},
{
"id_criteria": 2,
"criteria_name": "criteria name B"
}
]
}
}
And i get data in java using retrofit. And this is my java class.
GetReport.java
#SerializedName("response_code")
private int response_code;
#SerializedName("status")
private boolean status;
#SerializedName("message")
private String message;
#SerializedName("data")
Call<Data> listData;
Data.java
#SerializedName("report")
private List<Report> reportList;
#SerializedName("criteria")
private List<Criteria> criteriaList;
And this how i call the data.
public void populateData() {
Call<GetReport> getReportCall = apiInterface.getReportCall();
getReportCall.enqueue(new Callback<GetReport>() {
#Override
public void onResponse(Call<GetReport> call, Response<GetReport> response) {
response.body().getListData().enqueue(new Callback<Data>() {
#Override
public void onResponse(Call<Data> call, Response<Data> response) {
List<Report> reportList = response.body().getReportList();
Log.d("TAGGGGGGGGGG", String.valueOf(reportList.size()));
}
#Override
public void onFailure(Call<Data> call, Throwable t) {
t.printStackTrace();
}
});
}
#Override
public void onFailure(Call<GetReport> call, Throwable t) {
t.printStackTrace();
}
});
}
When I run the program, my activity closes immediately. When I look at logcat, there is too much running log data so I can't see where the error is.
I have managed to attempt and solve your problem with the following code. I copied and pasted the JSON you provided above at JSONbin.io so that I can be able to call it using an API call. I did not modify the structure of the JSON at all.
App build.gradle
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
GetReport.java
package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
public class GetReport {
#SerializedName("response_code")
int response_code;
#SerializedName("message")
String message;
#SerializedName("data")
Data data;
public int getResponse_code() {
return response_code;
}
public void setResponse_code(int response_code) {
this.response_code = response_code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}}
Data.java
package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Data {
#SerializedName("report")
List<Report> reportList;
#SerializedName("criteria")
List<Criteria> criteriaList;
public List<Report> getReportList() {
return reportList;
}
public void setReportList(List<Report> reportList) {
this.reportList = reportList;
}
public List<Criteria> getCriteriaList() {
return criteriaList;
}
public void setCriteriaList(List<Criteria> criteriaList) {
this.criteriaList = criteriaList;
}}
Criteria.java
package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
public class Criteria {
#SerializedName("id_criteria")
int id_criteria;
#SerializedName("criteria_name")
String criteria_name;
public Criteria(int id_criteria, String criteria_name) {
this.id_criteria = id_criteria;
this.criteria_name = criteria_name;
}
public int getId_criteria() {
return id_criteria;
}
public void setId_criteria(int id_criteria) {
this.id_criteria = id_criteria;
}
public String getCriteria_name() {
return criteria_name;
}
public void setCriteria_name(String criteria_name) {
this.criteria_name = criteria_name;
}}
Report.java
package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
public class Report {
#SerializedName("id_report")
int id_report;
#SerializedName("report_name")
String report_name;
public Report(int id_report, String report_name) {
this.id_report = id_report;
this.report_name = report_name;
}
public int getId_report() {
return id_report;
}
public void setId_report(int id_report) {
this.id_report = id_report;
}
public String getReport_name() {
return report_name;
}
public void setReport_name(String report_name) {
this.report_name = report_name;
}}
RetrofitClient.java
package com.example.retrofitapp.api;
import com.google.gson.*;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
public static Retrofit retrofit;
public static Retrofit getRetrofitClient(String baseUrl){
if(retrofit==null){
Gson gson = new GsonBuilder().setLenient().create();
retrofit = new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create(gson)).build();
}
return retrofit;
}}
Constants.java
package com.example.retrofitapp;
public class Constants {
public static String base_url = "https://api.jsonbin.io/";
}
Api.java
package com.example.retrofitapp.api;
import com.example.retrofitapp.GetReport;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Headers;
public interface Api {
#Headers("Secret-key:$2a$10$WxkkTylkdR7NwGSoPwrfy.Odxtj7MR2vDtYZBp9cOd0SaYGVRmhOm")
#GET("/b/5ff8172e63e86571a2e35639")
Call<GetReport> getReport();
}
MainActivity.java
package com.example.retrofitapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.retrofitapp.api.Api;
import com.example.retrofitapp.api.RetrofitClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//call method here
populateData();
}
private void populateData() {
Retrofit retrofit = RetrofitClient.getRetrofitClient(Constants.base_url);
Api api = retrofit.create(Api.class);
Call<GetReport> getReportCall = api.getReport();
//make asynchronous request
getReportCall.enqueue(new Callback<GetReport>() {
#Override
public void onResponse(Call<GetReport> call, Response<GetReport> response) {
if(response.code() == 200){
GetReport getReport = (GetReport) response.body();
//get response code
int responseCode = getReport.getResponse_code();
//get message
String message = getReport.getMessage();
//get data
Data data = getReport.getData();
//get reports(loop)
for(Report report : data.getReportList()){
//your report here
}
//get criteria(loop)
for(Criteria criteria : data.getCriteriaList()){
//your criteria here
}
}
}
#Override
public void onFailure(Call<GetReport> call, Throwable t) {
//do something if the request failed
}
});
}}
That is how I solved it.

XStream implicit configouration

I am working with XML like:
<localMSZ>
<territories>
<codeOKTMO>str1</codeOKTMO>
<codeOKTMO>str2</codeOKTMO>
</territories>
</localMSZ>
In Java code I have class LocalMSZ which have List of String like:
class LocalMSZ {
List<String> territories;
}
I doesn't understand how I should post annotation in this case?
The problem is in your mapping class: it lacks the structure and annotations needed for this. It should work with this:
import java.util.LinkedList;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;
#XStreamAlias("localMSZ")
public class LocalMSZ {
private Territories territories = new Territories();
public Territories getTerritories() {
return territories;
}
public void setTerritories(Territories territories) {
this.territories = territories;
}
#XStreamAlias("codeOKTMO")
#XStreamConverter(value = ToAttributedValueConverter.class, strings = { "value" })
public static class Code {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
#XStreamAlias("territories")
public static class Territories {
// This one maps the sequence of <codeOKTMO> tags
#XStreamImplicit
private List<Code> codes = new LinkedList<Code>();
public List<Code> getCodes() {
return codes;
}
public void setCodes(List<Code> codes) {
this.codes = codes;
}
}
}
Remember also when you write your main method to process the annotations of LocalMSZ
XStream xstream = new XStream();
xstream.processAnnotations(LocalMSZ.class);
...

Populating Action class instance variables from URL in Struts2

Facing an issue with passing values from my html form to action class. Created a sample project to test the functionality and have the same issue here. I have the following classes:
TestBean
package com.struts2test.beans;
public class TestBean {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
TestBeanHolder
package com.struts2test.beans;
import java.util.List;
import java.util.Map;
public class TestBeanHolder {
private Map<Integer, TestBean> testBeanMap;
private List<TestBean> testBeanList;
private Map<Integer, List<TestBean>> testBeanListMap;
public Map<Integer, TestBean> getTestBeanMap() {
return testBeanMap;
}
public void setTestBeanMap(Map<Integer, TestBean> testBeanMap) {
this.testBeanMap = testBeanMap;
}
public Map<Integer, List<TestBean>> getTestBeanListMap() {
return testBeanListMap;
}
public void setTestBeanListMap(Map<Integer, List<TestBean>> testBeanListMap) {
this.testBeanListMap = testBeanListMap;
}
public List<TestBean> getTestBeanList() {
return testBeanList;
}
public void setTestBeanList(List<TestBean> testBeanList) {
this.testBeanList = testBeanList;
}
}
TestAction
package com.struts2test.action;
import com.opensymphony.xwork2.ActionSupport;
import com.struts2test.beans.TestBeanHolder;
public class TestAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private TestBeanHolder testBeanHolder;
public TestBeanHolder getTestBeanHolder() {
return testBeanHolder;
}
public void setTestBeanHolder(TestBeanHolder testBeanHolder) {
this.testBeanHolder = testBeanHolder;
}
public String execute() throws Exception {
return SUCCESS;
}
}
When my url is http://localhost:8080/Struts2Test/test?testBeanHolder.testBeanMap[0].value=1, testBeanHolder.testBeanMap of my action gets populated with key of 0 mapping to a TestBean instance with value=1.
When the url is http://localhost:8080/Struts2Test/test?testBeanHolder.testBeanList[0].value=1, testBeanHolder.testBeanList gets populated with single instance of TestBean with value=1.
I am try to populate testBeanListMap property of testBeanHolder and doesn't work. The testBeanListMap is created but empty. Here is the URL I am trying http://localhost:8080/Struts2Test/test?testBeanHolder.testBeanListMap[0][0].value=1
Here is the code which worked, adding modified classes:
TestBeanListHolder
package com.struts2test.beans;
import java.util.List;
public class TestBeanListHolder {
private List<TestBean> testBeans;
public List<TestBean> getTestBeans() {
return testBeans;
}
public void setTestBeans(List<TestBean> testBeans) {
this.testBeans = testBeans;
}
}
TestBeanHolder
package com.struts2test.beans;
import java.util.List;
import java.util.Map;
public class TestBeanHolder {
private Map<Integer, TestBean> testBeanMap;
private List<TestBean> testBeanList;
private Map<Integer, TestBeanListHolder> testBeanListMap;
public Map<Integer, TestBean> getTestBeanMap() {
return testBeanMap;
}
public void setTestBeanMap(Map<Integer, TestBean> testBeanMap) {
this.testBeanMap = testBeanMap;
}
public Map<Integer, TestBeanListHolder> getTestBeanListMap() {
return testBeanListMap;
}
public void setTestBeanListMap(
Map<Integer, TestBeanListHolder> testBeanListMap) {
this.testBeanListMap = testBeanListMap;
}
public List<TestBean> getTestBeanList() {
return testBeanList;
}
public void setTestBeanList(List<TestBean> testBeanList) {
this.testBeanList = testBeanList;
}
}
URL
http://localhost:8080/Struts2Test/test?testBeanHolder.testBeanListMap[1].testBeans[0].value=somevalue
The url http://localhost:8080/Struts2Test/test?testBeanHolder.testBeanListMap[0][0].value=1 won't work because you are using wrong parameter name. Thus testBeanHolder.testBeanListMap[0][0].value is a name of the parameter that maps to the object which has a property of complex type (collection of collections). Struts2 can't handle such scenarios, . But you can wrap a second collection with an object and use a collection of objects. The name would change to testBeanHolder.testBeanListMap[0].object[0].value.
The expression testBeanHolder.testBeanListMap[0][0].value is not a valid OGNL expression.
See here for a complete reference of what is allowed.

Categories

Resources