Example usage for java.lang Boolean getBoolean

List of usage examples for java.lang Boolean getBoolean

Introduction

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

Prototype

public static boolean getBoolean(String name) 

Source Link

Document

Returns true if and only if the system property named by the argument exists and is equal to, ignoring case, the string "true" .

Usage

From source file:org.apache.geode.distributed.internal.membership.gms.membership.GMSJoinLeave.java

/**
 * attempt to join the distributed system loop send a join request to a locator & get a response
 * <p>/*from www .j a  v a2 s  .  co m*/
 * If the response indicates there's no coordinator it will contain a set of members that have
 * recently contacted it. The "oldest" member is selected as the coordinator based on ID sort
 * order.
 *
 * @return true if successful, false if not
 */
public boolean join() {

    try {
        if (Boolean.getBoolean(BYPASS_DISCOVERY_PROPERTY)) {
            synchronized (viewInstallationLock) {
                becomeCoordinator();
            }
            return true;
        }

        SearchState state = searchState;

        long locatorWaitTime = ((long) services.getConfig().getLocatorWaitTime()) * 1000L;
        long timeout = services.getConfig().getJoinTimeout();
        logger.debug("join timeout is set to {}", timeout);
        long retrySleep = JOIN_RETRY_SLEEP;
        long startTime = System.currentTimeMillis();
        long locatorGiveUpTime = startTime + locatorWaitTime;
        long giveupTime = startTime + timeout;

        for (int tries = 0; !this.isJoined && !this.isStopping; tries++) {
            logger.debug("searching for the membership coordinator");
            boolean found = findCoordinator();
            logger.debug("state after looking for membership coordinator is {}", state);
            if (found) {
                logger.debug("found possible coordinator {}", state.possibleCoordinator);
                if (localAddress.getNetMember().preferredForCoordinator()
                        && state.possibleCoordinator.equals(this.localAddress)) {
                    if (tries > 2 || System.currentTimeMillis() < giveupTime) {
                        synchronized (viewInstallationLock) {
                            becomeCoordinator();
                        }
                        return true;
                    }
                } else {
                    if (attemptToJoin()) {
                        return true;
                    }
                    if (!state.possibleCoordinator.equals(localAddress)) {
                        state.alreadyTried.add(state.possibleCoordinator);
                    }
                    if (System.currentTimeMillis() > giveupTime) {
                        break;
                    }
                }
            } else {
                long now = System.currentTimeMillis();
                if (state.locatorsContacted <= 0) {
                    if (now > locatorGiveUpTime) {
                        // break out of the loop and return false
                        break;
                    }
                    tries = 0;
                    giveupTime = now + timeout;
                } else if (now > giveupTime) {
                    break;
                }
            }
            try {
                if (found && !state.hasContactedAJoinedLocator) {
                    // if locators are restarting they may be handing out IDs from a stale view that
                    // we should go through quickly. Otherwise we should sleep a bit to let failure
                    // detection select a new coordinator
                    if (state.possibleCoordinator.getVmViewId() < 0) {
                        logger.debug("sleeping for {} before making another attempt to find the coordinator",
                                retrySleep);
                        Thread.sleep(retrySleep);
                    }
                    // since we were given a coordinator that couldn't be used we should keep trying
                    tries = 0;
                    giveupTime = System.currentTimeMillis() + timeout;
                }
            } catch (InterruptedException e) {
                logger.debug("retry sleep interrupted - giving up on joining the distributed system");
                return false;
            }
        } // for

        if (!this.isJoined) {
            logger.debug("giving up attempting to join the distributed system after "
                    + (System.currentTimeMillis() - startTime) + "ms");
        }

        // to preserve old behavior we need to throw a SystemConnectException if
        // unable to contact any of the locators
        if (!this.isJoined && state.hasContactedAJoinedLocator) {
            throw new SystemConnectException("Unable to join the distributed system in "
                    + (System.currentTimeMillis() - startTime) + "ms");
        }

        return this.isJoined;
    } finally {
        // notify anyone waiting on the address to be completed
        if (this.isJoined) {
            synchronized (this.localAddress) {
                this.localAddress.notifyAll();
            }
        }
        searchState.cleanup();
    }
}

