Mockito Test cases for catch block with Exception - mockito

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

Related

How to copy content of generic object for specific 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);
}

[Print alternatively using alternate Threads]

I am trying to implement this:
First Thread prints 1,Second Thread prints 2,Third Thread prints 3,First Thread prints 4 and so on:
I did this and its working :
class Display implements Runnable
{
int threadId;
static int v=1;
static int turn=1;//init
static Object monitor=new Object();
Display(int id)
{
this.threadId=id;
}
public void run() {// TODO Auto-generated method stub
print();
}
private void print() {
// TODO Auto-generated method stub
while(v<100)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
synchronized(monitor)
{
if(threadId==1)
{
if(turn!=1)
{
try {
monitor.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
System.out.println(threadId + ":"+v);
v++;
turn=2;
monitor.notifyAll();
}
}
else if(threadId==2)
{
if(turn!=2)
{
try {
monitor.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
System.out.println(threadId+":"+v);
v++;
turn=3;
monitor.notifyAll();
}
}
else
{
if(turn!=3)
{
try {
monitor.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
System.out.println(threadId+":"+v);
v++;
turn=1;
monitor.notifyAll();
}
}
}
}
}
}
public class Print {
public static void main(String[] ar)
{
Thread t1= new Thread(new Display(1));
Thread t2= new Thread(new Display(2));
Thread t3= new Thread(new Display(3));
t1.start();
t2.start();
t3.start();
}
}
Output is like this:
1:1
2:2
3:3
1:4
2:5
It achieves the purpose but if I am having two more Threads to print alternatively,then I have to use more If conditions.
Can Anyone suggest to write this code in a better form to achieve that task in a more clean way so that it is extendable if more Threads are added.
You will need the highest Id given to your threads. After this, you can simplify your code using the modulo operator.
class Display implements Runnable {
int threadId;
static int v = 1;
static int higehstId = 0;
static Object monitor = new Object();
Display(int id) {
this.threadId = id;
}
public void run() {
print();
}
private void print() {
while (v < 100) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synchronized (monitor) {
if ((v - 1) % higehstId == threadId - 1) {
System.out.println(threadId + ":" + v);
v++;
monitor.notifyAll();
} else {
try {
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] ar) {
Thread t1 = new Thread(new Display(1));
Thread t2 = new Thread(new Display(2));
Thread t3 = new Thread(new Display(3));
Thread t4 = new Thread(new Display(4));
Thread t5 = new Thread(new Display(5));
Display.higehstId = 5;
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
If you initialize v to 0 and start numbering the Threads from 0, you could simplify the if statement to this:
if(v % highestId == threadId)

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

send msg from senders to receivers (in concurrency mode) in java

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

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