Problem in getting attributes from webservice to servlet when the return type of operation in webservice is STRING [] - netbeans

I made a Webservice Operation whose return type is STRING []
Following is the code
#WebMethod(operationName = "authorize")
public String [] authorize(#WebParam(name = "Username")
String Username) {
CAuthorization CA = new CAuthorization();
String [] Result= null;
try {
Result = CA.CheckAuthorization(Username);
} catch (SQLException ex) {
Logger.getLogger(WS_Authentication.class.getName()).log(Level.SEVERE, null, ex);
}
**return Result;**
}
And then i made a Servlet
The code of the servlet thing is :
try { // Call Web Service Operation
java.lang.String result = null;
result = port.authorize(Username);
out.println("Result = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
Problem is in my WEbservice Code in RETURN STATEMENT i have attributes of any table
and i want to take these attributes to servlet so that i can see them on my front end
but what im getting here is the only the LAST ATTRIBUTE
Thanks!

This is the way u can handle Webservice Operation of String Return type
#WebMethod(operationName = "authorize")
public String authorize(#WebParam(name = "Username")
String Username) {
CAuthorization CA = new CAuthorization();
StringBuffer result = new StringBuffer();
try {
if (CA.CheckAuthorization(Username).length > 0) {
result.append(CA.CheckAuthorization(Username)[0]);
for (int i = 1; i < CA.CheckAuthorization(Username).length; i++) {
result.append(",");
result.append(CA.CheckAuthorization(Username)[i]);
}
}
} catch (SQLException ex) {
Logger.getLogger(WS_Authentication.class.getName()).log(Level.SEVERE, null, ex);
}
//TODO write your implementation code here:
return result.toString();
}
}

Related

FlyWay NoClassDefFoundError

When migrating using BaseJavaMigration
You need to parse the json string and get the value
For this I use GSON
private String getArtifactVersion(InputStream inputStream) {
String jsonTemplate = "";
try {
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, Charset.forName("UTF-8"));
jsonTemplate = writer.toString();
} catch (IOException ex) {
log.error("Error read file " + ex.getMessage(), ex);
}
String artifactVersion = "";
JsonObject jsonObject = new JsonParser().parse(jsonTemplate).getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("Parameters");
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject arrObject = jsonArray.get(i).getAsJsonObject();
log.info(arrObject.getAsString());
// if (arrObject.get.equals("ArtifactVersion")) {
// artifactVersion = arrObject.getString("Default");
// break;
// }
}
log.info(artifactVersion);
return artifactVersion;
}
But when I try to run the gradle flywayMigrate command, I get an error
Caused by: java.lang.NoClassDefFoundError: com/google/gson/JsonParser
How can I solve this problem?
Found a solution here.
FlyWay issues

Javafx Task for Bluetooth data reciever

