Example usage for java.lang System setOut

List of usage examples for java.lang System setOut

Introduction

In this page you can find the example usage for java.lang System setOut.

Prototype

public static void setOut(PrintStream out) 

Source Link

Document

Reassigns the "standard" output stream.

Usage

From source file:org.apache.hadoop.hdfs.TestDFSShell.java

private static void runCount(String path, long dirs, long files, FsShell shell) throws IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(bytes);
    PrintStream oldOut = System.out;
    System.setOut(out);
    Scanner in = null;/*from   w  w  w .j a v a 2 s  . co m*/
    String results = null;
    try {
        runCmd(shell, "-count", path);
        results = bytes.toString();
        in = new Scanner(results);
        assertEquals(dirs, in.nextLong());
        assertEquals(files, in.nextLong());
    } finally {
        if (in != null) {
            in.close();
        }
        IOUtils.closeStream(out);
        System.setOut(oldOut);
        System.out.println("results:\n" + results);
    }
}

From source file:com.alibaba.jstorm.utils.JStormUtils.java

public static void redirectOutput(String file) throws Exception {

    System.out.println("Redirect output to " + file);

    FileOutputStream workerOut = new FileOutputStream(new File(file));

    PrintStream ps = new PrintStream(new BufferedOutputStream(workerOut), true);
    System.setOut(ps);
    System.setErr(ps);//from   w ww .  ja  v a  2s  . co m

    LOG.info("Successfully redirect System.out to " + file);

}

From source file:org.bonitasoft.engine.test.ConnectorExecutionsLocalIT.java

@Cover(classes = Connector.class, concept = BPMNConcept.CONNECTOR, keywords = { "Connector",
        "Missing class connector",
        "Process instance" }, story = "Execute connector with missing class on process instance.", jira = "")
@Test//w  w w.j a  va 2s . com
public void executeMissingClassConnectorOnProcessInstance() throws Exception {
    final PrintStream stdout = System.out;
    final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
    System.setOut(new PrintStream(myOut));
    try {
        final ProcessDefinitionBuilder processDefBuilder = new ProcessDefinitionBuilder()
                .createNewInstance("executeConnectorOnActivityInstance", "1.0");
        processDefBuilder.addActor(ACTOR_NAME).addUserTask("step1", ACTOR_NAME).addConnector(
                "UnkownClassConnector", "unkownClassConnectorDef", "1.0.0", ConnectorEvent.ON_ENTER);
        final BusinessArchiveBuilder businessArchiveBuilder = new BusinessArchiveBuilder()
                .createNewBusinessArchive().setProcessDefinition(processDefBuilder.done());
        businessArchiveBuilder.addConnectorImplementation(
                new BarResource("UnknownClassConnector.impl", IOUtils.toByteArray(BPMRemoteTests.class
                        .getResourceAsStream("/org/bonitasoft/engine/connectors/UnknownClassConnector.impl"))));
        final ProcessDefinition processDefinition = deployAndEnableProcessWithActor(
                businessArchiveBuilder.done(), ACTOR_NAME, user);

        final ProcessInstance processInstance = getProcessAPI().startProcess(processDefinition.getId());
        waitForFlowNodeInFailedState(processInstance, "step1");
        disableAndDeleteProcess(processDefinition);
    } finally {
        System.setOut(stdout);
    }
    final String logs = myOut.toString();
    System.out.println(logs);
    assertTrue("should have written in logs an exception", logs.contains("SConnectorException"));
    assertTrue("should have written in logs an exception", logs.contains("org.unknown.MyUnknownClass"));
}

From source file:edu.oregonstate.eecs.mcplan.search.UTreeSearch.java

