Example usage for java.io ByteArrayInputStream reset

List of usage examples for java.io ByteArrayInputStream reset

Introduction

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

Prototype

public synchronized void reset() 

Source Link

Document

Resets the buffer to the marked position.

Usage

From source file:org.rundeck.api.ApiCall.java

/**
 * Execute an HTTP GET request to the Rundeck instance, on the given path. We will login first, and then execute the
 * API call./*  www . j av a 2s.c  o  m*/
 *
 * @param apiPath on which we will make the HTTP request - see {@link ApiPathBuilder}
 * @return a new {@link InputStream} instance, not linked with network resources
 * @throws RundeckApiException in case of error when calling the API
 * @throws RundeckApiLoginException if the login fails (in case of login-based authentication)
 * @throws RundeckApiTokenException if the token is invalid (in case of token-based authentication)
 */
public InputStream get(ApiPathBuilder apiPath, boolean parseXml)
        throws RundeckApiException, RundeckApiLoginException, RundeckApiTokenException {
    HttpGet request = new HttpGet(client.getUrl() + client.getApiEndpoint() + apiPath);
    if (null != apiPath.getAccept()) {
        request.setHeader("Accept", apiPath.getAccept());
    }
    ByteArrayInputStream response = execute(request);

    // try to load the document, to throw an exception in case of error
    if (parseXml) {
        ParserHelper.loadDocument(response);
        response.reset();
    }

    return response;
}

From source file:mobile.tiis.appv2.LoginActivity.java

/**
 * This method will take the url built to use the webservice
 * and will try to parse JSON from the webservice stream to get
 * the user and password if they are correct or not. In case correct, fills
 * the Android Account Manager.//from  w  w w .j  ava 2 s .  c o m
 *
 * <p>This method will throw a Toast message when user and password
 * are not valid
 *
 */

