Example usage for java.io BufferedReader read

List of usage examples for java.io BufferedReader read

Introduction

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

Prototype

public int read(char cbuf[], int off, int len) throws IOException 

Source Link

Document

Reads characters into a portion of an array.

Usage

From source file:org.intermine.web.struts.BuildBagAction.java

/**
 * Action for creating a bag of InterMineObjects or Strings from identifiers in text field.
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @return an ActionForward object defining where control goes next
 * @exception Exception if the application business logic throws
 *  an exception// ww  w.  j  a  va 2s .  c o m
 */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    final InterMineAPI im = SessionMethods.getInterMineAPI(session);
    ServletContext servletContext = request.getSession().getServletContext();
    Properties webProperties = (Properties) servletContext.getAttribute(Constants.WEB_PROPERTIES);
    BuildBagForm buildBagForm = (BuildBagForm) form;

    String type = buildBagForm.getType();

    if (StringUtils.isEmpty(type)) {
        recordError(new ActionMessage("bagBuild.typeNotSet"), request);
        return mapping.findForward("bags");
    }

    BagQueryRunner bagRunner = im.getBagQueryRunner();

    int maxBagSize = WebUtil.getIntSessionProperty(session, "max.bag.size", 100000);
    Profile profile = SessionMethods.getProfile(session);
    if (profile == null || profile.getUsername() == null) {
        int defaultMaxNotLoggedSize = 3;
        maxBagSize = WebUtil.getIntSessionProperty(session, "max.bag.size.notloggedin",
                defaultMaxNotLoggedSize);
    }
    BufferedReader reader = null;
    FormFile formFile = buildBagForm.getFormFile();

    /*
     * FormFile used from Struts works a bit strangely.
     * 1. Although the file does't exist formFile.getInputStream() doesn't
     * throw FileNotFoundException.
     * 2. When user specified empty file path or very invalid file path,
     * like file path not starting at '/' then formFile.getFileName() returns empty string.
     */
    if (formFile != null && formFile.getFileName() != null && formFile.getFileName().length() > 0) {
        // attach file name as the name of the bag
        String fileName = formFile.getFileName();
        // strip suffix
        Integer lastPos = new Integer(fileName.lastIndexOf('.'));
        if (lastPos.intValue() > 0) {
            fileName = fileName.substring(0, lastPos.intValue());
        }
        // replace underscores
        fileName = fileName.replaceAll("_", " ");
        // attach
        request.setAttribute("bagName", fileName);

        String mimetype = formFile.getContentType();
        if (!"application/octet-stream".equals(mimetype) && !mimetype.startsWith("text")) {
            recordError(new ActionMessage("bagBuild.notText", mimetype), request);
            return mapping.findForward("bags");
        }
        if (formFile.getFileSize() == 0) {
            recordError(new ActionMessage("bagBuild.noBagFileOrEmpty"), request);
            return mapping.findForward("bags");
        }
        reader = new BufferedReader(new InputStreamReader(formFile.getInputStream()));
    } else if (buildBagForm.getText() != null && buildBagForm.getText().length() != 0) {
        String trimmedText = buildBagForm.getText().trim();
        if (trimmedText.length() == 0) {
            recordError(new ActionMessage("bagBuild.noBagPaste"), request);
            return mapping.findForward("bags");
        }
        reader = new BufferedReader(new StringReader(trimmedText));
    } else {
        recordError(new ActionMessage("bagBuild.noBagFile"), request);
        return mapping.findForward("bags");
    }

    reader.mark(READ_AHEAD_CHARS);

    char[] buf = new char[READ_AHEAD_CHARS];

    int read = reader.read(buf, 0, READ_AHEAD_CHARS);

    for (int i = 0; i < read; i++) {
        if (buf[i] == 0) {
            recordError(new ActionMessage("bagBuild.notText", "binary"), request);
            return mapping.findForward("bags");
        }
    }

    reader.reset();

    String thisLine;
    List<String> list = new ArrayList<String>();
    int elementCount = 0;
    while ((thisLine = reader.readLine()) != null) {
        // append whitespace to valid delimiters
        String bagUploadDelims = (String) webProperties.get("list.upload.delimiters") + " ";
        StrMatcher matcher = StrMatcher.charSetMatcher(bagUploadDelims);
        StrTokenizer st = new StrTokenizer(thisLine, matcher, StrMatcher.doubleQuoteMatcher());
        while (st.hasNext()) {
            String token = st.nextToken();
            list.add(token);
            elementCount++;
            if (elementCount > maxBagSize) {
                ActionMessage actionMessage = null;
                if (profile == null || profile.getUsername() == null) {
                    actionMessage = new ActionMessage("bag.bigNotLoggedIn", new Integer(maxBagSize));
                } else {
                    actionMessage = new ActionMessage("bag.tooBig", new Integer(maxBagSize));
                }
                recordError(actionMessage, request);
                return mapping.findForward("bags");
            }
        }
    }
    BagQueryResult bagQueryResult = bagRunner.search(type, list, buildBagForm.getExtraFieldValue(), false,
            buildBagForm.getCaseSensitive());
    session.setAttribute("bagQueryResult", bagQueryResult);
    request.setAttribute("bagType", type);
    request.setAttribute("bagExtraFilter", buildBagForm.getExtraFieldValue());
    //buildNewBag used by jsp to set editable the bag name field
    request.setAttribute("buildNewBag", "true");
    return mapping.findForward("bagUploadConfirm");
}

