Example usage for java.io PrintStream print

List of usage examples for java.io PrintStream print

Introduction

In this page you can find the example usage for java.io PrintStream print.

Prototype

public void print(Object obj) 

Source Link

Document

Prints an object.

Usage

From source file:org.apache.hive.beeline.BeeLine.java

void output(ColorBuffer msg, boolean newline, PrintStream out) {
    if (newline) {
        out.println(msg.getColor());/*w  w w. java 2 s. c o  m*/
    } else {
        out.print(msg.getColor());
    }

    if (recordOutputFile == null) {
        return;
    }

    // only write to the record file if we are writing a line ...
    // otherwise we might get garbage from backspaces and such.
    if (newline) {
        recordOutputFile.addLine(msg.getMono()); // always just write mono
    } else {
        recordOutputFile.print(msg.getMono());
    }
}

From source file:com.sic.bb.jenkins.plugins.sicci_for_xcode.XcodeBuilder.java

@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) {
    PrintStream logger = listener.getLogger();
    XcodeBuilderDescriptor descr = getDescriptor();
    FilePath workspace = this.currentProjectDirectory;

    List<String> blackList = new ArrayList<String>();
    List<Boolean> returnCodes = new ArrayList<Boolean>();

    boolean rcode = true;

    logger.println("\n" + Messages.XcodeBuilder_perform_started() + "\n");

    try {/*w ww  .j av a  2s . c om*/
        EnvVars envVars = build.getEnvironment(listener);

        logger.println(Messages.XcodeBuilder_perform_cleanStarted() + "\n");

        if (!(descr.getCleanBeforeBuildGlobal() && !descr.getCleanBeforeBuild()))
            for (String toClean : getToPerformStep(CLEAN_BEFORE_BUILD_ARG,
                    (descr.getCleanBeforeBuildGlobal() && descr.getCleanBeforeBuild())))
                returnCodes.add(XcodebuildCommandCaller.getInstance().clean(launcher, envVars, listener,
                        workspace, createArgs(toClean)));

        logger.println(Messages.XcodeBuilder_perform_cleanFinished() + "\n\n");

        if (this.currentUsername != null && this.currentPassword != null) {
            if (!SecurityCommandCaller.getInstance().unlockKeychain(envVars, listener, workspace,
                    this.currentUsername, this.currentPassword)
                    && XcodePlatform.fromString(getXcodePlatform()) == XcodePlatform.IOS)
                return false;

            logger.print("\n");
        }

        logger.println(Messages.XcodeBuilder_perform_buildStarted() + "\n");

        for (String toBuild : getToPerformStep(BUILD_ARG, true)) {
            rcode = XcodebuildCommandCaller.getInstance().build(launcher, envVars, listener, workspace,
                    this.currentBuildIsUnitTest, createArgs(toBuild));

            if (!rcode)
                blackList.add(toBuild);

            returnCodes.add(rcode);
        }

        logger.println(Messages.XcodeBuilder_perform_buildFinished() + "\n\n");

        FilePath buildDir = workspace.child(BUILD_FOLDER_NAME);

        logger.println(Messages.XcodeBuilder_perform_archiveAppsStarted() + "\n");

        if (!(descr.getArchiveAppGlobal() && !descr.getArchiveApp())) {
            for (String toArchiveApp : getToPerformStep(ARCHIVE_APP_ARG,
                    (descr.getArchiveAppGlobal() && descr.getArchiveApp()))) {
                if (blackList.contains(toArchiveApp))
                    continue;

                String[] array = toArchiveApp.split(PluginUtils.stringToPattern(FIELD_DELIMITER));

                if (getBooleanPreference(array[0] + FIELD_DELIMITER + UNIT_TEST_TARGET_ARG))
                    continue;

                logger.print(Messages.XcodeBuilder_perform_archivingApp() + ": " + array[0] + " " + array[1]);

                FilePath tempBuildDir = getBuildDir(buildDir, array[1]);

                if (tempBuildDir != null && tempBuildDir
                        .act(new AppArchiverCallable(array[0], createFilename(build, array[0], array[1])))) {
                    logger.println(" " + Messages.XcodeBuilder_perform_archivingAppDone());
                    returnCodes.add(true);
                } else {
                    logger.println(" " + Messages.XcodeBuilder_perform_archivingAppFailed());
                    returnCodes.add(false);
                }
            }
        }

        logger.println("\n" + Messages.XcodeBuilder_perform_archiveAppsFinished() + "\n\n");
        logger.println(Messages.XcodeBuilder_perform_createIpasStarted() + "\n");

        if (!(descr.getCreateIpaGlobal() && !descr.getCreateIpa())) {
            for (String toCreateIpa : getToPerformStep(CREATE_IPA_ARG,
                    (descr.getCreateIpaGlobal() && descr.getCreateIpa()))) {
                if (blackList.contains(toCreateIpa))
                    continue;

                String[] array = toCreateIpa.split(PluginUtils.stringToPattern(FIELD_DELIMITER));

                if (getBooleanPreference(array[0] + FIELD_DELIMITER + UNIT_TEST_TARGET_ARG))
                    continue;

                logger.print(Messages.XcodeBuilder_perform_creatingIpa() + ": " + array[0] + " " + array[1]);

                FilePath tempBuildDir = getBuildDir(buildDir, array[1]);

                if (tempBuildDir != null && tempBuildDir
                        .act(new IpaPackagerCallable(array[0], createFilename(build, array[0], array[1])))) {
                    logger.println(" " + Messages.XcodeBuilder_perform_creatingIpaDone());
                    returnCodes.add(true);
                } else {
                    logger.println(" " + Messages.XcodeBuilder_perform_creatingIpaFailed());
                    returnCodes.add(false);
                }
            }
        }

        logger.println("\n" + Messages.XcodeBuilder_perform_createIpasFinished() + "\n\n");

        logger.println(Messages.XcodeBuilder_perform_finished() + "\n\n");

        if (returnCodes.contains(false))
            return false;

        return true;
    } catch (Exception e) {
        logger.println(e.getStackTrace());
    }

    return false;
}

