Example usage for java.io ByteArrayInputStream available

List of usage examples for java.io ByteArrayInputStream available

Introduction

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

Prototype

public synchronized int available() 

Source Link

Document

Returns the number of remaining bytes that can be read (or skipped over) from this input stream.

Usage

From source file:com.klarna.checkout.stubs.HttpClientStub.java

/**
 * Uppercase data to simulate it having passed on to the server.
 *
 * @throws IOException in case of an IO error.
 *//* w ww  .j a va2 s . c om*/
private void fixData() throws IOException {
    if (this.httpUriReq.getMethod().equals("POST")) {
        HttpEntityEnclosingRequest h = (HttpEntityEnclosingRequest) this.httpUriReq;

        InputStream is = h.getEntity().getContent();
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");

        String str = "";
        while (s.hasNext()) {
            str = str.concat(s.next());
        }
        JSONParser jsonParser = new JSONParser();
        HashMap<String, String> obj = null;
        try {
            obj = (HashMap<String, String>) jsonParser.parse(str);
        } catch (ParseException ex) {
            Logger.getLogger(HttpClientStub.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (obj != null && obj.containsKey("test")) {
            str = obj.get("test").toUpperCase();
            this.data.put("test", str);
        }

        ByteArrayInputStream in = new ByteArrayInputStream(JSONObject.toJSONString(this.data).getBytes());

        this.lastResponse.setEntity(new InputStreamEntity(in, in.available()));
    }
}

From source file:com.klarna.checkout.stubs.HttpClientStub.java

/**
 * Stubbed Execute implementation./*w  w  w .ja v a 2  s  .co  m*/
 *
 * @param <T> The class ResponseHandler operates on
 * @param hur HttpUriRequest object
 * @param rh ResponseHandler object
 * @param hc HttpContext holder
 *
 * @return ResponseHandler result
 *
 * @throws IOException never
 */
@Override
public <T> T execute(final HttpUriRequest hur, final ResponseHandler<? extends T> rh, final HttpContext hc)
        throws IOException {
    this.httpUriReq = hur;

    List<Integer> redirects = new ArrayList();
    redirects.add(301);
    redirects.add(302);
    redirects.add(303);
    this.visited.clear();
    if (this.httpUriReq instanceof HttpEntityEnclosingRequest) {
        try {
            this.httpUriReq = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) hur);
        } catch (ProtocolException ex) {
            throw new IOException(ex);
        }
    }
    int status;
    do {
        try {
            for (HttpRequestInterceptor hri : requestInterceptors) {
                hri.process(this.httpUriReq, hc);
            }
        } catch (HttpException ex) {
            throw new ClientProtocolException(ex);
        }

        if (!this.visited.add(this.httpUriReq.getURI())) {
            throw new ClientProtocolException(new CircularRedirectException());
        }

        this.lastResponse = this.getResponse();

        if (this.lastResponse.getStatusLine().getStatusCode() < 400) {
            fixData();
        }

        try {
            for (HttpResponseInterceptor hri : responseInterceptors) {
                hri.process(this.lastResponse, hc);
            }
        } catch (HttpException ex) {
            throw new ClientProtocolException(ex);
        }
        status = this.lastResponse.getStatusLine().getStatusCode();
        Header location = this.lastResponse.getLastHeader("Location");
        if (location != null) {
            this.httpUriReq = new HttpGet(location.getValue());
        }
    } while (redirects.contains(status));

    if (this.data.containsKey("test")) {
        ByteArrayInputStream bis = new ByteArrayInputStream(JSONObject.toJSONString(data).getBytes());
        this.lastResponse.setEntity(new InputStreamEntity(bis, bis.available()));
    }

    return rh.handleResponse(this.lastResponse);
}

From source file:com.lmco.ddf.endpoints.rest.TestRestEndpoint.java

/**
 * Converts a ByteArrayInputStream into a readable/printable String
 * @param content//  w w w.  j  a v  a 2s  .c om
 * @return
 */