protected void startWebService(final CharSequence loginURL, final String username, final String password) {
    client.setBasicAuth(username, password, true);

    //new handler in case of login error in the thread
    handler = new Handler();

    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                int balanceCounter = 0;
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(loginURL.toString());
                Utils.writeNetworkLogFileOnSD(
                        Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + loginURL.toString());
                httpGet.setHeader("Authorization", "Basic "
                        + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
                HttpResponse httpResponse = httpClient.execute(httpGet);
                InputStream inputStream = httpResponse.getEntity().getContent();
                Log.d("", loginURL.toString());

                ByteArrayInputStream bais = Utils.getMultiReadInputStream(inputStream);
                Utils.writeNetworkLogFileOnSD(Utils.returnDeviceIdAndTimestamp(getApplicationContext())
                        + Utils.getStringFromInputStreamAndLeaveStreamOpen(bais));
                bais.reset();
                JsonFactory factory = new JsonFactory();
                JsonParser jsonParser = factory.createJsonParser(bais);
                JsonToken token = jsonParser.nextToken();

                if (token == JsonToken.START_OBJECT) {
                    balanceCounter++;
                    boolean idNextToHfId = false;
                    while (!(balanceCounter == 0)) {
                        token = jsonParser.nextToken();

                        if (token == JsonToken.START_OBJECT) {
                            balanceCounter++;
                        } else if (token == JsonToken.END_OBJECT) {
                            balanceCounter--;
                        } else if (token == JsonToken.FIELD_NAME) {
                            String object = jsonParser.getCurrentName();
                            switch (object) {
                            case "HealthFacilityId":
                                token = jsonParser.nextToken();
                                app.setLoggedInUserHealthFacilityId(jsonParser.getText());
                                Log.d("", "healthFacilityId is: " + jsonParser.getText());
                                idNextToHfId = true;
                                break;
                            case "Firstname":
                                token = jsonParser.nextToken();
                                app.setLoggedInFirstname(jsonParser.getText());
                                Log.d("", "firstname is: " + jsonParser.getText());
                                break;
                            case "Lastname":
                                token = jsonParser.nextToken();
                                app.setLoggedInLastname(jsonParser.getText());
                                Log.d("", "lastname is: " + jsonParser.getText());
                                break;
                            case "Username":
                                token = jsonParser.nextToken();
                                app.setLoggedInUsername(jsonParser.getText());
                                Log.d("", "username is: " + jsonParser.getText());
                                break;
                            case "Lastlogin":
                                token = jsonParser.nextToken();
                                Log.d("", "lastlogin is: " + jsonParser.getText());
                                break;
                            case "Id":
                                if (idNextToHfId) {
                                    token = jsonParser.nextToken();
                                    app.setLoggedInUserId(jsonParser.getText());
                                    Log.d("", "Id is: " + jsonParser.getText());
                                }
                                break;
                            default:
                                break;
                            }
                        }
                    }

                    Account account = new Account(username, ACCOUNT_TYPE);
                    AccountManager accountManager = AccountManager.get(LoginActivity.this);
                    //                        boolean accountCreated = accountManager.addAccountExplicitly(account, LoginActivity.this.password, null);
                    boolean accountCreated = accountManager.addAccountExplicitly(account, password, null);

                    Bundle extras = LoginActivity.this.getIntent().getExtras();
                    if (extras != null) {
                        if (accountCreated) { //Pass the new account back to the account manager
                            AccountAuthenticatorResponse response = extras
                                    .getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
                            Bundle res = new Bundle();
                            res.putString(AccountManager.KEY_ACCOUNT_NAME, username);
                            res.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
                            res.putString(AccountManager.KEY_PASSWORD, password);
                            response.onResult(res);
                        }
                    }

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putBoolean("secondSyncNeeded", true);
                    editor.commit();

                    ContentValues values = new ContentValues();
                    values.put(SQLHandler.SyncColumns.UPDATED, 1);
                    values.put(SQLHandler.UserColumns.FIRSTNAME, app.getLOGGED_IN_FIRSTNAME());
                    values.put(SQLHandler.UserColumns.LASTNAME, app.getLOGGED_IN_LASTNAME());
                    values.put(SQLHandler.UserColumns.HEALTH_FACILITY_ID, app.getLOGGED_IN_USER_HF_ID());
                    values.put(SQLHandler.UserColumns.ID, app.getLOGGED_IN_USER_ID());
                    values.put(SQLHandler.UserColumns.USERNAME, app.getLOGGED_IN_USERNAME());
                    values.put(SQLHandler.UserColumns.PASSWORD, password);
                    databaseHandler.addUser(values);

                    Log.d(TAG, "initiating offline for " + username + " password = " + password);
                    app.initializeOffline(username, password);

                    Intent intent;
                    if (prefs.getBoolean("synchronization_needed", true)) {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                    } else {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                        evaluateIfFirstLogin(app.getLOGGED_IN_USER_ID());
                    }
                    app.setUsername(username);

                    startActivity(intent);
                }
                //if login failed show error
                else {
                    handler.post(new Runnable() {
                        public void run() {
                            progressDialog.show();
                            progressDialog.dismiss();
                            toastMessage("Login failed.\nPlease check your details!");
                            loginButton.setEnabled(true);
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    public void run() {
                        progressDialog.show();
                        progressDialog.dismiss();
                        toastMessage("Login failed Login failed.\n"
                                + "Please check your details or your web connectivity");
                        loginButton.setEnabled(true);

                    }
                });
                e.printStackTrace();
            }
        }
    });
    thread.start();

}

From source file:IntSort.java

public void readStream() {
    try {//from  w  ww .  ja  va  2 s  .  co m
        // Careful: Make sure this is big enough!
        // Better yet, test and reallocate if necessary      
        byte[] recData = new byte[50];

        // Read from the specified byte array
        ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);

        // Read Java data types from the above byte array
        DataInputStream strmDataType = new DataInputStream(strmBytes);

        if (rs.getNumRecords() > 0) {
            ComparatorInt comp = new ComparatorInt();

            int i = 1;
            RecordEnumeration re = rs.enumerateRecords(null, comp, false);
            while (re.hasNextElement()) {
                // Get data into the byte array          
                rs.getRecord(re.nextRecordId(), recData, 0);

                // Read back the data types      
                System.out.println("Record #" + i++);

                System.out.println("Name: " + strmDataType.readUTF());
                System.out.println("Dog: " + strmDataType.readBoolean());
                System.out.println("Rank: " + strmDataType.readInt());
                System.out.println("--------------------");

                // Reset so read starts at beginning of array 
                strmBytes.reset();
            }

            comp.compareIntClose();

            // Free enumerator
            re.destroy();
        }

        strmBytes.close();
        strmDataType.close();

    } catch (Exception e) {
        db(e.toString());
    }
}

From source file:ch.ksfx.web.pages.publishing.PublicationViewer.java

