getting java.nio.BufferUnderflowException while reading dbf file after using dbaseFileWriter.write(vals); - geotools

I'm using DbaseFileReader and DBaseFileWriter to read and update records in a dbf file. When I read the file first there is no error while opening DBF file but after I write some values to DBF using below method I'm getting the following Error
I've checked the value types in Object[] array, both type and count of values are equal to dbf file fields.
public static boolean updateFeatureAtts(String shpFile, Map<String, Object> attsFeature) throws IOException {
String file = CN.getMapDataFolder() + CN.FOLDER_LAYERS + "/" + shpFile.replace(".shp", ".dbf");
DbaseFileWriter dbaseFileWriter = null;
DbaseFileReader dbaseFileReader = null;
ReadableByteChannel dbfChannel = null;
WritableByteChannel writableByteChannel = null;
FileOutputStream fileOutputStream = null;
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
dbfChannel = Channels.newChannel(inputStream);
dbaseFileReader = new DbaseFileReader(dbfChannel, true, Charset.forName("Windows-1256"));
DbaseFileHeader header = dbaseFileReader.getHeader();
for (Iterator<Map.Entry<String, Object>> iterator = attsFeature.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, Object> entry = iterator.next();
if (entry.getKey().equals("FID")) {
iterator.remove();
}
}
fileOutputStream = new FileOutputStream(file);
writableByteChannel = Channels.newChannel(fileOutputStream);
dbaseFileWriter = new DbaseFileWriter(header, writableByteChannel, Charset.forName("UTF-8"), TimeZone.getDefault());
Object[] vals = attsFeature.values().toArray();
dbaseFileWriter.write(vals);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null)
inputStream.close();
if (fileOutputStream != null)
fileOutputStream.close();
if (dbaseFileReader != null)
dbaseFileReader.close();
if (dbaseFileWriter != null)
dbaseFileWriter.close();
}
return true;
}
this is the error
java.nio.BufferUnderflowException at
java.nio.DirectByteBuffer.get(DirectByteBuffer.java: 164)
at org.geotools.data.shapefile.dbf.DbaseFileReader.read(DbaseFileReader.java: 417)
at org.geotools.data.shapefile.dbf.DbaseFileReader.readRow(DbaseFileReader.java: 314)
at com.edsab.gedat.util.DBaseFileHandler.findRecord(DBaseFileHandler.java: 174)
at com.edsab.gedat.adapter.AttributePagerAdapter.instantiateItem(AttributePagerAdapter.java: 102)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java: 1003)
at android.support.v4.view.ViewPager.populate(ViewPager.java: 1217)
at android.support.v4.view.ViewPager.populate(ViewPager.java: 1085)
at android.support.v4.view.ViewPager$3.run(ViewPager.java: 273)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java: 777)
at android.view.Choreographer.doCallbacks(Choreographer.java: 590)
at android.view.Choreographer.doFrame(Choreographer.java: 559)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java: 763)
at android.os.Handler.handleCallback(Handler.java: 739)
at android.os.Handler.dispatchMessage(Handler.java: 95)
at android.os.Looper.loop(Looper.java: 145)
at android.app.ActivityThread.main(ActivityThread.java: 6918)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java: 372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 1199)

Related

Java/Android: Backslashes in JSON in Double Quotation places