protected String byteArrayConvert(ByteArrayInputStream content) {
    int streamSize = content.available();
    char[] charArray = new char[streamSize];
    byte[] byteArray = new byte[streamSize];

    content.read(byteArray, 0, streamSize);
    for (int i = 0; i < streamSize;) {
        charArray[i] = (char) (byteArray[i++] & 0xff);
    }

    return new String(charArray);
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * To get the unique identifier(serialnumber_issuerdn) of the certificate.
 *
 * @param certificate Base64 encoded certificate.
 * @return unique identifier of the certification.
 *///from ww w .java  2  s .  co  m
public String getUniqueIdentifierOfCertificate(String certificate) {
    byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8)));
    ByteArrayInputStream serverCert = new ByteArrayInputStream(cert);
    String uniqueIdentifier = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        while (serverCert.available() > 0) {
            Certificate generatedCertificate = cf.generateCertificate(serverCert);
            X509Certificate x509Certificate = (X509Certificate) generatedCertificate;
            uniqueIdentifier = String
                    .valueOf(x509Certificate.getSerialNumber() + "_" + x509Certificate.getIssuerDN());
            uniqueIdentifier = uniqueIdentifier.replaceAll(",", "#").replaceAll("\"", "'");
        }
    } catch (CertificateException e) {
        log.error("Error while getting serial number of the certificate.", e);
    } finally {
        closeStreams(serverCert);
    }
    return uniqueIdentifier;
}

From source file:org.dataconservancy.ui.api.PersonControllerTest.java

/**
 * Tests that when a user with an empty id is supplied, the system mints and
 * assign id to the created person.//  www. ja v  a2  s  .c  o  m
 * 
 * @throws InvalidXmlException
 * @throws BizInternalException
 * @throws BizPolicyException
 * @throws IOException
 */
@Test
public void testAddNewPersonWithEmptyId()
        throws InvalidXmlException, BizInternalException, BizPolicyException, IOException {
    //Set incoming person's id to null
    newUser.setId(null);
    bop.addPerson(newUser);
    businessObjectBuilder.buildBusinessObjectPackage(bop, sink);

    personController.handlePersonPostRequest(APPLICATION_XML, sink.toByteArray(), mockReq, resp);
    //Test that response is not null
    assertNotNull(resp);
    //Test that create response code was returned
    assertEquals(200, resp.getStatus());

    ByteArrayInputStream bais = new ByteArrayInputStream(resp.getContentAsByteArray());

    int contentLenth = bais.available();
    Bop returnedBop = businessObjectBuilder.buildBusinessObjectPackage(bais);
    //Test that bop was successfully built from the response
    assertNotNull(returnedBop);

    Set<Person> respPersons = returnedBop.getPersons();
    //Test that a set of persons was returned in the response
    assertNotNull(respPersons);
    //Test that only one person was included in the returned set
    assertEquals(1, respPersons.size());

    Person respPerson = respPersons.iterator().next();
    assertNull(newUser.getId());
    assertNotNull(respPerson.getId());
    //Have to set the ogriinal person id to the id set by the biz service.
    newUser.setId(respPerson.getId());
    //Test that the original user is the same as the person returned by the controller
    assertEquals(newUser, respPerson);
    //Test that the original user was created in the system
    assertEquals(newUser, userService.get(newUser.getId()));

    //Check for expected headers
    assertNotNull(resp.getHeader(LOCATION));
    assertEquals(resp.getHeader(LOCATION), respPerson.getId());
    assertNotNull(resp.getHeader(ETAG));
    assertNotNull(resp.getHeader(LAST_MODIFIED));
    assertNotNull(resp.getContentType());
    //Test that the actual received content-length is the same the declared content lenghth on response header
    assertEquals(contentLenth, resp.getContentLength());
}

From source file:org.dataconservancy.ui.api.PersonControllerTest.java

/**
 * Tests adding a person using the controller. Ensures that the correct
 * status code is returned and that the serialization returned matches the
 * person created. This is also a test case for the creation of person with
 * preset id./*from   ww w.j  av a2  s . c om*/
 * 
 * @throws BizInternalException
 * @throws BizPolicyException
 * @throws IOException
 * @throws InvalidXmlException
 */