public Object activatePublishingResourceForConfigurationLocatorAndResourceLocator(String configurationLocator,
        String resourceLocator, Integer fromCache, List<String> uriParameters) {
    PublishingConfiguration publishingConfiguration = publishingConfigurationDAO
            .getPublishingConfigurationForUri(configurationLocator);

    if (publishingConfiguration.getPublishingVisibility() == null || !publishingConfiguration
            .getPublishingVisibility().equals(PublishingVisibility.PUBLIC.toString())) {
        if (!userService.isAuthenticated()
                && (publishingConfiguration.getPublishingVisibility() == null || !publishingConfiguration
                        .getPublishingVisibility().equals(PublishingVisibility.CACHE_FOR_ALL.toString())
                        || fromCache == 0)) {
            return new TextStreamResponse("text/plain", "You are not authorized to view this page");
        }//from   w  w w . j av  a  2s . c  o m
    }

    pageHeaderTitle = publishingConfiguration.getName();

    PublishingResource publishingResource = publishingResourceDAO
            .getPublishingResourceForPublishingConfigurationAndUri(publishingConfiguration, resourceLocator);

    if (fromCache == 1) {
        PublishingResourceCacheData prcd = publishingResource
                .getPublishingResourceCacheDataForUriParameter(uriParameters.toString());

        if (prcd.getContentType().contains("text") && publishingResource.getEmbedInLayout()) {
            layoutEmbeddedData = new String(prcd.getCacheData());
            return null;
        }

        return new GenericStreamResponse(prcd.getCacheData(), publishingResource.getUri(),
                prcd.getContentType(), false);
    }

    try {
        Console.startConsole(publishingConfiguration);
        PublishingDataShare.startShare(publishingConfiguration);

        StreamResponse streamResponse = loadPublishingStrategy(publishingResource.getPublishingStrategy(),
                uriParameters);
        InputStream inputStream = streamResponse.getStream();

        if (inputStream instanceof ByteArrayInputStream) {
            systemLogger.logMessage("PUBLICATION", "Data can be cached: " + publishingResource.getTitle());

            ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream) inputStream;
            byte[] cacheData = IOUtils.toByteArray(byteArrayInputStream);
            String contentType = streamResponse.getContentType();

            if (!publishingConfiguration.getLockedForCacheUpdate()) {
                PublishingResourceCacheData prcd = publishingResourceDAO
                        .getPublishingResourceCacheDataForPublishingResourceAndUriParameter(publishingResource,
                                uriParameters.toString());

                if (prcd == null) {
                    prcd = new PublishingResourceCacheData();
                    prcd.setPublishingResource(publishingResource);
                    prcd.setUriParameter(uriParameters.toString());
                }

                prcd.setCacheData(cacheData);
                prcd.setContentType(contentType);
                publishingResourceDAO.saveOrUpdatePublishingResourceCacheData(prcd);
            }

            byteArrayInputStream.reset();

            if (contentType.contains("text") && publishingResource.getEmbedInLayout()) {
                layoutEmbeddedData = new String(cacheData);
                return null;
            }
        } else {
            systemLogger.logMessage("PUBLICATION", "Data can NOT be cached: " + publishingResource.getTitle());
        }

        return streamResponse;
    } catch (Exception e) {
        systemLogger.logMessage("PUBLICATION", "Error while creating publication PublicationViewer", e);
        throw new RuntimeException(e);
    } finally {
        Console.endConsole();
        PublishingDataShare.endShare();
    }
}

From source file:ch.ksfx.web.pages.publishing.PublicationViewer.java