From source file:fr.gael.dhus.database.DatabasePostInit.java

private boolean doForceReset() {
    // Case of user force reset requested.
    boolean force_reset = Boolean.getBoolean("Archive.forceReset");
    logger.info("Archives Reset (Archive.forceReset) " + "requested by user (" + force_reset + ")");
    if (!force_reset) {
        return false;
    }/*from  w  w w  .  ja v  a 2s .  c  om*/

    productDao.deleteAll();
    return true;
}

From source file:org.collectionspace.services.client.AbstractServiceClientImpl.java

@Override
public boolean isServerSecure() {
    return Boolean.getBoolean("cspace.server.secure");
}

From source file:fr.gael.dhus.database.DatabasePostInit.java

private boolean doProductReindex() {
    boolean force_reindex = Boolean.getBoolean("Archive.forceReindex");

    logger.info("Archives Reindex (Archive.forceReindex) " + "requested by user (" + force_reindex + ")");
    if (!force_reindex) {
        return false;
    }//from   w  w w.ja v  a2  s .  c  o m

    Iterator<Product> products = productDao.getAllProducts();
    while (products.hasNext()) {
        Product product = products.next();
        int retry = 10;
        while (retry > 0) {
            try {
                // Must read the product again because
                // ScrollableResultsIterator
                // use its own session.
                taskExecutor.execute(new IndexProductTask(productDao.read(product.getId())));
                retry = 0;
            } catch (RejectedExecutionException ree) {
                retry--;
                if (retry <= 0)
                    throw ree;
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    logger.warn("Current thread has interrupted by another", e);
                }
            }
        }
    }
    return true;
}

From source file:org.geotools.data.wms.test.LocalGeoServerOnlineTest.java

/**
 * Check GetMap request functionality in the provided CRS.
 * <p>/*  www  .  j a v a 2  s  .c  o m*/
 * Attempt is made to request the entire image.
 * 
 * @param wms
 * @param layer
 * @param crs
 */
private void checkGetMap(WebMapServer wms, Layer layer, CoordinateReferenceSystem crs) throws Exception {

    layer.clearCache();
    CRSEnvelope latLon = layer.getLatLonBoundingBox();
    GeneralEnvelope envelope = wms.getEnvelope(layer, crs);
    assertFalse(envelope.isEmpty() || envelope.isNull() || envelope.isInfinite());
    assertNotNull("Envelope " + CRS.toSRS(crs), envelope);

    GetMapRequest getMap = wms.createGetMapRequest();
    OperationType operationType = wms.getCapabilities().getRequest().getGetMap();

    getMap.addLayer(layer);
    String version = wms.getCapabilities().getVersion();

    getMap.setBBox(envelope);

    Properties properties = getMap.getProperties();
    String srs = null;
    if (properties.containsKey("SRS")) {
        srs = properties.getProperty("SRS");
    } else if (properties.containsKey("CRS")) {
        srs = properties.getProperty("CRS");
    }
    assertNotNull("setBBox supplied SRS information", srs);
    String expectedSRS = CRS.toSRS(envelope.getCoordinateReferenceSystem());
    assertEquals("srs matches CRS.toSRS", expectedSRS, srs);

    assertTrue("cite authority:" + srs, srs.contains("CRS") || srs.contains("EPSG"));

    //getMap.setSRS( srs );

    String format = format(operationType, "jpeg");
    getMap.setFormat(format);
    getMap.setDimensions(500, 500);

    URL url = getMap.getFinalURL();
    GetMapResponse response = wms.issueRequest(getMap);
    assertEquals("image/jpeg", response.getContentType());

    InputStream stream = response.getInputStream();
    BufferedImage image = ImageIO.read(stream);
    assertNotNull("jpeg", image);
    assertEquals(500, image.getWidth());
    assertEquals(500, image.getHeight());

    int rgb = image.getRGB(70, 420);
    Color sample = new Color(rgb);
    boolean forceXY = Boolean.getBoolean(GeoTools.FORCE_LONGITUDE_FIRST_AXIS_ORDER);
    String context = "srs=" + srs + " forceXY=" + forceXY + " Version=" + version;
    if (Color.WHITE.equals(sample)) {
        System.out.println("FAIL: " + context + ": GetMap BBOX=" + envelope);
        System.out.println("--> " + url);
        fail(context + ": GetMap BBOX=" + envelope);
    } else {
        //System.out.println("PASS: "+ context+": GetMap BBOX=" + bbox);
    }
}