From source file:gov.nasa.ensemble.dictionary.nddl.NumericResourceTranslator.java

protected void writeConstant(PrintStream out, Constant constant) {
    // Do nothing if no activity uses the constant.
    if (!formulaUsesIdentifier(null, NDDLUtil.escape(constant.getName())))
        return;//from ww w  .j  a v  a 2  s. c o  m
    // Could include constant comments, but clutters.
    // if (constant.getNote() != null)
    // out.printf("/* %s */\n", constant.getNote());
    Object value = constant.getValue();
    // What to do about units? Have to assume they are ok for the
    // compat resource formulas, but show them as comments.
    if (value instanceof Amount<?>) {
        try {
            // Remark: For mslice, all the Amount constants seem
            // to be durations measured in seconds.
            Amount<?> val = (Amount<?>) value;
            if (val.isExact()) {
                out.printf("int  \t %s = \t %d; // %s\n", NDDLUtil.escape(constant.getName()),
                        val.getExactValue(), val.getUnit().toString());
            } else {
                out.printf("float  \t %s = \t %f; // %s\n", NDDLUtil.escape(constant.getName()),
                        val.getEstimatedValue(), val.getUnit().toString());
            }
            return;
        } catch (Exception e) {
            out.printf("// **Unhandled amount**");
        }
    } else if (value instanceof Boolean) {
        out.printf("bool");
    } else if (value instanceof Float || value instanceof Double) {
        out.printf("float");
    } else if (value instanceof Integer || value instanceof Long) {
        out.printf("int");
    } else if (value instanceof String) {
        out.printf("string");
    } else {
        out.printf("// **Unknown type**");
    }
    out.printf(" \t %s = \t ", NDDLUtil.escape(constant.getName()));
    if (value instanceof String) {
        out.printf("\"%s\"", value); // String in quotes
    } else if (value instanceof Float || value instanceof Double) {
        out.printf("%f", value); // Nddl disallows exponents
    } else {
        out.print(value);
    }
    out.printf(";");
    if (constant.getUnits() != null)
        out.printf(" // %s", constant.getUnits());
    out.printf("\n");
}

From source file:org.apache.hadoop.hive.ql.MultiDriver_BAK.java

private void printHeader(MultiDriver_BAK qp, PrintStream out) {
    List<FieldSchema> fieldSchemas = qp.getSchema().getFieldSchemas();
    if (HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVE_CLI_PRINT_HEADER) && fieldSchemas != null) {
        // Print the column names
        boolean first_col = true;
        for (FieldSchema fs : fieldSchemas) {
            if (!first_col) {
                out.print('\t');
            }/*from   w w  w.jav  a2s  .c  o  m*/
            out.print(fs.getName());
            first_col = false;
        }
        out.println();
    }
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step6GraphTransitivityCleaner.java

