private void updateAddRemoveDataGetterStatements(
     OntModel displayModel,
     Model removeStatements,
     Model addStatements,
     Resource oldType,
     Resource newType) {
   log.debug("Old type: " + oldType.getURI() + " - newType: " + newType.getURI());
   removeStatements.add(displayModel.listStatements(null, RDF.type, oldType));
   StmtIterator oldStatements = displayModel.listStatements(null, RDF.type, oldType);
   while (oldStatements.hasNext()) {
     Statement stmt = oldStatements.nextStatement();
     addStatements.add(stmt.getSubject(), RDF.type, newType);
   }
   // Print out remove and add statements here
   StringWriter sw = new StringWriter();
   try {
     log.debug(
         "Adding statements with old data getter types to remove statements, remove statements is now");
     removeStatements.write(sw, "N3");
     log.debug(sw.toString());
     sw.close();
     sw = new StringWriter();
     log.debug(
         "Adding statements with new data getter types to add statements, add statements is now");
     addStatements.write(sw, "N3");
     log.debug(sw.toString());
     sw.close();
   } catch (Exception ex) {
     log.error("Error occurred in writing out remove and statements for data getter types", ex);
   }
 }
    private boolean safeEquals(final ClasspathItemWrapper a, final ClasspathItemWrapper b) {
      try {
        final StringWriter as = new StringWriter();
        final StringWriter bs = new StringWriter();

        final BufferedWriter bas = new BufferedWriter(as);
        final BufferedWriter bbs = new BufferedWriter(bs);

        weaken(a).write(bas);
        weaken(b).write(bbs);

        bas.flush();
        bbs.flush();

        as.close();
        bs.close();

        final String x = as.getBuffer().toString();
        final String y = bs.getBuffer().toString();

        return x.equals(y);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  /**
   * 格式化xml
   *
   * @param xml
   * @return
   */
  public static String formatXML(String xml) {

    SAXReader reader = null;
    XMLWriter writer = null;
    StringWriter stringWriter = null;
    try {
      reader = new SAXReader();
      org.dom4j.Document document = reader.read(new StringReader(xml));
      if (document != null) {
        stringWriter = new StringWriter();
        OutputFormat format = new OutputFormat("    ", false);
        format.setSuppressDeclaration(true);
        writer = new XMLWriter(stringWriter, format);
        writer.write(document);
        writer.flush();
      }
      return stringWriter.getBuffer().toString();
    } catch (Exception e) {
      LOG.error("格式化xml失败", e);
    } finally {
      try {
        writer.close();
        stringWriter.close();
      } catch (Exception e) {
        // ignore
      }
    }
    return xml;
  }
Beispiel #4
0
  /**
   * Serializes an object into an XML blob.
   *
   * @param object The object to serialize
   * @return The serialized XML blob, never null
   * @throws XmlParseException If the resource can not be parsed
   */
  public String marshal(final Object object) {
    final StringWriter writer = new StringWriter();

    try {
      final Marshaller marshaller = jaxb.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FRAGMENT, fragment);
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, prettyPrint);
      marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

      marshaller.marshal(object, writer);
    } catch (final JAXBException e) {
      throw new XmlParseException(e);
    }

    try {
      writer.flush();
      writer.close();
    } catch (final IOException e) {
      throw new XmlParseException(e);
    }

    final String xml = writer.toString();
    if (validated) {
      try {
        final String xsd = generateSchema();
        validate(xml, xsd);
      } catch (final IOException | SAXException e) {
        throw new XmlParseException(e);
      }
    }

    return xml;
  }
