Attempting to use Comparator to sort by name, ignore case, as well as nulls first

so i am having issues using the Java 8 Comparator library to sort a list of items.

My current working comparator is below:

comparator = Comparator.comparing(Person::getName, Comparator.nullsFirst(Comparator.naturalOrder()));

This works, it orders it by name with the null values as first. However, I am now attempting to ignore case of the names.

I know that I can write a new getter that returns the name all lowercase, but I do not want to go with this approach as I have to do this for multiple attributes.

Looking online it looks like I should be using String.CASE_INSENSITIVE_ORDER, but the only examples I see they do not include the null specification.

I can do something like this:

comparator = Comparator.comparing(Person::getName, String.CASE_INSENSITIVE_ORDER);

but whenever I try to include the Comparator.nullsFirst I end up getting type errors, and am confused on how to continue.

I’ve tried doing a chain similar to thenComparing(Comparator.nullsFirst(Comparator.naturalOrder)) but that also doesn’t work.

Could someone lend me some advice on how I can chain these together to sort by name (not case sensitive) and then order the nulls. I seem to be confusing myself with the types

Installing Wildfly on Windows 10 is complaining about dependancies

I’m trying to install Wildfly following this tutorial and this other too on youtube.

  • Windows 10
  • I’ve installed JDK9
  • WildFly10

When I type standalone, I get the following warnings:

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.jboss.modules.ClassLoaderLocalLoader$1
WARNING: Please consider reporting this to the maintainers of org.jboss.mod
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access 
WARNING: All illegal access operations will be denied in a future release

Then I get also a series of error, which basically says that: one or more services were unable to start due to one or more indirect dependencies not being available.

I’m completely new to Java world. I don’t know why I’m getting those errors, yet in both tutorials there are just few simple steps to follow.

Thanks for helping

Java swing concurrency, multiple propertychangelisteners?

I have a panel called DataPanel which extends JPanel, and a worker called DataPanelWorker which extends SwingWorker.

Currently when I create the DataPanel, I start the DataPanelWorker which does some calculations and fires property changes after each calculation.

The DataPanel listens for these property changes and displays a message each time.
e.g.
“Calculation 1 complete”
“Calculation 2 complete”

This works fine!

What I now want to do now is create a second instance of DataPanel (let’s call this DataPanel2) but I want to use the original DataPanelWorker to save computation. I register DataPanel2 as another propertyChangeListener on DataPanelWorker.

My problem is I might register DataPanel2 after calculation 1 has been completed and the first propertyChangeEvent has been fired.
How can I know how far through the worker is so that I can get DataPanel2 to be displaying the same messages as DataPanel1?

What I would like ideally is to keep a queue of propertyChangeEvents and when registering a new component, fire them all on just that component. Is there a standard way of doing this? Or am I looking at it from the wrong view?

Thanks

GEOCODING: How avoid OVER_QUERY_LIMIT in google map api -java

I have function that give me lat long from address:

 public static String[] getLatLongPositions(String address) throws Exception
  {
    int responseCode = 0;
    String api = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + URLEncoder.encode(address, "UTF-8") + "&sensor=true";
    //System.out.println("URL : "+api);
    URL url = new URL(api);
    HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();
    httpConnection.connect();
    responseCode = httpConnection.getResponseCode();
    if(responseCode == 200)
    {
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();;
      Document document = builder.parse(httpConnection.getInputStream());
      XPathFactory xPathfactory = XPathFactory.newInstance();
      XPath xpath = xPathfactory.newXPath();
      XPathExpression expr = xpath.compile("/GeocodeResponse/status");
      String status = (String)expr.evaluate(document, XPathConstants.STRING);
      if(status.equals("OK"))
      {
         expr = xpath.compile("//geometry/location/lat");
         String latitude = (String)expr.evaluate(document, XPathConstants.STRING);
         expr = xpath.compile("//geometry/location/lng");
         String longitude = (String)expr.evaluate(document, XPathConstants.STRING);
         return new String[] {latitude, longitude};
      }
      else
      {
         throw new Exception("Error from the API - response status: "+status+"street "+ address);
      }
    }
    return null;
  }

But very often i get OVER_QUERY_LIMIT so i try sleep for a moment and run my function again adding this:

if(status.equals("OVER_QUERY_LIMIT")){
              Thread.sleep(1000);
              getLatLongPositions(address);
          }

But when getLatLongPositions is running again recursively i get null at this line responseCode = httpConnection.getResponseCode();
How can i avoid this problem?
Also in this function some addresses are without error but when i run again this function i get error with these addresses which were good before.

What does this mean List < Class >?

I ran into a below statement which expects aforementioned parameter type while reviewing oracle entitlement server API.

FunctionEntry functionEntry = ...;
functionEntry.setParameterTypes(List<Class<? extends DataType>>);

I am having a hard time to understand what it is asking for. I only understand “? extends DataType”. What type of parameter I need to pass into setParameterTypes method?

QueryDSL, Hibernate, JPA — using .fetchJoin() and getting data in first SELECT, so why N+1 queries after?

