Example usage for java.util Properties put

List of usage examples for java.util Properties put

Introduction

In this page you can find the example usage for java.util Properties put.

Prototype

@Override
    public synchronized Object put(Object key, Object value) 

Source Link

Usage

From source file:com.anjlab.sat3.Program.java

private static void findHSSRoute(CommandLine commandLine, String formulaFile, Properties statistics,
        StopWatch stopWatch, ITabularFormula formula, ITabularFormula formulaClone, ObjectArrayList ctfClone,
        ObjectArrayList hss, String hssPath) throws IOException {
    long timeElapsed;
    //  TODO Configure hssTempPath using CL options
    String hssTempPath = hssPath + "-temp";
    stopWatch.start("Find HSS route");
    ObjectArrayList route = Helper.findHSSRouteByReduce(hss, hssTempPath);
    timeElapsed = stopWatch.stop();/*w w  w. j  a v a  2  s  .c om*/
    stopWatch.printElapsed();

    statistics.put(Helper.SEARCH_HSS_ROUTE_TIME, String.valueOf(timeElapsed));

    if (Helper.EnableAssertions) {
        if (formulaClone != null) {
            if (!formula.equals(formulaClone)) {
                LOGGER.warn("Initial formula differs from its cloned version");
            }
        }
    }

    String hssImageFile = formulaFile + "-hss-0.png";

    if (commandLine.hasOption(HSS_IMAGE_OUTPUT_FILENAME_OPTION)) {
        hssImageFile = commandLine.getOptionValue(HSS_IMAGE_OUTPUT_FILENAME_OPTION);
    }

    stopWatch.start("Write HSS as image to " + hssImageFile);
    Helper.writeToImage(((SimpleVertex) route.get(route.size() - 1)).getHyperStructure(), route, null,
            hssImageFile);
    stopWatch.stop();
    stopWatch.printElapsed();

    stopWatch.start("Verify formula is satisfiable using variable values from HSS route");
    verifySatisfiable(formula, route);
    if (Helper.EnableAssertions) {
        if (ctfClone != null) {
            verifySatisfiable(ctfClone, route);
        }
    }
    stopWatch.stop();
    stopWatch.printElapsed();

    String resultsFilename = getResultsFilename(commandLine, formulaFile);
    stopWatch.start("Write HSS route to " + resultsFilename);
    writeSatToFile(formula, resultsFilename, statistics, route);
    stopWatch.stop();
    stopWatch.printElapsed();
}

From source file:com.github.vatbub.awsvpnlauncher.Main.java

/**
 * Connects to the specified instance using ssh. Output will be sent to System.out, input will be taken from System.in
 *
 * @param instanceID The id of the instance to connect to
 *///from w  ww . ja  va 2 s.  c  om
private static void ssh(String instanceID) {
    try {
        File privateKey = new File(prefs.getPreference(Property.privateKeyFile));
        DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
        List<String> instanceId = new ArrayList<>(1);
        instanceId.add(instanceID);
        describeInstancesRequest.setInstanceIds(instanceId);
        DescribeInstancesResult describeInstancesResult = client.describeInstances(describeInstancesRequest);
        Instance instance = describeInstancesResult.getReservations().get(0).getInstances().get(0);

        String sshIp = instance.getPublicDnsName();

        // SSH config
        FOKLogger.info(Main.class.getName(), "Configuring SSH...");
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        jsch.addIdentity(privateKey.getAbsolutePath());

        FOKLogger.info(Main.class.getName(), "Connecting using ssh to " + sshUsername + "@" + sshIp);
        session = jsch.getSession(sshUsername, sshIp, 22);

        session.setConfig(sshConfig);
        try {
            session.connect();
        } catch (Exception e) {
            FOKLogger.log(Main.class.getName(), Level.SEVERE,
                    "Could not connect to the instance due to an exception", e);
        }

        // Connected
        FOKLogger.info(Main.class.getName(),
                "Connection established, connected to " + sshUsername + "@" + sshIp);

        Channel channel = session.openChannel("shell");

        if (posix.isatty(FileDescriptor.out)) {
            FOKLogger.info(Main.class.getName(), "Connected to a tty, disabling colors...");
            // Disable colors
            ((ChannelShell) channel).setPtyType("vt102");
        }

        channel.setInputStream(copyAndFilterInputStream());
        channel.setOutputStream(new MyPrintStream());
        channel.connect();

        NullOutputStream nullOutputStream = new NullOutputStream();
        Thread watchForSSHDisconnectThread = new Thread(() -> {
            while (channel.isConnected()) {
                nullOutputStream.write(0);
            }
            // disconnected
            System.exit(0);
        });
        watchForSSHDisconnectThread.setName("watchForSSHDisconnectThread");
        watchForSSHDisconnectThread.start();

    } catch (JSchException | IOException e) {
        FOKLogger.log(Main.class.getName(), Level.SEVERE, "An error occurred", e);
    }
}

