Example usage for java.io PushbackInputStream PushbackInputStream

List of usage examples for java.io PushbackInputStream PushbackInputStream

Introduction

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

Prototype

public PushbackInputStream(InputStream in) 

Source Link

Document

Creates a PushbackInputStream with a 1-byte pushback buffer, and saves its argument, the input stream in, for later use.

Usage

From source file:org.apache.pig.builtin.Utf8StorageConverter.java

@Override
public Map<String, Object> bytesToMap(byte[] b, ResourceFieldSchema fieldSchema) throws IOException {
    if (b == null)
        return null;
    Map<String, Object> map;
    try {//from  w ww.  j  av  a  2 s .com
        ByteArrayInputStream bis = new ByteArrayInputStream(b);
        PushbackInputStream in = new PushbackInputStream(bis);
        map = consumeMap(in, fieldSchema);
    } catch (IOException e) {
        LogUtils.warn(this, "Unable to interpret value " + Arrays.toString(b) + " in field being "
                + "converted to type map, caught ParseException <" + e.getMessage() + "> field discarded",
                PigWarning.FIELD_DISCARDED_TYPE_CONVERSION_FAILED, mLog);
        return null;
    }
    return map;
}

From source file:org.apache.pig.builtin.Utf8StorageConverter.java

@Override
public Tuple bytesToTuple(byte[] b, ResourceFieldSchema fieldSchema) throws IOException {
    if (b == null)
        return null;
    Tuple t;/* ww  w .  j av a 2  s .c om*/

    try {
        ByteArrayInputStream bis = new ByteArrayInputStream(b);
        PushbackInputStream in = new PushbackInputStream(bis);
        t = consumeTuple(in, fieldSchema);
    } catch (IOException e) {
        LogUtils.warn(this, "Unable to interpret value " + Arrays.toString(b) + " in field being "
                + "converted to type tuple, caught ParseException <" + e.getMessage() + "> field discarded",
                PigWarning.FIELD_DISCARDED_TYPE_CONVERSION_FAILED, mLog);
        return null;
    }

    return t;
}

From source file:com.temenos.interaction.media.hal.HALProvider.java

/**
 * Reads a Hypertext Application Language (HAL) representation of
 * {@link EntityResource} from the input stream.
 * //from www . ja v  a  2s .c  o  m
 * @precondition {@link InputStream} contains a valid HAL <resource/> document
 * @postcondition {@link EntityResource} will be constructed and returned.
 * @invariant valid InputStream
 */
@Override
public RESTResource readFrom(Class<RESTResource> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {
    /* To detect if the stream is empty (a valid case since an input entity is
     * sometimes optional), wrap in a PushbackInputStream before passing on
     */
    PushbackInputStream wrappedStream = new PushbackInputStream(entityStream);
    int firstByte = wrappedStream.read();
    uriInfo = new UriInfoImpl(uriInfo);
    if (firstByte == -1) {
        // No data provided
        return null;
    } else {
        // There is something in the body, so we will parse it. It is required
        // to be a valid JSON object. First replace the byte we borrowed.
        wrappedStream.unread(firstByte);

        //Parse hal+json into an Entity object
        Entity entity;
        try {
            entity = buildEntityFromHal(wrappedStream, mediaType);
        } catch (MethodNotAllowedException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Error building the entity.", e);
            }
            StringBuilder allowHeader = new StringBuilder();

            Set<String> allowedMethods = new HashSet<String>(e.getAllowedMethods());
            allowedMethods.add("HEAD");
            allowedMethods.add("OPTIONS");

            for (String method : allowedMethods) {
                allowHeader.append(method);
                allowHeader.append(", ");
            }

            Response response = Response.status(405)
                    .header("Allow", allowHeader.toString().substring(0, allowHeader.length() - 2)).build();

            throw new WebApplicationException(response);
        }
        return new EntityResource<Entity>(entity);
    }
}

From source file:com.temenos.interaction.media.odata.xml.atom.AtomXMLProvider.java

/**
 * Method to verify if receieved stream has content or its empty
 * @param stream Stream to check//from   w  w w . ja va  2  s.c o  m
 * @return verified stream
 * @throws IOException
 */
