Example usage for java.io PushbackInputStream unread

List of usage examples for java.io PushbackInputStream unread

Introduction

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

Prototype

public void unread(byte[] b) throws IOException 

Source Link

Document

Pushes back an array of bytes by copying it to the front of the pushback buffer.

Usage

From source file:it.unifi.rcl.chess.traceanalysis.Trace.java

/**
 * Checks if the input stream is compressed, and in case it returns a GZIPInputStream
 * @param stream/*w  w w.j  a va2s . c  om*/
 * @return
 * @throws IOException
 */
private static boolean checkGZIP(InputStream stream) throws IOException {
    PushbackInputStream pb = new PushbackInputStream(stream, 2); //we need a pushbackstream to look ahead
    byte[] signature = new byte[2];
    pb.read(signature); //read the signature
    pb.unread(signature); //push back the signature to the stream
    if (signature[0] == (byte) 0x1f && signature[1] == (byte) 0x8b) //check if matches standard gzip magic number
        return true;
    else
        return false;
}

From source file:com.digitalpebble.storm.crawler.protocol.http.HttpResponse.java

private static int peek(PushbackInputStream in) throws IOException {
    int value = in.read();
    in.unread(value);
    return value;
}

From source file:Main.java

public static final int ReadInt(PushbackInputStream in, int def) {
    int b;//from  w w w  .ja  va 2s. c  o m
    boolean neg = false;
    int i = 0, digits = 0;
    try {
        while (true) {
            b = (int) in.read() & 0xff;
            if (b == '-' && digits == 0)
                neg = !neg;
            else if (Character.isDigit(b)) {
                i = 10 * i + (b - (int) '0');
                ++digits;
            } else if (digits != 0 || !Character.isSpace((char) b)) {
                if (b != -1)
                    in.unread(b);
                break;
            }
        }
    } catch (IOException e) {
    }
    try {
        while ((b = in.read()) != '/' && b != -1)
            ;
    } catch (IOException e) {
    }
    if (neg)
        i = -i;
    return digits > 0 ? i : def;
}

From source file:grails.converters.JSON.java

/**
 * Parses the given request's InputStream and returns ether a JSONObject or a JSONArry
 *
 * @param request the JSON Request/*from ww  w.j  ava2s . c  o  m*/
 * @return ether a JSONObject or a JSONArray - depending on the given JSON
 * @throws ConverterException when the JSON content is not valid
 */
public static Object parse(HttpServletRequest request) throws ConverterException {
    Object json = request.getAttribute(CACHED_JSON);
    if (json != null) {
        return json;
    }

    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = Converter.DEFAULT_REQUEST_ENCODING;
    }
    try {
        PushbackInputStream pushbackInputStream = null;
        int firstByte = -1;
        try {
            pushbackInputStream = new PushbackInputStream(request.getInputStream());
            firstByte = pushbackInputStream.read();
        } catch (IOException ioe) {
        }

        if (firstByte == -1) {
            return new JSONObject();
        }

        pushbackInputStream.unread(firstByte);
        json = parse(pushbackInputStream, encoding);
        request.setAttribute(CACHED_JSON, json);
        return json;
    } catch (IOException e) {
        throw new ConverterException("Error parsing JSON", e);
    }
}

From source file:com.hs.mail.mailet.ToRepository.java