From source file:com.semsaas.utils.anyurl.App.java

private static String[] processOption(String[] args, Properties props) {
    LongOpt[] options = new LongOpt[] { new LongOpt("output", LongOpt.REQUIRED_ARGUMENT, null, 'o') };

    // Build auxilary structures
    HashMap<Integer, LongOpt> shortOptionMap = new HashMap<Integer, LongOpt>();
    StringBuffer decl = new StringBuffer();
    for (LongOpt o : options) {
        shortOptionMap.put(o.getVal(), o);
        decl.append((char) o.getVal());
        if (o.getHasArg() == LongOpt.OPTIONAL_ARGUMENT) {
            decl.append("::");
        } else if (o.getHasArg() == LongOpt.REQUIRED_ARGUMENT) {
            decl.append(":");
        }//from   ww  w  .j  a v a2 s  . c  om
    }
    Getopt g = new Getopt("anyurl", args, decl.toString(), options);

    int c = 0;
    while ((c = g.getopt()) != -1) {
        LongOpt opt = shortOptionMap.get(c);
        String optName = opt.getName();
        String optVal = g.getOptarg();
        props.put(optName, optVal);
    }

    // NB: Getopt moves non options to the end
    return Arrays.copyOfRange(args, g.getOptind(), args.length);
}

From source file:com.websqrd.catbot.setting.CatbotSettings.java

public static void storePasswd(String username, String passwd) {
    Properties props = getProperties(passwdFilename);
    props.put(username, encryptPasswd(passwd));
    storeProperties(props, passwdFilename);
    putToCache(props, passwdFilename);/*from   w ww.j a  v a  2 s .  c  o  m*/
}

From source file:com.glaf.core.config.DBConfiguration.java

public static ConnectionDefinition toConnectionDefinition(Properties props) {
    if (props != null && !props.isEmpty()) {
        ConnectionDefinition model = new ConnectionDefinition();
        model.setDatasource(props.getProperty(JDBC_DATASOURCE));
        model.setDriver(props.getProperty(JDBC_DRIVER));
        model.setUrl(props.getProperty(JDBC_URL));
        model.setName(props.getProperty(JDBC_NAME));
        model.setUser(props.getProperty(JDBC_USER));
        model.setPassword(props.getProperty(JDBC_PASSWORD));
        model.setSubject(props.getProperty(SUBJECT));
        model.setProvider(props.getProperty(JDBC_PROVIDER));
        model.setType(props.getProperty(JDBC_TYPE));
        model.setHost(props.getProperty(HOST));
        model.setDatabase(props.getProperty(DATABASE));
        if (StringUtils.isNotEmpty(props.getProperty(PORT))) {
            model.setPort(Integer.parseInt(props.getProperty(PORT)));
        }// w ww. j a  v a2  s .  c o m

        if (StringUtils.equals("true", props.getProperty(JDBC_AUTOCOMMIT))) {
            model.setAutoCommit(true);
        }

        Properties p = new Properties();
        Enumeration<?> e = props.keys();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value = props.getProperty(key);
            p.put(key, value);
        }
        model.setProperties(p);
        return model;
    }
    return null;
}

From source file:io.coala.json.DynaBean.java

/**
 * @param <T>//ww  w  . j a  v a  2 s . c o  m
 * @param wrapperType
 * @return
 */
