Example usage for java.io PrintWriter format

List of usage examples for java.io PrintWriter format

Introduction

In this page you can find the example usage for java.io PrintWriter format.

Prototype

public PrintWriter format(String format, Object... args) 

Source Link

Document

Writes a formatted string to this writer using the specified format string and arguments.

Usage

From source file:de.tudarmstadt.lt.lm.web.servlet.LanguageModelProviderServlet.java

private void show(String inputtype, String lm_key, String plaintext, String crawluri, boolean show_all_ngrams,
        PrintWriter w) throws Exception {
    if ("uri".equals(inputtype))
        plaintext = null;/* w  ww .j  av  a 2 s .co m*/
    if ("text".equals(inputtype))
        crawluri = null;

    if (plaintext == null && crawluri == null) // no parameter set
        plaintext = _test_text;

    w.write(_html_header);
    final Integer lm_index = _lm_keys.get(lm_key);
    if (lm_index == null) {
        LOG.error("Language model '{}' unknown.", lm_key);
        w.format("<p>Language model '%s' unknown. Please go to <a href='?'>main page</a>.</p>", lm_key);
        return;
    }

    StringProviderMXBean s = _lm_provider.get(lm_index);
    if (s == null) {
        if (!connectToLanguageModel(lm_key)) {
            w.format("<p>Language Model is loading. Please try again later.</p>", lm_key);
            w.write(_html_footer);
            w.flush();
            return;
        }
        s = _lm_provider.get(lm_index);
    }

    w.format("<h3>%s</h3>%n", lm_key);

    double crawl_perp = -1d;

    if (crawluri != null) {
        Object[] triple = crawl_and_extract_plaintext(crawluri, lm_key, lm_index);
        plaintext = (String) triple[0];
        crawl_perp = (Double) triple[1];
    } else
        crawluri = "";

    w.format(
            "<p>Crawl URI:</p>%n<p><form action='' method='get'><input type='text' name='crawluri' value='%s' size='100' />&nbsp;&nbsp;<input type='submit' value='Submit'><input type='hidden' name='inputtype' value='uri'><input type='hidden' name='lm' value='%s'><input type='hidden' name='action' value='show'></form></p>%n",
            crawluri, lm_key);
    w.format("<p>Crawler Perplexity = %012g</p>%n", crawl_perp);
    w.format("<p>Bytes Plaintext = %d</p>%n", plaintext.getBytes().length);
    w.format("<br />%n");
    w.format(
            "<p>Plaintext:</p>%n<p><form action='' method='get'><textarea rows='20' cols='150' name='plaintext'>%s</textarea><p><input type='submit' value='Submit'></p><input type='hidden' name='inputtype' value='text'><input type='hidden' name='lm' value='%s'><input type='hidden' name='action' value='show'></form></p>%n",
            plaintext, lm_key);
    w.format("<p>Perplexity = %012g</p>%n", s.getPerplexity(plaintext, false));
    w.format("<br />%n");

    w.format("<tt>%n");
    List<String>[] ngram_sequence = s.getNgrams(plaintext);
    w.format("+++ #ngrams= %d +++ <br /><br />%n", ngram_sequence.length);

    // TODO: provide ngrams
    for (int i = 0; i < ngram_sequence.length && (i <= 500 || show_all_ngrams); i++) {
        List<String> ngram = ngram_sequence[i];
        double log10_prob = s.getNgramLog10Probability(ngram);
        double prob10 = Math.pow(10, log10_prob);
        double log2_prob = log10_prob / Math.log10(2);
        int[] ngram_ids = s.getNgramAsIds(ngram);
        List<String> ngram_lm = s.getNgramAsWords(ngram_ids);
        w.format("%s <br />%n &nbsp;=> %s <br />%n &nbsp;= %012g (log_2 = %012g)<br /><br />%n",
                StringEscapeUtils.escapeHtml(ngram.toString()),
                StringEscapeUtils.escapeHtml(ngram_lm.toString()), prob10, log2_prob);
    }
    if (ngram_sequence.length > 500 && !show_all_ngrams)
        w.format("...%n");
    w.format("<br />%n");
    w.format("</tt>%n");

    w.write(_html_footer);

}

From source file:marytts.tools.voiceimport.VoicePackager.java

/**
 * Create config file for this voice.// ww w . j a v a  2 s. c o m
 * 
 * @param files
 *            &lt;property, File&gt; Map, e.g. "WaveTimelineMaker.waveTimeline" &rarr;
 *            File("VOICE_DIR/mary/timeline_waves.mry")
 * @return the config File object
 * @throws FileNotFoundException
 */
