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.opennms.upgrade.implementations.SnmpInterfaceUpgrade.java

/**
 * Gets the node directory.//from ww w  . j  a v a  2  s.  com
 *
 * @param nodeId the node id
 * @param foreignSource the foreign source
 * @param foreignId the foreign id
 * @return the node directory
 */
protected File getNodeDirectory(int nodeId, String foreignSource, String foreignId) {
    String rrdPath = DataCollectionConfigFactory.getInstance().getRrdPath();
    File dir = new File(rrdPath, String.valueOf(nodeId));
    if (Boolean.getBoolean("org.opennms.rrd.storeByForeignSource") && !(foreignSource == null)
            && !(foreignId == null)) {
        File fsDir = new File(rrdPath, "fs" + File.separatorChar + foreignSource);
        dir = new File(fsDir, foreignId);
    }
    return dir;
}

From source file:org.carrot2.dcs.RestProcessorServlet.java

@Override
@SuppressWarnings("unchecked")
public void init() throws ServletException {
    // Run in servlet container, load config from config.xml.
    ResourceLookup webInfLookup = new ResourceLookup(
            new PrefixDecoratorLocator(new ServletContextLocator(getServletContext()), "/WEB-INF/"));

    try {/*  w ww.j a  v a 2  s. c  om*/
        config = DcsConfig.deserialize(webInfLookup.getFirst("dcs-config.xml"));
    } catch (Exception e) {
        throw new ServletException("Could not read 'config.xml' resource.", e);
    }

    // Initialize XSLT
    initXslt(config, webInfLookup);

    // Load component suite. Use classpath too (for JUnit tests).
    try {
        List<IResourceLocator> resourceLocators = Lists.newArrayList();
        resourceLocators.add(
                new PrefixDecoratorLocator(new ServletContextLocator(getServletContext()), "/WEB-INF/suites/"));

        if (Boolean.getBoolean(ENABLE_CLASSPATH_LOCATOR))
            resourceLocators.add(Location.CONTEXT_CLASS_LOADER.locator);

        ResourceLookup suitesLookup = new ResourceLookup(resourceLocators);

        IResource suiteResource = suitesLookup.getFirst(config.componentSuiteResource);
        if (suiteResource == null) {
            throw new Exception("Suite file not found in servlet context's /WEB-INF/suites: "
                    + config.componentSuiteResource);
        }
        componentSuite = ProcessingComponentSuite.deserialize(suiteResource, suitesLookup);
    } catch (Exception e) {
        throw new ServletException("Could initialize component suite.", e);
    }

    // Initialize defaults.
    if (componentSuite.getAlgorithms().size() == 0) {
        throw new ServletException("Component suite has no algorithms.");
    }
    defaultAlgorithmId = componentSuite.getAlgorithms().get(0).getId();

    // Initialize controller
    final List<Class<? extends IProcessingComponent>> cachedComponentClasses = Lists
            .newArrayListWithExpectedSize(2);
    if (config.cacheDocuments) {
        cachedComponentClasses.add(IDocumentSource.class);
    }
    if (config.cacheClusters) {
        cachedComponentClasses.add(IClusteringAlgorithm.class);
    }

    controller = ControllerFactory
            .createCachingPooling(cachedComponentClasses.toArray(new Class[cachedComponentClasses.size()]));

    List<IResourceLocator> locators = Lists.newArrayList();
    locators.add(
            new PrefixDecoratorLocator(new ServletContextLocator(getServletContext()), "/WEB-INF/resources/"));

    if (Boolean.getBoolean(ENABLE_CLASSPATH_LOCATOR))
        locators.add(Location.CONTEXT_CLASS_LOADER.locator);

    // Allow multiple resource lookup paths for different component configurations.
    String resourceLookupAttrKey = AttributeUtils.getKey(DefaultLexicalDataFactory.class, "resourceLookup");
    String altResourceLookupAttrKey = "dcs.resource-lookup";
    ProcessingComponentConfiguration[] configurations = componentSuite.getComponentConfigurations();
    for (int i = 0; i < configurations.length; i++) {
        ProcessingComponentConfiguration config = configurations[i];
        Object location = config.attributes.get(altResourceLookupAttrKey);
        if (location != null && location instanceof String) {
            File resourceDir = new File((String) location);
            if (!resourceDir.isDirectory()) {
                Logger.getRootLogger().warn("Not a resource folder, ignored: " + resourceDir);
            } else {
                HashMap<String, Object> mutableMap = new HashMap<String, Object>(config.attributes);
                mutableMap.put(resourceLookupAttrKey, new ResourceLookup(new DirLocator(resourceDir)));
                config = configurations[i] = new ProcessingComponentConfiguration(config.componentClass,
                        config.componentId, mutableMap);
            }
        }
    }

    controller.init(ImmutableMap.<String, Object>of(resourceLookupAttrKey, new ResourceLookup(locators)),
            configurations);
}

