Example usage for java.lang Integer getInteger

List of usage examples for java.lang Integer getInteger

Introduction

In this page you can find the example usage for java.lang Integer getInteger.

Prototype

public static Integer getInteger(String nm, Integer val) 

Source Link

Document

Returns the integer value of the system property with the specified name.

Usage

From source file:io.adeptj.runtime.server.Server.java

private int sessionTimeout(Config cfg) {
    return Integer.getInteger(SYS_PROP_SESSION_TIMEOUT, cfg.getInt(KEY_SESSION_TIMEOUT));
}

From source file:org.openqa.selenium.server.ProxyHandler.java

protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port,
        int timeoutMS) throws IOException {
    try {// w  w  w . j a va  2  s .c  om
        Socket socket = null;
        InputStream in = null;

        String chained_proxy_host = System.getProperty("http.proxyHost");
        if (chained_proxy_host == null) {
            socket = new Socket(iaddr, port);
            socket.setSoTimeout(timeoutMS);
            socket.setTcpNoDelay(true);
        } else {
            int chained_proxy_port = Integer.getInteger("http.proxyPort", 8888).intValue();

            Socket chain_socket = new Socket(chained_proxy_host, chained_proxy_port);
            chain_socket.setSoTimeout(timeoutMS);
            chain_socket.setTcpNoDelay(true);
            if (log.isDebugEnabled())
                log.debug("chain proxy socket=" + chain_socket);

            LineInput line_in = new LineInput(chain_socket.getInputStream());
            byte[] connect = request.toString().getBytes(org.openqa.jetty.util.StringUtil.__ISO_8859_1);
            chain_socket.getOutputStream().write(connect);

            String chain_response_line = line_in.readLine();
            HttpFields chain_response = new HttpFields();
            chain_response.read(line_in);

            // decode response
            int space0 = chain_response_line.indexOf(' ');
            if (space0 > 0 && space0 + 1 < chain_response_line.length()) {
                int space1 = chain_response_line.indexOf(' ', space0 + 1);

                if (space1 > space0) {
                    int code = Integer.parseInt(chain_response_line.substring(space0 + 1, space1));

                    if (code >= 200 && code < 300) {
                        socket = chain_socket;
                        in = line_in;
                    } else {
                        Enumeration iter = chain_response.getFieldNames();
                        while (iter.hasMoreElements()) {
                            String name = (String) iter.nextElement();
                            if (!_DontProxyHeaders.containsKey(name)) {
                                Enumeration values = chain_response.getValues(name);
                                while (values.hasMoreElements()) {
                                    String value = (String) values.nextElement();
                                    response.setField(name, value);
                                }
                            }
                        }
                        response.sendError(code);
                        if (!chain_socket.isClosed())
                            chain_socket.close();
                    }
                }
            }
        }

        if (socket == null)
            return null;
        return new HttpTunnel(socket, in, null);
    } catch (IOException e) {
        log.debug(e);
        response.sendError(HttpResponse.__400_Bad_Request);
        return null;
    }
}

From source file:com.ivanbratoev.festpal.datamodel.db.external.ExternalDatabaseHandler.java

/**
 * @param festivalExternalID external id of the festival
 * @return number of voters after vote or -1 on fail
 * @throws ClientDoesNotHavePermissionException
 *//*from  w w  w  .  j  a  v  a2  s  .  c  om*/
public int vote(int festivalExternalID) throws ClientDoesNotHavePermissionException {
    try {
        URL url = new URL(ExternalDatabaseHelper.getVote());
        Map<String, String> parameters = new HashMap<>();
        parameters.put(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_ID,
                String.valueOf(festivalExternalID));
        String response = getRemoteData(url, parameters);

        if (response == null || ExternalDatabaseDefinitions.RESPONSE_INVALID_FESTIVAL_ID.equals(response))
            return -1;
        return Integer.getInteger(response, -1);
    } catch (MalformedURLException ignore) {
        return -1;
    }
}

From source file:org.akubraproject.txn.derby.TestTransactionalStore.java

/**
 * Stress test the stuff a bit.//from   w  ww. ja va2  s.co m
 */
