Example usage for java.lang RuntimeException RuntimeException

List of usage examples for java.lang RuntimeException RuntimeException

Introduction

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

Prototype

public RuntimeException(Throwable cause) 

Source Link

Document

Constructs a new runtime exception with the specified cause and a detail message of (cause==null ?

Usage

From source file:com.github.caldav4j.FunTest.java

public static void main(String args[]) {
    try {//from   w  w w.ja  v a2  s.  c o m
        Recur recur = new Recur("FREQ=HOURLY");
        DateTime startDate = new DateTime("20060101T010000Z");
        DateTime endDate = new DateTime("20060105T050000Z");
        DateTime baseDate = new DateTime("20050101T033300");
        DateList dateList = recur.getDates(baseDate, startDate, endDate, Value.DATE_TIME);
        for (int x = 0; x < dateList.size(); x++) {
            DateTime d = (DateTime) dateList.get(x);
            log.info(d.toString());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.joliciel.frenchTreebank.FrenchTreebank.java

/**
 * @param args//from w  ww .j  av a  2  s  .  com
 */
public static void main(String[] args) throws Exception {
    String command = args[0];

    String outFilePath = "";
    String outDirPath = "";
    String treebankPath = "";
    String ftbFileName = "";
    String rawTextDir = "";
    String queryPath = "";
    String sentenceNumber = null;
    boolean firstArg = true;
    for (String arg : args) {
        if (firstArg) {
            firstArg = false;
            continue;
        }
        int equalsPos = arg.indexOf('=');
        String argName = arg.substring(0, equalsPos);
        String argValue = arg.substring(equalsPos + 1);
        if (argName.equals("outfile"))
            outFilePath = argValue;
        else if (argName.equals("outdir"))
            outDirPath = argValue;
        else if (argName.equals("ftbFileName"))
            ftbFileName = argValue;
        else if (argName.equals("treebank"))
            treebankPath = argValue;
        else if (argName.equals("sentence"))
            sentenceNumber = argValue;
        else if (argName.equals("query"))
            queryPath = argValue;
        else if (argName.equals("rawTextDir"))
            rawTextDir = argValue;
        else
            throw new RuntimeException("Unknown argument: " + argName);
    }

    TalismaneServiceLocator talismaneServiceLocator = TalismaneServiceLocator.getInstance();

    TreebankServiceLocator locator = TreebankServiceLocator.getInstance(talismaneServiceLocator);

    if (treebankPath.length() == 0)
        locator.setDataSourcePropertiesFile("jdbc-live.properties");

    if (command.equals("search")) {
        final SearchService searchService = locator.getSearchService();
        final XmlPatternSearch search = searchService.newXmlPatternSearch();
        search.setXmlPatternFile(queryPath);
        List<SearchResult> searchResults = search.perform();

        FileWriter fileWriter = new FileWriter(outFilePath);
        for (SearchResult searchResult : searchResults) {
            String lineToWrite = "";
            Sentence sentence = searchResult.getSentence();
            Phrase phrase = searchResult.getPhrase();
            lineToWrite += sentence.getFile().getFileName() + "|";
            lineToWrite += sentence.getSentenceNumber() + "|";
            List<PhraseUnit> phraseUnits = searchResult.getPhraseUnits();
            LOG.debug("Phrase: " + phrase.getId());
            for (PhraseUnit phraseUnit : phraseUnits)
                lineToWrite += phraseUnit.getLemma().getText() + "|";
            lineToWrite += phrase.getText();
            fileWriter.write(lineToWrite + "\n");
        }
        fileWriter.flush();
        fileWriter.close();
    } else if (command.equals("load")) {
        final TreebankService treebankService = locator.getTreebankService();
        final TreebankSAXParser parser = new TreebankSAXParser();
        parser.setTreebankService(treebankService);
        parser.parseDocument(treebankPath);
    } else if (command.equals("loadAll")) {
        final TreebankService treebankService = locator.getTreebankService();

        File dir = new File(treebankPath);

        String firstFile = null;
        if (args.length > 2)
            firstFile = args[2];
        String[] files = dir.list();
        if (files == null) {
            throw new RuntimeException("Not a directory or no children: " + treebankPath);
        } else {
            boolean startProcessing = true;
            if (firstFile != null)
                startProcessing = false;
            for (int i = 0; i < files.length; i++) {
                if (!startProcessing && files[i].equals(firstFile))
                    startProcessing = true;
                if (startProcessing) {
                    String filePath = args[1] + "/" + files[i];
                    LOG.debug(filePath);
                    final TreebankSAXParser parser = new TreebankSAXParser();
                    parser.setTreebankService(treebankService);
                    parser.parseDocument(filePath);
                }
            }
        }
    } else if (command.equals("loadRawText")) {
        final TreebankService treebankService = locator.getTreebankService();
        final TreebankRawTextAssigner assigner = new TreebankRawTextAssigner();
        assigner.setTreebankService(treebankService);
        assigner.setRawTextDirectory(rawTextDir);
        assigner.loadRawText();
    } else if (command.equals("tokenize")) {
        Writer csvFileWriter = null;
        if (outFilePath != null && outFilePath.length() > 0) {
            if (outFilePath.lastIndexOf("/") > 0) {
                String outputDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/"));
                File outputDir = new File(outputDirPath);
                outputDir.mkdirs();
            }

            File csvFile = new File(outFilePath);
            csvFile.delete();
            csvFile.createNewFile();
            csvFileWriter = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(csvFile, false), "UTF8"));
        }
        try {

            final TreebankService treebankService = locator.getTreebankService();
            TreebankExportService treebankExportService = locator.getTreebankExportServiceLocator()
                    .getTreebankExportService();
            TreebankUploadService treebankUploadService = locator.getTreebankUploadServiceLocator()
                    .getTreebankUploadService();
            TreebankReader treebankReader = null;

            if (treebankPath.length() > 0) {
                File treebankFile = new File(treebankPath);
                if (sentenceNumber != null)
                    treebankReader = treebankUploadService.getXmlReader(treebankFile, sentenceNumber);
                else
                    treebankReader = treebankUploadService.getXmlReader(treebankFile);

            } else {
                treebankReader = treebankService.getDatabaseReader(TreebankSubSet.ALL, 0);
            }

            TokeniserAnnotatedCorpusReader reader = treebankExportService
                    .getTokeniserAnnotatedCorpusReader(treebankReader, csvFileWriter);

            while (reader.hasNextTokenSequence()) {
                TokenSequence tokenSequence = reader.nextTokenSequence();
                List<Integer> tokenSplits = tokenSequence.getTokenSplits();
                String sentence = tokenSequence.getText();
                LOG.debug(sentence);
                int currentPos = 0;
                StringBuilder sb = new StringBuilder();
                for (int split : tokenSplits) {
                    if (split == 0)
                        continue;
                    String token = sentence.substring(currentPos, split);
                    sb.append('|');
                    sb.append(token);
                    currentPos = split;
                }
                LOG.debug(sb.toString());
            }
        } finally {
            csvFileWriter.flush();
            csvFileWriter.close();
        }
    } else if (command.equals("export")) {
        if (outDirPath.length() == 0)
            throw new RuntimeException("Parameter required: outdir");
        File outDir = new File(outDirPath);
        outDir.mkdirs();

        final TreebankService treebankService = locator.getTreebankService();
        FrenchTreebankXmlWriter xmlWriter = new FrenchTreebankXmlWriter();
        xmlWriter.setTreebankService(treebankService);

        if (ftbFileName.length() == 0) {
            xmlWriter.write(outDir);
        } else {
            TreebankFile ftbFile = treebankService.loadTreebankFile(ftbFileName);
            String fileName = ftbFileName.substring(ftbFileName.lastIndexOf('/') + 1);
            File xmlFile = new File(outDir, fileName);
            xmlFile.delete();
            xmlFile.createNewFile();

            Writer xmlFileWriter = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(xmlFile, false), "UTF8"));
            xmlWriter.write(xmlFileWriter, ftbFile);
            xmlFileWriter.flush();
            xmlFileWriter.close();
        }
    } else {
        throw new RuntimeException("Unknown command: " + command);
    }
    LOG.debug("========== END ============");
}