From source file:com.github.mrstampy.esp.neurosky.MultiConnectionThinkGearSocket.java

/**
 * Connects to the ThinkGear socket on the specified host. The system property
 * 'broadcast.messages' is used to enable/disable broadcasting for
 * {@link ThinkGearSocketConnector}s, and the system property
 * 'send.neurosky.messages' is used to enable/disable remote
 * {@link ThinkGearSocketConnector}s sending messages to the Neurosky device.
 * /*from w w w.j a  va2  s  . co m*/
 * @param host
 * @throws IOException
 */
public MultiConnectionThinkGearSocket(String host) throws IOException {
    this(host, Boolean.getBoolean(BROADCAST_MESSAGES), Boolean.getBoolean(SEND_NEUROSKY_MESSAGES));
}

From source file:com.bugvm.maven.surefire.BugVMSurefireProvider.java

@Override
public RunResult invoke(Object forkTestSet) throws TestSetFailedException, ReporterException {
    if (testsToRun == null) {
        if (forkTestSet instanceof TestsToRun) {
            testsToRun = (TestsToRun) forkTestSet;
        } else if (forkTestSet instanceof Class) {
            testsToRun = TestsToRun.fromClass((Class<?>) forkTestSet);
        } else {/*from   w w  w  . ja v a  2 s.  c  o  m*/
            testsToRun = scanClassPath();
        }
    }

    final ReporterFactory reporterFactory = providerParameters.getReporterFactory();
    final RunListener reporter = reporterFactory.createReporter();
    ConsoleOutputCapture.startCapture((ConsoleOutputReceiver) reporter);
    final JUnit4RunListener jUnit4TestSetReporter = new JUnit4RunListener(reporter);
    Result result = new Result();
    final RunNotifier runNotifier = getRunNotifier(jUnit4TestSetReporter, result, customRunListeners);

    TestClient testClient = new TestClient();
    testClient.setRunListener(new org.junit.runner.notification.RunListener() {
        public void testRunStarted(Description description) throws Exception {
            runNotifier.fireTestRunStarted(description);
        }

        public void testRunFinished(Result result) throws Exception {
            runNotifier.fireTestRunFinished(result);
        }

        public void testStarted(Description description) throws Exception {
            runNotifier.fireTestStarted(description);
        }

        public void testFinished(Description description) throws Exception {
            runNotifier.fireTestFinished(description);
        }

        public void testFailure(Failure failure) throws Exception {
            runNotifier.fireTestFailure(failure);
        }

        public void testAssumptionFailure(Failure failure) {
            runNotifier.fireTestAssumptionFailed(failure);
        }

        public void testIgnored(Description description) throws Exception {
            runNotifier.fireTestIgnored(description);
        }
    });

    String runArgs = System.getProperty(PROP_RUN_ARGS, "");
    if (!runArgs.isEmpty()) {
        testClient
                .setRunArgs(new ArrayList<>(Arrays.asList(CommandLine.parse("cmd " + runArgs).getArguments())));
    }

    Process process = null;
    try {
        Config config = testClient.configure(createConfig(), isIOS()).build();
        config.getLogger().info("Building BugVM tests for: %s (%s)", config.getOs(), config.getArch());
        config.getLogger().info("This could take a while, especially the first time round");
        AppCompiler appCompiler = new AppCompiler(config);
        appCompiler.build();

        LaunchParameters launchParameters = config.getTarget().createLaunchParameters();
        if (Boolean.getBoolean(PROP_SERVER_DEBUG)) {
            launchParameters.getArguments().add("-rvm:Dbugvm.debug=true");
        }
        if (System.getProperty(PROP_IOS_SIMULATOR_NAME) != null
                && launchParameters instanceof IOSSimulatorLaunchParameters) {
            DeviceType type = DeviceType.getDeviceType(System.getProperty(PROP_IOS_SIMULATOR_NAME));
            ((IOSSimulatorLaunchParameters) launchParameters).setDeviceType(type);
        } else if (launchParameters instanceof IOSSimulatorLaunchParameters) {
            if (config.getArch() == Arch.x86_64) {
                ((IOSSimulatorLaunchParameters) launchParameters)
                        .setDeviceType(DeviceType.getBestDeviceType(config.getArch(), null, null, null));
            }
        }
        process = appCompiler.launchAsync(launchParameters);

        runNotifier.fireTestRunStarted(null);
        for (Class<?> clazz : testsToRun) {
            executeTestSet(testClient, clazz, reporter, runNotifier);
        }
        testClient.terminate();
        process.waitFor();
        runNotifier.fireTestRunFinished(result);
        JUnit4RunListener.rethrowAnyTestMechanismFailures(result);
    } catch (Throwable t) {
        throw new RuntimeException("BugVM test run failed", t);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    return reporterFactory.close();
}

From source file:org.robovm.eclipse.internal.AbstractLaunchConfigurationDelegate.java

@Override
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
        throws CoreException {

    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }//ww  w . j  a va2  s.c o  m

    monitor.beginTask(configuration.getName() + "...", 6);
    if (monitor.isCanceled()) {
        return;
    }

    try {
        monitor.subTask("Verifying launch attributes");

        String mainTypeName = getMainTypeName(configuration);
        File workingDir = getWorkingDirectory(configuration);
        String[] envp = getEnvironment(configuration);
        List<String> pgmArgs = splitArgs(getProgramArguments(configuration));
        List<String> vmArgs = splitArgs(getVMArguments(configuration));
        String[] classpath = getClasspath(configuration);
        String[] bootclasspath = getBootpath(configuration);
        IJavaProject javaProject = getJavaProject(configuration);
        int debuggerPort = findFreePort();
        boolean hasDebugPlugin = false;

        if (monitor.isCanceled()) {
            return;
        }

        // Verification done
        monitor.worked(1);

        RoboVMPlugin.consoleInfo("Building executable");

        monitor.subTask("Creating source locator");
        setDefaultSourceLocator(launch, configuration);
        monitor.worked(1);

        monitor.subTask("Creating build configuration");
        Config.Builder configBuilder;
        try {
            configBuilder = new Config.Builder();
        } catch (IOException e) {
            throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID,
                    "Launch failed. Check the RoboVM console for more information.", e));
        }
        configBuilder.logger(RoboVMPlugin.getConsoleLogger());

        File projectRoot = getJavaProject(configuration).getProject().getLocation().toFile();
        RoboVMPlugin.loadConfig(configBuilder, projectRoot, isTestConfiguration());

        Arch arch = getArch(configuration, mode);
        OS os = getOS(configuration, mode);

        configBuilder.os(os);
        configBuilder.arch(arch);

        File tmpDir = RoboVMPlugin.getBuildDir(getJavaProjectName(configuration));
        tmpDir = new File(tmpDir, configuration.getName());
        tmpDir = new File(new File(tmpDir, os.toString()), arch.toString());
        if (mainTypeName != null) {
            tmpDir = new File(tmpDir, mainTypeName);
        }

        if (ILaunchManager.DEBUG_MODE.equals(mode)) {
            configBuilder.debug(true);
            String sourcepaths = RoboVMPlugin.getSourcePaths(javaProject);
            configBuilder.addPluginArgument("debug:sourcepath=" + sourcepaths);
            configBuilder.addPluginArgument("debug:jdwpport=" + debuggerPort);
            configBuilder.addPluginArgument(
                    "debug:logdir=" + new File(projectRoot, "robovm-logs").getAbsolutePath());
            // check if we have the debug plugin
            for (Plugin plugin : configBuilder.getPlugins()) {
                if ("DebugLaunchPlugin".equals(plugin.getClass().getSimpleName())) {
                    hasDebugPlugin = true;
                }
            }
        }

        if (bootclasspath != null) {
            configBuilder.skipRuntimeLib(true);
            for (String p : bootclasspath) {
                configBuilder.addBootClasspathEntry(new File(p));
            }
        }
        for (String p : classpath) {
            configBuilder.addClasspathEntry(new File(p));
        }
        if (mainTypeName != null) {
            configBuilder.mainClass(mainTypeName);
        }
        // we need to filter those vm args that belong to plugins
        // in case of iOS run configs, we can only pass program args
        filterPluginArguments(vmArgs, configBuilder);
        filterPluginArguments(pgmArgs, configBuilder);

        configBuilder.tmpDir(tmpDir);
        configBuilder.skipInstall(true);

        Config config = null;
        AppCompiler compiler = null;
        try {
            RoboVMPlugin.consoleInfo("Cleaning output dir " + tmpDir.getAbsolutePath());
            FileUtils.deleteDirectory(tmpDir);
            tmpDir.mkdirs();

            Home home = RoboVMPlugin.getRoboVMHome();
            if (home.isDev()) {
                configBuilder.useDebugLibs(Boolean.getBoolean("robovm.useDebugLibs"));
                configBuilder.dumpIntermediates(true);
            }
            configBuilder.home(home);
            config = configure(configBuilder, configuration, mode).build();
            compiler = new AppCompiler(config);
            if (monitor.isCanceled()) {
                return;
            }
            monitor.worked(1);

            monitor.subTask("Building executable");
            AppCompilerThread thread = new AppCompilerThread(compiler, monitor);
            thread.compile();
            if (monitor.isCanceled()) {
                RoboVMPlugin.consoleInfo("Build canceled");
                return;
            }
            monitor.worked(1);
            RoboVMPlugin.consoleInfo("Build done");
        } catch (InterruptedException e) {
            RoboVMPlugin.consoleInfo("Build canceled");
            return;
        } catch (IOException e) {
            RoboVMPlugin.consoleError("Build failed");
            throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID,
                    "Build failed. Check the RoboVM console for more information.", e));
        }

        try {
            RoboVMPlugin.consoleInfo("Launching executable");
            monitor.subTask("Launching executable");
            mainTypeName = config.getMainClass();

            List<String> runArgs = new ArrayList<String>();
            runArgs.addAll(vmArgs);
            runArgs.addAll(pgmArgs);
            LaunchParameters launchParameters = config.getTarget().createLaunchParameters();
            launchParameters.setArguments(runArgs);
            launchParameters.setWorkingDirectory(workingDir);
            launchParameters.setEnvironment(envToMap(envp));
            customizeLaunchParameters(config, launchParameters, configuration, mode);
            String label = String.format("%s (%s)", mainTypeName,
                    DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(new Date()));
            // launch plugin may proxy stdout/stderr fifo, which
            // it then writes to. Need to save the original fifos
            File stdOutFifo = launchParameters.getStdoutFifo();
            File stdErrFifo = launchParameters.getStderrFifo();
            PipedInputStream pipedIn = new PipedInputStream();
            PipedOutputStream pipedOut = new PipedOutputStream(pipedIn);
            Process process = compiler.launchAsync(launchParameters, pipedIn);
            if (stdOutFifo != null || stdErrFifo != null) {
                InputStream stdoutStream = null;
                InputStream stderrStream = null;
                if (launchParameters.getStdoutFifo() != null) {
                    stdoutStream = new OpenOnReadFileInputStream(stdOutFifo);
                }
                if (launchParameters.getStderrFifo() != null) {
                    stderrStream = new OpenOnReadFileInputStream(stdErrFifo);
                }
                process = new ProcessProxy(process, pipedOut, stdoutStream, stderrStream, compiler);
            }

            IProcess iProcess = DebugPlugin.newProcess(launch, process, label);

            // setup the debugger
            if (ILaunchManager.DEBUG_MODE.equals(mode) && hasDebugPlugin) {
                VirtualMachine vm = attachToVm(monitor, debuggerPort);
                // we were canceled
                if (vm == null) {
                    process.destroy();
                    return;
                }
                if (vm instanceof VirtualMachineImpl) {
                    ((VirtualMachineImpl) vm).setRequestTimeout(DEBUGGER_REQUEST_TIMEOUT);
                }
                JDIDebugModel.newDebugTarget(launch, vm, mainTypeName + " at localhost:" + debuggerPort,
                        iProcess, true, false, true);
            }
            RoboVMPlugin.consoleInfo("Launch done");

            if (monitor.isCanceled()) {
                process.destroy();
                return;
            }
            monitor.worked(1);
        } catch (Throwable t) {
            RoboVMPlugin.consoleError("Launch failed");
            throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID,
                    "Launch failed. Check the RoboVM console for more information.", t));
        }

    } finally {
        monitor.done();
    }
}

