Vaadin grid.setItems not working in propertyChange methode - java

I have created a vaadin application using vaadin 14, i have a class accordion that passes an object HandlerTest to class Grid using a propertyChange listener. The object do pass to the grid class but when i try to use grid.setItems to show it it doesn't work. grid.setItems does add the object if i add it from the constructer but don't if i add it from the propertyChange methode.
Here is the code i used for bothe classes and the main class:
the Grid class:
`
package org.vaadin.example;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
#Route("grid")
public final class GridClass extends VerticalLayout implements PropertyChangeListener {
HandlerTest ht = new HandlerTest();
List<HandlerTest> list = new ArrayList<>();
Grid<HandlerTest> grid = new Grid<>();
public GridClass() {
grid.addColumn(HandlerTest::getPattern).setHeader("Pattern");
grid.addColumn(HandlerTest::getModuleName).setHeader("Module");
grid.setItems(list);
grid.getDataProvider().refreshAll();
grid.setAllRowsVisible(true);
grid.setHeight("480px");
add(grid);
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
HandlerTest newHandler = (HandlerTest) evt.getNewValue();
ht = newHandler;
list.add(ht);
Notification.show("Value of obj :" + evt.getNewValue());
grid.getDataProvider().refreshAll();
}
}
`
here is the HandlerTest class:
`
package org.vaadin.example;
public class HandlerTest implements java.io.Serializable{
private String moduleName;
private String pattern;
private String method;
private String sourceType;
private String itemsPerPage;
private String mimesAllowed;
private String comments;
private String pSource;
public HandlerTest(String moduleName, String pattern, String method, String sourceType, String itemsPerPage, String mimesAllowed, String comments, String pSource) {
this.moduleName = moduleName;
this.pattern = pattern;
this.method = method;
this.sourceType = sourceType;
this.itemsPerPage = itemsPerPage;
this.mimesAllowed = mimesAllowed;
this.comments = comments;
this.pSource = pSource;
}
public HandlerTest() {
}
public String getModuleName() {
return moduleName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getItemsPerPage() {
return itemsPerPage;
}
public void setItemsPerPage(String itemsPerPage) {
this.itemsPerPage = itemsPerPage;
}
public String getMimesAllowed() {
return mimesAllowed;
}
public void setMimesAllowed(String mimesAllowed) {
this.mimesAllowed = mimesAllowed;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getpSource() {
return pSource;
}
public void setpSource(String pSource) {
this.pSource = pSource;
}
#Override
public String toString() {
return moduleName + "/" + pattern + "/" + method + "/" + sourceType + "/" + itemsPerPage + "/" + mimesAllowed
+ "/" + comments + "/" + pSource ;
}
public HandlerTest createHandlerFromString(HandlerTest h){
String[] handlerText = (h.toString()).split("/");
HandlerTest handler = new HandlerTest(handlerText[0], handlerText[1], handlerText[2], handlerText[3],
handlerText[4], handlerText[5], handlerText[6], handlerText[7]);
return handler;
}
}
`
i was expecting the grid to be refreshed and the item is added but nothing happened. The notification shows the object to display but the grid don't add it.

Related

error: incompatible types: <null> cannot be converted to int if (!_cursor.isNull(null)) using android room