From source file:com.arpnetworking.tsdaggregator.TsdAggregator.java

/**
 * Entry point for Time Series Data (TSD) Aggregator.
 *
 * @param args the command line arguments
 *///  w  w  w .  j a  va  2 s.  c o  m
public static void main(final String[] args) {
    LOGGER.info("Launching tsd-aggregator");

    // Global initialization
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable throwable) {
            LOGGER.error("Unhandled exception!", throwable);
        }
    });

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
            context.stop();
        }
    }));

    System.setProperty("org.vertx.logger-delegate-factory-class-name",
            "org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");

    // Run the tsd aggregator
    if (args.length != 1) {
        throw new RuntimeException("No configuration file specified");
    }
    LOGGER.debug(String.format("Loading configuration from file; file=%s", args[0]));

    final File configurationFile = new File(args[0]);
    final Configurator<TsdAggregator, TsdAggregatorConfiguration> configurator = new Configurator<>(
            TsdAggregator.class, TsdAggregatorConfiguration.class);
    final ObjectMapper objectMapper = TsdAggregatorConfiguration.createObjectMapper();
    final DynamicConfiguration configuration = new DynamicConfiguration.Builder().setObjectMapper(objectMapper)
            .addSourceBuilder(
                    new JsonNodeFileSource.Builder().setObjectMapper(objectMapper).setFile(configurationFile))
            .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build()).addListener(configurator)
            .build();

    configuration.launch();

    final AtomicBoolean isRunning = new AtomicBoolean(true);
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            LOGGER.info("Stopping tsd-aggregator");
            configuration.shutdown();
            configurator.shutdown();
            isRunning.set(false);
        }
    }));

    while (isRunning.get()) {
        try {
            Thread.sleep(30000);
        } catch (final InterruptedException e) {
            break;
        }
    }

    LOGGER.info("Exiting tsd-aggregator");
}

