Example usage for com.google.common.io Resources toString

List of usage examples for com.google.common.io Resources toString

Introduction

In this page you can find the example usage for com.google.common.io Resources toString.

Prototype

public static String toString(URL url, Charset charset) throws IOException 

Source Link

Document

Reads all characters from a URL into a String , using the given character set.

Usage

From source file:org.apache.drill.jdbc.DrillHandler.java

public void onConnectionInit(OptiqConnection connection) throws SQLException {
    super.onConnectionInit(connection);

    final Properties p = connection.getProperties();

    if (ref) {/*  ww  w  .  j av a  2  s.  c  o m*/
        final String model = p.getProperty("model");
        if (model != null) {
            if (model != null) {
                try {
                    new ModelHandler(connection, model);
                } catch (IOException e) {
                    throw new SQLException(e);
                }
            }
        }
    } else {

        registry = new SchemaProviderRegistry(config);

        Preconditions.checkArgument(bit == null);
        Preconditions.checkArgument(client == null);
        Preconditions.checkArgument(coordinator == null);

        final String zk = connection.getProperties().getProperty("zk");

        try {
            String enginesData = Resources.toString(Resources.getResource("storage-engines.json"),
                    Charsets.UTF_8);

            StorageEngines engines = config.getMapper().readValue(enginesData, StorageEngines.class);

            if (zk != null) {
                coordinator = new ZKClusterCoordinator(config, zk);
                coordinator.start(10000);
                DrillClient cl = new DrillClient(config, coordinator);
                cl.connect();
                client = cl;
            } else {

                RemoteServiceSet local = RemoteServiceSet.getLocalServiceSet();
                this.coordinator = local.getCoordinator();
                bit = new Drillbit(config, local);
                bit.run();

                DrillClient cl = new DrillClient(config, coordinator);
                cl.connect();
                client = cl;
            }

            MutableSchema rootSchema = connection.getRootSchema();

            for (Map.Entry<String, StorageEngineConfig> entry : engines) {
                SchemaProvider provider = registry.getSchemaProvider(entry.getValue());
                FileSystemSchema schema = new FileSystemSchema(client, entry.getValue(), provider,
                        rootSchema.getTypeFactory(), rootSchema, entry.getKey(), rootSchema.getExpression(),
                        rootSchema.getQueryProvider());
                rootSchema.addSchema(entry.getKey(), schema);
            }

            rootSchema.addSchema("--FAKE--", new FakeSchema(rootSchema, rootSchema.getQueryProvider(),
                    rootSchema.getTypeFactory(), "fake", rootSchema.getExpression()));

        } catch (Exception ex) {
            System.out.println(ex);
            logger.error("Failure while setting up jdbc handler", ex);
            throw new SQLException("Failure trying to connect to Drill.", ex);
        }
    }

    // The "schema" parameter currently gives a name to the schema. In future
    // it will choose a schema that (presumably) already exists.
    final String schemaName = connection.getProperties().getProperty("schema");
    if (schemaName != null) {
        connection.setSchema(schemaName);
    }

}

From source file:com.quinsoft.zeidon.objectbrowser.OiDisplayPanel.java

OiDisplayPanel(BrowserEnvironment env) {
    super();//www .  j a  va 2 s.  co m
    this.env = env;
    //        setSize( new Dimension( 1000, 200 ) );
    borderLayout = new BorderLayout();
    setLayout(borderLayout);

    //
    // Set up buttons.
    //
    JPanel buttonPane = new JPanel();
    buttonPane.add(new JLabel("Cursors:"));
    addButton(buttonPane, "First", FIRST_CURSOR, "[Home]");
    addButton(buttonPane, "Prev in OI", PREV_CURSOR, "[Page Up]");
    addButton(buttonPane, "Next in OI", NEXT_CURSOR, "[Page Down]");
    addButton(buttonPane, "Last", LAST_CURSOR, "[End]");
    addButton(buttonPane, "Refresh OI", REFRESH_OI, "");

    // Add a dummy, invisible label for spacing.  It's a hack but it's easy.
    JLabel dummy = new JLabel("                               ");
    buttonPane.add(dummy);

    // Add a button who's only purpose is to be a mouse over tooltip.
    try {
        URL url = Resources.getResource("help-text.html.txt");
        String text = Resources.toString(url, Charsets.UTF_8);
        JButton button = new JButton("Help");
        button.setToolTipText(text);
        buttonPane.add(button);
    } catch (Exception e) {
        env.getOe().getSystemTask().log().error("Couldn't open help-text.html.txt");
    }

    add(buttonPane, BorderLayout.NORTH);

    InputMap im = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    ActionMap am = getActionMap();
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, KeyEvent.CTRL_DOWN_MASK), "increaseScale");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, KeyEvent.CTRL_DOWN_MASK), "increaseScale");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, KeyEvent.CTRL_DOWN_MASK), "increaseScale");
    am.put("increaseScale", new ChangeScaleAction(+2));

    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT, KeyEvent.CTRL_DOWN_MASK), "decreaseScale");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, KeyEvent.CTRL_DOWN_MASK), "decreaseScale");
    am.put("decreaseScale", new ChangeScaleAction(-2));

    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_0, KeyEvent.CTRL_DOWN_MASK), "resetScale");
    am.put("resetScale", new ChangeScaleAction(0));

    setVisible(true);
}

