Example usage for java.io BufferedReader mark

List of usage examples for java.io BufferedReader mark

Introduction

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

Prototype

public void mark(int readAheadLimit) throws IOException 

Source Link

Document

Marks the present position in the stream.

Usage

From source file:tufts.vue.action.ActionUtil.java

public static LWMap unmarshallMap(java.net.URL url, MapUnmarshalHandler handler) throws IOException {
    // We scan for lines at top of file that are comments.  If there are NO comment lines, the
    // file is of one of our original save formats that is not versioned, and that may need
    // special processing for the Resource class to Resource interface change over.  If there
    // are comments, the version instance of the string "@version(##)" will set the version ID
    // to ##, and we'll use the mapping appropriate for that version of the save file.

    if (DEBUG.CASTOR || DEBUG.IO) {
        Log.debug("unmarshallMap: " + Util.tags(url));
        //Util.printStackTrace("UM " + url);
    }/*w w w .ja  v a  2s . co m*/

    final BufferedReader reader = getMapReaderForURL(url, BOOTSTRAP_ENCODING, false).reader;

    String firstNonCommentLine;
    String versionID = null;
    boolean savedOnWindowsPlatform = false;
    boolean savedOnMacPlatform = false;
    String guessedEncoding = null;
    Mapping mapping = null;

    // We need to skip past the comments to position the reader at the <?xml line for
    // unmarshalling to start.  Also, we look at these comments to determine version of the
    // mapping to use, as well as if it's a pre VUE 1.5 (August 2006) save file, in which case
    // we must guess an encoding, and re-open the file using an InputStreamReader with the
    // proper encoding.

    String savingVersion = "unknown VUE version";

    for (;;) {
        reader.mark(2048); // a single comment line can't be longer than this...
        String line = reader.readLine();
        if (line == null) {
            Log.error("Unexpected end-of-stream in [" + url + "]");
            throw new java.io.IOException("end of stream in " + url);
        }
        if (DEBUG.CASTOR || DEBUG.IO)
            Log.debug("Scanning[" + line + "]");
        if (line.startsWith("<!--") == false) {
            // we should have juadst hit thie "<?xml ..." line -- done with comments
            firstNonCommentLine = line;
            break;
        }

        if (line.startsWith(VUE_COMMENT_START + " Saved")) {

            // The "saved on platform" comments were never expected to be used functionally
            // (only for debug), so determining if the save file was written on a Windows box
            // it's not 100% reliable: e.g., if a user somehow had the name "platform Windows",
            // we would mistake this "saved by" for a "saved on", but we're just going to take
            // this risk -- this is just a workaround backward compat hack because castor
            // wasn't naming the real encoding in it's XML output (turns out it was always
            // puting UTF-8), even if it was using the default Windows encoding of
            // Cp1252/windows-1252.

            //if (DEBUG.IO) System.out.println("scanning for Windows platform...");
            if (line.indexOf("platform Windows") > 0) {
                if (DEBUG.IO)
                    Log.debug(url + " was saved in the Windows environment");
                savedOnWindowsPlatform = true;
            } else if (line.indexOf("platform Mac") > 0) {
                if (DEBUG.IO)
                    Log.debug(url + " was saved in the Mac environment");
                savedOnMacPlatform = true;
            }
        } else if (line.startsWith(VUE_COMMENT_START + " Saving version")) {
            if (DEBUG.IO)
                Log.debug("Found saving version line: " + line);
            final int savingVersionIndex = line.indexOf("VUE");
            if (savingVersionIndex > 0) {
                savingVersion = line.substring(line.indexOf("VUE"), line.length());
                if (savingVersion.indexOf("-->") > 10)
                    savingVersion = savingVersion.substring(0, savingVersion.indexOf("-->"));
                savingVersion = savingVersion.trim();
            } else {
                Log.warn(url + ": unknown saving version XML comment [" + line + "]");
            }
            if (DEBUG.IO)
                Log.debug("Saving version: [" + savingVersion + "]");
        }

        // Scan the comment line for a version tag to base our mapping on:
        int idx;
        if ((idx = line.indexOf("@version(")) >= 0) {
            String s = line.substring(idx);
            //System.out.println("Found version start:" + s);
            int x = s.indexOf(')');
            if (x > 0) {
                versionID = s.substring(9, x);
                if (DEBUG.CASTOR || DEBUG.IO)
                    Log.debug(url + "; Found mapping version ID[" + versionID + "]");
                if (versionID.equals(XML_MAPPING_CURRENT_VERSION_ID)) {
                    mapping = getDefaultMapping();
                } else {
                    URL mappingURL = VueResources.getURL("mapping.lw.version_" + versionID);
                    if (mappingURL == null) {
                        Log.error("Failed to find mapping for version tag [" + versionID
                                + "], attempting default.");
                        mapping = getDefaultMapping();
                    } else {
                        mapping = getMapping(mappingURL);
                    }
                }
            }
        }
    }
    reader.close();

    if (firstNonCommentLine.startsWith("<?xml")) {
        // Check to see if we need to use a non-default input encoding.
        // NOTE: We make sure we only attempt guessedEncoding if the given encoding is
        // the default input encoding: otherwise assume we're here recursively,
        // after already guessing at an encoding (otherwise, we'll loop, and blow stack)
        if (DEBUG.IO)
            Log.debug("XML head [" + firstNonCommentLine + "]");

        if (firstNonCommentLine.indexOf("encoding=\"UTF-8\"") > 0) {

            boolean localEncoding = false;

            // If encoding is UTF-8, this a 2nd generation save file (mapping is
            // versioned, but not all US-ASCII encoding): the actual encoding is
            // unknown: make a guess as how to best handle it.  This is our rule: if
            // we're on the SAME platform as the save file, assuming the local
            // encoding (assume it's the same user, on the same machine, and the
            // current default system encoding is the same one that was active when
            // the file was originally saved).  If we're on a different platform,
            // assume a default encoding for that platform.

            if (Util.isWindowsPlatform()) {
                if (savedOnWindowsPlatform) {
                    localEncoding = true;
                } else if (savedOnMacPlatform)
                    guessedEncoding = DEFAULT_MAC_ENCODING;
                else
                    guessedEncoding = DEFAULT_WINDOWS_ENCODING;
            } else if (Util.isMacPlatform()) {
                if (savedOnMacPlatform)
                    localEncoding = true;
                else if (savedOnWindowsPlatform)
                    guessedEncoding = DEFAULT_WINDOWS_ENCODING;
                else
                    guessedEncoding = DEFAULT_MAC_ENCODING;
            }

            if (localEncoding)
                guessedEncoding = Util.getDefaultPlatformEncoding();

            Log.info(url + "; assuming " + (localEncoding ? "LOCAL " : "PLATFORM DEFAULT ") + "\'"
                    + guessedEncoding + "\' charset encoding");

            // Note: doing this is a real tradeoff amongst bugs: any old save file
            // that had fancy unicode characters in UTF, such as something in a
            // japanese charset, will be screwed by this, so we optimizing for what
            // we think is the most likely case.  if this becomes a real problem, we
            // could introduce a special convert dialog.  Also, pre US-ASCII save
            // files could have different strings in them saved in many DIFFERENT
            // charsets (e.g., japanese, UTF, etc), and it's complete luck as to
            // when those charsets would each be properly handled.

        }
    } else {
        Log.warn("Missing XML header in [" + firstNonCommentLine + "]");
    }

    boolean oldFormat = false;

    if (versionID == null && mapping == null) {
        oldFormat = true;
        Log.info(url + "; save file is of old pre-versioned type.");
        mapping = getMapping(XML_MAPPING_UNVERSIONED);
    }

    if (mapping == null)
        mapping = getDefaultMapping();

    final String encoding = guessedEncoding == null ? DEFAULT_INPUT_ENCODING : guessedEncoding;

    return unmarshallMap(url, mapping, encoding, oldFormat, savingVersion, handler);
}