Beispiel #5
0
  /** Updates Job by its XML definition. */
  public void updateByXml(Source source) throws IOException {
    checkPermission(CONFIGURE);
    StringWriter out = new StringWriter();
    try {
      // this allows us to use UTF-8 for storing data,
      // plus it checks any well-formedness issue in the submitted
      // data
      Transformer t = TransformerFactory.newInstance().newTransformer();
      t.transform(source, new StreamResult(out));
      out.close();
    } catch (TransformerException e) {
      throw new IOException("Failed to persist configuration.xml", e);
    }

    // try to reflect the changes by reloading
    InputStream in =
        new BufferedInputStream(new ByteArrayInputStream(out.toString().getBytes("UTF-8")));
    try {
      // Do not allow overwriting view name as it might collide with another
      // view in same ViewGroup and might not satisfy Jenkins.checkGoodName.
      String oldname = name;
      Jenkins.XSTREAM.unmarshal(new XppDriver().createReader(in), this);
      name = oldname;
    } catch (StreamException e) {
      throw new IOException("Unable to read", e);
    } catch (ConversionException e) {
      throw new IOException("Unable to read", e);
    } catch (Error e) { // mostly reflection errors
      throw new IOException("Unable to read", e);
    } finally {
      in.close();
    }
    save();
  }
  /**
   * Executes the specified query against the specified service, properly handling remote
   * exceptions.
   *
   * @param cqlQuery The CQL 2 query to execute
   * @param targetServiceURL The target service URL to query
   * @param cred The credentials to use to invoke the data service
   * @param preferTransfer If set to <code>true</code>, the service will be invoked using caGrid
   *     Transfer to retrieve results, if possible
   * @return The results of querying a the data service
   * @throws RemoteDataServiceException
   */
  public static CQLQueryResults queryDataService(
      CQLQuery cqlQuery, String targetServiceURL, GlobusCredential cred)
      throws RemoteDataServiceException {

    // debug
    if (LOG.isDebugEnabled()) {
      try {
        StringWriter s = new StringWriter();
        SerializationUtils.serializeCQL2Query(cqlQuery, s);
        LOG.debug("Sending query to service (" + targetServiceURL + "):\n" + s.toString());
        s.close();
      } catch (Exception e) {
        LOG.error("Problem in debug printout of CQL 2 query: " + e.getMessage(), e);
      }
    }

    // determine feature support
    boolean supportsCql2 = true;
    try {
      supportsCql2 = serviceSupportsCql2(targetServiceURL);
    } catch (Exception ex) {
      throw new RemoteDataServiceException(
          "Error determining support for CQL 2: " + ex.getMessage(), ex);
    }

    // query
    CQLQueryResults cqlResults = null;
    if (supportsCql2) {
      cqlResults = queryStandard(cqlQuery, targetServiceURL, cred);
    } else {
      cqlResults = queryStandardCql1(cqlQuery, targetServiceURL, cred);
    }
    return cqlResults;
  }
 private static CQLQueryResults queryStandardCql1(
     CQLQuery query, String targetServiceURL, GlobusCredential cred)
     throws RemoteDataServiceException {
   LOG.debug("Querying " + targetServiceURL + " with deprecated CQL 1 query mechanism");
   DataServiceClient client = null;
   try {
     client = new DataServiceClient(targetServiceURL, cred);
   } catch (MalformedURIException ex) {
     throw new RemoteDataServiceException("Invalid target service URL:" + targetServiceURL, ex);
   } catch (RemoteException ex) {
     String message = "Problem creating client for " + targetServiceURL + ": " + ex.getMessage();
     LOG.error(message, ex);
     throw new RemoteDataServiceException(message, ex);
   }
   // if we have been supplied a credential, make sure we always use it
   if (cred != null) {
     client.setAnonymousPrefered(false);
   }
   LOG.debug("Converting CQL 2 to CQL 1 for " + targetServiceURL);
   gov.nih.nci.cagrid.cqlquery.CQLQuery cql1Query = null;
   try {
     cql1Query = CQL2toCQL1Converter.convertToCql1Query(query);
   } catch (QueryConversionException ex) {
     throw new RemoteDataServiceException(
         "Error converting query to CQL 1 for " + targetServiceURL + ": " + ex.getMessage(), ex);
   }
   CQLQueryResults results = null;
   try {
     if (LOG.isDebugEnabled()) {
       try {
         StringWriter s = new StringWriter();
         SerializationUtils.serializeCQLQuery(cql1Query, s);
         LOG.debug(
             "Sending converted CQL 1 query to service ("
                 + targetServiceURL
                 + "):\n"
                 + s.toString());
         s.close();
       } catch (Exception e) {
         LOG.error("Problem in debug printout of CQL query: " + e.getMessage(), e);
       }
     }
     gov.nih.nci.cagrid.cqlresultset.CQLQueryResults cql1Results = client.query(cql1Query);
     results = CQL1ResultsToCQL2ResultsConverter.convertResults(cql1Results);
   } catch (RemoteException e) {
     String message =
         "Problem querying remote service " + targetServiceURL + ": " + e.getMessage();
     LOG.error(message, e);
     throw new RemoteDataServiceException(message, e);
   } catch (ResultsConversionException e) {
     String message =
         "Problem converting results from remote service "
             + targetServiceURL
             + ": "
             + e.getMessage();
     LOG.error(message, e);
     throw new RemoteDataServiceException(message, e);
   }
   return results;
 }