From source file:com.athenahealth.api.APIConnection.java

/**
 * Make the API call.//from   ww  w  .  j a  va2  s .  co m
 *
 * This method abstracts away the connection, streams, and readers necessary to make an HTTP
 * request.  It also adds in the Authorization header and token.
 *
 * @param verb       HTTP method to use
 * @param path       URI to find
 * @param parameters key-value pairs of request parameters
 * @param headers    key-value pairs of request headers
 * @param secondcall true if this is the retried request
 * @return the JSON-decoded response
 *
 * @throws AthenahealthException If there is an error making the call.
 *                               API-level errors are reported in the return-value.
 */
private Object call(String verb, String path, Map<String, String> parameters, Map<String, String> headers,
        boolean secondcall) throws AthenahealthException {
    try {
        // Join up a url and open a connection
        URL url = new URL(path_join(getBaseURL(), version, practiceid, path));
        HttpURLConnection conn = openConnection(url);
        conn.setRequestMethod(verb);

        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        // Set the Authorization header using the token, then do the rest of the headers
        conn.setRequestProperty("Authorization", "Bearer " + token);
        if (headers != null) {
            for (Map.Entry<String, String> pair : headers.entrySet()) {
                conn.setRequestProperty(pair.getKey(), pair.getValue());
            }
        }

        // Set the request parameters, if there are any
        if (parameters != null) {
            conn.setDoOutput(true);
            Writer wr = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            wr.write(urlencode(parameters));
            wr.flush();
            wr.close();
        }

        // If we get a 401, retry once
        if (conn.getResponseCode() == 401 && !secondcall) {
            authenticate();
            return call(verb, path, parameters, headers, true);
        }

        // The API response is in the input stream on success and the error stream on failure.
        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        } catch (IOException e) {
            rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        }
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();

        String rawResponse = sb.toString();

        if (503 == conn.getResponseCode())
            throw new AthenahealthException("Service Temporarily Unavailable: " + rawResponse);

        if (!"application/json".equals(conn.getContentType()))
            throw new AthenahealthException("Expected application/json response, got " + conn.getContentType()
                    + " instead." + " Content=" + rawResponse);

        // If it won't parse as an object, it'll parse as an array.
        Object response;
        try {
            response = new JSONObject(rawResponse);
        } catch (JSONException e) {
            try {
                response = new JSONArray(rawResponse);
            } catch (JSONException e2) {
                if (Boolean.getBoolean("com.athenahealth.api.dump-response-on-JSON-error")) {
                    System.err.println("Server response code: " + conn.getResponseCode());
                    Map<String, List<String>> responseHeaders = conn.getHeaderFields();
                    for (Map.Entry<String, List<String>> header : responseHeaders.entrySet())
                        for (String value : header.getValue()) {
                            if (null == header.getKey() || "".equals(header.getKey()))
                                System.err.println("Status: " + value);
                            else
                                System.err.println(header.getKey() + "=" + value);
                        }
                }
                throw new AthenahealthException(
                        "Cannot parse response from server as JSONObject or JSONArray: " + rawResponse, e2);
            }
        }

        return response;
    } catch (MalformedURLException mue) {
        throw new AthenahealthException("Invalid URL", mue);
    } catch (IOException ioe) {
        throw new AthenahealthException("I/O error during call", ioe);
    }
}