From source file:net.gaast.giggity.Schedule.java

public void loadSchedule(String url_, Fetcher.Source source) throws IOException {
    url = url_;/*from   w  w  w  . j  a v a2  s.co m*/

    id = null;
    title = null;

    allItems = new TreeMap<String, Schedule.Item>();
    tents = new LinkedList<Schedule.Line>();
    trackMap = null; /* Only assign if we have track info. */
    languages = new HashSet<>();

    firstTime = null;
    lastTime = null;

    dayList = null;
    curDay = null;
    curDayEnd = null;
    dayChange = new Date();
    dayChange.setHours(6);

    fullyLoaded = false;
    showHidden = false;

    icon = null;
    links = null;

    String head;
    Fetcher f = null;
    BufferedReader in;

    try {
        f = app.fetch(url, source);
        f.setProgressHandler(progressHandler);
        in = f.getReader();
        char[] headc = new char[detectHeaderSize];

        /* Read the first KByte (but keep it buffered) to try to detect the format. */
        in.mark(detectHeaderSize);
        in.read(headc, 0, detectHeaderSize);
        in.reset();

        head = new String(headc).toLowerCase();
    } catch (Exception e) {
        if (f != null)
            f.cancel();

        Log.e("Schedule.loadSchedule", "Exception while downloading schedule: " + e);
        e.printStackTrace();
        throw new LoadException("Network I/O problem: " + e);
    }

    /* Yeah, I know this is ugly, and actually reasonably fragile. For now it
     * just seems somewhat more efficient than doing something smarter, and
     * I want to avoid doing XML-specific stuff here already. */
    try {
        if (head.contains("<icalendar") && head.contains("<vcalendar")) {
            loadXcal(in);
        } else if (head.contains("<schedule") && head.contains("<conference")) {
            loadPentabarf(in);
        } else if (head.contains("<schedule") && head.contains("<line")) {
            loadDeox(in);
        } else if (head.contains("begin:vcalendar")) {
            loadIcal(in);
        } else {
            Log.d("head", head);
            throw new LoadException(app.getString(R.string.format_unknown));
        }
    } catch (LoadException e) {
        f.cancel();
        throw e;
    }

    Log.d("load", "Schedule has " + languages.size() + " languages");

    f.keep();

    if (title == null)
        if (id != null)
            title = id;
        else
            title = url;

    if (id == null)
        id = hashify(url);

    if (allItems.size() == 0) {
        throw new LoadException(app.getString(R.string.schedule_empty));
    }

    db = app.getDb();
    db.setSchedule(this, url, f.getSource() == Fetcher.Source.ONLINE);
    String md_json = db.getMetadata();
    if (md_json != null) {
        addMetadata(md_json);
    }

    /* From now, changes should be marked to go back into the db. */
    fullyLoaded = true;
}