I’m trying to query for a list of entities (MyOrders) that have mappings to a few simple sub-entities: each MyOrder is associated with exactly one Store, zero or more Transactions, and at most one Tender. The generated SELECT appears correct – it retrieves all the columns from all four joined tables – but afterwards, two more SELECTs are executed for each MyOrder, one for Transactions and one for Tender.

I’m using QueryDSL 4.1.3, Spring Data 1.12, JPA 2.1, and Hibernate 5.2.

In QueryDSL, my query is:

... = new JPAQuery<MyOrder>(entityManager)
    .from(qMyOrder)
    .where(predicates)
    .join(qMyOrder.store).fetchJoin()
    .leftJoin(qMyOrder.transactions).fetchJoin()
    .leftJoin(qMyOrder.tender).fetchJoin()
    .orderBy(qMyOrder.orderId.asc())
    .transform(GroupBy
        .groupBy(qMyOrder.orderId)
        .list(qMyOrder));

which is executed as:

SELECT myorder0_.ord_id AS col_0_0_,
    myorder0_.ord_id AS col_1_0_,
    store1_.sto_id AS sto_id1_56_1_, -- store's PK
    transactions3_.trn_no AS trn_no1_61_2_, -- transaction's PK
    tender4_.tender_id AS pos_trn_1_48_3_, -- tender's PK
    myorder0_.ord_id AS ord_id1_39_0_,
    myorder0_.app_name AS app_name3_39_0_, -- {app_name, ord_num} is unique
    myorder0_.ord_num AS ord_num8_39_0_,
    myorder0_.sto_id AS sto_id17_39_0_,
    store1_.division_num AS div_nu2_56_1_,
    store1_.store_num AS store_nu29_56_1_,
    transactions3_.trn_cd AS trn_cd18_61_2_,
    tx2myOrder2_.app_name AS app_name3_7_0__, -- join table
    tx2myOrder2_.ord_no AS ord_no6_7_0__,
    tx2myOrder2_.trn_no AS trn_no1_7_0__,
    tender4_.app_name AS app_name2_48_3_,
    tender4_.ord_num AS ord_num5_48_3_,
    tender4_.tender_cd AS tender_cd_7_48_3_,
FROM data.MY_ORDER myorder0_
INNER JOIN data.STORE store1_ ON myorder0_.sto_id=store1_.sto_id
LEFT OUTER JOIN data.TX_to_MY_ORDER tx2myOrder2_
    ON myorder0_.app_name=tx2myOrder2_.app_name
    AND myorder0_.ord_num=tx2myOrder2_.ord_no
LEFT OUTER JOIN data.TRANSACTION transactions3_ ON tx2myOrder2_.trn_no=transactions3_.trn_no
LEFT OUTER JOIN data.TENDER tender4_
    ON myorder0_.app_name=tender4_.app_name
    AND myorder0_.ord_num=tender4_.ord_num
ORDER BY myorder0_.ord_id ASC

which is pretty much what I’d expect. (I cut out most of the data columns for brevity, but everything I need is SELECTed.)

When querying an in-memory H2 database (set up with Spring’s @DataJpaTest annotation), after this query executes, a second query is made against the Tender table, but not Transaction. When querying a MS SQL database, the initial query is identical, but additional queries happen against both Tender and Transaction. Neither makes additional calls to load Store.

All the sources I’ve found suggest that the .fetchJoin() should be sufficient (such as Opinionated JPA with Query DSL; scroll up a few lines from the anchor) and indeed if I remove them, the initial query only selects columns from MY_ORDER. So it appears that .fetchJoin() does force generation of a query that fetches all the side tables in one go, but for some reason that extra information isn’t being used. What’s really weird is that I do see the Transaction data being attached in my H2 quasi-unit test without a second query (if and only if I use .fetchJoin() ) but not when using MS SQL.

I’ve tried annotating the entity mappings with @Fetch(FetchMode.JOIN), but the secondary queries still fire. I suspect there might be a solution involving extending CrudRepository<>, but I’ve had no success getting even the initial query correct there.

My primary entity mapping, using Lombok’s @Data annotations, other fields trimmed out for brevity. (Store, Transaction, and Tender all have an @Id a handful of simple numeric and string field-column mappings, no @Formulas or @OneToOnes or anything else.)