From source file:org.onosproject.drivers.netconf.MockDriverHandler.java

@SuppressWarnings("unchecked")
public MockDriverHandler(Class<? extends AbstractDriverLoader> loaderClass, String behaviorSpec,
        DeviceId mockDeviceId, CoreService mockCoreService, DeviceService mockDeviceService) {

    // Had to split into declaration and initialization to make stylecheck happy
    // else line was considered too long
    // and auto format couldn't be tweak to make it correct
    Map<Class<? extends Behaviour>, Class<? extends Behaviour>> behaviours;
    behaviours = new HashMap<Class<? extends Behaviour>, Class<? extends Behaviour>>();

    try {/*w ww .  ja v a 2  s  . co  m*/
        String data = Resources.toString(Resources.getResource(loaderClass, behaviorSpec),
                StandardCharsets.UTF_8);
        InputStream resp = IOUtils.toInputStream(data, StandardCharsets.UTF_8);
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(resp);

        XPath xp = XPathFactory.newInstance().newXPath();
        NodeList list = (NodeList) xp.evaluate("//behaviour", document, XPathConstants.NODESET);
        for (int i = 0; i < list.getLength(); i += 1) {
            Node node = list.item(i);
            NamedNodeMap attrs = node.getAttributes();
            Class<? extends Behaviour> api = (Class<? extends Behaviour>) Class
                    .forName(attrs.getNamedItem("api").getNodeValue());
            Class<? extends Behaviour> impl = (Class<? extends Behaviour>) Class
                    .forName(attrs.getNamedItem("impl").getNodeValue());
            behaviours.put(api, impl);
        }
        init(behaviours, mockDeviceId, mockCoreService, mockDeviceService);
    } catch (Exception e) {
        fail(e.toString());
    }
}

From source file:bear.fx.DownloadFxApp.java

public static String downloadJDKJs() {
    try {// w ww  .  j  a v  a 2 s . c o m
        return Resources.toString(DownloadFxApp.class.getResource("downloadJDK.js"), Charsets.UTF_8);
    } catch (IOException e) {
        throw Exceptions.runtime(e);
    }
}

From source file:com.streamsets.datacollector.execution.alerts.EmailNotifier.java