protected File createVoiceConfig(HashMap<String, File> files) throws FileNotFoundException {
    // open the config file for writing:
    String configFileName = String.format("%s-%s.config", getVoiceLocale(), getVoiceName());
    logger.info("Creating voice configuration file " + configFileName);
    File configFile = new File(getVoiceFileDir() + configFileName);
    PrintWriter out = new PrintWriter(configFile);

    // generate the config file contents, line by line:
    out.format("# Auto-generated config file for voice %s\r\n\r\n", getVoiceName());

    out.format("name = %s\r\n", getVoiceName());
    out.format("# Declare \"group names\" as component that other components can require.\r\n");
    out.format("# These correspond to abstract \"groups\" of which this component is an instance.\r\n");
    out.format("provides = \\\r\n\t%s-voice\r\n\r\n", getVoiceLocale());

    // TODO these seem to be ignored by MaryProperties, are they really needed?
    out.format("%s-voice.version = %s\r\n\r\n", getVoiceLocale(), getMaryVersion());
    out.format("voice.version = %s\r\n\r\n", getMaryVersion());

    out.format("# List the dependencies, as a whitespace-separated list.\r\n");
    out.format("# For each required component, an optional minimum version and an optional\r\n");
    out.format("# download url can be given.\r\n");
    out.format("# We can require a component by name or by an abstract \"group name\"\r\n");
    out.format("# as listed under the \"provides\" element.\r\n");
    out.format("requires = \\\r\n\t%s \\\r\n\tmarybase\r\n\r\n", getVoiceLocale());

    out.format("requires.marybase.version = %s\r\n", getMaryVersion());
    out.format("requires.%s.version = %s\r\n", getVoiceLocale(), getMaryVersion());
    // TODO: this is obviously a placeholder url; do we really need this?
    out.format("requires.%s.download = http://mary.dfki.de/download/mary-install-4.x.x.jar\r\n",
            getVoiceLocale());

    out.format("####################################################################\r\n");
    out.format("####################### Module settings  ###########################\r\n");
    out.format("####################################################################\r\n");
    out.format("# For keys ending in \".list\", values will be appended across config files,\r\n");
    out.format("# so that .list keys can occur in several config files.\r\n");
    out.format("# For all other keys, values will be copied to the global config, so\r\n");
    out.format("# keys should be unique across config files.\r\n");

    out.format("# If this setting is not present, a default value of 0 is assumed.\r\n");
    out.format("voice.%s.wants.to.be.default = 20\r\n\r\n", getVoiceName());

    out.format("# Add your voice to the list of Unit Selection Voices\r\n");
    out.format("unitselection.voices.list = \\\r\n\t%s\r\n\r\n", getVoiceName());

    out.format("# Set your voice specifications\r\n");
    out.format("voice.%s.gender = %s\r\n", getVoiceName(), getVoiceGender());
    out.format("voice.%s.locale = %s\r\n", getVoiceName(), getVoiceLocale());
    out.format("voice.%s.domain = %s\r\n", getVoiceName(), getVoiceDomain());
    out.format("voice.%s.samplingRate = %d\r\n\r\n", getVoiceName(), getVoiceSamplingRate());

    out.format("# Relative weight of the target cost function vs. the join cost function\r\n");
    out.format("voice.%s.viterbi.wTargetCosts = 0.7\r\n\r\n", getVoiceName());

    out.format("# Beam size in dynamic programming: smaller => faster but worse quality.\r\n");
    out.format("# (set to -1 to disable beam search; very slow but best available quality)\r\n");
    out.format("voice.%s.viterbi.beamsize = 100\r\n\r\n", getVoiceName());

    // TODO surely this should be dependent on having locale == "de"?
    out.format("# Sampa mapping for German voices \r\n");
    out.format("voice.%s.sampamap = \\\r\n", getVoiceName());
    out.format("\t=6->6 \\\r\n");
    out.format("\t=n->n \\\r\n");
    out.format("\t=m->m \\\r\n");
    out.format("\t=N->N \\\r\n");
    out.format("\t=l->l \\\r\n");
    out.format("\ti->i: \\\r\n");
    out.format("\te->e: \\\r\n");
    out.format("\tu->u: \\\r\n");
    out.format("\to->o: \r\n\r\n");

    out.format("# Java classes to use for the various unit selection components\r\n");
    out.format("voice.%s.databaseClass            = marytts.unitselection.data.DiphoneUnitDatabase\r\n",
            getVoiceName());
    out.format("voice.%s.selectorClass            = marytts.unitselection.select.DiphoneUnitSelector\r\n",
            getVoiceName());
    if (getProp(VOICETYPE).equalsIgnoreCase("HNM")) {
        out.format("voice.%s.concatenatorClass        = marytts.unitselection.concat.HnmUnitConcatenator\r\n",
                getVoiceName());
    } else if (getProp(VOICETYPE).equalsIgnoreCase("FDPSOLA")) {
        out.format(
                "voice.%s.concatenatorClass        = marytts.unitselection.concat.FdpsolaUnitConcatenator\r\n",
                getVoiceName());
    } else {
        out.format(
                "voice.%s.concatenatorClass        = marytts.unitselection.concat.OverlapUnitConcatenator\r\n",
                getVoiceName());
    }
    out.format(
            "voice.%s.targetCostClass          = marytts.unitselection.select.DiphoneFFRTargetCostFunction\r\n",
            getVoiceName());
    out.format("voice.%s.joinCostClass            = marytts.unitselection.select.JoinCostFeatures\r\n",
            getVoiceName());
    out.format("voice.%s.unitReaderClass          = marytts.unitselection.data.UnitFileReader\r\n",
            getVoiceName());
    out.format("voice.%s.cartReaderClass          = marytts.cart.io.MARYCartReader\r\n", getVoiceName());
    if (getProp(VOICETYPE).equalsIgnoreCase("HNM")) {
        out.format("voice.%s.audioTimelineReaderClass = marytts.unitselection.data.HnmTimelineReader\r\n\r\n",
                getVoiceName());
    } else {
        out.format("voice.%s.audioTimelineReaderClass = marytts.unitselection.data.TimelineReader\r\n\r\n",
                getVoiceName());
    }

    out.format("# Voice-specific files\r\n");
    out.format("voice.%s.featureFile       = MARY_BASE/lib/voices/%s/%s\r\n", getVoiceName(), getVoiceName(),
            files.get(HALFPHONEFEATSAC).getName());
    out.format("voice.%s.targetCostWeights = MARY_BASE/lib/voices/%s/%s\r\n", getVoiceName(), getVoiceName(),
            files.get(HALFPHONEFEATDEFAC).getName());
    out.format("voice.%s.joinCostFile      = MARY_BASE/lib/voices/%s/%s\r\n", getVoiceName(), getVoiceName(),
            files.get(JOINCOSTFEATS).getName());
    out.format("voice.%s.joinCostWeights   = MARY_BASE/lib/voices/%s/%s\r\n", getVoiceName(), getVoiceName(),
            files.get(JOINCOSTFEATDEF).getName());
    out.format("voice.%s.unitsFile         = MARY_BASE/lib/voices/%s/%s\r\n", getVoiceName(), getVoiceName(),
            files.get(HALFPHONEUNITS).getName());
    out.format("voice.%s.cartFile          = MARY_BASE/lib/voices/%s/%s\r\n", getVoiceName(), getVoiceName(),
            files.get(CARTFILE).getName());
    out.format("voice.%s.audioTimelineFile = MARY_BASE/lib/voices/%s/%s\r\n", getVoiceName(), getVoiceName(),
            files.get(TIMELINE).getName());
    out.format("voice.%s.basenameTimeline  = MARY_BASE/lib/voices/%s/%s\r\n\r\n", getVoiceName(),
            getVoiceName(), files.get(BASETIMELINE).getName());

    if (getVoiceDomain().equalsIgnoreCase("limited") || getProp(EXAMPLETEXTFILE).length() != 0) {
        out.format("# Location of example text\r\n");
        out.format("voice.%s.exampleTextFile = MARY_BASE/lib/voices/%s/%s\r\n\r\n", getVoiceName(),
                getVoiceName(), files.get(EXAMPLETEXTFILE).getName());
    }

    out.format("# Modules to use for predicting acoustic target features for this voice:\r\n\r\n");

    out.format("voice.%s.acousticModels = duration F0 midF0 rightF0\r\n\r\n", getVoiceName());

    out.format("voice.%s.duration.model = cart\r\n", getVoiceName());
    out.format("voice.%s.duration.data = MARY_BASE/lib/voices/%s/%s\r\n", getVoiceName(), getVoiceName(),
            files.get(DURTREE).getName());
    out.format("voice.%s.duration.attribute = d\r\n\r\n", getVoiceName());

    out.format("voice.%s.F0.model = cart\r\n", getVoiceName());
    out.format("voice.%s.F0.data = MARY_BASE/lib/voices/%s/%s\r\n", getVoiceName(), getVoiceName(),
            files.get(F0LEFTTREE).getName());
    out.format("voice.%s.F0.attribute = f0\r\n", getVoiceName());
    out.format("voice.%s.F0.attribute.format = (0,%%.0f)\r\n", getVoiceName());
    out.format("voice.%s.F0.predictFrom = firstVowels\r\n", getVoiceName());
    out.format("voice.%s.F0.applyTo = firstVoicedSegments\r\n\r\n", getVoiceName());

    out.format("voice.%s.midF0.model = cart\r\n", getVoiceName());
    out.format("voice.%s.midF0.data = MARY_BASE/lib/voices/%s/%s\r\n", getVoiceName(), getVoiceName(),
            files.get(F0MIDTREE).getName());
    out.format("voice.%s.midF0.attribute = f0\r\n", getVoiceName());
    out.format("voice.%s.midF0.attribute.format = (50,%%.0f)\r\n", getVoiceName());
    out.format("voice.%s.midF0.predictFrom = firstVowels\r\n", getVoiceName());
    out.format("voice.%s.midF0.applyTo = firstVowels\r\n\r\n", getVoiceName());

    out.format("voice.%s.rightF0.model = cart\r\n", getVoiceName());
    out.format("voice.%s.rightF0.data = MARY_BASE/lib/voices/%s/%s\r\n", getVoiceName(), getVoiceName(),
            files.get(F0RIGHTTREE).getName());
    out.format("voice.%s.rightF0.attribute = f0\r\n", getVoiceName());
    out.format("voice.%s.rightF0.attribute.format = (100,%%.0f)\r\n", getVoiceName());
    out.format("voice.%s.rightF0.predictFrom = firstVowels\r\n", getVoiceName());
    out.format("voice.%s.rightF0.applyTo = lastVoicedSegments\r\n", getVoiceName());

    // vocalization support, if available:
    if ("true".equals(getProp(VOCALIZATIONSUPPORT))) {
        out.format("\r\n# support for synthesis of vocalizations\r\n");
        out.format("voice.%s.vocalizationSupport = true\r\n", getVoiceName());
        out.format("voice.%s.vocalization.unitfile = MARY_BASE/lib/voices/%s/vocalization_units.mry\r\n",
                getVoiceName(), getVoiceName());
        out.format(
                "voice.%s.vocalization.timeline = MARY_BASE/lib/voices/%s/vocalization_wave_timeline.mry\r\n",
                getVoiceName(), getVoiceName());
        out.format("voice.%s.vocalization.featurefile = MARY_BASE/lib/voices/%s/vocalization_features.mry\r\n",
                getVoiceName(), getVoiceName());
        out.format(
                "voice.%s.vocalization.featureDefinitionFile = MARY_BASE/lib/voices/%s/vocalization_feature_definition.txt\r\n",
                getVoiceName(), getVoiceName());
        out.format(
                "voice.%s.vocalization.intonationfile = MARY_BASE/lib/voices/%s/vocalization_intonation.mry\r\n",
                getVoiceName(), getVoiceName());
        out.format("voice.%s.vocalization.synthesisTechnology = fdpsola\r\n\r\n", getVoiceName());

        out.format("voice.%s.f0ContourImposeSupport = true\r\n", getVoiceName());
        out.format("voice.%s.vocalization.usePrecondition = true\r\n", getVoiceName());
        out.format("voice.%s.vocalization.contourCostWeight = 0.05\r\n", getVoiceName());
        out.format(
                "voice.%s.vocalization.intonation.featureDefinitionFile = MARY_BASE/lib/voices/%s/vocalization_f0_feature_definition.txt\r\n",
                getVoiceName(), getVoiceName());

        out.format("voice.%s.vocalization.intonation.numberOfSuitableUnits = 5\r\n", getVoiceName());
    }

    out.close();
    return configFile;
}