public static void main(final String[] argv) throws FileNotFoundException {
    System.setOut(new PrintStream(new FileOutputStream(new File("UTreeSearch.log"))));

    final MersenneTwister rng = new MersenneTwister(44);
    final double c = 100.0;
    final int Ngames = 1;
    final int Nepisodes = 2 << 11;
    final int split_threshold = 2 << 9;
    final int top_actions = 2;
    final double size_regularization = 1;

    //      final ChainWalk cw = new ChainWalk( 2, 0.2, 10 );
    //      final ChainWalk.Simulator sim = cw.new Simulator( cw.new State() );
    //      final ChainWalk.ActionGen action_gen = cw.new ActionGen( rng );
    //      final UTreeSearch<ChainWalk.State, ChainWalk.Action> ut
    //         = new UTreeSearch<ChainWalk.State, ChainWalk.Action>(
    //            ResetAdapter.of( sim ), new ChainWalk.IdentityRepresenter(),
    //            SingleAgentJointActionGenerator.create( action_gen ), c, Nepisodes,
    //            getChainWalkEvaluator( rng, action_gen.create() ),
    //            new DefaultMctsVisitor<ChainWalk.State, ChainWalk.Action>() );
    //      ut.run();

    //      for( int i = 0; i < Ngames; ++i ) {
    //         final FuelWorldState fw = FuelWorldState.createDefaultWithChoices( rng );
    //         final FuelWorldSimulator sim = new FuelWorldSimulator( fw );
    //         final FuelWorldActionGenerator action_gen = new FuelWorldActionGenerator();
    ///*w  ww .j ava  2  s .  c  o m*/
    //         while( !fw.isTerminal() ) {
    //            final UTreeSearch<FuelWorldState, FuelWorldAction> ut
    //               = new UTreeSearch<FuelWorldState, FuelWorldAction>(
    //                  ResetAdapter.of( sim ), new PrimitiveFuelWorldRepresenter(),
    //                  SingleAgentJointActionGenerator.create( action_gen ), c, Nepisodes,
    //                  getFuelWorldEvaluator( rng, action_gen.create() ),
    //                  new DefaultMctsVisitor<FuelWorldState, FuelWorldAction>(),
    //                  split_threshold, top_actions, size_regularization );
    //
    //            ut.run();
    //
    //            final JointAction<FuelWorldAction> astar = BackupRules.MaxAction( ut.root() ).a();
    //            System.out.println( astar );
    //            System.out.println( "********************" );
    //            sim.takeAction( astar );
    //
    //            break;
    //         }
    //      }

    //      final int L = 3;
    //      final int W = 4;
    //      final int F = 2;
    //      for( int i = 0; i < Ngames; ++i ) {
    //         final CliffWorld.State s = new CliffWorld.State( L, W, F );
    //         final CliffWorld.Simulator sim = new CliffWorld.Simulator( s, rng );
    //         final CliffWorld.Actions actions = new CliffWorld.Actions( rng );
    //
    //         int t = 0;
    //         while( !s.isTerminal() ) {
    //            final UTreeSearch<CliffWorld.State, CliffWorld.Action> ut
    //               = new UTreeSearch<CliffWorld.State, CliffWorld.Action>(
    //                  ResetAdapter.of( sim ), new CliffWorld.PrimitiveRepresenter(),
    //                  SingleAgentJointActionGenerator.create( actions ), c, Nepisodes,
    //                  getEvaluator( rng, actions.create() ),
    //                  new DefaultMctsVisitor<CliffWorld.State, CliffWorld.Action>(),
    //                  split_threshold, top_actions, size_regularization );
    //
    //            ut.run();
    //
    //
    //            final JointAction<CliffWorld.Action> astar = BackupRules.MaxAction( ut.root() ).a();
    //            System.out.println( astar );
    //            System.out.println( "********************" );
    //            sim.takeAction( astar );
    //
    //            System.out.println( "****************************************" );
    //            System.out.println( "** Final tree **************************" );
    //            ut.root().accept( new TreePrinter<CliffWorld.State, CliffWorld.Action>( 8 ) );
    //            System.out.println( "----------------------------------------" );
    //
    //            if( t++ == 1 ) {
    //               break;
    //            }
    //         }
    //      }

    final int Nother_taxis = 1;
    final double slip = 0.2;
    for (int i = 0; i < Ngames; ++i) {
        final TaxiState s = TaxiWorlds.dietterich2000(rng, Nother_taxis, slip);
        final TaxiSimulator sim = new TaxiSimulator(rng, s, slip, 40);
        final TaxiActionGenerator actions = new TaxiActionGenerator();

        int t = 0;
        while (!s.isTerminal()) {
            final UTreeSearch<TaxiState, TaxiAction> ut = new UTreeSearch<TaxiState, TaxiAction>(
                    ResetAdapter.of(sim), new PrimitiveTaxiRepresenter(s),
                    SingleAgentJointActionGenerator.create(actions), c, Nepisodes,
                    getEvaluator(rng, actions.create()), new DefaultMctsVisitor<TaxiState, TaxiAction>(),
                    split_threshold, top_actions, size_regularization);

            ut.run();

            final JointAction<TaxiAction> astar = BackupRules.MaxAction(ut.root()).a();
            System.out.println(astar);
            System.out.println("********************");
            sim.takeAction(astar);

            System.out.println("****************************************");
            System.out.println("** Final tree **************************");
            ut.root().accept(new TreePrinter<TaxiState, TaxiAction>(8));
            System.out.println("----------------------------------------");

            if (t++ == 10) {
                break;
            }
        }
    }
}

From source file:com.jug.MoMA.java

/**
 * Created and shows the console window and redirects System.out and
 * System.err to it.//from   ww w .  jav  a  2 s.com
 */