private void deliver(Collection<Recipient> recipients, SmtpMessage message) throws IOException {
    String returnPath = (message.getNode() != SmtpMessage.LOCAL)
            ? "Return-Path: <" + message.getFrom().getMailbox() + ">\r\n"
            : null;/*from  ww  w .  j ava  2  s .  c  om*/
    MailMessage msg = message.getMailMessage();
    try {
        if (returnPath != null) {
            Header header = msg.getHeader().getHeader();
            header.setField(AbstractField.parse(returnPath));
            msg.setSize(msg.getSize() + returnPath.getBytes().length);
        }
        for (Recipient rcpt : recipients) {
            try {
                if (rcpt.getID() != -1) {
                    if (!Sieve.runSieve(context, rcpt, message)) {
                        context.storeMail(rcpt.getID(), ImapConstants.INBOX_NAME, message);
                    }
                }
            } catch (Exception e) {
                StringBuilder errorBuffer = new StringBuilder(256).append("Error while delivering message to ")
                        .append(rcpt);
                logger.error(errorBuffer.toString(), e);

                if (!message.isNotificationMessage()) {
                    errorBuffer.append(": ").append(e.getMessage().trim()).append("\r\n");
                    message.appendErrorMessage(errorBuffer.toString());
                }
            }
        }
    } catch (MimeException e) {
        // impossible really
    }
    if (msg != null && msg.getPhysMessageID() != 0) {
        try {
            if (returnPath != null) {
                PushbackInputStream is = new PushbackInputStream(msg.getInputStream(), returnPath.length());
                is.unread(returnPath.getBytes("ASCII"));
                msg.save(is);
            } else {
                msg.save(true);
            }
            builder.build(msg.getInternalDate(), msg.getPhysMessageID());
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } catch (MimeException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:eu.scape_project.up2ti.container.ArcContainer.java

@Override
public void init(String containerFileName, InputStream containerFileStream) throws IOException {
    this.containerFileName = containerFileName;
    // Read first two bytes to check if we have a gzipped input stream
    PushbackInputStream pb = new PushbackInputStream(containerFileStream, 2);
    byte[] signature = new byte[2];
    pb.read(signature);//ww  w . j ava 2  s . c o m
    pb.unread(signature);
    // use compressed reader if gzip magic number is matched
    if (signature[0] == (byte) 0x1f && signature[1] == (byte) 0x8b) {
        reader = ArcReaderFactory.getReaderCompressed(pb);
    } else {
        reader = ArcReaderFactory.getReaderUncompressed(pb);
    }
    archiveRecords = new ArrayList<ArcRecordBase>();
    // initialise object by create temporary files and the bidirectional 
    // file-record map.
    arcRecContentsToTempFiles();
}

From source file:com.trsst.server.AbstractMultipartAdapter.java

private MultipartInputStream getMultipartStream(RequestContext request, InputStream inputStream)
        throws IOException, ParseException, IllegalArgumentException {
    String boundary = request.getContentType().getParameter(BOUNDARY_PARAM);

    if (boundary == null) {
        throw new IllegalArgumentException("multipart/related stream invalid, boundary parameter is missing.");
    }//  w  w  w . j av a  2s.c o  m

    boundary = "--" + boundary;

    String type = request.getContentType().getParameter(TYPE_PARAM);
    if (!(type != null && MimeTypeHelper.isAtom(type))) {
        throw new ParseException(
                "multipart/related stream invalid, type parameter should be " + Constants.ATOM_MEDIA_TYPE);
    }

    PushbackInputStream pushBackInput = new PushbackInputStream(inputStream, 2);
    pushBackInput.unread("\r\n".getBytes());

    return new MultipartInputStream(pushBackInput, boundary.getBytes());
}

From source file:eu.scape_project.tpid.ContainerProcessing.java

/**
 * Prepare input/*from  w  ww.  j a v a  2 s  .  c  om*/
 *
 * @param pt
 * @throws IOException IO Error
 * @throws java.lang.InterruptedException
 */
public void prepareInput(Path pt) throws InterruptedException, IOException {
    FileSystem fs = FileSystem.get(context.getConfiguration());
    InputStream containerFileStream = fs.open(pt);
    String containerFileName = pt.getName();

    ArcReader reader;
    // Read first two bytes to check if we have a gzipped input stream
    PushbackInputStream pb = new PushbackInputStream(containerFileStream, 2);
    byte[] signature = new byte[2];
    pb.read(signature);
    pb.unread(signature);
    // use compressed reader if gzip magic number is matched
    if (signature[0] == (byte) 0x1f && signature[1] == (byte) 0x8b) {
        reader = ArcReaderFactory.getReaderCompressed(pb);
    } else {
        reader = ArcReaderFactory.getReaderUncompressed(pb);
    }
    long currTM = System.currentTimeMillis();
    String unpackHdfsPath = conf.get("unpack_hdfs_path", "tpid_unpacked");
    String hdfsUnpackDirStr = StringUtils.normdir(unpackHdfsPath, Long.toString(currTM));
    String hdfsJoboutputPath = conf.get("tooloutput_hdfs_path", "tpid_tooloutput");
    String hdfsOutputDirStr = StringUtils.normdir(hdfsJoboutputPath, Long.toString(currTM));

    Iterator<ArcRecordBase> arcIterator = reader.iterator();

    // Number of files which should be processed per invokation
    int numItemsPerInvocation = conf.getInt("num_items_per_task", 50);
    int numItemCounter = numItemsPerInvocation;
    // List of input files to be processed
    String inliststr = "";
    // List of output files to be generated
    String outliststr = "";
    try {
        while (arcIterator.hasNext()) {
            ArcRecordBase arcRecord = arcIterator.next();
            String recordKey = getRecordKey(arcRecord, containerFileName);
            String outFileName = RandomStringUtils.randomAlphabetic(25);
            String hdfsPathStr = hdfsUnpackDirStr + outFileName;
            Path hdfsPath = new Path(hdfsPathStr);
            String outputFileSuffix = conf.get("output_file_suffix", ".fits.xml");
            String hdfsOutPathStr = hdfsOutputDirStr + outFileName + outputFileSuffix;
            FSDataOutputStream hdfsOutStream = fs.create(hdfsPath);
            ArcUtils.recordToOutputStream(arcRecord, hdfsOutStream);
            Text key = new Text(recordKey);
            Text value = new Text(fs.getHomeDirectory() + File.separator + hdfsOutPathStr);
            mos.write("keyfilmapping", key, value);
            String scapePlatformInvoke = conf.get("scape_platform_invoke", "fits dirxml");
            Text ptmrkey = new Text(scapePlatformInvoke);
            // for the configured number of items per invokation, add the 
            // files to the input and output list of the command.
            inliststr += "," + fs.getHomeDirectory() + File.separator + hdfsPathStr;
            outliststr += "," + fs.getHomeDirectory() + File.separator + hdfsOutPathStr;
            if (numItemCounter > 1 && arcIterator.hasNext()) {
                numItemCounter--;
            } else if (numItemCounter == 1 || !arcIterator.hasNext()) {
                inliststr = inliststr.substring(1); // cut off leading comma 
                outliststr = outliststr.substring(1); // cut off leading comma 
                String pattern = conf.get("tomar_param_pattern", "%1$s %2$s");
                String ptMrStr = StringUtils.formatCommandOutput(pattern, inliststr, outliststr);
                Text ptmrvalue = new Text(ptMrStr);
                // emit tomar input line where the key is the tool invokation
                // (tool + operation) and the value is the parameter list
                // where input and output strings contain file lists.
                mos.write("tomarinput", ptmrkey, ptmrvalue);
                numItemCounter = numItemsPerInvocation;
                inliststr = "";
                outliststr = "";
            }
        }
    } catch (Exception ex) {
        mos.write("error", new Text("Error"), new Text(pt.toString()));
    }

}

From source file:edu.mayo.trilliumbridge.webapp.TransformerController.java

/**
 * From http://stackoverflow.com/a/19137900/656853
 *//*  w  ww  . ja  v  a  2 s.  c  o  m*/
private InputStream checkStreamIsNotEmpty(InputStream inputStream) throws IOException {
    if (inputStream == null) {
        throw new UserInputException(NO_CONTENT_ERROR_MSG);
    }

    PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream);
    int b;
    b = pushbackInputStream.read();
    if (b == -1) {
        throw new UserInputException("No file or XML content body sent.");
    }
    pushbackInputStream.unread(b);

    return pushbackInputStream;
}

From source file:eu.europeana.uim.sugarcrmclient.internal.ExtendedSaajSoapMessageFactory.java

/**
 * Checks for the UTF-8 Byte Order Mark, and removes it if present. The SAAJ RI cannot cope with these BOMs.
 *
 * @see <a href="http://jira.springframework.org/browse/SWS-393">SWS-393</a>
 * @see <a href="http://unicode.org/faq/utf_bom.html#22">UTF-8 BOMs</a>
 *///from   w ww.j  av a  2s. co m
private InputStream checkForUtf8ByteOrderMark(InputStream inputStream) throws IOException {
    PushbackInputStream pushbackInputStream = new PushbackInputStream(new BufferedInputStream(inputStream), 3);
    byte[] bom = new byte[3];
    if (pushbackInputStream.read(bom) != -1) {
        // check for the UTF-8 BOM, and remove it if there. See SWS-393
        if (!(bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF)) {
            pushbackInputStream.unread(bom);
        }
    }
    return pushbackInputStream;
}