@Test(groups = { "blobs" }, dependsOnGroups = { "init" })
public void stressTest() throws Exception {
    // get our config
    final int numFillers = Integer.getInteger("akubra.txn.test.numFillers", 0);
    final int numReaders = Integer.getInteger("akubra.txn.test.numReaders", 10);
    final int numWriters = Integer.getInteger("akubra.txn.test.numWriters", 10);
    final int numObjects = Integer.getInteger("akubra.txn.test.numObjects", 10);
    final int numRounds = Integer.getInteger("akubra.txn.test.numRounds", 10);

    long t0 = System.currentTimeMillis();

    // "fill" the db a bit
    for (int b = 0; b < numFillers / 1000; b++) {
        final int start = b * 1000;

        doInTxn(new ConAction() {
            public void run(BlobStoreConnection con) throws Exception {
                for (int idx = start; idx < start + 1000; idx++) {
                    Blob b = con.getBlob(URI.create("urn:blobStressTestFiller" + idx), null);
                    setBody(b, "v" + idx);
                }
            }
        }, true);
    }

    long t1 = System.currentTimeMillis();

    // set up
    Thread[] writers = new Thread[numWriters];
    Thread[] readers = new Thread[numReaders];
    boolean[] failed = new boolean[] { false };

    final boolean[] testDone = new boolean[] { false };
    final int[] lowIds = new int[numWriters];
    final int[] highId = new int[] { 0 };

    // start/run the writers
    for (int t = 0; t < writers.length; t++) {
        final int tid = t;
        final int start = t * numRounds * numObjects;

        writers[t] = doInThread(new ERunnable() {
            @Override
            public void erun() throws Exception {
                for (int r = 0; r < numRounds; r++) {
                    final int off = start + r * numObjects;

                    doInTxn(new ConAction() {
                        public void run(BlobStoreConnection con) throws Exception {
                            for (int o = 0; o < numObjects; o++) {
                                int idx = off + o;
                                URI id = URI.create("urn:blobStressTest" + idx);
                                String val = "v" + idx;

                                Blob b = getBlob(con, id, null);
                                createBlob(con, b, val);
                            }
                        }
                    }, true);

                    synchronized (testDone) {
                        highId[0] = Math.max(highId[0], off + numObjects);
                    }

                    doInTxn(new ConAction() {
                        public void run(BlobStoreConnection con) throws Exception {
                            for (int o = 0; o < numObjects; o++) {
                                int idx = off + o;
                                URI id = URI.create("urn:blobStressTest" + idx);
                                String val = "v" + idx;

                                Blob b = getBlob(con, id, val);
                                deleteBlob(con, b);
                            }
                        }
                    }, true);

                    synchronized (testDone) {
                        lowIds[tid] = off + numObjects;
                    }
                }
            }
        }, failed);
    }

    // start/run the readers
    for (int t = 0; t < readers.length; t++) {
        readers[t] = doInThread(new ERunnable() {
            @Override
            public void erun() throws Exception {
                final Random rng = new Random();
                final int[] found = new int[] { 0 };

                while (true) {
                    final int low, high;
                    synchronized (testDone) {
                        if (testDone[0])
                            break;

                        high = highId[0];

                        int tmp = Integer.MAX_VALUE;
                        for (int id : lowIds)
                            tmp = Math.min(tmp, id);
                        low = tmp;
                    }

                    if (low == high) {
                        Thread.yield();
                        continue;
                    }

                    doInTxn(new ConAction() {
                        public void run(BlobStoreConnection con) throws Exception {
                            for (int o = 0; o < numObjects; o++) {
                                int idx = rng.nextInt(high - low) + low;
                                URI id = URI.create("urn:blobStressTest" + idx);
                                String val = "v" + idx;

                                Blob b = con.getBlob(id, null);
                                if (b.exists()) {
                                    assertEquals(getBody(b), val);
                                    found[0]++;
                                }
                            }
                        }
                    }, true);
                }

                if (found[0] == 0)
                    System.out.println("Warning: this reader found no blobs");
            }
        }, failed);
    }

    // wait for things to end
    for (int t = 0; t < writers.length; t++)
        writers[t].join();

    synchronized (testDone) {
        testDone[0] = true;
    }

    for (int t = 0; t < readers.length; t++)
        readers[t].join();

    long t2 = System.currentTimeMillis();

    // remove the fillers again
    for (int b = 0; b < numFillers / 1000; b++) {
        final int start = b * 1000;

        doInTxn(new ConAction() {
            public void run(BlobStoreConnection con) throws Exception {
                for (int idx = start; idx < start + 1000; idx++)
                    con.getBlob(URI.create("urn:blobStressTestFiller" + idx), null).delete();
            }
        }, true);
    }

    long t3 = System.currentTimeMillis();

    System.out.println("Time to create " + numFillers + " fillers: " + ((t1 - t0) / 1000.) + " s");
    System.out.println("Time to remove " + numFillers + " fillers: " + ((t3 - t2) / 1000.) + " s");
    System.out.println("Time to run test (" + numWriters + "/" + numRounds + "/" + numObjects + "): "
            + ((t2 - t1) / 1000.) + " s");

    assertFalse(failed[0]);
}