From source file:org.helios.collector.url.URLCollector.java

/**
 * Implementation of abstract collectCallback method from base class (AbstractCollector)
 * @return CollectionResult Results of the scheduled URL Monitor
 *//*  w ww . jav  a2s . co  m*/
public CollectionResult collectCallback() {
    int availability = 0;
    int httpResponseCode = -1;
    int contentSize = -1;
    int successContentMatched = 0;
    int failureContentMatched = 0;
    BufferedReader reader = null;
    CollectionResult result = new CollectionResult();

    try {
        if (httpClient != null) {
            if (!isWebServiceEndpoint) {
                httpResponseCode = httpClient.executeMethod(getMethod);
                trace("HTTP Response Code returned by URL [" + this.url.toString() + "] is: "
                        + httpResponseCode);
                reader = new BufferedReader(new InputStreamReader(getMethod.getResponseBodyAsStream()));
            } else {
                if (wsStyle.equalsIgnoreCase("SOAP")) {
                    httpResponseCode = httpClient.executeMethod(postMethod);
                    reader = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream()));
                } else {
                    httpResponseCode = httpClient.executeMethod(getMethod);
                    reader = new BufferedReader(new InputStreamReader(getMethod.getResponseBodyAsStream()));
                }
            }
            if (httpResponseCode != HttpStatus.SC_OK) {
                availability = 0;
                throw new CollectorException("HTTP Response Code returned by URL [" + this.url.toString()
                        + "] is: " + httpResponseCode);
            } else { // Response code is 200
                availability = 1; //check for any success or failure patterns
                if (successContentPattern != null || failureContentPattern != null) {
                    long startT = System.currentTimeMillis();
                    char[] holder = new char[BYTES_TO_READ];
                    String firstBucket = "";
                    String secondBucket = "";
                    try {
                        int bytesRead = reader.read(holder, 0, BYTES_TO_READ);
                        while (bytesRead != -1) {
                            secondBucket = new String(holder);
                            if (successContentPattern != null && successContentMatched == 0)
                                successContentMatched = successContentPattern
                                        .matcher(firstBucket + secondBucket).find() == true ? 1 : 0;

                            if (failureContentPattern != null && failureContentMatched == 0)
                                failureContentMatched = failureContentPattern
                                        .matcher(firstBucket + secondBucket).find() == true ? 1 : 0;

                            contentSize += bytesRead;
                            firstBucket = secondBucket;
                            holder = new char[BYTES_TO_READ];
                            bytesRead = reader.read(holder, 0, BYTES_TO_READ);
                        }
                        //tracer.traceSticky(contentSize, "Content Size", getTracingNameSpace());
                        tracer.traceGauge(contentSize, "Content Size", getTracingNameSpace());
                        debug("Time taken for success/failure pattern matcher: "
                                + (System.currentTimeMillis() - startT));
                    } catch (IOException iox) {
                        debug("An error occured while matching the success/failure pattern..."
                                + iox.getMessage());
                    }

                    if (failureContentMatched == 1)
                        availability = 0;
                    else if (successContentPattern != null && successContentMatched == 0)
                        availability = 0;
                }

                result.setResultForLastCollection(CollectionResult.Result.SUCCESSFUL);
            }
        } else { // Either HTTPClient or GetMethod is not initialized properly
            availability = 0;
            throw new CollectorException(
                    "Invalid state of HttpClient or GetMethod for location [ " + getUrl() + " ]");
        }
    } catch (Exception ex) {
        if (logErrors) {
            error(ex.getMessage(), ex);
        }
        result.setResultForLastCollection(CollectionResult.Result.FAILURE);
        result.setAnyException(ex);
        return result;
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            tracer.traceGauge(availability, defaultAvailabilityLabel, getTracingNameSpace());
            tracer.traceGauge(httpResponseCode, "ResponseCode", getTracingNameSpace());
            if (successContentPattern != null) {
                tracer.traceGauge(successContentMatched, "SuccessContentMatch", getTracingNameSpace());
            }
            if (failureContentPattern != null) {
                tracer.traceGauge(failureContentMatched, "FailureContentMatch", getTracingNameSpace());
            }
        } catch (Exception ex) {
            reader = null;
        }
    }
    return result;
}

From source file:CB_Utils.Util.Downloader.java

/**
 * Start downloading the remote resource. The target object should not be accessed until after calling waitUntilCompleted().
 *//*from   w w  w.j ava  2s .c o m*/
