Example usage for java.io InputStream reset

List of usage examples for java.io InputStream reset

Introduction

In this page you can find the example usage for java.io InputStream reset.

Prototype

public synchronized void reset() throws IOException 

Source Link

Document

Repositions this stream to the position at the time the mark method was last called on this input stream.

Usage

From source file:io.sledge.core.impl.extractor.SledgeApplicationPackageExtractor.java

@Override
public DeploymentConfiguration getDeploymentConfiguration(InputStream appPackageInputStream) {
    DeploymentConfiguration deploymentConfig = null;
    ZipInputStream zipStream = new ZipInputStream(new BufferedInputStream(appPackageInputStream),
            Charset.forName("UTF-8"));

    try {// w  w  w .j  ava2s. com
        byte[] buffer = new byte[2048];
        ZipEntry zipEntry = null;

        while ((zipEntry = zipStream.getNextEntry()) != null) {

            if (zipEntry.isDirectory()) {
                zipStream.closeEntry();
                continue;
            }

            if (zipEntry.getName().startsWith(SLEDGEFILE_XML)) {
                ByteArrayOutputStream output = new ByteArrayOutputStream();

                int length;
                while ((length = zipStream.read(buffer, 0, buffer.length)) >= 0) {
                    output.write(buffer, 0, length);
                }

                DeploymentConfigurationReader deploymentConfigReader = new DeploymentConfigurationReaderXml();
                deploymentConfig = deploymentConfigReader
                        .parseDeploymentConfiguration(new ByteArrayInputStream(output.toByteArray()));

                zipStream.closeEntry();

                // Stop here, the file is read
                break;
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        try {
            zipStream.close();
            appPackageInputStream.reset();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    return deploymentConfig;
}

From source file:org.apache.tika.parser.microsoft.POIFSContainerDetector.java

public MediaType detect(InputStream input, Metadata metadata) throws IOException {
    // Check if we have access to the document
    if (input == null) {
        return MediaType.OCTET_STREAM;
    }//from   w  w w . jav a 2s  . c  o m

    // If this is a TikaInputStream wrapping an already
    // parsed NPOIFileSystem/DirectoryNode, just get the
    // names from the root:
    TikaInputStream tis = TikaInputStream.cast(input);
    Set<String> names = null;
    if (tis != null) {
        Object container = tis.getOpenContainer();
        if (container instanceof NPOIFSFileSystem) {
            names = getTopLevelNames(((NPOIFSFileSystem) container).getRoot());
        } else if (container instanceof DirectoryNode) {
            names = getTopLevelNames((DirectoryNode) container);
        }
    }

    if (names == null) {
        // Check if the document starts with the OLE header
        input.mark(8);
        try {
            if (input.read() != 0xd0 || input.read() != 0xcf || input.read() != 0x11 || input.read() != 0xe0
                    || input.read() != 0xa1 || input.read() != 0xb1 || input.read() != 0x1a
                    || input.read() != 0xe1) {
                return MediaType.OCTET_STREAM;
            }
        } finally {
            input.reset();
        }
    }

    // We can only detect the exact type when given a TikaInputStream
    if (names == null && tis != null) {
        // Look for known top level entry names to detect the document type
        names = getTopLevelNames(tis);
    }

    // Detect based on the names (as available)
    if (tis != null && tis.getOpenContainer() != null && tis.getOpenContainer() instanceof NPOIFSFileSystem) {
        return detect(names, ((NPOIFSFileSystem) tis.getOpenContainer()).getRoot());
    } else {
        return detect(names, null);
    }
}

From source file:com.dsi.ant.antplus.pluginsampler.weightscale.Activity_WeightScaleSampler.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.e("WeightScale", "onCreate");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_weightscale);

    layoutControllerList = new ArrayList<Closeable>();

    button_requestBasicMeasurement = (Button) findViewById(R.id.button_requestBasicMeasurement);
    button_requestAdvancedMeasurement = (Button) findViewById(R.id.button_requestAdvancedMeasurement);
    button_requestCapabilities = (Button) findViewById(R.id.button_requestCapabilities);
    button_configUserProfile = (Button) findViewById(R.id.button_configUserProfile);
    button_requestDownloadAllHistory = (Button) findViewById(R.id.button_requestDownloadAllHistory);

    linearLayout_FitDataView = (LinearLayout) findViewById(R.id.linearLayout_WeightScaleCards);

    tv_status = (TextView) findViewById(R.id.textView_Status);
    tv_estTimestamp = (TextView) findViewById(R.id.textView_EstTimestamp);
    tv_bodyWeightResult = (TextView) findViewById(R.id.textView_BodyWeightResult);
    tv_bodyWeightBroadcast = (TextView) findViewById(R.id.textView_BodyWeightBroadcast);
    tv_bodyFatPercentage = (TextView) findViewById(R.id.textView_BodyFatPercentage);
    tv_hydrationPercentage = (TextView) findViewById(R.id.textView_HydrationPercentage);
    tv_muscleMass = (TextView) findViewById(R.id.textView_MuscleMass);
    tv_boneMass = (TextView) findViewById(R.id.textView_BoneMass);
    tv_activeMetabolicRate = (TextView) findViewById(R.id.textView_ActiveMetabolicRate);
    tv_basalMetabolicRate = (TextView) findViewById(R.id.textView_BasalMetabolicRate);

    tv_userProfileExchangeSupport = (TextView) findViewById(R.id.textView_UserProfileExchangeSupport);
    tv_userProfileSelected = (TextView) findViewById(R.id.textView_UserProfileSelected);
    tv_userProfileID = (TextView) findViewById(R.id.textView_UserProfileID);
    tv_historySupport = (TextView) findViewById(R.id.textView_HistorySupport);

    tv_hardwareRevision = (TextView) findViewById(R.id.textView_HardwareRevision);
    tv_manufacturerID = (TextView) findViewById(R.id.textView_ManufacturerID);
    tv_modelNumber = (TextView) findViewById(R.id.textView_ModelNumber);

    tv_mainSoftwareRevision = (TextView) findViewById(R.id.textView_MainSoftwareRevision);
    tv_supplementalSoftwareRevision = (TextView) findViewById(R.id.textView_SupplementalSoftwareRevision);
    tv_serialNumber = (TextView) findViewById(R.id.textView_SerialNumber);

    userProfile.age = 32;/*from  w  ww . j  a v  a 2 s  .  co  m*/
    userProfile.height = 160;
    userProfile.gender = Gender.FEMALE;
    userProfile.lifetimeAthlete = false;
    userProfile.activityLevel = 4;

    button_requestBasicMeasurement.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            boolean submitted = wgtPcc.requestBasicMeasurement(new IBasicMeasurementFinishedReceiver() {

                @Override
                public void onBasicMeasurementFinished(long estTimestamp, EnumSet<EventFlag> eventFlags,
                        final WeightScaleRequestStatus status, final BigDecimal bodyWeight) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setRequestButtonsEnabled(true);
                            if (checkRequestResult(status)) {
                                if (bodyWeight.intValue() == -1)
                                    tv_bodyWeightResult.setText("Invalid");
                                else
                                    tv_bodyWeightResult.setText(String.valueOf(bodyWeight) + "kg");
                            }
                        }
                    });
                }
            });

            if (submitted) {
                setRequestButtonsEnabled(false);
                resetWeightRequestedDataDisplay("Computing");
            }
        }
    });

    button_requestAdvancedMeasurement.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            boolean submitted = wgtPcc.requestAdvancedMeasurement(new IAdvancedMeasurementFinishedReceiver() {
                @Override
                public void onAdvancedMeasurementFinished(long estTimestamp, EnumSet<EventFlag> eventFlags,
                        final WeightScaleRequestStatus status, final AdvancedMeasurement measurement) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setRequestButtonsEnabled(true);
                            if (checkRequestResult(status)) {
                                if (measurement.bodyWeight.intValue() == -1)
                                    tv_bodyWeightResult.setText("Invalid");
                                else
                                    tv_bodyWeightResult.setText(String.valueOf(measurement.bodyWeight) + "kg");
                                if (measurement.hydrationPercentage.intValue() == -1)
                                    tv_hydrationPercentage.setText("Invalid");
                                else
                                    tv_hydrationPercentage
                                            .setText(String.valueOf(measurement.hydrationPercentage) + "%");
                                if (measurement.bodyFatPercentage.intValue() == -1)
                                    tv_bodyFatPercentage.setText("Invalid");
                                else
                                    tv_bodyFatPercentage
                                            .setText(String.valueOf(measurement.bodyFatPercentage) + "%");
                                if (measurement.muscleMass.intValue() == -1)
                                    tv_muscleMass.setText("Invalid");
                                else
                                    tv_muscleMass.setText(String.valueOf(measurement.muscleMass) + "kg");
                                if (measurement.boneMass.intValue() == -1)
                                    tv_boneMass.setText("Invalid");
                                else
                                    tv_boneMass.setText(String.valueOf(measurement.boneMass) + "kg");
                                if (measurement.activeMetabolicRate.intValue() == -1)
                                    tv_activeMetabolicRate.setText("Invalid");
                                else
                                    tv_activeMetabolicRate
                                            .setText(String.valueOf(measurement.activeMetabolicRate) + "kcal");
                                if (measurement.basalMetabolicRate.intValue() == -1)
                                    tv_basalMetabolicRate.setText("Invalid");
                                else
                                    tv_basalMetabolicRate
                                            .setText(String.valueOf(measurement.basalMetabolicRate) + "kcal");
                            }
                        }
                    });
                }
            }, userProfile);

            if (submitted) {
                setRequestButtonsEnabled(false);
                resetWeightRequestedDataDisplay("Computing");
            }
        }
    });

    button_requestCapabilities.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean submitted = wgtPcc.requestCapabilities(new ICapabilitiesRequestFinishedReceiver() {
                @Override
                public void onCapabilitiesRequestFinished(long estTimestamp, EnumSet<EventFlag> eventFlags,
                        final WeightScaleRequestStatus status, final int userProfileID,
                        final boolean historySupport, final boolean userProfileExchangeSupport,
                        final boolean userProfileSelected) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setRequestButtonsEnabled(true);

                            if (checkRequestResult(status)) {
                                tv_bodyWeightResult.setText("Req Capab Success");
                                tv_userProfileExchangeSupport
                                        .setText(String.valueOf(userProfileExchangeSupport));
                                tv_userProfileSelected.setText(String.valueOf(userProfileSelected));
                                tv_historySupport.setText(String.valueOf(historySupport));
                                if (userProfileID == -1)
                                    tv_userProfileID.setText("UNASSIGNED");
                                else
                                    tv_userProfileID.setText(String.valueOf(userProfileID));
                            }
                        }
                    });
                }
            });

            if (submitted) {
                setRequestButtonsEnabled(false);
                resetWeightRequestedDataDisplay("Req Capab");
            }
        }
    });

    button_configUserProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Dialog_ConfigUserProfile dialog = new Dialog_ConfigUserProfile(userProfile);
            dialog.show(getSupportFragmentManager(), "Configure User Profile");
        }
    });

    button_requestDownloadAllHistory.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            antFsProgressDialog = new ProgressDialog(Activity_WeightScaleSampler.this);
            antFsProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            antFsProgressDialog.setMessage("Sending Request...");
            antFsProgressDialog.setCancelable(false);
            antFsProgressDialog.setIndeterminate(false);

            boolean submitted = wgtPcc.requestDownloadAllHistory(new IDownloadAllHistoryFinishedReceiver() {
                //Process the final result of the download
                @Override
                public void onDownloadAllHistoryFinished(final AntFsRequestStatus status) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setRequestButtonsEnabled(true);
                            antFsProgressDialog.dismiss();

                            switch (status) {
                            case SUCCESS:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory finished successfully.", Toast.LENGTH_SHORT).show();
                                break;
                            case FAIL_ALREADY_BUSY_EXTERNAL:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory failed, device busy.", Toast.LENGTH_SHORT).show();
                                break;
                            case FAIL_DEVICE_COMMUNICATION_FAILURE:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory failed, communication error.", Toast.LENGTH_SHORT)
                                        .show();
                                break;
                            case FAIL_NOT_SUPPORTED:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory failed, feature not supported in weight scale.",
                                        Toast.LENGTH_LONG).show();
                                break;
                            case FAIL_AUTHENTICATION_REJECTED:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory failed, authentication rejected.",
                                        Toast.LENGTH_LONG).show();
                                break;
                            case FAIL_DEVICE_TRANSMISSION_LOST:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory failed, transmission lost.", Toast.LENGTH_SHORT)
                                        .show();
                                break;
                            case FAIL_PLUGINS_SERVICE_VERSION:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "Failed: Plugin Service Upgrade Required?", Toast.LENGTH_SHORT).show();
                                break;
                            case UNRECOGNIZED:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "Failed: UNRECOGNIZED. PluginLib Upgrade Required?", Toast.LENGTH_SHORT)
                                        .show();
                                break;
                            default:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory failed, unrecognized code: " + status,
                                        Toast.LENGTH_SHORT).show();
                                break;
                            }
                        }
                    });
                }
            },
                    //Written using FIT SDK 7.10 Library (fit.jar)
                    new IFitFileDownloadedReceiver() {
                        //Process incoming FIT file(s)
                        @Override
                        public void onNewFitFileDownloaded(FitFile downloadedFitFile) {

                            InputStream fitFile = downloadedFitFile.getInputStream();

                            if (!Decode.checkIntegrity(fitFile)) {
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "FIT file integrity check failed.", Toast.LENGTH_SHORT).show();
                                return;
                            }

                            //Must reset InputStream after reading it for integrity check
                            try {
                                fitFile.reset();
                            } catch (IOException e) {
                                //No IOExceptions thrown from ByteArrayInputStream
                            }

                            FileIdMesgListener fileIdMesgListener = new FileIdMesgListener() {
                                @Override
                                public void onMesg(final FileIdMesg mesg) {
                                    //Add File ID Layout to the list of layouts displayed to the user
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            layoutControllerList.add(new LayoutController_FileId(
                                                    getLayoutInflater(), linearLayout_FitDataView, mesg));
                                        }
                                    });
                                }
                            };

                            UserProfileMesgListener userProfileMesgListener = new UserProfileMesgListener() {
                                @Override
                                public void onMesg(final UserProfileMesg mesg) {
                                    //Add User Profile Layout to the list of layouts displayed to the user
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            layoutControllerList
                                                    .add(new LayoutController_WeightScaleUserProfile(
                                                            getLayoutInflater(), linearLayout_FitDataView,
                                                            mesg));
                                        }
                                    });
                                }
                            };

                            WeightScaleMesgListener weightScaleMesgListener = new WeightScaleMesgListener() {
                                @Override
                                public void onMesg(final WeightScaleMesg mesg) {
                                    //Add Weight Scale Layout to the list of layouts displayed to the user
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            layoutControllerList.add(new LayoutController_WeightScale(
                                                    getLayoutInflater(), linearLayout_FitDataView, mesg));
                                        }
                                    });
                                }
                            };

                            DeviceInfoMesgListener deviceInfoMesgListener = new DeviceInfoMesgListener() {
                                @Override
                                public void onMesg(final DeviceInfoMesg mesg) {
                                    //Add Device Information Layout to the list of layouts displayed to the user
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            layoutControllerList.add(new LayoutController_WeightScaleDeviceInfo(
                                                    getLayoutInflater(), linearLayout_FitDataView, mesg));
                                        }
                                    });
                                }
                            };

                            MesgBroadcaster mesgBroadcaster = new MesgBroadcaster();
                            mesgBroadcaster.addListener(fileIdMesgListener);
                            mesgBroadcaster.addListener(userProfileMesgListener);
                            mesgBroadcaster.addListener(weightScaleMesgListener);
                            mesgBroadcaster.addListener(deviceInfoMesgListener);

                            try {
                                mesgBroadcaster.run(fitFile);
                            } catch (FitRuntimeException e) {
                                Log.e("WeightScaleSampler", "Error decoding FIT file: " + e.toString());
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(Activity_WeightScaleSampler.this,
                                                "Error decoding FIT file", Toast.LENGTH_LONG).show();
                                    }
                                });
                            }
                        }

                    }, new IAntFsProgressUpdateReceiver() {
                        @Override
                        public void onNewAntFsProgressUpdate(final AntFsState state,
                                final long transferredBytes, final long totalBytes) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    switch (state) {
                                    //In Link state and requesting to link with the device in order to pass to Auth state
                                    case LINK_REQUESTING_LINK:
                                        antFsProgressDialog.setMax(4);
                                        antFsProgressDialog.setProgress(1);
                                        antFsProgressDialog.setMessage("In Link State: Requesting Link.");
                                        break;

                                    //In Authentication state, processing authentication commands
                                    case AUTHENTICATION:
                                        antFsProgressDialog.setMax(4);
                                        antFsProgressDialog.setProgress(2);
                                        antFsProgressDialog.setMessage("In Authentication State.");
                                        break;

                                    //In Authentication state, currently attempting to pair with the device
                                    //NOTE: Feedback SHOULD be given to the user here as pairing typically requires user interaction with the device
                                    case AUTHENTICATION_REQUESTING_PAIRING:
                                        antFsProgressDialog.setMax(4);
                                        antFsProgressDialog.setProgress(2);
                                        antFsProgressDialog
                                                .setMessage("In Authentication State: User Pairing Requested.");
                                        break;

                                    //In Transport state, no requests are currently being processed
                                    case TRANSPORT_IDLE:
                                        antFsProgressDialog.setMax(4);
                                        antFsProgressDialog.setProgress(3);
                                        antFsProgressDialog.setMessage(
                                                "Requesting download (In Transport State: Idle)...");
                                        break;

                                    //In Transport state, files are currently being downloaded
                                    case TRANSPORT_DOWNLOADING:
                                        antFsProgressDialog.setMessage("In Transport State: Downloading.");
                                        antFsProgressDialog.setMax(100);

                                        if (transferredBytes >= 0 && totalBytes > 0) {
                                            int progress = (int) (transferredBytes * 100 / totalBytes);
                                            antFsProgressDialog.setProgress(progress);
                                        }
                                        break;

                                    case UNRECOGNIZED:
                                        Toast.makeText(Activity_WeightScaleSampler.this,
                                                "Failed: UNRECOGNIZED. PluginLib Upgrade Required?",
                                                Toast.LENGTH_SHORT).show();
                                        break;

                                    default:
                                        Log.w("WeightScaleSampler",
                                                "Unknown ANT-FS State Code Received: " + state);
                                        break;
                                    }
                                }
                            });
                        }
                    });

            if (submitted) {
                clearLayoutList();

                setRequestButtonsEnabled(false);
                antFsProgressDialog.show();
            }
        }
    });

    resetPcc();
}