From source file:com.smartsheet.api.internal.AbstractResources.java

int getResponseLogLength() {
    // not cached to allow for it to be changed dynamically by client code
    return Integer.getInteger(PROPERTY_RESPONSE_LOG_CHARS, 1024);
}

From source file:org.apache.geode.internal.cache.Oplog.java

private static ByteBuffer allocateWriteBuf(OplogFile prevOlf) {
    if (prevOlf != null && prevOlf.writeBuf != null) {
        ByteBuffer result = prevOlf.writeBuf;
        prevOlf.writeBuf = null;//from  w ww. jav  a2s . co m
        return result;
    } else {
        return ByteBuffer.allocateDirect(Integer.getInteger("WRITE_BUF_SIZE", 32768));
    }
}

From source file:org.apache.geode.internal.cache.GemFireCacheImpl.java

/**
 * Perform initialization, solve the early escaped reference problem by putting publishing
 * references to this instance in this method (vs. the constructor).
 *///from   w ww .j a  v  a2  s.  c  om
private void initialize() {
    if (GemFireCacheImpl.instance != null) {
        Assert.assertTrue(GemFireCacheImpl.instance == null, "Cache instance already in place: " + instance);
    }
    GemFireCacheImpl.instance = this;
    GemFireCacheImpl.pdxInstance = this;

    for (Iterator<CacheLifecycleListener> iter = cacheLifecycleListeners.iterator(); iter.hasNext();) {
        CacheLifecycleListener listener = (CacheLifecycleListener) iter.next();
        listener.cacheCreated(this);
    }

    ClassPathLoader.setLatestToDefault();

    // request and check cluster configuration
    ConfigurationResponse configurationResponse = requestSharedConfiguration();
    deployJarsRecevedFromClusterConfiguration(configurationResponse);

    // apply the cluster's properties configuration and initialize security using that configuration
    ClusterConfigurationLoader.applyClusterPropertiesConfiguration(this, configurationResponse,
            system.getConfig());

    // first initialize the security service using the security properties
    securityService.initSecurity(system.getConfig().getSecurityProps());
    // secondly if cacheConfig has a securityManager, use that instead
    if (cacheConfig.getSecurityManager() != null) {
        securityService.setSecurityManager(cacheConfig.getSecurityManager());
    }
    // if cacheConfig has a postProcessor, use that instead
    if (cacheConfig.getPostProcessor() != null) {
        securityService.setPostProcessor(cacheConfig.getPostProcessor());
    }

    SystemMemberCacheEventProcessor.send(this, Operation.CACHE_CREATE);
    this.resourceAdvisor.initializationGate();

    // Register function that we need to execute to fetch available REST service endpoints in DS
    FunctionService.registerFunction(new FindRestEnabledServersFunction());

    // moved this after initializeDeclarativeCache because in the future
    // distributed system creation will not happen until we have read
    // cache.xml file.
    // For now this needs to happen before cache.xml otherwise
    // we will not be ready for all the events that cache.xml
    // processing can deliver (region creation, etc.).
    // This call may need to be moved inside initializeDeclarativeCache.
    /** Entry to GemFire Management service **/
    this.jmxAdvisor.initializationGate();

    // this starts up the ManagementService, register and federate the internal beans
    system.handleResourceEvent(ResourceEvent.CACHE_CREATE, this);

    boolean completedCacheXml = false;

    initializeServices();

    try {
        // Deploy all the jars from the deploy working dir.
        new JarDeployer(this.system.getConfig().getDeployWorkingDir()).loadPreviouslyDeployedJars();
        ClusterConfigurationLoader.applyClusterXmlConfiguration(this, configurationResponse,
                system.getConfig());
        initializeDeclarativeCache();
        completedCacheXml = true;
    } finally {
        if (!completedCacheXml) {
            // so initializeDeclarativeCache threw an exception
            try {
                close(); // fix for bug 34041
            } catch (Throwable ignore) {
                // I don't want init to throw an exception that came from the close.
                // I want it to throw the original exception that came from initializeDeclarativeCache.
            }
        }
    }

    this.clientpf = null;

    startColocatedJmxManagerLocator();

    startMemcachedServer();

    startRedisServer();

    startRestAgentServer(this);

    int time = Integer.getInteger(DistributionConfig.GEMFIRE_PREFIX + "CLIENT_FUNCTION_TIMEOUT",
            DEFAULT_CLIENT_FUNCTION_TIMEOUT);
    clientFunctionTimeout = time >= 0 ? time : DEFAULT_CLIENT_FUNCTION_TIMEOUT;

    isInitialized = true;
}

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

