Failed to upload a Document Library Entry File in Liferay DXP 7.4 - liferay

I'm currently developing a Liferay portlet that can upload some pdfs and png to the Documents and Media Repository in Liferay DXP 7.4.13 u33.
I'm trying to use the static method addFileEntry from the class DLFileEntryLocalServiceUtil. Either in its normal or deprecated mode it's not working.
I have also tried with DLAppLocalServiceUtil.addFileEntry(externalReferenceCode, userId, repositoryId, folderId, sourceFileName,mimeType, urlTitle, description, changeLog, file, expirationDate, reviewDate, serviceContext) but I got the same result.
Im getting the following errors from this request, when I call this method via an MVCActionCommand in my portlet:
ERROR [liferay/monitoring-4][ParallelDestination:59] Unable to process message {destinationName=liferay/monitoring, response=null, responseDestinationName=null,
responseId=null, payload=[{displayName=ConceptUploadUrls, portletId=com_liferay_concept_upload_urls_ConceptUploadUrlsPortlet_INSTANCE_KNuJiTyuo6gx,
requestType=ACTION, {attributes=null, companyId=20097, groupId=20121, description=null, duration=0, name=com_liferay_concept_upload_urls_ConceptUploadUrlsPortlet,
namespace=com.liferay.monitoring.Portlet, requestStatus=null, stopWatch=0:00:10.151, timeout=0, user=20125}}, {referer=http://localhost:8080/client, remoteAddr=127.0.0.1,
requestURL=, statusCode=0, userAgent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36, {attributes=null,
companyId=20097, groupId=20121, description=null, duration=10155, name=/c/portal/layout, namespace=com.liferay.monitoring.Portal, requestStatus=ERROR, stopWatch=0:00:10.155,
timeout=-1, user=20125}}, {referer=http://localhost:8080/client, remoteAddr=127.0.0.1, requestURL=, statusCode=0, userAgent=Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36, {attributes=null, companyId=20097, groupId=0, description=null, duration=10157, name=/web/guest/carga-por-url,
namespace=com.liferay.monitoring.Portal, requestStatus=ERROR, stopWatch=0:00:10.157, timeout=-1, user=null}}], values={defaultLocale=en_US, companyId=20097, groupId=0, principalName=20125,
permissionChecker=com.liferay.portal.kernel.util.TransientValue#4ff66308, siteDefaultLocale=en_US, themeDisplayLocale=en_US}}
com.liferay.portal.kernel.messaging.MessageListenerException: java.lang.NullPointerException
Caused by: java.lang.NullPointerException at com.liferay.portal.monitoring.internal.statistics.portlet.PortletStatistics.processDataSample(PortletStatistics.java:112) ~[?:?]
...
ERROR [http-nio-8080-exec-3][VirtualHostFilter:381] null
javax.servlet.ServletException: Servlet execution threw an exception
Caused by: java.lang.NoSuchMethodError: com.liferay.document.library.kernel.service.DLAppService.addFileEntry(Ljava/lang/String;
JJLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/io/File;Ljava/util/Date;Ljava/util/Date;Lcom/liferay/portal/kernel/service/ServiceContext;)Lcom/liferay/portal/kernel/repository/model/FileEntry;
at com.liferay.concept.upload.urls.portlet.action.UploadFile.uploadFile(UploadFile.java:193) ~[?:?]
...
The complete program is the following:
package com.liferay.concept.upload.urls.portlet.action;
import com.liferay.concept.upload.urls.constants.ConceptUploadUrlsPortletKeys;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.portlet.bridges.mvc.BaseMVCActionCommand;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCActionCommand;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.service.ServiceContextFactory;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.theme.ThemeDisplay;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.kernel.util.MimeTypesUtil;
import com.liferay.portal.kernel.util.PortalUtil;
import com.liferay.portal.kernel.util.WebKeys;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import com.liferay.concept.upload.urls.constants.MVCCommandNames;
import com.liferay.document.library.kernel.model.DLFileEntry;
import com.liferay.document.library.kernel.model.DLFolderConstants;
import com.liferay.document.library.kernel.service.DLFileEntryLocalServiceUtil;
import com.liferay.dynamic.data.mapping.kernel.DDMFormValues;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import org.osgi.service.component.annotations.Component;
#Component(immediate = true, property = { "javax.portlet.name=" + ConceptUploadUrlsPortletKeys.CONCEPTUPLOADURLS,
"mvc.command.name=" + MVCCommandNames.UPLOAD_FILE }, service = MVCActionCommand.class)
public class UploadFile extends BaseMVCActionCommand {
#Override
protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
try {
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
if (uploadRequest.getSize("myFile") == 0) {
SessionErrors.add(actionRequest, "error");
}
// saving the document in local
String fileName = uploadRequest.getFileName("myFile");
File file = uploadRequest.getFile("myFile");
saveDocument(file, fileName);
// readandDownload
List<String> urls = UploadUrlsFromFile(actionRequest, file);
System.out.println("urls Read: " + urls);
SessionMessages.add(actionRequest, "success");
} catch (FileNotFoundException e) {
System.out.println("EXCEPTION! Input File Not Found.");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
} catch (NullPointerException e) {
System.out.println("EXCEPTION! An Object is null");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
} catch (IOException e) {
System.out.println("EXCEPTION! Error Reading The Input File.");
SessionMessages.add(actionRequest, "error");
e.printStackTrace();
} catch (PortalException p) {
System.out.println("EXCEPTION! Portal Exception");
p.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
}
private void saveDocument(File file, String fileName) throws IOException {
File newFile = new File(folder + "_" + fileName);
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(newFile);
System.out.println("File: " + file);
System.out.println("SavedFile: " + newFile);
byte[] bytes_ = FileUtil.getBytes(file);
int i = fis.read(bytes_);
while (i != -1) {
fos.write(bytes_, 0, i);
i = fis.read(bytes_);
}
fis.close();
fos.close();
long size = newFile.length();
System.out.println("File size kb:" + (float) size / 1024);
System.out.println("File created: " + newFile.getName());
}
private List<String> UploadUrlsFromFile(ActionRequest actionRequest, File inputFile)
throws IOException, PortalException {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
String line;
List<String> urls = new ArrayList<String>();
while ((line = br.readLine()) != null) {
urls.add(line);
}
br.close();
for (String url : urls) {
String fileName = getNameForFileFromUrl(url);
// download file from the web
try {
File file = downloadFile(url, fileName);
DLFileEntry dlFileEntry = uploadFile(actionRequest, file);
} catch (NoSuchMethodError e) {
System.out.println("EXCEPTION! Error with the class method.");
SessionMessages.add(actionRequest, "error");
} catch (PortalException e) {
SessionMessages.add(actionRequest, "error");
throw (new PortalException());
} catch (FileNotFoundException e) {
System.out.println("EXCEPTION! File Not Found.");
SessionMessages.add(actionRequest, "error");
} catch (MalformedURLException e) {
System.out.println("EXCEPTION! Malformed URL.");
SessionMessages.add(actionRequest, "error");
} catch (IOException e) {
System.out.println("EXCEPTION! Error reading the File.");
SessionMessages.add(actionRequest, "error");
}
}
return urls;
}
private String getNameForFileFromUrl(String url) {
String fileName = String.valueOf(url);
int index = fileName.lastIndexOf("/");
if (index != -1) {
fileName = fileName.substring(index + 1);
}
return fileName;
}
private File downloadFile(String url, String fileName) throws MalformedURLException, IOException, FileNotFoundException {
String completePath = folder + fileName;
BufferedInputStream in = new BufferedInputStream(new URL(url).openStream());
System.out.println("URL: " + url);
FileOutputStream fileOutputStream = new FileOutputStream(completePath);
byte dataBuffer[] = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
fileOutputStream.close();
File file = new File(completePath);
System.out.println("New File Downloaded: " + completePath);
return file;
}
#SuppressWarnings("deprecation")
private DLFileEntry uploadFile(ActionRequest actionRequest, File file) throws PortalException {
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
String fileName = file.getName();
String externalReferenceCode = "";
long userId = themeDisplay.getUserId();
long groupId = themeDisplay.getScopeGroupId();
long repositoryId = groupId;
long folderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
String sourceFileName = fileName;
String mimeType = MimeTypesUtil.getContentType(file);
String title = FileUtil.stripExtension(fileName);
String urlTitle = FileUtil.stripExtension(fileName).substring(0, 10);
String description = fileName;
String changeLog = "initialization, web source";
long fileEntryType = 0;
Map<String, DDMFormValues> ddmFormValuesMap = null;
InputStream inputStream = null;
long size = file.length();
// Calendar.set
Calendar myCal = Calendar.getInstance();
myCal.set(Calendar.YEAR, 2023);
myCal.set(Calendar.MONTH, 3);
myCal.set(Calendar.DAY_OF_MONTH, 2);
// Date expirationDate = myCal.getTime(); // never expire
myCal.set(Calendar.DAY_OF_MONTH, 1);
// Date reviewDate = myCal.getTime(); // never review
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); // permissions and assets
System.out.println("size: " + size);
System.out.println("folderId: " + folderId);
System.out.println("Creating file in DL....");
DLFileEntry fileEntry = null;
try {
fileEntry = DLFileEntryLocalServiceUtil.addFileEntry(userId, groupId, repositoryId, folderId, fileName,
mimeType, fileName, "", "", 0, null, file, null, size, serviceContext);
System.out.println("file entry added");
} catch (Exception e) {
System.out.println("Exception File Entry");
e.printStackTrace();
throw (new PortalException());
}
return fileEntry;
}
private String folder = "D:\\LIFERAY-gradebook\\gradebook-workspace\\modules\\concept-upload-urls\\files\\";
}