Beispiel #8
0
 /**
  * Method toMyString:
  *
  * @param verboseflag sets whether we want to list the results info inside the XML or not at all.
  * @return the XML String representing this requested Query Definition XML fields
  */
 public String toMyString(boolean verboseflag) {
   StringWriter outStringWriter = new StringWriter();
   WstxOutputFactory fout = new WstxOutputFactory();
   fout.configureForXmlConformance();
   SMOutputDocument doc = null;
   try {
     // output
     XMLStreamWriter2 sw = (XMLStreamWriter2) fout.createXMLStreamWriter(outStringWriter);
     doc = SMOutputFactory.createOutputDocument(sw, "1.0", "UTF-8", true);
     doc.setIndentation("\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", 2, 1);
     createInfoInDocument(doc, null, verboseflag);
     doc.closeRoot();
   } catch (Exception e) {
     e.printStackTrace();
     return "Errors encountered while attempting to print this Query Definition!";
   }
   String retString = "";
   try {
     retString = outStringWriter.toString();
     outStringWriter.close();
   } catch (Exception e) {
     logger.error("Errors encountered while attempting to print this XML document!");
     e.printStackTrace();
   }
   return retString;
   //           StructuredTextDocument document = (StructuredTextDocument)
   // StructuredDocumentFactory.newStructuredDocument(new MimeMediaType("text/xml"),
   // IndexOfQueries.getQueryDefTag());
 }
  /* (non-Javadoc)
   * @see com.welocally.geodb.services.util.JsonStoreLoader#loadSingle(org.json.JSONObject, int, int, java.io.StringWriter)
   */
  public void loadSingle(
      JSONObject deal, Integer count, Integer commitEvery, StringWriter sw, String endpoint)
      throws JSONException, IOException {
    logger.debug("adding document:" + deal.getString("_id"));

    URL solrUrl = new URL(endpoint);

    JSONObject doc = welocallyJSONUtils.makeIndexableDeal(deal);
    JSONObject solrCommand = new JSONObject("{\"add\": {\"doc\":" + doc.toString() + "}}");

    ByteArrayInputStream bais = new ByteArrayInputStream(solrCommand.toString().getBytes());
    BufferedReader newReader = new BufferedReader(new InputStreamReader(bais));

    postData(newReader, sw, solrUrl);

    // commit only every x docs
    if (count % commitEvery == 0) {
      logger.debug("commit");
      commit(sw, solrUrl);
      sw.flush();
      sw.close();
      sw = new StringWriter();
    }

    loadMonitor.increment();
  }
