@Test
  public void pullFileProjectUsingFileMapping() throws Exception {
    PullOptionsImpl opts = mockServerRule.getPullOpts();
    opts.setPullType("trans");
    File pullBaseDir = tempFolder.newFolder("file-pull-test");
    opts.setSrcDir(pullBaseDir);
    opts.setTransDir(pullBaseDir);
    log.debug("pull base dir is: {}", pullBaseDir);
    // we define our own rule
    opts.setFileMappingRules(
        Lists.newArrayList(
            new FileMappingRule("**/*.odt", "{extension}/{path}/{locale}/{filename}.{extension}"),
            new FileMappingRule(
                "**/*.ods", "{extension}/{locale_with_underscore}/{filename}.{extension}")));

    InputStream sourceFileStream = IOUtils.toInputStream("source content", Charsets.UTF_8);
    InputStream transFileStream = IOUtils.toInputStream("translation content", Charsets.UTF_8);
    ArrayList<ResourceMeta> remoteDocList =
        Lists.newArrayList(new ResourceMeta("test-ods.ods"), new ResourceMeta("test-odt.odt"));

    RawPullCommand pullCommand =
        mockServerRule.createRawPullCommand(remoteDocList, sourceFileStream, transFileStream);

    pullCommand.run();

    assertThat(new File(pullBaseDir, "odt/zh-CN/test-odt.odt").exists(), is(true));
    assertThat(new File(pullBaseDir, "ods/zh_CN/test-ods.ods").exists(), is(true));
  }
 @Override
 public Future<Void> pasteHtmlAtCaret(String html) {
   String escapedHtml = this.escape(html);
   try {
     File js = File.createTempFile("paste", ".js");
     FileUtils.write(
         js,
         "if(['input','textarea'].indexOf(document.activeElement.tagName.toLowerCase()) != -1) { document.activeElement.value = '");
     FileOutputStream outStream = new FileOutputStream(js, true);
     IOUtils.copy(IOUtils.toInputStream(escapedHtml), outStream);
     IOUtils.copy(
         IOUtils.toInputStream(
             "';} else { var t,n;if(window.getSelection){t=window.getSelection();if(t.getRangeAt&&t.rangeCount){n=t.getRangeAt(0);n.deleteContents();var r=document.createElement(\"div\");r.innerHTML='"),
         outStream);
     IOUtils.copy(IOUtils.toInputStream(escapedHtml), outStream);
     IOUtils.copy(
         IOUtils.toInputStream(
             "';var i=document.createDocumentFragment(),s,o;while(s=r.firstChild){o=i.appendChild(s)}n.insertNode(i);if(o){n=n.cloneRange();n.setStartAfter(o);n.collapse(true);t.removeAllRanges();t.addRange(n)}}}else if(document.selection&&document.selection.type!=\"Control\"){document.selection.createRange().pasteHTML('"),
         outStream);
     IOUtils.copy(IOUtils.toInputStream(escapedHtml + "')}}"), outStream);
     return this.injectJsFile(js);
   } catch (Exception e) {
     return new CompletedFuture<Void>(null, e);
   }
 }
  /* private support methods */
  private List<ArticleMetadata> setupContentForAU(
      ArchivalUnit au, String url, String content, boolean isHtmlExtractor)
      throws IOException, PluginException {
    FileMetadataExtractor me;

    InputStream input = null;
    CIProperties props = null;
    if (isHtmlExtractor) {
      input = IOUtils.toInputStream(content, "utf-8");
      props = getContentHtmlProperties();
      me =
          new BaseAtyponHtmlMetadataExtractorFactory()
              .createFileMetadataExtractor(MetadataTarget.Any(), "text/html");
    } else {
      input = IOUtils.toInputStream(content, "utf-8");
      props = getContentRisProperties();
      me =
          new BaseAtyponRisMetadataExtractorFactory()
              .createFileMetadataExtractor(MetadataTarget.Any(), "text/plain");
    }
    UrlData ud = new UrlData(input, props, url);
    UrlCacher uc = au.makeUrlCacher(ud);
    uc.storeContent();
    CachedUrl cu = uc.getCachedUrl();
    FileMetadataListExtractor mle = new FileMetadataListExtractor(me);
    return mle.extract(MetadataTarget.Any(), cu);
  }
  @Override
  public InputStream addEditLink(final InputStream content, final String title, final String href)
      throws Exception {

    final ByteArrayOutputStream copy = new ByteArrayOutputStream();
    IOUtils.copy(content, copy);
    IOUtils.closeQuietly(content);

    XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLEventWriter writer = getEventWriter(bos);

    final String editLinkElement =
        String.format("<link rel=\"edit\" title=\"%s\" href=\"%s\" />", title, href);

    try {
      // check edit link existence
      extractElement(
          reader,
          writer,
          Collections.<String>singletonList(Constants.get(ConstantKey.LINK)),
          Collections.<Map.Entry<String, String>>singletonList(
              new AbstractMap.SimpleEntry<String, String>("rel", "edit")),
          false,
          0,
          -1,
          -1);

      addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer);
      writer.add(reader);

    } catch (Exception e) {
      reader.close();
      reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

      bos = new ByteArrayOutputStream();
      writer = getEventWriter(bos);

      final XMLElement entryElement =
          extractElement(reader, writer, Collections.<String>singletonList("entry"), 0, 1, 1)
              .getValue();

      writer.add(entryElement.getStart());

      addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer);

      writer.add(entryElement.getContentReader());
      writer.add(entryElement.getEnd());

      writer.add(reader);

      writer.flush();
      writer.close();
    } finally {
      reader.close();
    }

    return new ByteArrayInputStream(bos.toByteArray());
  }
 @Test
 public void setContentDatastreamManagedTwice() throws Exception {
   addObjectWithDS1(true);
   store.setContent(EXISTING_PID, "DS1", "DS1.0", IOUtils.toInputStream("value1"));
   Assert.assertEquals("value1", IOUtils.toString(store.getContent(EXISTING_PID, "DS1", "DS1.0")));
   store.setContent(EXISTING_PID, "DS1", "DS1.0", IOUtils.toInputStream("value2"));
   Assert.assertEquals("value2", IOUtils.toString(store.getContent(EXISTING_PID, "DS1", "DS1.0")));
 }
 private void addObjectWithDS1andDS2(boolean withContent) {
   FedoraObject object =
       new FedoraObject()
           .pid(EXISTING_PID)
           .putDatastream(getManagedDatastreamWithOneVersion("DS1"))
           .putDatastream(getManagedDatastreamWithOneVersion("DS2"));
   store.addObject(object);
   if (withContent) {
     store.setContent(EXISTING_PID, "DS1", "DS1.0", IOUtils.toInputStream("foo"));
     store.setContent(EXISTING_PID, "DS2", "DS2.0", IOUtils.toInputStream("bar"));
   }
 }
 @Override
 public MessageValidationResult validate(TestContext testContext, MessageValidationCommand command)
     throws MessageValidationException {
   try {
     if (testContext instanceof HL7V2TestContext) {
       HL7V2TestContext v2TestContext = (HL7V2TestContext) testContext;
       String title = command.getName();
       String contextType = command.getContextType();
       String message = getMessageContent(command);
       String conformanceProfielId = v2TestContext.getConformanceProfile().getSourceId();
       String integrationProfileXml =
           v2TestContext.getConformanceProfile().getIntegrationProfile().getXml();
       String valueSets = v2TestContext.getVocabularyLibrary().getXml();
       String c1 = v2TestContext.getConstraints().getXml();
       String c2 =
           v2TestContext.getAddditionalConstraints() != null
               ? v2TestContext.getAddditionalConstraints().getXml()
               : null;
       InputStream c1Stream = c1 != null ? IOUtils.toInputStream(c1) : null;
       InputStream c2Stream = c2 != null ? IOUtils.toInputStream(c2) : null;
       List<InputStream> cStreams = new ArrayList<InputStream>();
       if (c1Stream != null) cStreams.add(c1Stream);
       if (c2Stream != null) cStreams.add(c2Stream);
       ConformanceContext c = getConformanceContext(cStreams);
       ValueSetLibrary vsLib =
           valueSets != null ? getValueSetLibrary(IOUtils.toInputStream(valueSets)) : null;
       ValidationProxy vp = new ValidationProxy(title, "NIST", "1.0");
       EnhancedReport report =
           vp.validate(
               message,
               integrationProfileXml,
               c,
               vsLib,
               conformanceProfielId,
               Context.valueOf(contextType));
       return new MessageValidationResult(
           report.to("json").toString(), report.render("iz-report", null));
     } else {
       throw new MessageValidationException(
           "Invalid Context Provided. Expected Context is HL7V2TestContext but found "
               + testContext.getClass().getSimpleName());
     }
   } catch (RuntimeException e) {
     throw new MessageValidationException(e);
   } catch (Exception e) {
     throw new MessageValidationException(e);
   }
 }
 @Test
 public void getContentLengthDatastreamExistsContentFoundTwice() throws Exception {
   addObjectWithDS1(true);
   store.setContent(EXISTING_PID, "DS1", "DS1.0", IOUtils.toInputStream("value"));
   Assert.assertEquals(5L, store.getContentLength(EXISTING_PID, "DS1", "DS1.0"));
   Assert.assertEquals(5L, store.getContentLength(EXISTING_PID, "DS1", "DS1.0"));
 }
  /** ******************************************************************************** */
  private void assertContentItem(String data, String mimeTypeRawData, String expectedFileSuffix)
      throws Exception {
    // Simulates what ContentFrameworkImpl would do
    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    ContentItem contentItem =
        new IncomingContentItem(uuid, IOUtils.toInputStream(data), mimeTypeRawData);
    CreateRequest createRequest = new CreateRequestImpl(contentItem, null);
    CreateResponse createResponse = provider.create(createRequest);
    ContentItem createdContentItem = createResponse.getCreatedContentItem();

    assertNotNull(createdContentItem);
    String id = createdContentItem.getId();
    assertNotNull(id);
    assertThat(id, equalTo(uuid));

    String contentUri = createdContentItem.getUri();
    LOGGER.debug("contentUri = {}", contentUri);
    assertNotNull(contentUri);
    String expectedContentUri = FileSystemProvider.CONTENT_URI_PREFIX + uuid;
    assertThat(contentUri, equalTo(expectedContentUri));

    File file = createdContentItem.getFile();
    assertNotNull(file);
    assertTrue(file.exists());
    assertTrue(createdContentItem.getSize() > 0);
    assertEquals(mimeTypeRawData, createdContentItem.getMimeTypeRawData());
    assertEquals(data, IOUtils.toString(createdContentItem.getInputStream()));
  }