@Test
public void testAddPerson() throws BizInternalException, BizPolicyException, IOException, InvalidXmlException {

    bop.addPerson(newUser);
    businessObjectBuilder.buildBusinessObjectPackage(bop, sink);

    personController.handlePersonPostRequest(APPLICATION_XML, sink.toByteArray(), mockReq, resp);
    //Test that response is not null
    assertNotNull(resp);
    //Test that create response code was returned
    assertEquals(200, resp.getStatus());

    ByteArrayInputStream bais = new ByteArrayInputStream(resp.getContentAsByteArray());

    int contentLenth = bais.available();
    Bop returnedBop = businessObjectBuilder.buildBusinessObjectPackage(bais);
    //Test that bop was successfully built from the response
    assertNotNull(returnedBop);

    Set<Person> respPersons = returnedBop.getPersons();
    //Test that a set of persons was returned in the response
    assertNotNull(respPersons);
    //Test that only one person was included in the returned set
    assertEquals(1, respPersons.size());

    Person respPerson = respPersons.iterator().next();
    //Have to set the ogriinal person id to the id set by the biz service.
    newUser.setId(respPerson.getId());
    //Test that the original user is the same as the person returned by the controller
    assertEquals(newUser, respPerson);
    //Test that the original user was created in the system
    assertEquals(newUser, userService.get(newUser.getId()));

    //Check for expected headers
    assertNotNull(resp.getHeader(LOCATION));
    assertEquals(resp.getHeader(LOCATION), respPerson.getId());
    assertNotNull(resp.getHeader(ETAG));
    assertNotNull(resp.getHeader(LAST_MODIFIED));
    assertNotNull(resp.getContentType());
    //Test that the actual received content-length is the same the declared content lenghth on response header
    assertEquals(contentLenth, resp.getContentLength());

    //*** note: this test is only expected to pass if the underlying policy doesn't dictate that the Person
    //object has to be altered before creation.
    //Test that a correct Etag was sent with the response
    assertEquals(ETagCalculator.calculate(Integer.toString(bop.hashCode())), resp.getHeader(ETAG));
}

From source file:org.dataconservancy.ui.api.PersonControllerTest.java

/**
 * Tests that when a user with empty registration status is supplied, the
 * created person in the system would have the default value for
 * registration status.// ww w. j  a  va2  s  .co m
 * 
 * @throws BizInternalException
 * @throws BizPolicyException
 * @throws IOException
 * @throws InvalidXmlException
 */
@Test
public void testAddNewPersonWithEmptyRegistrationStatuses()
        throws BizInternalException, BizPolicyException, IOException, InvalidXmlException {

    //Set incoming person's registration status to null
    newUser.setRegistrationStatus(null);
    bop.addPerson(newUser);
    businessObjectBuilder.buildBusinessObjectPackage(bop, sink);

    personController.handlePersonPostRequest(APPLICATION_XML, sink.toByteArray(), mockReq, resp);
    //Test that response is not null
    assertNotNull(resp);
    //Test that create response code was returned
    assertEquals(200, resp.getStatus());

    ByteArrayInputStream bais = new ByteArrayInputStream(resp.getContentAsByteArray());

    int contentLenth = bais.available();
    Bop returnedBop = businessObjectBuilder.buildBusinessObjectPackage(bais);
    //Test that bop was successfully built from the response
    assertNotNull(returnedBop);

    Set<Person> respPersons = returnedBop.getPersons();
    //Test that a set of persons was returned in the response
    assertNotNull(respPersons);
    //Test that only one person was included in the returned set
    assertEquals(1, respPersons.size());

    Person respPerson = respPersons.iterator().next();
    //verify assumption
    assertNull(newUser.getRegistrationStatus());
    //Test that the created person has a defaut registration status
    assertEquals(userService.getPolicyConsultant().getDefaultRegistrationStatus(),
            respPerson.getRegistrationStatus());

    //Have to set the original person's reg status to the created person's reg status to compare the rest of
    //the fields
    newUser.setRegistrationStatus(respPerson.getRegistrationStatus());
    //Have to set the ogriinal person id to the id set by the biz service.
    newUser.setId(respPerson.getId());
    //Test that the original user is the same as the person returned by the controller
    assertEquals(newUser, respPerson);
    //Test that the original user was created in the system
    assertEquals(newUser, userService.get(newUser.getId()));

    //Check for expected headers
    assertNotNull(resp.getHeader(LOCATION));
    assertEquals(resp.getHeader(LOCATION), respPerson.getId());
    assertNotNull(resp.getHeader(ETAG));
    assertNotNull(resp.getHeader(LAST_MODIFIED));
    assertNotNull(resp.getContentType());
    //Test that the actual received content-length is the same the declared content lenghth on response header
    assertEquals(contentLenth, resp.getContentLength());
}