From source file:erigo.filewatch.FileWatch.java

/**
 * Process a new file.  If we receive a file called "end.txt", that is
 * a signal to stop the test; return true in this case.
 *///from   w w  w. j  ava  2s. com
boolean processNewFile(String filenameStr, double eventTime) throws IOException {
    boolean bDone = false;
    if (filenameStr.equals("end.txt")) {
        // this is the signal that we're done
        bDone = true;
        // If we are doing recasting, put "end.txt" in output directory also
        if (bRecast) {
            // create end.txt in the output directory
            File endFile = new File(outputDir, filenameStr);
            new FileOutputStream(endFile).close();
        }
    } else {
        System.err.print(".");

        // Make sure we are using a unique key
        String testValue = fileData.get(new Double(eventTime));
        if (testValue != null) {
            // This key is already in use; create a unique key by adding a small artificial time increment
            while (true) {
                // Add a microsecond onto the event time
                eventTime = eventTime + 0.001;
                testValue = fileData.get(new Double(eventTime));
                if (testValue == null) {
                    // We now have a unique key!
                    break;
                }
            }
        }
        // System.out.format("%d  %s %s\n", eventTime, event.kind().name(), name);
        fileData.put(new Double(eventTime), filenameStr);
        ++num_received_files;
        if (num_received_files % 20 == 0) {
            System.err.println(" " + String.format("%4d", num_received_files));
        }

        // When doing recasting, put new file in the output directory;
        // it must be different from the received file in order to avoid
        // deduplication.
        if (bRecast) {
            // Do a quick check to make sure this is a valid filename before passing it on
            boolean bFilenameErr = false;
            // 1. name must start with a number
            char firstChar = filenameStr.charAt(0);
            bFilenameErr = !(firstChar >= '0' && firstChar <= '9');
            // 2. name must end with ".txt"
            if ((!bFilenameErr) && (!filenameStr.endsWith(".txt"))) {
                bFilenameErr = true;
            }
            if (!bFilenameErr) {
                //
                // Write a random number in the new outgoing file
                //
                //   *******************************************
                //   **                                       **
                //   **    NEED TO ADD FTP/SFTP CAPABILITY    **
                //   **                                       **
                //   *******************************************
                //
                int random_num = (int) ((double) random_range * random_generator.nextDouble());
                File newFullFile = new File(outputDir, filenameStr);
                try {
                    FileWriter fw = new FileWriter(newFullFile, false);
                    PrintWriter pw = new PrintWriter(fw);
                    // Write out random number to the file
                    pw.format("%06d\n", random_num);
                    pw.close();
                } catch (Exception e) {
                    System.err.println("Error writing to output file " + filenameStr);
                }
            }
        }
    }
    return bDone;
}