From source file:org.jboss.errai.marshalling.rebind.util.MarshallingGenUtil.java

public static boolean isForceStaticMarshallers() {
    if (System.getProperty(FORCE_STATIC_MARSHALLERS) != null) {
        return Boolean.getBoolean(FORCE_STATIC_MARSHALLERS);
    }/*from w w w  .  j av  a 2  s  .c  om*/

    final Map<String, String> frameworkProperties = EnvUtil.getEnvironmentConfig().getFrameworkProperties();
    if (frameworkProperties.containsKey(FORCE_STATIC_MARSHALLERS)) {
        return "true".equals(frameworkProperties.get(FORCE_STATIC_MARSHALLERS));
    } else {
        return false;
    }
}

From source file:com.konakart.actions.gateways.CyberSourceResponseAction.java

public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();

    String reconciliationID = null;
    String merchantReference = null;
    String reasonCode = null;/* ww  w . jav a  2s.c om*/
    String ccAuthReply_amount = null;
    String decision = null;
    String ccAuthReply_authorizationCode = null;
    String requestId = null;
    String customerEmail = null;
    String orderAmount_publicSignature = null;
    String orderAmount = null;
    String responseEnvironment = null;

    KKAppEng kkAppEng = null;

    if (log.isDebugEnabled()) {
        log.debug(CyberSource.CYBERSOURCE_GATEWAY_CODE + " Response Action");
    }

    try {
        // Process the parameters sent in the callback
        StringBuffer sb = new StringBuffer();
        if (request != null) {
            Enumeration<String> en = request.getParameterNames();
            while (en.hasMoreElements()) {
                String paramName = en.nextElement();
                String paramValue = request.getParameter(paramName);
                if (sb.length() > 0) {
                    sb.append("\n");
                }
                sb.append(paramName);
                sb.append(" = ");
                sb.append(paramValue);

                // Capture important variables so that we can determine whether the transaction
                // was successful
                if (paramName != null) {
                    if (paramName.equalsIgnoreCase("decision")) {
                        decision = paramValue;
                    } else if (paramName.equalsIgnoreCase("reconciliationID")) {
                        reconciliationID = paramValue;
                    } else if (paramName.equalsIgnoreCase(CyberSource.CYBERSOURCE_MERCHANT_REF)) {
                        merchantReference = paramValue;
                    } else if (paramName.equalsIgnoreCase(CyberSource.CYBERSOURCE_ENVIRONMENT)) {
                        responseEnvironment = paramValue;
                    } else if (paramName.equalsIgnoreCase("reasonCode")) {
                        reasonCode = paramValue;
                    } else if (paramName.equalsIgnoreCase("ccAuthReply_amount")) {
                        ccAuthReply_amount = paramValue;
                    } else if (paramName.equalsIgnoreCase("ccAuthReply_authorizationCode")) {
                        ccAuthReply_authorizationCode = paramValue;
                    } else if (paramName.equalsIgnoreCase("requestId")) {
                        requestId = paramValue;
                    } else if (paramName.equalsIgnoreCase("orderAmount")) {
                        orderAmount = paramValue;
                    } else if (paramName.equalsIgnoreCase("CUSTOMER_EMAIL")) {
                        customerEmail = paramValue;
                    } else if (paramName.equalsIgnoreCase("orderAmount_publicSignature")) {
                        orderAmount_publicSignature = paramValue;
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Un-processed parameter in response:  '" + paramName + "' = '"
                                    + paramValue + "'");
                        }
                    }
                }
            }
        }

        String fullGatewayResponse = sb.toString();

        if (log.isDebugEnabled()) {
            log.debug(CyberSource.CYBERSOURCE_GATEWAY_CODE + " Raw Response data:\n" + fullGatewayResponse);
            log.debug("\n    decision                      = " + decision
                    + "\n    reconciliationID              = " + reconciliationID
                    + "\n    merchantReference             = " + merchantReference
                    + "\n    orderPage_environment         = " + responseEnvironment
                    + "\n    reasonCode                    = " + reasonCode
                    + "\n    ccAuthReply_amount            = " + ccAuthReply_amount
                    + "\n    ccAuthReply_authorizationCode = " + ccAuthReply_authorizationCode
                    + "\n    orderAmount                   = " + orderAmount
                    + "\n    requestId                     = " + requestId
                    + "\n    orderAmount_publicSignature   = " + orderAmount_publicSignature
                    + "\n    customerEmail                 = " + customerEmail);
        }

        // Pick out the values from the merchantReference
        // Split the merchantReference into orderId, orderNumber and store information
        StringTokenizer st = new StringTokenizer(merchantReference, "~");
        int orderId = -1;
        String orderIdStr = null;
        String orderNumberStr = null;
        String storeId = null;
        int engineMode = -1;
        boolean customersShared = false;
        boolean productsShared = false;
        boolean categoriesShared = false;
        String countryCode = null;

        if (st.hasMoreTokens()) {
            orderIdStr = st.nextToken();
            orderId = Integer.parseInt(orderIdStr);
        }
        if (st.hasMoreTokens()) {
            orderNumberStr = st.nextToken();
        }
        if (st.hasMoreTokens()) {
            storeId = st.nextToken();
        }
        if (st.hasMoreTokens()) {
            engineMode = Integer.parseInt(st.nextToken());
        }
        if (st.hasMoreTokens()) {
            customersShared = Boolean.getBoolean(st.nextToken());
        }
        if (st.hasMoreTokens()) {
            productsShared = Boolean.getBoolean(st.nextToken());
        }
        if (st.hasMoreTokens()) {
            categoriesShared = Boolean.getBoolean(st.nextToken());
        }
        if (st.hasMoreTokens()) {
            countryCode = st.nextToken();
        }

        if (log.isDebugEnabled()) {
            log.debug("Derived from merchantReference:         \n" + "    OrderId                       = "
                    + orderId + "\n" + "    OrderNumber                   = " + orderNumberStr + "\n"
                    + "    StoreId                       = " + storeId + "\n"
                    + "    EngineMode                    = " + engineMode + "\n"
                    + "    CustomersShared               = " + customersShared + "\n"
                    + "    ProductsShared                = " + productsShared + "\n"
                    + "    CategoriesShared              = " + categoriesShared + "\n"
                    + "    CountryCode                   = " + countryCode);
        }

        // Get an instance of the KonaKart engine
        // kkAppEng = this.getKKAppEng(request); // v3.2 code
        kkAppEng = this.getKKAppEng(request, response); // v4.1 code

        int custId = this.loggedIn(request, response, kkAppEng, "Checkout");

        // Check to see whether the user is logged in
        if (custId < 0) {
            if (log.isInfoEnabled()) {
                log.info("Customer is not logged in");
            }
            return KKLOGIN;
        }

        // If we didn't receive a decision, we log a warning and return
        if (decision == null) {
            String msg = "No decision returned for the " + CyberSource.CYBERSOURCE_GATEWAY_CODE + " module";
            saveIPNrecord(kkAppEng, orderId, CyberSource.CYBERSOURCE_GATEWAY_CODE, fullGatewayResponse,
                    decision, reconciliationID, RET1_DESC + msg, RET1);
            throw new Exception(msg);
        }

        boolean validateSignature = false;
        String sharedSecret = kkAppEng.getCustomConfig(orderIdStr + "-CUSTOM1", true);
        if (sharedSecret == null) {
            if (log.isWarnEnabled()) {
                log.warn("CyberSource shared secret is null on the session");
            }
            validateSignature = false;
        } else {
            // Check the authenticity of the message by checking the signature
            validateSignature = CyberSourceHMACTools.verifyBase64EncodedSignature(sharedSecret,
                    orderAmount_publicSignature, orderAmount);
        }

        if (log.isDebugEnabled()) {
            log.debug("Signature Validation Result: " + validateSignature);
        }

        // If the signature on the amount doesn't validate we log a warning and return
        if (!validateSignature) {
            String msg = "Signature Validation Failed for the " + CyberSource.CYBERSOURCE_GATEWAY_CODE
                    + " module - orderId " + orderId;
            saveIPNrecord(kkAppEng, orderId, CyberSource.CYBERSOURCE_GATEWAY_CODE, fullGatewayResponse,
                    decision, reconciliationID, RET1_DESC + msg, RET1);
            throw new Exception(msg);
        }

        // Validate we are in the correct environment
        boolean validateEnvironment = true;
        String sessionEnvironment = kkAppEng.getCustomConfig(orderIdStr + "-CUSTOM2", true);
        if (sessionEnvironment == null) {
            if (log.isWarnEnabled()) {
                log.warn("CyberSource Operating Environment is null on the session");
            }
            validateEnvironment = false;
        } else if (illegalEnvironmentValue(sessionEnvironment)) {
            if (log.isWarnEnabled()) {
                log.warn("CyberSource Operating Environment on the session is illegal");
            }
            validateEnvironment = false;
        } else if (illegalEnvironmentValue(responseEnvironment)) {
            if (log.isWarnEnabled()) {
                log.warn("CyberSource Operating Environment in the session is illegal");
            }
            validateEnvironment = false;
        } else if (!sessionEnvironment.equals(responseEnvironment)) {
            if (log.isWarnEnabled()) {
                log.warn("CyberSource Operating Environment in the session (" + sessionEnvironment
                        + ") does not match that in the response (" + responseEnvironment + ")");
            }
            validateEnvironment = false;
        }

        // If the signature on the amount doesn't validate we log a warning and return
        if (!validateEnvironment) {
            String msg = "Environment Validation Failed for the " + CyberSource.CYBERSOURCE_GATEWAY_CODE
                    + " module - orderId " + orderId;
            saveIPNrecord(kkAppEng, orderId, CyberSource.CYBERSOURCE_GATEWAY_CODE, fullGatewayResponse,
                    decision, reconciliationID, RET1_DESC + msg, RET1);
            throw new Exception(msg);
        }

        // See if we need to send an email, by looking at the configuration
        String sendEmailsConfig = kkAppEng.getConfig(ConfigConstants.SEND_EMAILS);
        boolean sendEmail = false;
        if (sendEmailsConfig != null && sendEmailsConfig.equalsIgnoreCase("true")) {
            sendEmail = true;
        }

        // If we didn't receive an ACCEPT decision, we let the user Try Again

        OrderUpdateIf updateOrder = new OrderUpdate();
        updateOrder.setUpdatedById(kkAppEng.getActiveCustId());

        if (!decision.equals("ACCEPT")) {
            if (log.isDebugEnabled()) {
                log.debug("Payment Not Approved for orderId: " + orderId + " for customer: " + customerEmail
                        + " reason: " + getReasonDescription(reasonCode));
            }
            saveIPNrecord(kkAppEng, orderId, CyberSource.CYBERSOURCE_GATEWAY_CODE, fullGatewayResponse,
                    decision, reconciliationID, RET2_DESC + decision + " : " + getReasonDescription(reasonCode),
                    RET2);

            String comment = ORDER_HISTORY_COMMENT_KO + decision;
            kkAppEng.getEng().updateOrder(kkAppEng.getSessionId(), orderId,
                    com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS, sendEmail, comment, updateOrder);
            if (sendEmail) {
                sendOrderConfirmationMail(kkAppEng, orderId, /* success */false);
            }

            String msg = kkAppEng.getMsg("checkout.cc.gateway.error", new String[] { comment });
            addActionError(msg);

            return "TryAgain";
        }

        // If successful, we forward to "Approved"

        if (log.isDebugEnabled()) {
            log.debug("Payment Approved for orderId " + orderId + " for customer " + customerEmail);
        }
        saveIPNrecord(kkAppEng, orderId, CyberSource.CYBERSOURCE_GATEWAY_CODE, fullGatewayResponse, decision,
                reconciliationID, RET0_DESC, RET0);

        String comment = ORDER_HISTORY_COMMENT_OK + reconciliationID;
        kkAppEng.getEng().updateOrder(kkAppEng.getSessionId(), orderId,
                com.konakart.bl.OrderMgr.PAYMENT_RECEIVED_STATUS, sendEmail, comment, updateOrder);

        // If the order payment was approved we update the inventory
        kkAppEng.getEng().updateInventory(kkAppEng.getSessionId(), orderId);

        if (sendEmail) {
            sendOrderConfirmationMail(kkAppEng, orderId, /* success */true);
        }

        // If we received no exceptions, delete the basket
        kkAppEng.getBasketMgr().emptyBasket();

        return "Approved";

    } catch (Exception e) {
        e.printStackTrace();
        return super.handleException(request, e);
    }
}