From source file:org.dataconservancy.ui.api.PersonControllerTest.java

/**
 * Tests supplying person with empty role lists. Expected that person is
 * created successfully with a default role per policy
 * /*from w  ww. j av a2s.c  o m*/
 * @throws BizInternalException
 * @throws BizPolicyException
 * @throws IOException
 * @throws InvalidXmlException
 */
@Test
public void testAddNewPersonWithEmptyRolesList()
        throws BizInternalException, BizPolicyException, IOException, InvalidXmlException {
    //set person's role list to an empty list
    newUser.setRoles(new ArrayList<Role>());
    bop.addPerson(newUser);
    businessObjectBuilder.buildBusinessObjectPackage(bop, sink);

    personController.handlePersonPostRequest(APPLICATION_XML, sink.toByteArray(), mockReq, resp);
    //Test that response is not null
    assertNotNull(resp);
    //Test that create response code was returned
    assertEquals(200, resp.getStatus());

    ByteArrayInputStream bais = new ByteArrayInputStream(resp.getContentAsByteArray());

    int contentLenth = bais.available();
    Bop returnedBop = businessObjectBuilder.buildBusinessObjectPackage(bais);
    //Test that bop was successfully built from the response
    assertNotNull(returnedBop);

    Set<Person> respPersons = returnedBop.getPersons();
    //Test that a set of persons was returned in the response
    assertNotNull(respPersons);
    //Test that only one person was included in the returned set
    assertEquals(1, respPersons.size());

    Person respPerson = respPersons.iterator().next();

    //verify assumption
    assertTrue(newUser.getRoles().isEmpty());
    assertNotNull(respPerson.getRoles());

    for (Role acceptedRole : userService.getPolicyConsultant()
            .getRolesForRegistrationStatus(respPerson.getRegistrationStatus())) {
        assertTrue(respPerson.getRoles().contains(acceptedRole));
    }

    //Assigned created person's role to supplied user's roles to compare the rest of the fields
    newUser.setRoles(respPerson.getRoles());

    //Have to set the ogriinal person id to the id set by the biz service.
    newUser.setId(respPerson.getId());
    //Test that the original user is the same as the person returned by the controller
    assertEquals(newUser, respPerson);
    //Test that the original user was created in the system
    assertEquals(newUser, userService.get(newUser.getId()));

    //Check for expected headers
    assertNotNull(resp.getHeader(LOCATION));
    assertEquals(resp.getHeader(LOCATION), respPerson.getId());
    assertNotNull(resp.getHeader(ETAG));
    assertNotNull(resp.getHeader(LAST_MODIFIED));
    assertNotNull(resp.getContentType());
    //Test that the actual received content-length is the same the declared content lenghth on response header
    assertEquals(contentLenth, resp.getContentLength());

    //*** note: this test is only expected to pass if the underlying policy doesn't dictate that the Person
    //object has to be altered before creation.
    //Test that a correct Etag was sent with the response
    assertEquals(ETagCalculator.calculate(Integer.toString(bop.hashCode())), resp.getHeader(ETAG));
}

From source file:org.dataconservancy.ui.api.PersonControllerTest.java

/**
 * Tests supplying a person with non-acceptable roles (per policy). Expect:
 * the new person is created successfully, but with defaults role (per
 * policy)/* www.ja v a  2 s.com*/
 * 
 * @throws BizInternalException
 * @throws BizPolicyException
 * @throws IOException
 * @throws InvalidXmlException
 */
