Example usage for java.io File exists

List of usage examples for java.io File exists

Introduction

In this page you can find the example usage for java.io File exists.

Prototype

public boolean exists() 

Source Link

Document

Tests whether the file or directory denoted by this abstract pathname exists.

Usage

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step11GoldDataStatistics.java

public static void main(String[] args) throws Exception {
    // input dir - list of xml query containers
    // /home/user-ukp/research/data/dip/wp1-documents/step3-filled-raw-html
    File inputDir = new File(args[0]);

    // output dir
    File outputDir = new File(args[1]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();/*w w  w. j a  v  a 2s. c om*/
    }

    statistics1(inputDir, outputDir);
    statistics2(inputDir, outputDir);
    statistics3(inputDir, outputDir);
    statistics4(inputDir, outputDir);
    statistics5(inputDir, outputDir);
    statistics6(inputDir, outputDir);
}

From source file:jeffaschenk.tomcat.zuul.util.KeyFileUtils.java

/**
 * Utility Main to provide capabilities to generate a protected KeyFile for use with Zuul
 *
 * @param args - Incoming program Arguments
 * @throws Exception//from w  ww .  j a  v  a2s .c  om
 */
public static void main(String[] args) throws Exception {

    // Initialize our Ciphers
    KeyFileUtils keyFileUtils = new KeyFileUtils();
    keyFileUtils.InitCiphers();

    // Assume we our sole purpose in life is to prompt for a Password, which is the same,
    // ensure we have an argument to be out filename.
    if ((args == null) || (args.length != 1)) {
        System.out.println("Invalid number of Arguments specified!");
        System.out.println(
                "Usage: " + keyFileUtils.getClass().getName() + " <Fully Qualified Output Key Filename>");
        return;
    }

    // Validate Argument as a file.
    File outputKeyFile = new File(args[0]);
    if (outputKeyFile.exists()) {
        // Prompt to overwrite...
        char[] answer = readPassword("Specified Key File:[" + outputKeyFile + "], exists. Overwrite? (y/n)? ");
        if ((answer == null) || (answer.length == 0)
                || (!String.valueOf(answer).toUpperCase().startsWith("Y"))) {
            System.out.println(
                    "Existing Key File:[" + outputKeyFile + "], exists. Will not be Overwritten, Done.");
            return;
        } else {
            outputKeyFile.delete();
        }
    }

    // Prompt Operator for the Zuul Encryption Password to be encrypted in a file and saved for later access.
    // Prompt to overwrite...
    char[] password = obtainValidatedPassword("Enter Zuul Encryption Password: ");
    if (password == null) {
        System.out.println("Unable to obtain Password, Done.");
        return;
    }

    // Create our Input and Output Streams for the encryption of the Password.
    InputStream is = IOUtils.toInputStream(String.valueOf(password), "UTF-8");
    FileOutputStream fos = new FileOutputStream(outputKeyFile);

    // Encrypt
    keyFileUtils.CBCEncrypt(is, fos);

    // Now lets us Validate the file.
    keyFileUtils.ResetCiphers();
    keyFileUtils = new KeyFileUtils();
    keyFileUtils.InitCiphers();

    // Obtain the Decrypted Contents
    byte[] obtainedDecryptedData = keyFileUtils.CBCDecrypt(new FileInputStream(outputKeyFile));

    // Compare to validate...
    boolean valid = String.valueOf(password).equals(new String(obtainedDecryptedData));
    Arrays.fill(password, ' ');
    Arrays.fill(obtainedDecryptedData, (byte) 0x00);
    if (valid) {
        System.out.println("Key File:[" + outputKeyFile + "], validated and available for use, Done.");
        return;
    } else {
        System.out.println("Key File:[" + outputKeyFile + "], Did not Validate, very bad!");
        return;
    }
}

From source file:com.moss.appsnap.server.AppSnapServer.java

