Example usage for java.io InputStreamReader ready

List of usage examples for java.io InputStreamReader ready

Introduction

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

Prototype

public boolean ready() throws IOException 

Source Link

Document

Tells whether this stream is ready to be read.

Usage

From source file:org.mzd.shap.analysis.metagene.Metagene2008ToXML.java

public static void main(String[] args) throws IOException, BeanIOException {
    if (args.length != 2) {
        System.out.println("[input sequence] [output orfs]");
        System.exit(1);/* w  w  w . ja  va2 s  . c om*/
    }

    Process p = Runtime.getRuntime().exec("metagene " + args[0]);
    try {
        synchronized (p) {
            StringWriter sw = new StringWriter();
            InputStreamReader isr = new InputStreamReader(p.getInputStream());
            int retVal;
            while (true) {
                p.wait(100);
                while (isr.ready()) {
                    sw.write(isr.read());
                }
                try {
                    retVal = p.exitValue();
                    break;
                } catch (IllegalThreadStateException ex) {
                    /*...*/}
            }

            // Just make sure stdout is completely empty.
            while (isr.ready()) {
                sw.write(isr.read());
            }

            if (retVal != 0) {
                System.out.println("Non-zero exist status [" + retVal + "]");
                InputStream is = null;
                try {
                    is = p.getErrorStream();
                    while (is.available() > 0) {
                        System.out.write(is.read());
                    }
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
            } else {
                new Metagene2008ToXML().convert(sw.toString(), new File(args[1]));
            }

            System.exit(retVal);
        }
    } catch (InterruptedException ex) {
        /*...*/}
}

From source file:org.sakaiproject.assignment.tool.AssignmentAction.java

/**
 * upload local file for attachment//from   w ww.  j  a  v  a2  s .  c o m
 * @param data
 * @param singleFileUpload
 */
public void doAttachUpload(RunData data, boolean singleFileUpload) {
    if (!"POST".equals(data.getRequest().getMethod())) {
        return;
    }

    SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
    ToolSession toolSession = SessionManager.getCurrentToolSession();
    ParameterParser params = data.getParameters();

    String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1");

    // construct the state variable for attachment list
    List attachments = state.getAttribute(ATTACHMENTS) != null ? (List) state.getAttribute(ATTACHMENTS)
            : EntityManager.newReferenceList();

    FileItem fileitem = null;
    try {
        fileitem = params.getFileItem("upload");
    } catch (Exception e) {
        // other exceptions should be caught earlier
        M_log.debug(this + ".doAttachupload ***** Unknown Exception ***** " + e.getMessage());
        addAlert(state, rb.getString("failed.upload"));
    }
    if (fileitem == null) {
        // "The user submitted a file to upload but it was too big!"
        addAlert(state, rb.getFormattedMessage("size.exceeded", new Object[] { max_file_size_mb }));
        //addAlert(state, hrb.getString("size") + " " + max_file_size_mb + "MB " + hrb.getString("exceeded2"));
    } else if (singleFileUpload && (fileitem.getFileName() == null || fileitem.getFileName().length() == 0)) {
        // only if in the single file upload case, need to warn user to upload a local file
        addAlert(state, rb.getString("choosefile7"));
    } else if (fileitem.getFileName().length() > 0) {
        String filename = Validator.getFileName(fileitem.getFileName());
        InputStream fileContentStream = fileitem.getInputStream();
        String contentType = fileitem.getContentType();

        InputStreamReader reader = new InputStreamReader(fileContentStream);

        try {

            //check the InputStreamReader to see if the file is 0kb aka empty
            if (reader.ready() == false) {
                addAlert(state, rb.getFormattedMessage("attempty", new Object[] { filename }));
            } else if (fileContentStream != null) {
                // we just want the file name part - strip off any drive and path stuff
                String name = Validator.getFileName(filename);
                String resourceId = Validator.escapeResourceName(name);

                // make a set of properties to add for the new resource
                ResourcePropertiesEdit props = m_contentHostingService.newResourceProperties();
                props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
                props.addProperty(ResourceProperties.PROP_DESCRIPTION, filename);

                // make an attachment resource for this URL
                SecurityAdvisor sa = new SecurityAdvisor() {
                    public SecurityAdvice isAllowed(String userId, String function, String reference) {
                        //Needed to be able to add or modify their own
                        if (function.equals(m_contentHostingService.AUTH_RESOURCE_ADD)
                                || function.equals(m_contentHostingService.AUTH_RESOURCE_WRITE_OWN)) {
                            return SecurityAdvice.ALLOWED;
                        }
                        return SecurityAdvice.PASS;
                    }
                };
                try {
                    String siteId = ToolManager.getCurrentPlacement().getContext();

                    // add attachment
                    // put in a security advisor so we can create citationAdmin site without need
                    // of further permissions
                    m_securityService.pushAdvisor(sa);
                    ContentResource attachment = m_contentHostingService.addAttachmentResource(resourceId,
                            siteId, "Assignments", contentType, fileContentStream, props);

                    Site s = null;
                    try {
                        s = SiteService.getSite(siteId);
                    } catch (IdUnusedException iue) {
                        M_log.warn(this + ":doAttachUpload: Site not found!" + iue.getMessage());
                    }

                    // Check if the file is acceptable with the ContentReviewService
                    boolean blockedByCRS = false;
                    if (allowReviewService && contentReviewService != null
                            && contentReviewService.isSiteAcceptable(s)) {
                        String assignmentReference = (String) state
                                .getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
                        Assignment a = getAssignment(assignmentReference, "doAttachUpload", state);
                        if (a.getContent().getAllowReviewService()) {
                            if (!contentReviewService.isAcceptableContent(attachment)) {
                                addAlert(state,
                                        rb.getFormattedMessage("review.file.not.accepted",
                                                new Object[] { contentReviewService.getServiceName(),
                                                        getContentReviewAcceptedFileTypesMessage() }));
                                blockedByCRS = true;
                                // TODO: delete the file? Could we have done this check without creating it in the first place?
                            }
                        }
                    }

                    if (!blockedByCRS) {
                        try {
                            Reference ref = EntityManager
                                    .newReference(m_contentHostingService.getReference(attachment.getId()));
                            if (singleFileUpload && attachments.size() > 1) {
                                //SAK-26319   - the assignment type is 'single file upload' and the user has existing attachments, so they must be uploading a 'newSingleUploadedFile'   --bbailla2
                                state.setAttribute("newSingleUploadedFile", ref);
                            } else {
                                attachments.add(ref);
                            }
                        } catch (Exception ee) {
                            M_log.warn(this + "doAttachUpload cannot find reference for " + attachment.getId()
                                    + ee.getMessage());
                        }
                    }

                    state.setAttribute(ATTACHMENTS, attachments);
                } catch (PermissionException e) {
                    addAlert(state, rb.getString("notpermis4"));
                } catch (RuntimeException e) {
                    if (m_contentHostingService.ID_LENGTH_EXCEPTION.equals(e.getMessage())) {
                        // couldn't we just truncate the resource-id instead of rejecting the upload?
                        addAlert(state, rb.getFormattedMessage("alert.toolong", new String[] { name }));
                    } else {
                        M_log.debug(this + ".doAttachupload ***** Runtime Exception ***** " + e.getMessage());
                        addAlert(state, rb.getString("failed"));
                    }
                } catch (ServerOverloadException e) {
                    // disk full or no writing permission to disk
                    M_log.debug(this + ".doAttachupload ***** Disk IO Exception ***** " + e.getMessage());
                    addAlert(state, rb.getString("failed.diskio"));
                } catch (Exception ignore) {
                    // other exceptions should be caught earlier
                    M_log.debug(this + ".doAttachupload ***** Unknown Exception ***** " + ignore.getMessage());
                    addAlert(state, rb.getString("failed"));
                } finally {
                    m_securityService.popAdvisor(sa);
                }
            } else {
                addAlert(state, rb.getString("choosefile7"));
            }
        } catch (IOException e) {
            M_log.debug(this + ".doAttachupload ***** IOException ***** " + e.getMessage());
            addAlert(state, rb.getString("failed"));
        }
    }
}