private InputStream verifyContentReceieved(InputStream stream) throws IOException {

    if (stream == null) { // Check if its null
        LOGGER.debug("Request stream received as null");
        return null;
    } else if (stream.markSupported()) { // Check stream supports mark/reset
        // mark() and read the first byte just to check
        stream.mark(1);
        final int bytesRead = stream.read(new byte[1]);
        if (bytesRead != -1) {
            //stream not empty
            stream.reset(); // reset the stream as if untouched
            return stream;
        } else {
            //stream empty
            LOGGER.debug("Request received with empty body");
            return null;
        }
    } else {
        // Panic! this stream does not support mark/reset, try with PushbackInputStream as a last resort
        int bytesRead;
        PushbackInputStream pbs = new PushbackInputStream(stream);
        if ((bytesRead = pbs.read()) != -1) {
            // Contents detected, unread and return
            pbs.unread(bytesRead);
            return pbs;
        } else {
            // Empty stream detected
            LOGGER.debug("Request received with empty body!");
            return null;
        }
    }
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void handleSetContainerAcl(HttpServletRequest request, HttpServletResponse response,
        InputStream is, BlobStore blobStore, String containerName) throws IOException, S3Exception {
    ContainerAccess access;/*from   ww  w  .  j  a  v a2s.c om*/

    String cannedAcl = request.getHeader("x-amz-acl");
    if (cannedAcl == null || "private".equalsIgnoreCase(cannedAcl)) {
        access = ContainerAccess.PRIVATE;
    } else if ("public-read".equalsIgnoreCase(cannedAcl)) {
        access = ContainerAccess.PUBLIC_READ;
    } else if (CANNED_ACLS.contains(cannedAcl)) {
        throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    PushbackInputStream pis = new PushbackInputStream(is);
    int ch = pis.read();
    if (ch != -1) {
        pis.unread(ch);
        AccessControlPolicy policy = new XmlMapper().readValue(pis, AccessControlPolicy.class);
        String accessString = mapXmlAclsToCannedPolicy(policy);
        if (accessString.equals("private")) {
            access = ContainerAccess.PRIVATE;
        } else if (accessString.equals("public-read")) {
            access = ContainerAccess.PUBLIC_READ;
        } else {
            throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
        }
    }

    blobStore.setContainerAccess(containerName, access);
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void handleSetBlobAcl(HttpServletRequest request, HttpServletResponse response, InputStream is,
        BlobStore blobStore, String containerName, String blobName) throws IOException, S3Exception {
    BlobAccess access;// www  . j a v  a2s . c  o m

    String cannedAcl = request.getHeader("x-amz-acl");
    if (cannedAcl == null || "private".equalsIgnoreCase(cannedAcl)) {
        access = BlobAccess.PRIVATE;
    } else if ("public-read".equalsIgnoreCase(cannedAcl)) {
        access = BlobAccess.PUBLIC_READ;
    } else if (CANNED_ACLS.contains(cannedAcl)) {
        throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    PushbackInputStream pis = new PushbackInputStream(is);
    int ch = pis.read();
    if (ch != -1) {
        pis.unread(ch);
        AccessControlPolicy policy = new XmlMapper().readValue(pis, AccessControlPolicy.class);
        String accessString = mapXmlAclsToCannedPolicy(policy);
        if (accessString.equals("private")) {
            access = BlobAccess.PRIVATE;
        } else if (accessString.equals("public-read")) {
            access = BlobAccess.PUBLIC_READ;
        } else {
            throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
        }
    }

    blobStore.setBlobAccess(containerName, blobName, access);
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void handleContainerCreate(HttpServletRequest request, HttpServletResponse response,
        InputStream is, BlobStore blobStore, String containerName) throws IOException, S3Exception {
    if (containerName.isEmpty()) {
        throw new S3Exception(S3ErrorCode.METHOD_NOT_ALLOWED);
    }/*  ww  w . j  a v a 2 s.  c  o m*/
    if (containerName.length() < 3 || containerName.length() > 255 || containerName.startsWith(".")
            || containerName.endsWith(".") || validateIpAddress(containerName)
            || !VALID_BUCKET_FIRST_CHAR.matches(containerName.charAt(0))
            || !VALID_BUCKET.matchesAllOf(containerName)) {
        throw new S3Exception(S3ErrorCode.INVALID_BUCKET_NAME);
    }

    String contentLengthString = request.getHeader(HttpHeaders.CONTENT_LENGTH);
    if (contentLengthString != null) {
        long contentLength;
        try {
            contentLength = Long.parseLong(contentLengthString);
        } catch (NumberFormatException nfe) {
            throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT, nfe);
        }
        if (contentLength < 0) {
            throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT);
        }
    }

    String locationString;
    try (PushbackInputStream pis = new PushbackInputStream(is)) {
        int ch = pis.read();
        if (ch == -1) {
            // handle empty bodies
            locationString = null;
        } else {
            pis.unread(ch);
            CreateBucketRequest cbr = new XmlMapper().readValue(pis, CreateBucketRequest.class);
            locationString = cbr.locationConstraint;
        }
    }

    Location location = null;
    if (locationString != null) {
        for (Location loc : blobStore.listAssignableLocations()) {
            if (loc.getId().equalsIgnoreCase(locationString)) {
                location = loc;
                break;
            }
        }
        if (location == null) {
            throw new S3Exception(S3ErrorCode.INVALID_LOCATION_CONSTRAINT);
        }
    }
    logger.debug("Creating bucket with location: {}", location);

    CreateContainerOptions options = new CreateContainerOptions();
    String acl = request.getHeader("x-amz-acl");
    if ("public-read".equalsIgnoreCase(acl)) {
        options.publicRead();
    }

    boolean created;
    try {
        created = blobStore.createContainerInLocation(location, containerName, options);
    } catch (AuthorizationException ae) {
        throw new S3Exception(S3ErrorCode.BUCKET_ALREADY_EXISTS, ae);
    }
    if (!created) {
        throw new S3Exception(S3ErrorCode.BUCKET_ALREADY_OWNED_BY_YOU,
                S3ErrorCode.BUCKET_ALREADY_OWNED_BY_YOU.getMessage(), null,
                ImmutableMap.of("BucketName", containerName));
    }

    response.addHeader(HttpHeaders.LOCATION, "/" + containerName);
}

From source file:com.cohort.util.String2.java

/**
 * On the command line, this prompts the user a String (which is
 * not echoed to the screen, so is suitable for passwords).
 * This is slighly modified from /*from w  w  w . j ava  2  s.  c o m*/
 * http://java.sun.com/developer/technicalArticles/Security/pwordmask/ .
 *
 * @param prompt
 * @return the String the user entered
 * @throws Exception if trouble
 */
public static final String getPasswordFromSystemIn(String prompt) throws Exception {
    InputStream in = System.in; //bob added, instead of parameter

    MaskingThread maskingthread = new MaskingThread(prompt);
    Thread thread = new Thread(maskingthread);
    thread.start();

    char[] lineBuffer;
    char[] buf;
    int i;

    buf = lineBuffer = new char[128];

    int room = buf.length;
    int offset = 0;
    int c;

    try { //bob added
        loop: while (true) {
            c = in.read();
            if (c == -1 || c == '\n')
                break loop;
            if (c == '\r') {
                int c2 = in.read();
                if ((c2 != '\n') && (c2 != -1)) {
                    if (!(in instanceof PushbackInputStream)) {
                        in = new PushbackInputStream(in);
                    }
                    ((PushbackInputStream) in).unread(c2);
                } else {
                    break loop;
                }
            }

            //if not caught and 'break loop' above...
            if (--room < 0) {
                buf = new char[offset + 128];
                room = buf.length - offset - 1;
                System.arraycopy(lineBuffer, 0, buf, 0, offset);
                Arrays.fill(lineBuffer, ' ');
                lineBuffer = buf;
            }
            buf[offset++] = (char) c;
        }
    } catch (Exception e) {
    }
    maskingthread.stopMasking();
    if (offset == 0) {
        return ""; //bob changed from null
    }
    char[] ret = new char[offset];
    System.arraycopy(buf, 0, ret, 0, offset);
    Arrays.fill(buf, ' ');
    return new String(ret); //bob added; originally it returned char[]
}

From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java

/**
 * @param in stream to be used (e.g. System.in)
 * @param prompt The prompt to display to the user.
 * @return The password as entered by the user.
 * @throws IOException //w  w w.  j a va 2  s  .  c  o m
 */
public static final char[] retrievePasswordFromStdin(InputStream in, String prompt) throws IOException {
    MaskingThread maskingthread = new MaskingThread(prompt);

    Thread thread = new Thread(maskingthread);
    thread.start();

    char[] lineBuffer;
    char[] buf;

    buf = lineBuffer = new char[128];

    int room = buf.length;
    int offset = 0;
    int c;

    loop: while (true) {
        switch (c = in.read()) {
        case -1:
        case '\n':
            break loop;

        case '\r':
            int c2 = in.read();
            if ((c2 != '\n') && (c2 != -1)) {
                if (!(in instanceof PushbackInputStream)) {
                    in = new PushbackInputStream(in);
                }
                ((PushbackInputStream) in).unread(c2);
            } else {
                break loop;
            }

        default:
            if (--room < 0) {
                buf = new char[offset + 128];
                room = buf.length - offset - 1;
                System.arraycopy(lineBuffer, 0, buf, 0, offset);
                Arrays.fill(lineBuffer, ' ');
                lineBuffer = buf;
            }
            buf[offset++] = (char) c;
            break;
        }
    }
    maskingthread.stopMasking();
    if (offset == 0) {
        return null;
    }
    char[] ret = new char[offset];
    System.arraycopy(buf, 0, ret, 0, offset);
    Arrays.fill(buf, ' ');
    return ret;
}