static final <T> JsonSerializer<T> createJsonSerializer(final Class<T> type) {
    return new JsonSerializer<T>() {
        @Override
        public void serialize(final T value, final JsonGenerator jgen, final SerializerProvider serializers)
                throws IOException, JsonProcessingException {
            // non-Proxy objects get default treatment
            if (!Proxy.isProxyClass(value.getClass())) {
                @SuppressWarnings("unchecked")
                final JsonSerializer<T> ser = (JsonSerializer<T>) serializers
                        .findValueSerializer(value.getClass());
                if (ser != this)
                    ser.serialize(value, jgen, serializers);
                else
                    LOG.warn("Problem serializing: {}", value);
                return;
            }

            // BeanWrapper gets special treatment
            if (DynaBeanInvocationHandler.class.isInstance(Proxy.getInvocationHandler(value))) {
                final DynaBeanInvocationHandler handler = (DynaBeanInvocationHandler) Proxy
                        .getInvocationHandler(value);

                // Wrapper extensions get special treatment
                if (Wrapper.class.isAssignableFrom(handler.type)) {
                    final Object wrap = handler.bean.get("wrap");
                    serializers.findValueSerializer(wrap.getClass(), null).serialize(wrap, jgen, serializers);
                    return;
                }
                // Config (Accessible) extensions get special treatment
                else if (Accessible.class.isAssignableFrom(handler.type)) {
                    final Map<String, Object> copy = new HashMap<>(handler.bean.any());
                    final Accessible config = (Accessible) handler.config;
                    for (String key : config.propertyNames())
                        copy.put(key, config.getProperty(key));
                    serializers.findValueSerializer(copy.getClass(), null).serialize(copy, jgen, serializers);
                    return;
                } else if (Config.class.isAssignableFrom(handler.type))
                    throw new JsonGenerationException("BeanWrapper should extend " + Accessible.class.getName()
                            + " required for serialization: " + Arrays.asList(handler.type.getInterfaces()),
                            jgen);

                // BeanWrappers that do not extend OWNER API's Config
                serializers.findValueSerializer(handler.bean.getClass(), null).serialize(handler.bean, jgen,
                        serializers);
                return;
            }

            // Config (Accessible) gets special treatment
            if (Accessible.class.isInstance(value)) {
                final Accessible config = (Accessible) value;
                final Properties entries = new Properties();
                for (String key : config.propertyNames())
                    entries.put(key, config.getProperty(key));
                serializers.findValueSerializer(entries.getClass(), null).serialize(entries, jgen, serializers);
                return;
            }

            if (Config.class.isInstance(value))
                throw new JsonGenerationException("Config should extend " + Accessible.class.getName()
                        + " required for serialization: " + Arrays.asList(value.getClass().getInterfaces()),
                        jgen);

            throw new JsonGenerationException(
                    "No serializer found for proxy of: " + Arrays.asList(value.getClass().getInterfaces()),
                    jgen);
        }
    };
}

From source file:com.esri.geoportal.commons.pdf.PdfUtils.java

/**
 * Reads metadata values from a PDF file.
 * /*ww w  . j  a  v a2 s.c  o m*/
 * @param rawBytes the PDF to read
 * @param defaultTitle title to be used if the PDF metadata doesn't have one
 * @param geometryServiceUrl url of a <a href="https://developers.arcgis.com/rest/services-reference/geometry-service.htm">geometry service</a> for reprojecting coordinates. 
 * 
 * @return metadata properties or null if the PDF cannot be read.
 * 
 * @throws IOException on parsing error
 */
public static Properties readMetadata(byte[] rawBytes, String defaultTitle, String geometryServiceUrl)
        throws IOException {
    Properties ret = new Properties();

    // Attempt to read in the PDF file
    try (PDDocument document = PDDocument.load(rawBytes)) {

        // See if we can read the PDF
        if (!document.isEncrypted()) {
            // Get document metadata
            PDDocumentInformation info = document.getDocumentInformation();

            if (info != null) {

                if (info.getTitle() != null) {
                    ret.put(PROP_TITLE, info.getTitle());
                } else {
                    ret.put(PROP_TITLE, defaultTitle);
                }

                if (info.getSubject() != null) {
                    ret.put(PROP_SUBJECT, info.getSubject());
                } else {

                    StringBuilder psudoSubject = new StringBuilder("");
                    psudoSubject.append("\nAuthor: " + info.getAuthor());
                    psudoSubject.append("\nCreator: " + info.getCreator());
                    psudoSubject.append("\nProducer: " + info.getProducer());

                    ret.put(PROP_SUBJECT, psudoSubject.toString());
                }

                if (info.getModificationDate() != null) {
                    ret.put(PROP_MODIFICATION_DATE, info.getModificationDate().getTime());
                } else {
                    ret.put(PROP_MODIFICATION_DATE, info.getCreationDate().getTime());
                }
            } else {
                LOG.warn("Got null metadata for PDF file");
                return null;
            }

            // Attempt to read in geospatial PDF data
            COSObject measure = document.getDocument().getObjectByType(COSName.getPDFName("Measure"));
            String bBox = null;
            if (measure != null) {
                // This is a Geospatial PDF (i.e. Adobe's standard)
                COSDictionary dictionary = (COSDictionary) measure.getObject();

                float[] coords = ((COSArray) dictionary.getItem("GPTS")).toFloatArray();

                bBox = generateBbox(coords);
            } else {
                PDPage page = document.getPage(0);
                if (page.getCOSObject().containsKey(COSName.getPDFName("LGIDict"))) {
                    // This is a GeoPDF (i.e. TerraGo's standard)
                    bBox = extractGeoPDFProps(page, geometryServiceUrl);
                }
            }

            if (bBox != null) {
                ret.put(PROP_BBOX, bBox);
            }

        } else {
            LOG.warn("Cannot read encrypted PDF file");
            return null;
        }

    } catch (IOException ex) {
        LOG.error("Exception reading PDF", ex);
        throw ex;
    }

    return ret;
}

From source file:com.aurel.track.util.emailHandling.MailReader.java