public static void main(String[] args) throws Exception {
    System.setProperty("org.mortbay.log.class", Slf4jLog.class.getName());

    File log4jConfigFile = new File("log4j.xml");

    if (log4jConfigFile.exists()) {
        DOMConfigurator.configureAndWatch(log4jConfigFile.getAbsolutePath(), 1000);
    } else {// ww w .j  av  a2 s.c  o m
        BasicConfigurator.configure();
        Logger.getRootLogger().setLevel(Level.INFO);
    }

    ServerConfiguration config;

    JAXBContext context = JAXBContext.newInstance(ServerConfiguration.class, VeracityId.class);
    JAXBHelper helper = new JAXBHelper(context);

    Logger log = Logger.getLogger(AppSnapServer.class);

    File[] configPaths = new File[] { new File("settings.xml"),
            new File(new File(System.getProperty("user.home")), ".appsnap-server.xml"),
            new File("/etc/appsnap-server.xml") };

    File configFile = null;

    for (File next : configPaths) {
        if (next.exists()) {
            configFile = next;
        }
    }

    if (configFile == null) {

        log.warn("No config file found.");

        for (int x = configPaths.length - 1; x >= 0; x--) {
            File next = configPaths[x];
            log.warn("Attempting to create default config file at " + next.getAbsolutePath());
            ServerConfiguration defaults = new ServerConfiguration();
            defaults.idProofRecipie(
                    new PasswordProofRecipie(new SimpleId("mr-admin-dude"), "my-super-secret-password"));
            try {
                helper.writeToFile(helper.writeToXmlString(defaults), next);
                log.warn("done");
                break;
            } catch (Exception e) {
                log.warn("Error writing file: " + e.getMessage(), e);
            }
        }
        System.exit(1);
        return;
    } else {
        log.info("Reading configuration from " + configFile.getAbsolutePath());
        config = helper.readFromFile(configFile);
    }

    ProxyFactory proxyFactory = new ProxyFactory(new HessianProxyProvider());
    try {
        new AppSnapServer(config, proxyFactory);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Unexpected Error.  Shutting Down.");
        System.exit(1);
    }
}

From source file:eu.sendregning.oxalis.Main.java

public static void main(String[] args) throws Exception {

    OptionParser optionParser = getOptionParser();

    if (args.length == 0) {
        System.out.println("");
        optionParser.printHelpOn(System.out);
        System.out.println("");
        return;/*from  w  w w  . j  a v a 2 s .  c  om*/
    }

    OptionSet optionSet;

    try {
        optionSet = optionParser.parse(args);
    } catch (Exception e) {
        printErrorMessage(e.getMessage());
        return;
    }

    File xmlInvoice = xmlDocument.value(optionSet);

    if (!xmlInvoice.exists()) {
        printErrorMessage("XML document " + xmlInvoice + " does not exist");
        return;
    }

    String recipientId = recipient.value(optionSet);
    String senderId = sender.value(optionSet);

    try {

        System.out.println("");
        System.out.println("");

        // bootstraps the Oxalis outbound module
        OxalisOutboundModule oxalisOutboundModule = new OxalisOutboundModule();

        // creates a transmission request builder and enable tracing
        TransmissionRequestBuilder requestBuilder = oxalisOutboundModule.getTransmissionRequestBuilder();
        requestBuilder.trace(trace.value(optionSet));
        System.out.println("Trace mode of RequestBuilder: " + requestBuilder.isTraceEnabled());

        // add receiver participant
        if (recipientId != null) {
            requestBuilder.receiver(new ParticipantId(recipientId));
        }

        // add sender participant
        if (senderId != null) {
            requestBuilder.sender((new ParticipantId(senderId)));
        }

        if (docType != null && docType.value(optionSet) != null) {
            requestBuilder.documentType(PeppolDocumentTypeId.valueOf(docType.value(optionSet)));
        }

        if (profileType != null && profileType.value(optionSet) != null) {
            requestBuilder.processType(PeppolProcessTypeId.valueOf(profileType.value(optionSet)));
        }

        // Supplies the payload
        requestBuilder.payLoad(new FileInputStream(xmlInvoice));

        // Overrides the destination URL if so requested
        if (optionSet.has(destinationUrl)) {
            String destinationString = destinationUrl.value(optionSet);
            URL destination;

            try {
                destination = new URL(destinationString);
            } catch (MalformedURLException e) {
                printErrorMessage("Invalid destination URL " + destinationString);
                return;
            }

            // Fetches the transmission method, which was overridden on the command line
            BusDoxProtocol busDoxProtocol = BusDoxProtocol.instanceFrom(transmissionMethod.value(optionSet));

            if (busDoxProtocol == BusDoxProtocol.AS2) {
                String accessPointSystemIdentifier = destinationSystemId.value(optionSet);
                if (accessPointSystemIdentifier == null) {
                    throw new IllegalStateException("Must specify AS2 system identifier if using AS2 protocol");
                }
                requestBuilder.overrideAs2Endpoint(destination, accessPointSystemIdentifier);
            } else {
                throw new IllegalStateException("Unknown busDoxProtocol : " + busDoxProtocol);
            }
        }

        // Specifying the details completed, creates the transmission request
        TransmissionRequest transmissionRequest = requestBuilder.build();

        // Fetches a transmitter ...
        Transmitter transmitter = oxalisOutboundModule.getTransmitter();

        // ... and performs the transmission
        TransmissionResponse transmissionResponse = transmitter.transmit(transmissionRequest);

        // Write the transmission id and where the message was delivered
        System.out.printf("Message using messageId %s sent to %s using %s was assigned transmissionId %s\n",
                transmissionResponse.getStandardBusinessHeader().getMessageId().stringValue(),
                transmissionResponse.getURL().toExternalForm(), transmissionResponse.getProtocol().toString(),
                transmissionResponse.getTransmissionId());

        String evidenceFileName = transmissionResponse.getTransmissionId().toString() + "-evidence.dat";
        IOUtils.copy(new ByteArrayInputStream(transmissionResponse.getEvidenceBytes()),
                new FileOutputStream(evidenceFileName));
        System.out.printf("Wrote transmission receipt to " + evidenceFileName);

    } catch (Exception e) {
        System.out.println("");
        System.out.println("Message failed : " + e.getMessage());
        //e.printStackTrace();
        System.out.println("");
    }
}