From source file:org.sample.client.TestServlet.java

/**
 * Processes requests for both HTTP/*from  w  w w .ja  v  a2  s.  c  o m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>JAX-RS 2 Client API</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>JAX-RS 2 Client API at " + request.getContextPath() + "</h1>");
    out.println("Initializing client...<br>");
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://" + request.getServerName() + ":" + request.getServerPort()
            + request.getContextPath() + "/webresources/persons");

    out.print("POSTing...<br>");
    // POST
    MultivaluedHashMap<String, String> map = new MultivaluedHashMap<>();
    map.add("name", "Name");
    map.add("age", "17");
    target.request().post(Entity.form(map));
    out.print("POSTed a new item ...<br>");

    // GET
    out.print("GETTing...<br>");
    Person[] list = target.request().get(Person[].class);
    out.format("GOT %1$s items<br>", list.length);
    for (Person p : list) {
        out.print(p + "<br>");
    }
    out.println("... done.<br>");

    // GET with path param
    out.print("GETTing with parameter...<br>");
    Person person = target.path("{id}").resolveTemplate("id", "1").request(MediaType.APPLICATION_XML)
            .get(Person.class);
    out.print("GOT person: " + person + "<br>");
    out.println("... done.");

    out.println("</body>");
    out.println("</html>");
}

From source file:org.apache.parquet.tools.command.ColumnIndexCommand.java

@Override
public void execute(CommandLine options) throws Exception {
    super.execute(options);

    String[] args = options.getArgs();
    InputFile in = HadoopInputFile.fromPath(new Path(args[0]), new Configuration());
    PrintWriter out = new PrintWriter(Main.out, true);
    String rowGroupValue = options.getOptionValue("r");
    Set<String> indexes = new HashSet<>();
    if (rowGroupValue != null) {
        indexes.addAll(Arrays.asList(rowGroupValue.split("\\s*,\\s*")));
    }// w  ww  . j av  a2 s  . c om
    boolean showColumnIndex = options.hasOption("i");
    boolean showOffsetIndex = options.hasOption("o");
    if (!showColumnIndex && !showOffsetIndex) {
        showColumnIndex = true;
        showOffsetIndex = true;
    }

    try (ParquetFileReader reader = ParquetFileReader.open(in)) {
        boolean firstBlock = true;
        int rowGroupIndex = 0;
        for (BlockMetaData block : reader.getFooter().getBlocks()) {
            if (!indexes.isEmpty() && !indexes.contains(Integer.toString(rowGroupIndex))) {
                ++rowGroupIndex;
                continue;
            }
            if (!firstBlock) {
                out.println();
                firstBlock = false;
            }
            out.format("row group %d:%n", rowGroupIndex);
            for (ColumnChunkMetaData column : getColumns(block, options)) {
                String path = column.getPath().toDotString();
                if (showColumnIndex) {
                    out.format("column index for column %s:%n", path);
                    ColumnIndex columnIndex = reader.readColumnIndex(column);
                    if (columnIndex == null) {
                        out.println("NONE");
                    } else {
                        out.println(columnIndex);
                    }
                }
                if (showOffsetIndex) {
                    out.format("offset index for column %s:%n", path);
                    OffsetIndex offsetIndex = reader.readOffsetIndex(column);
                    if (offsetIndex == null) {
                        out.println("NONE");
                    } else {
                        out.println(offsetIndex);
                    }
                }
            }
            ++rowGroupIndex;
        }
    }
}

From source file:sf.net.experimaestro.manager.js.XPMObject.java

/**
 * Creates a new command line job// w w w. j  a  v  a  2 s.c o  m
 *
 * @param path     The identifier for this job
 * @param commands The command line(s)
 * @param options  The options
 * @return
 * @throws Exception
 */