private static void updateSecurityProps(String protocol, String server, int securityConnection,
        Properties props) {
    props.remove("mail.pop3.socketFactory.class");
    props.remove("mail.imap.socketFactory.class");
    String oldTrustStore = (String) props.remove("javax.net.ssl.trustStore");
    switch (securityConnection) {
    case TSiteBean.SECURITY_CONNECTIONS_MODES.TLS_IF_AVAILABLE:
        if ("pop3".equalsIgnoreCase(protocol)) {
            props.put("mail.pop3.starttls.enable", "true");
            props.put("mail.pop3.ssl.protocols", "SSLv3 TLSv1");
        }//from w  w w.j  av  a 2s  .co m
        if ("imap".equalsIgnoreCase(protocol)) {
            props.put("mail.imap.starttls.enable", "true");
            props.put("mail.imap.ssl.protocols", "SSLv3 TLSv1");
        }
        break;
    case TSiteBean.SECURITY_CONNECTIONS_MODES.TLS:
        if ("pop3".equalsIgnoreCase(protocol)) {
            props.put("mail.pop3.starttls.enable", "true");
            props.put("mail.pop3.starttls.required", "true");
            props.put("mail.pop3.ssl.protocols", "SSLv3 TLSv1");
        }
        if ("imap".equalsIgnoreCase(protocol)) {
            props.put("mail.imap.starttls.enable", "true");
            props.put("mail.imap.starttls.required", "true");
            props.put("mail.imap.ssl.protocols", "SSLv3 TLSv1");
        }
        MailBL.setTrustKeyStore(server);
        break;
    case TSiteBean.SECURITY_CONNECTIONS_MODES.SSL: {
        LOGGER.debug("Update security   to SSL...");
        LOGGER.debug("oldTrustStore=" + oldTrustStore);
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        MailBL.setTrustKeyStore(server);
        if ("pop3".equalsIgnoreCase(protocol)) {
            LOGGER.debug("Use SSL pop3 protocol");
            props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        }
        if ("imap".equalsIgnoreCase(protocol)) {
            LOGGER.debug("Use SSL imap protocol");
            props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
        }
        break;
    }
    default:
        break;
    }
}

From source file:net.big_oh.common.utils.PropertyUtil.java

/**
 * Construct a new {@link Properties} object from the {@link ResourceBundle}
 * identified by resourceBundleName. Prior to looking up the ResourceBundle,
 * the resourceBundleName parameter is processed to conform to the naming
 * conventions for ResourceBundles: <br/>
 * <ul>/*  www.  j a  va2  s  .c o  m*/
 * <li>1) Any terminating ".properties" is stripped off.</li>
 * <li>2) Period characters ('.') are replaced with forward slash characters
 * ('/').</li>
 * </ul>
 * 
 * @param resourceBundleName
 *            The name of the ResourceBundle from which the new Properties
 *            object will be constructed.
 * @return A Properties object built from the named REsourceBundle.
 * @throws MissingResourceException
 */
public static Properties loadProperties(String resourceBundleName) throws MissingResourceException {

    logger.info("Requested properties file from resource bundle named " + resourceBundleName + ".");

    Properties props = new Properties();

    if (resourceBundleName != null) {

        // correct common naming mistakes when getting resource bundles
        String requestedResourceBundleName = resourceBundleName;
        resourceBundleName = resourceBundleName.replaceAll("\\.properties$", "");
        resourceBundleName = resourceBundleName.replace('/', '.');

        if (!resourceBundleName.equals(requestedResourceBundleName)) {
            logger.info("Translated requested resource bundle name from '" + requestedResourceBundleName
                    + "' to '" + resourceBundleName + "'");
        }

        ResourceBundle rb = ResourceBundle.getBundle(resourceBundleName);

        for (Enumeration<String> keys = rb.getKeys(); keys.hasMoreElements();) {
            final String key = (String) keys.nextElement();
            final String value = rb.getString(key);

            props.put(key, value);
        }

    }

    return props;

}

From source file:com.alecgorge.minecraft.jsonapi.NanoHTTPD.java

/**
 * Decodes parameters in percent-encoded URI-format ( e.g.
 * "name=Jack%20Daniels&pass=Single%20Malt" ) and adds them to given
 * Properties. NOTE: this doesn't support multiple identical keys due to the
 * simplicity of Properties -- if you need multiples, you might want to
 * replace the Properties with a Hastable of Vectors or such.
 *///  ww  w. j  av a  2  s.c  om
public static void decodeParms(String parms, Properties p) {
    if (parms == null)
        return;

    StringTokenizer st = new StringTokenizer(parms, "&");
    while (st.hasMoreTokens()) {
        String e = st.nextToken();
        int sep = e.indexOf('=');
        if (sep >= 0)
            p.put(decodePercent(e.substring(0, sep)).trim(), decodePercent(e.substring(sep + 1)));
    }
}