Search in sources :

Example 61 with InputStream

use of java.io.InputStream in project bazel by bazelbuild.

the class ZipReaderTest method testSimultaneousReads.

@Test
public void testSimultaneousReads() throws IOException {
    byte[] expectedFooData = "This is file foo. It contains a foo.".getBytes(UTF_8);
    byte[] expectedBarData = "This is a different file bar. It contains only a bar.".getBytes(UTF_8);
    try (ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(test))) {
        ZipEntry foo = new ZipEntry("foo");
        foo.setComment("foo comment.");
        foo.setMethod(ZipEntry.DEFLATED);
        zout.putNextEntry(foo);
        zout.write(expectedFooData);
        zout.closeEntry();
        ZipEntry bar = new ZipEntry("bar");
        bar.setComment("bar comment.");
        bar.setMethod(ZipEntry.DEFLATED);
        zout.putNextEntry(bar);
        zout.write(expectedBarData);
        zout.closeEntry();
    }
    try (ZipReader reader = new ZipReader(test, UTF_8)) {
        ZipFileEntry fooEntry = reader.getEntry("foo");
        ZipFileEntry barEntry = reader.getEntry("bar");
        InputStream fooIn = reader.getInputStream(fooEntry);
        InputStream barIn = reader.getInputStream(barEntry);
        byte[] fooData = new byte[expectedFooData.length];
        byte[] barData = new byte[expectedBarData.length];
        fooIn.read(fooData, 0, 10);
        barIn.read(barData, 0, 10);
        fooIn.read(fooData, 10, 10);
        barIn.read(barData, 10, 10);
        fooIn.read(fooData, 20, fooData.length - 20);
        barIn.read(barData, 20, barData.length - 20);
        assertThat(fooData).isEqualTo(expectedFooData);
        assertThat(barData).isEqualTo(expectedBarData);
    }
}
Also used : ZipOutputStream(java.util.zip.ZipOutputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) ZipEntry(java.util.zip.ZipEntry) Test(org.junit.Test)

Example 62 with InputStream

use of java.io.InputStream in project ADWLauncher2 by boombuler.