Beispiel #10
0
 // https://github.com/robert-bor/CSVeed/issues/46
 @Test
 public void bug46ReportedByJnash67() throws IOException {
   StringWriter writer = new StringWriter();
   List<BeanWithMultipleStrings> beans = new ArrayList<BeanWithMultipleStrings>();
   beans.add(createBean("row 1, cell 3", "row 1, cell 2", "row 1, cell 1"));
   beans.add(createBean("row 2, cell 3", "row 2, cell 2", "row 2, cell 1"));
   beans.add(createBean("row 3, cell 3", "row 3, cell 2", "row 3, cell 1"));
   BeanInstructions bi = new BeanInstructionsImpl(BeanWithMultipleStrings.class);
   bi.logSettings();
   bi.mapColumnNameToProperty("Aap", "gamma");
   bi.mapColumnNameToProperty("Noot", "beta");
   bi.mapColumnNameToProperty("Mies", "alpha");
   BeanWriter<BeanWithMultipleStrings> beanWriter =
       new BeanWriterImpl<BeanWithMultipleStrings>(writer, bi);
   //                new BeanWriterImpl<BeanWithMultipleStrings>(writer,
   // BeanWithMultipleStrings.class);
   beanWriter.writeBeans(beans);
   writer.close();
   assertEquals(
       "\"Aap\";\"Noot\";\"Mies\"\r\n"
           + "\"row 1, cell 1\";\"row 1, cell 2\";\"row 1, cell 3\"\r\n"
           + "\"row 2, cell 1\";\"row 2, cell 2\";\"row 2, cell 3\"\r\n"
           + "\"row 3, cell 1\";\"row 3, cell 2\";\"row 3, cell 3\"\r\n",
       writer.getBuffer().toString());
 }
 /**
  * Method toString: no parameters
  *
  * @return the XML String representing this Style Numeric Case entry's XML fields
  */
 public String toString() {
   StringWriter outStringWriter = new StringWriter();
   WstxOutputFactory fout = new WstxOutputFactory();
   fout.configureForXmlConformance();
   SMOutputDocument doc = null;
   SMOutputElement outputRootEl = null;
   try {
     // output
     XMLStreamWriter2 sw = (XMLStreamWriter2) fout.createXMLStreamWriter(outStringWriter);
     doc = SMOutputFactory.createOutputDocument(sw, "1.0", "UTF-8", true);
     doc.setIndentation("\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", 2, 1);
     outputRootEl = doc.addElement(Model3dStylesEntry.getNumericCaseTag());
     createInfoInDocument(outputRootEl);
     doc.closeRoot();
   } catch (Exception e) {
     return "";
   }
   String retString = "";
   try {
     retString = outStringWriter.toString();
     outStringWriter.close();
   } catch (Exception e) {
     logger.error("Errors encountered while attempting to print this XML document!");
     e.printStackTrace();
   }
   return retString;
 }
Beispiel #12
0
  /**
   * Конвертирует XMLDOM древо в текстовое представление
   *
   * @param xmlDocument XMLDOM древо
   * @return Текстовое представление XMLDOM древа
   * @throws javax.xml.stream.XMLStreamException Если не смогло
   * @throws javax.xml.transform.TransformerConfigurationException Если не смогло
   * @throws javax.xml.transform.TransformerException Если не смогло
   * @throws java.io.IOException Если не смогло
   */
  public static String toStringWithException(Node xmlDocument)
      throws XMLStreamException, TransformerConfigurationException, TransformerException,
          IOException {
    if (xmlDocument == null) {
      throw new IllegalArgumentException("xmlDocument == null");
    }

    Transformer tr = TransformerFactory.newInstance().newTransformer();

    DOMSource domSrc = new DOMSource(xmlDocument);

    StringWriter sWiter = new StringWriter();
    XMLStreamWriter xml2format = new FormatXMLWriter(sWiter);

    StAXResult sResult = new StAXResult(xml2format);
    Result result = sResult;

    tr.transform(domSrc, result);

    //        sWiter.flush();
    xml2format.writeEndDocument();
    xml2format.flush();

    String toOutput = sWiter.toString();

    xml2format.close();
    sWiter.close();

    return toOutput;
  }
 public String printFormatData(DataItems data) {
   String ret = "";
   StringWriter sw = new StringWriter();
   BufferedWriter bw = new BufferedWriter(sw);
   int numRows = data.getLength();
   try {
     for (int row = 0; row < numRows; row++) {
       DataItem s = data.getElementAt(row);
       bw.write(s.toString());
       bw.write("\r\n");
     }
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     ret = sw.toString();
     if (bw != null)
       try {
         bw.close();
       } catch (Exception ee) {
       }
     if (sw != null)
       try {
         sw.close();
       } catch (Exception ee) {
       }
   }
   return ret;
 }
  public String getPageContent(String uri) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    HttpClient httpClient = httpClientBuilder.build();
    HttpUriRequest httpReq = new HttpGet(uri);
    HttpResponse httpResp = null;
    HttpEntity httpEntity = null;
    try {
      httpResp = httpClient.execute(httpReq);
      httpEntity = httpResp.getEntity();
      if (httpEntity != null) {
        InputStream is = httpEntity.getContent();
        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer, "UTF-8");
        writer.close();
        is.close();
        return writer.toString();
      }
    } catch (IOException e) {
      logger.error("获取网页内容时,发生异常,具体为:{}", e);
      return StringUtils.EMPTY;
    } finally {
      httpReq.abort();
      try {
        EntityUtils.consume(httpEntity);
      } catch (Exception e2) {

      }
    }
    return StringUtils.EMPTY;
  }