Exemple #10
0
  /**
   * Send an XBMC notification via POST-HTTP. Errors will be logged, returned values just ignored.
   * Additional implementation to be able to show also images and to define a display time
   *
   * @param host the XBMC client to be notified
   * @param port the XBMC web server port
   * @param title the notification title
   * @param message the notification text
   * @param image A URL pointing to an image (only used if not null)
   * @param displayTime A display time for the message in milliseconds (between 1500 and 2147483647
   *     (inclusive))
   */
  @ActionDoc(
      text =
          "Send an XBMC notification via POST-HTTP. Errors will be logged, returned values just ignored. ")
  public static void sendXbmcNotification(
      @ParamDoc(name = "host") String host,
      @ParamDoc(name = "port") int port,
      @ParamDoc(name = "title") String title,
      @ParamDoc(name = "message") String message,
      @ParamDoc(name = "image") String image,
      @ParamDoc(name = "displayTime") long displayTime) {
    String url = "http://" + host + ":" + port + "/jsonrpc";

    StringBuilder content = new StringBuilder();
    content.append(
        "{\"id\":1,\"jsonrpc\":\"2.0\",\"method\":\"GUI.ShowNotification\",\"params\":{\"title\":\""
            + title
            + "\",\"message\":\""
            + message
            + "\"");
    if (StringUtils.isNotEmpty(image)) {
      content.append(",\"image\":\"" + image + "\"");
    }
    if (displayTime >= 1500 && displayTime <= 2147483647) {
      content.append(",\"displaytime\":" + displayTime);
    }
    content.append("}}");

    HttpUtil.executeUrl(
        "POST", url, IOUtils.toInputStream(content.toString()), CONTENT_TYPE_JSON, 1000);
  }
  public InputStream addAtomInlinecount(final InputStream feed, final int count) throws Exception {
    final XMLEventReader reader = getEventReader(feed);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    try {

      final XMLElement feedElement =
          extractElement(reader, writer, Collections.<String>singletonList("feed"), 0, 1, 1)
              .getValue();

      writer.add(feedElement.getStart());
      addAtomElement(
          IOUtils.toInputStream(String.format("<m:count>%d</m:count>", count), Constants.ENCODING),
          writer);
      writer.add(feedElement.getContentReader());
      writer.add(feedElement.getEnd());

      while (reader.hasNext()) {
        writer.add(reader.nextEvent());
      }

    } finally {
      writer.flush();
      writer.close();
      reader.close();
      IOUtils.closeQuietly(feed);
    }

    return new ByteArrayInputStream(bos.toByteArray());
  }
  @Override
  public InputStream deleteProperty(final InputStream src, final List<String> path)
      throws Exception {
    final XMLEventReader reader = getEventReader(src);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    final XMLEventReader changesReader =
        new XMLEventReaderWrapper(
            IOUtils.toInputStream(
                String.format("<%s m:null=\"true\" />", path.get(path.size() - 1)),
                Constants.ENCODING));

    writer.add(changesReader);
    changesReader.close();

    writer.add(reader);

    reader.close();
    IOUtils.closeQuietly(src);

    writer.flush();
    writer.close();

    return new ByteArrayInputStream(bos.toByteArray());
  }
 // likely want to reuse PySystemState in some clever fashion since expensive to setup...
 public JythonObjectFactory(
     PythonInterpreter interpreter, Class<? extends T> interfaceType, String script) {
   this.interfaceType = interfaceType;
   pythonInterpreter = interpreter;
   pythonInterpreter.exec(FileUtil.wrap(IOUtils.toInputStream(script)));
   klass = pythonInterpreter.get("rep");
 }
