Example usage for java.lang Boolean parseBoolean

List of usage examples for java.lang Boolean parseBoolean

Introduction

In this page you can find the example usage for java.lang Boolean parseBoolean.

Prototype

public static boolean parseBoolean(String s) 

Source Link

Document

Parses the string argument as a boolean.

Usage

From source file:com.netflix.governator.configuration.PropertiesConfigurationProvider.java

@Override
public Property<Boolean> getBooleanProperty(final ConfigurationKey key, final Boolean defaultValue) {
    return new Property<Boolean>() {
        @Override//from w  ww  .j av  a2s.  co m
        public Boolean get() {
            String value = properties.getProperty(key.getKey(variableValues));
            if (value == null) {
                return defaultValue;
            }
            return Boolean.parseBoolean(value);
        }
    };
}

From source file:com.cerebro.provevaadin.smtp.ConfigurazioneSMTPSpring.java

public ConfigurazioneSMTPSpring() {

    TextField smtpHost = new TextField("SMTP Host Server");
    smtpHost.setRequired(true);/*from  w w  w . j  a v a2  s  . co  m*/
    TextField smtpPort = new TextField("SMTP Port");
    smtpPort.setRequired(true);
    TextField smtpUser = new TextField("SMTP Username");
    smtpUser.setRequired(true);
    PasswordField smtpPwd = new PasswordField("SMTP Password");
    smtpPwd.setRequired(true);
    PasswordField pwdConf = new PasswordField("Conferma la Password");
    pwdConf.setRequired(true);
    CheckBox security = new CheckBox("Sicurezza del server");

    Properties props = new Properties();
    InputStream config = VaadinServlet.getCurrent().getServletContext()
            .getResourceAsStream("/WEB-INF/config.properties");
    if (config != null) {
        System.out.println("Carico file di configurazione");
        try {
            props.load(config);
        } catch (IOException ex) {
            Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    smtpHost.setValue(props.getProperty("mail.smtp.host"));
    smtpUser.setValue(props.getProperty("smtp_user"));
    security.setValue(Boolean.parseBoolean(props.getProperty("smtp_sec")));

    Button salva = new Button("Salva i parametri");
    salva.addClickListener((Button.ClickEvent event) -> {
        System.out.println("Salvo i parametri SMTP");
        if (smtpHost.isValid() && smtpPort.isValid() && smtpUser.isValid() && smtpPwd.isValid()
                && smtpPwd.getValue().equals(pwdConf.getValue())) {
            System.out.println(smtpHost.getValue() + smtpPort.getValue() + smtpUser.getValue()
                    + smtpPwd.getValue() + security.getValue().toString());
            props.setProperty("mail.smtp.host", smtpHost.getValue());
            props.setProperty("mail.smtp.port", smtpPort.getValue());
            props.setProperty("smtp_user", smtpUser.getValue());
            props.setProperty("smtp_pwd", smtpPwd.getValue());
            props.setProperty("mail.smtp.ssl.enable", security.getValue().toString());
            String webInfPath = VaadinServlet.getCurrent().getServletConfig().getServletContext()
                    .getRealPath("WEB-INF");
            File f = new File(webInfPath + "/config.properties");
            try {
                OutputStream o = new FileOutputStream(f);
                try {
                    props.store(o, "Prova");
                } catch (IOException ex) {
                    Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
            }
            Notification.show("Parametri salvati");
        } else {
            Notification.show("Ricontrolla i parametri");
        }

    });

    TextField emailTest = new TextField("Destinatario Mail di Prova");
    emailTest.setImmediate(true);
    emailTest.addValidator(new EmailValidator("Mail non valida"));

    Button test = new Button("Invia una mail di prova");
    test.addClickListener((Button.ClickEvent event) -> {
        System.out.println("Invio della mail di prova");
        if (emailTest.isValid() && !emailTest.isEmpty()) {
            System.out.println("Invio mail di prova a " + emailTest.getValue());
            JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
            mailSender.setJavaMailProperties(props);
            mailSender.setUsername(props.getProperty("smtp_user"));
            mailSender.setPassword(props.getProperty("smtp_pwd"));
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            try {
                helper.setFrom("dottmatteocasagrande@gmail.com");
                helper.setSubject("Subject");
                helper.setText("It works!");
                helper.addTo(emailTest.getValue());
                mailSender.send(message);
            } catch (MessagingException ex) {
                Logger.getLogger(ConfigurazioneSMTPSpring.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {
            Notification.show("Controlla l'indirizzo mail del destinatario");
        }
    });

    this.addComponents(smtpHost, smtpPort, smtpUser, smtpPwd, pwdConf, security, salva, emailTest, test);

}

From source file:com.trigonic.utils.spring.beans.ImportBeanDefinitionParser.java

@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
    XmlReaderContext readerContext = parserContext.getReaderContext();
    String primaryLocation = element.getAttribute(RESOURCE_ATTRIBUTE);
    if (!StringUtils.hasText(primaryLocation)) {
        readerContext.error("Resource location must not be empty", element);
        return null;
    }/*from   w  w  w.  ja va2s.c om*/

    String alternateLocation = element.getAttribute(ALTERNATE_ATTRIBUTE);
    boolean optional = Boolean.parseBoolean(element.getAttribute(OPTIONAL_ATTRIBUTE));

    String currentLocation = primaryLocation;
    try {
        Set<Resource> actualResources = ImportHelper.importResource(readerContext.getReader(),
                readerContext.getResource(), currentLocation);

        if (actualResources.isEmpty() && StringUtils.hasLength(alternateLocation)) {
            currentLocation = alternateLocation;
            actualResources = ImportHelper.importResource(readerContext.getReader(),
                    readerContext.getResource(), currentLocation);
        }

        if (actualResources.isEmpty() && !optional) {
            readerContext.error("Primary location [" + primaryLocation + "]"
                    + (alternateLocation == null ? "" : " and alternate location [" + alternateLocation + "]")
                    + " are not optional", element);
            return null;
        }

        Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]);
        readerContext.fireImportProcessed(primaryLocation, actResArray, readerContext.extractSource(element));
    } catch (BeanDefinitionStoreException ex) {
        readerContext.error("Failed to import bean definitions from location [" + currentLocation + "]",
                element, ex);
    }

    return null;
}

From source file:code.google.nfs.rpc.mina.client.MinaClientFactory.java

protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key)
        throws Exception {
    if (isDebugEnabled) {
        LOGGER.debug("create connection to :" + targetIP + ":" + targetPort + ",timeout is:" + connectTimeout
                + ",key is:" + key);
    }/*  w ww  . ja  v  a  2 s .c o m*/
    SocketConnectorConfig cfg = new SocketConnectorConfig();
    cfg.setThreadModel(ThreadModel.MANUAL);
    if (connectTimeout > 1000) {
        cfg.setConnectTimeout((int) connectTimeout / 1000);
    } else {
        cfg.setConnectTimeout(1);
    }
    cfg.getSessionConfig()
            .setTcpNoDelay(Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")));
    cfg.getFilterChain().addLast("objectserialize", new MinaProtocolCodecFilter());
    SocketAddress targetAddress = new InetSocketAddress(targetIP, targetPort);
    MinaClientProcessor processor = new MinaClientProcessor(this, key);
    ConnectFuture connectFuture = ioConnector.connect(targetAddress, null, processor, cfg);
    // wait for connection established
    connectFuture.join();

    IoSession ioSession = connectFuture.getSession();
    if ((ioSession == null) || (!ioSession.isConnected())) {
        String targetUrl = targetIP + ":" + targetPort;
        LOGGER.error("create connection error,targetaddress is " + targetUrl);
        throw new Exception("create connection error,targetaddress is " + targetUrl);
    }
    if (isDebugEnabled) {
        LOGGER.debug("create connection to :" + targetIP + ":" + targetPort + ",timeout is:" + connectTimeout
                + ",key is:" + key + " successed");
    }
    MinaClient client = new MinaClient(ioSession, key, connectTimeout);
    processor.setClient(client);
    return client;
}

From source file:lu.list.itis.dkd.aig.SimilarityProvider.java

/**
 * Constructor initialising the comparator from properties read from a properties file.
 *
 * @throws ExceptionInInitializerError//from  ww w.  j ava2s.co  m
 */
private SimilarityProvider() throws ExceptionInInitializerError {
    final Properties properties = PropertiesFetcher.getProperties();

    if (properties.isEmpty()) {
        throw new ExceptionInInitializerError("The properties file could not be located!"); //$NON-NLS-1$
    }

    useSemanticSimilarity = Boolean.parseBoolean(
            properties.getProperty(Externalization.SEMANTIC_SIMILARITY_PROPERTY, Externalization.FALSE_STRING));
    useStringSimilarity = Boolean.parseBoolean(
            properties.getProperty(Externalization.STRING_SIMILARITY_PROPERTY, Externalization.FALSE_STRING));
    useSoundexSimilarity = Boolean.parseBoolean(
            properties.getProperty(Externalization.SOUNDEX_SIMILARITY_PROPERTY, Externalization.FALSE_STRING));

    semanticSimilarityWeight = Float.parseFloat(properties
            .getProperty(Externalization.SEMANTIC_SIMILARITY_WEIGHT_PROPERTY, Externalization.ZERO_INTEGER));
    stringSimilarityWeight = Float.parseFloat(properties
            .getProperty(Externalization.STRING_SIMILARITY_WEIGHT_PROPERTY, Externalization.ZERO_INTEGER));
    soundexSimilarityWeight = Float.parseFloat(properties
            .getProperty(Externalization.SOUNDEX_SIMILARITY_WEIGHT_PROPERTY, Externalization.ZERO_INTEGER));

    if (useSemanticSimilarity) {
        throw new NotImplementedException("semantic similarity not yet available");
        //instantiateSemanticSimilarityBridge();
    }
}

From source file:de.blizzy.backup.BackupPlugin.java

boolean isCheckGui() {
    return Boolean.parseBoolean(
            StringUtils.defaultString(getApplicationArg(ARG_CHECK_GUI), Boolean.FALSE.toString()));
}

From source file:infrascructure.data.parse.PlainDocsRepository.java

@Override
public void readAll() throws IOException {
    Boolean parse = Boolean.parseBoolean(config.getProperty(Config.PARSE_DOCS_NOW, "true"));
    if (!parse) {
        Trace.trace("Property " + Config.PARSE_DOCS_NOW + " is false. Parsing disabled.");
        return;/*from   w  ww. j  av  a  2  s.c  o m*/
    }
    int resourceId = docs.size();
    while (docs.size() < required_docs_count) {
        ResourceMetaData resource = resourcesRepository.get(resourceId++);
        if (resource == null) {
            Trace.trace("Resource is null. Trying next ...");
            continue;
        }
        PlainTextResource data = parser.parse(resource);
        Tag[] tags = new Tag[] { resource.getTag(Tags.URL), new Tag(Tags.TITLE, data.getTittle()) };
        ResourceMetaData resourceMetaData = new ResourceMetaData(resourceId, data.getData(), tags);

        boolean added = addData(resourceMetaData);
        onAdded(resourceId, added);
    }

}

From source file:edu.cmu.cs.lti.ark.fn.identification.FrameIdentificationRelease.java

public static TObjectDoubleHashMap<String> readOldModel(String idParamsFile) throws IOException {
    TObjectDoubleHashMap<String> params = new TObjectDoubleHashMap<String>();
    int count = 0;
    String line;/*from  www .ja  v a2  s . co  m*/
    final BufferedReader input = Files.newReader(new File(idParamsFile), Charsets.UTF_8);
    try {
        while ((line = input.readLine()) != null) {
            final String[] nameAndVal = line.split("\t");
            final String[] logAndSign = nameAndVal[1].split(", ");
            final double value = exp(Double.parseDouble(logAndSign[0]));
            final double sign = Boolean.parseBoolean(logAndSign[1]) ? 1.0 : -1.0;
            params.put(nameAndVal[0], value * sign);
            count++;
            if (count % 100000 == 0)
                System.err.print(count + " ");
        }
    } finally {
        closeQuietly(input);
    }
    return params;
}

From source file:com.redhat.coolstore.api_gateway.CartGateway.java

@Override
public void configure() throws Exception {
    try {/*from  w w  w  . j av a2 s . com*/
        getContext().setTracing(Boolean.parseBoolean(env.getProperty("ENABLE_TRACER", "false")));
    } catch (Exception e) {
        LOG.error("Failed to parse the ENABLE_TRACER value: {}", env.getProperty("ENABLE_TRACER", "false"));
    }

    JacksonDataFormat productFormatter = new ListJacksonDataFormat();
    productFormatter.setUnmarshalType(Product.class);

    restConfiguration().component("servlet").bindingMode(RestBindingMode.auto).apiContextPath("/api-docs")
            .contextPath("/api").apiProperty("host", "")
            .apiProperty("api.title", "CoolStore Microservice API Gateway").apiProperty("api.version", "1.0.0")
            .apiProperty("api.description",
                    "The API of the gateway which fronts the various backend microservices in the CoolStore")
            .apiProperty("api.contact.name", "Red Hat Developers")
            .apiProperty("api.contact.email", "developers@redhat.com")
            .apiProperty("api.contact.url", "https://developers.redhat.com");

    rest("/cart/").description("Personal Shopping Cart Service").produces(MediaType.APPLICATION_JSON_VALUE)

            // Handle CORS Preflight requests
            .options("/{cartId}").route().id("getCartOptionsRoute").end().endRest()
            .options("/checkout/{cartId}").route().id("checkoutCartOptionsRoute").end().endRest()
            .options("/{cartId}/{tmpId}").route().id("cartSetOptionsRoute").end().endRest()
            .options("/{cartId}/{itemId}/{quantity}").route().id("cartAddDeleteOptionsRoute").end().endRest()

            .post("/checkout/{cartId}").description("Finalize shopping cart and process payment").param()
            .name("cartId").type(RestParamType.path).description("The ID of the cart to process")
            .dataType("string").endParam().outType(ShoppingCart.class).route().id("checkoutRoute").hystrix()
            .id("Cart Service (Checkout Cart)").hystrixConfiguration()
            .executionTimeoutInMilliseconds(hystrixExecutionTimeout).groupKey(hystrixGroupKey)
            .circuitBreakerEnabled(hystrixCircuitBreakerEnabled).end().removeHeaders("CamelHttp*")
            .setBody(simple("null")).setHeader(Exchange.HTTP_METHOD, HttpMethods.POST)
            .setHeader(Exchange.HTTP_URI,
                    simple("http://{{env:CART_ENDPOINT:cart:8080}}/api/cart/checkout/${header.cartId}"))
            .to("http4://DUMMY").onFallback()
            //.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(Response.Status.SERVICE_UNAVAILABLE.getStatusCode()))
            .setHeader(Exchange.CONTENT_TYPE, constant("application/json")).to("direct:defaultFallback").end()
            .setHeader("CamelJacksonUnmarshalType", simple(ShoppingCart.class.getName())).unmarshal()
            .json(JsonLibrary.Jackson, ShoppingCart.class).endRest()

            .get("/{cartId}").description("Get the current user's shopping cart content").param().name("cartId")
            .type(RestParamType.path).description("The ID of the cart to process").dataType("string").endParam()
            .outType(ShoppingCart.class).route().id("getCartRoute").hystrix().id("Cart Service (Get Cart)")
            .hystrixConfiguration().executionTimeoutInMilliseconds(hystrixExecutionTimeout)
            .groupKey(hystrixGroupKey).circuitBreakerEnabled(hystrixCircuitBreakerEnabled).end()
            .removeHeaders("CamelHttp*").setBody(simple("null"))
            .setHeader(Exchange.HTTP_METHOD, HttpMethods.GET)
            .setHeader(Exchange.HTTP_URI,
                    simple("http://{{env:CART_ENDPOINT:cart:8080}}/api/cart/${header.cartId}"))
            .to("http4://DUMMY").onFallback()
            //.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(Response.Status.SERVICE_UNAVAILABLE.getStatusCode()))
            .setHeader(Exchange.CONTENT_TYPE, constant("application/json")).to("direct:defaultFallback").end()
            .setHeader("CamelJacksonUnmarshalType", simple(ShoppingCart.class.getName())).unmarshal()
            .json(JsonLibrary.Jackson, ShoppingCart.class).endRest()

            .delete("/{cartId}/{itemId}/{quantity}")
            .description("Delete items from current user's shopping cart").param().name("cartId")
            .type(RestParamType.path).description("The ID of the cart to process").dataType("string").endParam()
            .param().name("itemId").type(RestParamType.path).description("The ID of the item to delete")
            .dataType("string").endParam().param().name("quantity").type(RestParamType.path)
            .description("The number of items to delete").dataType("integer").endParam()
            .outType(ShoppingCart.class).route().id("deleteFromCartRoute").hystrix()
            .id("Cart Service (Delete Cart)").hystrixConfiguration()
            .executionTimeoutInMilliseconds(hystrixExecutionTimeout).groupKey(hystrixGroupKey)
            .circuitBreakerEnabled(hystrixCircuitBreakerEnabled).end().removeHeaders("CamelHttp*")
            .setBody(simple("null")).setHeader(Exchange.HTTP_METHOD, HttpMethods.DELETE)
            .setHeader(Exchange.HTTP_URI, simple(
                    "http://{{env:CART_ENDPOINT:cart:8080}}/api/cart/${header.cartId}/${header.itemId}/${header.quantity}"))
            .to("http4://DUMMY").onFallback()
            //.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(Response.Status.SERVICE_UNAVAILABLE.getStatusCode()))
            .setHeader(Exchange.CONTENT_TYPE, constant("application/json")).to("direct:defaultFallback").end()
            .setHeader("CamelJacksonUnmarshalType", simple(ShoppingCart.class.getName())).unmarshal()
            .json(JsonLibrary.Jackson, ShoppingCart.class).endRest()

            .post("/{cartId}/{itemId}/{quantity}").description("Add items from current user's shopping cart")
            .param().name("cartId").type(RestParamType.path).description("The ID of the cart to process")
            .dataType("string").endParam().param().name("itemId").type(RestParamType.path)
            .description("The ID of the item to add").dataType("string").endParam().param().name("quantity")
            .type(RestParamType.path).description("The number of items to add").dataType("integer").endParam()
            .outType(ShoppingCart.class).route().id("addToCartRoute").hystrix().id("Cart Service (Add To Cart)")
            .hystrixConfiguration().executionTimeoutInMilliseconds(hystrixExecutionTimeout)
            .groupKey(hystrixGroupKey).circuitBreakerEnabled(hystrixCircuitBreakerEnabled).end()
            .removeHeaders("CamelHttp*").setBody(simple("null"))
            .setHeader(Exchange.HTTP_METHOD, HttpMethods.POST)
            .setHeader(Exchange.HTTP_URI, simple(
                    "http://{{env:CART_ENDPOINT:cart:8080}}/api/cart/${header.cartId}/${header.itemId}/${header.quantity}"))
            .to("http4://DUMMY").onFallback()
            //.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(Response.Status.SERVICE_UNAVAILABLE.getStatusCode()))
            .setHeader(Exchange.CONTENT_TYPE, constant("application/json")).to("direct:defaultFallback").end()
            .setHeader("CamelJacksonUnmarshalType", simple(ShoppingCart.class.getName())).unmarshal()
            .json(JsonLibrary.Jackson, ShoppingCart.class).endRest()

            .post("/{cartId}/{tmpId}").description("Transfer temp shopping items to user's cart").param()
            .name("cartId").type(RestParamType.path).description("The ID of the cart to process")
            .dataType("string").endParam().param().name("tmpId").type(RestParamType.path)
            .description("The ID of the temp cart to transfer").dataType("string").endParam()
            .outType(ShoppingCart.class).route().id("setCartRoute").hystrix().id("Cart Service (Set Cart)")
            .hystrixConfiguration().executionTimeoutInMilliseconds(hystrixExecutionTimeout)
            .groupKey(hystrixGroupKey).circuitBreakerEnabled(hystrixCircuitBreakerEnabled).end()
            .removeHeaders("CamelHttp*").setBody(simple("null"))
            .setHeader(Exchange.HTTP_METHOD, HttpMethods.POST)
            .setHeader(Exchange.HTTP_URI,
                    simple("http://{{env:CART_ENDPOINT:cart:8080}}/api/cart/${header.cartId}/${header.tmpId}"))
            .to("http4://DUMMY").onFallback()
            //.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(Response.Status.SERVICE_UNAVAILABLE.getStatusCode()))
            .setHeader(Exchange.CONTENT_TYPE, constant("application/json")).to("direct:defaultFallback").end()
            .setHeader("CamelJacksonUnmarshalType", simple(ShoppingCart.class.getName())).unmarshal()
            .json(JsonLibrary.Jackson, ShoppingCart.class).endRest();

    // Provide a response
    from("direct:defaultFallback").routeId("defaultfallback").description("Default Fall back response response")
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    exchange.getIn().setBody(new ShoppingCart());
                }
            }).marshal().json(JsonLibrary.Jackson);

}

From source file:org.apache.hadoop.gateway.hive.HiveHttpClientDispatch.java

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    super.init(filterConfig);
    String basicAuthPreemptiveString = filterConfig.getInitParameter(BASIC_AUTH_PREEMPTIVE_PARAM);
    if (basicAuthPreemptiveString != null) {
        setBasicAuthPreemptive(Boolean.parseBoolean(basicAuthPreemptiveString));
    }/*from  w  w w  .j  a  v  a 2  s .  c o m*/
}