From source file:org.opencastproject.publication.youtube.YouTubePublicationServiceImpl.java

/**
 * {@inheritDoc}//ww  w  . j a  v  a 2  s. c om
 * 
 * @see org.osgi.service.cm.ManagedService#updated(java.util.Dictionary)
 */
@Override
public synchronized void updated(Dictionary properties) throws ConfigurationException {
    logger.info("Update method from managed service");

    String username = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.username"));
    String password = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.password"));
    String clientid = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.clientid"));
    String developerkey = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.developerkey"));
    String category = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.category"));
    String keywords = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.keywords"));

    String privacy = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.private"));

    String isChunked = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.chunked"));

    defaultPlaylist = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.default.playlist"));

    // Setup configuration from properties
    if (StringUtils.isBlank(clientid))
        throw new IllegalArgumentException("Youtube clientid must be specified");
    if (StringUtils.isBlank(developerkey))
        throw new IllegalArgumentException("Youtube developerkey must be specified");
    if (StringUtils.isBlank(username))
        throw new IllegalArgumentException("Youtube username must be specified");
    if (StringUtils.isBlank(password))
        throw new IllegalArgumentException("Youtube password must be specified");
    if (StringUtils.isBlank(category))
        throw new IllegalArgumentException("Youtube category must be specified");
    if (StringUtils.isBlank(keywords))
        throw new IllegalArgumentException("Youtube keywords must be specified");
    if (StringUtils.isBlank(privacy))
        throw new IllegalArgumentException("Youtube privacy must be specified");

    String uploadUrl = VIDEO_ENTRY_URL.replaceAll("\\{username\\}", username);

    config.setClientId(clientid);
    config.setDeveloperKey(developerkey);
    config.setUserId(username);
    config.setUploadUrl(uploadUrl);
    config.setPassword(password);
    config.setKeywords(keywords);
    config.setCategory(category);
    config.setVideoPrivate(Boolean.getBoolean(privacy));

    if (StringUtils.isNotBlank(isChunked))
        isDefaultChunked = Boolean.getBoolean(isChunked);
}