Exemple #14
0
  /**
   * Returns an InputStream containing a complete ZSync upload (Params, Relocate stream, and
   * ByteRange stream), ready to be sent as the body of a PUT request.
   *
   * <p>Note: In this implementation, any temporary file used to store the RelocateRanges will be
   * automatically deleted when this stream is closed, so a second invocation of this method on the
   * same Upload object is likely to throw an exception. Therefore, this method should be used only
   * once per Upload object.
   *
   * @return The complete ZSync upload
   * @throws UnsupportedEncodingException
   * @throws IOException
   */
  public InputStream getInputStream() throws UnsupportedEncodingException, IOException {

    List<InputStream> streamList = new ArrayList<InputStream>();

    /*
     * The getParams and getRelocStream must be terminated by a single LF character.
     */
    streamList.add(IOUtils.toInputStream(getParams(), CHARSET));
    streamList.add(IOUtils.toInputStream(RELOCATE + ": ", CHARSET));
    streamList.add(getRelocStream());
    /* Prepend the data portion with a blank line. */
    streamList.add(IOUtils.toInputStream(Character.toString(LF), CHARSET));
    streamList.add(getDataStream());

    return new SequenceInputStream(new IteratorEnum<InputStream>(streamList));
  }
  @Override
  public MessageModel parse(TestContext context, MessageParserCommand command)
      throws MessageParserException {
    try {
      if (context instanceof HL7V2TestContext) {
        HL7V2TestContext testContext = (HL7V2TestContext) context;
        String er7Message = command.getContent();
        String profileXml = testContext.getConformanceProfile().getIntegrationProfile().getXml();
        if (profileXml == null) {
          throw new MessageParserException("No Conformance Profile Provided to Parse the Message");
        }
        String conformanceProfileId = testContext.getConformanceProfile().getSourceId();
        if (!"".equals(er7Message) && er7Message != null && !"".equals(conformanceProfileId)) {
          InputStream profileStream = IOUtils.toInputStream(profileXml);
          Profile profile = XMLDeserializer.deserialize(profileStream).get();
          JParser p = new JParser();
          Message message = p.jparse(er7Message, profile.messages().apply(conformanceProfileId));
          return parse(message, er7Message);
        }
      } else {
        throw new MessageParserException(
            "Invalid Context Provided. Expected Context is HL7V2TestContext but found "
                + context.getClass().getSimpleName());
      }

    } catch (RuntimeException e) {
      throw new MessageParserException(e.getMessage());
    } catch (Exception e) {
      throw new MessageParserException(e.getMessage());
    }
    return new MessageModel();
  }
 private Node populateCache(HtmlLibrary library, String root, Session session) {
   Node cacheNode = null;
   try {
     String libPath = (new StringBuilder(CACHE_PATH).append(library.getPath(false))).toString();
     Node src = JcrUtils.getNodeIfExists(libPath, session);
     cacheNode = session.getNode(root);
     if (null != src) {
       // this.lock.readLock().lock();
       // produced closure compiled src
       String compiled = compile(library, this.optimization, JcrUtils.readFile(src));
       // this.lock.readLock().unlock();
       // this.lock.writeLock().lock();
       //
       JcrUtils.putFile(
           cacheNode.getParent(),
           getLibraryName(library),
           library.getType().contentType,
           IOUtils.toInputStream(compiled, "UTF-8"));
       session.save();
       // this.lock.writeLock().unlock();
     }
   } catch (RepositoryException re) {
     log.debug(re.getMessage());
   } catch (IOException ioe) {
     log.debug(ioe.getMessage());
   }
   return cacheNode;
 }