public GraphCleaningResults processSingleFile(File file, File outputDir, String prefix,
        Boolean collectGeneratedArgumentPairs) throws Exception {
    GraphCleaningResults result = new GraphCleaningResults();

    File outFileTable = new File(outputDir, prefix + file.getName() + "_table.csv");
    File outFileInfo = new File(outputDir, prefix + file.getName() + "_info.txt");

    PrintStream psTable = new PrintStream(new FileOutputStream(outFileTable));
    PrintStream psInfo = new PrintStream(new FileOutputStream(outFileInfo));

    // load one topic/side
    List<AnnotatedArgumentPair> pairs = new ArrayList<>(
            (List<AnnotatedArgumentPair>) XStreamTools.getXStream().fromXML(file));

    int fullDataSize = pairs.size();

    // filter out missing gold data
    Iterator<AnnotatedArgumentPair> iterator = pairs.iterator();
    while (iterator.hasNext()) {
        AnnotatedArgumentPair pair = iterator.next();
        if (pair.getGoldLabel() == null) {
            iterator.remove();// w w w .  j av  a  2s.c om
        }
        // or we want to completely remove equal edges in advance!
        else if (this.removeEqualEdgesParam && "equal".equals(pair.getGoldLabel())) {
            iterator.remove();
        }
    }

    // sort pairs by their weight
    this.argumentPairListSorter.sortArgumentPairs(pairs);

    int preFilteredDataSize = pairs.size();

    // compute correlation between score threshold and number of removed edges
    double[] correlationEdgeWeights = new double[pairs.size()];
    double[] correlationRemovedEdges = new double[pairs.size()];

    // only cycles of length 0 to 5 are interesting (5+ are too big)
    Range<Integer> range = Range.between(0, 5);

    psTable.print(
            "EdgeWeightThreshold\tPairs\tignoredEdgesCount\tIsDAG\tTransitivityScoreMean\tTransitivityScoreMax\tTransitivityScoreSamples\tEdges\tNodes\t");
    for (int j = range.getMinimum(); j <= range.getMaximum(); j++) {
        psTable.print("Cycles_" + j + "\t");
    }
    psTable.println();

    // store the indices of all pairs (edges) that have been successfully added without
    // generating cycles
    TreeSet<Integer> addedPairsIndices = new TreeSet<>();

    // number of edges ignored as they generated cycles
    int ignoredEdgesCount = 0;

    Graph lastGraph = null;

    // flag that the first cycle was already processed
    boolean firstCycleAlreadyHit = false;

    for (int i = 1; i < pairs.size(); i++) {
        // now filter the finalArgumentPairList and add only pairs that have not generated cycles
        List<AnnotatedArgumentPair> subList = new ArrayList<>();

        for (Integer index : addedPairsIndices) {
            subList.add(pairs.get(index));
        }

        // and add the current at the end
        subList.add(pairs.get(i));

        // what is the current lowest value of a pair weight?
        double weakestEdgeWeight = computeEdgeWeight(subList.get(subList.size() - 1), LAMBDA_PENALTY);

        //            Graph graph = buildGraphFromArgumentPairs(finalArgumentPairList);
        int numberOfLoops;

        // map for storing cycles by their length
        TreeMap<Integer, TreeSet<String>> lengthCyclesMap = new TreeMap<>();

        Graph graph = buildGraphFromArgumentPairs(subList);

        lastGraph = graph;

        List<List<Object>> cyclesInGraph = findCyclesInGraph(graph);

        DescriptiveStatistics transitivityScore = new DescriptiveStatistics();

        if (cyclesInGraph.isEmpty()) {
            // we have DAG
            transitivityScore = computeTransitivityScores(graph);

            // update results
            result.maxTransitivityScore = (int) transitivityScore.getMax();
            result.avgTransitivityScore = transitivityScore.getMean();
        }

        numberOfLoops = cyclesInGraph.size();

        // initialize map
        for (int r = range.getMinimum(); r <= range.getMaximum(); r++) {
            lengthCyclesMap.put(r, new TreeSet<String>());
        }

        // we hit a loop
        if (numberOfLoops > 0) {
            // let's update the result

            if (!firstCycleAlreadyHit) {
                result.graphSizeEdgesBeforeFirstCycle = graph.getEdgeCount();
                result.graphSizeNodesBeforeFirstCycle = graph.getNodeCount();

                // find the shortest cycle
                int shortestCycleLength = Integer.MAX_VALUE;

                for (List<Object> cycle : cyclesInGraph) {
                    shortestCycleLength = Math.min(shortestCycleLength, cycle.size());
                }
                result.lengthOfFirstCircle = shortestCycleLength;

                result.pairsBeforeFirstCycle = i;

                firstCycleAlreadyHit = true;
            }

            // ignore this edge further
            ignoredEdgesCount++;

            // update counts of different cycles lengths
            for (List<Object> cycle : cyclesInGraph) {
                int currentSize = cycle.size();

                // convert to sorted set of nodes
                List<String> cycleAsSortedIDs = new ArrayList<>();
                for (Object o : cycle) {
                    cycleAsSortedIDs.add(o.toString());
                }
                Collections.sort(cycleAsSortedIDs);

                if (range.contains(currentSize)) {
                    lengthCyclesMap.get(currentSize).add(cycleAsSortedIDs.toString());
                }
            }
        } else {
            addedPairsIndices.add(i);
        }

        // we hit the first cycle

        // collect loop sizes
        StringBuilder loopsAsString = new StringBuilder();
        for (int j = range.getMinimum(); j <= range.getMaximum(); j++) {
            //                    loopsAsString.append(j).append(":");
            loopsAsString.append(lengthCyclesMap.get(j).size());
            loopsAsString.append("\t");
        }

        psTable.printf(Locale.ENGLISH, "%.4f\t%d\t%d\t%b\t%.2f\t%d\t%d\t%d\t%d\t%s%n", weakestEdgeWeight, i,
                ignoredEdgesCount, numberOfLoops == 0,
                Double.isNaN(transitivityScore.getMean()) ? 0d : transitivityScore.getMean(),
                (int) transitivityScore.getMax(), transitivityScore.getN(), graph.getEdgeCount(),
                graph.getNodeCount(), loopsAsString.toString().trim());

        // update result
        result.finalGraphSizeEdges = graph.getEdgeCount();
        result.finalGraphSizeNodes = graph.getNodeCount();
        result.ignoredEdgesThatBrokeDAG = ignoredEdgesCount;

        // update stats for correlation
        correlationEdgeWeights[i] = weakestEdgeWeight;
        //            correlationRemovedEdges[i] =  (double) ignoredEdgesCount;
        // let's try: if we keep = 0, if we remove = 1
        correlationRemovedEdges[i] = numberOfLoops == 0 ? 0.0 : 1.0;
    }

    psInfo.println("Original: " + fullDataSize + ", removed by MACE: " + (fullDataSize - preFilteredDataSize)
            + ", final: " + (preFilteredDataSize - ignoredEdgesCount) + " (removed: " + ignoredEdgesCount
            + ")");

    double[][] matrix = new double[correlationEdgeWeights.length][];
    for (int i = 0; i < correlationEdgeWeights.length; i++) {
        matrix[i] = new double[2];
        matrix[i][0] = correlationEdgeWeights[i];
        matrix[i][1] = correlationRemovedEdges[i];
    }

    PearsonsCorrelation pearsonsCorrelation = new PearsonsCorrelation(matrix);

    double pValue = pearsonsCorrelation.getCorrelationPValues().getEntry(0, 1);
    double correlation = pearsonsCorrelation.getCorrelationMatrix().getEntry(0, 1);

    psInfo.printf(Locale.ENGLISH, "Correlation: %.3f, p-Value: %.4f%n", correlation, pValue);
    if (lastGraph == null) {
        throw new IllegalStateException("Graph is null");
    }

    // close
    psInfo.close();
    psTable.close();

    // save filtered final gold data
    List<AnnotatedArgumentPair> finalArgumentPairList = new ArrayList<>();

    for (Integer index : addedPairsIndices) {
        finalArgumentPairList.add(pairs.get(index));
    }
    XStreamTools.toXML(finalArgumentPairList, new File(outputDir, prefix + file.getName()));

    // TODO: here, we can add newly generated edges from graph transitivity
    if (collectGeneratedArgumentPairs) {
        Set<GeneratedArgumentPair> generatedArgumentPairs = new HashSet<>();
        // collect all arguments
        Map<String, Argument> allArguments = new HashMap<>();
        for (ArgumentPair argumentPair : pairs) {
            allArguments.put(argumentPair.getArg1().getId(), argumentPair.getArg1());
            allArguments.put(argumentPair.getArg2().getId(), argumentPair.getArg2());
        }

        Graph finalGraph = buildGraphFromArgumentPairs(finalArgumentPairList);
        for (Edge e : finalGraph.getEdgeSet()) {
            e.setAttribute(WEIGHT, 1.0);
        }

        for (Node j : finalGraph) {
            for (Node k : finalGraph) {
                if (j != k) {
                    // is there a path between?
                    BellmanFord bfShortest = new BellmanFord(WEIGHT, j.getId());
                    bfShortest.init(finalGraph);
                    bfShortest.compute();

                    Path shortestPath = bfShortest.getShortestPath(k);

                    if (shortestPath.size() > 0) {
                        // we have a path
                        GeneratedArgumentPair ap = new GeneratedArgumentPair();
                        Argument arg1 = allArguments.get(j.getId());

                        if (arg1 == null) {
                            throw new IllegalStateException("Cannot find argument " + j.getId());
                        }
                        ap.setArg1(arg1);

                        Argument arg2 = allArguments.get(k.getId());

                        if (arg2 == null) {
                            throw new IllegalStateException("Cannot find argument " + k.getId());
                        }
                        ap.setArg2(arg2);

                        ap.setGoldLabel("a1");
                        generatedArgumentPairs.add(ap);
                    }
                }
            }
        }
        // and now add the reverse ones
        Set<GeneratedArgumentPair> generatedReversePairs = new HashSet<>();
        for (GeneratedArgumentPair pair : generatedArgumentPairs) {
            GeneratedArgumentPair ap = new GeneratedArgumentPair();
            ap.setArg1(pair.getArg2());
            ap.setArg2(pair.getArg1());
            ap.setGoldLabel("a2");
            generatedReversePairs.add(ap);
        }
        generatedArgumentPairs.addAll(generatedReversePairs);
        // and save it
        XStreamTools.toXML(generatedArgumentPairs, new File(outputDir, "generated_" + prefix + file.getName()));
    }

    result.fullPairsSize = fullDataSize;
    result.removedApriori = (fullDataSize - preFilteredDataSize);
    result.finalPairsRetained = finalArgumentPairList.size();

    // save the final graph
    Graph outGraph = cleanCopyGraph(lastGraph);
    FileSinkDGS dgs1 = new FileSinkDGS();
    File outFile = new File(outputDir, prefix + file.getName() + ".dgs");

    System.out.println("Saved to " + outFile);
    FileWriter w1 = new FileWriter(outFile);

    dgs1.writeAll(outGraph, w1);
    w1.close();

    return result;
}