From source file:de.micromata.genome.test.web.SimHttpServletRequest.java

protected void setInputStream(final InputStream servletIs) {
    this.servletIs = new ServletInputStream() {

        public int available() throws IOException {
            return servletIs.available();
        }/*from w  w  w  .j a v  a2  s .c  o m*/

        public void close() throws IOException {
            servletIs.close();
        }

        public boolean equals(Object obj) {
            return servletIs.equals(obj);
        }

        public int hashCode() {
            return servletIs.hashCode();
        }

        public void mark(int readlimit) {
            servletIs.mark(readlimit);
        }

        public boolean markSupported() {
            return servletIs.markSupported();
        }

        public int read(byte[] b, int off, int len) throws IOException {
            return servletIs.read(b, off, len);
        }

        public int read(byte[] b) throws IOException {
            return servletIs.read(b);
        }

        public void reset() throws IOException {
            servletIs.reset();
        }

        public long skip(long n) throws IOException {
            return servletIs.skip(n);
        }

        public String toString() {
            return servletIs.toString();
        }

        @Override
        public int read() throws IOException {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:org.springframework.remoting.caucho.HessianExporter.java

/**
 * Actually invoke the skeleton with the given streams.
 * @param skeleton the skeleton to invoke
 * @param inputStream the request stream
 * @param outputStream the response stream
 * @throws Throwable if invocation failed
 *//*from   ww w . j ava 2s.  co  m*/
protected void doInvoke(HessianSkeleton skeleton, InputStream inputStream, OutputStream outputStream)
        throws Throwable {

    ClassLoader originalClassLoader = overrideThreadContextClassLoader();
    try {
        InputStream isToUse = inputStream;
        OutputStream osToUse = outputStream;

        if (this.debugLogger != null && this.debugLogger.isDebugEnabled()) {
            try (PrintWriter debugWriter = new PrintWriter(new CommonsLogWriter(this.debugLogger))) {
                @SuppressWarnings("resource")
                HessianDebugInputStream dis = new HessianDebugInputStream(inputStream, debugWriter);
                @SuppressWarnings("resource")
                HessianDebugOutputStream dos = new HessianDebugOutputStream(outputStream, debugWriter);
                dis.startTop2();
                dos.startTop2();
                isToUse = dis;
                osToUse = dos;
            }
        }

        if (!isToUse.markSupported()) {
            isToUse = new BufferedInputStream(isToUse);
            isToUse.mark(1);
        }

        int code = isToUse.read();
        int major;
        int minor;

        AbstractHessianInput in;
        AbstractHessianOutput out;

        if (code == 'H') {
            // Hessian 2.0 stream
            major = isToUse.read();
            minor = isToUse.read();
            if (major != 0x02) {
                throw new IOException("Version " + major + '.' + minor + " is not understood");
            }
            in = new Hessian2Input(isToUse);
            out = new Hessian2Output(osToUse);
            in.readCall();
        } else if (code == 'C') {
            // Hessian 2.0 call... for some reason not handled in HessianServlet!
            isToUse.reset();
            in = new Hessian2Input(isToUse);
            out = new Hessian2Output(osToUse);
            in.readCall();
        } else if (code == 'c') {
            // Hessian 1.0 call
            major = isToUse.read();
            minor = isToUse.read();
            in = new HessianInput(isToUse);
            if (major >= 2) {
                out = new Hessian2Output(osToUse);
            } else {
                out = new HessianOutput(osToUse);
            }
        } else {
            throw new IOException(
                    "Expected 'H'/'C' (Hessian 2.0) or 'c' (Hessian 1.0) in hessian input at " + code);
        }

        in.setSerializerFactory(this.serializerFactory);
        out.setSerializerFactory(this.serializerFactory);
        if (this.remoteResolver != null) {
            in.setRemoteResolver(this.remoteResolver);
        }

        try {
            skeleton.invoke(in, out);
        } finally {
            try {
                in.close();
                isToUse.close();
            } catch (IOException ex) {
                // ignore
            }
            try {
                out.close();
                osToUse.close();
            } catch (IOException ex) {
                // ignore
            }
        }
    } finally {
        resetThreadContextClassLoader(originalClassLoader);
    }
}

From source file:org.codice.ddf.rest.impl.CatalogServiceImpl.java

@Override
public BinaryContent createMetacard(MultipartBody multipartBody, String transformerParam)
        throws CatalogServiceException {
    LOGGER.trace("ENTERING: createMetacard");

    String contentUri = multipartBody.getAttachmentObject("contentUri", String.class);
    LOGGER.debug("contentUri = {}", contentUri);

    InputStream stream = null;
    String contentType = null;//from  w w  w. j a v  a2  s  . c o m

    Attachment contentPart = multipartBody.getAttachment(FILE_ATTACHMENT_CONTENT_ID);
    if (contentPart != null) {
        // Example Content-Type header:
        // Content-Type: application/json;id=geojson
        if (contentPart.getContentType() != null) {
            contentType = contentPart.getContentType().toString();
        }

        // Get the file contents as an InputStream and ensure the stream is positioned
        // at the beginning
        try {
            stream = contentPart.getDataHandler().getInputStream();
            if (stream != null && stream.available() == 0) {
                stream.reset();
            }
        } catch (IOException e) {
            LOGGER.info("IOException reading stream from file attachment in multipart body", e);
        }
    } else {
        LOGGER.debug(NO_FILE_CONTENTS_ATT_FOUND);
    }

    return createMetacard(stream, contentType, transformerParam);
}

From source file:org.codice.ddf.rest.impl.CatalogServiceImpl.java

@Override
public BinaryContent createMetacard(HttpServletRequest httpServletRequest, String transformerParam)
        throws CatalogServiceException {
    LOGGER.trace("ENTERING: createMetacard");

    InputStream stream = null;
    String contentType = null;/*from  w w  w .j  a  v  a2s  . co  m*/

    try {
        Part contentPart = httpServletRequest.getPart(FILE_ATTACHMENT_CONTENT_ID);
        if (contentPart != null) {
            // Example Content-Type header:
            // Content-Type: application/json;id=geojson
            if (contentPart.getContentType() != null) {
                contentType = contentPart.getContentType();
            }

            // Get the file contents as an InputStream and ensure the stream is positioned
            // at the beginning
            try {
                stream = contentPart.getInputStream();
                if (stream != null && stream.available() == 0) {
                    stream.reset();
                }
            } catch (IOException e) {
                LOGGER.info("IOException reading stream from file attachment in multipart body", e);
            }
        } else {
            LOGGER.debug(NO_FILE_CONTENTS_ATT_FOUND);
        }
    } catch (ServletException | IOException e) {
        LOGGER.info("No file contents part found: ", e);
    }

    return createMetacard(stream, contentType, transformerParam);
}

From source file:org.mifos.customers.client.struts.action.ClientCustAction.java

@TransactionDemarcate(joinToken = true)
public ActionForward retrievePicture(ActionMapping mapping, @SuppressWarnings("unused") ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    ClientBO clientBO = getClientFromSession(request);
    ClientPhotoService cps = ApplicationContextProvider.getBean(ClientPhotoService.class);
    ClientPhoto cp = cps.read(clientBO.getCustomerId().longValue());
    InputStream in = null;
    if (cp != null) {
        in = new ByteArrayInputStream(cps.getData(cp.getImageInfo().getPath()));
        response.setContentType(cp.getImageInfo().getContentType());
    } else {/*www  .j  a v a  2 s  .c om*/
        in = ClientPhotoService.class.getResourceAsStream("/org/mifos/image/nopicture.png");
        response.setContentType("image/png");
    }
    in.mark(0);
    BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
    byte[] by = new byte[1024 * 4]; // 4K buffer buf, 0, buf.length
    int index = in.read(by, 0, 1024 * 4);
    while (index != -1) {
        out.write(by, 0, index);
        index = in.read(by, 0, 1024 * 4);
    }
    out.flush();
    out.close();
    in.reset();
    String forward = ClientConstants.CUSTOMER_PICTURE_PAGE;
    return mapping.findForward(forward);
}

From source file:org.exist.xquery.functions.request.GetData.java

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    final RequestModule myModule = (RequestModule) context.getModule(RequestModule.NAMESPACE_URI);

    // request object is read from global variable $request
    final Variable var = myModule.resolveVariable(RequestModule.REQUEST_VAR);

    if (var == null || var.getValue() == null) {
        throw new XPathException(this, "No request object found in the current XQuery context.");
    }/*  w  ww  .j  a va2s .c  o m*/

    if (var.getValue().getItemType() != Type.JAVA_OBJECT) {
        throw new XPathException(this, "Variable $request is not bound to an Java object.");
    }

    final JavaObjectValue value = (JavaObjectValue) var.getValue().itemAt(0);

    if (!(value.getObject() instanceof RequestWrapper)) {
        throw new XPathException(this, "Variable $request is not bound to a Request object.");
    }
    final RequestWrapper request = (RequestWrapper) value.getObject();

    //if the content length is unknown or 0, return
    if (request.getContentLength() == -1 || request.getContentLength() == 0) {
        return Sequence.EMPTY_SEQUENCE;
    }

    InputStream isRequest = null;
    Sequence result = Sequence.EMPTY_SEQUENCE;
    try {

        isRequest = request.getInputStream();

        //was there any POST content?
        /**
         * There is a bug in HttpInput.available() in Jetty 7.2.2.v20101205
         * This has been filed as Bug 333415 - https://bugs.eclipse.org/bugs/show_bug.cgi?id=333415
         * It is expected to be fixed in the Jetty 7.3.0 release
         */

        //TODO reinstate call to .available() when Jetty 7.3.0 is released, use of .getContentLength() is not reliable because of http mechanics
        //if(is != null && is.available() > 0) {
        if (isRequest != null && request.getContentLength() > 0) {

            // 1) determine if exists mime database considers this binary data
            String contentType = request.getContentType();
            if (contentType != null) {
                //strip off any charset encoding info
                if (contentType.indexOf(";") > -1) {
                    contentType = contentType.substring(0, contentType.indexOf(";"));
                }

                final MimeType mimeType = MimeTable.getInstance().getContentType(contentType);
                if (mimeType != null && !mimeType.isXMLType()) {

                    //binary data
                    result = BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(),
                            isRequest);
                }
            }

            if (result == Sequence.EMPTY_SEQUENCE) {
                //2) not binary, try and parse as an XML documemnt, otherwise 3) return a string representation

                //parsing will consume the stream so we must cache!
                InputStream is = null;
                FilterInputStreamCache cache = null;
                try {
                    //we have to cache the input stream, so we can reread it, as we may use it twice (once for xml attempt and once for string attempt)
                    cache = FilterInputStreamCacheFactory
                            .getCacheInstance(new FilterInputStreamCacheConfiguration() {

                                @Override
                                public String getCacheClass() {
                                    return (String) context.getBroker().getConfiguration()
                                            .getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY);
                                }
                            });
                    is = new CachingFilterInputStream(cache, isRequest);

                    //mark the start of the stream
                    is.mark(Integer.MAX_VALUE);

                    //2) try and  parse as XML
                    result = parseAsXml(is);

                    if (result == Sequence.EMPTY_SEQUENCE) {
                        // 3) not a valid XML document, return a string representation of the document
                        String encoding = request.getCharacterEncoding();
                        if (encoding == null) {
                            encoding = "UTF-8";
                        }

                        try {
                            //reset the stream, as we need to reuse for string parsing after the XML parsing happened
                            is.reset();

                            result = parseAsString(is, encoding);
                        } catch (final IOException ioe) {
                            throw new XPathException(this, "An IO exception occurred: " + ioe.getMessage(),
                                    ioe);
                        }
                    }

                } finally {
                    if (cache != null) {
                        try {
                            cache.invalidate();
                        } catch (final IOException ioe) {
                            LOG.error(ioe.getMessage(), ioe);
                        }
                    }

                    if (is != null) {
                        try {
                            is.close();
                        } catch (final IOException ioe) {
                            LOG.error(ioe.getMessage(), ioe);
                        }
                    }
                }
            }

            //NOTE we do not close isRequest, because it may be needed further by the caching input stream wrapper
        }
    } catch (final IOException ioe) {
        throw new XPathException(this, "An IO exception occurred: " + ioe.getMessage(), ioe);
    }

    return result;
}