Exemple #17
0
  /**
   * Gets the hash data from the s-ramp repository and stores it in the {@link InputData} for use by
   * Maven.
   *
   * @param gavInfo
   * @param inputData
   * @throws TransferFailedException
   * @throws ResourceDoesNotExistException
   * @throws AuthorizationException
   */
  private void doGetHash(MavenGavInfo gavInfo, InputData inputData)
      throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    String artyPath = gavInfo.getFullName();
    String hashPropName;
    if (gavInfo.getType().endsWith(".md5")) { // $NON-NLS-1$
      hashPropName = "maven.hash.md5"; // $NON-NLS-1$
      artyPath = artyPath.substring(0, artyPath.length() - 4);
    } else {
      hashPropName = "maven.hash.sha1"; // $NON-NLS-1$
      artyPath = artyPath.substring(0, artyPath.length() - 5);
    }
    // See the comment in {@link SrampWagon#fillInputData(InputData)} about why we're doing this
    // context classloader magic.
    ClassLoader oldCtxCL = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(SrampWagon.class.getClassLoader());
    try {
      SrampArchiveEntry entry = this.archive.getEntry(artyPath);
      if (entry == null) {
        throw new ResourceDoesNotExistException(
            Messages.i18n.format("MISSING_RESOURCE_HASH", gavInfo.getName())); // $NON-NLS-1$
      }
      BaseArtifactType metaData = entry.getMetaData();

      String hashValue = SrampModelUtils.getCustomProperty(metaData, hashPropName);
      if (hashValue == null) {
        throw new ResourceDoesNotExistException(
            Messages.i18n.format("MISSING_RESOURCE_HASH", gavInfo.getName())); // $NON-NLS-1$
      }
      inputData.setInputStream(IOUtils.toInputStream(hashValue));
    } finally {
      Thread.currentThread().setContextClassLoader(oldCtxCL);
    }
  }
  private InputStream getInputStream(boolean raw) throws Exception {
    if (raw) {
      return IOUtils.toInputStream(xmlEditorModel.getObject(), "utf-8");
    }
    File newFile = null;
    try {
      // Create new file
      MidPointApplication application = getMidpointApplication();
      WebApplicationConfiguration config = application.getWebApplicationConfiguration();
      File folder = new File(config.getImportFolder());
      if (!folder.exists() || !folder.isDirectory()) {
        folder.mkdir();
      }

      FileUpload uploadedFile = getUploadedFile();
      newFile = new File(folder, uploadedFile.getClientFileName());
      // Check new file, delete if it already exists
      if (newFile.exists()) {
        newFile.delete();
      }
      // Save file

      newFile.createNewFile();
      uploadedFile.writeTo(newFile);

      InputStreamReader reader = new InputStreamReader(new FileInputStream(newFile), "utf-8");
      return new ReaderInputStream(reader, reader.getEncoding());
    } finally {
      if (newFile != null) {
        FileUtils.deleteQuietly(newFile);
      }
    }
  }
  @Test
  public void readJSONViaLowerlevelLibs() throws IOException {
    final ObjectMapper mapper = new ObjectMapper();

    final JsonNode entry = mapper.readTree(IOUtils.toInputStream(input.get(ODataPubFormat.JSON)));
    assertNotNull(entry);
  }
 @Test
 public void testGenerateCode() throws Exception {
   for (String algorithm : algs) {
     for (String key : keys) {
       for (int i = 0; i < testStrings.length; ++i) {
         InputStream in = IOUtils.toInputStream(testStrings[i]);
         InputStream keyStream = IOUtils.toInputStream(key);
         PipedInputStream result = new PipedInputStream();
         OutputStream out = new PipedOutputStream(result);
         MessageAuthenticator.generateCode(algorithm, in, keyStream, out);
         out.close();
         String actual = new String(Hex.encodeHex(IOUtils.toByteArray(result)));
         assertEquals(codes.get(algorithm).get(key)[i].toLowerCase(), actual.toLowerCase());
       }
     }
   }
 }
 @Ignore("reading with unix style csv for now")
 @Test
 public void readQuotes() throws IOException {
   LabeledCSVParser csvParser =
       CSVUtil.createLabeledCSVParser(IOUtils.toInputStream("name\n\"hello \"\"world\"\"\""));
   csvParser.getLine();
   assertThat(csvParser.getValueByLabel("name"), is("hello \"world\""));
 }