From source file:edu.oregonstate.eecs.mcplan.domains.blackjack.Experiments.java

private static <X extends Representation<BlackjackState>, R extends Representer<BlackjackState, X>> void runExperiment(
        final R repr, final BlackjackParameters params, final int Nepisodes, final double p, final int Ngames,
        final PrintStream data_out) {
    System.out.println("****************************************");
    System.out.println(/*from  w  ww  .  ja v  a2  s  .  c om*/
            "game = " + params.max_score + " x " + Ngames + ": " + repr + " x " + Nepisodes + ", p = " + p);

    final MctsVisitor<BlackjackState, BlackjackAction> visitor = new DefaultMctsVisitor<BlackjackState, BlackjackAction>();

    final ActionGenerator<BlackjackState, JointAction<BlackjackAction>> action_gen = new BlackjackJointActionGenerator(
            1);

    final double c = 1.0;
    final int rollout_width = 1;
    final int rollout_depth = Integer.MAX_VALUE;
    final double discount = 1.0;
    // Optimistic default value
    final double[] default_value = new double[] { 1.0 };
    final BackupRule<X, BlackjackAction> backup = BackupRule.<X, BlackjackAction>MaxQ();
    final MeanVarianceAccumulator ret = new MeanVarianceAccumulator();
    for (int i = 0; i < Ngames; ++i) {
        if (i % 100000 == 0) {
            System.out.println("Episode " + i);
        }

        final Deck deck = new InfiniteDeck();
        final BlackjackSimulator sim = new BlackjackSimulator(deck, 1, params);

        final Policy<BlackjackState, JointAction<BlackjackAction>> rollout_policy = new RandomPolicy<BlackjackState, JointAction<BlackjackAction>>(
                0 /*Player*/, rng.nextInt(), action_gen.create());
        final EvaluationFunction<BlackjackState, BlackjackAction> rollout_evaluator = RolloutEvaluator
                .create(rollout_policy, discount, rollout_width, rollout_depth);

        final GameTreeFactory<BlackjackState, X, BlackjackAction> factory = new UctSearch.Factory<BlackjackState, X, BlackjackAction>(
                sim, base_repr.create(), action_gen, c, Nepisodes, rng, rollout_evaluator, backup,
                default_value);

        final SearchPolicy<BlackjackState, X, BlackjackAction> search_policy = new SearchPolicy<BlackjackState, X, BlackjackAction>(
                factory, visitor, null) {

            @Override
            protected JointAction<BlackjackAction> selectAction(final GameTree<X, BlackjackAction> tree) {
                return BackupRules.MaxAction(tree.root()).a();
            }

            @Override
            public int hashCode() {
                return System.identityHashCode(this);
            }

            @Override
            public boolean equals(final Object that) {
                return this == that;
            }
        };

        final Episode<BlackjackState, BlackjackAction> episode = new Episode<BlackjackState, BlackjackAction>(
                sim, search_policy);
        episode.run();
        //         System.out.println( sim.state().token().toString() );
        //         System.out.println( "Reward: " + sim.reward()[0] );
        ret.add(sim.reward()[0]);
    }
    System.out.println("****************************************");
    System.out.println("Average return: " + ret.mean());
    System.out.println("Return variance: " + ret.variance());
    final double conf = 1.96 * Math.sqrt(ret.variance()) / Math.sqrt(Ngames);
    System.out.println("Confidence: " + conf);
    System.out.println();
    data_out.print(repr);
    data_out.print("," + params.max_score);
    data_out.print("," + Ngames);
    data_out.print("," + Nepisodes);
    data_out.print("," + p);
    data_out.print("," + ret.mean());
    data_out.print("," + ret.variance());
    data_out.print("," + conf);
    data_out.println();
}