From source file:org.opendatakit.utilities.LocalizationUtils.java

private static synchronized void loadTranslations(String appName, String tableId) throws IOException {
    if (savedAppName != null && !savedAppName.equals(appName)) {
        clearTranslations();//from  w  w  w.j  a  va2 s  .co m
    }
    savedAppName = appName;
    TypeReference<HashMap<String, Object>> ref = new TypeReference<HashMap<String, Object>>() {
    };
    if (commonDefinitions == null) {
        File commonFile = new File(ODKFileUtils.getCommonDefinitionsFile(appName));
        if (commonFile.exists() && commonFile.isFile()) {
            InputStream stream = null;
            BufferedReader reader = null;
            String value;
            try {
                stream = new FileInputStream(commonFile);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
                } else {
                    reader = new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8));
                }
                int ch = reader.read();
                while (ch != -1 && ch != '{') {
                    ch = reader.read();
                }

                StringBuilder b = new StringBuilder();
                b.append((char) ch);
                ch = reader.read();
                while (ch != -1) {
                    b.append((char) ch);
                    ch = reader.read();
                }
                reader.close();
                stream.close();
                value = b.toString().trim();
                if (value.endsWith(";")) {
                    value = value.substring(0, value.length() - 1).trim();
                }

            } finally {
                if (reader != null) {
                    reader.close();
                } else if (stream != null) {
                    stream.close();
                }
            }

            try {
                commonDefinitions = ODKFileUtils.mapper.readValue(value, ref);
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
                throw new IllegalStateException("Unable to read commonDefinitions.js file");
            }
        }
    }

    if (tableId != null) {
        File tableFile = new File(ODKFileUtils.getTableSpecificDefinitionsFile(appName, tableId));
        if (!tableFile.exists()) {
            tableSpecificDefinitionsMap.remove(tableId);
        } else {
            // assume it is current if it exists
            if (tableSpecificDefinitionsMap.containsKey(tableId)) {
                return;
            }
            InputStream stream = null;
            BufferedReader reader = null;
            try {
                stream = new FileInputStream(tableFile);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
                } else {
                    reader = new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8));
                }
                reader.mark(1);
                int ch = reader.read();
                while (ch != -1 && ch != '{') {
                    reader.mark(1);
                    ch = reader.read();
                }
                reader.reset();
                Map<String, Object> tableSpecificTranslations = ODKFileUtils.mapper.readValue(reader, ref);
                if (tableSpecificTranslations != null) {
                    tableSpecificDefinitionsMap.put(tableId, tableSpecificTranslations);
                }
            } finally {
                if (reader != null) {
                    reader.close();
                } else if (stream != null) {
                    stream.close();
                }
            }
        }
    }
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.por.PORFileReader.java