Beispiel #15
0
 @JRubyMethod(
     name = {"export", "to_pem", "to_s"},
     rest = true)
 public IRubyObject export(IRubyObject[] args) {
   StringWriter w = new StringWriter();
   org.jruby.runtime.Arity.checkArgumentCount(getRuntime(), args, 0, 2);
   CipherSpec ciph = null;
   char[] passwd = null;
   if (args.length > 0 && !args[0].isNil()) {
     org.jruby.ext.openssl.Cipher c = (org.jruby.ext.openssl.Cipher) args[0];
     ciph = new CipherSpec(c.getCipher(), c.getName(), c.getKeyLen() * 8);
     if (args.length > 1 && !args[1].isNil()) {
       passwd = args[1].toString().toCharArray();
     }
   }
   try {
     if (privKey != null) {
       PEMInputOutput.writeDSAPrivateKey(w, privKey, ciph, passwd);
     } else {
       PEMInputOutput.writeDSAPublicKey(w, pubKey);
     }
     w.close();
     return getRuntime().newString(w.toString());
   } catch (NoClassDefFoundError ncdfe) {
     throw newDSAError(getRuntime(), OpenSSLReal.bcExceptionMessage(ncdfe));
   } catch (IOException ioe) {
     throw newDSAError(getRuntime(), ioe.getMessage());
   }
 }
  private static String csr() {
    try {
      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
      keyGen.initialize(2048);
      KeyPair keyPair = keyGen.generateKeyPair();
      X500Principal subject =
          new X500Principal(
              "CN = edea87b4-034d-48dc-94dd-e7cdcfdde370/10562468, OU = fgdfgretertgdfg, O = VW, L = US");
      ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate());
      PKCS10CertificationRequestBuilder builder =
          new JcaPKCS10CertificationRequestBuilder(subject, keyPair.getPublic());
      PKCS10CertificationRequest csr = builder.build(signer);

      String type = "CERTIFICATE REQUEST";
      PemObject pem = new PemObject(type, csr.getEncoded());
      StringWriter str = new StringWriter();
      PEMWriter pemWriter = new PEMWriter(str);
      pemWriter.writeObject(pem);
      pemWriter.close();
      str.close();
      Log.d("Test", "" + str);
      return Base64Util.getStringAsBase64(str.toString());
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (OperatorCreationException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "";
  }
Beispiel #17
0
    @Override
    public void uncaughtException(Thread t, Throwable thrw) {
      // log warning for the exception
      StringWriter s = new StringWriter();
      s.write("Uncaught exception in thread " + t.getName() + ":\n");
      PrintWriter w = new PrintWriter(s);
      thrw.printStackTrace(w);
      log.warn(s.toString());
      try {
        s.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      // resume work
      Thread th = new Thread(this, "Rxthread " + this.id);
      th.setDaemon(true);
      th.setUncaughtExceptionHandler(this);

      synchronized (currentTrainingRun.threads) {
        log.warn("Resuming thread " + t.getName() + " with " + th.getName());
        currentTrainingRun.threads.add(th); // don't want to join before thread has been started
        th.start();
      }
    }
  /**
   * Test how the system handles save of Inf and NaN
   *
   * @throws Exception
   */
  public void testOctaveSaveNanInf() throws Exception {
    final StringWriter stderr = new StringWriter();
    final OctaveEngine octave = new OctaveEngineFactory().getScriptEngine();
    octave.setErrorWriter(stderr);

    octave.eval("ok=1;");
    final OctaveDouble okOne = Octave.scalar(1);
    OctaveDouble ok;

    octave.eval("xnan=[NaN 0];");
    ok = octave.get(OctaveDouble.class, "ok");
    assertEquals(okOne, ok);
    final OctaveDouble xnan = octave.get(OctaveDouble.class, "xnan");
    assertEquals(Double.NaN, xnan.get(1, 1));
    assertEquals(Double.valueOf(0), xnan.get(1, 2));
    ok = octave.get(OctaveDouble.class, "ok");
    assertEquals(okOne, ok);

    octave.eval("xinf=[Inf -Inf];");
    ok = octave.get(OctaveDouble.class, "ok");
    assertEquals(okOne, ok);
    final OctaveDouble xinf = octave.get(OctaveDouble.class, "xinf");
    assertEquals(Double.POSITIVE_INFINITY, xinf.get(1, 1));
    assertEquals(Double.NEGATIVE_INFINITY, xinf.get(1, 2));
    ok = octave.get(OctaveDouble.class, "ok");
    assertEquals(okOne, ok);

    octave.close();
    stderr.close();
    assertEquals("", stderr.toString()); // No warning when saving matrix with NaN/Inf
  }
Beispiel #19
0
  public boolean executeFilter(@NotNull Editor editor, @NotNull TextRange range, String command)
      throws IOException {
    if (logger.isDebugEnabled()) logger.debug("command=" + command);
    CharSequence chars = editor.getDocument().getCharsSequence();
    StringReader car =
        new StringReader(
            chars.subSequence(range.getStartOffset(), range.getEndOffset()).toString());
    StringWriter sw = new StringWriter();

    logger.debug("about to create filter");
    Process filter = Runtime.getRuntime().exec(command);
    logger.debug("filter created");
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(filter.getOutputStream()));
    logger.debug("sending text");
    copy(car, writer);
    writer.close();
    logger.debug("sent");

    BufferedReader reader = new BufferedReader(new InputStreamReader(filter.getInputStream()));
    logger.debug("getting result");
    copy(reader, sw);
    sw.close();
    logger.debug("received");

    editor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), sw.toString());

    lastCommand = command;

    return true;
  }
