Example usage for java.lang String toString

List of usage examples for java.lang String toString

Introduction

In this page you can find the example usage for java.lang String toString.

Prototype

public String toString() 

Source Link

Document

This object (which is already a string!) is itself returned.

Usage

From source file:com.clustercontrol.notify.util.QueryUtil.java

public static NotifyMailInfo getNotifyMailInfoPK(String pk) throws NotifyNotFound {
    HinemosEntityManager em = new JpaTransactionManager().getEntityManager();
    NotifyMailInfo entity = em.find(NotifyMailInfo.class, pk, ObjectPrivilegeMode.READ);
    if (entity == null) {
        NotifyNotFound e = new NotifyNotFound("NotifyMailInfoEntity.findByPrimaryKey" + pk.toString());
        m_log.info("getNotifyMailInfoPK() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;/*from w  w  w  . j a va2s.c om*/
    }
    return entity;
}

From source file:com.clustercontrol.notify.util.QueryUtil.java

public static NotifyEventInfo getNotifyEventInfoPK(String pk) throws NotifyNotFound {
    HinemosEntityManager em = new JpaTransactionManager().getEntityManager();
    NotifyEventInfo entity = em.find(NotifyEventInfo.class, pk, ObjectPrivilegeMode.READ);
    if (entity == null) {
        NotifyNotFound e = new NotifyNotFound("NotifyEventInfoEntity.findByPrimaryKey" + pk.toString());
        m_log.info("getNotifyEventInfoPK() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;//from w ww . j  a v a  2  s  . c  om
    }
    return entity;
}

From source file:org.dkpro.similarity.experiments.rte.util.Evaluator.java

public static void runClassifier(WekaClassifier wekaClassifier, Dataset trainDataset, Dataset testDataset)
        throws Exception {
    Classifier baseClassifier = ClassifierSimilarityMeasure.getClassifier(wekaClassifier);

    // Set up the random number generator
    long seed = new Date().getTime();
    Random random = new Random(seed);

    // Add IDs to the train instances and get the instances
    AddID.main(new String[] { "-i", MODELS_DIR + "/" + trainDataset.toString() + ".arff", "-o",
            MODELS_DIR + "/" + trainDataset.toString() + "-plusIDs.arff" });
    Instances train = DataSource.read(MODELS_DIR + "/" + trainDataset.toString() + "-plusIDs.arff");
    train.setClassIndex(train.numAttributes() - 1);

    // Add IDs to the test instances and get the instances
    AddID.main(new String[] { "-i", MODELS_DIR + "/" + testDataset.toString() + ".arff", "-o",
            MODELS_DIR + "/" + testDataset.toString() + "-plusIDs.arff" });
    Instances test = DataSource.read(MODELS_DIR + "/" + testDataset.toString() + "-plusIDs.arff");
    test.setClassIndex(test.numAttributes() - 1);

    // Instantiate the Remove filter
    Remove removeIDFilter = new Remove();
    removeIDFilter.setAttributeIndices("first");

    // Randomize the data
    test.randomize(random);//  w  ww. j a  v  a 2 s  .  c om

    // Apply log filter
    //       Filter logFilter = new LogFilter();
    //       logFilter.setInputFormat(train);
    //       train = Filter.useFilter(train, logFilter);        
    //       logFilter.setInputFormat(test);
    //       test = Filter.useFilter(test, logFilter);

    // Copy the classifier
    Classifier classifier = AbstractClassifier.makeCopy(baseClassifier);

    // Instantiate the FilteredClassifier
    FilteredClassifier filteredClassifier = new FilteredClassifier();
    filteredClassifier.setFilter(removeIDFilter);
    filteredClassifier.setClassifier(classifier);

    // Build the classifier
    filteredClassifier.buildClassifier(train);

    // Prepare the output buffer 
    AbstractOutput output = new PlainText();
    output.setBuffer(new StringBuffer());
    output.setHeader(test);
    output.setAttributes("first");

    Evaluation eval = new Evaluation(train);
    eval.evaluateModel(filteredClassifier, test, output);

    // Convert predictions to CSV
    // Format: inst#, actual, predicted, error, probability, (ID)
    String[] scores = new String[new Double(eval.numInstances()).intValue()];
    double[] probabilities = new double[new Double(eval.numInstances()).intValue()];
    for (String line : output.getBuffer().toString().split("\n")) {
        String[] linesplit = line.split("\\s+");

        // If there's been an error, the length of linesplit is 6, otherwise 5,
        // due to the error flag "+"

        int id;
        String expectedValue, classification;
        double probability;

        if (line.contains("+")) {
            id = Integer.parseInt(linesplit[6].substring(1, linesplit[6].length() - 1));
            expectedValue = linesplit[2].substring(2);
            classification = linesplit[3].substring(2);
            probability = Double.parseDouble(linesplit[5]);
        } else {
            id = Integer.parseInt(linesplit[5].substring(1, linesplit[5].length() - 1));
            expectedValue = linesplit[2].substring(2);
            classification = linesplit[3].substring(2);
            probability = Double.parseDouble(linesplit[4]);
        }

        scores[id - 1] = classification;
        probabilities[id - 1] = probability;
    }

    System.out.println(eval.toSummaryString());
    System.out.println(eval.toMatrixString());

    // Output classifications
    StringBuilder sb = new StringBuilder();
    for (String score : scores)
        sb.append(score.toString() + LF);

    FileUtils.writeStringToFile(new File(OUTPUT_DIR + "/" + testDataset.toString() + "/"
            + wekaClassifier.toString() + "/" + testDataset.toString() + ".csv"), sb.toString());

    // Output probabilities
    sb = new StringBuilder();
    for (Double probability : probabilities)
        sb.append(probability.toString() + LF);

    FileUtils.writeStringToFile(new File(OUTPUT_DIR + "/" + testDataset.toString() + "/"
            + wekaClassifier.toString() + "/" + testDataset.toString() + ".probabilities.csv"), sb.toString());

    // Output predictions
    FileUtils.writeStringToFile(new File(OUTPUT_DIR + "/" + testDataset.toString() + "/"
            + wekaClassifier.toString() + "/" + testDataset.toString() + ".predictions.txt"),
            output.getBuffer().toString());

    // Output meta information
    sb = new StringBuilder();
    sb.append(classifier.toString() + LF);
    sb.append(eval.toSummaryString() + LF);
    sb.append(eval.toMatrixString() + LF);

    FileUtils.writeStringToFile(new File(OUTPUT_DIR + "/" + testDataset.toString() + "/"
            + wekaClassifier.toString() + "/" + testDataset.toString() + ".meta.txt"), sb.toString());
}

From source file:com.clustercontrol.notify.util.QueryUtil.java

public static NotifyInfraInfo getNotifyInfraInfoPK(String pk) throws NotifyNotFound {
    HinemosEntityManager em = new JpaTransactionManager().getEntityManager();
    NotifyInfraInfo entity = em.find(NotifyInfraInfo.class, pk, ObjectPrivilegeMode.READ);
    if (entity == null) {
        NotifyNotFound e = new NotifyNotFound("NotifyInfraInfoEntity.findByPrimaryKey" + pk.toString());
        // ?????Internal?????debug??
        m_log.debug("getNotifyInfraInfoPK() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;//from   w  w  w. j  a v  a 2s . c om
    }
    return entity;
}

From source file:com.clustercontrol.notify.util.QueryUtil.java

public static NotifyStatusInfo getNotifyStatusInfoPK(String pk) throws NotifyNotFound {
    HinemosEntityManager em = new JpaTransactionManager().getEntityManager();
    NotifyStatusInfo entity = em.find(NotifyStatusInfo.class, pk, ObjectPrivilegeMode.READ);
    if (entity == null) {
        NotifyNotFound e = new NotifyNotFound("NotifyStatusInfoEntity.findByPrimaryKey" + pk.toString());
        // ?????Internal?????debug??
        m_log.debug("getNotifyStatusInfoPK() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;/*from  www.  j  ava 2 s  .  c  o  m*/
    }
    return entity;
}

From source file:com.clustercontrol.notify.util.QueryUtil.java

public static NotifyCommandInfo getNotifyCommandInfoPK(String pk) throws NotifyNotFound {
    HinemosEntityManager em = new JpaTransactionManager().getEntityManager();
    NotifyCommandInfo entity = em.find(NotifyCommandInfo.class, pk, ObjectPrivilegeMode.READ);
    if (entity == null) {
        NotifyNotFound e = new NotifyNotFound("NotifyCommandInfoEntity.findByPrimaryKey" + pk.toString());
        m_log.info("getNotifyCommandInfoPK() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;// w w  w  . j  av  a  2s. c  o  m
    }
    return entity;
}

From source file:org.ofbiz.party.tool.SmsSimpleClient.java

/**
 * ??http GEThttp?/*from  w  w w. j  a  v a 2s .  c  o m*/
 * 
 * @param urlstr url
 * @return
 */
public static String doGetRequest(String urlstr) {
    HttpClient client = new DefaultHttpClient();
    client.getParams().setIntParameter("http.socket.timeout", 10000);
    client.getParams().setIntParameter("http.connection.timeout", 5000);

    HttpEntity entity = null;
    String entityContent = null;
    try {
        HttpGet httpGet = new HttpGet(urlstr.toString());

        HttpResponse httpResponse = client.execute(httpGet);
        entityContent = EntityUtils.toString(httpResponse.getEntity());

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (Exception e) {
                Debug.logError(e, module);
            }
        }
    }
    return entityContent;
}

From source file:edu.odu.cs.cs350.yellow1.ui.cli.Main.java

/**
 * Main program function. Creates and runs mutants as well as logging and output files
 * /*from  w w w  .  j  a  v  a2  s  .  c  o  m*/
 * @param srcFolder Source folder for project to be mutated
 * @param fileToBeMutated Source file for project to be mutated
 * @param testSuitePath Path for test suite
 * @param goldOutput Original version output file
 * @throws BuildFileNotFoundException
 * @throws IOException
 */
@SuppressWarnings("static-access")
public static void mutate(String srcFolder, String fileToBeMutated, String testSuitePath, String goldOutput)
        throws BuildFileNotFoundException, IOException {

    //Step 1: Set up file directory paths for antRunner, jarExecutor, and fileMover

    logger = LogManager.getLogger(Main.class);
    mutLog = new File(srcFolder.toString() + File.separator + "mutantDir" + File.separator + "logs"
            + File.separator + "mutationsApplied.txt");
    aliveLog = new File(srcFolder.toString() + File.separator + "mutantDir" + File.separator + "logs"
            + File.separator + "mutationsAlive.txt");
    logFolder = new File(srcFolder.toString() + File.separator + "mutantDir" + File.separator + "logs");
    // ok because of the output on jenkins sanitize the logs directory
    if (logFolder.exists())
        if (logFolder.isDirectory())
            for (File f : logFolder.listFiles())
                f.delete();
    //give ant runer the project location
    ant = new AntRunner(srcFolder);
    ant.requiresInit(true);
    //call setup
    ant.setUp();
    a = new JavaFile();

    //give the jarUtil the  directory where to expect the jar   the directory where to put the jar
    jar = new JarUtil((srcFolder + File.separator + "bin"), (srcFolder + File.separator + "mutantDir"));

    //get a file object to the original file
    File goldFile = new File(fileToBeMutated);
    goldPath = goldFile.toPath();
    //get the bytes from it for checking if applying mutation and restore works
    goldOrgContent = Files.readAllBytes(goldPath);

    File script = new File(srcFolder + File.separator + "compare.sh");
    //build the JarExecutor using the JarExecutor
    jarExecutor = JarExecutorBuilder.pathToJarDirectory(srcFolder + File.separator + "mutantDir")
            .pathToCompareScript(script.getAbsolutePath())
            .pathToLogDir(srcFolder + File.separator + "mutantDir" + File.separator + "logs")
            .pathToGold(goldOutput.toString()).withExecutionState(ExecutionState.multiFile)
            .withTestSuitePath(testSuitePath).create();
    File tDir = new File(srcFolder + File.separator + "mutantDir");
    if (!tDir.exists())
        tDir.mkdir();
    //Create a fileMover object give it the directory where mutations will be placed   the directory of the original file location
    fMover = new FileMover(srcFolder + File.separator + "mutantDir", fileToBeMutated);
    fMover.setNoDelete(true);
    try {

        fMover.setUp();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();

    }

    //Step2: Create and run mutants

    try {
        a.readFile(fileToBeMutated);
    } catch (IOException e) {
        e.printStackTrace();
    }

    a.executeAll();
    int mutantsCreated = a.getMutantCaseVector().getSize();
    logger.info("Created " + mutantsCreated + " Mutants");
    for (int i = 0; i < a.getMutantCaseVector().getSize(); i++) {
        a.getMutantCaseOperations(i).writeMutation(srcFolder + File.separator + "mutantDir" + File.separator
                + "Mutation" + Integer.toString(i + 1) + ".java");
    }

    //get the files into the file mover object
    fMover.pullFiles();

    //check to see if the filemover got all the files
    //assertEquals(fMover.getFileToBeMovedCount(),mutantsCreated);

    int moved = 0;
    int failed = 0;
    //move through each file moving them one by one
    while (fMover.hasMoreFiles()) {
        try {
            //move next file
            fMover.moveNextFile();

            //build the new executable
            ant.build();
            //move the created jar with correct number corresponding to the mutation created 
            jar.moveJarToDestNumbered();
            //clean the project
            ant.clean();
            //check to see if the mutation was applied
            //assertThat(additionOrgContent, IsNot.not(IsEqual.equalTo(Files.readAllBytes(additionPath))));

        } catch (FileMovingException | BuildException | TargetNotFoundException | IOException e) {

            //build failed
            if (e instanceof BuildException) {
                logger.error("Build exception " + e.getMessage());

                //restore the file back since compilation was not successful 
                fMover.restorTarget();
                //try {
                //   //check to see if the file was restored
                //   assertArrayEquals(goldOrgContent, Files.readAllBytes(goldPath));
                //} catch (IOException e1) {
                //   
                //}
                //clean the project
                try {
                    ant.clean();
                } catch (BuildException e1) {

                } catch (TargetNotFoundException e1) {

                }
                //indicate compile failure
                ++failed;
            }
            //fail();
        }

        //restore the file back to its original state
        fMover.restorTarget();
        //check to see if the file was restored
        //try {
        //   assertArrayEquals(goldOrgContent, Files.readAllBytes(goldPath));
        //} catch (IOException e) {
        //   
        //}

        //increment move count
        ++moved;
        //see if the file mover has the correct amount of mutatants still to be moved
        //assertEquals(fMover.getFileToBeMovedCount(), mutantsCreated - moved);
    }

    //set up for execution
    jarExecutor.setUp();
    //start execution of jars
    jarExecutor.start();

    //get the number of successful and failed runs
    int succesful = jarExecutor.getNumberOfMutantsKilled();
    int failurs = jarExecutor.getNumberOfMutantsNotKilled();
    int numTests = jarExecutor.getNumberOfTests();
    int total = succesful + failurs;
    String aliveFile = null;
    String newLine = System.lineSeparator();

    //Find any test jars that remain alive and write them to the log file
    List<ExecutionResults> testResults = jarExecutor.getMutationTestingResults();
    for (ExecutionResults result : testResults) {
        if (!result.isKilled()) {
            aliveFile = result.getJarName();
            FileUtils.writeStringToFile(aliveLog, aliveFile + newLine, true);
        }
    }

    //moved - failed = number of jars actually created
    moved = moved - failed;
    //see if the total number of executions equals the total amount of jars created
    //assertEquals(succesful+failurs,moved);
    logger.debug("Compilation failurs= " + failed + " total files moved= " + moved);
    logger.debug("Execution succesful=" + succesful + " Execution failurs= " + failurs);

    EOL eol = System.getProperty("os.name").toLowerCase().contains("windows") ? EOL.DOS : EOL.NIX;
    try {
        a.writeMutationsLog(srcFolder.toString() + File.separator + "mutantDir" + File.separator + "logs"
                + File.separator + "mutationsApplied.txt", eol);
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
    String finalOutput = "Number of tests: " + numTests + " " + "Number of mutants: " + total + " "
            + "Mutants killed: " + succesful;
    FileUtils.writeStringToFile(mutLog, newLine + finalOutput, true);

    System.out.println(finalOutput + "\n");
}

From source file:de.fhg.igd.mapviewer.server.wms.capabilities.WMSUtil.java

/**
 * Get the WMS layers// w w  w.jav  a  2 s.  co  m
 * 
 * @param layerString the layer string
 * @param capabilities the WMS capabilities
 * @return the list of layers
 */
public static List<Layer> getLayers(String layerString, WMSCapabilities capabilities) {
    // determine layers to show
    List<String> showLayers = null;
    if (layerString != null && !layerString.isEmpty()) {
        String[] layers = layerString.split(","); //$NON-NLS-1$
        showLayers = new ArrayList<String>();
        for (String layer : layers) {
            showLayers.add(layer);
        }
    }

    List<Layer> layers = new ArrayList<Layer>();

    for (Layer layer : capabilities.getLayers()) {
        if (showLayers != null) {
            try {
                layer.setSelected(showLayers.contains(layer.getName())
                        || showLayers.contains(URLEncoder.encode(layer.toString(), "UTF-8"))); //$NON-NLS-1$
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported encoding", e); //$NON-NLS-1$
            }
        }

        layers.add(layer);
    }

    return layers;
}

From source file:Main.java

public static String MD5(String source) {
    String resultHash = null;
    try {/*from ww w.  j  a  v  a  2 s.c om*/
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.reset();
        md5.update(source.getBytes("UTF-8"));
        byte[] result = md5.digest();
        StringBuffer buf = new StringBuffer(result.length * 2);
        for (int i = 0; i < result.length; i++) {
            int intVal = result[i] & 0xff;
            if (intVal < 0x10) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(intVal));
        }
        resultHash = buf.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resultHash.toString();
}