From source file:com.partnet.automation.selenium.AbstractConfigurableDriverProvider.java

/**
 * Used to indicate whether or not a proxy should be used by default.
 * /*from w w  w.  j  a  va  2s. c o  m*/
 * @see #USE_PROXY_BY_DEFAULT
 * @return true if using proxy, false otherwise
 */
protected boolean useProxy() {
    boolean useProxy = true;
    String useProxyValue = System.getProperty(USE_PROXY_BY_DEFAULT);
    if (useProxyValue != null) {
        useProxy = Boolean.getBoolean(USE_PROXY_BY_DEFAULT);
        LOG.info("by default, useProxy: {}", useProxy);
    }
    return useProxy;
}

From source file:ddf.test.itests.AbstractIntegrationTest.java

protected Option[] configurePaxExam() {
    return options(logLevel(LogLevelOption.LogLevel.WARN), useOwnExamBundlesStartLevel(100),
            // increase timeout for CI environment
            systemTimeout(TimeUnit.MINUTES.toMillis(10)),
            when(Boolean.getBoolean("keepRuntimeFolder")).useOptions(keepRuntimeFolder()), cleanCaches(true));
}

From source file:org.jvnet.hudson.test.JenkinsRule.java

/**
 * Override to set up your specific external resource.
 * @throws Throwable if setup fails (which will disable {@code after}
 *//*  w  w  w  .ja v  a2  s. c  om*/
public void before() throws Throwable {
    if (Functions.isWindows()) {
        // JENKINS-4409.
        // URLConnection caches handles to jar files by default,
        // and it prevents delete temporary directories on Windows.
        // Disables caching here.
        // Though defaultUseCache is a static field,
        // its setter and getter are provided as instance methods.
        URLConnection aConnection = new File(".").toURI().toURL().openConnection();
        origDefaultUseCache = aConnection.getDefaultUseCaches();
        aConnection.setDefaultUseCaches(false);
    }

    // Not ideal (https://github.com/junit-team/junit/issues/116) but basically works.
    if (Boolean.getBoolean("ignore.random.failures")) {
        RandomlyFails rf = testDescription.getAnnotation(RandomlyFails.class);
        if (rf != null) {
            throw new AssumptionViolatedException("Known to randomly fail: " + rf.value());
        }
    }

    env = new TestEnvironment(testDescription);
    env.pin();
    recipe();
    AbstractProject.WORKSPACE.toString();
    User.clear();

    try {
        jenkins = hudson = newHudson();
    } catch (Exception e) {
        // if Hudson instance fails to initialize, it leaves the instance field non-empty and break all the rest of the tests, so clean that up.
        Field f = Jenkins.class.getDeclaredField("theInstance");
        f.setAccessible(true);
        f.set(null, null);
        throw e;
    }
    jenkins.setNoUsageStatistics(true); // collecting usage stats from tests are pointless.

    jenkins.setCrumbIssuer(new TestCrumbIssuer());

    jenkins.servletContext.setAttribute("app", jenkins);
    jenkins.servletContext.setAttribute("version", "?");
    WebAppMain.installExpressionFactory(new ServletContextEvent(jenkins.servletContext));

    // set a default JDK to be the one that the harness is using.
    jenkins.getJDKs().add(new JDK("default", System.getProperty("java.home")));

    configureUpdateCenter();

    // expose the test instance as a part of URL tree.
    // this allows tests to use a part of the URL space for itself.
    jenkins.getActions().add(this);

    JenkinsLocationConfiguration.get().setUrl(getURL().toString());

    setUpTimeout();
}

From source file:org.apache.zookeeper.server.quorum.auth.MiniKdc.java

/**
 * Set the System property; return the old value for caching.
 *
 * @param sysprop property/* ww  w  .  j a  v a 2 s.  c  o  m*/
 * @param debug true or false
 * @return the previous value
 */
private boolean getAndSet(String sysprop, String debug) {
    boolean old = Boolean.getBoolean(sysprop);
    System.setProperty(sysprop, debug);
    return old;
}