public Object activatePublishingConfigurationForId(Long publishingConfigurationId, Integer fromCache,
        List<String> uriParameters) {
    PublishingConfiguration publishingConfiguration = publishingConfigurationDAO
            .getPublishingConfigurationForId(publishingConfigurationId);

    if (publishingConfiguration.getPublishingVisibility() == null || !publishingConfiguration
            .getPublishingVisibility().equals(PublishingVisibility.PUBLIC.toString())) {
        if (!userService.isAuthenticated()
                && (publishingConfiguration.getPublishingVisibility() == null || !publishingConfiguration
                        .getPublishingVisibility().equals(PublishingVisibility.CACHE_FOR_ALL.toString())
                        || fromCache == 0)) {
            return new TextStreamResponse("text/plain", "You are not authorized to view this page");
        }/*from w w  w .j  ava2s. c  om*/
    }

    pageHeaderTitle = publishingConfiguration.getName();

    if (fromCache == 1) {
        PublishingConfigurationCacheData pccd = publishingConfiguration
                .getPublishingConfigurationCacheDataForUriParameter(uriParameters.toString());

        if (pccd.getContentType().contains("text") && publishingConfiguration.getEmbedInLayout()) {
            layoutEmbeddedData = new String(pccd.getCacheData());
            return null;
        }

        return new GenericStreamResponse(pccd.getCacheData(), publishingConfiguration.getUri(),
                pccd.getContentType(), false);
    }

    //purgeAllCaches(publishingConfiguration);

    try {
        Console.startConsole(publishingConfiguration);
        PublishingDataShare.startShare(publishingConfiguration);

        StreamResponse streamResponse = loadPublishingStrategy(publishingConfiguration.getPublishingStrategy(),
                uriParameters);
        InputStream inputStream = streamResponse.getStream();

        if (inputStream instanceof ByteArrayInputStream) {
            systemLogger.logMessage("PUBLICATION", "Data can be cached: " + publishingConfiguration.getName());

            ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream) inputStream;
            byte[] cacheData = IOUtils.toByteArray(byteArrayInputStream);
            String contentType = streamResponse.getContentType();

            publishingConfiguration = publishingConfigurationDAO
                    .getPublishingConfigurationForId(publishingConfigurationId);

            if (!publishingConfiguration.getLockedForCacheUpdate()) {
                PublishingConfigurationCacheData pccd = publishingConfigurationDAO
                        .getPublishingConfigurationCacheDataForPublishingConfigurationAndUriParameter(
                                publishingConfiguration, uriParameters.toString());

                if (pccd == null) {
                    pccd = new PublishingConfigurationCacheData();
                    pccd.setPublishingConfiguration(publishingConfiguration);
                    pccd.setUriParameter(uriParameters.toString());
                }

                pccd.setCacheData(cacheData);
                pccd.setContentType(contentType);
                publishingConfigurationDAO.saveOrUpdatePublishingConfigurationCacheData(pccd);
            }

            byteArrayInputStream.reset();

            if (contentType.contains("text") && publishingConfiguration.getEmbedInLayout()) {
                layoutEmbeddedData = new String(cacheData);
                return null;
            }
        } else {
            systemLogger.logMessage("PUBLICATION",
                    "Data can NOT be cached: " + publishingConfiguration.getName());
        }

        return streamResponse;
    } catch (Exception e) {
        systemLogger.logMessage("PUBLICATION", "Error while creating publication PublicationViewer", e);
        throw new RuntimeException(e);
    } finally {
        Console.endConsole();
        PublishingDataShare.endShare();
    }
}

From source file:de.escidoc.core.common.util.xml.XmlUtility.java

/**
 * Validates the provided XML data using the specified schema.<br> The provided {@code ByteArrayInputStream} is
 * reset after validation./*ww w. j a v  a 2  s  . c om*/
 *
 * @param byteArrayInputStream The XML data to validate in an {@code ByteArrayInputStream}.<br> This input
 *                             stream is reset after the validation.
 * @param schemaUri            The URL identifying the schema that shall be used for validation.
 * @throws XmlCorruptedException        Thrown if the XML data cannot be parsed.
 * @throws XmlSchemaValidationException Thrown if both validation fail or only one validation is executed and fails
 * @throws WebserverSystemException     Thrown in any other case.
 */
public void validate(final ByteArrayInputStream byteArrayInputStream, final String schemaUri)
        throws XmlCorruptedException, XmlSchemaValidationException, WebserverSystemException {

    try {
        final Validator validator = getSchema(schemaUri).newValidator();
        validator.validate(new SAXSource(new InputSource(byteArrayInputStream)));
    } catch (final SAXParseException e) {
        final String errorMsg = "Error in line " + e.getLineNumber() + ", column " + e.getColumnNumber() + ". "
                + e.getMessage();
        if (e.getMessage().startsWith("cvc")) {
            throw new XmlSchemaValidationException(errorMsg, e);
        } else {
            throw new XmlCorruptedException(errorMsg, e);
        }
    } catch (final Exception e) {
        throw new WebserverSystemException(e.getMessage(), e);
    } finally {
        if (byteArrayInputStream != null) {
            byteArrayInputStream.reset();
        }
    }
}

From source file:org.alfresco.encoding.BomCharactersetFinder.java

/**
 * Just searches the Byte Order Marker, i.e. the first three characters for a sign of
 * the encoding./*from  www . j a  v  a 2  s.  c  o m*/
 */
