Object values becomes NULL while passing to the servlet in JAX-RS

JAX-RS using Jersey

I am trying to send an object “Broadcast” from the client to the servlet and print the values in the servlet side. But my output becomes null. Help me with the issue thanks in advance 🙂

Servlet

@POST
@Path("/receiverMessage")
public Response sendMessage(Broadcast broadcast) {
    System.out.println(broadcast.getSenderName());
    System.out.println(broadcast.getReceiverName());
    System.out.println(broadcast.getTime());
    return Response.ok().status(200).entity("SUCCESS").build();
}

Client

public class Client {
public static void main(String[] args) {
    Client client = ClientBuilder.newClient();
    Broadcast broadcast = new Broadcast("SENDER", "RECEIVER", new Timestamp(System.currentTimeMillis()));
    Response messagePost = client.target("http://localhost:8081/xyz/abc")
            .path("receiverMessage")
            .request()
            .post(Entity.entity(broadcast, MediaType.APPLICATION_JSON), Response.class);
    System.out.println(messagePost.getStatus());
}}

Broadcast Model

public class Broadcast {
private String senderName;
private String receiverName;
private Timestamp time;
}

MessageBodyWriter

@Override
public void writeTo(Broadcast broadcast, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    System.setProperty("javax.xml.bind.context.factory","org.eclipse.persistence.jaxb.JAXBContextFactory");
    try {
        JAXBContext context = JAXBContext.newInstance(type);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
        marshaller.marshal(broadcast, entityStream);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}

Output

null 
null
null

Apache PoolingHttpClientConnectionManager Error: Connection pool shut down

I use these methods to get HttpClient from connection pool:

public static final PoolingHttpClientConnectionManager connManager;

    public void initConnectionMnager() {
        HttpHost httpHost = new HttpHost("localhost");
        connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(200);
        connManager.setDefaultMaxPerRoute(50);
        connManager.setMaxPerRoute(new HttpRoute(httpHost),50);
        IdleConnectionMonitorThread staleMonitor
                = new IdleConnectionMonitorThread(connManager);
        staleMonitor.start();
    }

    public static CloseableHttpClient getHttpClient() {
        initConnectionMnager();
        RequestConfig requestConfig = RequestConfig.custom()
              .setConnectionRequestTimeout(servicesRequestTimeoutInMilliseconds)
                .setSocketTimeout(SOCKET_TIMEOUT_IN_MILLIS)
                .setConnectTimeout(servicesRequestTimeoutInMilliseconds)
                .build();
        HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(3, false);
        return HttpClients
                .custom()
                .setConnectionManager(connManager)
                .setConnectionManagerShared(true)
                .setDefaultRequestConfig(requestConfig)
                .setRetryHandler(retryHandler)
                .setKeepAliveStrategy(getKeepAliveStrategy())
                .disableRedirectHandling()
                .build();
    }

    private static ConnectionKeepAliveStrategy getKeepAliveStrategy() {
        return (response, context) -> {
            HeaderElementIterator it = new BasicHeaderElementIterator
                    (response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase
                        (TIMEOUT_HEADER)) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return (long) servicesRequestTimeoutInMilliseconds;
        };
    }
}

But I get this error :

java.lang.IllegalStateException: Connection pool shut down
    at org.apache.http.util.Asserts.check(Asserts.java:34)
    at org.apache.http.pool.AbstractConnPool.lease(AbstractConnPool.java:169)

and sometimes return this error(I am sure that my server return correct response and I get correct response without using connection pool):

org.apache.http.NoHttpResponseException: 192.168.1.2 failed to responed

Also, I use apache HttpClient 4.5.2.

Web scraping a site using the user id’s from a text file?

I have a text file that contains list of restaurants as id’s and their cuisine.

id: 4950
cui: American
id: 4951
cui: Italian

I would then need to scrape the REST data using the link below.

specificwebsite.com/i/userid/4950/?list=1

The link above returns this data.

{id: 4950, cui: American, schedule:open}

Hoping to output into a text file only the ones that says schedule: open.

Any source materials in java or python are ok.

Private field and overriding the getter and setter methods

I have an abstract class like this:

public abstract class Block {
    private boolean collided = false;

    public boolean hasCollided() {
        return collided;
    }

    public void markCollided() {
        collided = true;
    }
}