private void initConsoleWindow() {
    frameConsoleWindow = new JFrame(String.format("%s Console Window", this.VERSION_STRING));
    // frameConsoleWindow.setResizable( false );
    consoleWindowTextArea = new JTextArea();
    consoleWindowTextArea.setLineWrap(true);
    consoleWindowTextArea.setWrapStyleWord(true);

    final int centerX = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2;
    final int centerY = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2;
    frameConsoleWindow.setBounds(centerX - GUI_CONSOLE_WIDTH / 2, centerY - GUI_HEIGHT / 2, GUI_CONSOLE_WIDTH,
            GUI_HEIGHT);
    final JScrollPane scrollPane = new JScrollPane(consoleWindowTextArea);
    //      scrollPane.setHorizontalScrollBarPolicy( ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );
    scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 15, 0, 0));
    frameConsoleWindow.getContentPane().add(scrollPane);

    final OutputStream out = new OutputStream() {

        private final PrintStream original = new PrintStream(System.out);

        @Override
        public void write(final int b) throws IOException {
            updateConsoleTextArea(String.valueOf((char) b));
            original.print(String.valueOf((char) b));
        }

        @Override
        public void write(final byte[] b, final int off, final int len) throws IOException {
            updateConsoleTextArea(new String(b, off, len));
            original.print(new String(b, off, len));
        }

        @Override
        public void write(final byte[] b) throws IOException {
            write(b, 0, b.length);
        }
    };

    final OutputStream err = new OutputStream() {

        private final PrintStream original = new PrintStream(System.out);

        @Override
        public void write(final int b) throws IOException {
            updateConsoleTextArea(String.valueOf((char) b));
            original.print(String.valueOf((char) b));
        }

        @Override
        public void write(final byte[] b, final int off, final int len) throws IOException {
            updateConsoleTextArea(new String(b, off, len));
            original.print(new String(b, off, len));
        }

        @Override
        public void write(final byte[] b) throws IOException {
            write(b, 0, b.length);
        }
    };

    System.setOut(new PrintStream(out, true));
    System.setErr(new PrintStream(err, true));
}

From source file:org.apache.hadoop.fs.TestCopyFiles.java

static String execCmd(FsShell shell, String... args) throws Exception {
    ByteArrayOutputStream baout = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(baout, true);
    PrintStream old = System.out;
    System.setOut(out);
    shell.run(args);/*from   ww  w .j a  v  a  2s  . c o  m*/
    out.close();
    System.setOut(old);
    return baout.toString();
}

From source file:org.hyperic.hq.bizapp.agent.client.AgentClient.java

private void redirectOutputs(Properties bootProp) {
    if (this.redirectedOutputs) {
        return;/*  w ww.j  a va  2  s.  co  m*/
    }
    this.redirectedOutputs = true;

    try {
        System.setErr(newLogStream("SystemErr", bootProp));
        System.setOut(newLogStream("SystemOut", bootProp));
    } catch (Exception e) {
        e.printStackTrace(SYSTEM_ERR);
    }
}

From source file:net.sourceforge.seqware.pipeline.deciders.BasicDeciderTest.java

/**
 * Don't use the output of this thing unless you really really have to
 * stdout can change a lot/*from   w w  w .  j  av a 2s  .c  om*/
 * @param params
 * @return 
 */
protected String launchAndCaptureOutput(String[] params) {
    ByteArrayOutputStream testOut = new ByteArrayOutputStream();
    System.setOut(new PrintStream(testOut));
    launchPlugin(params);
    String redirected = testOut.toString();
    System.setOut(System.out);
    return redirected;
}

From source file:edu.isi.wings.catalog.component.api.impl.kb.ComponentReasoningKB.java

/**
 * <b>Query 4.2</b><br/>
 * This function is supposed to <b>SET</b> the DataSet Metrics, or Parameter
 * Values for the Variables that are passed in via the input/output maps as
 * part of details.<br/>//www.j av  a 2s.c om
 * Variables will already be bound to dataObjects, so the function will have
 * to do something like the following :
 * 
 * <pre>
 * If Variable.isParameterVariable() Variable.setParameterValue(value)
 * If Variable.isDataVariable() Variable.getDataObjectBinding().setDataMetrics(xml)
 * </pre>
 * 
 * @param details
 *            A ComponentDetails Object which contains:
 *            <ul>
 *            <li>component,
 *            <li>maps of component input arguments to template variables,
 *            <li>maps of component output arguments to template variables,
 *            <li>template variable descriptions (dods) - list of triples
 *            </ul>
 * @return List of extra template variable descriptions (will mostly be
 *         empty in Q4.2 though)
 */