protected Charset detectCharsetImpl(byte[] buffer) throws Exception {
    Charset charset = null;
    ByteArrayInputStream bis = null;
    try {
        bis = new ByteArrayInputStream(buffer);
        bis.mark(3);
        char[] byteHeader = new char[3];
        InputStreamReader in = new InputStreamReader(bis);
        int bytesRead = in.read(byteHeader);
        bis.reset();

        if (bytesRead < 2) {
            // ASCII
            charset = Charset.forName("Cp1252");
        } else if (byteHeader[0] == 0xFE && byteHeader[1] == 0xFF) {
            // UCS-2 Big Endian
            charset = Charset.forName("UTF-16BE");
        } else if (byteHeader[0] == 0xFF && byteHeader[1] == 0xFE) {
            // UCS-2 Little Endian
            charset = Charset.forName("UTF-16LE");
        } else if (bytesRead >= 3 && byteHeader[0] == 0xEF && byteHeader[1] == 0xBB && byteHeader[2] == 0xBF) {
            // UTF-8
            charset = Charset.forName("UTF-8");
        } else {
            // No idea
            charset = null;
        }
        // Done
        return charset;
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (Throwable e) {
            }
        }
    }
}

From source file:org.apache.hadoop.io.TestIOUtils.java

@Test
public void testSkipFully() throws IOException {
    byte inArray[] = new byte[] { 0, 1, 2, 3, 4 };
    ByteArrayInputStream in = new ByteArrayInputStream(inArray);
    try {/*from  w  w w.  j a  v a2 s.  co  m*/
        in.mark(inArray.length);
        IOUtils.skipFully(in, 2);
        IOUtils.skipFully(in, 2);
        try {
            IOUtils.skipFully(in, 2);
            fail("expected to get a PrematureEOFException");
        } catch (EOFException e) {
            assertEquals("Premature EOF from inputStream " + "after skipping 1 byte(s).", e.getMessage());
        }
        in.reset();
        try {
            IOUtils.skipFully(in, 20);
            fail("expected to get a PrematureEOFException");
        } catch (EOFException e) {
            assertEquals("Premature EOF from inputStream " + "after skipping 5 byte(s).", e.getMessage());
        }
        in.reset();
        IOUtils.skipFully(in, 5);
        try {
            IOUtils.skipFully(in, 10);
            fail("expected to get a PrematureEOFException");
        } catch (EOFException e) {
            assertEquals("Premature EOF from inputStream " + "after skipping 0 byte(s).", e.getMessage());
        }
    } finally {
        in.close();
    }
}

From source file:org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreTextWriterTest.java

@Test
public void basicOperation() throws Exception {
    File fdsDir = temporaryFolder.newFolder();
    FileDataStore fds = DataStoreUtils.createFDS(fdsDir, 0);
    ByteArrayInputStream is = new ByteArrayInputStream("hello".getBytes());
    DataRecord dr = fds.addRecord(is);/* w w w  . jav a  2  s.c o  m*/

    File writerDir = temporaryFolder.newFolder();
    TextWriter writer = new DataStoreTextWriter(writerDir, false);
    writer.write(dr.getIdentifier().toString(), "hello");

    FileDataStore fds2 = DataStoreUtils.createFDS(writerDir, 0);
    DataRecord dr2 = fds2.getRecordIfStored(dr.getIdentifier());

    is.reset();
    assertTrue(IOUtils.contentEquals(is, dr2.getStream()));

}

From source file:org.apache.pdfbox.filter.LZWFilter.java

/**
 * {@inheritDoc}// www .ja  v  a  2s . c om
 */
@Override
public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary parameters, int index)
        throws IOException {
    int predictor = -1;
    int earlyChange = 1;

    COSDictionary decodeParams = getDecodeParams(parameters, index);
    if (decodeParams != null) {
        predictor = decodeParams.getInt(COSName.PREDICTOR);
        earlyChange = decodeParams.getInt(COSName.EARLY_CHANGE, 1);
        if (earlyChange != 0 && earlyChange != 1) {
            earlyChange = 1;
        }
    }
    if (predictor > 1) {
        @SuppressWarnings("null")
        int colors = Math.min(decodeParams.getInt(COSName.COLORS, 1), 32);
        int bitsPerPixel = decodeParams.getInt(COSName.BITS_PER_COMPONENT, 8);
        int columns = decodeParams.getInt(COSName.COLUMNS, 1);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        doLZWDecode(encoded, baos, earlyChange);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        Predictor.decodePredictor(predictor, colors, bitsPerPixel, columns, bais, decoded);
        decoded.flush();
        baos.reset();
        bais.reset();
    } else {
        doLZWDecode(encoded, decoded, earlyChange);
    }
    return new DecodeResult(parameters);
}