I have 4 sub classes for the Block class. Those class also require to receive the collided variable. That means the two methods should be overridden by the 4 sub classes of Block. How can I make it work?

If I try to override it, it will show error because sub classes does not contain such a variable in it.

How can I receive the collided variable in all sub classes?

Also,I created an array of block class that array contains 4 subclass objects.Is it possible to set different values for the collided variable for each object,while traversing the array?
In short,the colllided variable can be unique for each object in the array?

How to insert record to foreign key table in Spring MVC Hibernate

I’m creating a web application in Spring MVC Hibernate. I have two tables one is master and second is transaction, these tables are created by hibernate and data’s are fetched from jsp. I’m new to hibernate so I didn’t know how to add record to the transaction table.
Thanks in advance.

Master Table

@Embeddable
@Entity
public class ProjectDetails implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
public Integer projectId;

@Column(updatable=true)
public String projectName;

// Getters and setters method
}

Transaction Table

@Embeddable
@Entity
public class ProjectMembers implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
public Integer sId;

@Column(updatable=true)
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn
public ProjectDetails projectId;

 // Getters and setters method
}

Controller

@RequestMapping(value = "/addMember", method = RequestMethod.POST)
public String addMember(HttpServletRequest request)
{
    ProjectMembers members = new ProjectMembers();
    try 
    {
        String id = request.getParameter("projectId"); /*Data (project id) from JSP*/

        members.setProjectId(id); /*here to insert data*/

        projectService.addProjectMember(members);
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
    return "";
}

How to resolve this error 501 #5.1.3 Partial domain not allowed: ”?

2017-12-13T15:39:01.072+11:00 [APP/PROC/WEB/0] [OUT] SMTP HOST —>> 10.97.216.202
2017-12-13T15:39:01.081+11:00 [APP/PROC/WEB/0] [OUT] [ [33mwarn [0m] c.c.c.c.e.CoreEnvironment – More than 1 Couchbase Environments found (6), this can have severe impact on performance and stability. Reuse environments!
2017-12-13T15:39:01.083+11:00 [APP/PROC/WEB/0] [OUT] [ [37minfo [0m] application – Getting bucket [secat-dev] from couchbase host [cb4clycluster01.non-prod.cly.np.top.corp.telstra.com]
2017-12-13T15:39:01.426+11:00 [APP/PROC/WEB/0] [OUT] Subject line just before submission — >> Request submitted by : jimmy@orchestrated.io
2017-12-13T15:39:01.478+11:00 [RTR/2] [OUT] secat-dev.apps.np.sdppcf.com – [2017-12-13T04:39:01.051+0000] “POST /register HTTP/1.1” 200 103 32 “https://secat-dev.apps.np.sdppcf.com/” “Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36” “10.192.230.144:54048” “10.192.224.29:61026″ x_forwarded_for:”144.136.160.20″ x_forwarded_proto:”https” vcap_request_id:”f760c7e3-dbef-433e-47e3-79b6c72b46b3″ response_time:0.426421409 app_id:”e4846497-fde0-4192-acfc-96a10e3db9ff” app_index:”0″ x_b3_traceid:”b2e068dbd1ec7fe1″ x_b3_spanid:”b2e068dbd1ec7fe1″ x_b3_parentspanid:”-”
2017-12-13T15:39:01.484+11:00 [APP/PROC/WEB/0] [ERR] com.sun.mail.smtp.SMTPSendFailedException: 501 #5.1.3 Partial domain not allowed: ”
2017-12-13T15:39:01.484+11:00 [APP/PROC/WEB/0] [ERR] at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1829)
2017-12-13T15:39:01.484+11:00 [APP/PROC/WEB/0] [ERR] at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1368)
2017-12-13T15:39:01.484+11:00 [APP/PROC/WEB/0] [ERR] at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:886)
2017-12-13T15:39:01.484+11:00 [APP/PROC/WEB/0] [ERR] at javax.mail.Transport.send0(Transport.java:191)
2017-12-13T15:39:01.484+11:00 [APP/PROC/WEB/0] [ERR] at javax.mail.Transport.send(Transport.java:120)
2017-12-13T15:39:01.484+11:00 [APP/PROC/WEB/0] [ERR] at com.telstra.secat.controllers.LoginController.registrationRequest(LoginController.java:113)
2017-12-13T15:39:01.484+11:00 [APP/PROC/WEB/0] [ERR] at router.Routes$$anonfun$routes$1$$anonfun$applyOrElse$3$$anonfun$apply$3.apply(Routes.scala:954)
2017-12-13T15:39:01.484+11:00 [APP/PROC/WEB/0] [ERR] at play.core.routing.HandlerInvokerFactory$$anon$4.resultCall(HandlerInvoker.scala:157)
2017-12-13T15:39:01.484+11:00 [APP/PROC/WEB/0] [ERR] at play.core.routing.HandlerInvokerFactory$$anon$4.resultCall(HandlerInvoker.scala:156)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.core.routing.HandlerInvokerFactory$JavaActionInvokerFactory$$anon$14$$anon$3$$anon$1.invocation(HandlerInvoker.scala:136)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:73)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.http.HttpRequestHandler$1.call(HttpRequestHandler.java:54)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.core.j.JavaAction$$anonfun$7.apply(JavaAction.scala:108)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.core.j.HttpExecutionContext$$anon$2.run(HttpExecutionContext.scala:56)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.api.libs.iteratee.Execution$trampoline$.execute(Execution.scala:70)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.core.j.HttpExecutionContext.execute(HttpExecutionContext.scala:48)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at scala.concurrent.impl.Future$.apply(Future.scala:31)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at scala.concurrent.Future$.apply(Future.scala:492)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.core.j.JavaAction.apply(JavaAction.scala:108)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.api.mvc.Action$$anonfun$apply$2$$anonfun$apply$5$$anonfun$apply$6.apply(Action.scala:112)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.utils.Threads$.withContextClassLoader(Threads.scala:21)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.api.mvc.Action$$anonfun$apply$2$$anonfun$apply$5.apply(Action.scala:111)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.api.mvc.Action$$anonfun$apply$2$$anonfun$apply$5.apply(Action.scala:110)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at scala.Option.map(Option.scala:146)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.api.mvc.Action$$anonfun$apply$2.apply(Action.scala:110)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at play.api.mvc.Action$$anonfun$apply$2.apply(Action.scala:103)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:251)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:249)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply$mcV$sp(BatchingExecutor.scala:91)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply(BatchingExecutor.scala:91)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:72)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at akka.dispatch.BatchingExecutor$BlockableBatch.run(BatchingExecutor.scala:90)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:39)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:415)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
2017-12-13T15:39:01.485+11:00 [APP/PROC/WEB/0] [ERR] at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