the class CustomShirtcutActivity method onActivityResult.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        switch(requestCode) {
            case PICK_CUSTOM_PICTURE:
                mBitmap = (Bitmap) data.getParcelableExtra("data");
                if (mBitmap != null) {
                    if (mBitmap.getWidth() > mIconSize)
                        mBitmap = Bitmap.createScaledBitmap(mBitmap, mIconSize, mIconSize, true);
                    btPickIcon.setImageBitmap(mBitmap);
                }
                break;
            case PICK_CUSTOM_ICON:
                Uri photoUri = data.getData();
                try {
                    InputStream is = getContentResolver().openInputStream(photoUri);
                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    BitmapFactory.decodeStream(is, null, opts);
                    BitmapFactory.Options ops2 = new BitmapFactory.Options();
                    int width = mIconSize;
                    float w = opts.outWidth;
                    //int scale = Math.round(w / width);
                    int scale = (int) (w / width);
                    ops2.inSampleSize = scale;
                    is = getContentResolver().openInputStream(photoUri);
                    mBitmap = BitmapFactory.decodeStream(is, null, ops2);
                    if (mBitmap != null) {
                        if (mBitmap.getWidth() > mIconSize)
                            mBitmap = Bitmap.createScaledBitmap(mBitmap, mIconSize, mIconSize, true);
                        btPickIcon.setImageBitmap(mBitmap);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case PICK_FROM_ICON_PACK:
                mBitmap = (Bitmap) data.getParcelableExtra("icon");
                if (mBitmap != null) {
                    if (mBitmap.getWidth() > mIconSize)
                        mBitmap = Bitmap.createScaledBitmap(mBitmap, mIconSize, mIconSize, true);
                    btPickIcon.setImageBitmap(mBitmap);
                }
                break;
            case PICK_STANDARD_MENU:
                String applicationName = getResources().getString(R.string.group_applications);
                String activitiesName = getResources().getString(R.string.shirtcuts_activity);
                String launcheractionsName = getResources().getString(R.string.launcher_actions);
                String shortcutName = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
                if (applicationName != null && applicationName.equals(shortcutName)) {
                    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
                    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                    Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
                    pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
                    startActivityForResult(pickIntent, PICK_STANDARD_APPLICATION);
                } else if (activitiesName != null && activitiesName.equals(shortcutName)) {
                    Intent picker = new Intent();
                    picker.setClass(this, ActivityPickerActivity.class);
                    startActivityForResult(picker, PICK_STANDARD_SHORTCUT);
                } else if (launcheractionsName != null && launcheractionsName.equals(shortcutName)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle(getString(R.string.launcher_actions));
                    final ListAdapter adapter = LauncherActions.getInstance().getSelectActionAdapter();
                    builder.setAdapter(adapter, new Dialog.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            LauncherActions.Action action = (LauncherActions.Action) adapter.getItem(which);
                            Intent result = new Intent();
                            result.putExtra(Intent.EXTRA_SHORTCUT_NAME, action.getName());
                            result.putExtra(Intent.EXTRA_SHORTCUT_INTENT, LauncherActions.getInstance().getIntentForAction(action));
                            ShortcutIconResource iconResource = new ShortcutIconResource();
                            iconResource.packageName = CustomShirtcutActivity.this.getPackageName();
                            iconResource.resourceName = getResources().getResourceName(action.getIconResourceId());
                            result.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
                            onActivityResult(PICK_STANDARD_SHORTCUT, RESULT_OK, result);
                        }
                    });
                    builder.create().show();
                } else {
                    startActivityForResult(data, PICK_STANDARD_SHORTCUT);
                }
                break;
            case PICK_STANDARD_APPLICATION:
                if (mBitmap != null) {
                    mBitmap.recycle();
                    mBitmap = null;
                }
                ComponentName component = data.getComponent();
                ActivityInfo activityInfo = null;
                try {
                    activityInfo = mPackageManager.getActivityInfo(component, 0);
                } catch (NameNotFoundException e) {
                }
                String title = null;
                if (activityInfo != null) {
                    title = activityInfo.loadLabel(mPackageManager).toString();
                    if (title == null) {
                        title = activityInfo.name;
                    }
                    mIntent = data;
                    btPickActivity.setText(title);
                    mBitmap = null;
                    btPickIcon.setImageDrawable(activityInfo.loadIcon(mPackageManager));
                    btPickIcon.setEnabled(true);
                    btOk.setEnabled(true);
                    edLabel.setText(title);
                }
                break;
            case PICK_STANDARD_SHORTCUT:
                if (mBitmap != null) {
                    mBitmap.recycle();
                    mBitmap = null;
                }
                Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
                String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
                Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
                Drawable icon = null;
                if (bitmap != null) {
                    icon = new FastBitmapDrawable(Bitmap.createScaledBitmap(bitmap, mIconSize, mIconSize, true));
                    mBitmap = bitmap;
                } else {
                    Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
                    if (extra != null && extra instanceof ShortcutIconResource) {
                        try {
                            ShortcutIconResource iconResource = (ShortcutIconResource) extra;
                            Resources resources = mPackageManager.getResourcesForApplication(iconResource.packageName);
                            final int id = resources.getIdentifier(iconResource.resourceName, null, null);
                            icon = resources.getDrawable(id);
                            mBitmap = Utilities.createIconBitmap(icon, this);
                        } catch (Exception e) {
                        }
                    }
                }
                if (icon == null) {
                    icon = getPackageManager().getDefaultActivityIcon();
                }
                mIntent = intent;
                btPickActivity.setText(name);
                btPickIcon.setImageDrawable(icon);
                btPickIcon.setEnabled(true);
                btOk.setEnabled(true);
                edLabel.setText(name);
                break;
            default:
                break;
        }
    }
}
Also used : AlertDialog(android.app.AlertDialog) DialogInterface(android.content.DialogInterface) ShortcutIconResource(android.content.Intent.ShortcutIconResource) Uri(android.net.Uri) Bitmap(android.graphics.Bitmap) Dialog(android.app.Dialog) AlertDialog(android.app.AlertDialog) ComponentName(android.content.ComponentName) BitmapFactory(android.graphics.BitmapFactory) ListAdapter(android.widget.ListAdapter) ActivityInfo(android.content.pm.ActivityInfo) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) InputStream(java.io.InputStream) Drawable(android.graphics.drawable.Drawable) Intent(android.content.Intent) Parcelable(android.os.Parcelable) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) LauncherActions(org.adw.launcher2.actions.LauncherActions) Resources(android.content.res.Resources)

Example 63 with InputStream

use of java.io.InputStream in project YCSB by brianfrankcooper.

the class RiakKVClient method loadDefaultProperties.