Related

System.out.println displays blank line

Why does the below 'System.out.println'(fileEncodedString) display a blank line while the value is there when I debug and I do get an output when I decode the value and print.
byte[] fileContent = readFileToByteArray(filePath);
String fileEncodedString = Base64.getEncoder().encodeToString(fileContent);
byte[] fileDecodedString = Base64.getDecoder().decode(fileEncodedString);
System.out.println("Base64 Decoded File (Basic): " + new String(fileDecodedString, "utf-8"));
private static byte[] readFileToByteArray(String filePath) {
FileInputStream fileInputStream = null;
byte[] bytesArray = null;
try {
File file = new File(filePath);
bytesArray = new byte[(int) file.length()];
// read file into bytes[]
fileInputStream = new FileInputStream(file);
fileInputStream.read(bytesArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bytesArray;
}
Try to use below method for readFileToByteArray and pass correct file path:
static byte[] readFileToByteArray(String filePath) throws IOException {
File file = new File(filePath);
return Files.readAllBytes(file.toPath());
}
its working fine.

json string is not properly shown in android device

i am facing a issue on getting JObject, my app is working in emulator and it is not working in device. because the string is not properly converting to JObject.
E/JSON 1111﹕ parsing data {"success":1,"projects":[{"thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","duration":"3 mins","updated_at":"0000-00-00 00:00:00","keywords":"law,white sheet,pen,pencil,mini bulbs,","materials":"pen,pencil,ball,worksheet","description":"about the law bla bla","subject":"science","target":"k2","created_at":"2015-08-14 14:24:54","pid":"1","rating":"4","procedure":"procedure about this project"},{"thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","duration":"3 mins","updated_at":"0000-00-00 00:00:00","keywords":"pen,pencil,color pencil,chart,sticks","materials":"pen,pencil,color pencil,chart,sticks,etc","description":"about description of the project","subject":"science","target":"k3","created_at":"2015-08-14 14:25:16",
"pid":"2","rating":"3","procedure":"about description of the procedure"},{"thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","duration":"5 mins","updated_at":"0000-00-00 00:00:00","keywords":"pen,pencil,wire,chart,sticks","materials":"pen,pencil,color pencil,chart,sticks,eraser","description":"about description of the project","subject":"english","target":"k4","created_at":"2015-08-14 14:25:21",
....
"pid":"8","rating":"3","procedure":"about description of the procedure"}]}
the above is the output of the jsonObject, the below is the correct result showing in emulator
{"projects":[{"pid":"1","target":"k2","subject":"science","description":"about the law bla bla","duration":"3 mins","materials":"pen,pencil,ball,worksheet","procedure":"procedure about this project","keywords":"law,white sheet,pen,pencil,mini bulbs,","thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","rating":"4","created_at":"2015-08-14 14:24:54","updated_at":"0000-00-00 00:00:00"},{"pid":"2","target":"k3","subject":"science","description":"about description of the project","duration":"3 mins","materials":"pen,pencil,color pencil,chart,sticks,etc","procedure":"about description of the procedure","keywords":"pen,pencil,color pencil,chart,sticks","thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","rating":"3","created_at":"2015-08-14 14:25:16","updated_at":"0000-00-00 00:00:00"},
...
{"pid":"8","target":"k3","subject":"english","description":"to learn english tenses","duration":"3 mins","materials":"white sheet,pen,pencil,eraser","procedure":"about description of the procedure","keywords":"english,grammer,tenses","thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","rating":"3","created_at":"2015-08-18 06:45:28","updated_at":"0000-00-00 00:00:00"}],"success":1}
this is my jsonparse class code:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static String jboolean = "0";
static JSONArray jarr =null;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000 + 12000);
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type","application/json");
httpPost.setParams(httpParameters);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("Buffer 11", "Error converting result " + e.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("Buffer 22", "Error converting result " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("Buffer 33", "Error converting result " + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
//Log.e("JSON 1111 ", "parsing data " + json.toString());
} catch (Exception e) {
Log.e("Buffer Error????", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
Log.e("JSON 1111 ", "parsing data " + jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser44", "Error parsing data " + e.toString());
}
return jObj;
/// This JObj is not properly getting the json string???
// return JSON String
}
}
Is there any issues on the above code? i am facing a issue on getting JObject, my app is working in emulator and it is not working in device. because the string is not properly converting to JObject.

Java read bytes from Socket on Linux

I'm trying to send a file from my Windows machine to my Raspberry-Pi 2, and I have a client and a server. The client should be able to send a zip file over the network to my server on my linux machine. I know my client and server work on Windows, as when I run both the client and server on windows and connect using 127.0.0.1 it works perfectly. But when sending it to my Pi, nothing gets sent over the socket. Any suggestion?
Server:
package zipsd;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws Exception {
if (args.length < 3)
System.out.println("Usage: zipsd <port> <directory> <password>");
else {
int port = Integer.parseInt(args[0]);
String directory = args[1];
String password = args[2];
System.out.println("zipsd: starting server on port " + port);
System.out.println("zipsd: directory = " + directory);
ServerSocket ss = new ServerSocket(port);
System.out.println("zipsd: listening...");
while (true) {
try {
Socket client = ss.accept();
System.out
.println("zipsd: from " + client.getInetAddress());
InputStream input = client.getInputStream();
BufferedReader in = new BufferedReader(
new InputStreamReader(input));
PrintStream out = new PrintStream(client.getOutputStream());
String pwdAttempt = in.readLine();
if (pwdAttempt != null) {
if (!pwdAttempt.equals(password)) {
out.println("[SERVER] zipsd: invalid password");
} else {
out.println("[SERVER] zipsd: authenticated");
String zipName = in.readLine();
if (zipName != null) {
File zipFile = new File(directory + "/"
+ zipName);
try {
FileOutputStream fos = new FileOutputStream(
zipFile);
BufferedOutputStream bos = new BufferedOutputStream(
fos);
byte[] data = new byte[1024 * 1024 * 50];
int count;
while((count = input.read(data)) > 0)
bos.write(data, 0, count);
for(int i = 0; i < 200; i++) //to see if data gets sent, it just prints 0's :(
System.out.println(data[i]);
System.out.println("Got zip file " + zipName);
bos.flush();
fos.close();
bos.close();
out.close();
in.close();
client.close();
} catch (Exception e) {
out.println("[SERVER] zipsd: error in transfer.");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Client:
package zipsend;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main {
public static class ZipUtils {
public static void zipFolder(final File folder, final File zipFile)
throws IOException {
zipFolder(folder, new FileOutputStream(zipFile));
}
public static void zipFolder(final File folder,
final OutputStream outputStream) throws IOException {
try (ZipOutputStream zipOutputStream = new ZipOutputStream(
outputStream)) {
processFolder(folder, zipOutputStream, folder.getPath()
.length() + 1);
zipOutputStream.flush();
zipOutputStream.finish();
zipOutputStream.close();
}
}
private static void processFolder(final File folder,
final ZipOutputStream zipOutputStream, final int prefixLength)
throws IOException {
for (final File file : folder.listFiles()) {
if (file.isFile()) {
final ZipEntry zipEntry = new ZipEntry(file.getPath()
.substring(prefixLength));
zipOutputStream.putNextEntry(zipEntry);
try (FileInputStream inputStream = new FileInputStream(file)) {
byte[] buf = new byte[(int) file.length() + 1];
int read = 0;
while ((read = inputStream.read(buf)) != -1) {
zipOutputStream.write(buf, 0, read);
}
}
zipOutputStream.flush();
zipOutputStream.closeEntry();
} else if (file.isDirectory()) {
processFolder(file, zipOutputStream, prefixLength);
}
}
}
}
public static void main(String[] args) throws Exception {
if(args.length < 4)
System.out.println("Usage: zipsend <folder> <ip> <port> <password>");
else {
String toZip = args[0];
String ip = args[1];
int port = Integer.parseInt(args[2]);
String pwd = args[3];
File folderToZip = new File(toZip);
if(!folderToZip.exists()) {
System.out.println("[ERROR] invalid folder name");
System.exit(1);
}
System.out.print("[INFO] connecting... ");
Socket s = new Socket(ip, port);
System.out.println("OK.");
System.out.println("[INFO] authenticating... ");
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintStream out = new PrintStream(s.getOutputStream());
out.println(pwd);
System.out.println(in.readLine());
System.out.println();
System.out.print("[INFO] zipping " + toZip + "... ");
File zipFile = new File(System.getProperty("user.dir") + "\\" + folderToZip.getName() + ".zip");
ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zipFile));
ZipUtils.processFolder(folderToZip, zout, folderToZip.getPath().length() + 1);
zout.close();
System.out.println("OK.");
//Transfer file
out.println(zipFile.getName());
byte[] data = new byte[(int)zipFile.length()];
FileInputStream fis = new FileInputStream(zipFile);
BufferedInputStream bis = new BufferedInputStream(fis);
System.out.println("[INFO] sending zip file... ");
OutputStream os = s.getOutputStream();
int count;
while((count = bis.read(data)) > 0) {
os.write(data, 0, count);
}
os.flush();
os.close();
fis.close();
bis.close();
s.close();
System.out.println("[INFO] done. Sent " + Files.size(zipFile.toPath()) + " bytes.");
zipFile.delete();
}
}
}
InputStream input = client.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
Your problem is here. You can't use multiple inputs on a socket when one or more of them is buffered. The buffered input stream/reader will read-ahead and 'steal' data from the other stream. You need to change your protocol so you can use the same stream for the life of the socket at both ends. For example, use DataInputStream, with readUTF() for the file name and read() for the data: at the sender, use DataOutputStream, with writeUTF() for the filename and write() for the data.

Blackberry - How to consume wcf rest services

Recently i have started working on consuming wcf rest webservices in blackberry.
I have used the below two codes:
1.
URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
// passing q’s value and ie’s value
postData.append("UserName", "hsharma#seasiaconsulting.com");
postData.append("Password", "mind#123");
HttpPosst hh=new HttpPosst();
add(new LabelField("1"));
String res=hh.GetResponse("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration",postData);
add(new LabelField("2"));
add(new LabelField(res));
public String GetResponse(String url, URLEncodedPostData data)
{
this._postData = data;
this._url = url;
ConnectionFactory conFactory = new ConnectionFactory();
ConnectionDescriptor conDesc = null;
try
{
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// logMessage("Carrier coverage.");
// String carrierUid = getCarrierBIBSUid();
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
// logMessage("No Uid");
connectionString = ";deviceside=true";
}
// Check for an MDS connection instead (BlackBerry Enterprise
// Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// logMessage("MDS coverage found");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the
// user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
// logMessage("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be reachable.
else {
// logMessage("no other options found, assuming device.");
// connectionString = ";deviceside=true";
}
conDesc = conFactory.getConnection(url + connectionString);
}
catch (Exception e)
{
System.out.println(e.toString() + ":" + e.getMessage());
}
String response = ""; // this variable used for the server response
// if we can get the connection descriptor from ConnectionFactory
if (null != conDesc)
{
try
{
HttpConnection connection = (HttpConnection) conDesc.getConnection();
// set the header property
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Length",Integer.toString(data.size()));
// body content of
// post data
connection.setRequestProperty("Connection", "close");
// close
// the
// connection
// after
// success
// sending
// request
// and
// receiving
// response
// from
// the
// server
connection.setRequestProperty("Content-Type","application/json");
// we set the
// content of
// this request
// as
// application/x-www-form-urlencoded,
// because the
// post data is
// encoded as
// form-urlencoded(if
// you print the
// post data
// string, it
// will be like
// this ->
// q=remoQte&ie=UTF-8).
// now it is time to write the post data into OutputStream
OutputStream out = connection.openOutputStream();
out.write(data.getBytes());
out.flush();
out.close();
int responseCode = connection.getResponseCode();
// when this
// code is
// called,
// the post
// data
// request
// will be
// send to
// server,
// and after
// that we
// can read
// the
// response
// from the
// server if
// the
// response
// code is
// 200 (HTTP
// OK).
if (responseCode == HttpConnection.HTTP_OK)
{
// read the response from the server, if the response is
// ascii character, you can use this following code,
// otherwise, you must use array of byte instead of String
InputStream in = connection.openInputStream();
StringBuffer buf = new StringBuffer();
int read = -1;
while ((read = in.read()) != -1)
buf.append((char) read);
response = buf.toString();
}
// don’t forget to close the connection
connection.close();
}
catch (Exception e)
{
System.out.println(e.toString() + ":" + e.getMessage());
}
}
return response;
}
public boolean checkResponse(String res)
{
if(!res.equals(""))
{
if(res.charAt(0)=='{')
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
but with this code i am unable to obtain response as what the above wcf web service return
which is({"UserRegistrationResult":[{"OutputCode":"2","OutputDescription":"UserName Already Exists."}]})
Can anybody help me regarding its parsing in blackberry client end.
2.And the another code which i used is:
public class KSoapDemo extends MainScreen
{
private EditField userNametxt;
private PasswordEditField passwordTxt;
private ButtonField loginBtn;
String Username;
String Password;
public KSoapDemo()
{
userNametxt = new EditField("User Name : ", "hsharma#seasiaconsulting.com");
passwordTxt = new PasswordEditField("Password : ", "mind#123");
loginBtn = new ButtonField("Login");
add(userNametxt);
add(passwordTxt);
add(loginBtn);
loginBtn.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert("Hi Satyaseshu..!");
login();
}
});
}
private void login()
{
if (userNametxt.getTextLength() == 0 || passwordTxt.getTextLength() == 0)
{
//Dialog.alert("You must enter a username and password", );
}
else
{
String username = userNametxt.getText();
String password = passwordTxt.getText();
System.out.println("UserName... " + username);
System.out.println("Password... " + password);
boolean value = loginPArse1(username, password);
add(new LabelField("value... " + value));
}
}
public boolean onClose()
{
Dialog.alert("ADIOOO!!");
System.exit(0);
return true;
}
public boolean loginPArse1(String username, String password)
{
username=this.Username;
password=this.Password;
boolean ans = false;
String result = null;
SoapObject request = new SoapObject("http://dotnetstg.seasiaconsulting.com/","UserRegistration");
//request.addProperty("PowerValue","1000");
//request.addProperty("fromPowerUnit","kilowatts");
//request.addProperty("toPowerUnit","megawatts");
request.addProperty("userName",Username);
request.addProperty("Password", Password);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = request;
envelope.dotNet = true;
add(new LabelField("value... " + "1"));
HttpTransport ht = new HttpTransport("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration"+ConnectionInfo.getInstance().getConnectionParameters());
ht.debug = true;
add(new LabelField("value... " + "2"));
//System.out.println("connectionType is: " + connectionType);
try {
ht.call("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration", envelope);
SoapObject body = (SoapObject) envelope.bodyIn;
add(new LabelField("soap....="+body.toString()));
add(new LabelField("property count....="+body.getPropertyCount()));
// add(new LabelField("Result....="+body.getProperty("HelloWorldResult")));
//result = body.getProperty("Params").toString();
// add(new LabelField("value... " + "4"));
ans=true;
}
catch (XmlPullParserException ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
} catch (IOException ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
} catch (Exception ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
}
return ans;
}
and in return i am obtain response as net.rim.device.cldc.io.dns.DNS Exception:DNS Error
Please help me in this regard
Thanks And Regards
Pinkesh Gupta
Please have the answer for my own question helps in parsing wcf rest services developed in .net and parsed at blackberry end.
This 2 classess definitely helps in achieving the above code parsing.
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
public class ConnectionThread extends Thread
{
private boolean start = false;
private boolean stop = false;
private String url;
private String data;
public boolean sendResult = false;
public boolean sending = false;
private String requestMode = HttpConnection.POST;
public String responseContent;
int ch;
public void run()
{
while (true)
{
if (start == false && stop == false)
{
try
{
sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
else if (stop)
{
return;
}
else if (start)
{
http();
}
}
}
private void getResponseContent( HttpConnection conn ) throws IOException
{
InputStream is = null;
is = conn.openInputStream();
// Get the length and process the data
int len = (int) conn.getLength();
if ( len > 0 )
{
int actual = 0;
int bytesread = 0;
byte[] data = new byte[len];
while ( ( bytesread != len ) && ( actual != -1 ) )
{
actual = is.read( data, bytesread, len - bytesread );
bytesread += actual;
}
responseContent = new String (data);
}
else
{
// int ch;
while ( ( ch = is.read() ) != -1 )
{
}
}
}
private void http()
{
System.out.println( url );
HttpConnection conn = null;
OutputStream out = null;
int responseCode;
try
{
conn = (HttpConnection) Connector.open(url);
conn.setRequestMethod(requestMode);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Length",Integer.toString(data.length()));
conn.setRequestProperty("Connection", "close");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("SOAPAction","http://dotnetstg.seasiaconsulting.com/");
out = conn.openOutputStream();
out.write(data.getBytes());
out.flush();
responseCode = conn.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
sendResult = false;
responseContent = null;
}
else
{
sendResult = true;
getResponseContent( conn );
}
start = false;
sending = false;
}
catch (IOException e)
{
start = false;
sendResult = false;
sending = false;
}
}
public void get(String url)
{
this.url = url;
this.data = "";
requestMode = HttpConnection.GET;
sendResult = false;
sending = true;
start = true;
}
public void post(String url, String data)
{
this.url = url;
this.data = data;
requestMode = HttpConnection.POST;
sendResult = false;
sending = true;
start = true;
}
public void stop()
{
stop = true;
}
}
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.AutoTextEditField;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.DateField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.container.MainScreen;
import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;
import org.xml.sax.SAXException;
import net.rim.device.api.xml.parsers.SAXParser;
import net.rim.device.api.xml.jaxp.SAXParserImpl;
import org.xml.sax.helpers.DefaultHandler;
import java.io.ByteArrayInputStream;
import com.sts.example.ConnectionThread;
import com.sts.example.ResponseHandler;
public class DemoScreen extends MainScreen
{
private ConnectionThread connThread;
private BasicEditField response = new BasicEditField("Response: ", "");
private BasicEditField xmlResponse = new BasicEditField("xml: ", "");
private ButtonField sendButton = new ButtonField("Response");
public DemoScreen(ConnectionThread connThread)
{
this.connThread = connThread;
FieldListener sendListener = new FieldListener();
sendButton.setChangeListener(sendListener);
response.setEditable( false );
xmlResponse.setEditable( false );
add(sendButton);
add(response);
add(new SeparatorField());
add(xmlResponse);
}
public boolean onClose()
{
connThread.stop();
close();
return true;
}
private String getFieldData()
{
//{"UserName":"hsharma#seasiaconsulting.com","Password":"mind#123"}
StringBuffer sb = new StringBuffer();
sb.append("{\"UserNamepinkesh.g#cisinlabs.com\",\"Password\":\"pinkesh1985\"}");
return sb.toString();
}
class FieldListener implements FieldChangeListener
{
public void fieldChanged(Field field, int context)
{
StringBuffer sb = new StringBuffer("Sending...");
connThread.post("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration"+ConnectionInfo.getInstance().getConnectionParameters(), getFieldData());
while (connThread.sending)
{
try
{
Status.show( sb.append(".").toString() );
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (connThread.sendResult)
{
Status.show("Transmission Successfull");
xmlResponse.setText( connThread.responseContent );
try {
JSONObject jsonResponse = new JSONObject(connThread.responseContent);
JSONArray jsonArray = jsonResponse.getJSONArray("UserRegistrationResult");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject result = (JSONObject)jsonArray.get(i);
add(new LabelField("OutputCode"+result.getString("OutputCode")));
add(new LabelField("OutputDescription"+result.getString("OutputDescription")));
}
}
catch (JSONException e)
{
add(new LabelField(e.getMessage().toString()));
e.printStackTrace();
}
}
else
{
Status.show("Transmission Failed");
}
}
}
}

How to Switch to OTA Provisioning option in Wireless toolkit J2ME?

I am new to J2ME and now I have to solve one J2ME project.
Below is my login form I don't know what to do with that but it is giving me the error "javax.microedition.io.ConnectionNotFoundException: TCP open". After searching on the google I got some hint that we have to run the code on "OTA Provisioning option ".
Now I don't know how to do that. I have "Version 2.5.2 for CLDC" of WTK. Can anybody suggest me on that?
package model;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import view.Dialogs;
public class Login {
public static RecordStore rs; // Record store
static final String REC_STORE = "db_Login"; // Name of record store
static RecordEnumeration re;
private String login,password;
private int c;
public static String s1,s2,s3;
public Login()
{
if(LoginSrv.st1.equals("Invalid") && LoginSrv.st2.equals("User"))
{
System.out.println("Im from Invalid User");
new Dialogs();
}
else
{
login = LoginSrv.st1;
password = LoginSrv.st2;
c= LoginSrv.it1;
saveRecord();
}
}
public Login(String log,String pas, String ctr)
{
s1 = log;
s2 = pas;
s3 = ctr;
}
public void saveRecord()
{
try
{
rs = RecordStore.openRecordStore(REC_STORE, true );
re = rs.enumerateRecords(null, null, false);
ByteArrayOutputStream baosdata = new ByteArrayOutputStream();
DataOutputStream daosdata = new DataOutputStream(baosdata);
daosdata.writeUTF(login);
daosdata.writeUTF(password);
daosdata.writeInt(c);
byte[] record = baosdata.toByteArray();
rs.addRecord(record, 0, record.length);
System.out.println("Login record added");
}
catch(Exception e)
{
System.out.println("Im from model Login craete record"+e);
}
}
public static Login getRecord()
{
try
{
rs = RecordStore.openRecordStore(REC_STORE, true );
re = rs.enumerateRecords(null, null, false);
if(re.hasNextElement())
{
byte data[] = rs.getRecord(re.nextRecordId());
ByteArrayInputStream strmBytes = new ByteArrayInputStream(data);
DataInputStream strmDataType = new DataInputStream(strmBytes);
String log = strmDataType.readUTF();
String pass = strmDataType.readUTF();
String counter = strmDataType.readUTF();
return(new Login(log,pass,counter));
}
return null;
}
catch(Exception e)
{
System.out.println("Im from model Login loadRecord"+e);
return null;
}
}
}
-----------------------LoginSrv code ---------------------------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import com.sun.lwuit.Dialog;
import controller.AppConstants;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
/**
*
* #author sandipp
*/
public class LoginSrv {
private ServCon srv;
public static String st1,st2,log,pas;
public static int it1;
public LoginSrv(String s1, String s2)
{
log = s1;
pas = s2;
it1=0;
try
{
ByteArrayOutputStream baosdata = new ByteArrayOutputStream();
DataOutputStream daosdata = new DataOutputStream(baosdata);
daosdata.writeUTF(s1);
daosdata.writeUTF(s2);
srv = new ServCon(new AppConstants().str1,null,baosdata.toByteArray(),false,false,null);
ByteArrayOutputStream obj = (ByteArrayOutputStream)srv.startTransfer();
byte[] record = obj.toByteArray();
ByteArrayInputStream instr = new ByteArrayInputStream(record);
DataInputStream indat = new DataInputStream(instr);
if(srv.getRc() == 200)
{
String su = indat.readUTF();
if(su.equals("successfull"))
{
st1 =indat.readUTF();
st2 =indat.readUTF();
}
else
{
Dialog.show("Error",su , null,Dialog.TYPE_INFO,null,5000);
}
}
else
{
Dialog.show("Error",srv.getRc() + " " + srv.getRm(), null,Dialog.TYPE_INFO,null,5000);
}
}
catch(Exception e)
{
System.out.println("Im from LoginSrv constructor:"+e);
}
}
}

Resources