From source file:me.mast3rplan.phantombot.PhantomBot.java

public PhantomBot(Properties pbProperties) {

    /* Set the exeption handler */
    Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance());

    /* Start loading the bot information */
    print("");//from  ww  w  .  j a v a2s  .  co  m
    print(botVersion());
    print(botRevision());
    print(getBotCreator());
    print(botDevelopers());
    print(getWebSite());
    print("");

    /* System interactive */
    interactive = (System.getProperty("interactive") != null);

    /* Assign properties passed in to local instance. */
    this.pbProperties = pbProperties;

    /* Set the default bot variables */
    this.botName = this.pbProperties.getProperty("user").toLowerCase();
    this.channelName = this.pbProperties.getProperty("channel").toLowerCase();
    this.ownerName = this.pbProperties.getProperty("owner").toLowerCase();
    this.apiOAuth = this.pbProperties.getProperty("apioauth", "");
    this.oauth = this.pbProperties.getProperty("oauth");

    /* Set the web variables */
    this.youtubeOAuth = this.pbProperties.getProperty("ytauth");
    this.youtubeOAuthThro = this.pbProperties.getProperty("ytauthro");
    this.youtubeKey = this.pbProperties.getProperty("youtubekey", "");
    this.basePort = Integer.parseInt(this.pbProperties.getProperty("baseport", "25000"));
    this.webOAuth = this.pbProperties.getProperty("webauth");
    this.webOAuthThro = this.pbProperties.getProperty("webauthro");
    this.webEnabled = this.pbProperties.getProperty("webenable", "true").equalsIgnoreCase("true");
    this.musicEnabled = this.pbProperties.getProperty("musicenable", "true").equalsIgnoreCase("true");
    this.useHttps = this.pbProperties.getProperty("usehttps", "false").equalsIgnoreCase("true");

    /* Set the datastore variables */
    this.dataStoreType = this.pbProperties.getProperty("datastore", "");
    this.dataStoreConfig = this.pbProperties.getProperty("datastoreconfig", "");

    /* Set the Twitter variables */
    this.twitterUsername = this.pbProperties.getProperty("twitterUser", "");
    this.twitterConsumerToken = this.pbProperties.getProperty("twitter_consumer_key", "");
    this.twitterConsumerSecret = this.pbProperties.getProperty("twitter_consumer_secret", "");
    this.twitterAccessToken = this.pbProperties.getProperty("twitter_access_token", "");
    this.twitterSecretToken = this.pbProperties.getProperty("twitter_secret_token", "");
    this.twitterAuthenticated = false;

    /* Set the Discord variables */
    this.discordToken = this.pbProperties.getProperty("discord_token", "");

    /* Set the GameWisp variables */
    this.gameWispOAuth = this.pbProperties.getProperty("gamewispauth", "");
    this.gameWispRefresh = this.pbProperties.getProperty("gamewisprefresh", "");

    /* Set the TwitchAlerts variables */
    this.twitchAlertsKey = this.pbProperties.getProperty("twitchalertskey", "");
    this.twitchAlertsLimit = Integer.parseInt(this.pbProperties.getProperty("twitchalertslimit", "5"));

    /* Set the StreamTip variables */
    this.streamTipOAuth = this.pbProperties.getProperty("streamtipkey", "");
    this.streamTipClientId = this.pbProperties.getProperty("streamtipid", "");
    this.streamTipLimit = Integer.parseInt(this.pbProperties.getProperty("streamtiplimit", "5"));

    /* Set the TipeeeStream variables */
    this.tipeeeStreamOAuth = this.pbProperties.getProperty("tipeeestreamkey", "");
    this.tipeeeStreamLimit = Integer.parseInt(this.pbProperties.getProperty("tipeeestreamlimit", "5"));

    /* Set the MySql variables */
    this.mySqlName = this.pbProperties.getProperty("mysqlname", "");
    this.mySqlUser = this.pbProperties.getProperty("mysqluser", "");
    this.mySqlPass = this.pbProperties.getProperty("mysqlpass", "");
    this.mySqlHost = this.pbProperties.getProperty("mysqlhost", "");
    this.mySqlPort = this.pbProperties.getProperty("mysqlport", "");

    /* twitch cache */
    PhantomBot.twitchCacheReady = "false";

    /* Set the SSL info */
    this.httpsFileName = this.pbProperties.getProperty("httpsFileName", "");
    this.httpsPassword = this.pbProperties.getProperty("httpsPassword", "");

    /* Set the timeZone */
    PhantomBot.timeZone = this.pbProperties.getProperty("logtimezone", "GMT");

    /* Set the panel username login for the panel to use */
    this.panelUsername = this.pbProperties.getProperty("paneluser", "panel");

    /* Set the panel password login for the panel to use */
    this.panelPassword = this.pbProperties.getProperty("panelpassword", "panel");

    /* Enable/disable devCommands */
    this.devCommands = this.pbProperties.getProperty("devcommands", "false").equalsIgnoreCase("true");

    /* Toggle for the old servers. */
    this.legacyServers = this.pbProperties.getProperty("legacyservers", "false").equalsIgnoreCase("true");

    /*
     * Set the message limit for session.java to use, note that Twitch rate limits at 100 messages in 30 seconds
     * for moderators.  For non-moderators, the maximum is 20 messages in 30 seconds. While it is not recommended
     * to go above anything higher than 18.75 in case the bot is ever de-modded, the option is available but is
     * capped at 80.0. 
     */
    PhantomBot.messageLimit = Double.parseDouble(this.pbProperties.getProperty("msglimit30", "18.75"));
    if (PhantomBot.messageLimit > 80.0) {
        PhantomBot.messageLimit = 80.0;
    } else if (PhantomBot.messageLimit < 18.75) {
        PhantomBot.messageLimit = 18.75;
    }

    /* Set the whisper limit for session.java to use. -- Currently Not Used -- */
    PhantomBot.whisperLimit = Double.parseDouble(this.pbProperties.getProperty("whisperlimit60", "60.0"));

    /* Set the client id for the twitch api to use */
    this.clientId = this.pbProperties.getProperty("clientid", "7wpchwtqz7pvivc3qbdn1kajz42tdmb");

    /* Set any SQLite backup options. */
    this.backupSQLiteAuto = this.pbProperties.getProperty("backupsqliteauto", "false").equalsIgnoreCase("true");
    this.backupSQLiteHourFrequency = Integer
            .parseInt(this.pbProperties.getProperty("backupsqlitehourfreqency", "24"));
    this.backupSQLiteKeepDays = Integer.parseInt(this.pbProperties.getProperty("backupsqlitekeepdays", "5"));

    /* Load up a new SecureRandom for the scripts to use */
    random = new SecureRandom();

    /* Create a map for multiple channels. */
    channels = new HashMap<>();

    /* Create a map for multiple sessions. */
    sessions = new HashMap<>();

    /* Create a map for multiple oauth tokens. */
    apiOAuths = new HashMap<>();

    /* Load the datastore */
    if (dataStoreType.equalsIgnoreCase("inistore")) {
        dataStore = IniStore.instance();
    } else if (dataStoreType.equalsIgnoreCase("mysqlstore")) {
        dataStore = MySQLStore.instance();
        if (this.mySqlPort.isEmpty()) {
            this.mySqlConn = "jdbc:mysql://" + this.mySqlHost + "/" + this.mySqlName + "?useSSL=false";
        } else {
            this.mySqlConn = "jdbc:mysql://" + this.mySqlHost + ":" + this.mySqlPort + "/" + this.mySqlName
                    + "?useSSL=false";
        }
        /* Check to see if we can create a connection */
        if (dataStore.CreateConnection(this.mySqlConn, this.mySqlUser, this.mySqlPass) == null) {
            print("Could not create a connection with MySql. PhantomBot now shutting down...");
            System.exit(0);
        }
        /* Convert to MySql */
        if (IniStore.instance().GetFileList().length > 0) {
            ini2MySql(true);
        } else if (SqliteStore.instance().GetFileList().length > 0) {
            sqlite2MySql();
        }
    } else {
        dataStoreType = "sqlite3store";
        dataStore = SqliteStore.instance();
        /* Create indexes. */
        if (!dataStore.exists("settings", "tables_indexed")) {
            print("Creating SQLite3 Indexes. This might take time...");
            dataStore.CreateIndexes();
            dataStore.set("settings", "tables_indexed", "true");
            print("Completed Creating SQLite3 Indexes!");
        }
        /* Convert the initstore to sqlite if the inistore exists and the db is empty */
        if (IniStore.instance().GetFileList().length > 0 && SqliteStore.instance().GetFileList().length == 0) {
            ini2Sqlite(true);
        }
    }

    /* Set the client Id in the Twitch api. */
    TwitchAPIv3.instance().SetClientID(this.clientId);

    /* Set the oauth key in the Twitch api. */
    if (!this.apiOAuth.isEmpty()) {
        TwitchAPIv3.instance().SetOAuth(this.apiOAuth);
    }

    /* Set the TwitchAlerts OAuth key and limiter. */
    if (!twitchAlertsKey.isEmpty()) {
        TwitchAlertsAPIv1.instance().SetAccessToken(twitchAlertsKey);
        TwitchAlertsAPIv1.instance().SetDonationPullLimit(twitchAlertsLimit);
    }

    /* Set the YouTube API Key if provided. */
    if (!this.youtubeKey.isEmpty()) {
        YouTubeAPIv3.instance().SetAPIKey(this.youtubeKey);
    }

    /* Set the StreamTip OAuth key, Client ID and limiter. */
    if (!streamTipOAuth.isEmpty() && !streamTipClientId.isEmpty()) {
        StreamTipAPI.instance().SetAccessToken(streamTipOAuth);
        StreamTipAPI.instance().SetDonationPullLimit(streamTipLimit);
        StreamTipAPI.instance().SetClientId(streamTipClientId);
    }

    /* Set the TipeeeStream oauth key. */
    if (!tipeeeStreamOAuth.isEmpty()) {
        TipeeeStreamAPIv1.instance().SetOauth(tipeeeStreamOAuth);
        TipeeeStreamAPIv1.instance().SetLimit(tipeeeStreamLimit);
    }

    /* Start things and start loading the scripts. */
    this.init();

    /* Start a channel instance to create a session, and then connect to WS-IRC @ Twitch. */
    this.channel = Channel.instance(this.channelName, this.botName, this.oauth, EventBus.instance());

    /* Start a host checking instance. */
    if (apiOAuth.length() > 0 && checkModuleEnabled("./handlers/hostHandler.js")) {
        this.wsHostIRC = TwitchWSHostIRC.instance(this.channelName, this.apiOAuth, EventBus.instance());
    }

    /* Start a pubsub instance here. */
    if (this.oauth.length() > 0 && checkDataStore("chatModerator", "moderationLogs")) {
        this.pubSubEdge = TwitchPubSub.instance(this.channelName,
                TwitchAPIv3.instance().getChannelId(this.channelName),
                TwitchAPIv3.instance().getChannelId(this.botName), this.oauth);
    }

    /* Check if the OS is Linux. */
    if (SystemUtils.IS_OS_LINUX && !interactive) {
        try {
            java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory
                    .getRuntimeMXBean();
            int pid = Integer.parseInt(runtime.getName().split("@")[0]);

            File file = new File("PhantomBot." + this.botName.toLowerCase() + ".pid");

            try (FileOutputStream fs = new FileOutputStream(file, false)) {
                PrintStream ps = new PrintStream(fs);
                ps.print(pid);
            }
            file.deleteOnExit();
        } catch (SecurityException | IllegalArgumentException | IOException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }
}