public JSResource commandlineJob(Object path, Commands commands, NativeObject options) throws Exception {
    CommandLineTask task = null;
    // --- XPMProcess arguments: convert the javascript array into a Java array
    // of String
    LOGGER.debug("Adding command line job");

    // --- Create the task

    final Connector connector;

    if (options != null && options.has("connector", options)) {
        connector = ((JSConnector) options.get("connector", options)).getConnector();
    } else {
        connector = currentResourceLocator.getConnector();
    }

    // Store connector in database
    scheduler.put(connector);

    // Resolve the path for the given connector
    if (path instanceof FileObject) {
        path = connector.getMainConnector().resolve((FileObject) path);
    } else
        path = connector.getMainConnector().resolve(path.toString());

    final ResourceLocator locator = new ResourceLocator(connector.getMainConnector(), path.toString());
    task = new CommandLineTask(scheduler, locator, commands);

    if (submittedJobs.containsKey(locator)) {
        getRootLogger().info("Not submitting %s [duplicate]", locator);
        if (simulate())
            return new JSResource(submittedJobs.get(locator));
        return new JSResource(scheduler.getResource(locator));
    }

    // -- Adds default locks
    Map<? extends Resource, ?> _defaultLocks = taskContext != null && taskContext.defaultLocks() != null
            ? taskContext.defaultLocks()
            : defaultLocks;
    for (Map.Entry<? extends Resource, ?> lock : _defaultLocks.entrySet()) {
        Dependency dependency = lock.getKey().createDependency(lock.getValue());
        task.addDependency(dependency);
    }

    // --- Environment
    task.environment = new TreeMap<>(environment);

    // --- Options

    if (options != null) {

        final ArrayList unmatched = new ArrayList(Sets.difference(options.keySet(), COMMAND_LINE_OPTIONS));
        if (!unmatched.isEmpty()) {
            throw new IllegalArgumentException(
                    format("Some options are not allowed: %s", Output.toString(", ", unmatched)));
        }

        // --- XPMProcess launcher
        if (options.has("launcher", options)) {
            final Object launcher = options.get("launcher", options);
            if (launcher != null && !(launcher instanceof UniqueTag))
                task.setLauncher(((JSLauncher) launcher).getLauncher());

        }

        // --- Redirect standard output
        if (options.has("stdin", options)) {
            final Object stdin = unwrap(options.get("stdin", options));
            if (stdin instanceof String || stdin instanceof ConsString) {
                task.setInput(stdin.toString());
            } else if (stdin instanceof FileObject) {
                task.setInput((FileObject) stdin);
            } else
                throw new XPMRuntimeException("Unsupported stdin type [%s]", stdin.getClass());
        }

        // --- Redirect standard output
        if (options.has("stdout", options)) {
            FileObject fileObject = getFileObject(connector, unwrap(options.get("stdout", options)));
            task.setOutput(fileObject);
        }

        // --- Redirect standard error
        if (options.has("stderr", options)) {
            FileObject fileObject = getFileObject(connector, unwrap(options.get("stderr", options)));
            task.setError(fileObject);
        }

        // --- Resources to lock
        if (options.has("lock", options)) {
            List locks = (List) options.get("lock", options);
            for (int i = (int) locks.size(); --i >= 0;) {
                Object lock_i = JSUtils.unwrap(locks.get(i));
                Dependency dependency = null;

                if (lock_i instanceof Dependency) {
                    dependency = (Dependency) lock_i;
                } else if (lock_i instanceof NativeArray) {
                    NativeArray array = (NativeArray) lock_i;
                    if (array.getLength() != 2)
                        throw new XPMRhinoException(
                                new IllegalArgumentException("Wrong number of arguments for lock"));

                    final Object depObject = JSUtils.unwrap(array.get(0, array));
                    Resource resource = null;
                    if (depObject instanceof Resource) {
                        resource = (Resource) depObject;
                    } else {
                        final String rsrcPath = Context.toString(depObject);
                        ResourceLocator depLocator = ResourceLocator.parse(rsrcPath);
                        resource = scheduler.getResource(depLocator);
                        if (resource == null)
                            if (simulate()) {
                                if (!submittedJobs.containsKey(depLocator))
                                    LOGGER.error("The dependency [%s] cannot be found", depLocator);
                            } else {
                                throw new XPMRuntimeException("Resource [%s] was not found", rsrcPath);
                            }
                    }

                    final Object lockType = array.get(1, array);
                    LOGGER.debug("Adding dependency on [%s] of type [%s]", resource, lockType);

                    if (!simulate()) {
                        dependency = resource.createDependency(lockType);
                    }
                } else {
                    throw new XPMRuntimeException("Element %d for option 'lock' is not a dependency but %s", i,
                            lock_i.getClass());
                }

                if (!simulate()) {
                    task.addDependency(dependency);
                }
            }

        }

    }

    // Update the task status now that it is initialized
    task.setGroup(defaultGroup);

    final Resource old = scheduler.getResource(locator);
    if (old != null) {
        // TODO: if equal, do not try to replace the task
        if (!task.replace(old)) {
            getRootLogger().warn(String.format("Cannot override resource [%s]", task.getIdentifier()));
            old.init(scheduler);
            return new JSResource(old);
        } else {
            getRootLogger().info(String.format("Overwriting resource [%s]", task.getIdentifier()));
        }
    }

    task.setState(ResourceState.WAITING);
    if (simulate()) {
        PrintWriter pw = new LoggerPrintWriter(getRootLogger(), Level.INFO);
        pw.format("[Simulation] Starting job: %s%n", task.getLocator().toString());
        pw.format("Command: %s%n", task.getCommands().toString());
        pw.format("Locator: %s", locator.toString());
        pw.flush();
    } else {
        scheduler.store(task, false);
    }

    final JSResource jsResource = new JSResource(task);
    this.submittedJobs.put(task.getLocator(), task);
    return jsResource;
}