I try to send "POST" request to serwer. Request includes JSON. Server returns "ok" or my JSON (in value of "message" key), if data in not correct. And I get strange backslashes ( \ sing) in my JSON, sent to server.
I get JSON response:
{"message":{"{\"phone_number\":\"_380661111111\",\"password\":\"112233aa\",\"military_id\":\"12345\",\"email\":\"won#mail_ru\"}":""}}
Normal JSON:
{"phone_number":"380666320670","password":"112233aa","military_id":"12345","email":"wovilon#mail.ru"}
Full code:
class SendLoginData extends AsyncTask<Void, Void, Void> {
String[] key,value;
String mResultString;
SendLoginData(String[] inKey, String[] inValue ){
this.key=new String[inKey.length];
this.value=new String[inValue.length];
this.key=inKey;
this.value=inValue;
}
String resultString = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {// http://oasushqg.beget.tech/users
String myURL = "http://y937220i.bget.ru/users";
byte[] data = null;
InputStream is = null;
try {
URL url = new URL(myURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
for (int i=0; i<this.key.length; i++) {
jsonParam.put(this.key[i], this.value[i]);
}
data=jsonParam.toString().getBytes("UTF-8");
os.write(data);
Log.d("MyLOG", "data is next: "+new String(data, "UTF-8"));
data = null;
conn.connect();
int responseCode= conn.getResponseCode();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (responseCode == 200) {
is = conn.getInputStream();
byte[] buffer = new byte[8192]; // Такого вот размера буфер
// Далее, например, вот так читаем ответ
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
data = baos.toByteArray();
resultString = new String(data, "UTF-8");
JSONObject jsonObj=new JSONObject(resultString);
mResultString=jsonObj.getString("message");
} else {
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (Exception e) {
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(resultString != null) {
Log.d("MyLOG", "postExecute run");
Log.d("MyLOG", mResultString);
}
}}

Converting finalBufferData into img url to display

I am trying to extract several images url constructed from parts of a JSON to be displayed.
I was able to retrieve the JSON and then construct several url from the JSON displaying it as a text on the screen ( String ).
at the end of the AsyncTask i used the Universal Image Loader, to display a single pic, in case the JSON contain information of a single pic, but the problem is whnen construct several url from the JSON :
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format + "/n");
it create a string of address just in separate lines ( if displayed in a textView), but bening passed to UIL it is not acceptable.
So i am not sure how to do this, since i am trying to have an image view within a listView in a linearway or differently maybe, to display several images, depending on the JSON information .
Any suggestion on how to do this will be great .
My AsyncTask code it;
public class JsonTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
StringBuffer finalBufferData = new StringBuffer();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String publicID = finalObject.getString("public_id");
String version = finalObject.getString("version");
String format = finalObject.getString("format");
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format);
}
return finalBufferData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ImageLoader.getInstance().displayImage(result, imageViewDisplayUp);
//imagesList.setText(result);
}
}
}
found a way around it, by adding another String which is not in the JSON but get created from other JASON strings.
Since the public_id, version, and format are in the JSON downloaded from Cloudinary and needed to build the right address for the images to be passed into the ImageLoader, and i couldnt not find another way to retrieve a list of images urls uploaded by the user with a specific tag to Cloudinary, without using the admin api which require writing api_secret in the program, i ended up doing the following;
public class JsonTask extends AsyncTask<String, String, List<upImgModels> > {
#Override
protected List<upImgModels> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
List<upImgModels> upImgList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
upImgModels upImgModels = new upImgModels();
upImgModels.setPublic_id(finalObject.getString("public_id"));
upImgModels.setVersion(finalObject.getString("version"));
upImgModels.setFormat(finalObject.getString("format"));
upImgModels.setAddress("http://res.cloudinary.com/we4x4/" + fileType
+ "/upload/v" + finalObject.getString("version") + "/"
+ finalObject.getString("public_id") + "." +
finalObject.getString("format"));
upImgList.add(upImgModels);
}
return upImgList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<upImgModels> result) {
super.onPostExecute(result);
upImgAdapter adapter = new upImgAdapter(getApplicationContext(), R.layout.row, result);
listViewUpload.setAdapter(adapter);
//imagesList.setText(result);
}
}
public class upImgAdapter extends ArrayAdapter{
public List<upImgModels> upImgModelsList;
private int resource;
private LayoutInflater inflater;
public upImgAdapter(Context context, int resource, List<upImgModels> objects) {
super(context, resource, objects);
upImgModelsList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = inflater.inflate(R.layout.row, null);
}
ImageView imageViewDisplay;
imageViewDisplay = (ImageView)convertView.findViewById(R.id.imageViewDisplay);
ImageLoader.getInstance().displayImage(upImgModelsList.get(position).getAddress(), imageViewDisplay);
return convertView;
}
}
}
I hope someone could suggest a better way to do this if it is possible, which i am sure that is the case.

Runtime error on Integer.parseInt(); i am trying to compare the content in the file and the new value obtained from the method