I'm using room for my android database. here i have a many to many relationship between Customer and ServiceProvider class i used this tutorial to do it but after compiling i received this error:
/home/omid/IntelliJIDEAProjects/Accounting/app/build/generated/ap_generated_sources/debug/out/com/omidmsl/accounting/db/CustomerDAO_Impl.java:69: error: incompatible types: cannot be converted to int
if (!_cursor.isNull(null)) {
and it is mentioning to this code CustomerDAO_Impl.java (compiler created this):
package com.omidmsl.accounting.db;
import android.database.Cursor;
import androidx.collection.ArrayMap;
import androidx.room.RoomDatabase;
import androidx.room.RoomSQLiteQuery;
import androidx.room.util.CursorUtil;
import androidx.room.util.DBUtil;
import androidx.room.util.StringUtil;
import com.omidmsl.accounting.models.Business;
import com.omidmsl.accounting.models.Customer;
import com.omidmsl.accounting.models.serviceprovider.CustomerOfServiceProvider;
import java.lang.Override;
import java.lang.String;
import java.lang.StringBuilder;
import java.lang.SuppressWarnings;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
#SuppressWarnings({"unchecked", "deprecation"})
public final class CustomerDAO_Impl implements CustomerDAO {
private final RoomDatabase __db;
public CustomerDAO_Impl(RoomDatabase __db) {
this.__db = __db;
}
#Override
public List<Customer> getCustomers() {
final String _sql = "SELECT * FROM Customer";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
__db.assertNotSuspendingTransaction();
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfCustomerName = CursorUtil.getColumnIndexOrThrow(_cursor, "customerName");
final int _cursorIndexOfPhoneNumber = CursorUtil.getColumnIndexOrThrow(_cursor, "phoneNumber");
final List<Customer> _result = new ArrayList<Customer>(_cursor.getCount());
while(_cursor.moveToNext()) {
final Customer _item;
_item = new Customer();
final String _tmpCustomerName;
_tmpCustomerName = _cursor.getString(_cursorIndexOfCustomerName);
_item.setCustomerName(_tmpCustomerName);
final String _tmpPhoneNumber;
_tmpPhoneNumber = _cursor.getString(_cursorIndexOfPhoneNumber);
_item.setPhoneNumber(_tmpPhoneNumber);
_result.add(_item);
}
return _result;
} finally {
_cursor.close();
_statement.release();
}
}
#Override
public List<CustomerOfServiceProvider> getCustomersOfServiceProvider() {
final String _sql = "SELECT * FROM Customer";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
__db.assertNotSuspendingTransaction();
__db.beginTransaction();
try {
final Cursor _cursor = DBUtil.query(__db, _statement, true, null);
try {
final int _cursorIndexOfPhoneNumber = CursorUtil.getColumnIndexOrThrow(_cursor, "phoneNumber");
final ArrayMap<String, ArrayList<Customer>> _collectionCustomers = new ArrayMap<String, ArrayList<Customer>>();
while (_cursor.moveToNext()) {
if (!_cursor.isNull(null)) {
final String _tmpKey = _cursor.getString(null);
ArrayList<Customer> _tmpCustomersCollection = _collectionCustomers.get(_tmpKey);
if (_tmpCustomersCollection == null) {
_tmpCustomersCollection = new ArrayList<Customer>();
_collectionCustomers.put(_tmpKey, _tmpCustomersCollection);
}
}
}
_cursor.moveToPosition(-1);
__fetchRelationshipCustomerAscomOmidmslAccountingModelsCustomer(_collectionCustomers);
final List<CustomerOfServiceProvider> _result = new ArrayList<CustomerOfServiceProvider>(_cursor.getCount());
while(_cursor.moveToNext()) {
final CustomerOfServiceProvider _item;
final Business _tmpServiceProvider;
if (! (_cursor.isNull(_cursorIndexOfPhoneNumber))) {
_tmpServiceProvider = new Business();
final String _tmpPhoneNumber;
_tmpPhoneNumber = _cursor.getString(_cursorIndexOfPhoneNumber);
_tmpServiceProvider.setPhoneNumber(_tmpPhoneNumber);
} else {
_tmpServiceProvider = null;
}
ArrayList<Customer> _tmpCustomersCollection_1 = null;
if (!_cursor.isNull(null)) {
final String _tmpKey_1 = _cursor.getString(null);
_tmpCustomersCollection_1 = _collectionCustomers.get(_tmpKey_1);
}
if (_tmpCustomersCollection_1 == null) {
_tmpCustomersCollection_1 = new ArrayList<Customer>();
}
_item = new CustomerOfServiceProvider();
_item.setServiceProvider(_tmpServiceProvider);
_item.setCustomers(_tmpCustomersCollection_1);
_result.add(_item);
}
__db.setTransactionSuccessful();
return _result;
} finally {
_cursor.close();
_statement.release();
}
} finally {
__db.endTransaction();
}
}
#Override
public List<Customer> getCustomer(final String cName) {
final String _sql = "SELECT * FROM Customer WHERE customerName = ?";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
int _argIndex = 1;
if (cName == null) {
_statement.bindNull(_argIndex);
} else {
_statement.bindString(_argIndex, cName);
}
__db.assertNotSuspendingTransaction();
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfCustomerName = CursorUtil.getColumnIndexOrThrow(_cursor, "customerName");
final int _cursorIndexOfPhoneNumber = CursorUtil.getColumnIndexOrThrow(_cursor, "phoneNumber");
final List<Customer> _result = new ArrayList<Customer>(_cursor.getCount());
while(_cursor.moveToNext()) {
final Customer _item;
_item = new Customer();
final String _tmpCustomerName;
_tmpCustomerName = _cursor.getString(_cursorIndexOfCustomerName);
_item.setCustomerName(_tmpCustomerName);
final String _tmpPhoneNumber;
_tmpPhoneNumber = _cursor.getString(_cursorIndexOfPhoneNumber);
_item.setPhoneNumber(_tmpPhoneNumber);
_result.add(_item);
}
return _result;
} finally {
_cursor.close();
_statement.release();
}
}
private void __fetchRelationshipCustomerAscomOmidmslAccountingModelsCustomer(final ArrayMap<String, ArrayList<Customer>> _map) {
final Set<String> __mapKeySet = _map.keySet();
if (__mapKeySet.isEmpty()) {
return;
}
// check if the size is too big, if so divide;
if(_map.size() > RoomDatabase.MAX_BIND_PARAMETER_CNT) {
ArrayMap<String, ArrayList<Customer>> _tmpInnerMap = new ArrayMap<String, ArrayList<Customer>>(androidx.room.RoomDatabase.MAX_BIND_PARAMETER_CNT);
int _tmpIndex = 0;
int _mapIndex = 0;
final int _limit = _map.size();
while(_mapIndex < _limit) {
_tmpInnerMap.put(_map.keyAt(_mapIndex), _map.valueAt(_mapIndex));
_mapIndex++;
_tmpIndex++;
if(_tmpIndex == RoomDatabase.MAX_BIND_PARAMETER_CNT) {
__fetchRelationshipCustomerAscomOmidmslAccountingModelsCustomer(_tmpInnerMap);
_tmpInnerMap = new ArrayMap<String, ArrayList<Customer>>(RoomDatabase.MAX_BIND_PARAMETER_CNT);
_tmpIndex = 0;
}
}
if(_tmpIndex > 0) {
__fetchRelationshipCustomerAscomOmidmslAccountingModelsCustomer(_tmpInnerMap);
}
return;
}
StringBuilder _stringBuilder = StringUtil.newStringBuilder();
_stringBuilder.append("SELECT `Customer`.`customerName` AS `customerName`,`Customer`.`phoneNumber` AS `phoneNumber`,_junction.`businessName` FROM `Service` AS _junction INNER JOIN `Customer` ON (_junction.`customerName` = `Customer`.`customerName`) WHERE _junction.`businessName` IN (");
final int _inputSize = __mapKeySet.size();
StringUtil.appendPlaceholders(_stringBuilder, _inputSize);
_stringBuilder.append(")");
final String _sql = _stringBuilder.toString();
final int _argCount = 0 + _inputSize;
final RoomSQLiteQuery _stmt = RoomSQLiteQuery.acquire(_sql, _argCount);
int _argIndex = 1;
for (String _item : __mapKeySet) {
if (_item == null) {
_stmt.bindNull(_argIndex);
} else {
_stmt.bindString(_argIndex, _item);
}
_argIndex ++;
}
final Cursor _cursor = DBUtil.query(__db, _stmt, false, null);
try {
final int _itemKeyIndex = 2; // _junction.businessName;
if (_itemKeyIndex == -1) {
return;
}
final int _cursorIndexOfCustomerName = CursorUtil.getColumnIndex(_cursor, "customerName");
final int _cursorIndexOfPhoneNumber = CursorUtil.getColumnIndex(_cursor, "phoneNumber");
while(_cursor.moveToNext()) {
if (!_cursor.isNull(_itemKeyIndex)) {
final String _tmpKey = _cursor.getString(_itemKeyIndex);
ArrayList<Customer> _tmpRelation = _map.get(_tmpKey);
if (_tmpRelation != null) {
final Customer _item_1;
_item_1 = new Customer();
if (_cursorIndexOfCustomerName != -1) {
final String _tmpCustomerName;
_tmpCustomerName = _cursor.getString(_cursorIndexOfCustomerName);
_item_1.setCustomerName(_tmpCustomerName);
}
if (_cursorIndexOfPhoneNumber != -1) {
final String _tmpPhoneNumber;
_tmpPhoneNumber = _cursor.getString(_cursorIndexOfPhoneNumber);
_item_1.setPhoneNumber(_tmpPhoneNumber);
}
_tmpRelation.add(_item_1);
}
}
}
} finally {
_cursor.close();
}
}
}
and here is the rest of my codes:
Customer.java:
package com.omidmsl.accounting.models;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity(tableName = "Customer")
public class Customer {
public static final String KEY_NAME = "customer_name";
public static final String KEY_PHONE_NUMBER = "phone_number";
#NonNull
#PrimaryKey
private String customerName;
private String phoneNumber;
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
CustomerDAO.java:
package com.omidmsl.accounting.db;
import androidx.room.Dao;
import androidx.room.Query;
import androidx.room.Transaction;
import com.omidmsl.accounting.models.Customer;
import com.omidmsl.accounting.models.serviceprovider.CustomerOfServiceProvider;
import java.util.List;
#Dao
public interface CustomerDAO {
#Query("SELECT * FROM Customer")
public List<Customer> getCustomers();
#Transaction
#Query("SELECT * FROM Customer")
public List<CustomerOfServiceProvider> getCustomersOfServiceProvider();
#Query("SELECT * FROM Customer WHERE customerName = :cName")
public List<Customer> getCustomer(String cName);
}
Business.java:
package com.omidmsl.accounting.models;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.*;
#Entity(tableName = "Business")
public class Business {
public static final String KEY_TYPE = "type";
public static final String KEY_NAME = "business_name";
public static final String KEY_PHONE_NUMBER = "phone_number";
private int type;
#PrimaryKey
#NonNull
private String businessName;
private String phoneNumber;
#Ignore
private long costs;
#Ignore
private long buys;
public Business(int type) {
this.type = type;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Business() {
businessName = "";
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public long getCosts() {
return costs;
}
public void setCosts(long costs) {
this.costs = costs;
}
public long getBuys() {
return buys;
}
public void setBuys(long buys) {
this.buys = buys;
}
}
ServiceProviderDAO.java:
package com.omidmsl.accounting.db;
import androidx.room.Dao;
import androidx.room.Query;
import androidx.room.Transaction;
import com.omidmsl.accounting.models.serviceprovider.ServiceProviderOfCustomer;
import java.util.List;
#Dao
public interface ServiceProviderDAO {
#Transaction
#Query("SELECT * FROM Business")
public List<ServiceProviderOfCustomer> getServiceProvidersOfCustomer();
}
CustomersOfServiceProvider.java:
package com.omidmsl.accounting.models.serviceprovider;
import androidx.room.*;
import com.omidmsl.accounting.models.Business;
import com.omidmsl.accounting.models.Customer;
import java.util.List;
public class CustomerOfServiceProvider {
#Embedded
private Business serviceProvider;
#Relation(
parentColumn = "businessName",
entityColumn = "customerName",
associateBy = #Junction(Service.class)
)
private List<Customer> customers;
public Business getServiceProvider() {
return serviceProvider;
}
public void setServiceProvider(Business serviceProvider) {
this.serviceProvider = serviceProvider;
}
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
}
please help me
This has nothing to do with the problem described by the original poster, but if you got here via Google search, here is something that might be relevant.
I recently updated Room from 2.4.x to 2.5.x and encountered error: incompatible types: <null> cannot be converted to int.
I had to replace androidx.room.OnConflictStrategy.REPLACE with androidx.room.OnConflictStrategy.Companion.REPLACE to fix.
thank you #ianhanniballake. problem solved!.
in CustomerDAO file i found this problem:
#Transaction
#Query("SELECT * FROM Customer")
public List<CustomerOfServiceProvider> getCustomersOfServiceProvider();
type of this list must be ServiceProvidersOfCustomer:
#Transaction
#Query("SELECT * FROM Customer")
public List<ServiceProviderOfCustomer> getServiceProvidersOfCustomer();
Like #solamour I also upgraded to room 2.5.x but my problem was this line:
#ColumnInfo(name = "elapsedTime", typeAffinity = INTEGER, defaultValue = "0")
And I changed it to:
#ColumnInfo(name = "elapsedTime", typeAffinity = ColumnInfo.Companion.INTEGER, defaultValue = "0")

RestTemplate returning null when serialized to POJO

I was following the start-up guide of at spring website https://spring.io/guides/gs/consuming-rest/.
I am not following the exact tutorial in the sense that I am using another endpoint: http://www.omdbapi.com?s=rush.
I am having an issue with JSON conversion to POJO. I am not getting any error or exceptions. Could someone point out where am I going wrong?
You can find the complete code here
Here are my POJOs:
package com.sample.restapi.model;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown=true)
public class SearchResponse {
private List<Search> search;
private String totalResults;
private String response;
public SearchResponse() {
}
public List<Search> getSearch() {
return search;
}
public void setSearch(List<Search> search) {
this.search = search;
}
public String getTotalResults() {
return totalResults;
}
public void setTotalResults(String totalResults) {
this.totalResults = totalResults;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
#Override
public String toString() {
return "SearchResponse [search=" + search + ", totalResults=" + totalResults + ", response=" + response + "]";
}
}
Here is the Search.java
package com.sample.restapi.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown=true)
public class Search {
private String title;
private String year;
private String imdbID;
private String type;
private String poster;
public Search() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getImdbID() {
return imdbID;
}
public void setImdbID(String imdbID) {
this.imdbID = imdbID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPoster() {
return poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
#Override
public String toString() {
return "Search [title=" + title + ", year=" + year + ", imdbID=" + imdbID + ", type=" + type + ", poster="
+ poster + "]";
}
}
Here is the driver class.
package com.sample.restapi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;
import com.sample.restapi.model.SearchResponse;
#SpringBootApplication
public class ConsumerApplication {
private static final Logger log = LoggerFactory.getLogger(ConsumerApplication.class);
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
SearchResponse searchResponse = restTemplate.getForObject("http://www.omdbapi.com?s=rush", SearchResponse.class);
log.info(searchResponse.toString());
}
}
The console output is :
14:34:12.941 [main] INFO com.sample.restapi.ConsumerApplication - SearchResponse [search=null, totalResults=344, response=null]
You are missing correct identifiers for the properties in the json, there are differences in the response and your classes in the Capital and lower case letters. Use #JsonProperty in your classes.
#JsonProperty("Search")
private List<Search> search = new ArrayList<Search>();
private String totalResults;
#JsonProperty("Response")
private String response;
you should also add #JsonProperty annotations in the Search class.

how to populate jcombobox with arrays that match specific criteria

When i try my code below the list isn't be populated with the specific arrays please help i'm pretty new to coding GUI in netbeans
private void bookingListJCBActionPerformed(java.awt.event.ActionEvent evt) {
for(int i = 0;i<dataSource.getBookingList().size();i++){
Bookings tempBooking = dataSource.getBookingList().get(i);
boolean tempFinish = tempBooking.getFinish();
String tempMechanic = tempBooking.getMechanic();
String tempClerk = tempBooking.getClerk();
String tempService = tempBooking.getService();
if(tempFinish == true){
bookingListJCB.addItem(tempBooking);
mechanicJTF.setText(tempMechanic);
seriveceClerkJTF.setText(tempMechanic);
serviceJTF.setText(""+tempService );
finishJTF.setText(""+tempFinish);
}
}
// TODO add your handling code here:
}
Here is the Bookings class how i don't know why the combo box isn't displaying anything
public class Bookings {
private String vehicle;
private String clerk;
private String service;
private String mechanic;
private boolean finish;
public Bookings() {
}
public Bookings(String vehicle, String clerk, String service, String mechanic, boolean finish) {
this.vehicle = vehicle;
this.clerk = clerk;
this.service = service;
this.mechanic = mechanic;
this.finish = finish;
}
public String getVehicle() {
return vehicle;
}
public void setVehicle(String vehicle) {
this.vehicle = vehicle;
}
public String getClerk() {
return clerk;
}
public void setClerk(String clerk) {
this.clerk = clerk;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getMechanic() {
return mechanic;
}
public void setMechanic(String mechanic) {
this.mechanic = mechanic;
}
public boolean getFinish() {
return finish;
}
public void setFinish(boolean finish) {
this.finish = finish;
}
#Override
public String toString() {
return "Bookings{" + "vehicle=" + vehicle + ", clerk=" + clerk + ", service=" + service + ", mechanic=" + mechanic + ", finish=" + finish + '}';
}
}

Scala: Java to Scala, how to eliminate setters and getters and reduce code size

Update: After suggestion from one of the experts here, I have cleaned up the following Java code:
There is a class called MyRespModifier and it holds two inner static classes called ResponseMail and Response
I have rewritten this code Scala as an exercise. Scala version: 2.11.2. I am not happy with the results. It resembles Java, and looks like it could do with a large dose of idiomatic Scala from the ground up. I would like to accomplish a reduction in the no of lines and also on inspection of the code it should stand out as elegant Scala code.At least my goal is to understand how some Java constructs can be rewritten in idiomatic Scala.
The Scala equivalent is posted after the Java code:
import java.util.ArrayList;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.io.FileInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.ContentType;
public class MyRespModifier {
private static final String VERSION = "1.0.0";
private static final String USER_AGENT = "myuseragent/"+ VERSION + "java";
private static final String ARG_TO = "to[%d]";
private static final String ARG_TONAME = "toname[%d]";
private static final String ARG_CC = "cc[%d]";
private static final String ARG_FROM = "from";
private static final String ARG_FROMNAME = "fromname";
private static final String ARG_REPLYTO = "replyto";
private static final String ARG_SUBJECT = "subject";
private static final String ARG_CONTENTS = "content[%s]";
private static final String ARG_MYSMTPAPI = "x-respModifierSmtpApi";
private String apikey;
private String apivalue;
private String apiUrlBasePath;
private String port;
private String endpoint;
private CloseableHttpClient client;
public MyRespModifier() {
this.apiUrlBasePath = "api/responseshaper/response";
this.endpoint = "/myapi/mymail.dispatch.json";
this.client = HttpClientBuilder.create().setUserAgent(USER_AGENT).build();
}
public MyRespModifier setUrl(String url) {
this.apiUrlBasePath = apiUrlBasePath;
return this;
}
public MyRespModifier setEndpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public MyRespModifier setClient(CloseableHttpClient client) {
this.client = client;
return this;
}
public HttpEntity constructRespBody(ResponseEmail respEmail) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("api_user", this.apikey);
builder.addTextBody("api_key", this.apivalue);
String[] tos = respEmail.getTos();
String[] tonames = respEmail.getToNames();
String[] ccs = respEmail.getCcs();
if (tos.length == 0) {
builder.addTextBody(String.format(ARG_TO, 0), respEmail.getFrom(), ContentType.create("text/plain", "UTF-8"));
}
for (int i = 0, len = tos.length; i < len; i++)
builder.addTextBody(String.format(ARG_TO, i), tos[i], ContentType.create("text/plain", "UTF-8"));
for (int i = 0, len = tonames.length; i < len; i++)
builder.addTextBody(String.format(ARG_TONAME, i), tonames[i], ContentType.create("text/plain", "UTF-8"));
for (int i = 0, len = ccs.length; i < len; i++)
builder.addTextBody(String.format(ARG_CC, i), ccs[i], ContentType.create("text/plain", "UTF-8"));
if (respEmail.getContentIds().size() > 0) {
Iterator it = respEmail.getContentIds().entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
builder.addTextBody(String.format(ARG_CONTENTS, entry.getKey()), (String) entry.getValue());
}
}
if (respEmail.getFrom() != null && !respEmail.getFrom().isEmpty())
builder.addTextBody(ARG_FROM, respEmail.getFrom(), ContentType.create("text/plain", "UTF-8"));
if (respEmail.getFromName() != null && !respEmail.getFromName().isEmpty())
builder.addTextBody(ARG_FROMNAME, respEmail.getFromName(), ContentType.create("text/plain", "UTF-8"));
if (respEmail.getReplyTo() != null && !respEmail.getReplyTo().isEmpty())
builder.addTextBody(ARG_REPLYTO, respEmail.getReplyTo(), ContentType.create("text/plain", "UTF-8"));
if (respEmail.getSubject() != null && !respEmail.getSubject().isEmpty())
builder.addTextBody(ARG_SUBJECT, respEmail.getSubject(), ContentType.create("text/plain", "UTF-8"));
String tmpString = respEmail.respModifierSmtpApi.jsonString();
if (!tmpString.equals("{}"))
builder.addTextBody(ARG_MYSMTPAPI, tmpString, ContentType.create("text/plain", "UTF-8"));
return builder.build();
} //end of method constructRespBody
public MyRespModifier.Response send(ResponseEmail respMail) throws RespModifierException {
HttpPost httppost = new HttpPost(this.apiUrlBasePath + this.endpoint);
httppost.setEntity(this.constructRespBody(respMail));
try {
HttpResponse res = this.client.execute(httppost);
return new MyRespModifier.Response(res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity()));
} catch (IOException e) {
throw new RespModifierException(e);
}
}
//*********************************************************************
public static class ResponseEmail {
private MyExperimentalApi respModifierSmtpApi;
private ArrayList<String> to;
private ArrayList<String> toname;
private ArrayList<String> cc;
private String from;
private String fromname;
private String replyto;
private String subject;
private String text;
private Map<String, String> contents;
private Map<String, String> headers;
public ResponseEmail () {
this.respModifierSmtpApi = new MyExperimentalApi();
this.to = new ArrayList<String>();
this.toname = new ArrayList<String>();
this.cc = new ArrayList<String>();
this.contents = new HashMap<String, String>();
this.headers = new HashMap<String, String>();
}
public ResponseEmail addTo(String to) {
this.to.add(to);
return this;
}
public ResponseEmail addTo(String[] tos) {
this.to.addAll(Arrays.asList(tos));
return this;
}
public ResponseEmail addTo(String to, String name) {
this.addTo(to);
return this.addToName(name);
}
public ResponseEmail setTo(String[] tos) {
this.to = new ArrayList<String>(Arrays.asList(tos));
return this;
}
public String[] getTos() {
return this.to.toArray(new String[this.to.size()]);
}
public ResponseEmail addSmtpApiTo(String to) {
this.respModifierSmtpApi.addTo(to);
return this;
}
public ResponseEmail addSmtpApiTo(String[] to) {
this.respModifierSmtpApi.addTos(to);
return this;
}
public ResponseEmail addToName(String toname) {
this.toname.add(toname);
return this;
}
public ResponseEmail addToName(String[] tonames) {
this.toname.addAll(Arrays.asList(tonames));
return this;
}
public ResponseEmail setToName(String[] tonames) {
this.toname = new ArrayList<String>(Arrays.asList(tonames));
return this;
}
public String[] getToNames() {
return this.toname.toArray(new String[this.toname.size()]);
}
public ResponseEmail addCc(String cc) {
this.cc.add(cc);
return this;
}
public ResponseEmail addCc(String[] ccs) {
this.cc.addAll(Arrays.asList(ccs));
return this;
}
public ResponseEmail setCc(String[] ccs) {
this.cc = new ArrayList<String>(Arrays.asList(ccs));
return this;
}
public String[] getCcs() {
return this.cc.toArray(new String[this.cc.size()]);
}
public ResponseEmail setFrom(String from) {
this.from = from;
return this;
}
public String getFrom() {
return this.from;
}
public ResponseEmail setFromName(String fromname) {
this.fromname = fromname;
return this;
}
public String getFromName() {
return this.fromname;
}
public ResponseEmail setReplyTo(String replyto) {
this.replyto = replyto;
return this;
}
public String getReplyTo() {
return this.replyto;
}
public ResponseEmail setSubject(String subject) {
this.subject = subject;
return this;
}
public String getSubject() {
return this.subject;
}
public ResponseEmail setText(String text) {
this.text = text;
return this;
}
public String getText() {
return this.text;
}
public JSONObject getFilters() {
return this.respModifierSmtpApi.getFilters();
}
public ResponseEmail addContentId(String attachmentName, String cid) {
this.contents.put(attachmentName, cid);
return this;
}
public Map getContentIds() {
return this.contents;
}
public ResponseEmail addHeader(String key, String val) {
this.headers.put(key, val);
return this;
}
public Map getHeaders() {
return this.headers;
}
public MyExperimentalApi getSMTPAPI() {
return this.respModifierSmtpApi;
}
}
public static class Response {
private int code;
private boolean success;
private String message;
public Response(int code, String msg) {
this.code = code;
this.success = code == 200;
this.message = msg;
}
public int getCode() {
return this.code;
}
public boolean getStatus() {
return this.success;
}
public String getMessage() {
return this.message;
}
}//end of class Response
You can change the imports to save some lines
import java.util.Arrays
import java.util.HashMap
import java.util.Iterator
becomes
import java.util.{Arrays, HashMap, Iterator}
The getters and setters can be generated for you. This is a feature of a Scala class if you declare the constructor parameter with val or var.
A simplified version of your class becomes:
class ResponseEmail(var to: ArrayList[String], var cc: ArrayList[String])
This getters are cc and to and the setters are cc_= and to_=
scala> res6.
asInstanceOf cc cc_= isInstanceOf to toString to_=

Malformed URL no protocol error [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
java.net.MalformedURLException: no protocol: "localhost/uatpw/ActiveTransaction"?isx=E13F42EC5E38
at java.net.URL.<init>(URL.java:567)
at java.net.URL.<init>(URL.java:464)
at java.net.URL.<init>(URL.java:413)
Malformed URL exception when reading data from url containing localhost.
Actually my program is as below
package bll.sap;
import java.net.MalformedURLException;
import utility.PropertyUtility;
public class GetActiveData
{
public static void main(String[] args) {
String sapURL = "";
try {
sapURL = PropertyUtility.getSapURL();
//Get Summary Data
SapDataSync sapDataSync = new SapDataSync();
//sapDataSync.readTransactionJsonFromUrl(sapURL+"?isx=false");
sapDataSync.readTransactionJsonFromUrl(sapURL+"?isx=E13F42EC5E38");
}
catch(MalformedURLException me)
{
me.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
AND
package bll.sap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import utility.Utility;
import com.google.code.morphia.Datastore;
import dal.GetMorphiaDB;
public class SapDataSync
{
private void saveSapTransaction(List<TransactionUnit> sapTransaction){
GetMorphiaDB morphia;
try {
morphia = GetMorphiaDB.getInstance();
Datastore ds = morphia.getDs();
ds.save(sapTransaction);
}catch (Exception e) {
e.printStackTrace();
}
}
private void createSapTransaction(String transactionJson){
JSONObject jsonObj = JSONObject.fromObject(transactionJson);
JSONArray transactionUnits = jsonObj.getJSONArray("TRANSACTION");
List<ActiveUnit> transactionList = new ArrayList<ActiveUnit>();
for(int i = 0; i < transactionUnits.size() ; i++){
JSONObject jsn = transactionUnits.getJSONObject(i);
JSONObject jsnFeed = transactionUnits.getJSONObject(i);
ActiveUnit transactionUnit = new ActiveUnit(
jsn.getString("listEditions"),
jsn.getString("listPackage"),
//Double.parseDouble(jsn.getString("YIELD")),
//Double.parseDouble(jsn.getString("QUANTITY")),
//Double.parseDouble(jsn.getString("VALUE")),
jsn.getString("referenceID")
//jsn.getString("PRICEGROUP"),
//jsn.getString("PAGE"),
//Utility.getCalendarTime(jsn.getString("PUBDATE"), "dd-MM-yyyy"),
//jsn.getString("CLIENTNAME"),
//jsn.getString("CLIENTCODE"),
// new Date().getTime(),
//jsn.getString("BOOKINGUNITNAME"),
//jsn.getString("BCCNAME"),
//jsn.getString("PAGENAME"),
// jsn.getString("PRICEGROUPNAME"),
// jsn.getString("ORDER"),
// jsn.getString("PAGE_LH_RH")
);
transactionList.add(transactionUnit);
System.out.println(transactionList);
}
System.out.println(transactionList.size());
if (transactionList.size() > 0) {
//saveSapTransaction(transactionList);
}
}
public void readTransactionJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
createSapTransaction(sb.toString());
} finally {
is.close();
}
}
}
AND
package bll.sap;
import java.io.Serializable;
import java.util.Date;
import org.bson.types.ObjectId;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
#Entity("SapTransaction")
public class ActiveUnit implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private ObjectId id;
private Long tilCreationDate;
private String clientName;
private String clientCode;
private String listEditions;
private Long date;
private String listPackage;
private String bookingUnitName;
private String referenceID;
private String bccName;
private String page;
private String pageName;
private String priceGroup;
private String pgName;
private Double yield;
private Double qty;
private Double value;
private String order;
private String pageType;
public ActiveUnit() {
}
public ActiveUnit(String listEdtions, String listPackage, /*Double yield,
Double qty, Double value,*/ String referenceID /*, String priceGroup,
String page, Long date,String clientName,
String clientCode,Long tilCreationDate,String bookingUnitName,String bccName,String pageName,String pgName,String order,String pageType*/) {
this.listEditions = listEdtions;
this.listPackage = listPackage;
//this.yield = yield;
//this.qty = qty;
//this.value = value;
this.referenceID = referenceID;
//this.priceGroup = priceGroup;
//this.page = page;
//this.date = date;
//this.clientName = clientName;
//this.clientCode = clientCode;
//this.tilCreationDate = tilCreationDate;
//this.setBookingUnitName(bookingUnitName);
//this.bccName = bccName;
//this.pageName = pageName;
//this.pgName = pgName;
//this.order = order;
//this.pageType = pageType;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientCode() {
return clientCode;
}
public void setClientCode(String clientCode) {
this.clientCode = clientCode;
}
public void setId(ObjectId id) {
this.id = id;
}
public ObjectId getId() {
return id;
}
public void setTilCreationDate(Long tilCreationDate) {
this.tilCreationDate = tilCreationDate;
}
public Long getTilCreationDate() {
return tilCreationDate;
}
public String getreferenceID() {
return referenceID;
}
public void setreferenceID(String referenceID) {
this.referenceID = referenceID;
}
public String getPriceGroup() {
return priceGroup;
}
public void setPriceGroup(String priceGroup) {
this.priceGroup = priceGroup;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
public String getListEditions() {
return listEditions;
}
public void setVertical(String listEditions) {
this.listEditions = listEditions;
}
public String getListPackage() {
return listPackage;
}
public void setListPackage(String listPackage) {
this.listPackage = listPackage;
}
public Double getYield() {
return yield;
}
public void setYield(Double yield) {
this.yield = yield;
}
public Double getQty() {
return qty;
}
public void setQty(Double qty) {
this.qty = qty;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public void setBookingUnitName(String bookingUnitName) {
this.bookingUnitName = bookingUnitName;
}
public String getBookingUnitName() {
return bookingUnitName;
}
public String getBccName() {
return bccName;
}
public void setBccName(String bccName) {
this.bccName = bccName;
}
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
public String getPgName() {
return pgName;
}
public void setPgName(String pgName) {
this.pgName = pgName;
}
#Override
public String toString() {
String unit = "{ " +
//"ClientCode: " + this.clientCode+
//",TILCreation Date: " + new Date(this.tilCreationDate)+
//",ClientName: "+ this.clientName+
"listEditions: " + this.listEditions+
",listPackage: "+ this.listPackage+
//",BookingUnitName: "+ this.bookingUnitName+
//",Yield: " + this.yield+
//",QTY: " + this.qty+
//",Value: " + this.value+
",referenceID: " + this.referenceID+
//",Price Group: " + this.priceGroup+
//",BCCName: " + this.bccName+
//",PageName: " + this.pageName+
//",PriceGroupName: " + this.pgName+
//",Page: " + this.page+
//",PageType: " + this.pageType+
//",Order: " + this.order+
//",PublishDate: " + new Date(this.date) +
" }";
return unit;
}
public void setOrder(String order) {
this.order = order;
}
public String getOrder() {
return order;
}
public void setPageType(String pageType) {
this.pageType = pageType;
}
public String getPageType() {
return pageType;
}
}
First, make sure you have the protocol set for your request.
Second, make sure that the String containing the URL is URL-encoded. I.e. the URL doesn't have any spaces and other special characters - these should be encoded (space is %20 etc).
Given that the two above are met, your program should not throw an exception from the java.net.URL class.
Looking at the exception above, you'll just have to set the protocol (http://), but do make sure that you encode your URL address strings properly or else you'll get exceptions from other parts of your program.
Also, adding http:// to the following string will also result in a MalformedURLException:
"localhost/uatpw/ActiveTransaction"?isx=E13F42EC5E38 as your URL would contain special characters (" in this case) which would need to be encoded.
To provide a valid URL you should make sure that the quotes are stripped from your URL's server and path segments areas:
localhost/uatpw/ActiveTransaction?isx=E13F42EC5E38. Prepeding http:// to this will result in a valid URL.
You are missing the protocol (e.g. http://) in front of localhost.
The welformed URL could be http://localhost/uatpw/ActiveTransaction
This is not a question. What are you trying to do?
But otherwise, "localhost/uatpw/ActiveTransaction" is not a valid URL. An url must start with a protocol (http, https, ftp, etc.).
You should try with:
http://localhost/uatpw/ActiveTransaction

Categories