private void decodeSec2(BufferedReader reader) throws IOException {
    dbgLog.fine("***** decodeSec2(): start *****");
    if (reader == null) {
        throw new IllegalArgumentException("decodeSec2: stream == null!");
    }//w w w . j a  v a  2  s .  c o  m

    // Because a 64-bit machine may not save the first 40
    // bytes of a POR file in a way as a 32-bit machine does,
    // the first 5 lines of a POR file is excluded from the read-back
    // file and the new 1st line contains the format mark "SPSSPORT"
    // somewhere in it.

    // mark the start position for the later rewind
    if (reader.markSupported()) {
        reader.mark(100000);
    }

    char[] sixthLineCharArray = new char[80];
    int nbytes_sixthLine = reader.read(sixthLineCharArray);

    String sixthLine = new String(sixthLineCharArray);
    dbgLog.info("sixthLineCharArray=" + Arrays.deepToString(ArrayUtils.toObject(sixthLineCharArray)));
    int signatureLocation = sixthLine.indexOf(POR_MARK);

    if (signatureLocation >= 0) {
        dbgLog.info("format signature was found at:" + signatureLocation);
    } else {
        dbgLog.severe("signature string was not found");
        throw new IOException("signature string was not found");
    }

    // rewind the position to the beginning
    reader.reset();

    // skip bytes up to the signature string
    long skippedBytes = reader.skip(signatureLocation);

    char[] sec2_leader = new char[POR_MARK.length()];
    int nbytes_sec2_leader = reader.read(sec2_leader);

    String leader_string = new String(sec2_leader);

    dbgLog.info("format signature [SPSSPORT] detected=" + leader_string);

    if (leader_string.equals("SPSSPORT")) {
        dbgLog.info("signature was correctly detected");

    } else {
        dbgLog.severe("the format signature is not found at the previously located column");
        throw new IOException("decodeSec2: failed to find the signature string");
    }

    int length_section_2 = LENGTH_SECTION_2;

    char[] Sec2_bytes = new char[length_section_2];

    int nbytes_sec2 = reader.read(Sec2_bytes);

    if (nbytes_sec2 == 0) {
        dbgLog.severe("decodeSec2: reading error");
        throw new IOException("decodeSec2: reading error");
    } else {
        dbgLog.fine("bytes read=" + nbytes_sec2);
    }

    String sec2 = new String(Sec2_bytes);
    dbgLog.fine("sec2[creation date/time]=" + sec2);

    // sec2
    //       0123456789012345678
    //       A8/YYYYMMDD6/HHMMSS
    // thus
    // section2 should has 3 elements

    String[] section2 = StringUtils.split(sec2, '/');

    dbgLog.fine("section2=" + StringUtils.join(section2, "|"));

    String fileCreationDate = null;
    String fileCreationTime = null;
    if ((section2.length == 3) && (section2[0].startsWith("A"))) {
        fileCreationDate = section2[1].substring(0, 7);
        fileCreationTime = section2[2];
    } else {
        dbgLog.severe("decodeSec2: file creation date/time were not correctly detected");
        throw new IOException("decodeSec2: file creation date/time were not correctly detected");
    }
    dbgLog.fine("fileCreationDate=" + fileCreationDate);
    dbgLog.fine("fileCreationTime=" + fileCreationTime);
    smd.getFileInformation().put("fileCreationDate", fileCreationDate);
    smd.getFileInformation().put("fileCreationTime", fileCreationTime);
    smd.getFileInformation().put("varFormat_schema", "SPSS");
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java

private void decodeSec2(BufferedReader reader) throws IOException {
    dbgLog.fine("decodeSec2(): start");
    if (reader == null) {
        throw new IllegalArgumentException("decodeSec2: stream == null!");
    }// w ww . j  ava  2  s.c  o m

    // Because a 64-bit machine may not save the first 40
    // bytes of a POR file in a way as a 32-bit machine does,
    // the first 5 lines of a POR file is excluded from the read-back
    // file and the new 1st line contains the format mark "SPSSPORT"
    // somewhere in it.

    // mark the start position for the later rewind
    if (reader.markSupported()) {
        reader.mark(100000);
    }

    char[] sixthLineCharArray = new char[80];
    int nbytes_sixthLine = reader.read(sixthLineCharArray);

    String sixthLine = new String(sixthLineCharArray);
    dbgLog.fine("sixthLineCharArray=" + Arrays.deepToString(ArrayUtils.toObject(sixthLineCharArray)));
    int signatureLocation = sixthLine.indexOf(POR_MARK);

    if (signatureLocation >= 0) {
        dbgLog.fine("format signature was found at:" + signatureLocation);
    } else {
        dbgLog.severe("signature string was not found");
        throw new IOException("signature string was not found");
    }

    // rewind the position to the beginning
    reader.reset();

    // skip bytes up to the signature string
    long skippedBytes = reader.skip(signatureLocation);

    char[] sec2_leader = new char[POR_MARK.length()];
    int nbytes_sec2_leader = reader.read(sec2_leader);

    String leader_string = new String(sec2_leader);

    dbgLog.fine("format signature [SPSSPORT] detected=" + leader_string);

    if (leader_string.equals("SPSSPORT")) {
        dbgLog.fine("signature was correctly detected");

    } else {
        dbgLog.severe("the format signature is not found at the previously located column");
        throw new IOException("decodeSec2: failed to find the signature string");
    }

    int length_section_2 = LENGTH_SECTION_2;

    char[] Sec2_bytes = new char[length_section_2];

    int nbytes_sec2 = reader.read(Sec2_bytes);

    if (nbytes_sec2 == 0) {
        dbgLog.severe("decodeSec2: reading error");
        throw new IOException("decodeSec2: reading error");
    } else {
        dbgLog.fine("bytes read=" + nbytes_sec2);
    }

    String sec2 = new String(Sec2_bytes);
    dbgLog.fine("sec2[creation date/time]=" + sec2);

    // sec2
    //       0123456789012345678
    //       A8/YYYYMMDD6/HHMMSS
    // thus
    // section2 should has 3 elements

    String[] section2 = StringUtils.split(sec2, '/');

    dbgLog.fine("section2=" + StringUtils.join(section2, "|"));

    String fileCreationDate = null;
    String fileCreationTime = null;
    if ((section2.length == 3) && (section2[0].startsWith("A"))) {
        fileCreationDate = section2[1].substring(0, 7);
        fileCreationTime = section2[2];
    } else {
        dbgLog.severe("decodeSec2: file creation date/time were not correctly detected");
        throw new IOException("decodeSec2: file creation date/time were not correctly detected");
    }
    dbgLog.fine("fileCreationDate=" + fileCreationDate);
    dbgLog.fine("fileCreationTime=" + fileCreationTime);
    ///smd.getFileInformation().put("fileCreationDate", fileCreationDate);
    ///smd.getFileInformation().put("fileCreationTime", fileCreationTime);
    ///smd.getFileInformation().put("varFormat_schema", "SPSS");
    dbgLog.fine("decodeSec2(): end");
}

From source file:org.apache.jmeter.save.CSVSaveService.java

/**
 * Reads from file and splits input into strings according to the delimiter,
 * taking note of quoted strings.//from   w w w.  jav a2s. co m
 * <p>
 * Handles DOS (CRLF), Unix (LF), and Mac (CR) line-endings equally.
 * <p>
 * A blank line - or a quoted blank line - both return an array containing
 * a single empty String.
 * @param infile
 *            input file - must support mark(1)
 * @param delim
 *            delimiter (e.g. comma)
 * @return array of strings, will be empty if there is no data, i.e. if the input is at EOF.
 * @throws IOException
 *             also for unexpected quote characters
 */
public static String[] csvReadFile(BufferedReader infile, char delim) throws IOException {
    int ch;
    ParserState state = ParserState.INITIAL;
    List<String> list = new ArrayList<>();
    CharArrayWriter baos = new CharArrayWriter(200);
    boolean push = false;
    while (-1 != (ch = infile.read())) {
        push = false;
        switch (state) {
        case INITIAL:
            if (ch == QUOTING_CHAR) {
                state = ParserState.QUOTED;
            } else if (isDelimOrEOL(delim, ch)) {
                push = true;
            } else {
                baos.write(ch);
                state = ParserState.PLAIN;
            }
            break;
        case PLAIN:
            if (ch == QUOTING_CHAR) {
                baos.write(ch);
                throw new IOException("Cannot have quote-char in plain field:[" + baos.toString() + "]");
            } else if (isDelimOrEOL(delim, ch)) {
                push = true;
                state = ParserState.INITIAL;
            } else {
                baos.write(ch);
            }
            break;
        case QUOTED:
            if (ch == QUOTING_CHAR) {
                state = ParserState.EMBEDDEDQUOTE;
            } else {
                baos.write(ch);
            }
            break;
        case EMBEDDEDQUOTE:
            if (ch == QUOTING_CHAR) {
                baos.write(QUOTING_CHAR); // doubled quote => quote
                state = ParserState.QUOTED;
            } else if (isDelimOrEOL(delim, ch)) {
                push = true;
                state = ParserState.INITIAL;
            } else {
                baos.write(QUOTING_CHAR);
                throw new IOException(
                        "Cannot have single quote-char in quoted field:[" + baos.toString() + "]");
            }
            break;
        default:
            throw new IllegalStateException("Unexpected state " + state);
        } // switch(state)
        if (push) {
            if (ch == '\r') {// Remove following \n if present
                infile.mark(1);
                if (infile.read() != '\n') {
                    infile.reset(); // did not find \n, put the character
                                    // back
                }
            }
            String s = baos.toString();
            list.add(s);
            baos.reset();
        }
        if ((ch == '\n' || ch == '\r') && state != ParserState.QUOTED) {
            break;
        }
    } // while not EOF
    if (ch == -1) {// EOF (or end of string) so collect any remaining data
        if (state == ParserState.QUOTED) {
            throw new IOException("Missing trailing quote-char in quoted field:[\"" + baos.toString() + "]");
        }
        // Do we have some data, or a trailing empty field?
        if (baos.size() > 0 // we have some data
                || push // we've started a field
                || state == ParserState.EMBEDDEDQUOTE // Just seen ""
        ) {
            list.add(baos.toString());
        }
    }
    return list.toArray(new String[list.size()]);
}

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/*from ww w.j  a  v a  2s.co  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.ut.biolab.medsavant.server.ontology.OBOParser.java

private OntologyTerm parseNextTerm(BufferedReader reader) throws IOException {

    String line;//from   w w w  . j av  a2s  .c om
    String id = null, name = null, description = null;
    List<String> altIDs = new ArrayList<String>();
    List<String> parentIDs = new ArrayList<String>();
    while ((line = reader.readLine()) != null) {
        if (line.startsWith("[")) {
            // We've hit the next term (or typedef).  Rewind to the beginning of the line.
            reader.reset();
            break;
        } else {
            lineNum++;
            if (line.length() > 0 && line.charAt(0) != '!') {
                int colonPos = line.indexOf(":");
                if (colonPos > 0) {
                    String key = line.substring(0, colonPos);
                    String value = line.substring(colonPos + 1);
                    int commentPos = indexOf(value, '!');
                    if (commentPos > 0) {
                        value = value.substring(0, commentPos);
                    }
                    value = value.trim();
                    if (key.equals("id")) {
                        id = value;
                    } else if (key.equals("alt_id")) {
                        altIDs.add(value);
                    } else if (key.equals("name")) {
                        name = value;
                    } else if (key.equals("def")) {
                        // Def consists of a quote-delimited string followed by some (ignored) reference material.
                        int quotePos = indexOf(value, '\"');
                        if (quotePos >= 0) {
                            value = value.substring(quotePos + 1);
                            quotePos = indexOf(value, '\"');
                            if (quotePos >= 0) {
                                value = value.substring(0, quotePos);
                                description = value.replace("\\", "");
                            }
                        }
                    } else if (key.equals("is_a")) {
                        parentIDs.add(value);
                    } else if (key.equals("is_obsolete") && value.equals("true")) {
                        return null;
                    }
                }
            }
            reader.mark(10); // So we can rewind if the line is the next [Term].
        }
    }
    return new OntologyTerm(ontology, id, name, description, altIDs.toArray(new String[0]),
            parentIDs.toArray(new String[0]));
}

From source file:com.zimbra.cs.util.ProxyConfOverride.java

public static void expandTemplate(File tFile, File wFile) throws ProxyConfException {
    BufferedReader r = null;
    BufferedWriter w = null;/*  w  ww  . ja  v  a 2s .c o m*/
    try {
        String tf = tFile.getAbsolutePath();
        String wf = wFile.getAbsolutePath();

        if (mDryRun) {
            mLog.info("Would expand template:" + tf + " to file:" + wf);
            return;
        }

        mLog.info("Expanding template:" + tf + " to file:" + wf);

        if (!tFile.exists()) {
            throw new ProxyConfException("Template file " + tf + " does not exist");
        }
        r = new BufferedReader(new FileReader(tf));
        w = new BufferedWriter(new FileWriter(wf));

        String line;

        //for the first line of template, check the custom header command
        r.mark(100); //assume the first line won't beyond 100
        line = r.readLine();

        //only for back compability
        if (line.equalsIgnoreCase("!{explode vhn_vip_ssl}")) {
            expandTemplateExplodeSSLConfigsForAllVhnsAndVIPs(r, w);
            return;
        }
        Matcher cmdMatcher = cmdPattern.matcher(line);
        if (cmdMatcher.matches()) {
            //the command is found
            String[] cmd_arg = cmdMatcher.group(2).split("[ \t]+", 2);
            //command selection can be extracted if more commands are introduced
            if (cmd_arg.length == 2 && cmd_arg[0].compareTo("explode") == 0) {

                if (!mGenConfPerVhn) { // explode only when GenConfPerVhn is enabled
                    return;
                }

                if (cmd_arg[1].startsWith("domain(") && cmd_arg[1].endsWith(")")) {
                    //extract the args in "domain(arg1, arg2, ...)
                    String arglist = cmd_arg[1].substring("domain(".length(), cmd_arg[1].length() - 1);
                    String[] args;
                    if (arglist.equals("")) {
                        args = new String[0];
                    } else {
                        args = arglist.split(",( |\t)*");
                    }
                    expandTemplateByExplodeDomain(r, w, args);
                } else {
                    throw new ProxyConfException("Illegal custom header command: " + cmdMatcher.group(2));
                }
            } else {
                throw new ProxyConfException("Illegal custom header command: " + cmdMatcher.group(2));
            }
        } else {
            r.reset(); //reset to read the first line
            expandTemplateSimple(r, w);
        }

    } catch (IOException ie) {
        throw new ProxyConfException("Cannot expand template file: " + ie.getMessage());

    } catch (SecurityException se) {
        throw new ProxyConfException("Cannot expand template: " + se.getMessage());
    } finally {
        try {
            if (w != null)
                w.close();
            if (r != null)
                r.close();
        } catch (IOException e) {
            throw new ProxyConfException("Cannot expand template file: " + e.getMessage());
        }
    }
}