/*the below code is i am trying for the notification of new mail i am trying to fetch the prestored value into the file and compare it to the new value from the method
public static void main(String args[]) throws MessagingException{
try {
Notification n= new Notification();
int a =n.Notification();
BufferedReader br = null;
//read from the earlier file value of the total messages
String sCurrentLine;
br = new BufferedReader(new FileReader("Notification.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
int b = Integer.parseInt(sCurrentLine);
if (a>b){
System.out.println("you have "+(a-b)+" new Messsages");
}else{
System.out.println("NO New message");
}
//write the new value of the total messages to the file
Writer output = null;
File file = new File("Notification.txt");
output = new BufferedWriter(new FileWriter(file, true));
output.write(String.valueOf(a));
output.close();
} catch (IOException ex) {
Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
}
}
If the file you are reading from only contains a number that you require, maybe this is what you have to do:
if ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
int b = Integer.parseInt(sCurrentLine);
// do other stuff
}
else
{
// file empty
}

Primefaces DefaultStreamedContent InputStream

I'm using PF 3.4.2 and just want to know if the DefaultStreamedContent handles closing the used inputstream? Because when i try to do it by myself in a finally block, it causes an exception.
Primefaces handles closing the stream used in DefaultStreamedContent, i checked the implementation of the fie download listener:
public void processAction(ActionEvent actionEvent) throws AbortProcessingException {
FacesContext facesContext = FacesContext.getCurrentInstance();
ELContext elContext = facesContext.getELContext();
StreamedContent content = (StreamedContent) value.getValue(elContext);
if(content == null) {
return;
}
ExternalContext externalContext = facesContext.getExternalContext();
String contentDispositionValue = contentDisposition != null ? (String) contentDisposition.getValue(elContext) : "attachment";
try {
externalContext.setResponseContentType(content.getContentType());
externalContext.setResponseHeader("Content-Disposition", contentDispositionValue + ";filename=\"" + content.getName() + "\"");
externalContext.addResponseCookie(Constants.DOWNLOAD_COOKIE, "true", new HashMap<String, Object>());
byte[] buffer = new byte[2048];
int length;
InputStream inputStream = content.getStream();
OutputStream outputStream = externalContext.getResponseOutputStream();
while ((length = (inputStream.read(buffer))) != -1) {
outputStream.write(buffer, 0, length);
}
externalContext.setResponseStatus(200);
externalContext.responseFlushBuffer();
content.getStream().close();
facesContext.responseComplete();
}
catch(IOException e) {
throw new FacesException(e);
}
}

SEVERE: java.sql.SQLException: Column count doesn't match value count at row 1

I have Mysql datatbase, and working on servlet:
this is my Table schema:
CREATE TABLE Files (
File_Name VARCHAR(50),
File_Data Blob ,
File_Date VARCHAR(20),
File_Course_Code VARCHAR(45) REFERENCES Course(Course_Code) ,
PRIMARY KEY (File_Name , File_Date, File_Course_Code)
);
And here is the servlet code:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
ServletOutputStream os = response.getOutputStream();
try {
InputStream uploadedFile = null;
DiskFileUpload fu = new DiskFileUpload();
// If file size exceeds, a FileUploadException will be thrown
fu.setSizeMax(10000000);
List fileItems = fu.parseRequest(request);
Iterator itr = fileItems.iterator();
while (itr.hasNext()) {
FileItem fi = (FileItem) itr.next();
//Check if not form field so as to only handle the file inputs
//else condition handles the submit button input
if (!fi.isFormField()) { // If the form fiel is a file
uploadedFile = fi.getInputStream();
}
}
// to get the file name:
String fileName= "String";
// to extract the date:
java.util.Date now = new java.util.Date();
String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
String strDateNew = sdf.format(now);
HttpSession session = request.getSession();
String a = (String) session.getAttribute("fileccode");
// set connection up:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/VC", "root", "");
PreparedStatement stmt = null;
stmt = conn.prepareStatement("INSERT INTO Files (File_Name,File_Data,File_Date,File_Course_Code) VALUES (?,? ?,?)");
stmt.setString(1,fileName);
stmt.setBinaryStream(2,uploadedFile);
stmt.setString(3,strDateNew);
stmt.setString(4,a);
stmt.executeUpdate();
} catch (FileUploadException e) {
os.print(e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
os.close();
}
}
I have seen many posts about this error, but almost all of them were having Syntax error in writing the query.
I have no syntax error i believe.
but maybe (File_Data) as a primary key and default null makes something wrong?
Your missing a comma
VALUES (?,? ?,?)
should be
VALUES (?,?,?,?)