Consolidate Transactions – Interview

I have recently stumbled upon an interview question which I am trying to solve in the most efficient way possible and within the time limit of 45 mins of an interview.

The question is about consolidating transactions:

Q Consolidate multiple transactions into a minimum number of transactions.

  transactions = [
  {"payee": "BoA", "amount": 132, "payer": "Chase"},
  {"payee": "BoA", "amount": 827, "payer": "Chase"},
  {"payee": "Well Fargo", "amount": 751, "payer": "BoA"},
  {"payee": "BoA", "amount": 585, "payer": "Chase"},
  {"payee": "Chase", "amount": 877, "payer": "Well Fargo"},
  {"payee": "Well Fargo", "amount": 157, "payer": "Chase"},
  {"payee": "Well Fargo", "amount": 904, "payer": "Chase"},
  {"payee": "Chase", "amount": 976, "payer": "BoA"},
  {"payee": "Chase", "amount": 548, "payer": "Well Fargo"},
  {"payee": "BoA", "amount": 872, "payer": "Well Fargo"},
  {"payee": "Well Fargo", "amount": 571, "payer": "Chase"}
]

The program should have the functionality to consolidate transitive transactions and reduce them to the lowest unit as possible. For Example:
A -> B and B -> C then we can reduce this transaction to A -> C

I have taken a stab at a sample program that can do this. However, I need some inputs from experts here on SO, if this could be solved efficiently.

public class ConsolidateTransaction {

    static class Transaction {
        String payer;
        long amount;
        String payee;

        public Transaction(String payee, long amnt, String payer) {
            if (payee.compareTo(payer) > 0) {
                this.payer = payee;
                amount = -amnt;
                this.payee = payer;
            } else {
                this.payer = payer;
                amount = amnt;
                this.payee = payee;
            }
        }
        public String toString() {
            return "  " + payee + "->" + amount + "->" + payer + "   ";
        }
    }