From source file:com.photon.phresco.framework.actions.applications.Build.java

public String readLogFile(Project project, String fromNodejs) {
    StringBuilder builder = new StringBuilder(Utility.getProjectHome());
    builder.append(project.getProjectInfo().getCode());
    builder.append(File.separator);
    builder.append(DO_NOT_CHECKIN_DIR);//from  w  w  w  .ja  va  2s.co m
    builder.append(File.separator);
    builder.append(NODEJS_LOG_DIR);
    builder.append(File.separator);
    builder.append(NODEJS_LOG_FILE);
    BufferedReader reader = null;
    StringBuffer contents = new StringBuffer();
    try {
        File file = new File(builder.toString());
        // It executed when file not exist and view method called
        if (!file.exists() && fromNodejs.equals(READ_LOG_VIEW)) {
            return "";
        }
        // It executed when file exist and view method called
        if (file.exists() && fromNodejs.equals(READ_LOG_VIEW)) {
            reader = new BufferedReader(new FileReader(file));
            String text = null;
            while ((text = reader.readLine()) != null) {
                contents.append(text).append(System.getProperty(LINE_SEPERATOR));
            }
            return contents.toString();
        }
        // It executed when file not exist and return reader
        if (!file.exists()) {
            StringReader sb = new StringReader("Server started successfully...");
            reader = new BufferedReader(sb);
            // getHttpSession().setAttribute(REQ_READER, reader);
            getHttpSession().setAttribute(projectCode + REQ_READ_LOG_FILE, reader);
            getHttpRequest().setAttribute(REQ_PROJECT_CODE, projectCode);
            getHttpRequest().setAttribute(REQ_TEST_TYPE, REQ_READ_LOG_FILE);
        }
        // It executed when file existence and return reader
        if (file.exists()) {
            waitForTime(2);
            reader = new BufferedReader(new FileReader(file));
            // getHttpSession().setAttribute(REQ_READER, reader);
            @SuppressWarnings("unused")
            String line = null;
            if (reader.markSupported()) {
                reader.mark(1);
                if ((line = reader.readLine()) == null) {
                    reader = new BufferedReader(new StringReader("Server started successfully..."));
                } else {
                    reader.reset();
                }
            }

            getHttpSession().setAttribute(projectCode + REQ_READ_LOG_FILE, reader);
            getHttpRequest().setAttribute(REQ_PROJECT_CODE, projectCode);
            getHttpRequest().setAttribute(REQ_TEST_TYPE, REQ_READ_LOG_FILE);
        }

    } catch (FileNotFoundException e) {
        if (debugEnabled) {
            S_LOGGER.error(
                    "Entered into catch block of Build.readLogFile()" + FrameworkUtil.getStackTraceAsString(e));
        }
    } catch (IOException e) {
        if (debugEnabled) {
            S_LOGGER.error(
                    "Entered into catch block of Build.readLogFile()" + FrameworkUtil.getStackTraceAsString(e));
        }
    }
    return null;
}