From source file:org.sipfoundry.voicemail.MailboxServlet.java

public void doIt(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    SipxIvrConfiguration ivrConfig = (SipxIvrConfiguration) request
            .getAttribute(SipxIvrServletHandler.IVR_CONFIG_ATTR);
    ValidUsers validUsers = (ValidUsers) request.getAttribute(SipxIvrServletHandler.VALID_USERS_ATTR);
    Map<String, String> depositMap = (Map<String, String>) request
            .getAttribute(SipxIvrServletHandler.DEPOSIT_MAP_ATTR);
    MailboxManager mailboxManager = (MailboxManager) request
            .getAttribute(SipxIvrServletHandler.MAILBOX_MANAGER);
    Mwi mwiManager = (Mwi) request.getAttribute(SipxIvrServletHandler.MWI_MANAGER);

    String method = request.getMethod().toUpperCase();

    String pathInfo = request.getPathInfo();
    String[] subDirs = pathInfo.split("/");
    if (subDirs.length < 3) {
        response.sendError(404); // path not found
        return;/*from  www.j  a  v  a  2  s. c  om*/
    }

    // The first element is empty (the leading slash)
    // The second element is the mailbox
    String mailboxString = subDirs[1];
    // The third element is the "context" (either mwi, message)
    String context = subDirs[2];

    User user = validUsers.getUser(mailboxString);
    // only superadmin and mailbox owner can access this service
    // TODO allow all admin user to access it

    if (user != null && ServletUtil.isForbidden(request, user.getUserName(), request.getLocalPort(),
            ivrConfig.getHttpPort())) {
        response.sendError(403); // Send 403 Forbidden
        return;
    }

    // delete mailbox could come only from a internal port, when user already deleted from
    // mongo
    if (context.equals("delete")) {
        if (ivrConfig.getHttpPort() == request.getLocalPort()) {
            if (method.equals(METHOD_PUT)) {
                try {
                    mailboxManager.deleteMailbox(mailboxString);
                } catch (Exception ex) {
                    response.sendError(500);
                }
            } else {
                response.sendError(405);
            }
        }
    } else {
        if (user != null) {
            PrintWriter pw = response.getWriter();
            LOG.info(String.format("MailboxServlet::doIt %s %s", method, pathInfo));
            // determine the message counts for the mailbox
            // (Okay, worry about this one. It walks the mailstore directories counting .xml
            // and
            // .sta files.)
            if (context.equals("message")) {
                if (subDirs.length >= 5) {
                    String messageId = subDirs[3];
                    String action = subDirs[4];
                    if (action.equals("heard")) {
                        if (method.equals(METHOD_DELETE)) {
                            mailboxManager.markMessageUnheard(user, messageId);
                        } else if (method.equals(METHOD_PUT)) {
                            mailboxManager.markMessageHeard(user, messageId);
                        } else if (method.equals(METHOD_GET)) {
                            try {
                                response.setContentType("text/xml");
                                pw.format("<heard>%s</heard>\n",
                                        mailboxManager.isMessageUnHeard(user, messageId) ? "false" : "true");
                            } catch (MessageNotFoundException ex) {
                                response.sendError(404, "messageId not found");
                            }
                        }
                    }

                    if (action.equals("delete")) {
                        if (method.equals(METHOD_PUT)) {
                            try {
                                mailboxManager.deleteMessage(user, messageId);
                            } catch (MessageNotFoundException ex) {
                                response.sendError(404, "messageId not found");
                            }
                        }
                    }

                    if (action.equals("subject")) {
                        if (method.equals(METHOD_PUT)) {
                            try {
                                String subject = IOUtils.toString(request.getInputStream());
                                mailboxManager.updateMessageSubject(user, messageId, subject);
                            } catch (MessageNotFoundException ex) {
                                response.sendError(404, "messageId not found");
                            }
                        }
                    }

                    if (action.equals("move")) {
                        if (method.equals(METHOD_PUT)) {
                            try {
                                String destinationFolder = subDirs[5];
                                mailboxManager.moveMessageToFolder(user, messageId, destinationFolder);
                                MailboxDetails mailbox = mailboxManager.getMailboxDetails(user.getUserName());
                                mwiManager.sendMWI(user, mailbox);
                            } catch (MessageNotFoundException ex) {
                                response.sendError(404, "messageId not found");
                            }
                        }
                    }

                } else {
                    response.sendError(400, "messageId missing");
                }
            } else if (context.equals("mwi")) {
                if (method.equals(METHOD_PUT)) {
                    MailboxDetails mailbox = mailboxManager.getMailboxDetails(user.getUserName());
                    mwiManager.sendMWI(user, mailbox);
                } else if (method.equals(METHOD_GET)) {
                    response.setContentType(Mwi.MessageSummaryContentType);
                    String accountUrl = "sip:" + user.getIdentity();
                    MailboxDetails mailbox = mailboxManager.getMailboxDetails(user.getUserName());
                    pw.write(Mwi.formatRFC3842(mailbox, accountUrl));
                } else {
                    response.sendError(405);
                }
            } else if (context.equals("uuid")) {
                response.setContentType("text/xml");
                String uuid = depositMap.get(user.getUserName());
                if (uuid == null) {
                    pw.write("<uuid></uuid>\n");
                } else {
                    pw.format("<uuid>%s</uuid>\n", uuid);
                }

            } else if (context.equals("rename")) {
                if (subDirs.length >= 4) {
                    String oldMailbox = subDirs[3];
                    if (method.equals(METHOD_PUT)) {
                        try {
                            mailboxManager.renameMailbox(user, oldMailbox);
                        } catch (Exception ex) {
                            response.sendError(500);
                        }
                    } else {
                        response.sendError(405);
                    }
                } else {
                    response.sendError(400, "destination missing");
                }

            } else if (context.equals("messages")) {
                if (method.equals(METHOD_GET)) {
                    response.setContentType("text/xml");
                    pw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
                    pw.write("<messages>\n");
                    List<VmMessage> inboxMessages = mailboxManager.getMessages(user.getUserName(),
                            Folder.INBOX);
                    List<VmMessage> savedMessages = mailboxManager.getMessages(user.getUserName(),
                            Folder.SAVED);
                    List<VmMessage> deletedMessages = mailboxManager.getMessages(user.getUserName(),
                            Folder.DELETED);
                    listMessages(inboxMessages, "inbox", pw);
                    listMessages(savedMessages, "saved", pw);
                    listMessages(deletedMessages, "deleted", pw);
                    pw.write("</messages>");
                } else {
                    response.sendError(405);
                }
            } else if (context.equals("inbox")) {
                if (method.equals(METHOD_GET)) {
                    response.setContentType("text/xml");
                    pw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
                    pw.write("<messages>\n");
                    if (subDirs.length >= 4) {
                        String messageId = subDirs[3];
                        try {
                            listFullMessage(mailboxManager.getVmMessage(user.getUserName(), Folder.INBOX,
                                    messageId, false), "inbox", pw);
                        } catch (MessageNotFoundException ex) {
                            response.sendError(404, "messageId not found");
                        }
                    } else {
                        listFullMessages(mailboxManager.getMessages(user.getUserName(), Folder.INBOX), "inbox",
                                pw);
                    }
                    pw.write("</messages>");
                } else {
                    response.sendError(405);
                }
            } else if (context.equals("saved")) {
                if (method.equals(METHOD_GET)) {
                    response.setContentType("text/xml");
                    pw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
                    pw.write("<messages>\n");
                    if (subDirs.length >= 4) {
                        String messageId = subDirs[3];
                        try {
                            listFullMessage(mailboxManager.getVmMessage(user.getUserName(), Folder.SAVED,
                                    messageId, false), "saved", pw);
                        } catch (MessageNotFoundException ex) {
                            response.sendError(404, "messageId not found");
                        }
                    } else {
                        listFullMessages(mailboxManager.getMessages(user.getUserName(), Folder.SAVED), "saved",
                                pw);
                    }
                    pw.write("</messages>");
                } else {
                    response.sendError(405);
                }
            } else if (context.equals("deleted")) {
                if (method.equals(METHOD_GET)) {
                    response.setContentType("text/xml");
                    pw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
                    pw.write("<messages>\n");
                    if (subDirs.length >= 4) {
                        String messageId = subDirs[3];
                        try {
                            listFullMessage(mailboxManager.getVmMessage(user.getUserName(), Folder.DELETED,
                                    messageId, false), "deleted", pw);
                        } catch (MessageNotFoundException ex) {
                            response.sendError(404, "messageId not found");
                        }
                    } else {
                        listFullMessages(mailboxManager.getMessages(user.getUserName(), Folder.DELETED),
                                "deleted", pw);
                    }
                    pw.write("</messages>");
                } else {
                    response.sendError(405);
                }
            } else if (context.equals("conference")) {
                if (method.equals(METHOD_GET)) {
                    response.setContentType("text/xml");
                    pw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
                    pw.write("<messages>\n");
                    if (subDirs.length >= 4) {
                        String messageId = subDirs[3];
                        try {
                            listFullMessage(mailboxManager.getVmMessage(user.getUserName(), Folder.CONFERENCE,
                                    messageId, false), "conference", pw);
                        } catch (MessageNotFoundException ex) {
                            response.sendError(404, "messageId not found");
                        }
                    } else {
                        listFullMessages(mailboxManager.getMessages(user.getUserName(), Folder.CONFERENCE),
                                "conference", pw);
                    }
                    pw.write("</messages>");
                } else {
                    response.sendError(405);
                }
            } else {
                response.sendError(400, "context not understood");
            }
            pw.close();
        } else {
            response.sendError(404, "Mailbox not found");
            LOG.info(String.format("MailboxServlet::doIt %s not found", mailboxString));
        }
    }

}