From source file:com.act.biointerpretation.sars.SarGenerationDriver.java

public static void main(String[] args) throws Exception {
    // Build command line parser.
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from w  ww  .j  a va 2 s .  c  om*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        LOGGER.error("Argument parsing failed: %s", e.getMessage());
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    // Print help.
    if (cl.hasOption(OPTION_HELP)) {
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    // Create DB and DbAPI
    MongoDB mongoDB = new MongoDB(LOCAL_HOST, MONGO_PORT, cl.getOptionValue(OPTION_DB));
    DbAPI dbApi = new DbAPI(mongoDB);

    // Handle output file
    File outputFile = new File(cl.getOptionValue(OPTION_OUTPUT_PATH));
    if (outputFile.isDirectory() || outputFile.exists()) {
        LOGGER.error("Supplied output file is a directory or already exists.");
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }
    outputFile.createNewFile();

    // Check that there is exactly one reaction group input option
    if (cl.hasOption(OPTION_REACTION_LIST) && cl.hasOption(OPTION_REACTIONS_FILE)) {
        LOGGER.error("Cannot process both a reaction list and a reactions file as input.");
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }
    if (!cl.hasOption(OPTION_REACTION_LIST) && !cl.hasOption(OPTION_REACTIONS_FILE)) {
        LOGGER.error("Must supply either a reaction list or a reactions file as input.");
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    // Build input reaction group corpus.
    Iterable<ReactionGroup> groups = null;
    if (cl.hasOption(OPTION_REACTION_LIST)) {
        LOGGER.info("Using specific input reactions.");
        ReactionGroup group = new ReactionGroup("ONLY_GROUP", "NO_DB");
        for (String idString : cl.getOptionValues(OPTION_REACTION_LIST)) {
            group.addReactionId(Long.parseLong(idString));
        }
        groups = Arrays.asList(group);
    }
    if (cl.hasOption(OPTION_REACTIONS_FILE)) {
        LOGGER.info("Using reactions file.");
        File inputFile = new File(cl.getOptionValue(OPTION_REACTIONS_FILE));
        try {
            groups = ReactionGroupCorpus.loadFromJsonFile(inputFile);
            LOGGER.info("Successfully parsed input as json file.");
        } catch (IOException e) {
            LOGGER.info("Input file not json file. Trying txt format.");
            try {
                groups = ReactionGroupCorpus.loadFromTextFile(inputFile);
                LOGGER.info("Successfully parsed input as text file.");
            } catch (IOException f) {
                LOGGER.error("Reactions input file not parseable. %s", f.getMessage());
                throw f;
            }
        }
    }

    // Build all pieces of SAR generator
    ReactionProjector projector = new ReactionProjector();
    ExpandedReactionSearcher generalizer = new ExpandedReactionSearcher(projector);

    McsCalculator reactionMcsCalculator = new McsCalculator(McsCalculator.REACTION_BUILDING_OPTIONS);
    McsCalculator sarMcsCalculator = new McsCalculator(McsCalculator.SAR_OPTIONS);

    FullReactionBuilder reactionBuilder = new FullReactionBuilder(reactionMcsCalculator, generalizer,
            projector);

    SarFactory substructureSarFactory = new OneSubstrateSubstructureSar.Factory(sarMcsCalculator);
    SarFactory carbonCountSarFactory = new OneSubstrateCarbonCountSar.Factory();
    List<SarFactory> sarFactories = Arrays.asList(carbonCountSarFactory, substructureSarFactory);

    ErosCorpus roCorpus = new ErosCorpus();
    roCorpus.loadValidationCorpus();

    ReactionGroupCharacterizer reactionGroupCharacterizer = new OneSubstrateOneRoCharacterizer(dbApi,
            sarFactories, reactionBuilder, roCorpus);
    SarCorpusBuilder corpusBuilder = new SarCorpusBuilder(groups, reactionGroupCharacterizer);
    LOGGER.info("Parsed arguments and constructed SAR corpus builder. Building corpus.");

    SarCorpus sarCorpus = corpusBuilder.build();
    LOGGER.info("Built sar corpus. Printing to file in json format.");

    sarCorpus.printToJsonFile(outputFile);
    LOGGER.info("Complete!");
}

From source file:com.jivesoftware.os.routing.bird.deployable.config.extractor.ConfigExtractor.java

public static void main(String[] args) {
    String configHost = args[0];/* www. j av  a2s  . c  om*/
    String configPort = args[1];
    String instanceKey = args[2];
    String instanceVersion = args[3];
    String setPath = args[4];
    String getPath = args[5];

    HttpRequestHelper buildRequestHelper = buildRequestHelper(null, configHost, Integer.parseInt(configPort));

    try {
        Set<URL> packages = new HashSet<>();
        for (int i = 5; i < args.length; i++) {
            packages.addAll(ClasspathHelper.forPackage(args[i]));
        }

        Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(packages)
                .setScanners(new SubTypesScanner(), new TypesScanner()));

        Set<Class<? extends Config>> subTypesOf = reflections.getSubTypesOf(Config.class);

        File configDir = new File("./config");
        configDir.mkdirs();

        Set<Class<? extends Config>> serviceConfig = new HashSet<>();
        Set<Class<? extends Config>> healthConfig = new HashSet<>();
        for (Class<? extends Config> type : subTypesOf) {
            if (HealthCheckConfig.class.isAssignableFrom(type)) {
                healthConfig.add(type);
            } else {
                serviceConfig.add(type);
            }
        }

        Map<String, String> defaultServiceConfig = extractAndPublish(serviceConfig,
                new File(configDir, "default-service-config.properties"), "default", instanceKey,
                instanceVersion, buildRequestHelper, setPath);

        DeployableConfig getServiceOverrides = new DeployableConfig("override", instanceKey, instanceVersion,
                defaultServiceConfig);
        DeployableConfig gotSerivceConfig = buildRequestHelper.executeRequest(getServiceOverrides, getPath,
                DeployableConfig.class, null);
        if (gotSerivceConfig == null) {
            System.out.println("Failed to publish default service config for " + Arrays.deepToString(args));
        } else {
            Properties override = createKeySortedProperties();
            override.putAll(gotSerivceConfig.properties);
            override.store(new FileOutputStream("config/override-service-config.properties"), "");
        }

        Map<String, String> defaultHealthConfig = extractAndPublish(healthConfig,
                new File(configDir, "default-health-config.properties"), "default-health", instanceKey,
                instanceVersion, buildRequestHelper, setPath);

        DeployableConfig getHealthOverrides = new DeployableConfig("override-health", instanceKey,
                instanceVersion, defaultHealthConfig);
        DeployableConfig gotHealthConfig = buildRequestHelper.executeRequest(getHealthOverrides, getPath,
                DeployableConfig.class, null);
        if (gotHealthConfig == null) {
            System.out.println("Failed to publish default health config for " + Arrays.deepToString(args));
        } else {
            Properties override = createKeySortedProperties();
            override.putAll(gotHealthConfig.properties);
            override.store(new FileOutputStream("config/override-health-config.properties"), "");
        }

        Properties instanceProperties = createKeySortedProperties();
        File configFile = new File("config/instance.properties");
        if (configFile.exists()) {
            instanceProperties.load(new FileInputStream(configFile));
        }

        Properties serviceOverrideProperties = createKeySortedProperties();
        configFile = new File("config/override-service-config.properties");
        if (configFile.exists()) {
            serviceOverrideProperties.load(new FileInputStream(configFile));
        }

        Properties healthOverrideProperties = createKeySortedProperties();
        configFile = new File("config/override-health-config.properties");
        if (configFile.exists()) {
            healthOverrideProperties.load(new FileInputStream(configFile));
        }

        Properties properties = createKeySortedProperties();
        properties.putAll(defaultServiceConfig);
        properties.putAll(defaultHealthConfig);
        properties.putAll(serviceOverrideProperties);
        properties.putAll(healthOverrideProperties);
        properties.putAll(instanceProperties);
        properties.store(new FileOutputStream("config/config.properties"), "");

        System.exit(0);
    } catch (Exception x) {
        x.printStackTrace();
        System.exit(1);
    }

}

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

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    String inputDir = args[0];/*from w ww.j a v a2 s  . co m*/
    File outputDir = new File(args[1]);

    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    // we will process only a subset first
    List<AnnotatedArgumentPair> allArgumentPairs = new ArrayList<>();

    Collection<File> files = IOHelper.listXmlFiles(new File(inputDir));

    for (File file : files) {
        allArgumentPairs.addAll((List<AnnotatedArgumentPair>) XStreamTools.getXStream().fromXML(file));
    }

    // collect turkers and csv
    List<String> turkerIDs = extractAndSortTurkerIDs(allArgumentPairs);
    String preparedCSV = prepareCSV(allArgumentPairs, turkerIDs);

    // save CSV and run MACE
    Path tmpDir = Files.createTempDirectory("mace");
    File maceInputFile = new File(tmpDir.toFile(), "input.csv");
    FileUtils.writeStringToFile(maceInputFile, preparedCSV, "utf-8");

    File outputPredictions = new File(tmpDir.toFile(), "predictions.txt");
    File outputCompetence = new File(tmpDir.toFile(), "competence.txt");

    // run MACE
    MACE.main(new String[] { "--iterations", "500", "--threshold", String.valueOf(MACE_THRESHOLD), "--restarts",
            "50", "--outputPredictions", outputPredictions.getAbsolutePath(), "--outputCompetence",
            outputCompetence.getAbsolutePath(), maceInputFile.getAbsolutePath() });

    // read back the predictions and competence
    List<String> predictions = FileUtils.readLines(outputPredictions, "utf-8");

    // check the output
    if (predictions.size() != allArgumentPairs.size()) {
        throw new IllegalStateException("Wrong size of the predicted file; expected " + allArgumentPairs.size()
                + " lines but was " + predictions.size());
    }

    String competenceRaw = FileUtils.readFileToString(outputCompetence, "utf-8");
    String[] competence = competenceRaw.split("\t");
    if (competence.length != turkerIDs.size()) {
        throw new IllegalStateException(
                "Expected " + turkerIDs.size() + " competence number, got " + competence.length);
    }

    // rank turkers by competence
    Map<String, Double> turkerIDCompetenceMap = new TreeMap<>();
    for (int i = 0; i < turkerIDs.size(); i++) {
        turkerIDCompetenceMap.put(turkerIDs.get(i), Double.valueOf(competence[i]));
    }

    // sort by value descending
    Map<String, Double> sortedCompetences = IOHelper.sortByValue(turkerIDCompetenceMap, false);
    System.out.println("Sorted turker competences: " + sortedCompetences);

    // assign the gold label and competence

    for (int i = 0; i < allArgumentPairs.size(); i++) {
        AnnotatedArgumentPair annotatedArgumentPair = allArgumentPairs.get(i);
        String goldLabel = predictions.get(i).trim();

        // might be empty
        if (!goldLabel.isEmpty()) {
            // so far the gold label has format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal
            // strip now only the gold label
            annotatedArgumentPair.setGoldLabel(goldLabel);
        }

        // update turker competence
        for (AnnotatedArgumentPair.MTurkAssignment assignment : annotatedArgumentPair.mTurkAssignments) {
            String turkID = assignment.getTurkID();

            int turkRank = getTurkerRank(turkID, sortedCompetences);
            assignment.setTurkRank(turkRank);

            double turkCompetence = turkerIDCompetenceMap.get(turkID);
            assignment.setTurkCompetence(turkCompetence);
        }
    }

    // now sort the data back according to their original file name
    Map<String, List<AnnotatedArgumentPair>> fileNameAnnotatedPairsMap = new HashMap<>();
    for (AnnotatedArgumentPair argumentPair : allArgumentPairs) {
        String fileName = IOHelper.createFileName(argumentPair.getDebateMetaData(),
                argumentPair.getArg1().getStance());

        if (!fileNameAnnotatedPairsMap.containsKey(fileName)) {
            fileNameAnnotatedPairsMap.put(fileName, new ArrayList<AnnotatedArgumentPair>());
        }

        fileNameAnnotatedPairsMap.get(fileName).add(argumentPair);
    }

    // and save them to the output file
    for (Map.Entry<String, List<AnnotatedArgumentPair>> entry : fileNameAnnotatedPairsMap.entrySet()) {
        String fileName = entry.getKey();
        List<AnnotatedArgumentPair> argumentPairs = entry.getValue();

        File outputFile = new File(outputDir, fileName);

        // and save all sampled pairs into a XML file
        XStreamTools.toXML(argumentPairs, outputFile);

        System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile);
    }

}