From source file:com.lmco.ddf.commands.catalog.RemoveAllCommand.java

@Override
protected Object doExecute() throws Exception {

    PrintStream console = System.out;

    if (batchSize < PAGE_SIZE_LOWER_LIMIT) {
        printColor(console, Ansi.Color.RED, String.format(BATCH_SIZE_ERROR_MESSAGE_FORMAT, batchSize));

        return null;
    }/*from   w w  w.  ja va 2  s .c  o  m*/

    CatalogFacade catalog = this.getCatalog();

    if (isAccidentalRemoval(console)) {
        return null;
    }

    FilterBuilder filterBuilder = getFilterBuilder();

    QueryRequest firstQuery = getIntendedQuery(filterBuilder, batchSize, expired, true);
    QueryRequest subsequentQuery = getIntendedQuery(filterBuilder, batchSize, expired, false);

    long totalAmountDeleted = 0;
    long start = System.currentTimeMillis();

    SourceResponse response = null;
    try {
        response = catalog.query(firstQuery);
    } catch (UnsupportedQueryException e) {
        firstQuery = getAlternateQuery(filterBuilder, batchSize, expired, true);
        subsequentQuery = getAlternateQuery(filterBuilder, batchSize, expired, false);

        response = catalog.query(firstQuery);
    }

    if (response == null) {
        printColor(console, Ansi.Color.RED, "No response from Catalog.");
        return null;
    }

    if (needsAlternateQueryAndResponse(response)) {
        firstQuery = getAlternateQuery(filterBuilder, batchSize, expired, true);
        subsequentQuery = getAlternateQuery(filterBuilder, batchSize, expired, false);

        response = catalog.query(firstQuery);
    }

    String totalAmount = getTotalAmount(response.getHits());

    while (response.getResults().size() > 0) {

        List<String> ids = new ArrayList<String>();

        // Add metacard ids to string array
        for (Result result : response.getResults()) {
            if (result != null && result.getMetacard() != null) {
                Metacard metacard = result.getMetacard();
                ids.add(metacard.getId());
            }

        }

        // Delete the records
        DeleteRequestImpl request = new DeleteRequestImpl(ids.toArray(new String[ids.size()]));

        DeleteResponse deleteResponse = catalog.delete(request);

        int amountDeleted = deleteResponse.getDeletedMetacards().size();

        totalAmountDeleted += amountDeleted;
        console.print(String.format(PROGRESS_FORMAT, totalAmountDeleted, totalAmount));
        console.flush();

        // Break out if there are no more records to delete
        if (amountDeleted < batchSize || batchSize < 1) {
            break;
        }

        // Re-query when necessary
        response = catalog.query(subsequentQuery);
    }

    long end = System.currentTimeMillis();

    console.println();

    console.printf(" %d file(s) removed in %3.3f seconds%n", totalAmountDeleted,
            (end - start) / MILLISECONDS_PER_SECOND);

    return null;

}