Exemple #22
0
 /**
  * Add to the package metadata file containing RO id.
  *
  * @param zipOutput zip output
  * @param entriesGroup exited entries
  * @param id Research Object id
  * @throws IOException .
  */
 private static void putMetadataId(ZipOutputStream zipOutput, Set<String> entriesGroup, URI id)
     throws IOException {
   String template =
       IOUtils.toString(
           IO.class.getClassLoader().getResourceAsStream(METADATA_TEMPLATE_ID_FILE_PATH));
   InputStream input = IOUtils.toInputStream(template.replace("{{object-id}}", id.toString()));
   putEntryAndDirectoriesPath(zipOutput, METADATA_ID_FILE_PATH, input, entriesGroup);
 }
 @Test
 public void shouldParseInputStreamInUt8() {
   StandardRulesXmlParser parser = new StandardRulesXmlParser();
   String xml =
       "<rules><rule key='key1' category='cat1' ><description>\\u00E9</description></rule></rules>";
   List<Rule> rules = parser.parse(IOUtils.toInputStream(xml));
   assertThat(rules.get(0).getDescription(), is("\\u00E9"));
 }
Exemple #24
0
 private InputStream replaceTextInResource(
     InputStream is, String textToReplace, String replacement) throws IOException {
   StringWriter writer = new StringWriter();
   IOUtils.copy(is, writer);
   String original = writer.toString();
   String modified = original.replace(textToReplace, replacement);
   return IOUtils.toInputStream(modified, "UTF-8");
 }
 @Test
 public void testCreateAndRetrieveBlobAppend() throws IOException {
   long before = System.currentTimeMillis();
   getBlobStore().storeBlob(CONTEXT, TEST_URI, false, IOUtils.toInputStream(TEST_BLOB_CONTENT));
   long after = System.currentTimeMillis();
   printDiff("testCreateAndRetrieveBlobAppend: storeBlob1", before, after);
   before = System.currentTimeMillis();
   boolean result =
       getBlobStore().storeBlob(CONTEXT, TEST_URI, true, IOUtils.toInputStream(TEST_BLOB_CONTENT));
   after = System.currentTimeMillis();
   printDiff("testCreateAndRetrieveBlobAppend: storeBlob2", before, after);
   assertTrue(result);
   before = System.currentTimeMillis();
   String blob = IOUtils.toString(getBlobStore().getBlob(CONTEXT, TEST_URI));
   after = System.currentTimeMillis();
   printDiff("testCreateAndRetrieveBlobAppend: getBlob", before, after);
   assertEquals(TEST_BLOB_CONTENT + TEST_BLOB_CONTENT, blob);
 }
 private String getJobStatus(String jobXML) throws Exception {
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   factory.setNamespaceAware(true);
   DocumentBuilder builder = factory.newDocumentBuilder();
   Document doc = builder.parse(IOUtils.toInputStream(jobXML, "UTF-8"));
   return ((Element)
           XPathFactory.newInstance().newXPath().compile("/*").evaluate(doc, XPathConstants.NODE))
       .getAttribute("status");
 }
  private CreateResponse storeContentItem(String data, String mimeType, String filename)
      throws Exception {
    String id = UUID.randomUUID().toString().replaceAll("-", "");
    ContentItem contentItem =
        new IncomingContentItem(id, IOUtils.toInputStream(data), mimeType, filename);
    CreateRequest createRequest = new CreateRequestImpl(contentItem, null);
    CreateResponse createResponse = provider.create(createRequest);

    return createResponse;
  }
 /**
  * internal helper to write output file
  *
  * @param message
  * @param logFile
  */
 private void writeFile(String message, String logFile) {
   try {
     File file = new File(logFile);
     FileOutputStream fout = FileUtils.openOutputStream(file);
     IOUtils.copy(IOUtils.toInputStream(message), fout);
     fout.close();
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
Exemple #29
0
 public Response postSequenceFile(
     String url, String recordId, EntryType entryType, String sequence) {
   WebTarget target = client.target("https://" + url).path("/rest/file/sequence");
   Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
   final FormDataMultiPart multiPart = new FormDataMultiPart();
   multiPart.field("file", IOUtils.toInputStream(sequence), MediaType.TEXT_PLAIN_TYPE);
   multiPart.field("entryRecordId", recordId);
   multiPart.field("entryType", entryType.name());
   return invocationBuilder.post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE));
 }
  @Test
  public void readAtomViaLowerlevelLibs()
      throws ParserConfigurationException, SAXException, IOException {
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder builder = factory.newDocumentBuilder();

    final Document entry = builder.parse(IOUtils.toInputStream(input.get(ODataPubFormat.ATOM)));
    assertNotNull(entry);
    entry.getDocumentElement().normalize();
  }