示例#1
0
  /**
   * For testing purposes only.
   *
   * @deprecate Please see class documentation for an example of how to use this class. Or consider
   *     using the Ant task for the schema generator.
   */
  public static void main(String args[]) {

    if (args.length == 0) {
      System.out.println("Missing filename");
      System.out.println();
      System.out.println("usage: java XMLInstance2Schema <input-file> [<output-file> (optional)]");
      return;
    }

    try {
      XMLInstance2Schema xi2s = new XMLInstance2Schema();
      Schema schema = xi2s.createSchema(args[0]);

      Writer dstWriter = null;
      if (args.length > 1) {
        dstWriter = new FileWriter(args[1]);
      } else {
        dstWriter = new PrintWriter(System.out, true);
      }

      xi2s.serializeSchema(dstWriter, schema);
      dstWriter.flush();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  static void sendJSONResponse(HttpServletResponse response, Map<String, String> responseMap) {
    if (!Boolean.parseBoolean(responseMap.get("success"))) {
      int serverCode = 500;
      if (responseMap.containsKey("serverCode")) {
        serverCode = Integer.parseInt(responseMap.get("serverCode"));
      }
      response.setStatus(serverCode);
    }

    String responseContent = new Gson().toJson(responseMap);
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    response.setHeader("Content-Length", Integer.toString(responseContent.length()));

    Writer writer = null;
    try {
      writer = response.getWriter();
      writer.write(responseContent);
    } catch (IOException ex) {
      Logger.getLogger(RequestResponseHelper.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException ex) {
          Logger.getLogger(RequestResponseHelper.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }
  }
示例#3
0
 protected void drawHtmlPreSubsForm(Writer out) throws IOException {
   out.write(
       "<form action=\"" //$NON-NLS-1$
           + this.getAction()
           + "\" name=\"mgnlFormMain\" method=\"post\" enctype=\"multipart/form-data\">\n"); //$NON-NLS-1$
   out.write(
       new Hidden("mgnlDialog", this.getConfigValue("dialog"), false)
           .getHtml()); //$NON-NLS-1$ //$NON-NLS-2$
   out.write(
       new Hidden("mgnlRepository", this.getConfigValue("repository"), false)
           .getHtml()); //$NON-NLS-1$ //$NON-NLS-2$
   out.write(
       new Hidden("mgnlPath", this.getConfigValue("path"), false)
           .getHtml()); //$NON-NLS-1$ //$NON-NLS-2$
   out.write(
       new Hidden("mgnlNodeCollection", this.getConfigValue("nodeCollection"), false)
           .getHtml()); //$NON-NLS-1$ //$NON-NLS-2$
   out.write(
       new Hidden("mgnlNode", this.getConfigValue("node"), false)
           .getHtml()); //$NON-NLS-1$ //$NON-NLS-2$
   out.write(
       new Hidden("mgnlJsCallback", this.getCallbackJavascript(), false).getHtml()); // $NON-NLS-1$
   out.write(
       new Hidden("mgnlRichE", this.getConfigValue("richE"), false)
           .getHtml()); //$NON-NLS-1$ //$NON-NLS-2$
   out.write(
       new Hidden("mgnlRichEPaste", this.getConfigValue("richEPaste"), false)
           .getHtml()); //$NON-NLS-1$ //$NON-NLS-2$
   if (this.getConfigValue("paragraph").indexOf(",") == -1) { // $NON-NLS-1$ //$NON-NLS-2$
     out.write(
         new Hidden("mgnlParagraph", this.getConfigValue("paragraph"), false)
             .getHtml()); //$NON-NLS-1$ //$NON-NLS-2$
   } // else multiple paragraph selection -> radios for selection
 }
 /**
  * Exports the throughput times of all process instances in piList to a comma-seperated text-file.
  *
  * @param piList ArrayList: the process instances used
  * @param file File: the file to which the times are exported
  * @param divider long: the time divider used
  * @param sort String: the time sort used
  * @param fitOption int: the fit option used (how to deal with non-conformance)
  * @throws IOException
  */
 public void exportToFile(ArrayList piList, File file, long divider, String sort, int fitOption)
     throws IOException {
   Writer output = new BufferedWriter(new FileWriter(file));
   String line = "Log Trace,Throughput time (" + sort + ")\n";
   output.write(line);
   ListIterator lit = piList.listIterator();
   while (lit.hasNext()) {
     ExtendedLogTrace currentTrace = (ExtendedLogTrace) lit.next();
     try {
       double tp =
           (currentTrace.getEndDate().getTime() - currentTrace.getBeginDate().getTime())
               * 1.0
               / divider;
       if (fitOption == 0) {
         // times based on all traces
         line = currentTrace.getName() + "," + tp + "\n";
         // write line to the file
         output.write(line);
       }
       if (fitOption == 1
           && currentTrace.hasProperlyTerminated()
           && currentTrace.hasSuccessfullyExecuted()) {
         // times based on fitting traces only
         line = currentTrace.getName() + "," + tp + "\n";
         // write line to the file
         output.write(line);
       }
     } catch (NullPointerException npe) {
     }
   }
   // close the file
   output.close();
 }
示例#5
0
  public static JSONObject getJsonFromInputStream(final InputStream inputStream, String type) {

    if (inputStream != null) {
      Writer writer = new StringWriter();
      int buffer_size = 1024;
      char[] buffer = new char[buffer_size];

      try {
        Reader reader =
            new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), buffer_size);
        int n;

        while ((n = reader.read(buffer)) != -1) {
          writer.write(buffer, 0, n);
        }

        inputStream.close();
        reader.close();
        writer.close();

        return new JSONObject(writer.toString()).getJSONObject(type);

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return null;
  }
 private static File convertGLFile(File originalFile) throws IOException {
   // Now translate the file; remove commas, then convert "::" delimiter to comma
   File resultFile = new File(new File(System.getProperty("java.io.tmpdir")), "ratings.txt");
   if (resultFile.exists()) {
     resultFile.delete();
   }
   Writer writer = null;
   try {
     writer = new OutputStreamWriter(new FileOutputStream(resultFile), Charsets.UTF_8);
     for (String line : new FileLineIterable(originalFile, false)) {
       int lastDelimiterStart = line.lastIndexOf(COLON_DELIMTER);
       if (lastDelimiterStart < 0) {
         throw new IOException("Unexpected input format on line: " + line);
       }
       String subLine = line.substring(0, lastDelimiterStart);
       String convertedLine = COLON_DELIMITER_PATTERN.matcher(subLine).replaceAll(",");
       writer.write(convertedLine);
       writer.write('\n');
     }
   } catch (IOException ioe) {
     resultFile.delete();
     throw ioe;
   } finally {
     Closeables.close(writer, false);
   }
   return resultFile;
 }
  /**
   * Test method for {@link cpath.converter.internal.UniprotCleanerImpl#cleane(java.lang.String)}.
   *
   * @throws IOException
   */
  @Test
  public void testCleaner() throws IOException {
    // read data from file and look for accessions before being cleaned
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    CPathUtils.unzip(
        new ZipInputStream(
            CPathUtils.LOADER.getResource("/test_uniprot_data.dat.zip").getInputStream()),
        os);
    byte[] bytes = os.toByteArray();
    String data = new String(bytes);
    assertTrue(data.indexOf(CALR3_HUMAN_BEFORE) != -1);
    assertTrue(data.indexOf(CALRL_HUMAN_BEFORE) != -1);

    Cleaner cleaner = new UniProtCleanerImpl();
    os.reset();
    cleaner.clean(new ByteArrayInputStream(bytes), os);
    bytes = os.toByteArray();

    data = new String(bytes);
    assertTrue(data.indexOf(CALR3_HUMAN_AFTER) != -1);
    assertTrue(data.indexOf(CALRL_HUMAN_AFTER) != -1);

    // dump owl for review
    String outFilename =
        getClass().getClassLoader().getResource("").getPath()
            + File.separator
            + "testCleanUniProt.out.dat";
    Writer out = new OutputStreamWriter(new FileOutputStream(outFilename));
    out.write(data);
    out.close();
  }
示例#8
0
 private static void main2(String[] args) {
   Config.cmdline(args);
   try {
     javabughack();
   } catch (InterruptedException e) {
     return;
   }
   setupres();
   MainFrame f = new MainFrame(null);
   if (Utils.getprefb("fullscreen", false)) f.setfs();
   f.mt.start();
   try {
     f.mt.join();
   } catch (InterruptedException e) {
     f.g.interrupt();
     return;
   }
   dumplist(Resource.remote().loadwaited(), Config.loadwaited);
   dumplist(Resource.remote().cached(), Config.allused);
   if (ResCache.global != null) {
     try {
       Writer w = new OutputStreamWriter(ResCache.global.store("tmp/allused"), "UTF-8");
       try {
         Resource.dumplist(Resource.remote().used(), w);
       } finally {
         w.close();
       }
     } catch (IOException e) {
     }
   }
   System.exit(0);
 }
示例#9
0
  /**
   * Creates the REST API documentation in HTML form, using the controllers' data and the velocity
   * template.
   *
   * @param controllers .
   * @return string that contains the documentation in HTML form.
   * @throws Exception .
   */
  public String generateHtmlDocumentation(final List<DocController> controllers) throws Exception {

    logger.log(
        Level.INFO,
        "Generate velocity using template: "
            + velocityTemplatePath
            + (isUserDefineTemplatePath
                ? File.separator + velocityTemplateFileName + " (got template path from user)"
                : "(default template path)"));

    Properties p = new Properties();
    p.setProperty("directive.set.null.allowed", "true");
    if (isUserDefineTemplatePath) {
      p.setProperty("file.resource.loader.path", velocityTemplatePath);
    } else {
      p.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
      p.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    }

    Velocity.init(p);

    VelocityContext ctx = new VelocityContext();

    ctx.put("controllers", controllers);
    ctx.put("version", version);
    ctx.put("docCssPath", docCssPath);

    Writer writer = new StringWriter();

    Template template = Velocity.getTemplate(velocityTemplateFileName);
    template.merge(ctx, writer);

    return writer.toString();
  }
示例#10
0
  /**
   * Start one module after the other and try to compile the input file. Then generate the assembler
   * file and create this file for jasmin.
   */
  private static void parseCompile(String input, String fileName)
      throws ParserException, LexerException, IOException {
    String output; // Init output string
    StringReader reader =
        new StringReader(input); // Standard routine to start the parser, lexer, ...
    PushbackReader r = new PushbackReader(reader, 100);
    Lexer l = new Lexer(r);
    Parser parser = new Parser(l);
    Start start = parser.parse();

    //        ASTPrinter printer = new ASTPrinter();
    //        start.apply(printer);

    TypeChecker typeChecker = new TypeChecker(); // Starting TypeChecker
    start.apply(typeChecker);

    CodeGenerator codeGenerator = new CodeGenerator(typeChecker.getSymbolTable());
    copySymbolTable(
        typeChecker, codeGenerator); // To get all the identifiers copied with an index to CodeGen
    start.apply(codeGenerator);

    output = createOutput(codeGenerator, fileName);

    Writer wout =
        new BufferedWriter( // Write everything to the outputfile.j
            new OutputStreamWriter(new FileOutputStream(fileName + ".j"), "UTF8"));
    wout.append(output);
    wout.close();
  }
示例#11
0
 public void writeLink(Writer out) throws Exception {
   out.write("<a href=\"group.jsp?g=");
   UtilityMethods.writeURLEncoded(out, tagName);
   out.write("\">");
   HTMLWriter.writeHtml(out, tagName);
   out.write("</a>");
 }
示例#12
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // text of validation target
    String text = request.getParameter("text");

    // type of validation.
    String method = request.getParameter("method");

    // length for check max length
    String lengthStr = request.getParameter("length");

    boolean result;
    if ("regexp".equals(method)) {
      result = checkRegExp(text);
    } else if ("charset".equals(method)) {
      result = checkCharset(text);
    } else if ("datefmt".equals(method)) {
      result = checkDateFormat(text);
    } else {
      int length = Integer.parseInt(lengthStr);
      result = checkMaxLength(text, length);
    }
    String resultStr = Boolean.toString(result);
    response.setContentType("text/plain");
    response.setContentLength(resultStr.length());
    Writer writer = response.getWriter();
    writer.write(resultStr);
    writer.flush();
    writer.close();
  }
  private String readContent(InputStream content) throws IOException {
    if (content == null) return "";

    Reader reader = null;
    Writer writer = new StringWriter();
    String result;

    char[] buffer = new char[1024];
    try {
      reader = new BufferedReader(new InputStreamReader(content, ENCODING));
      int n;
      while ((n = reader.read(buffer)) > 0) {
        writer.write(buffer, 0, n);
      }
      result = writer.toString();
    } finally {
      content.close();
      if (reader != null) {
        reader.close();
      }
      if (writer != null) {
        writer.close();
      }
    }
    return result;
  }
  public static void run(Configuration conf, Path input, String outputFile)
      throws IOException, InstantiationException, IllegalAccessException {
    Writer writer;
    if (outputFile == null) {
      writer = new OutputStreamWriter(System.out);
    } else {
      writer =
          new OutputStreamWriter(
              new FileOutputStream(new File(outputFile)), Charset.forName("UTF-8"));
    }

    try {
      FileSystem fs = input.getFileSystem(conf);
      for (FileStatus fst : fs.listStatus(input, new DataPathFilter())) {
        Path dataPath = fst.getPath();
        SequenceFile.Reader reader = new SequenceFile.Reader(fs, dataPath, conf);
        try {
          Text key = reader.getKeyClass().asSubclass(Text.class).newInstance();
          DocumentMapping value = new DocumentMapping();
          while (reader.next(key, value)) {
            String docId = value.getDocId();
            writer.write(docId + "\t" + key + "\n");
          }
        } finally {
          reader.close();
        }
      }
    } finally {
      writer.close();
    }
  }
  public int dumpNames(String fileName) throws IOException {
    File f = new File(fileName);

    final int[] entries = {0};
    final Writer out = new FileWriter(f);
    iterateThru(
        new IndexEntriesWalker() {
          public void process(String ctxPath, String value, String[] attrs) {
            try {
              out.write(ctxPath + " " + buildAppendix(value, attrs) + "\n");
              entries[0]++;
            } catch (IOException e) {
              throw new Error(e);
            }
          }
        });

    iterateFileNames(
        new IndexEntriesWalkerInterruptable() {
          public boolean process(String ctxPath, String value) {
            try {
              out.write(
                  ctxPath + " " + (value == null || value.length() == 0 ? NO_VAL : value) + "\n");
              entries[0]++;
              return true;
            } catch (IOException e) {
              throw new Error(e);
            }
          }
        });

    out.close();
    return entries[0];
  }
示例#16
0
    /** writer a column */
    public void write(String content) throws IOException {

      if (content == null) {
        content = "";
      }

      if (!firstColumn) {
        writer.write(Delimiter);
      }

      writer.write(TextQualifier);

      // support backslash mode
      if (EscapeMode == ESCAPE_MODE_BACKSLASH) {
        content = replace(content, "" + BACKSLASH, "" + BACKSLASH + BACKSLASH);
        content = replace(content, "" + TextQualifier, "" + BACKSLASH + TextQualifier);
      } else { // support double mode
        content = replace(content, "" + TextQualifier, "" + TextQualifier + TextQualifier);
      }

      writer.write(content);

      writer.write(TextQualifier);

      firstColumn = false;
    }
示例#17
0
  protected void writeCssTo(Writer writer, Output output) throws IOException {
    Object[] results;
    Mapper mapper;
    Node node;

    if (output.getMuted()) {
      throw new IllegalArgumentException();
    }
    mapper = SSASS.newInstance();
    mapper.setErrorHandler(new ExceptionErrorHandler());
    for (int i = 0; i < nodes.size(); i++) {
      node = nodes.get(i);
      if (i > 0) {
        writer.write(LF);
      }
      if (!overallMinimize) {
        writer.write(type.comment(location(node)));
      }
      results = mapper.run(node);
      if (results == null) {
        throw new IOException(node.toString() + ": css/sass error");
      }
      output.setMuted(declarationsOnly.get(i));
      try {
        ((Stylesheet) results[0]).toCss(output);
      } catch (GenericException e) {
        throw new IOException(node.toString() + ": css generation failed: " + e.getMessage(), e);
      }
      if (output.getMuted() != declarationsOnly.get(i)) {
        throw new IllegalStateException();
      }
    }
  }
示例#18
0
  public static String RenderTemplatePage(Bindings b, String templateName) throws IOException {

    MediaType mt = MediaType.TEXT_HTML;
    Resource config = model.createResource("eh:/root");
    Mode prefixMode = Mode.PreferPrefixes;
    ShortnameService sns = new StandardShortnameService();

    List<Resource> noResults = CollectionUtils.list(root.inModel(model));
    Graph resultGraph = graphModel.getGraph();

    resultGraph.getPrefixMapping().setNsPrefix("api", API.NS);
    resultGraph.add(Triple.create(root.asNode(), API.items.asNode(), RDF.nil.asNode()));

    APIResultSet rs = new APIResultSet(resultGraph, noResults, true, true, "details", View.ALL);
    VelocityRenderer vr = new VelocityRenderer(mt, null, config, prefixMode, sns);

    VelocityRendering vx = new VelocityRendering(b, rs, vr);

    VelocityEngine ve = vx.createVelocityEngine();
    VelocityContext vc = vx.createVelocityContext(b);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    Writer w = new OutputStreamWriter(bos, "UTF-8");
    Template t = ve.getTemplate(templateName);

    t.merge(vc, w);
    w.close();

    return bos.toString();
  }
  @Override
  @SuppressWarnings({"unchecked", "rawtypes"})
  public void render() {
    response.setContentType(CONTENT_TYPE);

    Enumeration<String> attrs = request.getAttributeNames();
    Map root = new HashMap();
    while (attrs.hasMoreElements()) {
      String attrName = attrs.nextElement();
      root.put(attrName, request.getAttribute(attrName));
    }

    Writer writer = null;
    try {
      writer = response.getWriter();
      Template template = getConfiguration().getTemplate(view);
      template.process(root, writer); // Merge the data-model and the template
    } catch (Exception e) {
      throw new RenderException(e);
    } finally {
      try {
        if (writer != null) {
          writer.close();
        }
      } catch (IOException e) {
        Throwables.propagate(e);
      }
    }
  }
示例#20
0
  /**
   * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is
   * added.
   *
   * <p>Warning: This method assumes that the data structure is acyclical.
   *
   * @return The writer.
   * @throws JSONException
   */
  public Writer write(Writer writer) throws JSONException {
    try {
      boolean b = false;
      int len = length();

      writer.write('[');

      for (int i = 0; i < len; i += 1) {
        if (b) {
          writer.write(',');
        }
        Object v = this.myArrayList.get(i);
        if (v instanceof JSONObject) {
          ((JSONObject) v).write(writer);
        } else if (v instanceof JSONArray) {
          ((JSONArray) v).write(writer);
        } else {
          writer.write(JSONObject.valueToString(v));
        }
        b = true;
      }
      writer.write(']');
      return writer;
    } catch (IOException e) {
      throw new JSONException(e);
    }
  }
示例#21
0
  /**
   * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is
   * added.
   *
   * <p>Warning: This method assumes that the data structure is acyclical.
   *
   * @param writer Writer
   * @param indentFactor The number of spaces to add to each level of indentation.
   * @param indent The indention of the top level.
   * @return The writer.
   * @throws JSONException Error
   */
  Writer write(Writer writer, int indentFactor, int indent) throws JSONException {
    try {
      boolean commanate = false;
      int length = this.length();
      writer.write('[');

      if (length == 1) {
        JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent);
      } else if (length != 0) {
        final int newindent = indent + indentFactor;

        for (int i = 0; i < length; i += 1) {
          if (commanate) {
            writer.write(',');
          }
          if (indentFactor > 0) {
            writer.write('\n');
          }
          JSONObject.indent(writer, newindent);
          JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent);
          commanate = true;
        }
        if (indentFactor > 0) {
          writer.write('\n');
        }
        JSONObject.indent(writer, indent);
      }
      writer.write(']');
      return writer;
    } catch (IOException e) {
      throw new JSONException(e);
    }
  }
示例#22
0
 /** Saves the file back to disk. */
 private void saveFile() {
   File file = getTargetFile().getFile();
   Writer writer = null;
   Cursor originalcursor = this.getOwner().getCursor();
   this.getOwner().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
   try {
     CharsetEncoder encoder = getCharset().newEncoder();
     if (encoder.canEncode(textArea.getText())) {
       writer = new OutputStreamWriter(new FileOutputStream(file), getCharset());
       textArea.write(writer);
       messageBox.clear();
     } else {
       findIllegalCharacter(encoder);
     }
   } catch (FileNotFoundException fnfx) {
     // happens also if file is RO
     logger.error("FileNotFoundException saving to " + file.getPath() + ": " + fnfx.getMessage());
     messageBox.error(getLocalizer().localize("message.file-removed"));
   } catch (IOException iox) {
     logger.error("IOException saving file " + file.getPath() + ": " + iox.getMessage());
     messageBox.error(
         getLocalizer()
             .localize("message.file-processing-error", new Object[] {iox.getMessage()}));
   } finally {
     this.getOwner().setCursor(originalcursor);
     if (writer != null)
       try {
         writer.close();
       } catch (IOException iox) {
         logger.warn("IOException closing stream: " + iox.getMessage());
       }
   }
 }
示例#23
0
  @Override
  public void uncaughtException(Thread thread, Throwable ex) {

    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);

    // Inject some info about android version and the device, since google can't provide them in the
    // developer console
    StackTraceElement[] trace = ex.getStackTrace();
    StackTraceElement[] trace2 = new StackTraceElement[trace.length + 3];
    System.arraycopy(trace, 0, trace2, 0, trace.length);
    trace2[trace.length + 0] =
        new StackTraceElement("Android", "MODEL", android.os.Build.MODEL, -1);
    trace2[trace.length + 1] =
        new StackTraceElement("Android", "VERSION", android.os.Build.VERSION.RELEASE, -1);
    trace2[trace.length + 2] =
        new StackTraceElement("Android", "FINGERPRINT", android.os.Build.FINGERPRINT, -1);
    ex.setStackTrace(trace2);

    ex.printStackTrace(printWriter);
    String stacktrace = result.toString();
    printWriter.close();
    Log.e(TAG, stacktrace);

    // Save the log on SD card if available
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      String sdcardPath = Environment.getExternalStorageDirectory().getPath();
      writeLog(stacktrace, sdcardPath + "/vlc_crash");
      writeLogcat(sdcardPath + "/vlc_logcat");
    }

    defaultUEH.uncaughtException(thread, ex);
  }