From source file:au.com.borner.salesforce.jps.SalesForceModuleLevelBuilder.java

public ExitCode compileUsingToolingAPI(final CompileContext context,
        DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder)
        throws ProjectBuildException, IOException {

    // Step 1: login to Salesforce
    context.processMessage(new CompilerMessage(EMPTY, BuildMessage.Kind.PROGRESS, "Logging into Salesforce"));
    InstanceCredentials instanceCredentials = new InstanceCredentials("Compile");
    instanceCredentials.setUsername(System.getProperty("username"));
    instanceCredentials.setPassword(System.getProperty("password"));
    instanceCredentials.setSecurityToken(System.getProperty("securityToken"));
    instanceCredentials.setEnvironment(System.getProperty("environment"));
    SoapClient soapClient = new SoapClient();
    soapClient.login(instanceCredentials, Boolean.getBoolean(System.getProperty("traceMessages")));
    ConnectionManager connectionManager = new ConnectionManager();
    connectionManager.setSessionDetails(soapClient.getSessionId(), soapClient.getServiceHost());
    final ToolingRestClient toolingRestClient = new ToolingRestClient(connectionManager);

    // Step 2: create Metadata container
    context.processMessage(//from  w w w.  java  2 s .c  om
            new CompilerMessage(EMPTY, BuildMessage.Kind.PROGRESS, "Creating Metadata Container"));
    String containerId = UUID.randomUUID().toString().replaceAll("-", "");
    final MetadataContainer metadataContainer = toolingRestClient
            .createSObject(new MetadataContainer(containerId));

    // Step 3: upload all the modified files into the Metadata container
    final Map<String, String> fileNameToUrlMap = new HashMap<String, String>();
    dirtyFilesHolder.processDirtyFiles(new FileProcessor<JavaSourceRootDescriptor, ModuleBuildTarget>() {
        @Override
        public boolean apply(ModuleBuildTarget target, File file, JavaSourceRootDescriptor root)
                throws IOException {
            fileNameToUrlMap.put(FileUtilities.filenameWithoutExtension(file.getName()),
                    file.getAbsolutePath());
            uploadSource(file, metadataContainer, context, toolingRestClient);
            return true;
        }
    });

    // Step 4: invoke the Salesforce compiler
    context.processMessage(new CompilerMessage(EMPTY, BuildMessage.Kind.PROGRESS, "Requesting Async Compile"));
    ContainerAsyncRequest containerAsyncRequest = new ContainerAsyncRequest(metadataContainer);
    containerAsyncRequest.setCheckOnly(false);
    containerAsyncRequest.setRunTests(true);
    containerAsyncRequest = toolingRestClient.createSObject(containerAsyncRequest);
    int retryCount = 0;
    // TODO: make these parameters configurable because large amount of source files will take longer to compile!
    while ((containerAsyncRequest.getState() == null
            || containerAsyncRequest.getState().equals(ContainerAsyncRequest.State.Queued))
            && ++retryCount < 60) {
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
            // ignore
        }
        containerAsyncRequest = toolingRestClient.getSObject(containerAsyncRequest,
                ContainerAsyncRequest.class);
    }

    // Step 5: check result
    if (containerAsyncRequest.getState() == null
            || containerAsyncRequest.getState().equals(ContainerAsyncRequest.State.Queued)) {
        context.processMessage(new CompilerMessage(EMPTY, BuildMessage.Kind.ERROR, "Compile has timed out"));
        soapClient.logoff();
        return ExitCode.ABORT;
    }

    ExitCode exitCode = ExitCode.OK;
    switch (containerAsyncRequest.getState()) {
    case Completed:
        context.processMessage(
                new CompilerMessage(EMPTY, BuildMessage.Kind.INFO, "Compilation was successful"));
        break;
    case Error:
        context.processMessage(new CompilerMessage(EMPTY, BuildMessage.Kind.ERROR,
                "A compiler error occurred " + containerAsyncRequest.getErrorMsg()));
        exitCode = ExitCode.ABORT;
        break;
    case Failed:
        List<CompilerError> compilerErrors = containerAsyncRequest.getCompilerErrors();
        if (compilerErrors.size() == 0) {
            context.processMessage(new CompilerMessage(EMPTY, BuildMessage.Kind.ERROR, "Compilation failed"));
        } else {
            for (CompilerError compilerError : compilerErrors) {
                String filePath = fileNameToUrlMap.get(compilerError.getName());
                Pair<Integer, Integer> location = compilerError.getLocation();
                if (location == null) {
                    context.processMessage(new CompilerMessage(EMPTY, BuildMessage.Kind.ERROR,
                            compilerError.getProblem(), filePath, -1, -1, -1, compilerError.getLine(), 0));
                } else {
                    context.processMessage(new CompilerMessage(EMPTY, BuildMessage.Kind.ERROR,
                            compilerError.getProblem(), filePath, -1, -1, -1, location.first, location.second));
                }
            }
        }
        exitCode = ExitCode.ABORT;
        break;
    case Invalidated:
        context.processMessage(new CompilerMessage(EMPTY, BuildMessage.Kind.WARNING,
                "The compilation was invalidated by the server"));
        exitCode = ExitCode.CHUNK_REBUILD_REQUIRED;
        break;
    case Aborted:
        context.processMessage(
                new CompilerMessage(EMPTY, BuildMessage.Kind.WARNING, "The compilation was aborted"));
        exitCode = ExitCode.CHUNK_REBUILD_REQUIRED;
        break;
    default:
        context.processMessage(
                new CompilerMessage(EMPTY, BuildMessage.Kind.ERROR, "An unknown error occurred"));
        exitCode = ExitCode.ABORT;
        break;
    }

    // Step 6: Delete metadata container and logoff
    context.processMessage(
            new CompilerMessage(EMPTY, BuildMessage.Kind.PROGRESS, "Deleting Metadata Container"));
    toolingRestClient.deleteSObject(metadataContainer);
    soapClient.logoff();
    return exitCode;

}

From source file:org.apache.jackrabbit.oak.plugins.segment.PartialCompactionMapTest.java

@Test
public void benchLargeMap() {
    assumeTrue(Boolean.getBoolean("benchmark.benchLargeMap"));
    assertHeapSize(4000000000L);//  w  w  w. ja  va2 s  .c o  m

    map = createCompactionMap();

    // check the memory use of really large mappings, 1M compacted segments with 10 records each.
    Runtime runtime = Runtime.getRuntime();
    for (int i = 0; i < 1000; i++) {
        Map<RecordId, RecordId> ids = randomRecordIdMap(rnd, getTracker(), 10000, 100);
        long start = System.nanoTime();
        for (Entry<RecordId, RecordId> entry : ids.entrySet()) {
            map.put(entry.getKey(), entry.getValue());
        }
        log.info("Bench Large Map #" + (i + 1) + ": "
                + (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024) + "MB, "
                + (System.nanoTime() - start) / 1000000 + "ms");
    }
}