Example usage for java.io LineNumberReader LineNumberReader

List of usage examples for java.io LineNumberReader LineNumberReader

Introduction

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

Prototype

public LineNumberReader(Reader in) 

Source Link

Document

Create a new line-numbering reader, using the default input-buffer size.

Usage

From source file:org.kawanfw.sql.jdbc.util.ColPositionBuilder.java

/**
 * /*from w w w .j a  v a  2  s .  co  m*/
 * Constructor
 * 
 * @param file
 *            the file that contains the positions of the columns
 * @param connectionHttp
 *            TODO
 */
public ColPositionBuilder(File file, ConnectionHttp connectionHttp) throws SQLException {
    if (!file.exists()) {
        String message = Tag.PRODUCT_PRODUCT_FAIL + "Internal File does not exists: " + file;
        throw new SQLException(message, new IOException(message));
    }

    String line = null;
    LineNumberReader lineNumberReader = null;

    try {
        lineNumberReader = new LineNumberReader(new FileReader(file));
        line = lineNumberReader.readLine();
    } catch (FileNotFoundException e) {
        String message = Tag.PRODUCT_PRODUCT_FAIL + "Internal File does not exists: " + file;
        throw new SQLException(message, new IOException(message));
    } catch (IOException e) {
        String message = Tag.PRODUCT_PRODUCT_FAIL + "I/O Error when reading file: " + file;
        throw new SQLException(message, new IOException(message));
    } finally {
        IOUtils.closeQuietly(lineNumberReader);
    }

    if (line == null) {
        String message = Tag.PRODUCT_PRODUCT_FAIL + "Internal File is empty: " + file;
        throw new SQLException(message, new IOException(message));
    }

    line = JsonLineDecryptor.decrypt(line, connectionHttp);

    if (DEBUG) {
        try {
            String fileContent = FileUtils.readFileToString(file);
            debug("fileContent: " + fileContent);
        } catch (IOException e) {
            throw new SQLException(e);
        }
    }

    columnsPosition = JsonColPosition.fromJson(line);
}

From source file:ch.cyberduck.core.i18n.RegexLocale.java

private void load(final String table, final File file) throws IOException {
    final LineNumberReader reader = new LineNumberReader(
            new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-16")));
    try {/*from www  .  j a  v  a 2  s.  c om*/
        String line;
        while ((line = reader.readLine()) != null) {
            final Matcher matcher = pattern.matcher(line);
            if (matcher.matches()) {
                cache.put(new Key(table, matcher.group(1)), matcher.group(2));
            }
        }
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:name.martingeisse.ecobuild.moduletool.output.OutputTool.java

@Override
public void execute(IModuleToolContext context) throws IOException {
    FileReader buildScriptReader;
    try {/*w w w . jav  a  2 s .  co m*/
        buildScriptReader = new FileReader(new File(context.getModuleSourceFolder(), "build.txt"));
    } catch (FileNotFoundException e) {
        throw new UserMessageBuildException(
                "Output build script 'build.txt' not found for module " + context.getModuleSourceFolder());
    }
    LineNumberReader lineReader = new LineNumberReader(buildScriptReader);
    State state = new State();
    state.currentFolder = context.getMainBuildFolder();
    state.folderStack = new Stack<File>();
    while (true) {
        String line = lineReader.readLine();
        if (line == null) {
            break;
        }
        handleLine(context, state, line);
    }
    buildScriptReader.close();
}

From source file:org.epics.archiverappliance.mgmt.bpl.UploadChannelArchiverConfigAction.java

@Override
public void execute(HttpServletRequest req, HttpServletResponse resp, ConfigService configService)
        throws IOException {

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart) {
        throw new IOException("HTTP request is not sending multipart content; therefore we cannnot process");
    }//  www  .  j  a v  a2 s . c  om

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    List<String> fieldsAsPartOfStream = ArchivePVAction.getFieldsAsPartOfStream(configService);
    try (PrintWriter out = new PrintWriter(new NullOutputStream())) {
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                logger.debug("Form field " + name + " detected.");
            } else {
                logger.debug("File field " + name + " with file name " + item.getName() + " detected.");
                try (InputStream is = new BufferedInputStream(item.openStream())) {
                    is.mark(1024);
                    logger.info((new LineNumberReader(new InputStreamReader(is))).readLine());
                    is.reset();
                    LinkedList<PVConfig> pvConfigs = EngineConfigParser.importEngineConfig(is);
                    for (PVConfig pvConfig : pvConfigs) {
                        boolean scan = !pvConfig.isMonitor();
                        float samplingPeriod = pvConfig.getPeriod();
                        if (logger.isDebugEnabled())
                            logger.debug("Adding " + pvConfig.getPVName() + " using "
                                    + (scan ? SamplingMethod.SCAN : SamplingMethod.MONITOR)
                                    + " and a period of " + samplingPeriod);
                        ArchivePVAction.archivePV(out, pvConfig.getPVName(), true,
                                scan ? SamplingMethod.SCAN : SamplingMethod.MONITOR, samplingPeriod, null, null,
                                null, false, configService, fieldsAsPartOfStream);
                    }
                } catch (Exception ex) {
                    logger.error("Error importing configuration", ex);
                    resp.sendRedirect("../ui/integration.html?message=Error importing config file "
                            + item.getName() + " " + ex.getMessage());
                    return;
                }
            }
        }
        resp.sendRedirect("../ui/integration.html?message=Successfully imported configuration files");
    } catch (FileUploadException ex) {
        throw new IOException(ex);
    }

}