From source file:com.shieldsbetter.sbomg.Cli.java

public static void main(String[] args) {
    int result;/*from  w w w  .j  a  v a 2 s .c o m*/

    try {
        Options options = new Options();
        options.addOption("f", false, "Force overwrite of files that already exist.");
        options.addOption("q", false, "Quiet all non-error output.");

        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);

        try {
            Plan p = makePlan(cmd);

            for (File input : p.files()) {
                if (!cmd.hasOption('q')) {
                    System.out.println("Processing " + input.getPath() + "...");
                }

                String modelName = nameWithoutExtension(input);
                File targetPath = p.getDestinationPath(input);
                try (Scanner inputScan = fileToScanner("input", input);
                        Writer outputWriter = outputPathToWriter(targetPath, modelName, cmd);) {
                    Object modelDesc = parseSbomgV1(inputScan);

                    try {
                        ViewModelGenerator.generate(p.getPackage(input), modelName, modelDesc, outputWriter);
                    } catch (IOException ioe) {
                        throw new FileException(buildOutputFile(targetPath, modelName), "writing to target",
                                ioe.getMessage());
                    }
                } catch (IOException ioe) {
                    throw new FileException(buildOutputFile(targetPath, modelName), "opening target",
                            ioe.getMessage());
                }
            }

            result = 0;
        } catch (OperationException oe) {
            System.err.println();
            System.err.println(oe.getMessage());
            result = 1;
        }
    } catch (FileException fe) {
        System.err.println();
        System.err.println("Error " + fe.getTask() + " file " + fe.getFile().getPath() + ":");
        System.err.println("    " + fe.getMessage());

        result = 1;
    } catch (ParseException pe) {
        throw new RuntimeException(pe);
    }

    System.exit(result);
}

From source file:fall2015.b565.wisBreastCancer.Assignment2.java