From source file:org.kalypso.model.hydrology.internal.preprocessing.writer.NetFileWriter.java

private void appendNodeList(final Node[] nodes, final PrintWriter netBuffer)
        throws IOException, SensorException {
    // FIXME: theses nodes do not contain the branching nodes
    final Map<Node, ZuflussBean> nodeInfos = new LinkedHashMap<>();

    /* First collect info and potentially add branching nodes */
    for (final Node node : nodes) {
        final ZuflussBean zuflussBean = createZuflussBean(node);

        // FIXME: strange we map the source-node here...
        nodeInfos.put(node, zuflussBean);

        final Node branchingNode = zuflussBean.getBranchingNode();
        if (branchingNode != null) {
            // FIXME: ... but check for the target node here; this can't be right, can it?
            // FIXME: comment is not correct
            /* Do not overwrite existing info */

            // FIXME: in reality, we make sure a node that is the target of a branching, gets a default bean; but this happens anyways, so what? -> if the target itself has a branching, it might get
            // removed, if the nodes are in the correct order...
            if (!nodeInfos.containsKey(branchingNode))
                nodeInfos.put(branchingNode, new ZuflussBean(0, 0, 0, 0, 0, null, StringUtils.EMPTY));
        }/*from   w w  w  .  j av a2  s . c  o  m*/
    }

    /* Write thes infos to file */
    final Set<Entry<Node, ZuflussBean>> entrySet = nodeInfos.entrySet();
    for (final Entry<Node, ZuflussBean> entry : entrySet) {
        final Node node = entry.getKey();
        final ZuflussBean zuflussBean = entry.getValue();

        final int nodeID = m_idManager.getAsciiID(node);

        netBuffer.format("%5d", nodeID); //$NON-NLS-1$

        netBuffer.format("%5d", zuflussBean.getIzug()); //$NON-NLS-1$
        netBuffer.format("%5d", zuflussBean.getIabg()); //$NON-NLS-1$
        netBuffer.format("%5d", zuflussBean.getIueb()); //$NON-NLS-1$
        netBuffer.format("%5d", zuflussBean.getIzuf()); //$NON-NLS-1$
        netBuffer.format("%5d\n", zuflussBean.getIvzwg()); //$NON-NLS-1$ //$NON-NLS-2$

        netBuffer.append(zuflussBean.getArgument());

        // FIXME: what additional nodes?
        /* TODO: we should also consider the additional nodes by QQ rleations; but as QQ rleations do not work..... */
    }

    // ENDKNOTEN
    netBuffer.append(" 9001    0    0    0    0    0\n"); //$NON-NLS-1$
    netBuffer.append("10000    0    0    0    0    0\n"); //$NON-NLS-1$
}