From source file:Base64.java

/**
 * Entry point.//w  ww .  j a va  2  s.  co  m
 * 
 * @param args
 *          the command line arguments.
 */
public static void main(final String[] args) {
    boolean decode = false;

    if (args.length == 0) {
        System.out.println("usage:  java Base64 [-d[ecode]] filename");
        System.exit(0);
    }
    for (int i = 0; i < args.length; i++) {
        if ("-decode".equalsIgnoreCase(args[i])) {
            decode = true;
        } else if ("-d".equalsIgnoreCase(args[i])) {
            decode = true;
        }
    }

    final String filename = args[args.length - 1];
    final File file = new File(filename);
    if (!file.exists()) {
        System.out.println("Error:  file '" + filename + "' doesn't exist!");
        System.exit(0);
    }

    if (decode) {
        final char[] encoded = readChars(file);
        final byte[] decoded = decode(encoded);
        writeBytes(file, decoded);
    } else {
        final byte[] decoded = readBytes(file);
        final char[] encoded = encode(decoded);
        writeChars(file, encoded);
    }
}

From source file:importer.handler.post.stages.Splitter.java

/** test and commandline utility */
public static void main(String[] args) {
    if (args.length >= 1) {
        try {/*ww  w  . j  a v  a  2s  . co m*/
            int i = 0;
            int fileIndex = 0;
            // see if the user supplied a conf file
            String textConf = Discriminator.defaultConf;
            while (i < args.length) {
                if (args[i].equals("-c") && i < args.length - 1) {
                    textConf = readConfig(args[i + 1]);
                    i += 2;
                } else {
                    fileIndex = i;
                    i++;
                }
            }
            File f = new File(args[fileIndex]);
            char[] data = new char[(int) f.length()];
            FileReader fr = new FileReader(f);
            fr.read(data);
            JSONObject config = (JSONObject) JSONValue.parse(textConf);
            Splitter split = new Splitter(config);
            Map<String, String> map = split.split(new String(data));
            Set<String> keys = map.keySet();
            String rawFileName = args[fileIndex];
            int pos = rawFileName.lastIndexOf(".");
            if (pos != -1)
                rawFileName = rawFileName.substring(0, pos);
            Iterator<String> iter = keys.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                String fName = rawFileName + "-" + key + ".xml";
                File g = new File(fName);
                if (g.exists())
                    g.delete();
                FileOutputStream fos = new FileOutputStream(g);
                fos.write(map.get(key).getBytes("UTF-8"));
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    } else
        System.out.println("usage: java -jar split.jar [-c json-config] <tei-xml>\n");
}

From source file:net.sf.mpaxs.test.ImpaxsExecution.java

/**
 *
 * @param args/*from   w  ww. j  ava 2 s  .  co  m*/
 */
public static void main(String[] args) {
    Options options = new Options();
    Option[] optionArray = new Option[] {
            OptionBuilder.withArgName("nhosts").hasArg()
                    .withDescription("Number of hosts for parallel processing").create("n"),
            OptionBuilder.withArgName("mjobs").hasArg().withDescription("Number of jobs to run in parallel")
                    .create("m"),
            OptionBuilder.withArgName("runmode").hasArg()
                    .withDescription("The mode in which to operate: one of <ALL,LOCAL,DISTRIBUTED>")
                    .create("r"), //            OptionBuilder.withArgName("gui").
            //            withDescription("Create gui for distributed execution").create("g")
    };
    for (Option opt : optionArray) {
        options.addOption(opt);
    }
    if (args.length == 0) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }
    GnuParser gp = new GnuParser();
    int nhosts = 1;
    int mjobs = 10;
    boolean gui = false;
    Mode mode = Mode.ALL;
    try {
        CommandLine cl = gp.parse(options, args);
        if (cl.hasOption("n")) {
            nhosts = Integer.parseInt(cl.getOptionValue("n"));
        }
        if (cl.hasOption("m")) {
            mjobs = Integer.parseInt(cl.getOptionValue("m"));
        }
        if (cl.hasOption("r")) {
            mode = Mode.valueOf(cl.getOptionValue("r"));
        }
        //            if (cl.hasOption("g")) {
        //                gui = true;
        //            }
    } catch (Exception ex) {
        Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }

    String version;
    try {
        version = net.sf.mpaxs.api.Version.getVersion();
        System.out.println("Running mpaxs " + version);
        File computeHostJarLocation = new File(System.getProperty("user.dir"), "mpaxs.jar");
        if (!computeHostJarLocation.exists() || !computeHostJarLocation.isFile()) {
            throw new IOException("Could not locate mpaxs.jar in " + System.getProperty("user.dir"));
        }
        final PropertiesConfiguration cfg = new PropertiesConfiguration();
        //set default execution type
        cfg.setProperty(ConfigurationKeys.KEY_EXECUTION_MODE, ExecutionType.DRMAA);
        //set location of compute host jar
        cfg.setProperty(ConfigurationKeys.KEY_PATH_TO_COMPUTEHOST_JAR, computeHostJarLocation);
        //do not exit to console when master server shuts down
        cfg.setProperty(ConfigurationKeys.KEY_MASTER_SERVER_EXIT_ON_SHUTDOWN, false);
        //limit the number of used compute hosts
        cfg.setProperty(ConfigurationKeys.KEY_MAX_NUMBER_OF_CHOSTS, nhosts);
        cfg.setProperty(ConfigurationKeys.KEY_NATIVE_SPEC, "");
        cfg.setProperty(ConfigurationKeys.KEY_GUI_MODE, gui);
        cfg.setProperty(ConfigurationKeys.KEY_SILENT_MODE, true);
        cfg.setProperty(ConfigurationKeys.KEY_SCHEDULE_WAIT_TIME, "500");
        final int maxJobs = mjobs;
        final int maxThreads = nhosts;
        final Mode runMode = mode;
        printMessage("Run mode: " + runMode);
        Executors.newSingleThreadExecutor().submit(new Runnable() {
            @Override
            public void run() {
                if (runMode == Mode.ALL || runMode == Mode.LOCAL) {
                    printMessage("Running Within VM Execution");
                    /*
                     * LOCAL within VM execution
                     */
                    WithinVmExecution lhe = new WithinVmExecution(maxJobs, maxThreads);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + lhe.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                if (runMode == Mode.ALL || runMode == Mode.DISTRIBUTED) {
                    printMessage("Running Distributed Host RMI Execution");
                    /*
                     * Grid Engine (DRMAA API) or local host distributed RMI execution
                     */
                    DistributedRmiExecution de = new DistributedRmiExecution(cfg, maxJobs);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + de.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                System.exit(0);
            }
        });
    } catch (IOException ex) {
        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
    }
}