@Data
@NoArgsConstructor
@Entity
@Immutable
@Table(name = "MY_ORDER", schema = "Data")
public class MyOrder implements Serializable {

@Id
@Column(name = "ORD_ID")
private Integer orderId;

@NonNull
@Column(name = "APP_NAME")
private String appName;
@NonNull
@Column(name = "ORD_NUM")
private String orderNumber;

@ManyToOne
@JoinColumn(name = "STO_ID")
private Store store;

@OneToOne
@JoinColumns({
        @JoinColumn(name = "APP_NAME", referencedColumnName = "APP_NAME", insertable = false, updatable = false),
        @JoinColumn(name = "ORD_NUM", referencedColumnName = "ORD_NUM", insertable = false, updatable = false)})
@org.hibernate.annotations.ForeignKey(name = "none")
private Tender tender;

@OneToMany
@JoinTable(
        name = "TX_to_MY_ORDER", schema = "Data",
        joinColumns = { // note X_to_MY_ORDER.ORD_NO vs. ORD_NUM
                @JoinColumn(name = "APP_NAM", referencedColumnName = "APP_NAM", insertable = false, updatable = false),
                @JoinColumn(name = "ORD_NO", referencedColumnName = "ORD_NUM", insertable = false, updatable = false)},
        inverseJoinColumns = {@JoinColumn(name = "TRN_NO", insertable = false, updatable = false)})
@org.hibernate.annotations.ForeignKey(name = "none")
private Set<Transaction> transactions;

/**
 * Because APP_NAM and ORD_NUM are not foreign keys to TX_TO_MY_ORDER (and they shouldn't be),
 * Hibernate 5.x saves this toString() as the 'owner' key of the transactions collection such that
 * it then appears in the transactions collection's own .toString(). Lombok's default generated
 * toString() includes this.getTransactions().toString(), which causes an infinite recursive loop.
 * @return a string that is unique per order
 */
@Override
public String toString() {
    // use appName + orderNumber since, as they are the columns used in the join, they must (?) have
    // already been set when attaching the transactions - primary key sometimes isn't set yet.
    return this.appName + "0" + this.orderNumber;
}
}

My question is: why am I getting redundant SELECTs, and how can I not do that?

Java string to date conversion

Can somebody recommend the best way to convert a string in the format ‘January 2, 2010’ to a date in java? Ultimately, I want to break out the month, the day, and the year as integers so that I can use:

Date date = new Date();
date.setMonth()..
date.setYear()..
date.setDay()..
date.setlong currentTime = date.getTime();

to convert the date into time.

convert java Date to mySql

I’m making a StudentAdministration project with a Usercontroller, studentrepository, some html templates, a css stylesheet and a mySql database. Everything is working out great, and i see my index site, but im having problem creating students because of the Date attribute at my Student class.

In my controller, this is how i create:

@Override
public void create(Student st) {
    jdbc.update("INSERT INTO studentdb.student(firstName, lastName, 
    enrollmentDate, password, cpr)

" + "VALUES('" + st.getFirstName() + "', 
'" + 
st.getLastName() + "', '" +  st.getEnrollmentDate() + "', '" + 
st.getPassword() + "', '" + st.getCpr() + "') ");
}

the problem is the st.getEnrollmentDate because it gives me another date format than the 1 MySql accepts. What should i do here? I’d rather not start changing the Date attribute to a String even though that would fix the problem.

Parsing Json Response sent from Google Distance Matrix API

I have spent hours trying to figure out whats going on here but can’t seem to figure it out whatsoever. I have researched in to the different methods and im 100% sure that ive seen every similar post on here but it’s been no help.

Anyway…

I am sending a request to google’s api. I am getting the response succesfully in json but cannot parse it. I am using gson to try and achieve this but had no luck. I have made a model class to model the json but only using three parameters as I just need to get the destination address, origin address and time it will take.

The model class :

public class GoogleResponsePojo {

private String destination_addresses;
private String origin_addresses;
private String durationText;


public String getDestinationAddress() {
    return destination_addresses;
}

public void setDestinationAddress(String destinationAddress) {
    this.destination_addresses = destinationAddress;
}

public String getOriginAddress() {
    return origin_addresses;
}

public void setOriginAddress(String originAddress) {
    this.origin_addresses = originAddress;
}

public String getDurationText() {
    return durationText;
}

public void setDurationText(String durationText) {
    this.durationText = durationText;
}

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append(getOriginAddress());
    builder.append(getDurationText());
    builder.append(getDestinationAddress());

    return builder.toString();
}

}

The next bit of code is sending the request using Javax.ws.rs (Which works fine)

    public static final String BASE_URL = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=Seattle&destinations=San+Francisco&key=***";


@GET
@Produces(MediaType.APPLICATION_JSON)
public static void updateTestExecutionDetails() throws IOException {

    Client client = ClientBuilder.newClient();
    Response response = client.target(BASE_URL)
            .request().get();

     if (response.getStatus() != 200)
         throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());


     // This is what im trying to do
     Gson gson = new Gson();
     GoogleResponsePojo name = gson.fromJson(response.toString(),GoogleResponsePojo.class);

     System.out.println(name.getDestinationAddress());
     System.out.println(name.getDurationText());
     System.out.println(name.getOriginAddress());



    System.out.println(response.readEntity(String.class));
    System.out.println("Status :" + response.getStatus());



}

public static void main(String[] args) throws IOException {
    updateTestExecutionDetails();
}

So essentially I want to receive the response and then parse the json so that I can get the required fields.

I get the following errorError

Resource Java method invocation error Error on Weblogic server restart

  1. Rest service has been deployed on weblogic server. On server restart rest service apis returns resource java method invocation error. Strack trace is as below:

]] Root cause of ServletException.
javax.ws.rs.ProcessingException: Resource Java method invocation error.
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:147)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
Truncated. see log file for complete stacktrace
Caused By: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
Truncated. see log file for complete stacktrace

  1. Some time same error reoccurs after some time span even when there is no server restart.

Thanks.