List of usage examples for java.io FileInputStream available
public int available() throws IOException
From source file:es.javocsoft.android.lib.toolbox.ToolBox.java
/** * Reads data from the application internal storage data folder. * // w w w . ja v a 2 s . c om * @param context * @param fileName * @return * @throws Exception */ public static byte[] storage_readDataFromInternalStorage(Context context, String fileName) throws Exception { FileInputStream fIn; try { fIn = context.openFileInput(fileName); byte[] buffer = new byte[fIn.available()]; fIn.read(buffer); fIn.close(); return buffer; } catch (Exception e) { throw new Exception("Error reading data '" + fileName + "' (internal storage) : " + e.getMessage(), e); } }
From source file:jp.aegif.alfresco.online_webdav.WebDAVMethod.java
/** * Set the request/response details/*w w w .j a va 2 s.c o m*/ * * @param req * HttpServletRequest * @param resp * HttpServletResponse * @param registry * ServiceRegistry * @param rootNode * NodeRef */ public void setDetails(final HttpServletRequest req, HttpServletResponse resp, WebDAVHelper davHelper, NodeRef rootNode) { // Wrap the request so that it is 'retryable'. Calls to getInputStream() and getReader() will result in the // request body being read into an intermediate file. this.m_request = new HttpServletRequestWrapper(req) { @Override public ServletInputStream getInputStream() throws IOException { if (WebDAVMethod.this.m_reader != null) { throw new IllegalStateException("Reader in use"); } if (WebDAVMethod.this.m_inputStream == null) { final FileInputStream in = new FileInputStream(getRequestBodyAsFile(req)); WebDAVMethod.this.m_inputStream = new ServletInputStream() { @Override public int read() throws IOException { return in.read(); } @Override public int read(byte b[]) throws IOException { return in.read(b); } @Override public int read(byte b[], int off, int len) throws IOException { return in.read(b, off, len); } @Override public long skip(long n) throws IOException { return in.skip(n); } @Override public int available() throws IOException { return in.available(); } @Override public void close() throws IOException { in.close(); } @Override public void mark(int readlimit) { in.mark(readlimit); } @Override public void reset() throws IOException { in.reset(); } @Override public boolean markSupported() { return in.markSupported(); } }; } return WebDAVMethod.this.m_inputStream; } @Override public BufferedReader getReader() throws IOException { if (WebDAVMethod.this.m_inputStream != null) { throw new IllegalStateException("Input Stream in use"); } if (WebDAVMethod.this.m_reader == null) { String encoding = req.getCharacterEncoding(); WebDAVMethod.this.m_reader = new BufferedReader( new InputStreamReader(new FileInputStream(getRequestBodyAsFile(req)), encoding == null ? "ISO-8859-1" : encoding)); } return WebDAVMethod.this.m_reader; } }; this.m_response = resp; this.m_davHelper = davHelper; this.m_rootNodeRef = rootNode; this.m_strPath = m_davHelper.getRepositoryPath(m_request); }
From source file:im.vector.activity.RoomActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { if (CommonActivityUtils.shouldRestartApp()) { Log.e(LOG_TAG, "Restart the application."); CommonActivityUtils.restartApp(this); }/* w w w . j a v a 2s . c o m*/ super.onCreate(savedInstanceState); setContentView(R.layout.activity_room); Intent intent = getIntent(); if (!intent.hasExtra(EXTRA_ROOM_ID)) { Log.e(LOG_TAG, "No room ID extra."); finish(); return; } // the user has tapped on the "View" notification button if ((null != intent.getAction()) && (intent.getAction().startsWith(NotificationUtils.TAP_TO_VIEW_ACTION))) { // remove any pending notifications NotificationManager notificationsManager = (NotificationManager) this .getSystemService(Context.NOTIFICATION_SERVICE); notificationsManager.cancelAll(); } mPendingThumbnailUrl = null; mPendingMediaUrl = null; mPendingMimeType = null; mPendingFilename = null; if (null != savedInstanceState) { if (savedInstanceState.containsKey(PENDING_THUMBNAIL_URL)) { mPendingThumbnailUrl = savedInstanceState.getString(PENDING_THUMBNAIL_URL); } if (savedInstanceState.containsKey(PENDING_MEDIA_URL)) { mPendingMediaUrl = savedInstanceState.getString(PENDING_MEDIA_URL); } if (savedInstanceState.containsKey(PENDING_MIMETYPE)) { mPendingMimeType = savedInstanceState.getString(PENDING_MIMETYPE); } if (savedInstanceState.containsKey(PENDING_FILENAME)) { mPendingFilename = savedInstanceState.getString(PENDING_FILENAME); } } String roomId = intent.getStringExtra(EXTRA_ROOM_ID); Log.i(LOG_TAG, "Displaying " + roomId); mEditText = (EditText) findViewById(R.id.editText_messageBox); mSendButton = (ImageButton) findViewById(R.id.button_send); mSendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // send the previewed image ? if (null != mPendingThumbnailUrl) { boolean sendMedia = true; // check if the media could be resized if ("image/jpeg".equals(mPendingMimeType)) { System.gc(); FileInputStream imageStream = null; try { Uri uri = Uri.parse(mPendingMediaUrl); final String filename = uri.getPath(); final int rotationAngle = ImageUtils.getRotationAngleForBitmap(RoomActivity.this, uri); imageStream = new FileInputStream(new File(filename)); int fileSize = imageStream.available(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.outWidth = -1; options.outHeight = -1; // get the full size bitmap Bitmap fullSizeBitmap = null; try { fullSizeBitmap = BitmapFactory.decodeStream(imageStream, null, options); } catch (OutOfMemoryError e) { Log.e(LOG_TAG, "Onclick BitmapFactory.decodeStream : " + e.getMessage()); } final ImageSize fullImageSize = new ImageSize(options.outWidth, options.outHeight); imageStream.close(); int maxSide = (fullImageSize.mHeight > fullImageSize.mWidth) ? fullImageSize.mHeight : fullImageSize.mWidth; // can be rescaled ? if (maxSide > SMALL_IMAGE_SIZE) { ImageSize largeImageSize = null; int divider = 2; if (maxSide > LARGE_IMAGE_SIZE) { largeImageSize = new ImageSize((fullImageSize.mWidth + (divider - 1)) / divider, (fullImageSize.mHeight + (divider - 1)) / divider); divider *= 2; } ImageSize mediumImageSize = null; if (maxSide > MEDIUM_IMAGE_SIZE) { mediumImageSize = new ImageSize( (fullImageSize.mWidth + (divider - 1)) / divider, (fullImageSize.mHeight + (divider - 1)) / divider); divider *= 2; } ImageSize smallImageSize = null; if (maxSide > SMALL_IMAGE_SIZE) { smallImageSize = new ImageSize((fullImageSize.mWidth + (divider - 1)) / divider, (fullImageSize.mHeight + (divider - 1)) / divider); } FragmentManager fm = getSupportFragmentManager(); ImageSizeSelectionDialogFragment fragment = (ImageSizeSelectionDialogFragment) fm .findFragmentByTag(TAG_FRAGMENT_IMAGE_SIZE_DIALOG); if (fragment != null) { fragment.dismissAllowingStateLoss(); } final ArrayList<ImageCompressionDescription> textsList = new ArrayList<ImageCompressionDescription>(); final ArrayList<ImageSize> sizesList = new ArrayList<ImageSize>(); ImageCompressionDescription description = new ImageCompressionDescription(); description.mCompressionText = getString(R.string.compression_opt_list_original); description.mCompressionInfoText = fullImageSize.mWidth + "x" + fullImageSize.mHeight + " (" + android.text.format.Formatter.formatFileSize(RoomActivity.this, fileSize) + ")"; textsList.add(description); sizesList.add(fullImageSize); if (null != largeImageSize) { int estFileSize = largeImageSize.mWidth * largeImageSize.mHeight * 2 / 10 / 1024 * 1024; description = new ImageCompressionDescription(); description.mCompressionText = getString(R.string.compression_opt_list_large); description.mCompressionInfoText = largeImageSize.mWidth + "x" + largeImageSize.mHeight + " (~" + android.text.format.Formatter .formatFileSize(RoomActivity.this, estFileSize) + ")"; textsList.add(description); sizesList.add(largeImageSize); } if (null != mediumImageSize) { int estFileSize = mediumImageSize.mWidth * mediumImageSize.mHeight * 2 / 10 / 1024 * 1024; description = new ImageCompressionDescription(); description.mCompressionText = getString(R.string.compression_opt_list_medium); description.mCompressionInfoText = mediumImageSize.mWidth + "x" + mediumImageSize.mHeight + " (~" + android.text.format.Formatter .formatFileSize(RoomActivity.this, estFileSize) + ")"; textsList.add(description); sizesList.add(mediumImageSize); } if (null != smallImageSize) { int estFileSize = smallImageSize.mWidth * smallImageSize.mHeight * 2 / 10 / 1024 * 1024; description = new ImageCompressionDescription(); description.mCompressionText = getString(R.string.compression_opt_list_small); description.mCompressionInfoText = smallImageSize.mWidth + "x" + smallImageSize.mHeight + " (~" + android.text.format.Formatter .formatFileSize(RoomActivity.this, estFileSize) + ")"; textsList.add(description); sizesList.add(smallImageSize); } fragment = ImageSizeSelectionDialogFragment.newInstance(textsList); fragment.setListener(new ImageSizeSelectionDialogFragment.ImageSizeListener() { @Override public void onSelected(int pos) { final int fPos = pos; RoomActivity.this.runOnUiThread(new Runnable() { @Override public void run() { try { // pos == 0 -> original if (0 != fPos) { FileInputStream imageStream = new FileInputStream( new File(filename)); ImageSize imageSize = sizesList.get(fPos); InputStream resizeBitmapStream = null; try { resizeBitmapStream = ImageUtils.resizeImage(imageStream, -1, (fullImageSize.mWidth + imageSize.mWidth - 1) / imageSize.mWidth, 75); } catch (OutOfMemoryError ex) { Log.e(LOG_TAG, "Onclick BitmapFactory.createScaledBitmap : " + ex.getMessage()); } catch (Exception e) { Log.e(LOG_TAG, "Onclick BitmapFactory.createScaledBitmap failed : " + e.getMessage()); } if (null != resizeBitmapStream) { String bitmapURL = mMediasCache.saveMedia( resizeBitmapStream, null, "image/jpeg"); if (null != bitmapURL) { mPendingMediaUrl = bitmapURL; } resizeBitmapStream.close(); // try to apply exif rotation if (0 != rotationAngle) { // rotate the image content ImageUtils.rotateImage(RoomActivity.this, mPendingMediaUrl, rotationAngle, mMediasCache); } } } } catch (Exception e) { Log.e(LOG_TAG, "Onclick " + e.getMessage()); } // mConsoleMessageListFragment.uploadImageContent(mPendingThumbnailUrl, mPendingMediaUrl, mPendingFilename, mPendingMimeType); mPendingThumbnailUrl = null; mPendingMediaUrl = null; mPendingMimeType = null; mPendingFilename = null; manageSendMoreButtons(); } }); } }); fragment.show(fm, TAG_FRAGMENT_IMAGE_SIZE_DIALOG); sendMedia = false; } } catch (Exception e) { Log.e(LOG_TAG, "Onclick " + e.getMessage()); } } if (sendMedia) { mConsoleMessageListFragment.uploadImageContent(mPendingThumbnailUrl, mPendingMediaUrl, mPendingFilename, mPendingMimeType); mPendingThumbnailUrl = null; mPendingMediaUrl = null; mPendingMimeType = null; mPendingFilename = null; manageSendMoreButtons(); } } else { String body = mEditText.getText().toString(); sendMessage(body); mEditText.setText(""); } } }); mAttachmentButton = (ImageButton) findViewById(R.id.button_more); mAttachmentButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FragmentManager fm = getSupportFragmentManager(); IconAndTextDialogFragment fragment = (IconAndTextDialogFragment) fm .findFragmentByTag(TAG_FRAGMENT_ATTACHMENTS_DIALOG); if (fragment != null) { fragment.dismissAllowingStateLoss(); } final Integer[] messages = new Integer[] { R.string.option_send_files, R.string.option_take_photo, }; final Integer[] icons = new Integer[] { R.drawable.ic_material_file, // R.string.option_send_files R.drawable.ic_material_camera, // R.string.action_members }; fragment = IconAndTextDialogFragment.newInstance(icons, messages, null, RoomActivity.this.getResources().getColor(R.color.vector_title_color)); fragment.setOnClickListener(new IconAndTextDialogFragment.OnItemClickListener() { @Override public void onItemClick(IconAndTextDialogFragment dialogFragment, int position) { Integer selectedVal = messages[position]; if (selectedVal == R.string.option_send_files) { RoomActivity.this.launchFileSelectionIntent(); } else if (selectedVal == R.string.option_take_photo) { RoomActivity.this.launchCamera(); } } }); fragment.show(fm, TAG_FRAGMENT_INVITATION_MEMBERS_DIALOG); } }); mEditText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(android.text.Editable s) { MXLatestChatMessageCache latestChatMessageCache = RoomActivity.this.mLatestChatMessageCache; String textInPlace = latestChatMessageCache.getLatestText(RoomActivity.this, mRoom.getRoomId()); // check if there is really an update // avoid useless updates (initializations..) if (!mIgnoreTextUpdate && !textInPlace.equals(mEditText.getText().toString())) { latestChatMessageCache.updateLatestMessage(RoomActivity.this, mRoom.getRoomId(), mEditText.getText().toString()); handleTypingNotification(mEditText.getText().length() != 0); } manageSendMoreButtons(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); mSession = getSession(intent); if (mSession == null) { Log.e(LOG_TAG, "No MXSession."); finish(); return; } mMyUserId = mSession.getCredentials().userId; CommonActivityUtils.resumeEventStream(this); mRoom = mSession.getDataHandler().getRoom(roomId); FragmentManager fm = getSupportFragmentManager(); mConsoleMessageListFragment = (ConsoleMessageListFragment) fm .findFragmentByTag(TAG_FRAGMENT_MATRIX_MESSAGE_LIST); if (mConsoleMessageListFragment == null) { // this fragment displays messages and handles all message logic mConsoleMessageListFragment = ConsoleMessageListFragment.newInstance(mMyUserId, mRoom.getRoomId(), org.matrix.androidsdk.R.layout.fragment_matrix_message_list_fragment); fm.beginTransaction().add(R.id.anchor_fragment_messages, mConsoleMessageListFragment, TAG_FRAGMENT_MATRIX_MESSAGE_LIST).commit(); } // set general room information setTitle(mRoom.getName(mMyUserId)); setTopic(mRoom.getTopic()); // listen for room name or topic changes mRoom.addEventListener(mEventListener); // The error listener needs the current activity mSession.setFailureCallback(new ErrorListener(this)); mImagePreviewLayout = findViewById(R.id.room_image_preview_layout); mImagePreviewView = (ImageView) findViewById(R.id.room_image_preview); mImagePreviewButton = (ImageButton) findViewById(R.id.room_image_preview_cancel_button); // the user cancels the image selection mImagePreviewButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mPendingThumbnailUrl = null; mPendingMediaUrl = null; mPendingMimeType = null; mPendingFilename = null; manageSendMoreButtons(); } }); mLatestChatMessageCache = Matrix.getInstance(this).getDefaultLatestChatMessageCache(); mMediasCache = Matrix.getInstance(this).getMediasCache(); // some medias must be sent while opening the chat if (intent.hasExtra(HomeActivity.EXTRA_ROOM_INTENT)) { final Intent mediaIntent = intent.getParcelableExtra(HomeActivity.EXTRA_ROOM_INTENT); // sanity check if (null != mediaIntent) { mEditText.postDelayed(new Runnable() { @Override public void run() { sendMediasIntent(mediaIntent); } }, 1000); } } }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractSubscriptionController.java
@RequestMapping(value = { "/{customPageTag}/{serviceInstanceUuid}/{resourceType}" }, method = RequestMethod.GET) @ResponseBody/*from w ww . j a v a 2s . c o m*/ public void getCustomSelector(@PathVariable String serviceInstanceUuid, @PathVariable String resourceType, @PathVariable String customPageTag, ModelMap map, HttpServletResponse response) { FileInputStream fileinputstream = null; try { Service service = connectorConfigurationManager.getInstance(serviceInstanceUuid).getService(); ServiceResourceType selectedResourceType = null; for (ServiceResourceType serviceResourceType : service.getServiceResourceTypes()) { if (serviceResourceType.getResourceTypeName().equals(resourceType)) { selectedResourceType = serviceResourceType; break; } } String jspPath = ""; String cssdkFilesDirectory = FilenameUtils.concat( config.getValue(Names.com_citrix_cpbm_portal_settings_services_datapath), service.getServiceName() + "_" + service.getVendorVersion()); if (selectedResourceType != null) { if (customPageTag.equalsIgnoreCase("customComponentSelector")) { jspPath = selectedResourceType.getComponentSelector(); } else if (customPageTag.equalsIgnoreCase("customEditorTag")) { jspPath = selectedResourceType.getEditor(); } if (jspPath != null && !jspPath.trim().equals("")) { String absoluteJspPath = FilenameUtils.concat(cssdkFilesDirectory, jspPath); fileinputstream = new FileInputStream(absoluteJspPath); if (fileinputstream != null) { int numberBytes = fileinputstream.available(); byte bytearray[] = new byte[numberBytes]; fileinputstream.read(bytearray); response.setContentType("text/html"); OutputStream outputStream = response.getOutputStream(); response.setContentLength(numberBytes); outputStream.write(bytearray); outputStream.flush(); outputStream.close(); fileinputstream.close(); return; } } } } catch (FileNotFoundException e) { logger.debug("###File not found in retrieving custom ui contribution."); } catch (IOException e) { logger.debug("###IO Error in retrieving custom ui contribution."); } response.setStatus(HttpServletResponse.SC_NOT_FOUND); }
From source file:com.zhengde163.netguard.ServiceSinkhole.java
private void showUpdateNotification(String name, String url) { Intent download;//from w w w. jav a2 s. c o m File tmpFile = new File(Environment.getExternalStorageDirectory(), fileName); String status; if (!tmpFile.exists()) { status = getString(R.string.msg_update); download = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); } else { int size = 0; try { FileInputStream in = new FileInputStream(tmpFile); size = in.available(); in.close(); } catch (Exception e) { // Do nothing. } if (size > 2000000) { status = "?, "; download = new Intent(Intent.ACTION_VIEW); download.setDataAndType(Uri.fromFile(tmpFile), "application/vnd.android.package-archive"); } else { return; } } PendingIntent pi = PendingIntent.getActivity(this, 0, download, PendingIntent.FLAG_UPDATE_CURRENT); TypedValue tv = new TypedValue(); getTheme().resolveAttribute(R.attr.colorPrimary, tv, true); NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_security_white_24dp).setContentTitle(getString(R.string.app_name)) .setContentText(status).setContentIntent(pi).setColor(tv.data).setOngoing(false) .setAutoCancel(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder.setCategory(Notification.CATEGORY_STATUS).setVisibility(Notification.VISIBILITY_SECRET); } NotificationCompat.BigTextStyle notification = new NotificationCompat.BigTextStyle(builder); notification.bigText(getString(R.string.msg_update)); notification.setSummaryText(name); NotificationManagerCompat.from(this).notify(NOTIFY_UPDATE, notification.build()); }
From source file:com.naryx.tagfusion.expression.function.file.Zip.java
/** * Performing Zip() operation/*from w ww . j ava 2 s . co m*/ * * @param session * @param zipfile * @param src * @param recurse * @param prefixx * @param compLvl * @param filter * @param overwrite * @param newpath * @throws cfmRunTimeException * @throws IOException */ protected void zipOperation(cfSession session, ZipArchiveOutputStream zipOut, File src, boolean recurse, String prefix, int compLvl, FilenameFilter filter, String newpath) throws cfmRunTimeException { if (src != null) { FileInputStream nextFileIn; ZipArchiveEntry nextEntry = null; byte[] buffer = new byte[4096]; int readBytes; zipOut.setLevel(compLvl); try { List<File> files = new ArrayList<File>(); int srcDirLen; if (src.isFile()) { String parentPath = src.getParent(); srcDirLen = parentPath.endsWith(File.separator) ? parentPath.length() : parentPath.length() + 1; files.add(src); } else { String parentPath = src.getAbsolutePath(); srcDirLen = parentPath.endsWith(File.separator) ? parentPath.length() : parentPath.length() + 1; getFiles(src, files, recurse, filter); } int noFiles = files.size(); File nextFile; boolean isDir; for (int i = 0; i < noFiles; i++) { nextFile = (File) files.get(i); isDir = nextFile.isDirectory(); if (noFiles == 1 && newpath != null) { // NEWPATH nextEntry = new ZipArchiveEntry(newpath.replace('\\', '/') + (isDir ? "/" : "")); } else { // PREFIX nextEntry = new ZipArchiveEntry( prefix + nextFile.getAbsolutePath().substring(srcDirLen).replace('\\', '/') + (isDir ? "/" : "")); } try { zipOut.putArchiveEntry(nextEntry); } catch (IOException e) { throwException(session, "Failed to add entry to zip file [" + nextEntry + "]. Reason: " + e.getMessage()); } if (!isDir) { nextEntry.setTime(nextFile.lastModified()); nextFileIn = new FileInputStream(nextFile); try { while (nextFileIn.available() > 0) { readBytes = nextFileIn.read(buffer); zipOut.write(buffer, 0, readBytes); } zipOut.flush(); } catch (IOException e) { throwException(session, "Failed to write entry [" + nextEntry + "] to zip file. Reason: " + e.getMessage()); } finally { // nextEntry close StreamUtil.closeStream(nextFileIn); } } zipOut.closeArchiveEntry(); } } catch (IOException ioe) { throwException(session, "Failed to create zip file: " + ioe.getMessage()); } } }
From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java
public int uploadFile(String sourceFileUri, String fileName) { String upLoadServerUri = ""; upLoadServerUri = "http://ip.roaming4world.com/esstel/file-transfer/file_upload.php"; HttpURLConnection conn = null; DataOutputStream dos = null;// ww w .j a v a 2 s . c o m String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { Log.e("uploadFile", "Source File Does not exist"); return 0; } try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP // connection to // the URL conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", sourceFileUri); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + multimediaMsg + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of // maximum size bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); // close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); } return serverResponseCode; }
From source file:org.matrix.console.activity.RoomActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { Intent intent = getIntent();// w ww . j av a2 s .com if (CommonActivityUtils.shouldRestartApp()) { if (intent.hasExtra(EXTRA_START_FROM_PUSH)) { Log.e(LOG_TAG, "Room activity is started from push but the application should be restarted"); } else { Log.e(LOG_TAG, "Restart the application."); CommonActivityUtils.restartApp(this); } } super.onCreate(savedInstanceState); setContentView(R.layout.activity_room); if (!intent.hasExtra(EXTRA_ROOM_ID)) { Log.e(LOG_TAG, "No room ID extra."); finish(); return; } if (intent.hasExtra(EXTRA_START_CALL_ID)) { mCallId = intent.getStringExtra(EXTRA_START_CALL_ID); } // the user has tapped on the "View" notification button if ((null != intent.getAction()) && (intent.getAction().startsWith(NotificationUtils.TAP_TO_VIEW_ACTION))) { // remove any pending notifications NotificationManager notificationsManager = (NotificationManager) this .getSystemService(Context.NOTIFICATION_SERVICE); notificationsManager.cancelAll(); } mPendingThumbnailUrl = null; mPendingMediaUrl = null; mPendingMimeType = null; mPendingFilename = null; if (null != savedInstanceState) { if (savedInstanceState.containsKey(PENDING_THUMBNAIL_URL)) { mPendingThumbnailUrl = savedInstanceState.getString(PENDING_THUMBNAIL_URL); Log.d(LOG_TAG, "Restore mPendingThumbnailUrl " + mPendingThumbnailUrl); } if (savedInstanceState.containsKey(PENDING_MEDIA_URL)) { mPendingMediaUrl = savedInstanceState.getString(PENDING_MEDIA_URL); Log.d(LOG_TAG, "Restore mPendingMediaUrl " + mPendingMediaUrl); } if (savedInstanceState.containsKey(PENDING_MIMETYPE)) { mPendingMimeType = savedInstanceState.getString(PENDING_MIMETYPE); Log.d(LOG_TAG, "Restore mPendingMimeType " + mPendingMimeType); } if (savedInstanceState.containsKey(PENDING_FILENAME)) { mPendingFilename = savedInstanceState.getString(PENDING_FILENAME); Log.d(LOG_TAG, "Restore mPendingFilename " + mPendingFilename); } } String roomId = intent.getStringExtra(EXTRA_ROOM_ID); Log.i(LOG_TAG, "Displaying " + roomId); mEditText = (EditText) findViewById(R.id.editText_messageBox); mSendButton = (ImageButton) findViewById(R.id.button_send); mSendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // send the previewed image ? if (null != mPendingThumbnailUrl) { boolean sendMedia = true; // check if the media could be resized if ("image/jpeg".equals(mPendingMimeType)) { System.gc(); FileInputStream imageStream = null; try { Uri uri = Uri.parse(mPendingMediaUrl); final String filename = uri.getPath(); final int rotationAngle = ImageUtils.getRotationAngleForBitmap(RoomActivity.this, uri); imageStream = new FileInputStream(new File(filename)); int fileSize = imageStream.available(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.outWidth = -1; options.outHeight = -1; // get the full size bitmap Bitmap fullSizeBitmap = null; try { fullSizeBitmap = BitmapFactory.decodeStream(imageStream, null, options); } catch (OutOfMemoryError e) { Log.e(LOG_TAG, "Onclick BitmapFactory.decodeStream : " + e.getMessage()); } final ImageSize fullImageSize = new ImageSize(options.outWidth, options.outHeight); imageStream.close(); int maxSide = (fullImageSize.mHeight > fullImageSize.mWidth) ? fullImageSize.mHeight : fullImageSize.mWidth; // can be rescaled ? if (maxSide > SMALL_IMAGE_SIZE) { ImageSize largeImageSize = null; int divider = 2; if (maxSide > LARGE_IMAGE_SIZE) { largeImageSize = new ImageSize((fullImageSize.mWidth + (divider - 1)) / divider, (fullImageSize.mHeight + (divider - 1)) / divider); divider *= 2; } ImageSize mediumImageSize = null; if (maxSide > MEDIUM_IMAGE_SIZE) { mediumImageSize = new ImageSize( (fullImageSize.mWidth + (divider - 1)) / divider, (fullImageSize.mHeight + (divider - 1)) / divider); divider *= 2; } ImageSize smallImageSize = null; if (maxSide > SMALL_IMAGE_SIZE) { smallImageSize = new ImageSize((fullImageSize.mWidth + (divider - 1)) / divider, (fullImageSize.mHeight + (divider - 1)) / divider); } FragmentManager fm = getSupportFragmentManager(); ImageSizeSelectionDialogFragment fragment = (ImageSizeSelectionDialogFragment) fm .findFragmentByTag(TAG_FRAGMENT_IMAGE_SIZE_DIALOG); if (fragment != null) { fragment.dismissAllowingStateLoss(); } final ArrayList<ImageCompressionDescription> textsList = new ArrayList<ImageCompressionDescription>(); final ArrayList<ImageSize> sizesList = new ArrayList<ImageSize>(); ImageCompressionDescription description = new ImageCompressionDescription(); description.mCompressionText = getString(R.string.compression_opt_list_original); description.mCompressionInfoText = fullImageSize.mWidth + "x" + fullImageSize.mHeight + " (" + android.text.format.Formatter.formatFileSize(RoomActivity.this, fileSize) + ")"; textsList.add(description); sizesList.add(fullImageSize); if (null != largeImageSize) { int estFileSize = largeImageSize.mWidth * largeImageSize.mHeight * 2 / 10 / 1024 * 1024; description = new ImageCompressionDescription(); description.mCompressionText = getString(R.string.compression_opt_list_large); description.mCompressionInfoText = largeImageSize.mWidth + "x" + largeImageSize.mHeight + " (~" + android.text.format.Formatter .formatFileSize(RoomActivity.this, estFileSize) + ")"; textsList.add(description); sizesList.add(largeImageSize); } if (null != mediumImageSize) { int estFileSize = mediumImageSize.mWidth * mediumImageSize.mHeight * 2 / 10 / 1024 * 1024; description = new ImageCompressionDescription(); description.mCompressionText = getString(R.string.compression_opt_list_medium); description.mCompressionInfoText = mediumImageSize.mWidth + "x" + mediumImageSize.mHeight + " (~" + android.text.format.Formatter .formatFileSize(RoomActivity.this, estFileSize) + ")"; textsList.add(description); sizesList.add(mediumImageSize); } if (null != smallImageSize) { int estFileSize = smallImageSize.mWidth * smallImageSize.mHeight * 2 / 10 / 1024 * 1024; description = new ImageCompressionDescription(); description.mCompressionText = getString(R.string.compression_opt_list_small); description.mCompressionInfoText = smallImageSize.mWidth + "x" + smallImageSize.mHeight + " (~" + android.text.format.Formatter .formatFileSize(RoomActivity.this, estFileSize) + ")"; textsList.add(description); sizesList.add(smallImageSize); } fragment = ImageSizeSelectionDialogFragment.newInstance(textsList); fragment.setListener(new ImageSizeSelectionDialogFragment.ImageSizeListener() { @Override public void onSelected(int pos) { final int fPos = pos; RoomActivity.this.runOnUiThread(new Runnable() { @Override public void run() { try { // pos == 0 -> original if (0 != fPos) { FileInputStream imageStream = new FileInputStream( new File(filename)); ImageSize imageSize = sizesList.get(fPos); InputStream resizeBitmapStream = null; try { resizeBitmapStream = ImageUtils.resizeImage(imageStream, -1, (fullImageSize.mWidth + imageSize.mWidth - 1) / imageSize.mWidth, 75); } catch (OutOfMemoryError ex) { Log.e(LOG_TAG, "Onclick BitmapFactory.createScaledBitmap : " + ex.getMessage()); } catch (Exception e) { Log.e(LOG_TAG, "Onclick BitmapFactory.createScaledBitmap failed : " + e.getMessage()); } if (null != resizeBitmapStream) { String bitmapURL = mMediasCache.saveMedia( resizeBitmapStream, null, "image/jpeg"); if (null != bitmapURL) { mPendingMediaUrl = bitmapURL; } resizeBitmapStream.close(); // try to apply exif rotation if (0 != rotationAngle) { // rotate the image content ImageUtils.rotateImage(RoomActivity.this, mPendingMediaUrl, rotationAngle, mMediasCache); } } } } catch (Exception e) { Log.e(LOG_TAG, "Onclick " + e.getMessage()); } // mConsoleMessageListFragment.uploadImageContent(mPendingThumbnailUrl, mPendingMediaUrl, mPendingFilename, mPendingMimeType); mPendingThumbnailUrl = null; mPendingMediaUrl = null; mPendingMimeType = null; mPendingFilename = null; manageSendMoreButtons(); } }); } }); fragment.show(fm, TAG_FRAGMENT_IMAGE_SIZE_DIALOG); sendMedia = false; } } catch (Exception e) { Log.e(LOG_TAG, "Onclick " + e.getMessage()); } } if (sendMedia) { mConsoleMessageListFragment.uploadImageContent(mPendingThumbnailUrl, mPendingMediaUrl, mPendingFilename, mPendingMimeType); mPendingThumbnailUrl = null; mPendingMediaUrl = null; mPendingMimeType = null; mPendingFilename = null; manageSendMoreButtons(); } } else { String body = mEditText.getText().toString(); sendMessage(body); mEditText.setText(""); } } }); mAttachmentButton = (ImageButton) findViewById(R.id.button_more); mAttachmentButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FragmentManager fm = getSupportFragmentManager(); IconAndTextDialogFragment fragment = (IconAndTextDialogFragment) fm .findFragmentByTag(TAG_FRAGMENT_ATTACHMENTS_DIALOG); if (fragment != null) { fragment.dismissAllowingStateLoss(); } final Integer[] messages = new Integer[] { R.string.option_send_files, R.string.option_take_photo, R.string.option_take_video }; final Integer[] icons = new Integer[] { R.drawable.ic_material_file, // R.string.option_send_files R.drawable.ic_material_camera, // R.string.action_members R.drawable.ic_material_videocam, // R.string.action_members }; fragment = IconAndTextDialogFragment.newInstance(icons, messages); fragment.setOnClickListener(new IconAndTextDialogFragment.OnItemClickListener() { @Override public void onItemClick(IconAndTextDialogFragment dialogFragment, int position) { Integer selectedVal = messages[position]; if (selectedVal == R.string.option_send_files) { RoomActivity.this.launchFileSelectionIntent(); } else if (selectedVal == R.string.option_take_photo) { RoomActivity.this.launchCamera(); } else if (selectedVal == R.string.option_take_video) { RoomActivity.this.launchVideo(); } } }); fragment.show(fm, TAG_FRAGMENT_INVITATION_MEMBERS_DIALOG); } }); mEditText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(android.text.Editable s) { MXLatestChatMessageCache latestChatMessageCache = RoomActivity.this.mLatestChatMessageCache; String textInPlace = latestChatMessageCache.getLatestText(RoomActivity.this, mRoom.getRoomId()); // check if there is really an update // avoid useless updates (initializations..) if (!mIgnoreTextUpdate && !textInPlace.equals(mEditText.getText().toString())) { latestChatMessageCache.updateLatestMessage(RoomActivity.this, mRoom.getRoomId(), mEditText.getText().toString()); handleTypingNotification(mEditText.getText().length() != 0); } manageSendMoreButtons(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); mSession = getSession(intent); if (mSession == null) { Log.e(LOG_TAG, "No MXSession."); finish(); return; } mMyUserId = mSession.getCredentials().userId; CommonActivityUtils.resumeEventStream(this); mRoom = mSession.getDataHandler().getRoom(roomId); FragmentManager fm = getSupportFragmentManager(); mConsoleMessageListFragment = (ConsoleMessageListFragment) fm .findFragmentByTag(TAG_FRAGMENT_MATRIX_MESSAGE_LIST); if (mConsoleMessageListFragment == null) { // this fragment displays messages and handles all message logic mConsoleMessageListFragment = ConsoleMessageListFragment.newInstance(mMyUserId, mRoom.getRoomId(), org.matrix.androidsdk.R.layout.fragment_matrix_message_list_fragment); fm.beginTransaction().add(R.id.anchor_fragment_messages, mConsoleMessageListFragment, TAG_FRAGMENT_MATRIX_MESSAGE_LIST).commit(); } // set general room information setTitle(mRoom.getName(mMyUserId)); setTopic(mRoom.getTopic()); mImagePreviewLayout = findViewById(R.id.room_image_preview_layout); mImagePreviewView = (ImageView) findViewById(R.id.room_image_preview); mImagePreviewButton = (ImageButton) findViewById(R.id.room_image_preview_cancel_button); // the user cancels the image selection mImagePreviewButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mPendingThumbnailUrl = null; mPendingMediaUrl = null; mPendingMimeType = null; mPendingFilename = null; manageSendMoreButtons(); } }); mLatestChatMessageCache = Matrix.getInstance(this).getDefaultLatestChatMessageCache(); mMediasCache = Matrix.getInstance(this).getMediasCache(); // some medias must be sent while opening the chat if (intent.hasExtra(HomeActivity.EXTRA_ROOM_INTENT)) { final Intent mediaIntent = intent.getParcelableExtra(HomeActivity.EXTRA_ROOM_INTENT); // sanity check if (null != mediaIntent) { mEditText.postDelayed(new Runnable() { @Override public void run() { sendMediasIntent(mediaIntent); } }, 1000); } } }
From source file:com.netscape.cms.servlet.csadmin.ConfigurationUtils.java
public static void restoreCertsFromP12(String p12File, String p12Pass) throws Exception { // TODO: The PKCS #12 file is already imported in security_database.py. // This method should be removed. byte b[] = new byte[1000000]; FileInputStream fis = new FileInputStream(p12File); while (fis.available() > 0) fis.read(b);// w ww .ja v a 2s . c om fis.close(); ByteArrayInputStream bis = new ByteArrayInputStream(b); StringBuffer reason = new StringBuffer(); Password password = new Password(p12Pass.toCharArray()); try { PFX pfx = (PFX) (new PFX.Template()).decode(bis); boolean verifypfx = pfx.verifyAuthSafes(password, reason); if (!verifypfx) { throw new IOException("PKCS #12 password is incorrect"); } AuthenticatedSafes safes = pfx.getAuthSafes(); Vector<Vector<Object>> pkeyinfo_collection = new Vector<Vector<Object>>(); Vector<Vector<Object>> cert_collection = new Vector<Vector<Object>>(); logger.debug("Importing PKCS #12 data"); for (int i = 0; i < safes.getSize(); i++) { logger.debug("- Safe #" + i + ":"); SEQUENCE scontent = safes.getSafeContentsAt(null, i); for (int j = 0; j < scontent.size(); j++) { SafeBag bag = (SafeBag) scontent.elementAt(j); OBJECT_IDENTIFIER oid = bag.getBagType(); if (oid.equals(SafeBag.PKCS8_SHROUDED_KEY_BAG)) { logger.debug(" - Bag #" + j + ": key"); byte[] epki = bag.getBagContent().getEncoded(); SET bagAttrs = bag.getBagAttributes(); String subjectDN = null; for (int k = 0; k < bagAttrs.size(); k++) { Attribute attrs = (Attribute) bagAttrs.elementAt(k); OBJECT_IDENTIFIER aoid = attrs.getType(); if (aoid.equals(SafeBag.FRIENDLY_NAME)) { SET val = attrs.getValues(); ANY ss = (ANY) val.elementAt(0); ByteArrayInputStream bbis = new ByteArrayInputStream(ss.getEncoded()); BMPString sss = (BMPString) new BMPString.Template().decode(bbis); subjectDN = sss.toString(); logger.debug(" Subject DN: " + subjectDN); break; } } // pkeyinfo_v stores EncryptedPrivateKeyInfo // (byte[]) and subject DN (String) Vector<Object> pkeyinfo_v = new Vector<Object>(); pkeyinfo_v.addElement(epki); if (subjectDN != null) pkeyinfo_v.addElement(subjectDN); pkeyinfo_collection.addElement(pkeyinfo_v); } else if (oid.equals(SafeBag.CERT_BAG)) { logger.debug(" - Bag #" + j + ": certificate"); CertBag cbag = (CertBag) bag.getInterpretedBagContent(); OCTET_STRING str = (OCTET_STRING) cbag.getInterpretedCert(); byte[] x509cert = str.toByteArray(); SET bagAttrs = bag.getBagAttributes(); String nickname = null; if (bagAttrs != null) { for (int k = 0; k < bagAttrs.size(); k++) { Attribute attrs = (Attribute) bagAttrs.elementAt(k); OBJECT_IDENTIFIER aoid = attrs.getType(); if (aoid.equals(SafeBag.FRIENDLY_NAME)) { SET val = attrs.getValues(); ANY ss = (ANY) val.elementAt(0); ByteArrayInputStream bbis = new ByteArrayInputStream(ss.getEncoded()); BMPString sss = (BMPString) (new BMPString.Template()).decode(bbis); nickname = sss.toString(); logger.debug(" Nickname: " + nickname); break; } } } X509CertImpl certImpl = new X509CertImpl(x509cert); logger.debug(" Serial number: " + certImpl.getSerialNumber()); try { certImpl.checkValidity(); logger.debug(" Status: valid"); } catch (CertificateExpiredException | CertificateNotYetValidException e) { logger.debug(" Status: " + e); continue; } // cert_v stores certificate (byte[]) and nickname (String) Vector<Object> cert_v = new Vector<Object>(); cert_v.addElement(x509cert); if (nickname != null) cert_v.addElement(nickname); cert_collection.addElement(cert_v); } } } importKeyCert(password, pkeyinfo_collection, cert_collection); } catch (Exception e) { throw e; } finally { if (password != null) { password.clear(); } } }
From source file:io.cloudex.cloud.impl.google.GoogleCloudServiceImpl.java
/** * Upload the provided file into cloud storage * THis is what Google returns:// w w w .java2 s. c o m * <pre> * CONFIG: { "kind": "storage#object", "id": "ecarf/umbel_links.nt_out.gz/1397227987451000", "selfLink": "https://www.googleapis.com/storage/v1beta2/b/ecarf/o/umbel_links.nt_out.gz", "name": "umbel_links.nt_out.gz", "bucket": "ecarf", "generation": "1397227987451000", "metageneration": "1", "contentType": "application/x-gzip", "updated": "2014-04-11T14:53:07.339Z", "storageClass": "STANDARD", "size": "8474390", "md5Hash": "UPhXcZZGbD9198OhQcdnvQ==", "owner": { "entity": "user-00b4903a97e56638621f0643dc282444442a11b19141d3c7b425c4d17895dcf6", "entityId": "00b4903a97e56638621f0643dc282444442a11b19141d3c7b425c4d17895dcf6" }, "crc32c": "3twYkA==", "etag": "CPj48u7X2L0CEAE=" } </pre> * @param filename * @param bucket * @throws IOException */ @Override public io.cloudex.framework.cloud.entities.StorageObject uploadFileToCloudStorage(String filename, String bucket, Callback callback) throws IOException { FileInputStream fileStream = new FileInputStream(filename); String contentType; boolean gzipDisabled; if (GzipUtils.isCompressedFilename(filename)) { contentType = Constants.GZIP_CONTENT_TYPE; gzipDisabled = true; } else { contentType = Files.probeContentType((new File(filename)).toPath()); if (contentType == null) { contentType = Constants.BINARY_CONTENT_TYPE; } gzipDisabled = false; } InputStreamContent mediaContent = new InputStreamContent(contentType, fileStream); // Not strictly necessary, but allows optimization in the cloud. mediaContent.setLength(fileStream.available()); Storage.Objects.Insert insertObject = getStorage().objects() .insert(bucket, new StorageObject().setName( StringUtils.substringAfterLast(filename, FileUtils.PATH_SEPARATOR)), mediaContent) .setOauthToken(this.getOAuthToken()); insertObject.getMediaHttpUploader().setProgressListener(new UploadProgressListener(callback)) .setDisableGZipContent(gzipDisabled); // For small files, you may wish to call setDirectUploadEnabled(true), to // reduce the number of HTTP requests made to the server. if (mediaContent.getLength() > 0 && mediaContent.getLength() <= 4 * FileUtils.ONE_MB /* 2MB */) { insertObject.getMediaHttpUploader().setDirectUploadEnabled(true); } StorageObject object = null; try { object = insertObject.execute(); } catch (IOException e) { log.error("Error whilst uploading file", e); ApiUtils.block(5); // try again object = insertObject.execute(); } return this.getCloudExStorageObject(object, bucket); }