Example usage for org.apache.commons.io.input ReaderInputStream ReaderInputStream

List of usage examples for org.apache.commons.io.input ReaderInputStream ReaderInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io.input ReaderInputStream ReaderInputStream.

Prototype

public ReaderInputStream(Reader reader) 

Source Link

Document

Construct a new ReaderInputStream that uses the default character encoding with a default input buffer size of 1024 characters.

Usage

From source file:com.edduarte.protbox.Protbox.java

public static void main(String... args) {

    // activate debug / verbose mode
    if (args.length != 0) {
        List<String> argsList = Arrays.asList(args);
        if (argsList.contains("-v")) {
            Constants.verbose = true;//from   w  w  w . j  a  v  a 2  s  .c  o  m
        }
    }

    // use System's look and feel
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
        // If the System's look and feel is not obtainable, continue execution with JRE look and feel
    }

    // check this is a single instance
    try {
        new ServerSocket(1882);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null,
                "Another instance of Protbox is already running.\n" + "Please close the other instance first.",
                "Protbox already running", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // check if System Tray is supported by this operative system
    if (!SystemTray.isSupported()) {
        JOptionPane.showMessageDialog(null,
                "Your operative system does not support system tray functionality.\n"
                        + "Please try running Protbox on another operative system.",
                "System tray not supported", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // add PKCS11 providers
    FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")),
            HiddenFileFilter.VISIBLE);

    File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter);

    if (providersConfigFiles != null) {
        for (File f : providersConfigFiles) {
            try {
                List<String> lines = FileUtils.readLines(f);
                String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get();
                lines.remove(aliasLine);
                String alias = aliasLine.split("=")[1].trim();

                StringBuilder sb = new StringBuilder();
                for (String s : lines) {
                    sb.append(s);
                    sb.append("\n");
                }

                Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString())));
                Security.addProvider(p);

                pkcs11Providers.put(p.getName(), alias);

            } catch (IOException | ProviderException ex) {
                if (ex.getMessage().equals("Initialization failed")) {
                    ex.printStackTrace();

                    String s = "The following error occurred:\n" + ex.getCause().getMessage()
                            + "\n\nIn addition, make sure you have "
                            + "an available smart card reader connected before opening the application.";
                    JTextArea textArea = new JTextArea(s);
                    textArea.setColumns(60);
                    textArea.setLineWrap(true);
                    textArea.setWrapStyleWord(true);
                    textArea.setSize(textArea.getPreferredSize().width, 1);

                    JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider",
                            JOptionPane.ERROR_MESSAGE);
                    System.exit(1);
                } else {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null,
                            "Error while setting up PKCS11 provider from configuration file " + f.getName()
                                    + ".\n" + ex.getMessage(),
                            "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    // adds a shutdown hook to save instantiated directories into files when the application is being closed
    Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit));

    // get system tray and run tray applet
    tray = SystemTray.getSystemTray();
    SwingUtilities.invokeLater(() -> {

        if (Constants.verbose) {
            logger.info("Starting application");
        }

        //Start a new TrayApplet object
        trayApplet = TrayApplet.getInstance();
    });

    // prompts the user to choose which provider to use
    ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> {

        // loads eID token
        eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> {
            user = returnedUser;
            certificateData = returnedCertificateData;

            // gets a password to use on the saved registry files (for loading and saving)
            final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null);
            consumerHolder.set(password -> {
                registriesPasswordKey = password;
                try {
                    // if there are serialized files, load them if they can be decoded by this user's private key
                    final List<SavedRegistry> serializedDirectories = new ArrayList<>();
                    if (Constants.verbose) {
                        logger.info("Reading serialized registry files...");
                    }

                    File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles();
                    if (registryFileList != null) {
                        for (File f : registryFileList) {
                            if (f.isFile()) {
                                byte[] data = FileUtils.readFileToByteArray(f);
                                try {
                                    Cipher cipher = Cipher.getInstance("AES");
                                    cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey);
                                    byte[] registryDecryptedData = cipher.doFinal(data);
                                    serializedDirectories.add(new SavedRegistry(f, registryDecryptedData));
                                } catch (GeneralSecurityException ex) {
                                    if (Constants.verbose) {
                                        logger.info("Inserted Password does not correspond to " + f.getName());
                                    }
                                }
                            }
                        }
                    }

                    // if there were no serialized directories, show NewDirectory window to configure the first folder
                    if (serializedDirectories.isEmpty() || registryFileList == null) {
                        if (Constants.verbose) {
                            logger.info("No registry files were found: running app as first time!");
                        }
                        NewRegistryWindow.start(true);

                    } else { // there were serialized directories
                        loadRegistry(serializedDirectories);
                        trayApplet.repaint();
                        showTrayApplet();
                    }

                } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException
                        | ProtboxException ex) {

                    JOptionPane.showMessageDialog(null,
                            "The inserted password was invalid! Please try another one!", "Invalid password!",
                            JOptionPane.ERROR_MESSAGE);
                    insertPassword(consumerHolder.get());
                }
            });
            insertPassword(consumerHolder.get());
        });
    });
}

From source file:com.fizzed.blaze.system.TailTest.java

@Test
public void works() throws Exception {
    Tail tail = new Tail(null);

    String s = "a\nb\nc\n";

    StringReader sr = new StringReader(s);

    tail.pipeInput(new ReaderInputStream(sr));

    Deque<String> output = tail.run();

    assertThat(output.size(), is(3));/*from  www  .  j ava2  s.  co m*/
    assertThat(output.remove(), is("a"));
    assertThat(output.remove(), is("b"));
    assertThat(output.remove(), is("c"));
}