示例#24
0
  /**
   * The entry point to start the program.
   *
   * @param args parameters
   */
  public static void main(String[] args) {
    NameGenerator generator = new NameGenerator();

    // Load the source file
    String[] sourceArray = generator.loadFile("source");
    try (Writer writer =
        new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream("generated.txt"), "utf-8"))) {

      // Randomly generate 100 names (including first name and last name)
      for (int i = 0; i < 100; i++) {
        // To generate two random number without duplication
        Random random = new Random();
        int first = random.nextInt(110) + 1;
        int second = -1;
        while (second == -1 || first == second) {
          second = random.nextInt(110) + 1;
        }

        // Write the name to the target file
        writer.write(sourceArray[first - 1] + " " + sourceArray[second - 1] + "\n");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
    public int handle(ProcessingContext processingContext) {
      StreamSource source;
      StreamTarget target;

      source = (StreamSource) processingContext.getRequestContext();
      target = (StreamTarget) processingContext.getResponseContext();

      try {
        Reader reader;
        Writer writer;
        char[] buffer;
        int length;

        reader = source.getReader();
        writer = target.getWriter();

        buffer = new char[256];
        while ((length = reader.read(buffer, 0, 256)) != -1) {
          writer.write(buffer, 0, length);
        }
        return Dispatcher.OK;
      } catch (IOException e) {
      }

      return Dispatcher.ERROR;
    }
  /**
   * Prepare a matching rule configuration file in the specified job folder based on whether the run
   * is Deduplication or Linkage.
   *
   * @param isDeduplication true when deduplicating records in a single data set.
   * @param jobDir
   * @return
   * @throws IOException
   */
  File prepareMatchingRuleConfiguration(boolean isDeduplication, File jobDir) throws IOException {
    final String templateFileStr =
        isDeduplication ? getDeduplicationTemplate() : getLinkageTemplate();
    if (templateFileStr == null) {
      throw new IllegalStateException(
          "No Template File set for " + (isDeduplication ? "deduplication" : "linkage") + " mode");
    }

    final Template matchConfigTemplate = loadTemplate(templateFileStr);
    if (matchConfigTemplate == null) {
      final String msg = "Unable to load matching rule configuration template: " + templateFileStr;
      LOG.error(msg);
      throw new IllegalStateException(msg);
    }

    final File configFile = new File(jobDir, "config.xml");

    // Generate the configuration file that specifies matching rules and
    // data sources
    final Map<String, String> templateParams = new HashMap<String, String>();
    templateParams.put("jobDir", jobDir.getAbsolutePath());
    final Writer configWriter = new FileWriter(configFile);
    try {
      // Apply parameters to template and write result to file
      matchConfigTemplate.execute(templateParams, configWriter);
      configWriter.flush();
    } finally {
      try {
        configWriter.close();
      } catch (IOException e) {
        // ignore
      }
    }
    return configFile;
  }
  public void writeNN(String source, String target, boolean flag) {
    this.loadCorpus(source, target);
    try {
      Writer bw =
          new BufferedWriter(new OutputStreamWriter(new FileOutputStream(source + ".nn"), "UTF-8"));

      Writer bw1 =
          new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target + ".nn"), "UTF-8"));
      if (flag)
        for (int i = 0; i < nelist.size(); i++) {
          String ne[] = nelist.get(i).split("\t");

          bw.write(this.formatStringCausal(ne[0]) + "\n");
          bw1.write(this.formatStringCausal(ne[1]) + "\n");
          bw.flush();
          bw1.flush();
        }
      else
        for (int i = 0; i < nelist.size(); i++) {
          String ne[] = nelist.get(i).split("\t");

          bw.write(ne[0] + "\n");
          bw1.write(ne[1] + "\n");
          bw.flush();
          bw1.flush();
        }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  @Override
  public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
    Map<TypeElement, BindingClass> targetClassMap = findAndParseTargets(env);

    for (Map.Entry<TypeElement, BindingClass> entry : targetClassMap.entrySet()) {
      TypeElement typeElement = entry.getKey();
      BindingClass bindingClass = entry.getValue();

      try {
        JavaFileObject jfo = filer.createSourceFile(bindingClass.getFqcn(), typeElement);
        Writer writer = jfo.openWriter();
        writer.write(bindingClass.brewJava());
        writer.flush();
        writer.close();
      } catch (IOException e) {
        error(
            typeElement,
            "Unable to write view binder for type %s: %s",
            typeElement,
            e.getMessage());
      }
    }

    return true;
  }