public static void main(String[] args) throws Exception {
    try {//from ww  w  .j  a  v a 2s  .c o  m
        parseArguments(args);
        FileReader fileReader = new FileReader();
        if (useReplaceDataSet) {
            cleanedFilePath = Constants.REPLACED_DATA_FILE_PATH;
        } else {
            cleanedFilePath = Constants.REMOVED_DATA_FILE_PATH;
        }
        KMeans kMeans = new KMeans();
        System.out.println("=============== Pre-Processing of Data ===============");
        fileReader.cleanDataSet();
        System.out.println("=============== Data Cleaned ===============");
        if (correlation) {
            System.out.println("=============== Finding Correlation between attributes ===============");
            kMeans.findAttributeCorrelations();
        }
        if (ppv) {
            System.out.println("=============== Finding PPV considering all the attributes ===============");
            KMeansResult kMeansResult = kMeans.findKmeansToAllAttributes(cleanedFilePath);
            double ppv = kMeans.calculatePPV(kMeansResult.getFinalCentroids(),
                    kMeans.getRecords(cleanedFilePath));
            System.out.println("Calculated PPV : " + ppv);
        }
        if (powerSetPPV) {
            System.out.println(
                    "=============== Finding PPV considering power set of the attributes ===============");
            kMeans.findKmeansToAttributePowerSet(cleanedFilePath);
        }
        if (vfoldCrossValidation) {
            System.out.println(
                    "=============== Finding V Fold cross validation considering all the attribute set ===============");
            KMeansResult kMeansResult = kMeans.findKmeansToAllAttributes(cleanedFilePath);
            HashSet<Integer> attributes = new HashSet<Integer>(Ints.asList(allAttributeHeaders));
            double vPPV = kMeans.vFoldCrossValidation(kMeansResult.getInitialRecords(), attributes);
            System.out.println("VFold cross validation PPV : " + vPPV);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.example.bigtable.simplecli.Loader.java

public static void main(String argv[]) throws IOException {
    String inputFile = "/tmp/pagecounts-20160101-000000";

    // Connect/*from w w  w . java  2 s  .co  m*/
    Connection bigTableConnection = ConnectionFactory.createConnection();

    // Load the file, and do stuff each row
    Stream<String> stream = Files.lines(Paths.get(inputFile));
    stream.forEach(row -> {

        String[] splitRow = row.split(" ");
        assert splitRow.length == 4 : "unexpected row " + row;

        String hour = "20160101-000000"; //from file name
        String language = splitRow[0];
        String title = splitRow[1];
        String requests = splitRow[2];
        String size = splitRow[3];

        assert language.length() == 2 : "unexpected language size" + language;

        // create a row key
        // [languageCode]-[title md5]-[hour]
        String rowKey = language + "-" + DigestUtils.md5Hex(title) + "-" + hour;
        System.out.println(rowKey);

        // Put it into Bigtable - [table name]
        try {
            Table table = bigTableConnection.getTable(TableName.valueOf("wikipedia-stats"));

            // Create a new Put request.
            Put put = new Put(Bytes.toBytes(rowKey));

            // Add columns: [column family], [column], [data]
            put.addColumn(Bytes.toBytes("traffic"), Bytes.toBytes("requests"), Bytes.toBytes(requests));
            put.addColumn(Bytes.toBytes("traffic"), Bytes.toBytes("size"), Bytes.toBytes(size));

            // Execute the put on the table.
            table.put(put);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    // Clean up
    bigTableConnection.close();
}

From source file:de.peran.DependencyReadingStarter.java

public static void main(final String[] args) throws ParseException, FileNotFoundException {
    final Options options = OptionConstants.createOptions(OptionConstants.FOLDER, OptionConstants.STARTVERSION,
            OptionConstants.ENDVERSION, OptionConstants.OUT);

    final CommandLineParser parser = new DefaultParser();
    final CommandLine line = parser.parse(options, args);

    final File projectFolder = new File(line.getOptionValue(OptionConstants.FOLDER.getName()));

    final File dependencyFile;
    if (line.hasOption(OptionConstants.OUT.getName())) {
        dependencyFile = new File(line.getOptionValue(OptionConstants.OUT.getName()));
    } else {/*w w w.jav a  2s .  co  m*/
        dependencyFile = new File("dependencies.xml");
    }

    File outputFile = projectFolder.getParentFile();
    if (outputFile.isDirectory()) {
        outputFile = new File(projectFolder.getParentFile(), "ausgabe.txt");
    }

    LOG.debug("Lese {}", projectFolder.getAbsolutePath());
    final VersionControlSystem vcs = VersionControlSystem.getVersionControlSystem(projectFolder);

    System.setOut(new PrintStream(outputFile));
    // System.setErr(new PrintStream(outputFile));

    final DependencyReader reader;
    if (vcs.equals(VersionControlSystem.SVN)) {
        final String url = SVNUtils.getInstance().getWCURL(projectFolder);
        final List<SVNLogEntry> entries = getSVNCommits(line, url);
        LOG.debug("SVN commits: "
                + entries.stream().map(entry -> entry.getRevision()).collect(Collectors.toList()));
        reader = new DependencyReader(projectFolder, url, dependencyFile, entries);
    } else if (vcs.equals(VersionControlSystem.GIT)) {
        final List<GitCommit> commits = getGitCommits(line, projectFolder);
        reader = new DependencyReader(projectFolder, dependencyFile, commits);
        LOG.debug("Reader initalized");
    } else {
        throw new RuntimeException("Unknown version control system");
    }
    reader.readDependencies();
}

From source file:it.damore.solr.importexport.App.java

public static void main(String[] args) throws IOException, ParseException, URISyntaxException {

    config = ConfigFactory.getConfigFromArgs(args);

    logger.info("Found config: " + config);

    if (config.getUniqueKey() == null) {
        readUniqueKeyFromSolrSchema();//from w  ww.  j  a  v  a2  s  .  co  m
    }

    try (HttpSolrClient client = new HttpSolrClient(config.getSolrUrl())) {

        try {
            switch (config.getActionType()) {
            case EXPORT:
            case BACKUP:

                readAllDocuments(client, new File(config.getFileName()));
                break;

            case RESTORE:
            case IMPORT:

                writeAllDocuments(client, new File(config.getFileName()));
                break;

            default:
                throw new RuntimeException("unsupported sitemap type");
            }

            logger.info("Build complete.");

        } catch (SolrServerException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:net.modelbased.proasense.storage.registry.StorageRegistryScrapRateTestClient.java

public static void main(String[] args) {
    // Get client properties from properties file
    //        StorageRegistryScrapRateTestClient client = new StorageRegistryScrapRateTestClient();
    //        client.loadClientProperties();

    // Hardcoded client properties (simple test client)
    String STORAGE_REGISTRY_SERVICE_URL = "http://192.168.84.34:8080/storage-registry";

    // Default HTTP client and common properties for requests
    HttpClient client = new DefaultHttpClient();
    StringBuilder requestUrl = null;
    List<NameValuePair> params = null;
    String queryString = null;//  w  ww .  j a v a 2  s .c  o  m

    // Default HTTP response and common properties for responses
    HttpResponse response = null;
    ResponseHandler<String> handler = null;
    int status = 0;
    String body = null;

    // Query for machine list
    requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL);
    requestUrl.append("/query/machine/list");

    try {
        HttpGet query11 = new HttpGet(requestUrl.toString());
        query11.setHeader("Content-type", "application/json");
        response = client.execute(query11);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            throw new RuntimeException("Failed! HTTP error code: " + status);
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        System.out.println("MACHINE LIST: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Query for machine properties
    requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL);
    requestUrl.append("/query/machine/list");

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("machineId", "IMM1"));

    queryString = URLEncodedUtils.format(params, "utf-8");
    requestUrl.append("?");
    requestUrl.append(queryString);

    try {
        HttpGet query12 = new HttpGet(requestUrl.toString());
        query12.setHeader("Content-type", "application/json");
        response = client.execute(query12);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            throw new RuntimeException("Failed! HTTP error code: " + status);
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        System.out.println("MACHINE PROPERTIES: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Query for sensor list
    requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL);
    requestUrl.append("/query/sensor/list");

    try {
        HttpGet query21 = new HttpGet(requestUrl.toString());
        query21.setHeader("Content-type", "application/json");
        response = client.execute(query21);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            throw new RuntimeException("Failed! HTTP error code: " + status);
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        System.out.println("SENSOR LIST: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Query for sensor properties
    requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL);
    requestUrl.append("/query/sensor/properties");

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("sensorId", "dustParticleSensor"));

    queryString = URLEncodedUtils.format(params, "utf-8");
    requestUrl.append("?");
    requestUrl.append(queryString);

    try {
        HttpGet query22 = new HttpGet(requestUrl.toString());
        query22.setHeader("Content-type", "application/json");
        response = client.execute(query22);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            throw new RuntimeException("Failed! HTTP error code: " + status);
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        System.out.println("SENSOR PROPERTIES: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Query for product list
    requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL);
    requestUrl.append("/query/product/list");

    try {
        HttpGet query31 = new HttpGet(requestUrl.toString());
        query31.setHeader("Content-type", "application/json");
        response = client.execute(query31);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            throw new RuntimeException("Failed! HTTP error code: " + status);
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        System.out.println("PRODUCT LIST: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Query for product properties
    requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL);
    requestUrl.append("/query/product/properties");

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("productId", "Astra_3300"));

    queryString = URLEncodedUtils.format(params, "utf-8");
    requestUrl.append("?");
    requestUrl.append(queryString);

    try {
        HttpGet query22 = new HttpGet(requestUrl.toString());
        query22.setHeader("Content-type", "application/json");
        response = client.execute(query22);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            throw new RuntimeException("Failed! HTTP error code: " + status);
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        System.out.println("PRODUCT PROPERTIES: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Query for mould list
    requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL);
    requestUrl.append("/query/mould/list");

    try {
        HttpGet query41 = new HttpGet(requestUrl.toString());
        query41.setHeader("Content-type", "application/json");
        response = client.execute(query41);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            throw new RuntimeException("Failed! HTTP error code: " + status);
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        System.out.println("MOULD LIST: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Query for mould properties
    requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL);
    requestUrl.append("/query/product/properties");

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("productId", "Astra_3300"));

    queryString = URLEncodedUtils.format(params, "utf-8");
    requestUrl.append("?");
    requestUrl.append(queryString);

    try {
        HttpGet query42 = new HttpGet(requestUrl.toString());
        query42.setHeader("Content-type", "application/json");
        response = client.execute(query42);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            throw new RuntimeException("Failed! HTTP error code: " + status);
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        System.out.println("MOULD PROPERTIES: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:org.mzd.shap.spring.cli.ConfigSetup.java

public static void main(String[] args) {
    // check args
    if (args.length != 1) {
        exitOnError(1, null);//from  ww  w. j a v  a  2s. c o m
    }

    // check file existance
    File analyzerXML = new File(args[0]);
    if (!analyzerXML.exists()) {
        exitOnError(1, "'" + analyzerXML.getPath() + "' did not exist\n");
    }

    // prompt user whether existing data should be purged
    boolean isPurged = false;
    String ormContext = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    try {
        System.out.println("\nDo you wish to purge the database before running setup?");
        System.out.println("WARNING: all existing data in SHAP will be lost!");
        System.out.println("Really purge? yes/[NO]");
        String ans = br.readLine();
        if (ans.toLowerCase().equals("yes")) {
            System.out.println("Purging enabled");
            ormContext = "orm-purge-context.xml";
            isPurged = true;
        } else {
            System.out.println("Purging disabled");
            ormContext = "orm-context.xml";
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    // run tool
    try {
        // Using a generic application context since we're referencing
        // both classpath and filesystem resources.
        GenericApplicationContext ctx = new GenericApplicationContext();
        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
        xmlReader.loadBeanDefinitions(new ClassPathResource("datasource-context.xml"),
                new ClassPathResource(ormContext), new FileSystemResource(analyzerXML));
        ctx.refresh();

        /*
         * Create an base admin user.
         */
        if (isPurged) {
            //only attempted if we've wiped the old database.
            RoleDao roleDao = (RoleDao) ctx.getBean("roleDao");
            Role adminRole = roleDao.saveOrUpdate(new Role("admin", "ROLE_ADMIN"));
            Role userRole = roleDao.saveOrUpdate(new Role("user", "ROLE_USER"));
            UserDao userDao = (UserDao) ctx.getBean("userDao");
            userDao.saveOrUpdate(new User("admin", "admin", "shap01", adminRole, userRole));
        }

        /*
         * Create some predefined analyzers. Users should have modified
         * the configuration file to suit their environment.
         */
        AnnotatorDao annotatorDao = (AnnotatorDao) ctx.getBean("annotatorDao");
        DetectorDao detectorDao = (DetectorDao) ctx.getBean("detectorDao");

        ConfigSetup config = (ConfigSetup) ctx.getBean("configuration");

        for (Annotator an : config.getAnnotators()) {
            System.out.println("Adding annotator: " + an.getName());
            annotatorDao.saveOrUpdate(an);
        }

        for (Detector dt : config.getDetectors()) {
            System.out.println("Adding detector: " + dt.getName());
            detectorDao.saveOrUpdate(dt);
        }

        System.exit(0);
    } catch (Throwable t) {
        System.err.println(t.getMessage());
        System.exit(1);
    }
}