From source file:org.apache.nifi.processors.standard.IdentifyMimeType.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    FlowFile flowFile = session.get();//www .  ja v  a  2 s  .  c  om
    if (flowFile == null) {
        return;
    }

    final ProcessorLog logger = getLogger();
    final boolean identifyZip = context.getProperty(IDENTIFY_ZIP).asBoolean();
    final boolean identifyTar = context.getProperty(IDENTIFY_TAR).asBoolean();

    final ObjectHolder<String> mimeTypeRef = new ObjectHolder<>(null);
    session.read(flowFile, new InputStreamCallback() {
        @Override
        public void process(final InputStream stream) throws IOException {
            try (final InputStream in = new BufferedInputStream(stream)) {
                // read in up to magicHeaderMaxLength bytes
                in.mark(magicHeaderMaxLength);
                byte[] header = new byte[magicHeaderMaxLength];
                for (int i = 0; i < header.length; i++) {
                    final int next = in.read();
                    if (next >= 0) {
                        header[i] = (byte) next;
                    } else if (i == 0) {
                        header = new byte[0];
                    } else {
                        final byte[] newBuffer = new byte[i - 1];
                        System.arraycopy(header, 0, newBuffer, 0, i - 1);
                        header = newBuffer;
                        break;
                    }
                }
                in.reset();

                for (final MagicHeader magicHeader : magicHeaders) {
                    if (magicHeader.matches(header)) {
                        mimeTypeRef.set(magicHeader.getMimeType());
                        return;
                    }
                }

                if (!identifyZip) {
                    for (final MagicHeader magicHeader : zipMagicHeaders) {
                        if (magicHeader.matches(header)) {
                            mimeTypeRef.set(magicHeader.getMimeType());
                            return;
                        }
                    }
                }

                if (!identifyTar) {
                    for (final MagicHeader magicHeader : tarMagicHeaders) {
                        if (magicHeader.matches(header)) {
                            mimeTypeRef.set(magicHeader.getMimeType());
                            return;
                        }
                    }
                }
            }
        }
    });

    String mimeType = mimeTypeRef.get();
    if (mimeType == null) {
        for (final ContentScanningMimeTypeIdentifier scanningIdentifier : this.contentScanners) {
            if (scanningIdentifier.isEnabled(context)) {
                session.read(flowFile, new InputStreamCallback() {
                    @Override
                    public void process(final InputStream in) throws IOException {
                        String mimeType = scanningIdentifier.getMimeType(in);
                        if (mimeType != null) {
                            mimeTypeRef.set(mimeType);
                        }
                    }
                });

                if (mimeTypeRef.get() != null) {
                    break;
                }
            }
        }
    }

    mimeType = mimeTypeRef.get();
    if (mimeType == null) {
        flowFile = session.putAttribute(flowFile, CoreAttributes.MIME_TYPE.key(), "application/octet-stream");
        logger.info("Unable to identify MIME Type for {}; setting to application/octet-stream",
                new Object[] { flowFile });
    } else {
        flowFile = session.putAttribute(flowFile, CoreAttributes.MIME_TYPE.key(), mimeType);
        logger.info("Identified {} as having MIME Type {}", new Object[] { flowFile, mimeType });
    }

    session.getProvenanceReporter().modifyAttributes(flowFile);
    session.transfer(flowFile, REL_SUCCESS);
}