@Test
public void testAddNewPersonWithWrongRoles()
        throws BizInternalException, BizPolicyException, IOException, InvalidXmlException {

    //Setting a pending user's roles to an approved user's roles
    List<Role> nonAcceptableRoles = userService.getPolicyConsultant()
            .getRolesForRegistrationStatus(RegistrationStatus.APPROVED);

    newUser.setRoles(nonAcceptableRoles);
    bop.addPerson(newUser);
    businessObjectBuilder.buildBusinessObjectPackage(bop, sink);

    personController.handlePersonPostRequest(APPLICATION_XML, sink.toByteArray(), mockReq, resp);
    //Test that response is not null
    assertNotNull(resp);
    //Test that create response code was returned
    assertEquals(200, resp.getStatus());
    ByteArrayInputStream bais = new ByteArrayInputStream(resp.getContentAsByteArray());

    int contentLenth = bais.available();
    Bop returnedBop = businessObjectBuilder.buildBusinessObjectPackage(bais);
    //Test that bop was successfully built from the response
    assertNotNull(returnedBop);

    Set<Person> respPersons = returnedBop.getPersons();
    //Test that a set of persons was returned in the response
    assertNotNull(respPersons);
    //Test that only one person was included in the returned set
    assertEquals(1, respPersons.size());

    Person respPerson = respPersons.iterator().next();

    assertNotNull(respPerson.getRoles());

    //Make sure the created person's roles are acceptable per policy.
    for (Role acceptedRole : userService.getPolicyConsultant()
            .getRolesForRegistrationStatus(respPerson.getRegistrationStatus())) {
        assertTrue(respPerson.getRoles().contains(acceptedRole));
    }
    //Test that the roles were changed during the creation of the person
    assertFalse(newUser.getRoles().equals(respPerson.getRoles()));

    //Assigned created person's role to supplied user's roles to compare the rest of the fields
    newUser.setRoles(respPerson.getRoles());

    //Have to set the ogriinal person id to the id set by the biz service.
    newUser.setId(respPerson.getId());
    //Test that the original user is the same as the person returned by the controller
    assertEquals(newUser, respPerson);
    //Test that the original user was created in the system
    assertEquals(newUser, userService.get(newUser.getId()));

    //Check for expected headers
    assertNotNull(resp.getHeader(LOCATION));
    assertEquals(resp.getHeader(LOCATION), respPerson.getId());
    assertNotNull(resp.getHeader(ETAG));
    assertNotNull(resp.getHeader(LAST_MODIFIED));
    assertNotNull(resp.getContentType());
    //Test that the actual received content-length is the same the declared content lenghth on response header
    assertEquals(contentLenth, resp.getContentLength());

    //assertNotNull(resp.getContentLength());

    //*** note: this test is only expected to pass if the underlying policy doesn't dictate that the Person
    //object has to be altered before creation.
    //Test that a correct Etag was sent with the response
    assertEquals(ETagCalculator.calculate(Integer.toString(bop.hashCode())), resp.getHeader(ETAG));
}

From source file:org.fosstrak.epcis.repository.query.QuerySubscription.java

/**
 * Updates the subscription in the database. This is required in order to
 * correctly re-initialize the subscriptions, especially the
 * lastTimeExecuted field, after a context restart.
 * <p>//from   w  ww .j  av  a 2s . c  om
 * TODO: This is a back-end method: move this method to the
 * QueryOperationsBackend and delegate to it (thus we would need a reference
 * to the QueryOperationsBackend in this class).
 * 
 * @param lastTimeExecuted
 *            The new lastTimeExecuted.
 */
private void updateSubscription(final Calendar lastTimeExecuted) {
    String jndiName = getProperties().getProperty("jndi.datasource.name", "java:comp/env/jdbc/EPCISDB");
    try {
        // open a database connection
        Context ctx = new InitialContext();
        DataSource db = (DataSource) ctx.lookup(jndiName);
        Connection dbconnection = db.getConnection();

        // update the subscription in the database
        String update = "UPDATE subscription SET lastexecuted=(?), params=(?)" + " WHERE subscriptionid=(?);";
        PreparedStatement stmt = dbconnection.prepareStatement(update);
        LOG.debug("SQL: " + update);
        Timestamp ts = new Timestamp(lastTimeExecuted.getTimeInMillis());
        String time = ts.toString();
        stmt.setString(1, time);
        LOG.debug("       query param 1: " + time);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outStream);
        out.writeObject(queryParams);
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(2, inStream, inStream.available());
        LOG.debug("       query param 2: [" + inStream.available() + " bytes]");
        stmt.setString(3, subscriptionID);
        LOG.debug("       query param 3: " + subscriptionID);
        stmt.executeUpdate();
        dbconnection.commit();

        // close the database connection
        dbconnection.close();
    } catch (SQLException e) {
        String msg = "An SQL error occurred while updating the subscriptions in the database.";
        LOG.error(msg, e);
    } catch (IOException e) {
        String msg = "Unable to update the subscription in the database: " + e.getMessage();
        LOG.error(msg, e);
    } catch (NamingException e) {
        String msg = "Unable to find JNDI data source with name " + jndiName;
        LOG.error(msg, e);
    }
}