public ArrayList<ComponentPacket> findOutputDataPredictedDescriptions(ComponentPacket details) {
    ArrayList<ComponentPacket> list = new ArrayList<ComponentPacket>();

    HashMap<String, KBObject> omap = this.objPropMap;
    HashMap<String, KBObject> dmap = this.dataPropMap;

    // If the component has no rules, then simplify !!

    // Extract info from details object
    ComponentVariable c = details.getComponent();
    HashMap<String, Variable> sRoleMap = details.getStringRoleMaps();
    HashMap<String, Boolean> noParamBindings = new HashMap<String, Boolean>();

    ArrayList<KBTriple> redbox = details.getRequirements();

    Component comp = this.getCachedComponent(c.getBinding().getID());
    if (comp == null) {
        logger.debug(c.getBinding().getID() + " is not a valid component");
        details.addExplanations(c.getBinding().getID() + " is not a valid component");
        details.setInvalidFlag(true);
        list.add(details);
        return list;
    }

    c.setRequirements(comp.getComponentRequirement());

    boolean typesOk = true;

    // Set default parameter values (if not already set)
    // - Also recheck type compatibility
    ArrayList<String> inputRoles = new ArrayList<String>();
    for (ComponentRole role : comp.getInputs()) {
        inputRoles.add(role.getRoleName());
        Variable v = sRoleMap.get(role.getRoleName());
        if (role.isParam()) {
            if (v.getBinding() == null) {
                v.setBinding(new ValueBinding(role.getParamDefaultalue()));
                noParamBindings.put(v.getID(), true);
            } else if (v.getBinding().getValue() == null) {
                v.getBinding().setValue(role.getParamDefaultalue());
                noParamBindings.put(v.getID(), true);
            }
        } else {
            ArrayList<String> varclassids = new ArrayList<String>();
            ArrayList<Metric> vartypes = v.getBinding().getMetrics().getMetrics().get(KBUtils.RDF + "type");
            if (vartypes != null) {
                for (Metric m : vartypes) {
                    varclassids.add(m.getValueAsString());
                }
                // Check type compatibility of roles
                if (!checkTypeCompatibility(varclassids, role.getID())) {
                    details.addExplanations("INFO " + comp + " is not selectable because " + role.getID()
                            + " is not type compatible with variable binding: " + v.getBinding());
                    typesOk = false;
                    break;
                }
            }
        }
    }
    details.setInputRoles(inputRoles);

    if (!typesOk) {
        details.setInvalidFlag(true);
        list.add(details);
        return list;
    }

    if (!comp.hasRules()) {
        // No rules. Just set default parameter values (if not already set)
        list.add(details);
        return list;
    }

    // Create a new temporary KB store to run rules on
    KBAPI tkb = this.ontologyFactory.getKB(OntSpec.PLAIN);

    KBObject compobj = this.kb.getIndividual(comp.getID());

    // Add component to the temporary KB store (add all its classes
    // explicitly)
    KBObject tcomp = this.copyObjectIntoKB(comp.getID(), compobj, tkb, this.pcdomns, null, false);

    // Keep a map of variable object to variable name
    HashMap<Variable, String> variableNameMap = new HashMap<Variable, String>();

    for (String rolestr : sRoleMap.keySet()) {
        Variable var = sRoleMap.get(rolestr);
        // Map template variable to a temporary variable for running rules
        // - Reason is that the same variable may be used in multiple roles
        // and we want to distinguish them
        String variableName = var.getID() + "_" + rolestr;
        variableNameMap.put(var, variableName);
    }
    // Add the information from redbox to the temporary KB store
    // Cache varid to varobj
    HashMap<String, KBObject> varIDObjMap = new HashMap<String, KBObject>();
    for (Variable var : sRoleMap.values()) {
        KBObject varobj = tkb.getResource(variableNameMap.get(var));
        varIDObjMap.put(var.getID(), varobj);
    }
    // Add information from redbox
    for (KBTriple t : redbox) {
        KBObject subj = varIDObjMap.get(t.getSubject().getID());
        KBObject obj = varIDObjMap.get(t.getObject().getID());
        if (subj == null)
            subj = t.getSubject();
        if (obj == null)
            obj = t.getObject();
        tkb.addTriple(subj, t.getPredicate(), obj);
    }

    // Get a mapping of ArgID's to arg for the Component
    // Also note which roles are inputs
    HashMap<String, ComponentRole> argMaps = new HashMap<String, ComponentRole>();
    HashMap<String, Boolean> sInputRoles = new HashMap<String, Boolean>();
    for (ComponentRole role : comp.getInputs()) {
        argMaps.put(role.getRoleName(), role);
        sInputRoles.put(role.getRoleName(), true);
    }
    for (ComponentRole role : comp.getOutputs()) {
        argMaps.put(role.getRoleName(), role);
    }

    // Convert metrics to Property assertions in the Temporary KB
    for (String rolestr : sRoleMap.keySet()) {
        Variable var = sRoleMap.get(rolestr);
        ComponentRole arg = argMaps.get(rolestr);
        if (arg == null) {
            details.addExplanations("ERROR Component catalog cannot recognize role id " + rolestr);
            continue;
        }
        String variableName = variableNameMap.get(var);

        // Get a KBObject for the temporary variable
        KBObject varobj = tkb.getResource(variableName);

        if (var.isDataVariable()) {
            // If the variable is a data variable (& is bound)
            if (var.getBinding() != null) {
                // Convert Metrics to PC properties in order to run rules
                Metrics metrics = var.getBinding().getMetrics();
                HashMap<String, ArrayList<Metric>> propValMap = metrics.getMetrics();
                for (String propid : propValMap.keySet()) {
                    for (Metric tmp : propValMap.get(propid)) {
                        Object val = tmp.getValue();
                        String valstring = tmp.getValueAsString();
                        int type = tmp.getType();
                        String dtype = tmp.getDatatype();
                        KBObject metricProp = this.kb.getProperty(propid);
                        if (metricProp != null) {
                            //System.out.println(var.getName()+": " + propid + " = " +valstring);
                            if (type == Metric.URI) {
                                // Object Property
                                KBObject valobj = this.kb.getResource(valstring);
                                if (valobj == null) {
                                    // TODO: Log and explain (make a utility
                                    // function)
                                    details.addExplanations(
                                            "ERROR Cannot Recognize Metrics Value " + valstring);
                                    continue;
                                }
                                // Copy over the object class into kb as well
                                // (except where the object itself is a class)
                                if (!metricProp.getID().equals(KBUtils.RDF + "type")) {
                                    valobj = this.copyObjectIntoKB(valobj.getID(), valobj, tkb, null, null,
                                            true);
                                    // Remove any existing values first
                                    for (KBTriple t : tkb.genericTripleQuery(varobj, metricProp, null))
                                        tkb.removeTriple(t);
                                }
                                // Add a Triple for the metric property value
                                tkb.addTriple(varobj, metricProp, valobj);
                            } else if (type == Metric.LITERAL && val != null) {
                                // Literal value
                                KBObject tobj = dtype != null ? tkb.createXSDLiteral(valstring, dtype)
                                        : tkb.createLiteral(val);
                                if (tobj != null) {
                                    // Remove any existing values first
                                    for (KBTriple t : tkb.genericTripleQuery(varobj, metricProp, null))
                                        tkb.removeTriple(t);
                                    // Add a Triple for the metric propertyvalue
                                    tkb.addTriple(varobj, metricProp, tobj);
                                } else {
                                    details.addExplanations("ERROR Cannot Convert Metrics Value " + valstring);
                                    continue;
                                }
                            }
                        } else {
                            // TODO: Log and explain (make a utility function)
                            details.addExplanations(
                                    "ERROR No Such Metrics Property Known to Component Catalog : " + propid);
                            continue;
                        }
                    }
                }

                // Create other standard PC properties on variable
                // - hasDimensionSizes
                // - hasBindingID
                if (var.getBinding().isSet()) {
                    String dimensionSizes = "";
                    ArrayList<Binding> vbs = new ArrayList<Binding>();
                    vbs.add(var.getBinding());
                    while (!vbs.isEmpty()) {
                        Binding vb = vbs.remove(0);
                        if (vb.isSet()) {
                            for (WingsSet vs : vb) {
                                vbs.add((Binding) vs);
                            }
                            if (!dimensionSizes.equals(""))
                                dimensionSizes += ",";
                            dimensionSizes += vb.getSize();
                        }
                    }
                    tkb.setPropertyValue(varobj, dmap.get("hasDimensionSizes"),
                            tkb.createLiteral(dimensionSizes));
                }

                if (var.getBinding().getID() != null)
                    tkb.addTriple(varobj, dmap.get("hasBindingID"),
                            tkb.createLiteral(var.getBinding().getName()));
                else
                    tkb.addTriple(varobj, dmap.get("hasBindingID"), tkb.createLiteral(""));

                // end if (var.getDataBinding() != null)
            }
            // end if (var.isDataVariable())
        } else if (var.isParameterVariable()) {
            // If the Variable/Argument is a Parameter
            ValueBinding parambinding = (ValueBinding) var.getBinding();
            if (parambinding != null && parambinding.getValue() != null) {
                // If the template has any value specified, use that instead
                //arg_value = tkb.createLiteral(var.getBinding().getValue());
                KBObject arg_value = tkb.createXSDLiteral(parambinding.getValueAsString(),
                        parambinding.getDatatype());
                tkb.setPropertyValue(varobj, dmap.get("hasValue"), arg_value);
            }
            if (dmap.containsKey("hasBindingID"))
                // Set the hasBindingID term
                tkb.addTriple(varobj, dmap.get("hasBindingID"), tkb.createLiteral("Param" + arg.getName()));
        }

        // Copy argument classes from Catalog as classes for the temporary
        // variable in the temporary kb store
        KBObject argobj = kb.getIndividual(arg.getID());
        this.copyObjectClassesIntoKB(varobj.getID(), argobj, tkb, null, null, true);

        // Set the temporary variable's argumentID so rules can get/set
        // triples based on the argument
        tkb.addTriple(varobj, dmap.get("hasArgumentID"), tkb.createLiteral(rolestr));

        // Set hasInput or hasOutput for the temporary Variable
        if (sInputRoles.containsKey(rolestr)) {
            tkb.addTriple(tcomp, omap.get("hasInput"), varobj);
        } else {
            tkb.addTriple(tcomp, omap.get("hasOutput"), varobj);
        }
        // end of for (String rolestr : sRoleMap.keySet())
    }

    // Add all metrics and datametrics properties to temporary store
    tkb.addTriples(metricTriples);

    // Set current output variable metrics to do a diff with later
    for (String rolestr : sRoleMap.keySet()) {
        Variable var = sRoleMap.get(rolestr);
        if (var.isDataVariable() && !sInputRoles.containsKey(rolestr)) {
            Metrics metrics = new Metrics();
            KBObject varobj = tkb.getResource(variableNameMap.get(var));
            // Create Metrics from PC Properties
            for (KBObject metricProp : metricProps) {
                KBObject val = tkb.getPropertyValue(varobj, metricProp);
                if (val == null)
                    continue;
                // Add value
                if (val.isLiteral())
                    metrics.addMetric(metricProp.getID(),
                            new Metric(Metric.LITERAL, val.getValue(), val.getDataType()));
                else
                    metrics.addMetric(metricProp.getID(), new Metric(Metric.URI, val.getID()));
            }
            var.getBinding().setMetrics(metrics);
        }
    }

    KBRuleList rules = this.getCachedComponentRules(comp);
    if (rules.getRules().size() > 0) {
        // Redirect Standard output to a byte stream
        ByteArrayOutputStream bost = new ByteArrayOutputStream();
        PrintStream oldout = System.out;
        System.setOut(new PrintStream(bost, true));

        // *** Run propagation rules on the temporary ontmodel ***
        tkb.setRulePrefixes(this.rulePrefixes);
        tkb.applyRules(rules);
        //tkb.applyRulesFromString(allrules);

        // Add printouts from rules as explanations
        if (!bost.toString().equals("")) {
            for (String exp : bost.toString().split("\\n")) {
                details.addExplanations(exp);
            }
        }
        // Reset the Standard output
        System.setOut(oldout);
    }

    // Check if the rules marked this component as invalid for
    // the current component details packet
    KBObject invalidProp = this.dataPropMap.get("isInvalid");
    KBObject isInvalid = tkb.getPropertyValue(tcomp, invalidProp);
    if (isInvalid != null && (Boolean) isInvalid.getValue()) {
        details.addExplanations("INFO " + tcomp + " is not valid for its inputs");
        logger.debug(tcomp + " is not valid for its inputs");
        details.setInvalidFlag(true);
        list.add(details);
        return list;
    }

    // Check component dependencies
    // If set, overwrite the component dependencies with these
    ComponentRequirement req = this.getComponentRequirements(tcomp, tkb);
    if (req != null) {
        if (req.getMemoryGB() != 0)
            c.getRequirements().setMemoryGB(req.getMemoryGB());
        if (req.getStorageGB() != 0)
            c.getRequirements().setStorageGB(req.getStorageGB());
    }

    // Set values of variables by looking at values set by rules
    // in temporary kb store
    // - Only set if there isn't already a binding value for the variable
    for (Variable var : sRoleMap.values()) {
        if (var.isParameterVariable() && (noParamBindings.containsKey(var.getID()) || var.getBinding() == null
                || var.getBinding().getValue() == null)) {
            KBObject varobj = tkb.getResource(variableNameMap.get(var));
            KBObject origvarobj = tkb.getResource(var.getID());
            KBObject val = tkb.getPropertyValue(varobj, dmap.get("hasValue"));
            if (val != null && val.getValue() != null) {
                tkb.addTriple(origvarobj, tkb.getResource(this.wflowns + "hasParameterValue"), val);
                var.setBinding(new ValueBinding(val.getValue(), val.getDataType()));
            }
        }
    }

    // To create the output Variable metrics, we go through the metrics
    // property of the output data variables and get their metrics property
    // values
    for (String rolestr : sRoleMap.keySet()) {
        Variable var = sRoleMap.get(rolestr);
        if (var.isDataVariable() && !sInputRoles.containsKey(rolestr)) {
            Metrics curmetrics = var.getBinding().getMetrics();
            Metrics metrics = new Metrics();
            KBObject varobj = tkb.getResource(variableNameMap.get(var));

            // Create Metrics from PC Properties
            for (KBObject metricProp : metricProps) {
                ArrayList<KBObject> vals = tkb.getPropertyValues(varobj, metricProp);
                if (vals == null)
                    continue;
                for (KBObject val : vals) {
                    if (vals.size() > 1) {
                        if (!curmetrics.getMetrics().containsKey(metricProp.getID()))
                            continue;
                        // If multiple values present, ignore value that is equal to current value
                        for (Metric mval : curmetrics.getMetrics().get(metricProp.getID())) {
                            if (!val.isLiteral() && val.getID().equals(mval.getValue()))
                                continue;
                            else if (val.isLiteral() && val.getValue().equals(mval.getValue()))
                                continue;
                        }
                    }
                    // Add value
                    if (val.isLiteral())
                        metrics.addMetric(metricProp.getID(),
                                new Metric(Metric.LITERAL, val.getValue(), val.getDataType()));
                    else
                        metrics.addMetric(metricProp.getID(), new Metric(Metric.URI, val.getID()));
                }
            }
            ArrayList<KBObject> clses = this.getAllClassesOfInstance(tkb, varobj.getID());
            for (KBObject cls : clses)
                metrics.addMetric(KBUtils.RDF + "type", new Metric(Metric.URI, cls.getID()));

            // Set metrics for the Binding
            if (var.getBinding() != null)
                var.getBinding().setMetrics(metrics);

            // -- Dealing with Collections --
            // User other Properties for creating output binding collections
            // and setting the collection item metrics as well
            // PC Properties used:
            // - hasDimensionSizes
            // - hasDimensionIndexProperties
            int dim = 0;
            final int maxdims = 10; // not more than 10 dimensions
            int[] dimSizes = new int[maxdims];
            String[] dimIndexProps = new String[maxdims];
            KBObject dimSizesObj = tkb.getPropertyValue(varobj, dmap.get("hasDimensionSizes"));
            KBObject dimIndexPropsObj = tkb.getPropertyValue(varobj, dmap.get("hasDimensionIndexProperties"));

            // Parse dimension sizes string (can be given as a comma-separated list)
            // Example 2,3
            // - This will create a 2x3 matrix
            if (dimSizesObj != null && dimSizesObj.getValue() != null) {
                if (dimSizesObj.getValue().getClass().getName().equals("java.lang.Integer")) {
                    dimSizes[0] = (Integer) dimSizesObj.getValue();
                    dim = 1;
                } else {
                    String dimSizesStr = (String) dimSizesObj.getValue();
                    for (String dimSize : dimSizesStr.split(",")) {
                        try {
                            int size = Integer.parseInt(dimSize);
                            dimSizes[dim] = size;
                            dim++;
                        } catch (Exception e) {
                        }
                    }
                }
            }

            // Parse dimension index string (can be given as a comma
            // separated list)
            // Example hasXIndex, hasYIndex
            // - This will set each output item's
            // - first dimension index using property hasXIndex
            // - second dimension index using property hasYIndex
            // Example output:
            // - output
            // - output0 (hasXIndex 0)
            // - output00 (hasXIndex 0, hasYIndex 0)
            // - output01 (hasXIndex 0, hasYIndex 1)
            // - output0 (hasXIndex 1)
            // - output10 (hasXIndex 1, hasYIndex 0)
            // - output11 (hasXIndex 1, hasYIndex 1)

            if (dimIndexPropsObj != null && dimIndexPropsObj.getValue() != null) {
                int xdim = 0;
                String dimIndexPropsStr = (String) dimIndexPropsObj.getValue();
                for (String dimIndexProp : dimIndexPropsStr.split(",")) {
                    try {
                        dimIndexProps[xdim] = dimIndexProp;
                        xdim++;
                    } catch (Exception e) {
                    }
                }
            }

            // If the output is a collection
            // dim = 1 is a List
            // dim = 2 is a Matrix
            // dim = 3 is a Cube
            // .. and so on
            if (dim > 0) {
                int[] dimCounters = new int[dim];
                dimCounters[0] = 1;
                for (int k = 1; k < dim; k++) {
                    int perms = 1;
                    for (int l = k - 1; l >= 0; l--)
                        perms *= dimSizes[l];
                    dimCounters[k] = dimCounters[k - 1] + perms;
                }

                Binding b = var.getBinding();
                ArrayList<Binding> vbs = new ArrayList<Binding>();
                vbs.add(b);
                int counter = 0;
                while (!vbs.isEmpty()) {
                    Binding vb = vbs.remove(0);
                    if (vb.getMetrics() == null)
                        continue;
                    int vdim = 0;
                    for (vdim = 0; vdim < dim; vdim++) {
                        if (counter < dimCounters[vdim])
                            break;
                    }
                    if (vdim < dim) {
                        for (int i = 0; i < dimSizes[vdim]; i++) {
                            Binding cvb = new Binding(b.getNamespace() + UuidGen.generateAUuid("" + i));
                            // Copy over metrics from parent variable binding
                            Metrics tmpMetrics = new Metrics(vb.getMetrics());
                            // Add dimension index (if property set)
                            String prop = dimIndexProps[vdim];
                            if (prop != null && !prop.equals("")) {
                                Metric nm = new Metric(Metric.LITERAL, i, KBUtils.XSD + "integer");
                                tmpMetrics.addMetric(this.dcdomns + prop, nm);
                            }
                            cvb.setMetrics(tmpMetrics);
                            vb.add(cvb);
                            vbs.add(cvb);
                        }
                    }
                    counter++;
                }
            }
            // end if(dim > 0)
        }
    }

    // FIXME: Handle multiple configurations
    list.add(details);
    return list;
}