I am creating javafx application where I have this case that I need to listen for data sent over Bluetooth.
I have one fxml window on which I need to initialize Bluetooth and start listening from data.
Following is my Code for fxml controller:
//all imports
public class NewBarcodeInvoicePaneController implements Initializable{
private BluetoothController bc;
public BluetoothController getBc() {
return bc;
}
#Override
public void initialize(URL location, ResourceBundle resources) {
try {
bc = new BluetoothController();
new Thread(bc).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
And BluetoothController is task where I initialize bluettoth and listen to the data
public class BluetoothController extends Task<Void> {
#Override
protected Void call() throws Exception {
LocalDevice local = null;
StreamConnectionNotifier notifier;
StreamConnection connection = null;
// setup the server to listen for connection
try {
local = LocalDevice.getLocalDevice();
try {
local.setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException e) {
}
UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (Exception e) {
e.printStackTrace();
return null;
}
try {
System.err.println("THIS IS HAPENING");
connection = notifier.acceptAndOpen();
System.err.println("HAPENING???????????????????????????");
InputStream inputStream = connection.openInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String lineRead = bReader.readLine();
connection.close();
inputStream.close();
notifier.close();
local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
JSONParser parser = new JSONParser();
Object obj = parser.parse(lineRead);
JSONArray array = (JSONArray) obj;
array.stream().map((o) -> (String) o).forEach((stringObj) -> {
System.out.println(stringObj);
});
System.out.println("AFTER DATA RECIEVED");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
}
It Works fine if I send data over bluetooth and blocking call to notifier.acceptAndOpen() is unblocked.
My problem is when we do not pass any data and I just want to close the window I opened..
It still have blocking call open with extra thread by the task.
I tried to cancel BluetoothController task in Main controller where I open this window like following
private void openNewBarcodeInvoicePane(ActionEvent ae) {
//following are custom classes to open windows from fxml and getting controller back for further manipulation
PostoryModalWindow modalWindow = new PostoryModalWindow();
modalWindow.openNewModalPaneWithParent("New Invoice", "fxml/newbarcodeinvoicepane.fxml", ae);
//getting controller object
NewBarcodeInvoicePaneController controller = (NewBarcodeInvoicePaneController) modalWindow.getDswFromController();
controller.getWindowStage().showAndWait();
BluetoothController bc = controller.getBc();
if(bc != null){
System.err.println("CANCELLING");
bc.cancel(true);
}
}
But it doesn't throw InterrupttedExeption (In which I might have Choice to close Bluetooth thread) and after research I found that waiting on Socket doesn't work on interrupt.
Any help on this?
Thanks
Got Solution After Some Research.
I just added new task to call notifier.acceptAndOpen();
And added method to close Bluetooth notifier.
public class BluetoothController extends Task<Void> {
private final ObservableList<Item> items = FXCollections.observableArrayList();
public ObservableList<Item> getItems() {
return items;
}
StreamConnectionNotifier notifier;
#Override
protected Void call() throws Exception {
try {
BluetoothConnectionTask bct = new BluetoothConnectionTask(items);
new Thread(bct).start();
Thread.sleep(2000);
notifier = bct.getNotifier();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public void cancelandExit() {
try {
if (notifier != null) {
notifier.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Here is new task for blocking call
public class BluetoothConnectionTask extends Task<Void>{
private StreamConnectionNotifier notifier;
private StreamConnection connection;
private ObservableList<Item> items = FXCollections.observableArrayList();
public StreamConnection getConnection() {
return connection;
}
public StreamConnectionNotifier getNotifier() {
return notifier;
}
public BluetoothConnectionTask(ObservableList<Item> is){
items = is;
}
#Override
protected Void call() throws Exception {
try {
LocalDevice local = LocalDevice.getLocalDevice();
try {
local.setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException e) {
}
UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (Exception e) {
e.printStackTrace();
return null;
}
connection = notifier.acceptAndOpen();
InputStream inputStream = connection.openInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String lineRead = bReader.readLine();
connection.close();
inputStream.close();
notifier.close();
LocalDevice local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
JSONParser parser = new JSONParser();
Object obj = parser.parse(lineRead);
JSONArray array = (JSONArray) obj;
ItemDAO idao = new ItemDAO();
array.stream().map((o) -> (String) o).forEach((stringObj) -> {
String barcode = (String) stringObj;
Item i = idao.getItemByBarCode(barcode);
System.err.println("Adding Item "+i.getName());
items.add(i);
});
System.out.println("AFTER DATA RECIEVED");
return null;
}
}
Now for cancelling closing my bluetooth thread I am calling cancelandExit() after window is closed.

wicket response trimmed at the end

I have a trouble with output data in response.
#Override
protected ResourceResponse newResourceResponse(Attributes attributes) {
ResourceResponse response = new ResourceResponse();
response.setContentDisposition(ContentDisposition.INLINE);
response.disableCaching();
StringBuilder stringBuilder = new StringBuilder(DEFAULT_CONTENT_TYPE);
stringBuilder.append(";").append(charset == null ? DEFAULT_CHARSET : charset);
response.setContentType(stringBuilder.toString());
response.setLastModified(Time.now());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
fillOutputStream(outputStream);
} catch (IOException e) {
logger.error("Error when try to fill data for html report", e);
}
String message = null;
try {
message = outputStream.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
logger.warn("Unknown encoding");
message = outputStream.toString();
}
final CharSequence data = message;
response.setContentLength(data.length());
response.setWriteCallback(new WriteCallback() {
#Override
public void writeData(Attributes attributes) {
attributes.getResponse().write(data);
}
});
configureResponse(response, attributes);
return response;
}
Here data is html page which has been generated in fillOutputStream() method and transform to CharSequence.
I've logged the data and it have correct content which I expect but in the result I have trimmed at the end page.
The length of String is not necessarily equal to its byte count.
Use a CountingOutputStream instead (e.g. from guava).

GWT-RPC method returns empty list on success

I am creating a webpage having CellTable.I need to feed this table with data from hbase table.
I have written a method to retrieve data from hbase table and tested it.
But when I call that method as GWT asynchronous RPC method then rpc call succeeds but it returns nothing.In my case it returns empty list.The alert box show list's size as 0.
Following is the related code.
Please help.
greetingService.getDeviceIDData(new AsyncCallback<List<DeviceDriverBean>>(){
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
System.out.println("RPC Call failed");
Window.alert("Data : RPC call failed");
}
public void onSuccess(List<DeviceDriverBean> result) {
//on success do something
Window.alert("Data : RPC call successful");
//deviceDataList.addAll(result);
Window.alert("Result size: " +result.size());
// Add a text column to show the driver name.
TextColumn<DeviceDriverBean> nameColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
Window.alert(object.getName());
return object.getName();
}
};
table.addColumn(nameColumn, "Name");
// Add a text column to show the device id
TextColumn<DeviceDriverBean> deviceidColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
return object.getDeviceId();
}
};
table.addColumn(deviceidColumn, "Device ID");
table.setRowCount(result.size(), true);
// more code here to add columns in celltable
// Push the data into the widget.
table.setRowData(0, result);
SimplePager pager = new SimplePager();
pager.setDisplay(table);
VerticalPanel vp = new VerticalPanel();
vp.add(table);
vp.add(pager);
// Add it to the root panel.
RootPanel.get("datagridContainer").add(vp);
}
});
Code to retrieve data from hbase (server side code)
public List<DeviceDriverBean> getDeviceIDData()
throws IllegalArgumentException {
List<DeviceDriverBean> deviceidList = new ArrayList<DeviceDriverBean>();
// Escape data from the client to avoid cross-site script
// vulnerabilities.
/*
* input = escapeHtml(input); userAgent = escapeHtml(userAgent);
*
* return "Hello, " + input + "!<br><br>I am running " + serverInfo +
* ".<br><br>It looks like you are using:<br>" + userAgent;
*/
try {
Configuration config = HbaseConnectionSingleton.getInstance()
.HbaseConnect();
HTable testTable = new HTable(config, "driver_details");
byte[] family = Bytes.toBytes("details");
Scan scan = new Scan();
int cnt = 0;
ResultScanner rs = testTable.getScanner(scan);
for (Result r = rs.next(); r != null; r = rs.next()) {
DeviceDriverBean deviceDriverBean = new DeviceDriverBean();
byte[] rowid = r.getRow(); // Category, Date, Sentiment
NavigableMap<byte[], byte[]> map = r.getFamilyMap(family);
Iterator<Entry<byte[], byte[]>> itrt = map.entrySet()
.iterator();
deviceDriverBean.setDeviceId(Bytes.toString(rowid));
while (itrt.hasNext()) {
Entry<byte[], byte[]> entry = itrt.next();
//cnt++;
//System.out.println("Count : " + cnt);
byte[] qual = entry.getKey();
byte[] val = entry.getValue();
if (Bytes.toString(qual).equalsIgnoreCase("account_number")) {
deviceDriverBean.setAccountNo(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("make")) {
deviceDriverBean.setMake(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("model")) {
deviceDriverBean.setModel(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("driver_name")) {
deviceDriverBean.setName(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("premium")) {
deviceDriverBean.setPremium(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("year")) {
deviceDriverBean.setYear(Bytes.toString(val));
} else {
System.out.println("No match found");
}
/*
* System.out.println(Bytes.toString(rowid) + " " +
* Bytes.toString(qual) + " " + Bytes.toString(val));
*/
}
deviceidList.add(deviceDriverBean);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// System.out.println("Message: "+e.getMessage());
e.printStackTrace();
}
return deviceidList;
}
Could this be lazy fetching on the server side by hbase. This means if you return the list hbase won't get a trigger to actually read the list and you will simple get an empty list. I don't know a correct solution, in the past I've seen a similar problem on GAE. This could by solved by simply asking the size of the list just before returning it to the client.
I don't have the exact answer, but I have an advise. In similar situation I put my own trace to check every step in my program.
On the server side before return put : System.out.println("size of table="+deviceidList.size());
You can put this trace in the loop for deviceidList;

How can i attach multiple images with email in Blackberry?

I want to attach multiple images with email in BB. How can I do this? Does any body have an idea? please help me.Below is my code which works fine when i send only one image with email. so what modification should I make in my code for attaching multiple images.
public static void SendMailAttachment(Bitmap screenshot)
{
String htmlContent = "String" ;
try
{
Multipart mp = new Multipart();
Message msg = new Message();
Address[] addresses = {new Address("","")};
for (int i = 0; i<2 ; i++)
{
PNGEncodedImage img = PNGEncodedImage.encode(screenshot);
SupportedAttachmentPart pt = new SupportedAttachmentPart(mp, img.getMIMEType(),
"Weed.png", img.getData());
mp.addBodyPart(pt);
}
msg.setContent(mp);
msg.setContent(htmlContent);
msg.addRecipients(RecipientType.TO, addresses);
msg.setSubject("Subject");
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(msg));
}
catch (AddressException ex)
{
System.out.println("Exception -->"+ex.getMessage());
}
catch (MessagingException ex)
{
System.out.println("Exception -->"+ex.getMessage());
}
}
Thanx in advance.
following code can be used to attach multiple images or files.
public void upload()
{
Multipart mp = new Multipart();
String fileName = null;
for (int i = 0; i<2 ; i++)
{
// Dialog.alert(image.);
byte[] stream = readStream("file:///SDCard/IMG00001-20110404-1119.JPEG");
SupportedAttachmentPart sap = new SupportedAttachmentPart(mp, MIMETypeAssociations.getMIMEType("IMG00001-20110404-1119.JPEG"),"IMG00001-20110404-1119.JPEG", stream);
mp.addBodyPart(sap);
}
TextBodyPart tbp = new TextBodyPart(mp,"test bodyString");
mp.addBodyPart(tbp);
Folder folders[] = Session.getDefaultInstance().getStore().list(Folder.SENT);
Message message = new Message(folders[0]);
Address[] toAdds = new Address[1];
try {
toAdds[0] = new Address("testmailid", null);
message.addRecipients(Message.RecipientType.TO,toAdds);
// message.setFrom(new InternetAddress(_from));
// message.addRecipients(Message.RecipientType.FROM,toAdds);
message.setContent(mp);
message.setSubject("test subject");
Transport.send(message);
Dialog.alert("message send successfully.");
} catch (AddressException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
Dialog.alert(e.getMessage());
} catch (MessagingException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
private byte[] readStream(String path)
{
InputStream in = null;
FileConnection fc = null;
byte[] bytes = null;
try
{
fc = (FileConnection) Connector.open(path);
if (fc !=null && fc.exists())
{
in = fc.openInputStream();
if (in !=null)
{
bytes = IOUtilities.streamToBytes(in);
}
}
}
catch(IOException e)
{
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch(IOException e)
{
}
try
{
if (fc !=null)
{
fc.close();
}
}
catch(IOException e)
{
}
}
return bytes;
}
i have used this code. it works fine.
Just create a new SupportedAttachmentPart for each image and add them to the message with the addBodyPart method.
Once the multipart is populated with the body part and the attachment parts, call msg.setContent(mp).