From source file:org.kse.utilities.pem.PemUtil.java

/**
 * Decode the PEM included in the supplied input stream.
 *
 * @param is//from w w w.j  av  a2 s.c  o  m
 *            Input stream
 * @return PEM information or null if stream does not contain PEM
 * @throws IOException
 *             If an I/O problem occurs
 */
public static PemInfo decode(InputStream is) throws IOException {
    byte[] streamContents = ReadUtil.readFully(is);

    LineNumberReader lnr = null;

    try {
        lnr = new LineNumberReader(new InputStreamReader(new ByteArrayInputStream(streamContents)));

        String line = lnr.readLine();
        StringBuffer sbBase64 = new StringBuffer();

        if (line != null) {
            line = line.trim();
            String headerType = getTypeFromHeader(line);

            if (headerType != null) {
                line = lnr.readLine();

                PemAttributes attributes = null;

                // Read any header attributes
                if (line != null && line.contains(": ")) {
                    line = line.trim();

                    attributes = new PemAttributes();

                    while (line != null) {
                        line = line.trim();

                        // Empty line - end of attributes
                        if (line.equals("")) {
                            line = lnr.readLine();
                            break;
                        }

                        // Run out of attributes before blank line - not PEM
                        if (!line.contains(": ")) {
                            return null;
                        }

                        // Parse attribute from line
                        int separator = line.indexOf(':');

                        String attributeName = line.substring(0, separator);
                        String attributeValue = line.substring(separator + 2);

                        attributes.add(new PemAttribute(attributeName, attributeValue));

                        line = lnr.readLine();
                    }
                }

                // Read content
                while (line != null) {
                    line = line.trim();
                    String footerType = getTypeFromFooter(line);

                    if (footerType == null) {
                        sbBase64.append(line);
                    } else {
                        // Header and footer types do not match - not PEM
                        if (!headerType.equals(footerType)) {
                            return null;
                        } else {
                            // Decode base 64 content
                            byte[] content = Base64.decode(sbBase64.toString());

                            return new PemInfo(headerType, attributes, content);
                        }
                    }

                    line = lnr.readLine();
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(lnr);
    }

    return null; // Not PEM
}

From source file:edu.stanford.muse.index.NEROld.java

public static void readLocationsWG() {
    try {/*from w ww.  j  a va  2  s . c om*/
        InputStream is = new GZIPInputStream(
                NER.class.getClassLoader().getResourceAsStream("WG.locations.txt.gz"));
        LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is, "UTF-8"));
        while (true) {
            String line = lnr.readLine();
            if (line == null)
                break;
            StringTokenizer st = new StringTokenizer(line, "\t");
            if (st.countTokens() == 4) {
                String locationName = st.nextToken();
                String canonicalName = locationName.toLowerCase();
                if (locationsToSuppress.contains(canonicalName))
                    continue;
                String lat = st.nextToken();
                String longi = st.nextToken();
                String pop = st.nextToken();
                long popl = Long.parseLong(pop);
                float latf = ((float) Integer.parseInt(lat)) / 100.0f;
                float longif = ((float) Integer.parseInt(longi)) / 100.0f;
                Long existingPop = populations.get(canonicalName);
                if (existingPop == null || popl > existingPop) {
                    populations.put(canonicalName, popl);
                    locations.put(canonicalName,
                            new LocationInfo(locationName, Float.toString(latf), Float.toString(longif)));
                }
            }
        }
    } catch (Exception e) {
        log.warn("Unable to read World Gazetteer file, places info may be inaccurate");
        log.debug(Util.stackTrace(e));
    }
}

From source file:net.sf.keystore_explorer.utilities.pem.PemUtil.java

/**
 * Decode the PEM included in the supplied input stream.
 *
 * @param is/*ww w . java  2  s.co  m*/
 *            Input stream
 * @return PEM information or null if stream does not contain PEM
 * @throws IOException
 *             If an I/O problem occurs
 */
public static PemInfo decode(InputStream is) throws IOException {
    byte[] streamContents = ReadUtil.readFully(is);

    LineNumberReader lnr = null;

    try {
        lnr = new LineNumberReader(new InputStreamReader(new ByteArrayInputStream(streamContents)));

        String line = lnr.readLine();
        StringBuffer sbBase64 = new StringBuffer();

        if (line != null) {
            line = line.trim();
            String headerType = getTypeFromHeader(line);

            if (headerType != null) {
                line = lnr.readLine();

                PemAttributes attributes = null;

                // Read any header attributes
                if (line != null && line.contains(": ")) {
                    line = line.trim();

                    attributes = new PemAttributes();

                    attributesDone: while (line != null) {
                        line = line.trim();

                        // Empty line - end of attributes
                        if (line.equals("")) {
                            line = lnr.readLine();
                            break;
                        }

                        // Run out of attributes before blank line - not PEM
                        if (!line.contains(": ")) {
                            return null;
                        }

                        // Parse attribute from line
                        int separator = line.indexOf(':');

                        String attributeName = line.substring(0, separator);
                        String attributeValue = line.substring(separator + 2);

                        attributes.add(new PemAttribute(attributeName, attributeValue));

                        line = lnr.readLine();
                    }
                }

                // Read content
                while (line != null) {
                    line = line.trim();
                    String footerType = getTypeFromFooter(line);

                    if (footerType == null) {
                        sbBase64.append(line);
                    } else {
                        // Header and footer types do not match - not PEM
                        if (!headerType.equals(footerType)) {
                            return null;
                        } else {
                            // Decode base 64 content
                            byte[] content = Base64.decode(sbBase64.toString());

                            return new PemInfo(headerType, attributes, content);
                        }
                    }

                    line = lnr.readLine();
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(lnr);
    }

    return null; // Not PEM
}

From source file:org.kalypso.model.wspm.core.imports.ImportTrippleHelper.java

/**
 * Imports the profile trippel data and converts it into IProfils
 * //from   ww  w .j a  va2 s .co  m
 * @param trippleFile
 *          file with profile tripples
 */
public static IProfile[] importTrippelData(final File trippleFile, final String separator,
        final String profileType, final String crs) throws CoreException {
    final IProfilePointPropertyProvider provider = KalypsoModelWspmCoreExtensions
            .getPointPropertyProviders(profileType);

    final IComponent rechtswert = provider.getPointProperty(IWspmPointProperties.POINT_PROPERTY_RECHTSWERT);
    final IComponent hochwert = provider.getPointProperty(IWspmPointProperties.POINT_PROPERTY_HOCHWERT);

    if (trippleFile == null)
        return new IProfile[0];

    /* read profiles, show warnings */
    final List<IProfile> profiles = new ArrayList<>();
    IProfile currentProfile = null;

    /* file loading */
    LineNumberReader fileReader = null;

    try (InputStreamReader inputReader = new InputStreamReader(new FileInputStream(trippleFile))) {
        fileReader = new LineNumberReader(inputReader);

        /* File Header */
        fileReader.readLine();

        IProfileRecord lastPoint = null;
        while (fileReader.ready()) {
            final String line = fileReader.readLine();
            if (line == null) {
                break;
            }

            /* ignore empty lines */
            if (StringUtils.isBlank(line)) {
                continue;
            }

            /* trippel-format should be: station, x, y, z */
            final String[] tokens = StringUtils.split(line, separator);

            /* continue just if there are enough values in the trippel file */
            if (tokens.length != 4) {
                // FIXME: better error handling
                // inform the user that his profile has not enough values...
                final String message = Messages.getString(
                        "org.kalypso.model.wspm.core.imports.ImportTrippleHelper.0", //$NON-NLS-1$
                        fileReader.getLineNumber());
                final IStatus status = new Status(IStatus.ERROR, KalypsoModelWspmCorePlugin.getID(), message);
                throw new CoreException(status);
            }

            try {
                /* first value = profile station */
                final double station = NumberUtils.parseDouble(tokens[0]);
                final BigDecimal currentStation = ProfileUtil.stationToBigDecimal(station);

                final BigDecimal currentProfileStation = currentProfile == null ? null
                        : ProfileUtil.stationToBigDecimal(currentProfile.getStation());

                if (!ObjectUtils.equals(currentStation, currentProfileStation)) {
                    lastPoint = null;

                    currentProfile = ProfileFactory.createProfil(profileType, null);

                    currentProfile.setStation(station);
                    currentProfile.setName(
                            Messages.getString("org.kalypso.model.wspm.core.imports.ImportTrippleHelper.1")); //$NON-NLS-1$
                    currentProfile.setDescription(
                            Messages.getString("org.kalypso.model.wspm.core.imports.ImportTrippleHelper.2")); //$NON-NLS-1$
                    currentProfile.setSrsName(crs);

                    currentProfile.addPointProperty(rechtswert);
                    currentProfile.addPointProperty(hochwert);

                    profiles.add(currentProfile);
                }

                final IProfileRecord point = ImportTrippleHelper.createProfilePoint(currentProfile, tokens,
                        lastPoint);
                if (point != null) {
                    currentProfile.addPoint(point);
                }

                lastPoint = point;
            } catch (final NumberFormatException e) {
                e.printStackTrace();
                final String message = Messages.getString(
                        "org.kalypso.model.wspm.core.imports.ImportTrippleHelper.3", //$NON-NLS-1$
                        fileReader.getLineNumber());
                final IStatus status = new Status(IStatus.ERROR, KalypsoModelWspmCorePlugin.getID(), message,
                        e);
                throw new CoreException(status);
            }
        }

        fileReader.close();
    } catch (final IOException e) {
        e.printStackTrace();

        final int lineNumber = fileReader == null ? 0 : fileReader.getLineNumber();

        final String message = Messages.getString("org.kalypso.model.wspm.core.imports.ImportTrippleHelper.4", //$NON-NLS-1$
                lineNumber);
        final IStatus status = new Status(IStatus.ERROR, KalypsoModelWspmCorePlugin.getID(), message, e);
        throw new CoreException(status);
    }

    return profiles.toArray(new IProfile[profiles.size()]);
}

From source file:info.magnolia.cms.module.ModuleUtil.java

/**
 * registers the properties in the repository
 * @param hm//from ww w . jav a  2s  . c om
 * @param name
 * @throws IOException
 * @throws RepositoryException
 * @throws PathNotFoundException
 * @throws AccessDeniedException
 */
public static void registerProperties(HierarchyManager hm, String name)
        throws IOException, AccessDeniedException, PathNotFoundException, RepositoryException {
    Map map = new ListOrderedMap();

    // not using properties since they are not ordered
    // Properties props = new Properties();
    // props.load(ModuleUtil.class.getResourceAsStream("/" + name.replace('.', '/') + ".properties"));
    InputStream stream = ModuleUtil.class.getResourceAsStream("/" + name.replace('.', '/') + ".properties"); //$NON-NLS-1$ //$NON-NLS-2$
    LineNumberReader lines = new LineNumberReader(new InputStreamReader(stream));

    String line = lines.readLine();
    while (line != null) {
        line = line.trim();
        if (line.length() > 0 && !line.startsWith("#")) { //$NON-NLS-1$
            String key = StringUtils.substringBefore(line, "=").trim(); //$NON-NLS-1$
            String value = StringUtils.substringAfter(line, "=").trim(); //$NON-NLS-1$
            map.put(key, value);
        }
        line = lines.readLine();
    }
    IOUtils.closeQuietly(lines);
    IOUtils.closeQuietly(stream);
    registerProperties(hm, map);
}

From source file:org.kawanfw.sql.jdbc.util.FileBackedList.java

/**
 * Constructor//ww  w. j  a  v  a 2s. com
 * 
 * @param fileIn
 *            the file to read as a list of lines
 */
public FileBackedList(File fileIn) throws SQLException {

    if (fileIn == null) {
        throw new IllegalArgumentException("fileIn can not be null!");
    }

    if (!fileIn.exists()) {
        String message = Tag.PRODUCT_PRODUCT_FAIL + "Internal File does not exists: " + file;
        throw new SQLException(message, new IOException(message));
    }

    try {
        this.file = fileIn;
        lineNumberReader = new LineNumberReader(new FileReader(file));

        // Call size to initialize size field:
        this.size();

    } catch (FileNotFoundException e) {
        String message = Tag.PRODUCT_PRODUCT_FAIL + "Internal File does not exists: " + file;
        throw new SQLException(message, new IOException(message));
    }

}