@Override
public void init(Services s) {
    this.services = s;

    DistributionConfig dc = services.getConfig().getDistributionConfig();
    if (dc.getMcastPort() != 0 && StringUtils.isBlank(dc.getLocators())
            && StringUtils.isBlank(dc.getStartLocator())) {
        throw new GemFireConfigException("Multicast cannot be configured for a non-distributed cache."
                + "  Please configure the locator services for this cache using " + LOCATORS + " or "
                + START_LOCATOR + ".");
    }/* w  ww.  jav  a 2  s . c om*/

    services.getMessenger().addHandler(JoinRequestMessage.class, this);
    services.getMessenger().addHandler(JoinResponseMessage.class, this);
    services.getMessenger().addHandler(InstallViewMessage.class, this);
    services.getMessenger().addHandler(ViewAckMessage.class, this);
    services.getMessenger().addHandler(LeaveRequestMessage.class, this);
    services.getMessenger().addHandler(RemoveMemberMessage.class, this);
    services.getMessenger().addHandler(FindCoordinatorRequest.class, this);
    services.getMessenger().addHandler(FindCoordinatorResponse.class, this);
    services.getMessenger().addHandler(NetworkPartitionMessage.class, this);

    int ackCollectionTimeout = dc.getMemberTimeout() * 2 * 12437 / 10000;
    if (ackCollectionTimeout < 1500) {
        ackCollectionTimeout = 1500;
    } else if (ackCollectionTimeout > 12437) {
        ackCollectionTimeout = 12437;
    }
    ackCollectionTimeout = Integer
            .getInteger(DistributionConfig.GEMFIRE_PREFIX + "VIEW_ACK_TIMEOUT", ackCollectionTimeout)
            .intValue();
    this.viewAckTimeout = ackCollectionTimeout;

    this.quorumRequired = services.getConfig().getDistributionConfig().getEnableNetworkPartitionDetection();

    DistributionConfig dconfig = services.getConfig().getDistributionConfig();
    String bindAddr = dconfig.getBindAddress();
    locators = GMSUtil.parseLocators(dconfig.getLocators(), bindAddr);
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient.java

/**
 * Download the file described by spec to the destination stream or streams.
 * <p>// ww  w  .  j  a  v  a2 s.c om
 * <h3>Notice:</h3>
 * <p>
 * This method can only recover from transient network problems (TCP socket
 * resets) if all {@link DownloadOutput}s support stream reset. Download
 * proxy connect errors do not require output stream reset because not data
 * will have been written to them yet.
 * <p>
 * The output streams are always left open (they may have been reset, but no
 * effort is made to finally close them), even when an exception is thrown.
 *
 * @param spec
 *        the spec that describes the file to download (must not be
 *        <code>null</code>)
 * @param outputs
 *        the outputs where the downloaded data will be written (must not be
 *        <code>null</code> or empty)
 * @param eventSource
 *        a custom {@link EventSource} or <code>null</code> to use
 *        {@link EventSource#newFromHere()}
 * @param taskMonitor
 *        a custom {@link TaskMonitor} or <code>null</code> to use the
 *        monitor from the {@link TaskMonitorService}
 * @throws CanceledException
 *         if the download was cancelled by the user via core's
 *         {@link TaskMonitor}. The output streams may have had some data
 *         written to them.
 */
public void downloadFileToStreams(final DownloadSpec spec, final DownloadOutput[] outputs,
        EventSource eventSource, final TaskMonitor taskMonitor) throws CanceledException {
    Check.notNull(spec, "spec"); //$NON-NLS-1$
    Check.notNullOrEmpty(outputs, "outputs"); //$NON-NLS-1$

    final int maxRetry = Integer.getInteger(MAX_REQUEST_RETRY_PROPERTY, MAX_REQUEST_RETRY_DEFAULT);

    if (eventSource == null) {
        eventSource = EventSource.newFromHere();
    }

    /*
     * This method aims to be tolerant of connection resets caused by
     * half-open sockets. It detects them and retries the operation once.
     * See the full notes in
     * com.microsoft.tfs.core.ws.runtime.client.SOAPService
     * #executeSOAPRequest about why this can happen when talking to IIS.
     *
     * Some JREs use the string "Connection reset by peer", others use
     * "Connection reset". We will match both.
     *
     * As soon as an exception is caught, we remember that we had that type
     * of exception, then let the loop retry. Second time we hit that same
     * exception we throw it.
     *
     * Also retry when when the download proxy is unavailable.
     */

    boolean hadDownloadProxyException = false;
    boolean hadSocketException = false;

    for (int retryCount = 1; retryCount <= maxRetry; retryCount++) {
        log.info("File download attempt " + retryCount); //$NON-NLS-1$

        try {
            // Don't reset for proxy error; no data would have been written
            if (hadSocketException) {
                resetOutputs(outputs);
            }

            downloadFileToStreamsInternal(spec, outputs, taskMonitor);

            /*
             * This breaks from the loop in the success case.
             */
            return;
        } catch (final SocketException e) {
            log.warn("SocketException for " + spec.getQueryString(), e); //$NON-NLS-1$
            /*
             * If this fault was not a TCP connection reset, rethrow it.
             * Weeds out non-retryable socket exceptions.
             */
            if (!e.getMessage().startsWith("Connection reset")) //$NON-NLS-1$
            {
                throw new VersionControlException(e);
            }

            if (retryCount == maxRetry) {
                log.warn(MessageFormat.format("Max retry reached {0}, not trying any longer", //$NON-NLS-1$
                        spec.getQueryString()));
                throw new VersionControlException(e);
            } else {
                hadSocketException = true;
            }

            log.warn(
                    MessageFormat.format("Retrying download after a connection reset for {0}", //$NON-NLS-1$
                            spec.getQueryString()), e);
        } catch (final SocketTimeoutException e) {
            log.warn("SocketTimeoutException for " + spec.getQueryString(), e); //$NON-NLS-1$

            if (retryCount == maxRetry) {
                log.warn(MessageFormat.format("Max retry reached {0}, not trying any longer", //$NON-NLS-1$
                        spec.getQueryString()));
                throw new VersionControlException(e);
            } else {
                hadSocketException = true;
            }

            log.warn(
                    MessageFormat.format("Retrying download after a socket timeout for {0}", //$NON-NLS-1$
                            spec.getQueryString()), e);
        } catch (final DownloadProxyException e) {
            /*
             * Since we call recordDownloadProxyFailure, we should never
             * have another of these during a retry, but the check is
             * probably valuable to prevent an infinite loop.
             */
            if (hadDownloadProxyException) {
                log.warn(MessageFormat.format(
                        "Second download proxy error for {0}, which should never happen because we disabled the download proxy, rethrowing", //$NON-NLS-1$
                        spec.getQueryString()));
                throw new VersionControlException(e);
            } else {
                hadDownloadProxyException = true;
            }

            log.warn(MessageFormat.format("Download proxy error for {0}, disabling for this session", //$NON-NLS-1$
                    spec.getQueryString()));

            /*
             * The download proxy exception has a nice message in it, but we
             * need to let the user know we'll retry.
             */
            getEventEngine().fireNonFatalError(new NonFatalErrorEvent(eventSource, this, e));
            getEventEngine().fireNonFatalError(new NonFatalErrorEvent(eventSource, this,
                    new DownloadProxyException(
                            //@formatter:off
                            Messages.getString(
                                    "VersionControlClient.DisablingDownloadProxyForThisSessionAndRetrying")))); //$NON-NLS-1$
            //@formatter:on
            recordDownloadProxyFailure();
        } catch (final IOException e) {
            /*
             * This is an exception from resetting the streams after a retry
             * (probably because the output doesn't support stream reset).
             * Just rethrow.
             */
            log.warn("Fatal IOException stops download retries", e); //$NON-NLS-1$
            throw new VersionControlException(e);
        }

        // Let the loop retry the download.

        final long delayTime = 10000 * (long) Math.pow(2, retryCount - 1);
        log.info("Retrying request in " + delayTime + " ms"); //$NON-NLS-1$ //$NON-NLS-2$
        try {
            Thread.sleep(delayTime);
        } catch (final InterruptedException e) {
            log.debug("Sleeping thred has been interrupted", e); //$NON-NLS-1$
            throw new VersionControlException(e);
        }
    }
}

From source file:org.apache.geode.internal.cache.Oplog.java

private void setMaxCrfDrfSize() {
    int crfPct = Integer.getInteger(DistributionConfig.GEMFIRE_PREFIX + "CRF_MAX_PERCENTAGE", 90);
    if (crfPct > 100 || crfPct < 0) {
        crfPct = 90;/* w ww .ja v a  2s .  c om*/
    }
    this.maxCrfSize = (long) (this.maxOplogSize * (crfPct / 100.0));
    this.maxDrfSize = this.maxOplogSize - this.maxCrfSize;
}