From source file:com.nuvolect.deepdive.probe.DecompileApk.java

/**
 * Fernflower converts JAR files to a zipped decompiled JAR file then
 * it unzips the JAR file./*  w  ww  . ja  v  a2 s.  com*/
 */
private JSONObject fern_flower() {// https://github.com/fesh0r/fernflower

    m_srcFernFolder.mkdirs();

    Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {

            LogUtil.log(LogUtil.LogType.DECOMPILE, "Uncaught exception: " + e.toString());
            m_progressStream.putStream("Uncaught exception: " + t.getName());
            m_progressStream.putStream("Uncaught exception: " + e.toString());
        }
    };

    m_fern_time = System.currentTimeMillis(); // Save start time for tracking

    m_fernThread = new Thread(m_threadGroup, new Runnable() {
        @Override
        public void run() {

            File inputJarFile = null;
            String inputJarFileName = "";

            for (int i = 0; i < m_dexFileNames.length; i++) {

                inputJarFileName = m_dexFileNames[i] + ".jar";
                OmniFile inputJarOmniFile = new OmniFile(m_volumeId, m_appFolderPath + inputJarFileName);
                inputJarFile = inputJarOmniFile.getStdFile();

                if (inputJarFile.exists() && inputJarFile.isFile()) {

                    boolean success = true;
                    try {
                        m_progressStream.putStream("Fernflower starting: " + inputJarFileName);
                        PrintStream printStream = new PrintStream(m_progressStream);
                        System.setErr(printStream);
                        System.setOut(printStream);
                        OmniFile fernLog = new OmniFile(m_volumeId,
                                m_srcFernFolderPath + "/" + m_dexFileNames[i] + "_log.txt");
                        PrintStream logStream = new PrintStream(fernLog.getOutputStream());
                        PrintStreamLogger logger = new PrintStreamLogger(logStream);

                        final Map<String, Object> mapOptions = new HashMap<>();
                        ConsoleDecompiler decompiler = new ConsoleDecompiler(m_srcFernFolder.getStdFile(),
                                mapOptions, logger);
                        decompiler.addSpace(inputJarFile, true);

                        m_progressStream
                                .putStream("Fernflower decompiler.addSpace complete: " + inputJarFileName);
                        decompiler.decompileContext();
                        m_progressStream.putStream(
                                "Fernflower decompiler.decompileContext complete: " + inputJarFileName);

                        String decompiledJarFilePath = m_srcFernFolderPath + "/" + inputJarFileName;
                        OmniFile decompiledJarFile = new OmniFile(m_volumeId, decompiledJarFilePath);
                        success = OmniZip.unzipFile(decompiledJarFile, m_srcFernFolder, null, null);
                        decompiledJarFile.delete();

                        if (success) {
                            m_progressStream
                                    .putStream("Fernflower decompiler.unpack complete: " + inputJarFileName);
                        } else {
                            m_progressStream
                                    .putStream("Fernflower decompiler.unpack failed: " + inputJarFileName);
                        }
                    } catch (Exception e) {
                        String str = LogUtil.logException(LogUtil.LogType.FERNFLOWER, e);
                        m_progressStream.putStream("Fernflower exception " + inputJarFileName);
                        m_progressStream.putStream(str);
                        success = false;
                    }
                    /**
                     * Look for the classes.jar file and unzip it
                     */
                    if (!success) {

                        OmniFile of = new OmniFile(m_volumeId, m_srcFernFolderPath + "/classes.jar");
                        if (of.exists()) {

                            ApkZipUtil.unzip(of, m_srcFernFolder, m_progressStream);
                            m_progressStream.putStream(
                                    "Fernflower utility unzip complete with errors: " + inputJarFileName);
                        } else {
                            m_progressStream.putStream("File does not exist: " + of.getAbsolutePath());
                        }
                    }
                }
            }
            m_progressStream.putStream("Fernflower complete: " + TimeUtil.deltaTimeHrMinSec(m_fern_time));
            m_fern_time = 0;

        }
    }, FERN_THREAD, STACK_SIZE);

    m_fernThread.setPriority(Thread.MAX_PRIORITY);
    m_fernThread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
    m_fernThread.start();

    //                String processStatus = getThreadStatus( true, m_fernThread);
    //                String url = OmniHash.getHashedServerUrl( m_ctx, m_volumeId, m_srcFernFolderPath);

    String processKey = "fern_thread";
    String urlKey = "fern_url";

    return processWrapper(processKey, urlKey);
}