    public static void main(String[] args) {

        Transaction t1 = new Transaction("Boa", 132, "Chase");
        Transaction t2 = new Transaction("Boa", 827, "Chase");
        Transaction t3 = new Transaction("Well Fargo", 751, "Boa");
        Transaction t4 = new Transaction("Boa", 585, "Chase");
        Transaction t5 = new Transaction("Chase", 877, "Well Fargo");
        Transaction t6 = new Transaction("Well Fargo", 571, "Chase");
        Transaction t7 = new Transaction("Boa", 872, "Well Fargo");
        Transaction t8 = new Transaction("Chase", 548, "Well Fargo");
        Transaction t9 = new Transaction("Chase", 976, "Boa");
        Transaction t10 = new Transaction("Well Fargo", 904, "Chase");
        Transaction t11 = new Transaction("Well Fargo", 157, "Chase");

        List<Transaction> list = new ArrayList<>();
        list.add(t1);
        list.add(t2);
        list.add(t3);
        list.add(t4);
        list.add(t5);
        list.add(t6);
        list.add(t7);
        list.add(t8);
        list.add(t9);
        list.add(t10);
        list.add(t11);
        ConsolidateTransaction s = new ConsolidateTransaction();
        System.out.println("Simplified transactions: " + s.getSimplifiedTransaction(list));
    }

    public List<Transaction> getSimplifiedTransaction(List<Transaction> list) {
        if (list == null || list.size() <=1) {
            return list;
        }
        // intelligent sort
        List<Transaction> result = new ArrayList<Transaction>();
        Collections.sort(list, (a, b) -> (a.payee + a.payer).compareTo(b.payee + b.payer));

        System.out.println(list);

        Transaction prev = list.get(0);
        for (int i=1; i< list.size(); i++) {
            Transaction curr = list.get(i);
            if (prev.payer.equals(curr.payer) && prev.payee.equals(curr.payee)) {
                Transaction merged = new Transaction(curr.payer, (prev.amount + curr.amount), curr.payee);
                prev = merged;
            } else {
                result.add(prev);
                prev = curr;
            }
        }
        result.add(prev);
        return result;
    }
}

JMeter – Groovy script concatenation of variables

Groovy is the preferred scripting in JMeter

We advise using Apache Groovy or any language that supports the Compilable interface of JSR223.

The following code in JSR233 Sampler works in Java but not in Groovy

String a= "0"+"1" +
"2" 
+"3";
log.info(a);

I found the reasons for + operator not to work as expected,

but what is the solution is I want to concatenate several variables to a script?

I failed to use answer of using three quotes """The row Id is: ${row.id}..."""

Currently I use Java as script language and use JMeter ${variable} although is also not recommended:

In this case, ensure the script does not use any variable using ${varName} as caching would take only first value of ${varName}

String text ="...<id>${id}</id><id2>${id2}</id2>...";

What’s a better approach in groovy in such case?

Cannot resolve constructor in ArrayAdapter

public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {

EditText myeditText1;
EditText myeditText2;
Button myButton;

Double myfirstET1;
Double myfirstET2;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    myeditText1 = (EditText) findViewById(R.id.editText1);
    myeditText2 = (EditText) findViewById(R.id.editText2);
    myButton = (Button) findViewById(R.id.buttonID);
    final TextView myTextView = (TextView) findViewById(R.id.textView2);


    myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            myfirstET1 = Double.parseDouble(myeditText1.getText().toString());
            myfirstET2 = Double.parseDouble(myeditText2.getText().toString());
            final ListView mListView = (ListView) findViewById(R.id.mList);

            if ((myeditText1.getText().length() > 0) && (myeditText2.getText().length() > 0)) {
                double oper1 = Double.parseDouble(myeditText1.getText().toString());
                double oper2 = Double.parseDouble(myeditText2.getText().toString());
                double result = oper1 / oper2;
                myTextView.setText(Double.toString(result));


                Double myyList[] = {oper1, oper2 + 1, oper2 + 1};

                ListAdapter myAdapter = new ArrayAdapter<Double>(this, android.R.layout.simple_list_item_1, myyList);
                mListView.setAdapter(myAdapter);

            }

        }
    });

Upon creating the ListView and setting adapter to it, I’m getting error in ListAdapter.. How do I fix it OR whats the easy alternative for it?
I hope my moto is clear with the code I’ve written.

All suggestions are heartly appreciated.