private void loadDefaultProperties() {
    InputStream propFile = RiakKVClient.class.getClassLoader().getResourceAsStream("riak.properties");
    Properties propsPF = new Properties(System.getProperties());
    try {
        propsPF.load(propFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
    hosts = propsPF.getProperty(HOST_PROPERTY).split(",");
    port = Integer.parseInt(propsPF.getProperty(PORT_PROPERTY));
    bucketType = propsPF.getProperty(BUCKET_TYPE_PROPERTY);
    rvalue = new Quorum(Integer.parseInt(propsPF.getProperty(R_VALUE_PROPERTY)));
    wvalue = new Quorum(Integer.parseInt(propsPF.getProperty(W_VALUE_PROPERTY)));
    readRetryCount = Integer.parseInt(propsPF.getProperty(READ_RETRY_COUNT_PROPERTY));
    waitTimeBeforeRetry = Integer.parseInt(propsPF.getProperty(WAIT_TIME_BEFORE_RETRY_PROPERTY));
    transactionTimeLimit = Integer.parseInt(propsPF.getProperty(TRANSACTION_TIME_LIMIT_PROPERTY));
    strongConsistency = Boolean.parseBoolean(propsPF.getProperty(STRONG_CONSISTENCY_PROPERTY));
    strongConsistentScansBucketType = propsPF.getProperty(STRONG_CONSISTENT_SCANS_BUCKET_TYPE_PROPERTY);
    debug = Boolean.parseBoolean(propsPF.getProperty(DEBUG_PROPERTY));
}
Also used : Quorum(com.basho.riak.client.api.cap.Quorum) InputStream(java.io.InputStream) IOException(java.io.IOException) StoreBucketProperties(com.basho.riak.client.api.commands.buckets.StoreBucketProperties)

Example 64 with InputStream

use of java.io.InputStream in project YCSB by brianfrankcooper.

the class S3Client method readFromStorage.

/**
  * Download an object from S3.
  *
  * @param bucket
  *            The name of the bucket
  * @param key
  *            The file key of the object to upload/update.
  * @param result
  *            The Hash map where data from the object are written
  *
  */
protected Status readFromStorage(String bucket, String key, HashMap<String, ByteIterator> result, SSECustomerKey ssecLocal) {
    try {
        Map.Entry<S3Object, ObjectMetadata> objectAndMetadata = getS3ObjectAndMetadata(bucket, key, ssecLocal);
        //consuming the stream
        InputStream objectData = objectAndMetadata.getKey().getObjectContent();
        // writing the stream to bytes and to results
        int sizeOfFile = (int) objectAndMetadata.getValue().getContentLength();
        byte[] inputStreamToByte = new byte[sizeOfFile];
        objectData.read(inputStreamToByte, 0, sizeOfFile);
        result.put(key, new ByteArrayByteIterator(inputStreamToByte));
        objectData.close();
        objectAndMetadata.getKey().close();
    } catch (Exception e) {
        System.err.println("Not possible to get the object " + key);
        e.printStackTrace();
        return Status.ERROR;
    }
    return Status.OK;
}
Also used : ByteArrayByteIterator(com.yahoo.ycsb.ByteArrayByteIterator) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) S3Object(com.amazonaws.services.s3.model.S3Object) HashMap(java.util.HashMap) ObjectMetadata(com.amazonaws.services.s3.model.ObjectMetadata) DBException(com.yahoo.ycsb.DBException)

Example 65 with InputStream

use of java.io.InputStream in project YCSB by brianfrankcooper.

the class RestClient method httpExecute.

private int httpExecute(HttpEntityEnclosingRequestBase request, String data) throws IOException {
    requestTimedout.setIsSatisfied(false);
    Thread timer = new Thread(new Timer(execTimeout, requestTimedout));
    timer.start();
    int responseCode = 200;
    for (int i = 0; i < headers.length; i = i + 2) {
        request.setHeader(headers[i], headers[i + 1]);
    }
    InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(data.getBytes()), ContentType.APPLICATION_FORM_URLENCODED);
    reqEntity.setChunked(true);
    request.setEntity(reqEntity);
    CloseableHttpResponse response = client.execute(request);
    responseCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    // If null entity don't bother about connection release.
    if (responseEntity != null) {
        InputStream stream = responseEntity.getContent();
        if (compressedResponse) {
            stream = new GZIPInputStream(stream);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        StringBuffer responseContent = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            if (requestTimedout.isSatisfied()) {
                // Must avoid memory leak.
                reader.close();
                stream.close();
                EntityUtils.consumeQuietly(responseEntity);
                response.close();
                client.close();
                throw new TimeoutException();
            }
            responseContent.append(line);
        }
        timer.interrupt();
        // Closing the input stream will trigger connection release.
        stream.close();
    }
    EntityUtils.consumeQuietly(responseEntity);
    response.close();
    client.close();
    return responseCode;
}
Also used : HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) InputStreamEntity(org.apache.http.entity.InputStreamEntity) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BufferedReader(java.io.BufferedReader)

Aggregations

InputStream (java.io.InputStream)14643 IOException (java.io.IOException)5387 ByteArrayInputStream (java.io.ByteArrayInputStream)3349 Test (org.junit.Test)3233 FileInputStream (java.io.FileInputStream)2806 File (java.io.File)2033 OutputStream (java.io.OutputStream)1307 InputStreamReader (java.io.InputStreamReader)1280 URL (java.net.URL)1267 BufferedInputStream (java.io.BufferedInputStream)1241 FileOutputStream (java.io.FileOutputStream)920 ByteArrayOutputStream (java.io.ByteArrayOutputStream)907 BufferedReader (java.io.BufferedReader)852 ArrayList (java.util.ArrayList)692 FileNotFoundException (java.io.FileNotFoundException)679 Properties (java.util.Properties)668 HttpURLConnection (java.net.HttpURLConnection)483 HashMap (java.util.HashMap)471 GZIPInputStream (java.util.zip.GZIPInputStream)394 Map (java.util.Map)337