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));
}
});
Related
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);
}
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.
All the other breakpoints inside my class work just fine.
However, none of the breakpoints inside the run method. What can the issue be?
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(final Object...args) {
new Handler(getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(ChatService.this, "connected", Toast.LENGTH_SHORT).show();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(user);
try {
obj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("set-user-data", obj, user.getRole());
JSONArray membersJSONArray = new JSONArray();
membersJSONArray.put(user.getUsername());
JSONObject roomInfo = new JSONObject();
try {
roomInfo.put("members", membersJSONArray);
roomInfo.put("platformInfo", user.getPlatformInfo());
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("set-room", roomInfo);
}
});
}
};
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);
//设置缓存路径
I want to write program that use one server that receive msg from reporters in specific port and send online msg to client (readers) that are connected on another specific port ...
tip1 =>
my server has two open port ... one specific for senders and another for reader...
tip2 =>
when msg is received from sender in server => we(server) should send this msg to all online client that listen
how can I implement them...
I have problem in send msg from server to "all" client!
You can do it like this -
public class SenderReceiver {
private static volatile boolean serverStarted;
private static final String SERVER_HOST = "127.0.0.1";
private static final int SERVER_PORT = 25000;
private static final List<ReceiverConnectionHandler> handlers = new CopyOnWriteArrayList<ReceiverConnectionHandler>();
private static final ExecutorService executorService = Executors.newCachedThreadPool();
public static void main(String[] args) {
// start server
executorService.submit(new SenderReceiver().new Server());
// wait until started
while (!serverStarted) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// start receiver threads
int i = 0;
while (i++ < 10) {
executorService.submit(new Receiver(SERVER_HOST, SERVER_PORT));
}
// start sender threads
i = 0;
while (i++ < 5) {
executorService.submit(new Sender(SERVER_HOST, SERVER_PORT));
}
}
private class Server implements Runnable {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
serverStarted = true;
System.out.println("Server started");
while (true) {
Socket socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String connectionName = br.readLine();
if ("sender".equals(connectionName)) {
executorService.submit(new SenderConnectionHandler(br, handlers));
} else {
ReceiverConnectionHandler handler = new ReceiverConnectionHandler(socket);
handlers.add(handler);
executorService.submit(handler);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private class SenderConnectionHandler implements Runnable {
private BufferedReader br;
private List<ReceiverConnectionHandler> handlers;
public SenderConnectionHandler(BufferedReader br, List<ReceiverConnectionHandler> handlers) {
this.br = br;
this.handlers = handlers;
}
public void run() {
try {
String message;
while ((message = br.readLine()) != null) {
Thread.sleep(1000); // just allowing all clients to be registered
for (ReceiverConnectionHandler handler : handlers) {
handler.update(message);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
private class ReceiverConnectionHandler implements Runnable {
private Socket receiverSocket;
private final BlockingQueue<String> messages = new LinkedBlockingQueue<>();
public ReceiverConnectionHandler(Socket socket) {
this.receiverSocket = socket;
}
public void run() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(receiverSocket.getOutputStream()));
String message;
while ((message = messages.poll(1, TimeUnit.SECONDS)) != null) {
bw.write(message);
bw.newLine();
bw.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void update(Object message) {
if (message instanceof String) {
messages.add((String) message);
}
}
}
}
class Sender implements Runnable {
private static AtomicInteger senderCount = new AtomicInteger(0);
private String serverHost;
private int serverPort;
public Sender(String serverHost, int serverPort) {
this.serverHost = serverHost;
this.serverPort = serverPort;
}
public void run() {
BufferedWriter bw = null;
try {
Socket socket = new Socket(serverHost, serverPort);
int senderNumber = senderCount.incrementAndGet();
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("sender");
bw.newLine();
String message = "This is a test message from sender " + senderNumber;
bw.write(message);
bw.newLine();
System.out.println("Sender " + senderNumber + " : " + message);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
class Receiver implements Runnable {
private static AtomicInteger receiverCount = new AtomicInteger(0);
private String serverHost;
private int serverPort;
public Receiver(String serverHost, int serverPort) {
this.serverHost = serverHost;
this.serverPort = serverPort;
}
public void run() {
BufferedReader br = null;
BufferedWriter bw = null;
try {
Socket socket = new Socket(serverHost, serverPort);
int receiverNumber = receiverCount.incrementAndGet();
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("client");
bw.newLine();
bw.flush();
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message;
while ((message = br.readLine()) != null) {
System.out.println("Receiver " + receiverNumber + ": " + message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}