From source file:fr.ybonnel.FruitShopTest.java

private void oneTest(int expectedResult, String... articles) {
    InputStream reader = new ReaderInputStream(
            new StringReader(Stream.of(articles).collect(Collectors.joining("\n")) + "\nexit\n"));

    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    new FruitShop().caisse(reader, new PrintStream(stream));

    String result = new String(stream.toByteArray());

    String[] lines = result.split("\\n");

    String lastTotal = lines[lines.length - 2];

    System.out.println(result);//from  w  w  w .j  av  a 2s .  c o  m

    assertEquals(expectedResult, Integer.parseInt(lastTotal));

}

From source file:es.us.isa.jdataset.loader.ExcelLoader.java

@Override
public DataSet load(InputStream is, String extension) throws IOException {
    try {//from ww  w .  java  2  s .c o  m
        StringBuilder sb = new StringBuilder();
        ExcelToCSV excel2CSV = new ExcelToCSV();
        excel2CSV.convertExcelToCSV(is, sb);
        return csvLoader.load(new ReaderInputStream(new StringReader(sb.toString())), extension);
    } catch (IllegalArgumentException ex) {
        Logger.getLogger(ExcelLoader.class.getName()).log(Level.SEVERE, null, ex);
        throw new IOException(ex);
    } catch (InvalidFormatException ex) {
        Logger.getLogger(ExcelLoader.class.getName()).log(Level.SEVERE, null, ex);
        throw new IOException(ex);
    }
}

From source file:io.apiman.gateway.engine.io.JsonPayloadIOTest.java

@Test
public void testUnmarshall_Simple() throws Exception {
    String json = "{\r\n" + "  \"hello\" : \"world\",\r\n" + "  \"foo\" : \"bar\"\r\n" + "}";

    JsonPayloadIO io = new JsonPayloadIO();
    Map data = io.unmarshall(new ReaderInputStream(new StringReader(json)));
    Assert.assertNotNull(data);//from  w w w  . java 2 s  .  co m
    Assert.assertEquals("world", data.get("hello"));
    Assert.assertEquals("bar", data.get("foo"));
    Assert.assertNull(data.get("other"));

    data = io.unmarshall(json.getBytes("UTF-8"));
    Assert.assertNotNull(data);
    Assert.assertEquals("world", data.get("hello"));
    Assert.assertEquals("bar", data.get("foo"));
    Assert.assertNull(data.get("other"));
}

From source file:com.silverpeas.export.ImportDescriptor.java

/**
 * Creates and initializes a new descriptor on an import process with the specified reader and
 * import format. The input stream is initialized with the specified reader.
 * @param reader the reader to use for importing the serializable resources.
 * @return an import descriptor.// w  w w . ja  va  2  s.c om
 */
public static ImportDescriptor withReader(final Reader reader) {
    if (reader == null) {
        throw new IllegalArgumentException("The reader cannot be null!");
    }
    ImportDescriptor descriptor = new ImportDescriptor();
    descriptor.setReader(reader);
    descriptor.setInputStream(new ReaderInputStream(reader));
    return descriptor;
}

From source file:cz.lbenda.common.CharSequenceBinaryData.java

@Override
public InputStream getInputStream() {
    return new ReaderInputStream(getReader());
}

From source file:co.cask.cdap.gateway.handlers.ConfigServiceTest.java

@Test
public void testConfig() {

    // cConf/*from www.  j  a  va2s  . com*/
    CConfiguration cConf = CConfiguration.create();
    cConf.clear();

    String cConfResourceString = "<configuration>\n" + "\n" + "  <property>\n"
            + "    <name>stream.zz.threshold</name>\n" + "    <value>1</value>\n"
            + "    <description>Some description</description>\n" + "  </property>\n" + "\n"
            + "</configuration>";
    ReaderInputStream cConfResource = new ReaderInputStream(new StringReader(cConfResourceString));
    cConf.addResource(cConfResource);

    ConfigEntry cConfEntry = new ConfigEntry("stream.zz.threshold", "1", cConfResource.toString());

    // hConf
    Configuration hConf = new Configuration();
    String hConfResourceString = "<configuration>\n" + "\n" + "  <property>\n"
            + "    <name>stream.notification.threshold</name>\n" + "    <value>3</value>\n"
            + "    <description>Some description</description>\n" + "  </property>\n" + "\n"
            + "</configuration>";
    ReaderInputStream hConfResource = new ReaderInputStream(new StringReader(hConfResourceString));
    hConf.addResource(hConfResource);

    ConfigEntry hConfEntry = new ConfigEntry("stream.notification.threshold", "3", hConfResource.toString());

    // test
    ConfigService configService = new ConfigService(cConf, hConf);
    List<ConfigEntry> cConfEntries = configService.getCConf();
    Assert.assertTrue(cConfEntries.contains(cConfEntry));

    List<ConfigEntry> hConfEntries = configService.getHConf();
    Assert.assertTrue(hConfEntries.contains(hConfEntry));
}

From source file:com.mycompany.cassandrajavaclient.XmlParser.java

private void parse(String xmlContent) {
    try {/*from w w w.jav  a  2 s  .  com*/
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder builder = factory.newDocumentBuilder();
        try {
            InputStream inputStream = new BufferedInputStream(
                    new ReaderInputStream(new StringReader(xmlContent)));
            final Document document = builder.parse(inputStream);
            emit(document);
        } catch (SAXException | IOException ex) {
            Logger.getLogger(XmlParser.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(XmlParser.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:cn.lambdalib.cgui.loader.xml.CGUIDocLoader.java

public CGui loadXml(String xml) throws Exception {
    return loadXml(new ReaderInputStream(new StringReader(xml)));
}