@Override
public void run() {
    synchronized (stateLock) {
        if (started) {
            return;
        } else {
            started = true;
            running = true;
        }
    }

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    BufferedReader br = null;

    try {
        /* open connection to the URL */
        checkState();
        progressString = "Opening connection to remote resource";
        progressUpdated = true;

        final URLConnection link;

        try {
            link = url.openConnection();
            link.connect();
        } catch (Exception e) {
            progressString = "Failed to open connection to remote resource";
            progressUpdated = true;
            throw e;
        }

        /* get length of the remote resource */
        checkState();
        progressString = "Getting length of remote resource";
        progressUpdated = true;

        /* get size of webpage in bytes; -1 if unknown */
        final int length = link.getContentLength();

        synchronized (lengthLock) {
            totalLength = length;
        }

        progressUpdated = true;

        /* open input stream to remote resource */
        checkState();
        progressString = "Opening input stream to remote resource";
        progressUpdated = true;

        InputStream input = null;

        try {

            if (totalLength < 1) {

                // load with http Request
                HttpGet httppost = new HttpGet(url.toString());

                // Execute HTTP Post Request
                try {
                    HttpParams httpParameters = new BasicHttpParams();
                    HttpConnectionParams.setConnectionTimeout(httpParameters, HttpUtils.conectionTimeout);
                    HttpConnectionParams.setSoTimeout(httpParameters, HttpUtils.socketTimeout);
                    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
                    HttpResponse response = httpClient.execute(httppost);
                    input = response.getEntity().getContent();
                } catch (ConnectTimeoutException e1) {

                    e1.printStackTrace();
                } catch (ClientProtocolException e1) {

                    e1.printStackTrace();
                } catch (IOException e1) {

                    e1.printStackTrace();
                }

            } else {
                input = link.getInputStream();
            }

            if (target instanceof File) {
                bis = new BufferedInputStream(input);
            } else if (target instanceof StringBuilder) {
                final String contentType = link.getContentType().toLowerCase(Locale.ENGLISH);

                /* look for charset, if specified */
                String charset = null;
                final Matcher m = Pattern.compile(".*charset[\\s]*=([^;]++).*").matcher(contentType);

                if (m.find()) {
                    charset = m.group(1).trim();
                }

                if ((charset != null) && charset.length() > 0) {
                    try {
                        br = new BufferedReader(new InputStreamReader(input, charset));
                    } catch (Exception e) {
                        br = null;
                    }
                }

                if (br == null) {
                    br = new BufferedReader(new InputStreamReader(input));
                }
            }
        } catch (Exception e) {
            progressString = "Failed to open input stream to remote resource";
            progressUpdated = true;
            throw e;
        }

        /* open output stream, if necessary */
        if (target instanceof File) {
            checkState();
            progressString = "Opening output stream to local file";
            progressUpdated = true;

            try {
                /* create parent directories, if necessary */
                final File f = (File) target;
                final File parent = f.getParentFile();

                if ((parent != null) && !parent.exists()) {
                    parent.mkdirs();
                }

                bos = new BufferedOutputStream(f.getFileOutputStream());
            } catch (Exception e) {
                progressString = "Failed to open output stream to local file";
                progressUpdated = true;
                throw e;
            }
        }

        /* download remote resource iteratively */
        progressString = "Downloading";
        progressUpdated = true;

        try {
            if (target instanceof File) {
                final byte[] byteBuffer = new byte[BUFFER_SIZE];

                while (true) {
                    checkState();
                    final int byteCount = bis.read(byteBuffer, 0, BUFFER_SIZE);

                    /* check for end-of-stream */
                    if (byteCount == -1) {
                        break;
                    }

                    bos.write(byteBuffer, 0, byteCount);

                    synchronized (lengthLock) {
                        downloadedLength += byteCount;
                    }

                    progressUpdated = true;
                }
            } else if (target instanceof StringBuilder) {
                final char[] charBuffer = new char[BUFFER_SIZE];
                final StringBuilder sb = (StringBuilder) target;

                while (true) {
                    checkState();
                    final int charCount = br.read(charBuffer, 0, BUFFER_SIZE);

                    /* check for end-of-stream */
                    if (charCount == -1) {
                        break;
                    }

                    sb.append(charBuffer, 0, charCount);

                    synchronized (lengthLock) {
                        downloadedLength += charCount; /* may be inaccurate because byte != char */
                    }

                    progressUpdated = true;
                }
            }
        } catch (Exception e) {
            progressString = "Failed to download remote resource";
            progressUpdated = true;
            throw e;
        }

        /* download completed successfully */
        progressString = "Download completed";
        progressUpdated = true;
    } catch (Exception e) {
        error = e;
    } finally {
        /* clean-up */
        for (Closeable c : new Closeable[] { bis, br, bos }) {
            if (c != null) {
                try {
                    c.close();
                } catch (Exception e) {
                    /* ignore */
                }
            }
        }

        synchronized (stateLock) {
            running = false;
            completed = true;
        }
    }
}