Search Results

Search found 561 results on 23 pages for 'inputstream'.

Page 7/23 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Download Large Files using java

    - by angelina
    Dear All, I M building a application in which i want to download large files on handset (mobile),but if size of file is large i m getting exception socket exception-broken pipe . inputStream = new FileInputStream(path); byte[] buffer = new byte[1024]; int bytesRead = 0; do { bytesRead = inputStream.read(buffer, offset, buffer.length); resp.getOutputStream().write(buffer, 0, bytesRead); } while (bytesRead == buffer.length); resp.getOutputStream().flush(); }

    Read the article

  • Image URL has the contentType "text/html"

    - by user1503025
    I want to implement a method to download Image from website to laptop. public static void DownloadRemoteImageFile(string uri, string fileName) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if ((response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect) && response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase)) { //if the remote file was found, download it using (Stream inputStream = response.GetResponseStream()) using (Stream outputStream = File.OpenWrite(fileName)) { byte[] buffer = new byte[4096]; int bytesRead; do { bytesRead = inputStream.Read(buffer, 0, buffer.Length); outputStream.Write(buffer, 0, bytesRead); } while (bytesRead != 0); } } } But the ContentType of request or response is not "image/jpg" or "image/png". They're always "text/html". I think that's why after I save them to local, they has incorrect content and I cannot view them. Can anyone has a solution here? Thanks

    Read the article

  • Database Tutorial: The method open() is undefined for the type MainActivity.DBAdapter

    - by user2203633
    I am trying to do this database tutorial on SQLite Eclipse: https://www.youtube.com/watch?v=j-IV87qQ00M But I get a few errors at the end.. at db.ppen(); i get error: The method open() is undefined for the type MainActivity.DBAdapter and similar for insert record and close. MainActivity: package com.example.studentdatabase; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.app.Activity; import android.app.ListActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { /** Called when the activity is first created. */ //DBAdapter db = new DBAdapter(this); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button addBtn = (Button)findViewById(R.id.add); addBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, addassignment.class); startActivity(i); } }); try { String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB"; File f = new File(destPath); if (!f.exists()) { CopyDB( getBaseContext().getAssets().open("mydb"), new FileOutputStream(destPath)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } DBAdapter db = new DBAdapter(); //---add an assignment--- db.open(); long id = db.insertRecord("Hello World", "2/18/2012", "DPR 224", "First Android Project"); id = db.insertRecord("Workbook Exercises", "3/1/2012", "MAT 100", "Do odd numbers"); db.close(); //---get all Records--- /* db.open(); Cursor c = db.getAllRecords(); if (c.moveToFirst()) { do { DisplayRecord(c); } while (c.moveToNext()); } db.close(); */ /* //---get a Record--- db.open(); Cursor c = db.getRecord(2); if (c.moveToFirst()) DisplayRecord(c); else Toast.makeText(this, "No Assignments found", Toast.LENGTH_LONG).show(); db.close(); */ //---update Record--- /* db.open(); if (db.updateRecord(1, "Hello Android", "2/19/2012", "DPR 224", "First Android Project")) Toast.makeText(this, "Update successful.", Toast.LENGTH_LONG).show(); else Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show(); db.close(); */ /* //---delete a Record--- db.open(); if (db.deleteRecord(1)) Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show(); else Toast.makeText(this, "Delete failed.", Toast.LENGTH_LONG).show(); db.close(); */ } private class DBAdapter extends BaseAdapter { private LayoutInflater mInflater; //private ArrayList<> @Override public int getCount() { return 0; } @Override public Object getItem(int arg0) { return null; } @Override public long getItemId(int arg0) { return 0; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { return null; } } public void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException { //---copy 1K bytes at a time--- byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); } public void DisplayRecord(Cursor c) { Toast.makeText(this, "id: " + c.getString(0) + "\n" + "Title: " + c.getString(1) + "\n" + "Due Date: " + c.getString(2), Toast.LENGTH_SHORT).show(); } public void addAssignment(View view) { Intent i = new Intent("com.pinchtapzoom.addassignment"); startActivity(i); Log.d("TAG", "Clicked"); } } DBAdapter code: package com.example.studentdatabase; public class DBAdapter { public static final String KEY_ROWID = "id"; public static final String KEY_TITLE = "title"; public static final String KEY_DUEDATE = "duedate"; public static final String KEY_COURSE = "course"; public static final String KEY_NOTES = "notes"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "AssignmentsDB"; private static final String DATABASE_TABLE = "assignments"; private static final int DATABASE_VERSION = 2; private static final String DATABASE_CREATE = "create table if not exists assignments (id integer primary key autoincrement, " + "title VARCHAR not null, duedate date, course VARCHAR, notes VARCHAR );"; private final Context context; private DatabaseHelper DBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL(DATABASE_CREATE); } catch (SQLException e) { e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS contacts"); onCreate(db); } } //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a record into the database--- public long insertRecord(String title, String duedate, String course, String notes) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_TITLE, title); initialValues.put(KEY_DUEDATE, duedate); initialValues.put(KEY_COURSE, course); initialValues.put(KEY_NOTES, notes); return db.insert(DATABASE_TABLE, null, initialValues); } //---deletes a particular record--- public boolean deleteContact(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---retrieves all the records--- public Cursor getAllRecords() { return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_DUEDATE, KEY_COURSE, KEY_NOTES}, null, null, null, null, null); } //---retrieves a particular record--- public Cursor getRecord(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_DUEDATE, KEY_COURSE, KEY_NOTES}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a record--- public boolean updateRecord(long rowId, String title, String duedate, String course, String notes) { ContentValues args = new ContentValues(); args.put(KEY_TITLE, title); args.put(KEY_DUEDATE, duedate); args.put(KEY_COURSE, course); args.put(KEY_NOTES, notes); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } } addassignment code: package com.example.studentdatabase; public class addassignment extends Activity { DBAdapter db = new DBAdapter(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add); } public void addAssignment(View v) { Log.d("test", "adding"); //get data from form EditText nameTxt = (EditText)findViewById(R.id.editTitle); EditText dateTxt = (EditText)findViewById(R.id.editDuedate); EditText courseTxt = (EditText)findViewById(R.id.editCourse); EditText notesTxt = (EditText)findViewById(R.id.editNotes); db.open(); long id = db.insertRecord(nameTxt.getText().toString(), dateTxt.getText().toString(), courseTxt.getText().toString(), notesTxt.getText().toString()); db.close(); nameTxt.setText(""); dateTxt.setText(""); courseTxt.setText(""); notesTxt.setText(""); Toast.makeText(addassignment.this,"Assignment Added", Toast.LENGTH_LONG).show(); } public void viewAssignments(View v) { Intent i = new Intent(this, MainActivity.class); startActivity(i); } } What is wrong here? Thanks in advance.

    Read the article

  • StreamInsight and Reactive Framework Challenge

    In his blogpost Roman from the StreamInsight team asked if we could create a Reactive Framework version of what he had done in the post using StreamInsight.  For those who don’t know, the Reactive Framework or Rx to its friends is a library for composing asynchronous and event-based programs using observable collections in the .Net framework.  Yes, there is some overlap between StreamInsight and the Reactive Extensions but StreamInsight has more flexibility and power in its temporal algebra (Windowing, Alteration of event headers) Well here are two alternate ways of doing what Roman did. The first example is a mix of StreamInsight and Rx var rnd = new Random(); var RandomValue = 0; var interval = Observable.Interval(TimeSpan.FromMilliseconds((Int32)rnd.Next(500,3000))) .Select(i => { RandomValue = rnd.Next(300); return RandomValue; }); Server s = Server.Create("Default"); Microsoft.ComplexEventProcessing.Application a = s.CreateApplication("Rx SI Mischung"); var inputStream = interval.ToPointStream(a, evt => PointEvent.CreateInsert( System.DateTime.Now.ToLocalTime(), new { RandomValue = evt}), AdvanceTimeSettings.IncreasingStartTime, "Rx Sample"); var r = from evt in inputStream select new { runningVal = evt.RandomValue }; foreach (var x in r.ToPointEnumerable().Where(e => e.EventKind != EventKind.Cti)) { Console.WriteLine(x.Payload.ToString()); } This next version though uses the Reactive Extensions Only   var rnd = new Random(); var RandomValue = 0; Observable.Interval(TimeSpan.FromMilliseconds((Int32)rnd.Next(500, 3000))) .Select(i => { RandomValue = rnd.Next(300); return RandomValue; }).Subscribe(Console.WriteLine, () => Console.WriteLine("Completed")); Console.ReadKey();   These are very simple examples but both technologies allow us to do a lot more.  The ICEPObservable() design pattern was reintroduced in StreamInsight 1.1 and the more I use it the more I like it.  It is a very useful pattern when wanting to show StreamInsight samples as is the IEnumerable() pattern.

    Read the article

  • Visual Studio C++ list iterator not decementable

    - by user69514
    I keep getting an error on visual studio that says list iterator not decrementable: line 256 My program works fine on Linux, but visual studio compiler throws this error. Dammit this is why I hate windows. Why can't the world run on Linux? Anyway, do you see what my problem is? #include <iostream> #include <fstream> #include <sstream> #include <list> using namespace std; int main(){ /** create the list **/ list<int> l; /** create input stream to read file **/ ifstream inputstream("numbers.txt"); /** read the numbers and add them to list **/ if( inputstream.is_open() ){ string line; istringstream instream; while( getline(inputstream, line) ){ instream.clear(); instream.str(line); /** get he five int's **/ int one, two, three, four, five; instream >> one >> two >> three >> four >> five; /** add them to the list **/ l.push_back(one); l.push_back(two); l.push_back(three); l.push_back(four); l.push_back(five); }//end while loop }//end if /** close the stream **/ inputstream.close(); /** display the list **/ cout << "List Read:" << endl; list<int>::iterator i; for( i=l.begin(); i != l.end(); ++i){ cout << *i << " "; } cout << endl << endl; /** now sort the list **/ l.sort(); /** display the list **/ cout << "Sorted List (head to tail):" << endl; for( i=l.begin(); i != l.end(); ++i){ cout << *i << " "; } cout << endl; list<int> lReversed; for(i=l.begin(); i != l.end(); ++i){ lReversed.push_front(*i); } cout << "Sorted List (tail to head):" << endl; for(i=lReversed.begin(); i!=lReversed.end(); ++i){ cout << *i << " "; } cout << endl << endl; /** remove first biggest element and display **/ l.pop_back(); cout << "List after removing first biggest element:" << endl; cout << "Sorted List (head to tail):" << endl; for( i=l.begin(); i != l.end(); ++i){ cout << *i << " "; } cout << endl; cout << "Sorted List (tail to head):" << endl; lReversed.pop_front(); for(i=lReversed.begin(); i!=lReversed.end(); ++i){ cout << *i << " "; } cout << endl << endl; /** remove second biggest element and display **/ l.pop_back(); cout << "List after removing second biggest element:" << endl; cout << "Sorted List (head to tail):" << endl; for( i=l.begin(); i != l.end(); ++i){ cout << *i << " "; } cout << endl; lReversed.pop_front(); cout << "Sorted List (tail to head):" << endl; for(i=lReversed.begin(); i!=lReversed.end(); ++i){ cout << *i << " "; } cout << endl << endl; /** remove third biggest element and display **/ l.pop_back(); cout << "List after removing third biggest element:" << endl; cout << "Sorted List (head to tail):" << endl; for( i=l.begin(); i != l.end(); ++i){ cout << *i << " "; } cout << endl; cout << "Sorted List (tail to head):" << endl; lReversed.pop_front(); for(i=lReversed.begin(); i!=lReversed.end(); ++i){ cout << *i << " "; } cout << endl << endl; /** create frequency table **/ const int biggest = 1000; //create array size of biggest element int arr[biggest]; //set everything to zero for(int j=0; j<biggest+1; j++){ arr[j] = 0; } //now update number of occurences for( i=l.begin(); i != l.end(); i++){ arr[*i]++; } //now print the frequency table. only print where occurences greater than zero cout << "Final list frequency table: " << endl; for(int j=0; j<biggest+1; j++){ if( arr[j] > 0 ){ cout << j << ": " << arr[j] << " occurences" << endl; } } return 0; }//end main

    Read the article

  • how to display bitmaps in listview?

    - by mary
    hi i want to show images downloaded in listview.images downloaded with function DownloadImage and are as bitmap.how to show in listview . name photoes with book_id in tabel book are aqual.i want each book has its own image. i can show in listview book_name and book_price just the problem with image book please help me class: package bookstore.category; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Typeface; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import bookstore.pack.JSONParser; import bookstore.pack.R; import android.app.Activity; import android.app.ProgressDialog; public class Computer extends Activity { Bitmap bm = null; // progress dialog private ProgressDialog pDialog; // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList<HashMap<String, String>> computerBookList; private static String url_books = "http://10.0.2.2/project/computer.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_BOOK = "book"; private static final String TAG_BOOK_NAME = "book_name"; private static final String TAG_BOOK_PRICE = "book_price"; private static final String TAG_BOOK_ID = "book_id"; private static final String TAG_MESSAGE = "massage"; // category JSONArray JSONArray book = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.category); Typeface font1 = Typeface.createFromAsset(getAssets(), "font/bnazanin.TTF"); // Hashmap for ListView computerBookList = new ArrayList<HashMap<String, String>>(); new LoadBook().execute(); } class LoadBook extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Computer.this); pDialog.setMessage("Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } protected String doInBackground(String... args) { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url_books, "GET", params); // Check your log cat for JSON reponse Log.d("book:", json.toString()); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { DownloadImage("10.0.2.2/project/images/100.png"); DownloadImage("10.0.2.2/project/images/101.png"); DownloadImage("10.0.2.2/project/images/102.png"); DownloadImage("10.0.2.2/project/images/103.png"); DownloadImage("10.0.2.2/project/images/104.png"); DownloadImage("10.0.2.2/project/images/105.png"); DownloadImage("10.0.2.2/project/images/106.png"); DownloadImage("10.0.2.2/project/images/107.png"); DownloadImage("10.0.2.2/project/images/108.png"); DownloadImage("10.0.2.2/project/images/109.png"); DownloadImage("10.0.2.2/project/images/110.png"); // books found book = json.getJSONArray(TAG_BOOK); for (int i = 0; i < book.length(); i++) { JSONObject c = book.getJSONObject(i); // Storing each json item in variable String book_name = c.getString(TAG_BOOK_NAME); String book_price = c.getString(TAG_BOOK_PRICE); String book_id = c.getString(TAG_BOOK_ID); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(TAG_BOOK_NAME, book_name); map.put(TAG_BOOK_PRICE, book_price); // map.put(TAG_AUTHOR_NAME, author_name); // adding HashList to ArrayList computerBookList.add(map); } return json.getString(TAG_MESSAGE); } else { System.out.println("no book found"); } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { ListView view1 = (ListView) findViewById(R.id.list_view); public void run() { ImageView iv = (ImageView) findViewById(R.id.list_image); // bm=BitmapFactory.decodeResource(getResources(), resId); //bm=BitmapFactory.decodeResource(null,R.id.list_image); // iv.setImageBitmap(bm); /* * */ /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter(Computer.this, computerBookList, R.layout.search_item, new String[] { TAG_BOOK_NAME, TAG_BOOK_PRICE }, new int[] { R.id.book_name, R.id.book_price }); view1.setAdapter(adapter); } }); } } private Bitmap DownloadImage(String URL) { Bitmap bitmap = null; InputStream in = null; try { in = OpenHttpConnection(URL); bitmap = BitmapFactory.decodeStream(in); in.close(); } catch (IOException e1) { e1.printStackTrace(); } return bitmap; } private InputStream OpenHttpConnection(String urlString) throws IOException { InputStream in = null; int response = -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { throw new IOException("Error connecting"); } return in; } }

    Read the article

  • OAF Page to Upload Files into Server from local Machine

    - by PRajkumar
    1. Create a New Workspace and Project File > New > General > Workspace Configured for Oracle Applications File Name – PrajkumarFileUploadDemo   Automatically a new OA Project will also be created   Project Name -- FileUploadDemo Default Package -- prajkumar.oracle.apps.fnd.fileuploaddemo   2. Create a New Application Module (AM) Right Click on FileUploadDemo > New > ADF Business Components > Application Module Name -- FileUploadAM Package -- prajkumar.oracle.apps.fnd.fileuploaddemo.server Check Application Module Class: FileUploadAMImpl Generate JavaFile(s)   3. Create a New Page Right click on FileUploadDemo > New > Web Tier > OA Components > Page Name -- FileUploadPG Package -- prajkumar.oracle.apps.fnd.fileuploaddemo.webui   4. Select the FileUploadPG and go to the strcuture pane where a default region has been created   5. Select region1 and set the following properties --     Attribute Property ID PageLayoutRN AM Definition prajkumar.oracle.apps.fnd.fileuploaddemo.server.FileUploadAM Window Title Uploading File into Server from Local Machine Demo Window Title Uploading File into Server from Local Machine Demo     6. Create Stack Layout Region Under Page Layout Region Right click PageLayoutRN > New > Region   Attribute Property ID MainRN AM Definition messageComponentLayout   7. Create a New Item messageFileUpload Bean under MainRN Right click on MainRN > New > messageFileUpload Set Following Properties for New Item --   Attribute Property ID MessageFileUpload Item Style messageFileUpload   8. Create a New Item Submit Button Bean under MainRN Right click on MainRN > New > messageLayout Set Following Properties for messageLayout --   Attribute Property ID ButtonLayout   Right Click on ButtonLayout > New > Item   Attribute Property ID Submit Item Style submitButton Attribute Set /oracle/apps/fnd/attributesets/Buttons/Go   9. Create Controller for page FileUploadPG Right Click on PageLayoutRN > Set New Controller Package Name: prajkumar.oracle.apps.fnd.fileuploaddemo.webui Class Name: FileUploadCO   Write Following Code in FileUploadCO processFormRequest   import oracle.cabo.ui.data.DataObject; import java.io.FileOutputStream; import java.io.InputStream; import oracle.jbo.domain.BlobDomain; import java.io.File; import oracle.apps.fnd.framework.OAException; public void processFormRequest(OAPageContext pageContext, OAWebBean webBean) { super.processFormRequest(pageContext, webBean);    if(pageContext.getParameter("Submit")!=null)  {   upLoadFile(pageContext,webBean);      } }   -- Use Following Code if want to Upload Files in Local Machine -- ----------------------------------------------------------------------------------- public void upLoadFile(OAPageContext pageContext,OAWebBean webBean) { String filePath = "D:\\PRajkumar";  System.out.println("Default File Path---->"+filePath);  String fileUrl = null;  try  {   DataObject fileUploadData =  pageContext.getNamedDataObject("MessageFileUpload"); //FileUploading is my MessageFileUpload Bean Id   if(fileUploadData!=null)   {    String uFileName = (String)fileUploadData.selectValue(null, "UPLOAD_FILE_NAME");  // include this line    String contentType = (String) fileUploadData.selectValue(null, "UPLOAD_FILE_MIME_TYPE");  // For Mime Type    System.out.println("User File Name---->"+uFileName);    FileOutputStream output = null;    InputStream input = null;    BlobDomain uploadedByteStream = (BlobDomain)fileUploadData.selectValue(null, uFileName);    System.out.println("uploadedByteStream---->"+uploadedByteStream);                               File file = new File("D:\\PRajkumar", uFileName);    System.out.println("File output---->"+file);    output = new FileOutputStream(file);    System.out.println("output----->"+output);    input = uploadedByteStream.getInputStream();    System.out.println("input---->"+input);    byte abyte0[] = new byte[0x19000];    int i;         while((i = input.read(abyte0)) > 0)    output.write(abyte0, 0, i);    output.close();    input.close();   }  }  catch(Exception ex)  {   throw new OAException(ex.getMessage(), OAException.ERROR);  }     }   -- Use Following Code if want to Upload File into Server -- ------------------------------------------------------------------------- public void upLoadFile(OAPageContext pageContext,OAWebBean webBean) { String filePath = "/u01/app/apnac03r12/PRajkumar/";  System.out.println("Default File Path---->"+filePath);  String fileUrl = null;  try  {   DataObject fileUploadData =  pageContext.getNamedDataObject("MessageFileUpload");  //FileUploading is my MessageFileUpload Bean Id     if(fileUploadData!=null)   {    String uFileName = (String)fileUploadData.selectValue(null, "UPLOAD_FILE_NAME");   // include this line    String contentType = (String) fileUploadData.selectValue(null, "UPLOAD_FILE_MIME_TYPE");   // For Mime Type    System.out.println("User File Name---->"+uFileName);    FileOutputStream output = null;    InputStream input = null;    BlobDomain uploadedByteStream = (BlobDomain)fileUploadData.selectValue(null, uFileName);    System.out.println("uploadedByteStream---->"+uploadedByteStream);                               File file = new File("/u01/app/apnac03r12/PRajkumar", uFileName);    System.out.println("File output---->"+file);    output = new FileOutputStream(file);    System.out.println("output----->"+output);    input = uploadedByteStream.getInputStream();    System.out.println("input---->"+input);    byte abyte0[] = new byte[0x19000];    int i;         while((i = input.read(abyte0)) > 0)    output.write(abyte0, 0, i);    output.close();    input.close();   }  }  catch(Exception ex)  {   throw new OAException(ex.getMessage(), OAException.ERROR);  }     }   10. Congratulation you have successfully finished. Run Your page and Test Your Work           -- Used Code to Upload files into Server   -- Before Upload files into Server     -- After Upload files into Server       -- Used Code to Upload files into Local Machine   -- Before Upload files into Local Machine       -- After Upload files into Local Machine

    Read the article

  • The fastest way to resize images from ASP.NET. And it’s (more) supported-ish.

    - by Bertrand Le Roy
    I’ve shown before how to resize images using GDI, which is fairly common but is explicitly unsupported because we know of very real problems that this can cause. Still, many sites still use that method because those problems are fairly rare, and because most people assume it’s the only way to get the job done. Plus, it works in medium trust. More recently, I’ve shown how you can use WPF APIs to do the same thing and get JPEG thumbnails, only 2.5 times faster than GDI (even now that GDI really ultimately uses WIC to read and write images). The boost in performance is great, but it comes at a cost, that you may or may not care about: it won’t work in medium trust. It’s also just as unsupported as the GDI option. What I want to show today is how to use the Windows Imaging Components from ASP.NET APIs directly, without going through WPF. The approach has the great advantage that it’s been tested and proven to scale very well. The WIC team tells me you should be able to call support and get answers if you hit problems. Caveats exist though. First, this is using interop, so until a signed wrapper sits in the GAC, it will require full trust. Second, the APIs have a very strong smell of native code and are definitely not .NET-friendly. And finally, the most serious problem is that older versions of Windows don’t offer MTA support for image decoding. MTA support is only available on Windows 7, Vista and Windows Server 2008. But on 2003 and XP, you’ll only get STA support. that means that the thread safety that we so badly need for server applications is not guaranteed on those operating systems. To make it work, you’d have to spin specialized threads yourself and manage the lifetime of your objects, which is outside the scope of this article. We’ll assume that we’re fine with al this and that we’re running on 7 or 2008 under full trust. Be warned that the code that follows is not simple or very readable. This is definitely not the easiest way to resize an image in .NET. Wrapping native APIs such as WIC in a managed wrapper is never easy, but fortunately we won’t have to: the WIC team already did it for us and released the results under MS-PL. The InteropServices folder, which contains the wrappers we need, is in the WicCop project but I’ve also included it in the sample that you can download from the link at the end of the article. In order to produce a thumbnail, we first have to obtain a decoding frame object that WIC can use. Like with WPF, that object will contain the command to decode a frame from the source image but won’t do the actual decoding until necessary. Getting the frame is done by reading the image bytes through a special WIC stream that you can obtain from a factory object that we’re going to reuse for lots of other tasks: var photo = File.ReadAllBytes(photoPath); var factory = (IWICComponentFactory)new WICImagingFactory(); var inputStream = factory.CreateStream(); inputStream.InitializeFromMemory(photo, (uint)photo.Length); var decoder = factory.CreateDecoderFromStream( inputStream, null, WICDecodeOptions.WICDecodeMetadataCacheOnLoad); var frame = decoder.GetFrame(0); We can read the dimensions of the frame using the following (somewhat ugly) code: uint width, height; frame.GetSize(out width, out height); This enables us to compute the dimensions of the thumbnail, as I’ve shown in previous articles. We now need to prepare the output stream for the thumbnail. WIC requires a special kind of stream, IStream (not implemented by System.IO.Stream) and doesn’t directlyunderstand .NET streams. It does provide a number of implementations but not exactly what we need here. We need to output to memory because we’ll want to persist the same bytes to the response stream and to a local file for caching. The memory-bound version of IStream requires a fixed-length buffer but we won’t know the length of the buffer before we resize. To solve that problem, I’ve built a derived class from MemoryStream that also implements IStream. The implementation is not very complicated, it just delegates the IStream methods to the base class, but it involves some native pointer manipulation. Once we have a stream, we need to build the encoder for the output format, which could be anything that WIC supports. For web thumbnails, our only reasonable options are PNG and JPEG. I explored PNG because it’s a lossless format, and because WIC does support PNG compression. That compression is not very efficient though and JPEG offers good quality with much smaller file sizes. On the web, it matters. I found the best PNG compression option (adaptive) to give files that are about twice as big as 100%-quality JPEG (an absurd setting), 4.5 times bigger than 95%-quality JPEG and 7 times larger than 85%-quality JPEG, which is more than acceptable quality. As a consequence, we’ll use JPEG. The JPEG encoder can be prepared as follows: var encoder = factory.CreateEncoder( Consts.GUID_ContainerFormatJpeg, null); encoder.Initialize(outputStream, WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache); The next operation is to create the output frame: IWICBitmapFrameEncode outputFrame; var arg = new IPropertyBag2[1]; encoder.CreateNewFrame(out outputFrame, arg); Notice that we are passing in a property bag. This is where we’re going to specify our only parameter for encoding, the JPEG quality setting: var propBag = arg[0]; var propertyBagOption = new PROPBAG2[1]; propertyBagOption[0].pstrName = "ImageQuality"; propBag.Write(1, propertyBagOption, new object[] { 0.85F }); outputFrame.Initialize(propBag); We can then set the resolution for the thumbnail to be 96, something we weren’t able to do with WPF and had to hack around: outputFrame.SetResolution(96, 96); Next, we set the size of the output frame and create a scaler from the input frame and the computed dimensions of the target thumbnail: outputFrame.SetSize(thumbWidth, thumbHeight); var scaler = factory.CreateBitmapScaler(); scaler.Initialize(frame, thumbWidth, thumbHeight, WICBitmapInterpolationMode.WICBitmapInterpolationModeFant); The scaler is using the Fant method, which I think is the best looking one even if it seems a little softer than cubic (zoomed here to better show the defects): Cubic Fant Linear Nearest neighbor We can write the source image to the output frame through the scaler: outputFrame.WriteSource(scaler, new WICRect { X = 0, Y = 0, Width = (int)thumbWidth, Height = (int)thumbHeight }); And finally we commit the pipeline that we built and get the byte array for the thumbnail out of our memory stream: outputFrame.Commit(); encoder.Commit(); var outputArray = outputStream.ToArray(); outputStream.Close(); That byte array can then be sent to the output stream and to the cache file. Once we’ve gone through this exercise, it’s only natural to wonder whether it was worth the trouble. I ran this method, as well as GDI and WPF resizing over thirty twelve megapixel images for JPEG qualities between 70% and 100% and measured the file size and time to resize. Here are the results: Size of resized images   Time to resize thirty 12 megapixel images Not much to see on the size graph: sizes from WPF and WIC are equivalent, which is hardly surprising as WPF calls into WIC. There is just an anomaly for 75% for WPF that I noted in my previous article and that disappears when using WIC directly. But overall, using WPF or WIC over GDI represents a slight win in file size. The time to resize is more interesting. WPF and WIC get similar times although WIC seems to always be a little faster. Not surprising considering WPF is using WIC. The margin of error on this results is probably fairly close to the time difference. As we already knew, the time to resize does not depend on the quality level, only the size does. This means that the only decision you have to make here is size versus visual quality. This third approach to server-side image resizing on ASP.NET seems to converge on the fastest possible one. We have marginally better performance than WPF, but with some additional peace of mind that this approach is sanctioned for server-side usage by the Windows Imaging team. It still doesn’t work in medium trust. That is a problem and shows the way for future server-friendly managed wrappers around WIC. The sample code for this article can be downloaded from: http://weblogs.asp.net/blogs/bleroy/Samples/WicResize.zip The benchmark code can be found here (you’ll need to add your own images to the Images directory and then add those to the project, with content and copy if newer in the properties of the files in the solution explorer): http://weblogs.asp.net/blogs/bleroy/Samples/WicWpfGdiImageResizeBenchmark.zip WIC tools can be downloaded from: http://code.msdn.microsoft.com/wictools To conclude, here are some of the resized thumbnails at 85% fant:

    Read the article

  • How can i make a gallery with web images from my website?

    - by ronhdoge
    I currently have two codes that i am trying to figure out how to mix or write a new code to have a gallery with image doing fill_parent but i can slide sideways to see the other url linked images from my site. here are both parts of code i have: package com.mandarich.gallerygrid; import java.io.InputStream; import java.net.URL; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.widget.ImageView; public class Gallery extends Activity { /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView imgView =(ImageView)findViewById(R.id.ImageView01); Drawable drawable = LoadImageFromWebOperations("http://www.mandarichmodels.com/hot-pics/"); imgView.setImageDrawable(drawable); } private Drawable LoadImageFromWebOperations(String url) { try { InputStream is = (InputStream) new URL(url).getContent(); Drawable d = Drawable.createFromStream(is, "src name"); return d; }catch (Exception e) { System.out.println("Exc="+e); return null; } } } and here is my gallery code package com.mandarich.Grid; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class gridfinal extends Activity { private Gallery gallery; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); gallery = (Gallery) findViewById(R.id.examplegallery); gallery.setAdapter(new AddImgAdp(this)); gallery.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("unchecked") public void onItemClick(AdapterView parent, View v, int position, long id) { // Displaying the position when the gallery item in clicked Toast.makeText(gridfinal.this, "Position=" + position, Toast.LENGTH_SHORT).show(); } }); } public class AddImgAdp extends BaseAdapter { int GalItemBg; private Context cont; // Adding images. private Integer[] Imgid = { R.drawable.cindy, R.drawable.clinton, R.drawable.colin, R.drawable.cybil, R.drawable.david, R.drawable.demi, R.drawable.drew }; public AddImgAdp(Context c) { cont = c; TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme); GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0); typArray.recycle(); } public int getCount() { return Imgid.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imgView = new ImageView(cont); imgView.setImageResource(Imgid[position]); // Fixing width & height for image to display imgView.setLayoutParams(new Gallery.LayoutParams(430, 370)); imgView.setScaleType(ImageView.ScaleType.FIT_XY); imgView.setBackgroundResource(GalItemBg); return imgView; } } }

    Read the article

  • Qt - reloading widget contents

    - by bullettime
    I'm trying to modify the fridge magnets example by adding a button that will reload the widget where the draggable labels are drawn, reflecting any changes made to the text file it reads. I defined another class that would contain the button and the DragWidget object, so there would be an instance of this class instead of DragWidget in main(): class wrapWidget: public QWidget { public: wrapWidget(); }; wrapWidget::wrapWidget() { QGridLayout *gridlayout = new QGridLayout(); DragWidget *w = new DragWidget(); QPushButton *b = new QPushButton("refresh"); gridlayout ->addWidget(w,0,0); gridlayout ->addWidget(b,1,0); setLayout(gridlayout ); connect(b,SIGNAL(clicked()),w,SLOT(draw())); } The call to connect is where I'm trying to do the refresh thing. In the original fridge magnets example, all the label drawing code was inside the constructor of the DragWidget class. I moved that code to a public method that I named 'draw()', and called this method from the constructor instead. Here's DragWidget definition and implementation: #include <QWidget> QT_BEGIN_NAMESPACE class QDragEnterEvent; class QDropEvent; QT_END_NAMESPACE class DragWidget : public QWidget { public: DragWidget(QWidget *parent = 0); public slots: void draw(); protected: void dragEnterEvent(QDragEnterEvent *event); void dragMoveEvent(QDragMoveEvent *event); void dropEvent(QDropEvent *event); void mousePressEvent(QMouseEvent *event); void paintEvent(QPaintEvent *event); }; DragWidget::DragWidget(QWidget *parent) : QWidget(parent) { draw(); QPalette newPalette = palette(); newPalette.setColor(QPalette::Window, Qt::white); setPalette(newPalette); setMinimumSize(400, 100);//qMax(200, y)); setWindowTitle(tr("Fridge Magnets")); setAcceptDrops(true); } void DragWidget::draw(){ QFile dictionaryFile(":/dictionary/words.txt"); dictionaryFile.open(QFile::ReadOnly); QTextStream inputStream(&dictionaryFile); int x = 5; int y = 5; while (!inputStream.atEnd()) { QString word; inputStream >> word; if (!word.isEmpty()) { DragLabel *wordLabel = new DragLabel(word, this); wordLabel->move(x, y); wordLabel->show(); wordLabel->setAttribute(Qt::WA_DeleteOnClose); x += wordLabel->width() + 2; if (x >= 245) { x = 5; y += wordLabel->height() + 2; } } } } I thought that maybe calling draw() as a slot would be enough to reload the labels, but it didn't work. Putting the draw() call inside the widget's overriden paintEvent() instead of the constructor didn't work out as well, the program would end up in an infinite loop. What I did was obviously not the right way of doing it, so what should I be doing instead?

    Read the article

  • Android Dev Help: Saving an image from Res/raw or Asset folder to the Sd card

    - by Lucy
    Android Development Query Hello, I wonder if anyone could help me, i am trying to save an image (jpg or png) from the res/raw or assets folder to the SD card location (/sdcard/DCIM/). I have been following a tutorial which can save an image from a URL to the SD card Root, but i have looked everywhere to be able to save from res/raw or asset folder instead, and to a differnet location onthe sd card /sdcard/DCIM/ Here is the code, can anyone show me how to do the above from this? Thanks Lucy public class home extends Activity { private File file; private String imgNumber; private Button btnDownload; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnDownload=(Button)findViewById(R.id.btnDownload); btnDownload.setOnClickListener(new OnClickListener() { public void onClick(View v) { btnDownload.setText("Download is in Progress."); String savedFilePath=Download("http://www.domain.com/android1.png"); Toast.makeText(getApplicationContext(), "File is Saved in "+savedFilePath, 1000).show(); if(savedFilePath!=null) { btnDownload.setText("Download Completed."); } } }); } public String Download(String Url) { String filepath=null; try { //set the download URL, a url that points to a file on the internet //this is the file to be downloaded URL url = new URL(Url); //create the new connection HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //set up some things on the connection urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); //and connect! urlConnection.connect(); //set the path where we want to save the file //in this case, going to save it on the root directory of the //sd card. File SDCardRoot = Environment.getExternalStorageDirectory(); //create a new file, specifying the path, and the filename //which we want to save the file as. String filename= "download_"+System.currentTimeMillis()+".png"; // you can download to any type of file ex:.jpeg (image) ,.txt(text file),.mp3 (audio file) Log.i("Local filename:",""+filename); file = new File(SDCardRoot,filename); if(file.createNewFile()) { file.createNewFile(); } //this will be used to write the downloaded data into the file we created FileOutputStream fileOutput = new FileOutputStream(file); //this will be used in reading the data from the internet InputStream inputStream = urlConnection.getInputStream(); //this is the total size of the file int totalSize = urlConnection.getContentLength(); //variable to store total downloaded bytes int downloadedSize = 0; //create a buffer... byte[] buffer = new byte[1024]; int bufferLength = 0; //used to store a temporary size of the buffer //now, read through the input buffer and write the contents to the file while ( (bufferLength = inputStream.read(buffer)) > 0 ) { //add the data in the buffer to the file in the file output stream (the file on the sd card fileOutput.write(buffer, 0, bufferLength); //add up the size so we know how much is downloaded downloadedSize += bufferLength; //this is where you would do something to report the prgress, like this maybe Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ; btnDownload.setText("download Status:"+downloadedSize+" / "+totalSize); } //close the output stream when done fileOutput.close(); if(downloadedSize==totalSize) filepath=file.getPath(); //catch some possible errors... } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { filepath=null; btnDownload.setText("Internet Connection Failed.\n"+e.getMessage()); e.printStackTrace(); } Log.i("filepath:"," "+filepath) ; return filepath; } }

    Read the article

  • How to insert and reterive key from registry editor

    - by deepa
    Hi.. I am new to cryptography.. i have to develop project based on cryptography..In part of my project I have to insert a key to the registry and afterwards i have to reterive the same key for decryption.. i done until getting the path of the registry .. Here i given my code.. import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; public static final String readRegistry(String location, String key) { try { // Run reg query, then read output with StreamReader (internal class) Process process = Runtime.getRuntime().exec("reg query " + '"' + location + "\" /v " + key); StreamReader reader = new StreamReader(process.getInputStream()); reader.start(); process.waitFor(); reader.join(); String output = reader.getResult(); // Output has the following format: // \n<Version information>\n\n<key>\t<registry type>\t<value> if (!output.contains("\t")) { return null; } // Parse out the value String[] parsed = output.split("\t"); return parsed[parsed.length - 1]; } catch (Exception e) { return null; } } static class StreamReader extends Thread { private InputStream is; private StringWriter sw = new StringWriter(); ; public StreamReader(InputStream is) { this.is = is; } public void run() { try { int c; while ((c = is.read()) != -1) { System.out.println("Reading" + c); sw.write(c); } } catch (IOException e) { System.out.println("Exception in run() " + e); } } public String getResult() { System.out.println("Content " + sw.toString()); return sw.toString(); } } public static boolean addValue(String key, String valName, String val) { try { // Run reg query, then read output with StreamReader (internal class) Process process = Runtime.getRuntime().exec("reg add \"" + key + "\" /v \"" + valName + "\" /d \"\\\"" + val + "\\\"\" /f"); StreamReader reader = new StreamReader(process.getInputStream()); reader.start(); process.waitFor(); reader.join(); String output = reader.getResult(); System.out.println("Processing........ggggggggggggggggggggg." + output); // Output has the following format: // \n&lt;Version information&gt;\n\n&lt;key&gt;\t&lt;registry type&gt;\t&lt;value&gt; return output.contains("The operation completed successfully"); } catch (Exception e) { System.out.println("Exception in addValue() " + e); } return false; } public static void main(String[] args) { // Sample usage JAXRDeleteConcept hc = new JAXRDeleteConcept(); System.out.println("Before Insertion"); if (JAXRDeleteConcept.addValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU", "REG_SZ", "Muthus")) { System.out.println("Inserted Successfully"); } String value = JAXRDeleteConcept.readRegistry("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU" , "Project_Key"); System.out.println(value); } } But i dont know how to insert a key in a registry and read the particular key which i inserted..Please help me.. Thanks in advance..

    Read the article

  • java.lang.OutOfMemoryError: bitmap size exceeds VM budget ?

    - by UMMA
    friends, i am using following code to display bitmap on screen and having next and previous buttons to change images. and getting out of memory error New Code HttpGet httpRequest = null; try { httpRequest = new HttpGet(mImage_URL[val]); } catch (Exception e) { return 0; } HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); Bitmap bm; HttpEntity entity = response.getEntity(); BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); InputStream is = bufHttpEntity.getContent(); try { bm = BitmapFactory.decodeStream(is); }catch(Exception ex) { } is.close(); Old Code URL aURL = new URL(mImage_URL[val]); URLConnection conn = aURL.openConnection(); conn.connect(); InputStream is = null; try { is= conn.getInputStream(); }catch(IOException e) { } BufferedInputStream bis = new BufferedInputStream(is); bm = BitmapFactory.decodeStream(bis); bis.close(); is.close(); img.setImageBitmap(bm); and it was giving me error decoder-decode return false. on images of size bigger than 400kb. so after googling i got new code as answer the old code was not giving me out of memory error on those images but decoder-decode return false, so i choosed new code. any one guide me what is the solution and which is the best approach to display live images?

    Read the article

  • How do I get google protocol buffer messages over a socket connection without disconnecting the clie

    - by Dan
    Hi there, I'm attempting to send a .proto message from an iPhone application to a Java server via a socket connection. However so far I'm running into an issue when it comes to the server receiving the data; it only seems to process it after the client connection has been terminated. This points to me that the data is getting sent, but the server is keeping its inputstream open and waiting for more data. Would anyone know how I might go about solving this? The current code (or at least the relevant parts) is as follows: iPhone: Person *person = [[[[Person builder] setId:1] setName:@"Bob"] build]; RequestWrapper *request = [[[RequestWrapper builder] setPerson:person] build]; NSData *data = [request data]; AsyncSocket *socket = [[AsyncSocket alloc] initWithDelegate:self]; if (![socket connectToHost:@"192.168.0.6" onPort:6666 error:nil]){ [self updateLabel:@"Problem connecting to socket!"]; } else { [self updateLabel:@"Sending data to server..."]; [socket writeData:data withTimeout:-1 tag:0]; [self updateLabel:@"Data sent, disconnecting"]; //[socket disconnect]; } Java: try { RequestWrapper wrapper = RequestWrapper.parseFrom(socket.getInputStream()); Person person = wrapper.getPerson(); if (person != null) { System.out.println("Persons name is " + person.getName()); socket.close(); } On running this, it seems to hang on the line where the RequestWrapper is processing the inputStream. I did try replacing the socket writedata method with [request writeToOutputStream:[socket getCFWriteStream]]; Which I thought might work, however I get an error claiming that the "Protocol message contained an invalid tag (zero)". I'm fairly certain that it doesn't contain an invalid tag as the message works when sending it via the writedata method. Any help on the matter would be greatly appreciated! Cheers! Dan (EDIT: I should mention, I am using the metasyntactic gpb code; and the cocoaasyncsocket implementation)

    Read the article

  • FTP server output and accents

    - by James P.
    I've written this little test class to connect up to an FTP server. import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class FTPTest { public static void main(String[] args) { URL url = null; try { url = new URL("ftp://anonymous:[email protected]"); } catch (MalformedURLException e) { e.printStackTrace(); } URLConnection conn = null; try { conn = url.openConnection(); } catch (IOException e) { e.printStackTrace(); } InputStream in = null; try { in = conn.getInputStream(); } catch (IOException e) { e.printStackTrace(); } BufferedInputStream bin = new BufferedInputStream(in); int b; try { while ((b = bin.read()) != -1) { char c = (char) b; System.out.print("" + (char) b); } } catch (IOException e) { e.printStackTrace(); } } } Here's the output: -rw-r--r-- 1 ftp ftp 4700 Apr 30 2007 premier.java -rw-r--r-- 1 ftp ftp 88576 Oct 23 2007 Serie1_1.doc -rw-r--r-- 1 ftp ftp 1401 Nov 21 2006 tp20061121.txt drwxr-xr-x 1 ftp ftp 0 Apr 23 20:04 répertoire Notice the name of the directory at the end of the list. There should be an "é" (e with acute accent) instead of the double character "é". This reminds me of an issue encountered previously with JSF where there was a mix-up between standards. I have little experience with character-encoding though so I'm not sure what's happening. I'm supposing that the server output is in ASCII so how do I adapt the output so it appears correctly in the console?

    Read the article

  • Should all public methods of an API be documented?

    - by cynicalman
    When writing "library" type classes, is it better practice to always write markup documentation (i.e. javadoc) in java or assume that the code can be "self-documenting"? For example, given the following method stub: /** * Copies all readable bytes from the provided input stream to the provided output * stream. The output stream will be flushed, but neither stream will be closed. * * @param inStream an InputStream from which to read bytes. * @param outStream an OutputStream to which to copy the read bytes. * @throws IOException if there are any errors reading or writing. */ public void copyStream(InputStream inStream, OutputStream outStream) throws IOException { // copy the stream } The javadoc seems to be self-evident, and noise that just needs to be updated if the funcion is changed at all. But the sentence about flushing and not closing the stream could be valuable. So, when writing a library, is it best to: a) always document b) document anything that isn't obvious c) never document (code should speak for itself!) I usually use b), myself (since the code can be self-documenting otherwise)...

    Read the article

  • How do you save images to a Blackberry device via HttpConnection?

    - by Kai
    My script fetches xml via httpConnection and saves to persistent store. No problems there. Then I loop through the saved data to compose a list of image url's to fetch via queue. Each of these requests calls the httpConnection thread as so ... public synchronized void run() { HttpConnection connection = (HttpConnection)Connector.open("http://www.somedomain.com/image1.jpg"); connection.setRequestMethod("GET"); String contentType = connection.getHeaderField("Content-type"); InputStream responseData = connection.openInputStream(); connection.close(); outputFinal(responseData, contentType); } public synchronized void outputFinal(InputStream result, String contentType) throws SAXException, ParserConfigurationException, IOException { if(contentType.startsWith("text/")) { // bunch of xml save code that works fine } else if(contentType.equals("image/png") || contentType.equals("image/jpeg") || contentType.equals("image/gif")) { // how to save images here? } else { //default } } What I can't find any good documentation on is how one would take the response data and save it to an image stored on the device. Maybe I just overlooked something very obvious. Any help is very appreciated. Thanks

    Read the article

  • Images from SQL Server JPG/PNG Image Column not being Type Converted to Bitmap in HttpHandlers (cons

    - by kanchirk
    Our Silverlight 3.0 Client consumes Images stored/retrieved on the File System thorough ASP.NET HttpHandlers successfully. We are trying to store and read back Images using a SQL Server 2008 Database. Please find the stripped down code pasted below with the Exception. "Bitmap is not Valid" //Store document to the database private void SaveImageToDatabaseKK(HttpContext context, string pImageFileName) { try { //ADO.NET Entity Framework ImageTable documentDB = new ImageTable(); int intLength = Convert.ToInt32(context.Request.InputStream.Length); //Move the file contents into the Byte array Byte[] arrContent = new Byte[intLength]; context.Request.InputStream.Read(arrContent, 0, intLength); //Insert record into the Document table documentDB.InsertDocument(pImageFileName, arrContent, intLength); } catch { } } =The method to Read Back the Row from the Table and Send it back is below.= private void RetrieveImageFromDatabaseTableKK(HttpContext context, string pImageName) { try { ImageTable documentDB = new ImageTable(); var docRow = documentDB.GetDocument(pImageName); //based on Imagename which is unique //DocData column in table is **Image** if (docRow!=null && docRow.DocData != null && docRow.DocData.Length > 0) { Byte[] bytImage = docRow.DocData; if (bytImage != null && bytImage.Length > 0) { Bitmap newBmp = ConvertToBitmap(context, bytImage ); if (newBmp != null) { newBmp.Save(context.Response.OutputStream, ImageFormat.Jpeg); newBmp.Dispose(); } } } } catch (Exception exRI) { } } // Convert byte array to Bitmap (byte[] to Bitmap) protected Bitmap ConvertToBitmap(byte[] bmp) { if (bmp != null) { try { TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap)); Bitmap b = (Bitmap)tc.ConvertFrom(bmp); **//This is where the Exception Occurs.** return b; } catch (Exception) { } } return null; }

    Read the article

  • How do I read text from a serial port?

    - by user2164
    I am trying to read data off of a Windows serial port through Java. I have the javax.comm libraries and am able to get some data but not correct data. When I read the port into a byte array and convert it to text I get a series of characters but no real text string. I have tried to specify the byte array as being both "UTF-8" and "US-ASCII". Does anyone know how to get real text out of this? Here is my code: while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); System.out.println("Reading from " + portId.getName() + ": "); System.out.println("Read " + numBytes + " bytes"); } System.out.println(new String(readBuffer)); System.out.println(new String(readBuffer, "UTF-8")); System.out.println(new String(readBuffer, "US-ASCII")); the output of the first three lines will not let me copy and paste (I assume because they are not normal characters). Here is the output of the Hex: 78786000e67e9e60061e8606781e66e0869e98e086f89898861878809e1e9880 I am reading from a Hollux GPS device which does output in string format. I know this for sure because I did it through C#. The settings that I am using for communication which I know are right from the work in the C# app are: Baud Rate: 9600 Databits: 8 Stop bit: 1 parity: none

    Read the article

  • why won't Eclipse use the compiler I specify for my project?

    - by codeman73
    I'm using Eclipse 3.3. In my project, I've set the compiler compliance level to 5.0 In the build path for the project. I've added the Java 1.5 JDK in the Installed JREs section and am referencing that System Library in my project build path. However, I'm getting compile errors for a class that implements PreparedStatement for not implementing abstract methods that only exist in Java 1.6 PreparedStatement. Specifically, the methods setAsciiStream(int, InputStream, long) and setAsciiStream(int, InputStream) Strangely enough, it worked when we were compiling it against Java 1.4, which it was originally written for. We added the JREs for Java 1.4 and referenced that system library in the project, and set the project's compiler level to 1.4, and it works fine. But when I do the same changes to try to point to Java 5.0, it instead uses Java 6. Any ideas why? I wrote a similar question earlier, here: http://stackoverflow.com/questions/2540548/how-do-i-get-eclipse-to-use-a-different-compiler-version-for-java I know how you're supposed to choose a different compiler but it seems Eclipse isn't taking it. It seems to be defaulting to Java 6, even though I have deleted all Java 6 JDKs and JREs that I could find. I've also updated the -vm option in my eclipse.ini to point to the Java5 JDK.

    Read the article

  • Problem with DSL and Business Rules creation in Drools

    - by jillika iyer
    Hi, I am using Eclipse with the Drools plugin to create rules. I want to create business rules and main aim is to try and provide the user a set of options which he can use to create rules. For eg:If an Apple can have only 3 colors: I want to provide an option like a drop down so that the user can know before hand which are the options he can use in his rules. Is it possible? I am creating a dsl but unable to still provide the above functionality for a business rule. I am having an error implementing a basic dsl also. The code to add the dsl is as follows in my RuleRunner class() InputStream ruleSource = RuleRunner.class.getClassLoader().getResourceAsStream("/Rule1.dslr"); InputStream dslSource = RuleRunner.class.getClassLoader().getResourceAsStream("/sample-dsl.dsl"); //Load the rules , using DSL addRulesToThisPackage.addPackageFromDrl( new InputStreamReader(ruleSource),new InputStreamReader(dslSource)); I have both the sample-dsl .dsl and Rule1.dslr in my working directory. Error encountered at adding the dsl to the package (last line) Error stack: Exception in thread "main" java.lang.NullPointerException at java.io.Reader.<init>(Unknown Source) at java.io.InputStreamReader.<init>(Unknown Source) at com.org.RuleRunner.loadRuleFile(RuleRunner.java:96) at com.org.RuleRunner.loadRules(RuleRunner.java:48) at com.org.RuleRunner.runStatelessRules(RuleRunner.java:109) at com.org.RulesTest.main(RulesTest.java:41) my dsl file has basic mapping as per the online documentations. The dsl rule I created is: expander sample-dsl.dsl rule "A status changes B status" when There is an A - has an address There is a B - has name then - print updated A and Aaddress End I have created DSL in eclipse. Is the code I added for it to be loaded to my package correct?? Or am I missing something???? It seems like my program is unable to find the dsl? Please help. Can you point me towards the right direction to create a user friendly business rule ?? Thanks. J

    Read the article

  • To have efficient many-to-many relation in Java

    - by Masi
    How can you make the efficient many-to-many -relation from fileID to Words and from word to fileIDs without database -tools like Postgres in Java? I have the following classes. The relation from fileID to words is cheap, but not the reverse, since I need three for -loops for it. My solution is not apparently efficient. Other options may be to create an extra class that have word as an ID with the ArrayList of fileIDs. Reply to JacobM's answer The relevant part of MyFile's constructors is: /** * Synopsis of data in wordToWordConutInFile.txt: * fileID|wordID|wordCount * * Synopsis of the data in the file wordToWordID.txt: * word|wordID **/ /** * Getting words by getting first wordIDs from wordToWordCountInFile.txt and then words in wordToWordID.txt. */ InputStream in2 = new FileInputStream("/home/dev/wordToWordCountInFile.txt"); BufferedReader fi2 = new BufferedReader(new InputStreamReader(in2)); ArrayList<Integer> wordIDs = new ArrayList<Integer>(); String line = null; while ((line = fi2.readLine()) != null) { if ((new Integer(line.split("|")[0]) == currentFileID)) { wordIDs.add(new Integer(line.split("|")[6])); } } in2.close(); // Getting now the words by wordIDs. InputStream in3 = new FileInputStream("/home/dev/wordToWordID.txt"); BufferedReader fi3 = new BufferedReader(new InputStreamReader(in3)); line = null; while ((line = fi3.readLine()) != null) { for (Integer wordID : wordIDs) { if (wordID == (new Integer(line.split("|")[1]))) { this.words.add(new Word(new String(line.split("|")[0]), fileID)); break; } } } in3.close(); this.words.addAll(words); The constructor of Word is at the paste.

    Read the article

  • How can i add image in email body

    - by Kutbi
    final Intent i = new Intent(android.content.Intent.ACTION_SEND); i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ txt.getText().toString()}); i.putExtra(Intent.EXTRA_SUBJECT, "Merry Christmas"); i.setType("text/html"); Spanned html =Html.fromHtml("<html><body>h<b>ell</b>o<img src='http://www.pp.rhul.ac.uk/twiki/pub/TWiki/GnuPlotPlugin/RosenbrockFunctionSample.png'>world</body></html>", new ImageGetter() { InputStream s; public Drawable getDrawable(String url) { try { s = (InputStream) (new URL(url)).getContent(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Drawable d = Drawable.createFromStream(s, null); LogUtil.debug(this, "Got image: " + d.getClass() + ", " + d.getIntrinsicWidth() + "x" + d.getIntrinsicHeight()); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; }},null); i.putExtra(Intent.EXTRA_TEXT, html); startActivity(Intent.createChooser(i, "Send email"));*

    Read the article

  • how do I get eclipse to use a different compiler version for Java?

    - by codeman73
    It seems like this should be a simple task, with the options in the Preferences menu for different JREs and the ability to set different compiler and build paths per project. However, it also seems to simply not work. For example, I have my JAVA_HOME set to a jre for Java 1.6. It's still not clear to me how Eclipse uses this, but it appears to be defaulting to this and not taking the project overrides. I have also installed Java 1.5, and added a JRE for this in eclipse in the Java-Installed JREs section. In my project, I've set the compiler compliance level to 1.5. In the build path for the project, I've added the System Library for the Java 1.5 JRE. However, I'm getting compile errors for a class that implements PreparedStatement for not implementing abstract methods that only exist in Java 1.6 PreparedStatement. Specifically, the methods setAsciiStream(int, InputStream, long) and setAsciiStream(int, InputStream) Strangely enough, it worked when we were compiling it against Java 1.4, which it was originally written for. We added the JREs for Java 1.4 and referenced that system library in the project, and set the project's compiler level to 1.4, and it works fine. But when I do the same changes to try to point to Java 1.5, it instead uses 1.6. Any ideas why?

    Read the article

  • EOFException in ObjectInputStream Only happens with Webstart not by java(w).exe ?!

    - by Houtman
    Hi, Anyone familiar with the differences in starting with Webstart(javaws.exe) compared to starting the app. using java.exe or javaw.exe regarding streams ? This is the exception which i ONLY get when using Webstart : java.io.EOFException at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source) at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source) at java.io.ObjectInputStream.readStreamHeader(Unknown Source) at java.io.ObjectInputStream.<init>(Unknown Source) at fasttools.jtools.dss.api.core.remoting.thinclient.RemoteSocketChannel.<init>(RemoteSocketChannel.java:77) This is how i setup the connections on both sides //==Server side== //Thread{ Socket mClientSocket = cServSock.accept(); new DssServant(mClientSocket).start(); //} DssServant(Socket socket) throws DssException { try { OutputStream mOutputStream = new BufferedOutputStream( socket.getOutputStream() ); cObjectOutputStream = new ObjectOutputStream(mOutputStream); cObjectOutputStream.flush(); //publish streamHeader InputStream mInputStream = new BufferedInputStream( socket.getInputStream() ); cObjectInputStream = new ObjectInputStream(mInputStream); .. } catch (IOException e) { .. } .. } //==Client side== public RemoteSocketChannel(String host, int port, IEventDispatcher eventSubscriptionHandler) throws DssException { cHost = host; port = (port == 0 ? DssServer.PORT : port); try { cSocket = new Socket(cHost, port); OutputStream mOutputStream = new BufferedOutputStream( cSocket.getOutputStream() ); cObjectOut = new ObjectOutputStream(mOutputStream); cObjectOut.flush(); //publish streamHeader InputStream mInputStream = new BufferedInputStream( cSocket.getInputStream() ); cObjectIn = new ObjectInputStream(mInputStream); } catch (IOException e) { .. } .. } Thanks [EDIT] Webstart console says: Java Web Start 1.6.0_19 Using JRE version 1.6.0_19-b04 Java HotSpot(TM) Client VM Server is running same 1.6u19

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >