Search in sources :

Example 61 with LineNumberReader

use of java.io.LineNumberReader in project intellij-plugins by JetBrains.

the class DebugCLI method main.

public static void main(String[] args) {
    DebugCLI cli = new DebugCLI();
    /* attach our 'main' input method and out/err*/
    cli.m_err = System.err;
    cli.m_out = System.out;
    // get the default <application.home>/projects/frameworks/*/src entries into the source path
    cli.initSourceDirectoriesList();
    // a big of wrangling for our keyboard input stream since its special
    cli.m_keyboardStream = new LineNumberReader(new InputStreamReader(System.in));
    cli.pushStream(cli.m_keyboardStream);
    /* iterate through the args list */
    cli.processArgs(args);
    /* figure out $HOME and the current directory */
    //$NON-NLS-1$
    String userHome = System.getProperty("user.home");
    //$NON-NLS-1$
    String userDir = System.getProperty("user.dir");
    /*
		 * If the current directory is not $HOME, and a .fdbinit file exists in the current directory,
		 * then push it onto the stack of files to read.
		 * 
		 * Note, we want ./.fdbinit to be read AFTER $HOME/.fdbinit, but we push them in reverse
		 * order, because they're going onto a stack.  If we push them in reverse order, then they
		 * will be read in the correct order (last one pushed is the first one read).
		 */
    if (userDir != null && !userDir.equals(userHome)) {
        try {
            //$NON-NLS-1$
            FileReader sr = new FileReader(new File(userDir, ".fdbinit"));
            cli.pushStream(new LineNumberReader(sr));
        } catch (FileNotFoundException fnf) {
        }
    }
    /*
		 * If a .fdbinit file exists in the $HOME directory, then push it onto the stack of files
		 * to read.
		 * 
		 * Note, we want ./.fdbinit to be read AFTER $HOME/.fdbinit, but we push them in reverse
		 * order, because they're going onto a stack.  If we push them in reverse order, then they
		 * will be read in the correct order (last one pushed is the first one read).
		 */
    if (userHome != null) {
        try {
            //$NON-NLS-1$
            FileReader sr = new FileReader(new File(userHome, ".fdbinit"));
            cli.pushStream(new LineNumberReader(sr));
        } catch (FileNotFoundException fnf) {
        }
    }
    cli.execute();
}
Also used : InputStreamReader(java.io.InputStreamReader) FileNotFoundException(java.io.FileNotFoundException) FileReader(java.io.FileReader) File(java.io.File) SourceFile(flash.tools.debugger.SourceFile) LineNumberReader(java.io.LineNumberReader)

Example 62 with LineNumberReader

use of java.io.LineNumberReader in project sling by apache.

the class ModelResolveUtility method getProcessedConfiguration.

/**
     * Replaces variables in configuration.
     * @param feature Feature
     * @param newConfig New configuration with replaced variables
     * @param config Source configuration which may contain variable placeholders
     * @param replaceVariables If set to true variables are resolved in the config before processing it.
     * @param resolver Variable resolver Optional variable resolver which is used. If not given only the feature's variables are used.
     */
static void getProcessedConfiguration(final Feature feature, final Configuration newConfig, final Configuration config, final boolean replaceVariables, final VariableResolver resolver) {
    newConfig.setComment(config.getComment());
    newConfig.setLocation(config.getLocation());
    // check for raw configuration
    String rawConfig = (String) config.getProperties().get(ModelConstants.CFG_UNPROCESSED);
    if (rawConfig != null) {
        if (replaceVariables) {
            rawConfig = replace(feature, rawConfig, resolver);
        }
        if (config.isSpecial()) {
            newConfig.getProperties().put(config.getPid(), rawConfig);
        } else {
            final String format = (String) config.getProperties().get(ModelConstants.CFG_UNPROCESSED_FORMAT);
            if (ModelConstants.CFG_FORMAT_PROPERTIES.equals(format)) {
                // properties
                final Properties props = new Properties();
                try {
                    props.load(new StringReader(rawConfig));
                } catch (final IOException ioe) {
                    throw new IllegalArgumentException("Unable to read configuration properties.", ioe);
                }
                final Enumeration<Object> i = props.keys();
                while (i.hasMoreElements()) {
                    final String key = (String) i.nextElement();
                    newConfig.getProperties().put(key, props.get(key));
                }
            } else {
                // Apache Felix CA format
                // the raw format might have comments, we have to remove them first
                final StringBuilder sb = new StringBuilder();
                try {
                    final LineNumberReader lnr = new LineNumberReader(new StringReader(rawConfig));
                    String line = null;
                    while ((line = lnr.readLine()) != null) {
                        line = line.trim();
                        if (line.isEmpty() || line.startsWith("#")) {
                            continue;
                        }
                        sb.append(line);
                        sb.append('\n');
                    }
                } catch (final IOException ioe) {
                    throw new IllegalArgumentException("Unable to read configuration properties: " + config, ioe);
                }
                ByteArrayInputStream bais = null;
                try {
                    bais = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
                    @SuppressWarnings("unchecked") final Dictionary<String, Object> props = ConfigurationHandler.read(bais);
                    final Enumeration<String> i = props.keys();
                    while (i.hasMoreElements()) {
                        final String key = i.nextElement();
                        newConfig.getProperties().put(key, props.get(key));
                    }
                } catch (final IOException ioe) {
                    throw new IllegalArgumentException("Unable to read configuration properties: " + config, ioe);
                } finally {
                    if (bais != null) {
                        try {
                            bais.close();
                        } catch (final IOException ignore) {
                        // ignore
                        }
                    }
                }
            }
        }
    } else {
        // simply copy
        final Enumeration<String> i = config.getProperties().keys();
        while (i.hasMoreElements()) {
            final String key = i.nextElement();
            newConfig.getProperties().put(key, config.getProperties().get(key));
        }
    }
}
Also used : IOException(java.io.IOException) Properties(java.util.Properties) LineNumberReader(java.io.LineNumberReader) ByteArrayInputStream(java.io.ByteArrayInputStream) StringReader(java.io.StringReader)

Example 63 with LineNumberReader

use of java.io.LineNumberReader in project sling by apache.

the class ModelWriter method write.

/**
     * Writes the model to the writer.
     * The writer is not closed.
     * @param writer Writer
     * @param model Model
     * @throws IOException
     */
public static void write(final Writer writer, final Model model) throws IOException {
    final PrintWriter pw = new PrintWriter(writer);
    boolean firstFeature = true;
    // features
    for (final Feature feature : model.getFeatures()) {
        if (firstFeature) {
            firstFeature = false;
        } else {
            pw.println();
        }
        writeComment(pw, feature);
        pw.print("[feature name=");
        pw.print(feature.getName());
        if (!FeatureTypes.PLAIN.equals(feature.getType())) {
            pw.print(" type=");
            pw.print(feature.getType());
        }
        if (feature.getVersion() != null) {
            pw.print(" version=");
            pw.print(feature.getVersion());
        }
        pw.println("]");
        // variables
        if (!feature.getVariables().isEmpty()) {
            pw.println();
            writeComment(pw, feature.getVariables());
            pw.println("[variables]");
            for (final Map.Entry<String, String> entry : feature.getVariables()) {
                pw.print("  ");
                pw.print(entry.getKey());
                pw.print("=");
                pw.println(entry.getValue());
            }
        }
        // run modes
        for (final RunMode runMode : feature.getRunModes()) {
            // settings
            if (!runMode.getSettings().isEmpty()) {
                pw.println();
                writeComment(pw, runMode.getSettings());
                pw.print("[settings");
                writeRunMode(pw, runMode);
                pw.println("]");
                for (final Map.Entry<String, String> entry : runMode.getSettings()) {
                    pw.print("  ");
                    pw.print(entry.getKey());
                    pw.print("=");
                    pw.println(entry.getValue());
                }
            }
            // artifact groups
            for (final ArtifactGroup group : runMode.getArtifactGroups()) {
                // skip empty groups
                if (group.isEmpty()) {
                    continue;
                }
                pw.println();
                writeComment(pw, group);
                pw.print("[artifacts");
                if (group.getStartLevel() > 0) {
                    pw.print(" startLevel=");
                    pw.print(String.valueOf(group.getStartLevel()));
                }
                writeRunMode(pw, runMode);
                pw.println("]");
                // artifacts
                for (final Artifact ad : group) {
                    writeComment(pw, ad);
                    pw.print("  ");
                    pw.print(ad.toMvnUrl().substring(4));
                    if (!ad.getMetadata().isEmpty()) {
                        boolean first = true;
                        for (final Map.Entry<String, String> entry : ad.getMetadata().entrySet()) {
                            if (first) {
                                first = false;
                                pw.print(" [");
                            } else {
                                pw.print(", ");
                            }
                            pw.print(entry.getKey());
                            pw.print("=");
                            pw.print(entry.getValue());
                        }
                        pw.print("]");
                    }
                    pw.println();
                }
            }
            // configurations
            if (!runMode.getConfigurations().isEmpty()) {
                pw.println();
                writeComment(pw, runMode.getConfigurations());
                pw.print("[configurations");
                writeRunMode(pw, runMode);
                pw.println("]");
                boolean firstConfig = true;
                for (final Configuration config : runMode.getConfigurations()) {
                    if (firstConfig) {
                        firstConfig = false;
                    } else {
                        pw.println();
                    }
                    writeComment(pw, config);
                    final String raw = (String) config.getProperties().get(ModelConstants.CFG_UNPROCESSED);
                    String format = (String) config.getProperties().get(ModelConstants.CFG_UNPROCESSED_FORMAT);
                    if (format == null) {
                        format = ModelConstants.CFG_FORMAT_FELIX_CA;
                    }
                    String cfgMode = (String) config.getProperties().get(ModelConstants.CFG_UNPROCESSED_MODE);
                    if (cfgMode == null) {
                        cfgMode = ModelConstants.CFG_MODE_OVERWRITE;
                    }
                    pw.print("  ");
                    if (config.getFactoryPid() != null) {
                        pw.print(config.getFactoryPid());
                        pw.print("-");
                    }
                    pw.print(config.getPid());
                    final boolean isDefaultFormat = ModelConstants.CFG_FORMAT_FELIX_CA.equals(format);
                    final boolean isDefaultMode = ModelConstants.CFG_MODE_OVERWRITE.equals(cfgMode);
                    if (!isDefaultFormat || !isDefaultMode) {
                        pw.print(" [");
                        if (!isDefaultFormat) {
                            pw.print("format=");
                            pw.print(format);
                            if (!isDefaultMode) {
                                pw.print(",");
                            }
                        }
                        if (!isDefaultMode) {
                            pw.print("mode=");
                            pw.print(cfgMode);
                        }
                        pw.print("]");
                    }
                    pw.println();
                    final String configString;
                    if (raw != null) {
                        configString = raw;
                    } else if (config.isSpecial()) {
                        configString = config.getProperties().get(config.getPid()).toString();
                    } else {
                        final ByteArrayOutputStream os = new ByteArrayOutputStream();
                        try {
                            ConfigurationHandler.write(os, config.getProperties());
                        } finally {
                            os.close();
                        }
                        configString = new String(os.toByteArray(), "UTF-8");
                    }
                    // we have to read the configuration line by line to properly indent
                    final LineNumberReader lnr = new LineNumberReader(new StringReader(configString));
                    String line = null;
                    while ((line = lnr.readLine()) != null) {
                        if (line.trim().isEmpty()) {
                            continue;
                        }
                        pw.print("    ");
                        pw.println(line.trim());
                    }
                }
            }
        }
        // additional sections
        for (final Section section : feature.getAdditionalSections()) {
            pw.println();
            pw.print("  [:");
            pw.print(section.getName());
            for (final Map.Entry<String, String> entry : section.getAttributes().entrySet()) {
                pw.print(' ');
                pw.print(entry.getKey());
                pw.print('=');
                pw.print(entry.getValue());
            }
            pw.println("]");
            if (section.getContents() != null) {
                pw.println(section.getContents());
            }
        }
    }
}
Also used : Configuration(org.apache.sling.provisioning.model.Configuration) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Feature(org.apache.sling.provisioning.model.Feature) Section(org.apache.sling.provisioning.model.Section) Artifact(org.apache.sling.provisioning.model.Artifact) LineNumberReader(java.io.LineNumberReader) RunMode(org.apache.sling.provisioning.model.RunMode) StringReader(java.io.StringReader) Map(java.util.Map) ArtifactGroup(org.apache.sling.provisioning.model.ArtifactGroup) PrintWriter(java.io.PrintWriter)

Example 64 with LineNumberReader

use of java.io.LineNumberReader in project opennms by OpenNMS.

the class HypericAckProcessor method parseHypericAlerts.

/**
 * <p>parseHypericAlerts</p>
 *
 * @param reader a {@link java.io.Reader} object.
 * @return a {@link java.util.List} object.
 * @throws javax.xml.bind.JAXBException if any.
 * @throws javax.xml.stream.XMLStreamException if any.
 */
public static List<HypericAlertStatus> parseHypericAlerts(Reader reader) throws JAXBException, XMLStreamException {
    List<HypericAlertStatus> retval = new ArrayList<HypericAlertStatus>();
    // Instantiate a JAXB context to parse the alert status
    JAXBContext context = JAXBContext.newInstance(new Class[] { HypericAlertStatuses.class, HypericAlertStatus.class });
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    XMLEventReader xmler = xmlif.createXMLEventReader(reader);
    EventFilter filter = new EventFilter() {

        @Override
        public boolean accept(XMLEvent event) {
            return event.isStartElement();
        }
    };
    XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter);
    // Read up until the beginning of the root element
    StartElement startElement = (StartElement) xmlfer.nextEvent();
    // Fetch the root element name for {@link HypericAlertStatus} objects
    String rootElementName = context.createJAXBIntrospector().getElementName(new HypericAlertStatuses()).getLocalPart();
    if (rootElementName.equals(startElement.getName().getLocalPart())) {
        Unmarshaller unmarshaller = context.createUnmarshaller();
        // Use StAX to pull parse the incoming alert statuses
        while (xmlfer.peek() != null) {
            Object object = unmarshaller.unmarshal(xmler);
            if (object instanceof HypericAlertStatus) {
                HypericAlertStatus alertStatus = (HypericAlertStatus) object;
                retval.add(alertStatus);
            }
        }
    } else {
        // Try to pull in the HTTP response to give the user a better idea of what went wrong
        final StringBuilder errorContent = new StringBuilder();
        LineNumberReader lineReader = new LineNumberReader(reader);
        try {
            String line;
            while (true) {
                line = lineReader.readLine();
                if (line == null) {
                    break;
                } else {
                    errorContent.append(line.trim());
                }
            }
        } catch (IOException e) {
            errorContent.append("Exception while trying to print out message content: " + e.getMessage());
        }
        // Throw an exception and include the erroneous HTTP response in the exception text
        throw new JAXBException("Found wrong root element in Hyperic XML document, expected: \"" + rootElementName + "\", found \"" + startElement.getName().getLocalPart() + "\"\n" + errorContent.toString());
    }
    return retval;
}
Also used : JAXBException(javax.xml.bind.JAXBException) ArrayList(java.util.ArrayList) JAXBContext(javax.xml.bind.JAXBContext) IOException(java.io.IOException) EventFilter(javax.xml.stream.EventFilter) LineNumberReader(java.io.LineNumberReader) StartElement(javax.xml.stream.events.StartElement) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) Unmarshaller(javax.xml.bind.Unmarshaller) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 65 with LineNumberReader

use of java.io.LineNumberReader in project linuxtools by eclipse.

the class Activator method getRpmGroups.

public List<String> getRpmGroups() {
    if (rpmGroups.isEmpty()) {
        // FIXME: Can we assume that all distros place
        // documentations files in the below path?
        // $NON-NLS-1$
        String docDir = "/usr/share/doc/";
        File dir = new File(docDir);
        if (dir.exists()) {
            // $NON-NLS-1$
            File[] files = dir.listFiles((FilenameFilter) (dir1, name) -> name.startsWith("rpm-"));
            try {
                // (e.g. rpm-apidocs is the wrong directory.)
                for (File file : files) {
                    // $NON-NLS-1$
                    File groupsFile = new File(file, "GROUPS");
                    if (groupsFile.exists()) {
                        LineNumberReader reader = null;
                        try {
                            reader = new LineNumberReader(new FileReader(groupsFile));
                            String line;
                            while ((line = reader.readLine()) != null) {
                                rpmGroups.add(line);
                            }
                        } finally {
                            if (reader != null) {
                                reader.close();
                            }
                        }
                        break;
                    }
                }
            } catch (IOException e) {
                SpecfileLog.logError(e);
            }
        }
    }
    return rpmGroups;
}
Also used : FilenameFilter(java.io.FilenameFilter) ContributionTemplateStore(org.eclipse.ui.editors.text.templates.ContributionTemplateStore) Image(org.eclipse.swt.graphics.Image) IOException(java.io.IOException) LineNumberReader(java.io.LineNumberReader) ContextTypeRegistry(org.eclipse.jface.text.templates.ContextTypeRegistry) File(java.io.File) ImageDescriptor(org.eclipse.jface.resource.ImageDescriptor) BundleContext(org.osgi.framework.BundleContext) ArrayList(java.util.ArrayList) List(java.util.List) AbstractUIPlugin(org.eclipse.ui.plugin.AbstractUIPlugin) TemplateStore(org.eclipse.jface.text.templates.persistence.TemplateStore) FileReader(java.io.FileReader) ContributionContextTypeRegistry(org.eclipse.ui.editors.text.templates.ContributionContextTypeRegistry) ImageRegistry(org.eclipse.jface.resource.ImageRegistry) FileReader(java.io.FileReader) IOException(java.io.IOException) File(java.io.File) LineNumberReader(java.io.LineNumberReader)

Aggregations

LineNumberReader (java.io.LineNumberReader)401 IOException (java.io.IOException)203 InputStreamReader (java.io.InputStreamReader)167 FileReader (java.io.FileReader)102 File (java.io.File)79 InputStream (java.io.InputStream)64 StringReader (java.io.StringReader)64 ArrayList (java.util.ArrayList)54 FileInputStream (java.io.FileInputStream)33 BufferedReader (java.io.BufferedReader)27 PrintWriter (java.io.PrintWriter)25 HashMap (java.util.HashMap)22 FileNotFoundException (java.io.FileNotFoundException)20 BufferedWriter (java.io.BufferedWriter)16 FileWriter (java.io.FileWriter)16 Pattern (java.util.regex.Pattern)16 Test (org.junit.jupiter.api.Test)16 ByteArrayInputStream (java.io.ByteArrayInputStream)15 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 Reader (java.io.Reader)14