Beispiel #20
0
  @SuppressWarnings("unused")
  private String unzipBody(InputStream str) {
    InputStreamReader sr = null;
    StringWriter writer = null;
    GZIPInputStream gis = null;
    try {
      char[] buffer = new char[10240];
      gis = new GZIPInputStream(str);
      sr = new InputStreamReader(gis, "UTF-8");
      writer = new StringWriter();

      for (int i = 0; (i = sr.read(buffer)) > 0; ) {
        writer.write(buffer, 0, i);
      }

      return writer.toString();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
        if (writer != null) writer.close();
        if (sr != null) sr.close();
        if (gis != null) gis.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return null;
  }
  @RequestMapping(value = "/validate", method = RequestMethod.POST)
  public void file(File file, BindingResult resultx, HttpServletRequest request, Model model) {

    // Instantiate CWRC XML validator
    CwrcXmlValidator validator = new CwrcXmlValidator();

    // Instantiate a Validator object
    // CwrcValidator validator = CwrcValidatorFactory.NewValidator("CwrcJavaXmlValidator");

    // Do the validation and obtain results.
    Document report =
        validator.ValidateDocContent(file.getSch(), file.getContent(), file.getType());

    // Exporting the validation-result DOM object into a string.
    String xml;
    try {
      TransformerFactory factory = TransformerFactory.newInstance();
      Transformer transformer = factory.newTransformer();

      StringWriter writer = new StringWriter();
      StreamResult result = new StreamResult(writer);
      Source source = new DOMSource(report.getDocumentElement());
      transformer.transform(source, result);
      writer.close();
      xml = writer.toString();
    } catch (Exception e) {
      xml =
          "<validation-result><status>fail</status><error><message>"
              + e.getMessage()
              + "</message></error></validation-result>";
    }

    // Export results for printing
    model.addAttribute("result", xml);
  }
Beispiel #22
0
 /**
  * Reads a string from a reader.
  *
  * @param reader the reader to be read.
  * @return a string read from the specified reader.
  * @throws IOException if there is IO error occurred during the operation.
  */
 public static String readString(Reader reader) throws IOException {
   StringWriter writer = new StringWriter();
   pipe(reader, writer);
   String s = writer.toString();
   writer.close();
   return s;
 }
 /** @tests java.io.PrintWriter#append(CharSequence, int, int) */
 public void test_appendCharSequenceIntInt() throws IOException {
   String testString = "My Test String";
   StringWriter stringWriter = new StringWriter(20);
   stringWriter.append(testString, 1, 3);
   assertEquals(testString.substring(1, 3), stringWriter.toString());
   stringWriter.close();
 }
Beispiel #24
0
  public String func_71498_d() {
    StringWriter var1 = null;
    PrintWriter var2 = null;
    String var3 = this.field_71511_b.toString();

    try {
      var1 = new StringWriter();
      var2 = new PrintWriter(var1);
      this.field_71511_b.printStackTrace(var2);
      var3 = var1.toString();
    } finally {
      try {
        if (var1 != null) {
          var1.close();
        }

        if (var2 != null) {
          var2.close();
        }
      } catch (IOException var10) {;
      }
    }

    return var3;
  }
 /** @tests java.io.StringWriter#append(char) */
 public void test_appendChar() throws IOException {
   char testChar = ' ';
   StringWriter stringWriter = new StringWriter(20);
   stringWriter.append(testChar);
   assertEquals(String.valueOf(testChar), stringWriter.toString());
   stringWriter.close();
 }
 @Override
 public void close() throws IOException {
   parser.close();
   reader.close();
   writer.close();
   stack.clear();
 }
  // replace
  private void replaceTboxAndDisplayMetadata(
      OntModel displayModel, Model addStatements, Model removeStatements, UpdateSettings settings) {

    OntModel oldDisplayModelTboxModel = settings.getOldDisplayModelTboxModel();
    OntModel oldDisplayModelDisplayMetadataModel =
        settings.getOldDisplayModelDisplayMetadataModel();
    OntModel newDisplayModelTboxModel = settings.getNewDisplayModelTboxModel();
    OntModel newDisplayModelDisplayMetadataModel =
        settings.getNewDisplayModelDisplayMetadataModel();
    OntModel loadedAtStartup = settings.getLoadedAtStartupDisplayModel();
    OntModel oldVivoListView = settings.getVivoListViewConfigDisplayModel();
    // Remove old display model tbox and display metadata statements from display model
    removeStatements.add(oldDisplayModelTboxModel);
    removeStatements.add(oldDisplayModelDisplayMetadataModel);
    // the old startup folder only contained by oldVivoListView
    removeStatements.add(oldVivoListView);
    StringWriter sw = new StringWriter();

    try {
      log.debug(
          "Adding old display tbox model, display metadata model, and oldVivoListView to remove statements.  Remove statements now include:");
      removeStatements.write(sw, "N3");
      log.debug(sw.toString());
      sw.close();
    } catch (Exception ex) {
      log.error("Exception occurred", ex);
    }
    // Add statements from new tbox and display metadata
    addStatements.add(newDisplayModelTboxModel);
    addStatements.add(newDisplayModelDisplayMetadataModel);
    // this should include the list view in addition to other files
    addStatements.add(loadedAtStartup);
    try {
      sw = new StringWriter();
      log.debug(
          "Adding new display tbox model, display metadata model, and loaded at startup to add statements.  Add statements now include:");
      addStatements.write(sw, "N3");
      log.debug(sw.toString());
      sw.close();
    } catch (Exception ex) {
      log.error(
          "Exception occurred in adding new display model tbox/metadata info to add statements ",
          ex);
    }
    log.debug(
        "Adding new display tbox model, display metadata model, and all models loaded at startup");
  }
 /** @tests java.io.StringWriter#close() */
 public void test_close() {
   // Test for method void java.io.StringWriter.close()
   try {
     sw.close();
   } catch (IOException e) {
     fail("IOException closing StringWriter : " + e.getMessage());
   }
 }
  /** @tests java.io.PrintWriter#append(CharSequence) */
  public void test_appendCharSequence() throws IOException {

    String testString = "My Test String";
    StringWriter stringWriter = new StringWriter(20);
    stringWriter.append(testString);
    assertEquals(String.valueOf(testString), stringWriter.toString());
    stringWriter.close();
  }
Beispiel #30
0
  /** {@inheritDoc} */
  @Override
  public void sendAccountActivationMail(User recipient) {
    VelocityContext veloContext = new VelocityContext();
    ResourceBundle mailBoundle =
        ResourceBundle.getBundle(MAIL_MESSAGES_TEMPLATES_PATH, recipient.getLanguage().getLocale());
    String appName = mailBoundle.getString("application_name");

    veloContext.put("application_name", appName);
    veloContext.put(
        "account_activation_subject",
        MessageFormat.format(mailBoundle.getString("account_activation.subject"), appName));
    veloContext.put("account_activation_img_path", applicationUrl + ACCOUNT_ACTIVATION_IMG_PATH);
    veloContext.put(
        "greeting",
        MessageFormat.format(mailBoundle.getString("greeting"), recipient.getUserName()));
    veloContext.put(
        "account_activation_content_part1",
        MessageFormat.format(
            mailBoundle.getString("account_activation.content.part1"), applicationUrl, appName));
    veloContext.put(
        "account_activation_content_part2",
        mailBoundle.getString("account_activation.content.part2"));
    veloContext.put(
        "account_activation_content_part3",
        MessageFormat.format(
            mailBoundle.getString("account_activation.content.part3"),
            applicationUrl + ACTIVATE_ACCOUNT_URL_PATTERN + "/" + recipient.getUuid()));
    veloContext.put(
        "account_activation_content_part4",
        mailBoundle.getString("account_activation.content.part4"));
    veloContext.put(
        "account_activation_content_part5",
        mailBoundle.getString("account_activation.content.part5"));
    veloContext.put("wish", MessageFormat.format(mailBoundle.getString("wish"), appName));

    Template veloTemp = velocityEngine.getTemplate(ACCOUNT_ACTIVATION_HTML_TEMPLATE_PATH, "UTF-8");
    StringWriter sw = new StringWriter();
    veloTemp.merge(veloContext, sw);
    logger.debug("account activation mail's body {}", sw.toString());
    try {
      mailSender.sendEmail(
          recipient.getEmail(),
          MessageFormat.format(mailBoundle.getString("account_activation.subject"), appName),
          sw.toString(),
          true);
    } catch (MailingException e) {
      logger.error("Failed to sent activation email message to user " + recipient.getUserName(), e);
    }

    if (sw != null) {
      try {
        sw.close();
      } catch (IOException e) {
        logger.warn("Some error occurred in I/O while StringWriter closing", e);
      }
    }
  }