From source file:edu.ku.brc.dbsupport.ImportExportDB.java

/**
     * write all the records of the given table.
     * @param dbTable the class name of the table
     * @return creates an xml file with name of the table
     *//*from  w  ww. ja  v  a2 s . c o  m*/
    @SuppressWarnings("unchecked")
    public void writeXMLfile(String dataBase) {
        FileOutputStream fout;

        Session dom4jSession = session.getSession(EntityMode.DOM4J);
        String query = "from " + dataBase + " where id = 1"; //$NON-NLS-1$ //$NON-NLS-2$

        System.out.println(query);

        List userXML = dom4jSession.createQuery(query).list();
        try {
            fout = new FileOutputStream(importFolderPath + dataBase + ".xml"); //$NON-NLS-1$
            PrintStream p = new PrintStream(fout);
            p.print("<root>"); //$NON-NLS-1$
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(fout, format);

            for (int i = 0; i < userXML.size(); i++) {
                Element writeMe = (Element) userXML.get(i);
                writer.write(writeMe);
            }
            p.println("\n</root>"); //$NON-NLS-1$
            p.close();
            fout.close();
            writer.close();
            System.out.println("Wrote: " + dataBase + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$
        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex);
            ex.printStackTrace();
        }

    }

From source file:edu.ku.brc.dbsupport.ImportExportDB.java

/**
     * write a single record//from  ww w .j  av a2  s . co m
     * @param dbTable the class name of the table
     * @param id the id number of the record
     */
    @SuppressWarnings("unchecked")
    public void writeSingleRecordXML(String dbTable, int id) {
        FileOutputStream fout;

        Session dom4jSession = session.getSession(EntityMode.DOM4J);
        // load the object by using its primary key
        DBTableInfo info = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase());
        String primaryKey = info.getPrimaryKeyName();
        String query = "from " + dbTable + " where " + primaryKey + " = " + id; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

        List userXML = dom4jSession.createQuery(query).list();

        try {
            fout = new FileOutputStream(importFolderPath + dbTable + ".xml"); //$NON-NLS-1$
            PrintStream p = new PrintStream(fout);
            p.print("<root>"); //$NON-NLS-1$
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(fout, format);

            for (int i = 0; i < userXML.size(); i++) {
                Element writeMe = (Element) userXML.get(i);
                writer.write(writeMe);
            }
            p.println("\n</root>"); //$NON-NLS-1$
            p.close();
            fout.close();
            writer.close();
            System.out.println("Wrote: " + dbTable + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$
        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex);
            ex.printStackTrace();
        }
        System.out.println();
    }