示例#29
0
  protected void drawHtmlPostSubsButtons(Writer out) throws IOException {
    Messages msgs = MessagesManager.getMessages();

    out.write(
        "<div class=\""
            + CssConstants.CSSCLASS_TABSETSAVEBAR
            + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$

    Button save = new Button();
    String saveOnclick = this.getConfigValue("saveOnclick", "mgnlDialogFormSubmit();");
    String saveLabel = this.getConfigValue("saveLabel", msgs.get("buttons.save"));
    if (StringUtils.isNotEmpty(saveOnclick) && StringUtils.isNotEmpty("saveLabel")) {
      save.setOnclick(saveOnclick); // $NON-NLS-1$ //$NON-NLS-2$
      save.setLabel(saveLabel); // $NON-NLS-1$ //$NON-NLS-2$
      out.write(save.getHtml());
    }
    Button cancel = new Button();
    cancel.setOnclick(
        this.getConfigValue("cancelOnclick", "window.close();")); // $NON-NLS-1$ //$NON-NLS-2$
    cancel.setLabel(
        this.getConfigValue(
            "cancelLabel", msgs.get("buttons.cancel"))); // $NON-NLS-1$ //$NON-NLS-2$
    out.write(cancel.getHtml());

    out.write("</div>\n"); // $NON-NLS-1$
  }
示例#30
0
  private String runJob() throws Exception {
    OutputStream os = getFileSystem().create(new Path(getInputDir(), "text.txt"));
    Writer wr = new OutputStreamWriter(os);
    wr.write("hello1\n");
    wr.write("hello2\n");
    wr.write("hello3\n");
    wr.close();

    JobConf conf = createJobConf();
    conf.setJobName("mr");
    conf.setJobPriority(JobPriority.HIGH);

    conf.setInputFormat(TextInputFormat.class);

    conf.setMapOutputKeyClass(LongWritable.class);
    conf.setMapOutputValueClass(Text.class);

    conf.setOutputFormat(TextOutputFormat.class);
    conf.setOutputKeyClass(LongWritable.class);
    conf.setOutputValueClass(Text.class);

    conf.setMapperClass(org.apache.hadoop.mapred.lib.IdentityMapper.class);
    conf.setReducerClass(org.apache.hadoop.mapred.lib.IdentityReducer.class);

    FileInputFormat.setInputPaths(conf, getInputDir());
    FileOutputFormat.setOutputPath(conf, getOutputDir());

    return JobClient.runJob(conf).getID().toString();
  }