How to copy content of generic object for specific object - object

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);
}

Related

Mockito Test cases for catch block with Exception

Class A
{
public String name (String str)
{
try {
fullName = str + "org";
} catch (Exception e) {
logger.debug(e.getMessage())
}
}
}

zk LongUIOperation Executions.deactivate null pointer exception

I'm using LongUIOperation custom implementation, but, sometimes, on
Executions.deactivate(getNativeDesktop());
I receive messagebox on screen and:
dic 11, 2017 11:09:42 AM org.zkoss.zk.ui.impl.UiEngineImpl handleError
GRAVE: java.lang.NullPointerException at
org.apache.catalina.connector.Request.notifyAttributeAssigned(Request.java:1528)
at
org.apache.catalina.connector.Request.setAttribute(Request.java:1514)
at
org.apache.catalina.connector.RequestFacade.setAttribute(RequestFacade.java:540)
at
org.zkoss.zk.ui.http.ExecutionImpl.setAttribute(ExecutionImpl.java:497)
at org.zkoss.zk.ui.impl.Utils.getComponentInfos(Utils.java:120) at
org.zkoss.zk.ui.impl.Utils.setComponentInfo(Utils.java:129) at
org.zkoss.zk.ui.impl.AbstractUiFactory.newComponent(AbstractUiFactory.java:137)
at
org.zkoss.zk.ui.impl.UiEngineImpl.execCreateChild0(UiEngineImpl.java:919)
at
org.zkoss.zk.ui.impl.UiEngineImpl.execCreateChild(UiEngineImpl.java:889)
at
org.zkoss.zk.ui.impl.UiEngineImpl.execCreate0(UiEngineImpl.java:776)
at org.zkoss.zk.ui.impl.UiEngineImpl.access$800(UiEngineImpl.java:128)
at
org.zkoss.zk.ui.impl.UiEngineImpl$TemplateImpl.create(UiEngineImpl.java:2318)
at
org.zkoss.bind.impl.BindListitemRenderer.render(BindListitemRenderer.java:79)
at org.zkoss.zul.Listbox$Renderer.render(Listbox.java:2769) at
org.zkoss.zul.Listbox.doInitRenderer(Listbox.java:2584) at
org.zkoss.zul.Listbox.onInitRender(Listbox.java:2537) at
sun.reflect.GeneratedMethodAccessor2366.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.zkoss.zk.ui.AbstractComponent.service(AbstractComponent.java:3146)
at
org.zkoss.zk.ui.AbstractComponent.service(AbstractComponent.java:3077)
at
org.zkoss.zk.ui.impl.EventProcessor.process(EventProcessor.java:138)
at
org.zkoss.zk.ui.impl.UiEngineImpl.processEvent(UiEngineImpl.java:1846)
at org.zkoss.zk.ui.impl.UiEngineImpl.process(UiEngineImpl.java:1618)
at org.zkoss.zk.ui.impl.UiEngineImpl.endUpdate(UiEngineImpl.java:1222)
at
org.zkoss.zkex.ui.comet.CometServerPush.deactivate(CometServerPush.java:522)
at
org.zkoss.zk.ui.impl.DesktopImpl.deactivateServerPush(DesktopImpl.java:1596)
at org.zkoss.zk.ui.Executions.deactivate(Executions.java:1011) at
com.ims.web.ui.GenericViewModel.deactivateNativeDesktop(GenericViewModel.java:193)
at
com.ims.web.zk.ui.DesktopVMLongUIOperation.run(DesktopVMLongUIOperation.java:186)
at java.lang.Thread.run(Unknown Source)
Use case example:
#Command
#Override
public void editBaseItem() throws Exception {
super.editBaseItem();
if(selectedBaseItem.getOid() == null){
initNewItem();
}
final String sessionID = getSessionID();
final StaffDailyAvailabilityVM instanceVM = this;
new DesktopVMLongUIOperation(this,win,Labels.getLabel("def.msg.refreshdata","Refresh data...")) {
#Override
protected void execute() throws InterruptedException {
try {
StaffDailyAvailabilityManager.evaluateStaffDailyAvailabilitySynch(selectedBaseItem, sessionID);
} catch (Exception e) {
logger.error(e,e);
}
}
protected void onCleanup() {
try {
//refresh clock time list
selectedBaseItem.getLastStaffDailyTimestampDTO();
if(selectedBaseItem.isErrorDetected()){
selectedBaseItem.setCertified(false);
}
BindUtils.postNotifyChange(null, null, instanceVM.getSelectedBaseItem(),"lastStaffDailyTimestampDTO");
BindUtils.postNotifyChange(null, null, instanceVM, "selectedBaseItem");
} catch (Exception e) {
logger.error(e,e);
}
};
}.start();
}
Here the code:
public abstract class DesktopVMLongUIOperation implements Runnable {
protected static final Logger logger = Logger.getLogger(DesktopVMLongUIOperation.class);
private Thread thread;
private AtomicBoolean cancelled = new AtomicBoolean(false);
private Window win;
private GenericViewModel genericViewModel;
public DesktopVMLongUIOperation(GenericViewModel genericViewModel){
this(genericViewModel,null,"");
}
public DesktopVMLongUIOperation(GenericViewModel genericViewModel, Window win, String busyMsg){
this.win = win;
this.genericViewModel = genericViewModel;
try {
this.genericViewModel.enableServerPush(null);
if(win != null){
Clients.showBusy(win,busyMsg);
}
} catch (Exception e) {
logger.error(e,e);
}
}
/**
* asynchronous callback for your long operation code
* #throws InterruptedException
*/
protected abstract void execute() throws InterruptedException;
/**
* optional callback method when the task has completed successfully
*/
protected void onFinish() {};
/**
* optional callback method when the task has been cancelled or was interrupted otherwise
*/
protected void onCancel() {};
/**
* optional callback method when the task has completed with an uncaught RuntimeException
* #param exception
*/
protected void onException(RuntimeException exception) {
logger.error(exception,exception);
};
/**
* optional callback method when the task has completed (always called)
*/
protected void onCleanup() {};
/**
* set the cancelled flag and try to interrupt the thread
*/
public final void cancel() {
try {
cancelled.set(true);
if(thread != null){
thread.interrupt();
}
} catch (Throwable e) {
logger.error(e,e);
}
}
/**
* check the cancelled flag
* #return
*/
public final boolean isCancelled() {
return cancelled.get();
}
/**
* Checks if the task thread has been interrupted. Use this to check whether or not to exit a busy operation in case.
* #throws InterruptedException when the current task has been cancelled/interrupted
*/
protected final void checkCancelled() throws InterruptedException {
try {
if(Thread.currentThread() != this.thread) {
throw new IllegalStateException("this method can only be called in the worker thread (i.e. during execute)");
}
boolean interrupted = Thread.interrupted();
if(interrupted || cancelled.get()) {
cancelled.set(true);
throw new InterruptedException();
}
} catch (Throwable e) {
logger.error(e,e);
}
}
/**
* launch the long operation
*/
public final void start() {
try {
thread = new Thread(this);
thread.start();
} catch (Throwable e) {
logger.error(e,e);
}
}
#Override
public final void run() {
try {
try {
checkCancelled(); //avoid unnecessary execution
execute();
checkCancelled(); //final cancelled check before calling onFinish
genericViewModel.activateNativeDesktop();
logger.error("ACTIVATE: RUN");
onFinish();
} catch (InterruptedException e) {
try {
cancelled.set(true);
genericViewModel.activateNativeDesktop();
logger.error("ACTIVATE: INTERRUPT");
onCancel();
} catch (InterruptedException e1) {
throw new RuntimeException("interrupted onCancel handling", e1);
} catch (Exception e1) {
logger.error(e1,e1);
} finally {
try {
genericViewModel.deactivateNativeDesktop();
logger.error("DEACTIVATE: INTERRUPT");
} catch (Exception e1) {
logger.error(e1,e1);
}
}
} catch (RuntimeException rte) {
try {
genericViewModel.activateNativeDesktop();
logger.error("ACTIVATE: EXCEPTION");
onException(rte);
} catch (InterruptedException e1) {
throw new RuntimeException("interrupted onException handling", e1);
} catch (Exception e) {
logger.error(e,e);
} finally {
try {
genericViewModel.deactivateNativeDesktop();
logger.error("ACTIVATE: EXCEPTION");
} catch (Exception e) {
logger.error(e,e);
}
}
throw rte;
} catch (Exception e) {
logger.error(e,e);
} finally {
try {
genericViewModel.deactivateNativeDesktop();
logger.error("DEACTIVATE: RUN");
} catch (Exception e) {
logger.error(e,e);
}
}
} finally {
try {
genericViewModel.activateNativeDesktop();
logger.error("ACTIVATE: CLEANUP");
try {
if(win != null){
Clients.clearBusy(win);
}
} catch (Exception e) {
logger.error(e,e);
}
onCleanup();
} catch (InterruptedException e1) {
throw new RuntimeException("interrupted onCleanup handling", e1);
} catch (Exception e1) {
logger.error(e1,e1);
} finally {
try {
genericViewModel.deactivateNativeDesktop();
logger.error("DEACTIVATE: CLEANUP");
} catch (Exception e) {
logger.error(e,e);
}
}
}
}
}
And activate deactivate code from genericViewModel:
... ... public GenericViewModel(){ nativeDesktop = Executions.getCurrent().getDesktop(); }
... ...
public GenericViewModel(){
nativeDesktop = Executions.getCurrent().getDesktop();
}
public boolean activateNativeDesktop() throws Exception{
boolean res = false;
if(getNativeDesktop() != null && getNativeDesktop().isAlive()){
try {
Executions.activate(getNativeDesktop());
res = true;
} catch (Throwable e) {
logger.error(e,e);
throw(e);
}
}else{
throw new Exception("ZK native Desktop is null");
}
return res;
}
public boolean deactivateNativeDesktop() throws Exception{
boolean res = false;
if(getNativeDesktop() != null && getNativeDesktop().isAlive()){
try {
Executions.deactivate(getNativeDesktop());
res = true;
} catch (Throwable e) {
logger.error(e,e);
throw(e);
}
}else{
throw new Exception("ZK native Desktop is null");
}
return res;
}

Nifi:transfer relationship not specified

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.

Breakpoint not working inside a Handler - Android Studio

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);
}
});
}
};

How to use CatalogResolver in JAXB

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));
}
});

Resources