@Override
public void onStateChange(PipelineState fromState, PipelineState toState, String toStateJson,
        ThreadUsage threadUsage) throws PipelineRuntimeException {
    //should not be active in slave mode
    if (toState.getExecutionMode() != ExecutionMode.SLAVE && name.equals(toState.getName())) {
        if (pipelineStates != null && pipelineStates.contains(toState.getStatus().name())) {
            //pipeline switched to a terminal state. Send email
            String emailBody = null;
            String subject = null;
            URL url;//  ww  w .j a  v  a2  s  .co  m
            try {
                switch (toState.getStatus()) {
                case START_ERROR:
                case RUN_ERROR:
                    url = Resources.getResource(EmailConstants.NOTIFY_ERROR_EMAIL_TEMPLATE);
                    emailBody = Resources.toString(url, Charsets.UTF_8);
                    emailBody = emailBody.replace(EmailConstants.DESCRIPTION_KEY, toState.getMessage());
                    subject = EmailConstants.STREAMSETS_DATA_COLLECTOR_ALERT + toState.getName() + " - ERROR";
                    break;
                case STOPPED:
                    url = Resources.getResource(EmailConstants.PIPELINE_STATE_CHANGE__EMAIL_TEMPLATE);
                    emailBody = Resources.toString(url, Charsets.UTF_8);
                    emailBody = emailBody.replace(EmailConstants.MESSAGE_KEY, "was stopped");
                    subject = EmailConstants.STREAMSETS_DATA_COLLECTOR_ALERT + toState.getName() + " - STOPPED";
                    break;
                case FINISHED:
                    url = Resources.getResource(EmailConstants.PIPELINE_STATE_CHANGE__EMAIL_TEMPLATE);
                    emailBody = Resources.toString(url, Charsets.UTF_8);
                    emailBody = emailBody.replace(EmailConstants.MESSAGE_KEY, "finished executing");
                    subject = EmailConstants.STREAMSETS_DATA_COLLECTOR_ALERT + toState.getName()
                            + " - FINISHED";
                    break;
                case RUNNING:
                    url = Resources.getResource(EmailConstants.PIPELINE_STATE_CHANGE__EMAIL_TEMPLATE);
                    emailBody = Resources.toString(url, Charsets.UTF_8);
                    emailBody = emailBody.replace(EmailConstants.MESSAGE_KEY, "started executing");
                    subject = EmailConstants.STREAMSETS_DATA_COLLECTOR_ALERT + toState.getName() + " - RUNNING";
                    break;
                case DISCONNECTED:
                    url = Resources.getResource(EmailConstants.SDC_STATE_CHANGE__EMAIL_TEMPLATE);
                    emailBody = Resources.toString(url, Charsets.UTF_8);
                    emailBody = emailBody.replace(EmailConstants.MESSAGE_KEY, "was shut down");
                    subject = EmailConstants.STREAMSETS_DATA_COLLECTOR_ALERT + toState.getName()
                            + " - DISCONNECTED";
                    break;
                case CONNECTING:
                    url = Resources.getResource(EmailConstants.SDC_STATE_CHANGE__EMAIL_TEMPLATE);
                    emailBody = Resources.toString(url, Charsets.UTF_8);
                    emailBody = emailBody.replace(EmailConstants.MESSAGE_KEY, "was started");
                    subject = EmailConstants.STREAMSETS_DATA_COLLECTOR_ALERT + toState.getName()
                            + " - CONNECTING";
                    break;
                default:
                    throw new IllegalStateException("Unexpected PipelineState " + toState);
                }
            } catch (IOException e) {
                throw new PipelineRuntimeException(ContainerError.CONTAINER_01000, e.toString(), e);
            }
            java.text.DateFormat dateTimeFormat = new SimpleDateFormat(EmailConstants.DATE_MASK,
                    Locale.ENGLISH);
            emailBody = emailBody
                    .replace(EmailConstants.TIME_KEY, dateTimeFormat.format(new Date(toState.getTimeStamp())))
                    .replace(EmailConstants.PIPELINE_NAME_KEY, toState.getName())
                    .replace(EmailConstants.URL_KEY, runtimeInfo.getBaseHttpUrl() + EmailConstants.PIPELINE_URL
                            + toState.getName().replaceAll(" ", "%20"));
            try {
                emailSender.send(emails, subject, emailBody);
            } catch (EmailException e) {
                LOG.error("Error sending email : '{}'", e.toString());
            }
        }
    }
}

From source file:org.isisaddons.wicket.pdfjs.cpt.ui.PdfJsViewerPanel.java

PdfJsViewerPanel(String id, ScalarModel scalarModel) {
    super(id, scalarModel);

    final URL resource = Resources.getResource(PdfJsViewerPanel.class, "PdfJsViewerPanelCallbacks.template.js");
    try {//from  www.  ja  va2 s .  c o  m
        pdfJsViewerPanelCallbacksTemplateJs = Resources.toString(resource, Charsets.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.sangupta.andruil.Andruil.java

/**
 * //from   ww  w.  j  a  v  a  2s  .  com
 * @return
 */
private static JavaPackage[] loadExternalJavaPackages() {
    URL url = Resources.getResource("javapack.json");
    if (url == null) {
        return null;
    }

    String json;
    try {
        json = Resources.toString(url, Charset.defaultCharset());
    } catch (IOException e) {
        // TODO: log this
        return null;
    }

    if (AssertUtils.isEmpty(json)) {
        return null;
    }

    return GsonUtils.getGson().fromJson(json, JavaPackage[].class);
}

From source file:com.facebook.buck.features.python.PythonInPlaceBinary.java

private static String getNamedResource(String resourceName) {
    try {/*from w  w w. j  a  v  a2s  .co  m*/
        return Resources.toString(Resources.getResource(PythonInPlaceBinary.class, resourceName),
                Charsets.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.redzoo.article.planetcassandra.reactive.CassandraDB.java

/**
 * executes a CQL file. CQL processing errors will be ignored 
 * //from   w  ww. j a va2s  .c om
 * @param cqlFile    the CQL file name 
 * @throws IOException  if the file could not be found
 */
public void tryExecuteCqlFile(String cqlFile) {
    try {
        File file = new File(cqlFile);
        if (file.exists()) {
            tryExecuteCql(Files.toString(new File(cqlFile), Charsets.UTF_8));
        } else {
            tryExecuteCql(Resources.toString(Resources.getResource(cqlFile), Charsets.UTF_8));
        }
    } catch (IOException ioe) {
        throw new RuntimeException(cqlFile + " not found");
    }
}

From source file:org.apache.provisionr.test.ProvisionrLiveTestSupport.java

public String getResourceAsString(String resource) throws IOException {
    return Resources.toString(Resources.getResource(ProvisionrLiveTestSupport.class, resource), Charsets.UTF_8);
}