@Test
  public void testTwoInclude() throws Exception {
    HttpGet httpGet =
        new HttpGet(
            "http://localhost:"
                + ourPort
                + "/Patient?name=Hello&_include=foo&_include=bar&_pretty=true");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info(responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.size());

    Patient p = bundle.getResources(Patient.class).get(0);
    assertEquals(2, p.getName().size());
    assertEquals("Hello", p.getId().getIdPart());

    Set<String> values = new HashSet<String>();
    values.add(p.getName().get(0).getFamilyFirstRep().getValue());
    values.add(p.getName().get(1).getFamilyFirstRep().getValue());
    assertThat(values, containsInAnyOrder("foo", "bar"));
  }
  public void configMongoShard() throws IOException {
    // 初始化副本集1
    expect.sendLine("mongo --port 27010");
    expect.expect(contains(">"));
    expect.sendLine("use admin");
    expect.expect(contains(">"));
    InputStream resource0 = getClass().getClassLoader().getResourceAsStream("mongo/sh0.bson");
    String content0 = IOUtils.toString(resource0, StandardCharsets.UTF_8);
    String sh0 = "cfg=" + content0;
    System.out.println(sh0);
    expect.sendLine(sh0);
    expect.expect(contains(">"));
    expect.sendLine("rs.initiate(cfg);");
    expect.expect(anyOf(contains("PRIMARY>"), contains("OTHER>"), contains("SECONDARY>")));
    expect.sendLine("exit");
    ready(ROOT_USER);

    // 初始化副本集2
    expect.sendLine("mongo --port 27011");
    expect.expect(contains(">"));
    expect.sendLine("use admin");
    expect.expect(contains(">"));
    InputStream resource1 = getClass().getClassLoader().getResourceAsStream("mongo/sh1.bson");
    String content1 = IOUtils.toString(resource1, StandardCharsets.UTF_8);
    String sh1 = "cfg=" + content1;
    System.out.println(sh1);
    expect.sendLine(sh1);
    expect.expect(contains(">"));
    expect.sendLine("rs.initiate(cfg);");
    expect.expect(anyOf(contains("PRIMARY>"), contains("OTHER>"), contains("SECONDARY>")));
    expect.sendLine("exit");
    ready(ROOT_USER);

    // 配置分片
    expect.sendLine("mongo --port 30000");
    expect.expect(contains("mongos>"));
    expect.sendLine("use admin");
    expect.expect(contains("mongos>"));
    expect.sendLine(
        "sh.addShard(\"sh0/11.11.11.101:27010,11.11.11.102:27010,11.11.11.103:27010\");");
    expect.expect(contains("mongos>"));
    expect.sendLine(
        "sh.addShard(\"sh1/11.11.11.101:27011,11.11.11.102:27011,11.11.11.103:27011\");");
    expect.expect(contains("mongos>"));

    expect.sendLine("use mydb;");
    expect.expect(contains("mongos>"));

    expect.sendLine("db.createCollection(\"test\");");
    expect.expect(contains("mongos>"));

    expect.sendLine("sh.enableSharding(\"mydb\");");
    expect.expect(contains("mongos>"));

    expect.sendLine("sh.shardCollection(\"mydb.test\", {\"_id\":1});");
    expect.expect(contains("mongos>"));

    expect.sendLine("exit");
    ready(ROOT_USER);
  }
  @Test
  public void testIIncludedResourcesNonContainedInExtensionJson() throws Exception {
    HttpGet httpGet =
        new HttpGet(
            "http://localhost:" + ourPort + "/Patient?_query=extInclude&_pretty=true&_format=json");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newJsonParser().parseBundle(responseContent);

    ourLog.info(responseContent);

    assertEquals(3, bundle.size());
    assertEquals(
        new IdDt("Patient/p1"),
        bundle.toListOfResources().get(0).getId().toUnqualifiedVersionless());
    assertEquals(
        new IdDt("Patient/p2"),
        bundle.toListOfResources().get(1).getId().toUnqualifiedVersionless());
    assertEquals(
        new IdDt("Organization/o1"),
        bundle.toListOfResources().get(2).getId().toUnqualifiedVersionless());
    assertEquals(
        BundleEntrySearchModeEnum.INCLUDE,
        bundle.getEntries().get(2).getSearchMode().getValueAsEnum());

    Patient p1 = (Patient) bundle.toListOfResources().get(0);
    assertEquals(0, p1.getContained().getContainedResources().size());

    Patient p2 = (Patient) bundle.toListOfResources().get(1);
    assertEquals(0, p2.getContained().getContainedResources().size());
  }
  @Override
  public List<AttributeMappingData> loadMappingsFromSource(InputStream inputStream)
      throws ParserDataException {
    List<AttributeMappingData> attributesMapping = new ArrayList<AttributeMappingData>();
    BufferedReader br = null;
    try {

      Set<String> siteIds = siteService.getAllIds();
      Set<String> categoryIds = categoryService.getAllIds();

      br = new BufferedReader(new InputStreamReader(inputStream));
      String line = null;
      while ((line = br.readLine()) != null) {
        if (line == null || line.trim().isEmpty() || line.startsWith("#")) {
          continue;
        }
        AttributeMappingData att = parseObject(line);
        if (!siteIds.contains(att.getSiteKey())) {
          throw new ParserDataException("Site Key: " + att.getSiteKey() + " not found");
        }
        if (!categoryIds.contains(att.getCategoryKey())) {
          throw new ParserDataException("Category Key: " + att.getCategoryKey() + " not found");
        }
        attributesMapping.add(att);
      }
    } catch (IOException ex) {
      logger.error("Error loading Sites. Error: {}", ex);
      throw new ParserDataException(ex.getMessage());
    } finally {
      IOUtils.closeQuietly(br);
      IOUtils.closeQuietly(inputStream);
    }
    return attributesMapping;
  }
示例#5
0
  private void createUnixScript(
      String jarPath, File scriptDestinationDir, String wrapperPropertiesPath) throws IOException {
    String unixWrapperScriptHead =
        IOUtils.toString(getClass().getResourceAsStream("unixWrapperScriptHead.txt"));
    String unixWrapperScriptTail =
        IOUtils.toString(getClass().getResourceAsStream("unixWrapperScriptTail.txt"));

    String fillingUnix =
        ""
            + UNIX_NL
            + "STARTER_MAIN_CLASS="
            + FULLY_QUALIFIED_WRAPPER_NAME
            + UNIX_NL
            + "CLASSPATH="
            + CURRENT_DIR_UNIX
            + "/"
            + FilenameUtils.separatorsToUnix(jarPath)
            + UNIX_NL
            + "WRAPPER_PROPERTIES="
            + CURRENT_DIR_UNIX
            + "/"
            + FilenameUtils.separatorsToUnix(wrapperPropertiesPath)
            + UNIX_NL;

    String unixScript = unixWrapperScriptHead + fillingUnix + unixWrapperScriptTail;
    File unixScriptFile = new File(scriptDestinationDir, "gradlew");
    FileUtils.writeStringToFile(unixScriptFile, unixScript);
    createExecutablePermission(unixScriptFile);
  }
示例#6
0
 public static MD5InputStreamResult generateMD5Result(InputStream toEncode) {
   MD5Digest eTag = new MD5Digest();
   byte[] resBuf = new byte[eTag.getDigestSize()];
   byte[] buffer = new byte[1024];
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   long length = 0;
   int numRead = -1;
   try {
     do {
       numRead = toEncode.read(buffer);
       if (numRead > 0) {
         length += numRead;
         eTag.update(buffer, 0, numRead);
         out.write(buffer, 0, numRead);
       }
     } while (numRead != -1);
   } catch (IOException e) {
     throw new RuntimeException(e);
   } finally {
     IOUtils.closeQuietly(out);
     IOUtils.closeQuietly(toEncode);
   }
   eTag.doFinal(resBuf, 0);
   return new MD5InputStreamResult(out.toByteArray(), resBuf, length);
 }
示例#7
0
 public void testStringStream() throws IOException {
   String input = "aads ghaskdgasgldj asl sadg ajdsg &jag # @ hjsakg hsakdg hjkas s";
   ContentStreamBase stream = new ContentStreamBase.StringStream(input);
   assertEquals(input.length(), stream.getSize().intValue());
   assertEquals(input, IOUtils.toString(stream.getStream(), "UTF-8"));
   assertEquals(input, IOUtils.toString(stream.getReader()));
 }
示例#8
0
  public static String handleRetrofitErrorQuietly(final RetrofitError error) {
    error.printStackTrace();

    InputStream inputStream = null;
    try {
      if (error.isNetworkError()) {
        Log.e("XDA-ONE", "Network error happened.");
      } else {
        final TypedInput body = error.getResponse().getBody();
        if (body == null) {
          Log.e("XDA-ONE", "Unable to retrieve body");
          return null;
        }
        inputStream = body.in();

        final String result = IOUtils.toString(inputStream);
        Log.e("XDA-ONE", result);
        return result;
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      IOUtils.closeQuietly(inputStream);
    }
    return null;
  }
  public <P extends AbstractProject<P, B>, B extends AbstractBuild<P, B>> String getContent(
      AbstractBuild<P, B> build,
      ExtendedEmailPublisher publisher,
      EmailType type,
      Map<String, ?> args)
      throws IOException, InterruptedException {

    InputStream inputStream = null;
    InputStream templateStream = null;
    String scriptName = Args.get(args, SCRIPT_NAME_ARG, DEFAULT_SCRIPT_NAME);
    String templateName = Args.get(args, SCRIPT_TEMPLATE_ARG, DEFAULT_TEMPLATE_NAME);
    boolean runInit = Args.get(args, SCRIPT_INIT_ARG, DEFAULT_INIT_VALUE);

    try {
      inputStream = getFileInputStream(scriptName);
      // sanity check on template as well
      templateStream = getFileInputStream(templateName);
      IOUtils.closeQuietly(templateStream);

      return renderContent(build, inputStream, scriptName, templateName, runInit);
    } catch (FileNotFoundException e) {
      String missingScriptError = generateMissingFile(scriptName, templateName);
      LOGGER.log(Level.SEVERE, missingScriptError);
      return missingScriptError;
    } catch (ScriptException e) {
      LOGGER.log(Level.SEVERE, null, e);
      return "Exception: " + e.getMessage();
    } finally {
      IOUtils.closeQuietly(inputStream);
    }
  }
示例#10
0
  private static String readProcessOutput(String command, String arguments) {
    String result = "";
    ProcessBuilder pb = new ProcessBuilder(command, arguments);
    pb.redirectErrorStream(true);
    try {
      Process process = pb.start();
      InputStream stdout = process.getInputStream();
      final BufferedReader brstdout = new BufferedReader(new InputStreamReader(stdout));
      String line = null;

      try {
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = brstdout.readLine()) != null) {
          stringBuilder.append(line);
        }

        result = stringBuilder.toString();
      } catch (Exception e) {
      } finally {
        IOUtils.closeQuietly(brstdout);
        IOUtils.closeQuietly(stdout);
      }

    } catch (Throwable e) {
      e.printStackTrace();
    }
    return result;
  }
 /**
  * @return
  * @throws IllegalStateException if {@code tesseract} binary invoked with {@code --list-langs}
  *     returns a code {@code != 0}
  */
 public List<String> getAvailableLanguages()
     throws IllegalStateException, IOException, InterruptedException {
   ProcessBuilder tesseractProcessBuilder = new ProcessBuilder(this.getBinary(), "--list-langs");
   Process tesseractProcess =
       tesseractProcessBuilder.redirectOutput(ProcessBuilder.Redirect.PIPE).start();
   int tesseractProcessReturnCode = tesseractProcess.waitFor();
   String tesseractProcessStdout = IOUtils.toString(tesseractProcess.getInputStream());
   String tesseractProcessStderr = IOUtils.toString(tesseractProcess.getErrorStream());
   if (tesseractProcessReturnCode != 0) {
     throw new IllegalStateException(
         String.format(
             "The tesseract process '%s' unexpectedly returned with non-zero return code %d and output '%s' (stdout) and '%s' (stderr).",
             this.getBinary(),
             tesseractProcessReturnCode,
             tesseractProcessStdout,
             tesseractProcessStderr));
   }
   // tesseract --list-langs prints to stderr, reported as
   // https://bugs.launchpad.net/ubuntu/+source/tesseract/+bug/1481015
   List<String> langs = new LinkedList<>();
   for (String lang : tesseractProcessStderr.split("\n")) {
     if (!lang.startsWith("List of available languages")) {
       langs.add(lang);
     }
   }
   Collections.sort(langs, String.CASE_INSENSITIVE_ORDER);
   return langs;
 }
  private void doSaveImage(final String diagramFileString, BpmnMemoryModel model) {
    boolean saveImage =
        PreferencesUtil.getBooleanPreference(Preferences.SAVE_IMAGE, ActivitiPlugin.getDefault());
    if (saveImage) {
      List<String> languages =
          PreferencesUtil.getStringArray(
              Preferences.ACTIVITI_LANGUAGES, ActivitiPlugin.getDefault());
      if (languages != null && languages.size() > 0) {

        for (String language : languages) {
          for (Process process : model.getBpmnModel().getProcesses()) {
            fillContainerWithLanguage(process, language);
          }

          ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
          InputStream imageStream =
              processDiagramGenerator.generatePngDiagram(model.getBpmnModel());

          if (imageStream != null) {
            String imageFileName = null;
            if (diagramFileString.endsWith(".bpmn20.xml")) {
              imageFileName =
                  diagramFileString.substring(0, diagramFileString.length() - 11)
                      + "_"
                      + language
                      + ".png";
            } else {
              imageFileName =
                  diagramFileString.substring(0, diagramFileString.lastIndexOf("."))
                      + "_"
                      + language
                      + ".png";
            }
            File imageFile = new File(imageFileName);
            FileOutputStream outStream = null;
            ByteArrayOutputStream baos = null;
            try {
              outStream = new FileOutputStream(imageFile);
              baos = new ByteArrayOutputStream();
              IOUtils.copy(imageStream, baos);
              baos.writeTo(outStream);

            } catch (Exception e) {
              e.printStackTrace();
            } finally {
              if (outStream != null) {
                IOUtils.closeQuietly(outStream);
              }
              if (baos != null) {
                IOUtils.closeQuietly(baos);
              }
            }
          }
        }

      } else {
        marshallImage(model, diagramFileString);
      }
    }
  }
  private File getCachedImage(File file, int size) throws IOException {
    String md5 = DigestUtils.md5Hex(file.getPath());
    File cachedImage = new File(getImageCacheDirectory(size), md5 + ".jpeg");

    // Is cache missing or obsolete?
    if (!cachedImage.exists() || FileUtil.lastModified(file) > cachedImage.lastModified()) {
      InputStream in = null;
      OutputStream out = null;
      try {
        in = getImageInputStream(file);
        out = new FileOutputStream(cachedImage);
        BufferedImage image = ImageIO.read(in);
        if (image == null) {
          throw new Exception("Unable to decode image.");
        }

        image = scale(image, size, size);
        ImageIO.write(image, "jpeg", out);

      } catch (Throwable x) {
        // Delete corrupt (probably empty) thumbnail cache.
        LOG.warn("Failed to create thumbnail for " + file, x);
        IOUtils.closeQuietly(out);
        cachedImage.delete();
        throw new IOException("Failed to create thumbnail for " + file + ". " + x.getMessage());

      } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
      }
    }
    return cachedImage;
  }
示例#14
0
 @Override
 public void close() {
   IOUtils.closeQuietly(socketChannelOutput);
   IOUtils.closeQuietly(channel);
   socketChannelOutput = null;
   channel = null;
 }
  private Capabilities getCapabilitiesValue(String property) {
    if (StringUtils.isEmpty(property)) {
      return null;
    }
    try {
      URL url = new URL(property);
      InputStream stream = null;
      try {
        stream = url.openStream();
        property = IOUtils.toString(stream, Charset.defaultCharset());
      } catch (IOException e) {
        throw new ConfigurationException("Can't read Capabilities defined at " + url, e);
      } finally {
        IOUtils.closeQuietly(stream);
      }
    } catch (MalformedURLException e) { // NOPMD EmptyCatchBlock
      // This is not an URL. Consider property as JSON.
    }
    CapabilitiesFactory factory = (CapabilitiesFactory) CapabilitiesRegistry.INSTANCE.get(property);
    if (factory != null) {
      return factory.newCapabilities(getGlobalConfiguration());
    }

    try {
      return jsonConverter.convert(DesiredCapabilities.class, property);
    } catch (JsonException e) {
      throw new ConfigurationException("Can't convert JSON Capabilities to Object.", e);
    }
  }
示例#16
0
  protected void check(LayoutDefinition layoutDef, String lang) throws Exception {
    LayoutConversionContext ctx = new LayoutConversionContext(lang, null);
    List<LayoutDefinitionConverter> layoutConverters = service.getLayoutConverters(TEST_CATEGORY);
    for (LayoutDefinitionConverter conv : layoutConverters) {
      layoutDef = conv.getLayoutDefinition(layoutDef, ctx);
    }
    List<WidgetDefinitionConverter> widgetConverters = service.getWidgetConverters(TEST_CATEGORY);

    String langFilePath = lang;
    if (langFilePath == null) {
      langFilePath = "nolang";
    }
    File file = Framework.createTempFile("layout-export-" + langFilePath, ".json");
    FileOutputStream out = new FileOutputStream(file);
    JSONLayoutExporter.export(WebLayoutManager.JSF_CATEGORY, layoutDef, ctx, widgetConverters, out);
    out.close();

    InputStream written = new FileInputStream(file);
    InputStream expected =
        new FileInputStream(
            FileUtils.getResourcePathFromContext("layout-export-" + langFilePath + ".json"));

    String expectedString = IOUtils.toString(expected, Charsets.UTF_8);
    String writtenString = IOUtils.toString(written, Charsets.UTF_8);
    // order of select options may depend on directory database => do not
    // check order of element by using the NON_EXTENSIBLE mode
    JSONAssert.assertEquals(expectedString, writtenString, JSONCompareMode.NON_EXTENSIBLE);
  }
示例#17
0
  @Override
  public void replicate(ConfigManager manager, ConfigRequest request) throws IOException {
    if (!request.applies(CertificateManager.FEATURE)) {
      return;
    }

    boolean chainCertificate = false;
    boolean caCertificate = false;
    File dir = manager.getGlobalDataDirectory();
    String sipCert = m_certificateManager.getCommunicationsCertificate();
    FileUtils.writeStringToFile(new File(dir, "ssl.crt"), sipCert);
    String sipKey = m_certificateManager.getCommunicationsPrivateKey();
    FileUtils.writeStringToFile(new File(dir, "ssl.key"), sipKey);
    String webCert = m_certificateManager.getWebCertificate();
    FileUtils.writeStringToFile(new File(dir, "ssl-web.crt"), webCert);
    String webKey = m_certificateManager.getWebPrivateKey();
    FileUtils.writeStringToFile(new File(dir, "ssl-web.key"), webKey);

    String chainCert = m_certificateManager.getChainCertificate();
    if (chainCert != null) {
      FileUtils.writeStringToFile(new File(dir, "server-chain.crt"), chainCert);
      chainCertificate = true;
    }
    String caCert = m_certificateManager.getCACertificate();
    if (caCert != null) {
      FileUtils.writeStringToFile(new File(dir, "ca-bundle.crt"), caCert);
      caCertificate = true;
    }
    Writer writer = new FileWriter(new File(dir, "ssl.conf"));
    try {
      write(writer, chainCertificate, caCertificate);
    } finally {
      IOUtils.closeQuietly(writer);
    }

    String domain = Domain.getDomain().getName();

    JavaKeyStore sslSip = new JavaKeyStore();
    sslSip.addKey(domain, sipCert, sipKey);
    sslSip.storeIfDifferent(new File(dir, "ssl.keystore"));

    JavaKeyStore sslWeb = new JavaKeyStore();
    sslWeb.addKey(domain, webCert, webKey);
    sslWeb.storeIfDifferent(new File(dir, "ssl-web.keystore"));

    File authDir = new File(dir, "authorities");
    authDir.mkdir();
    JavaKeyStore store = new JavaKeyStore();
    for (String authority : m_certificateManager.getAuthorities()) {
      String authCert = m_certificateManager.getAuthorityCertificate(authority);
      FileUtils.writeStringToFile(new File(authDir, authority + ".crt"), authCert);
      store.addAuthority(authority, authCert);
    }
    OutputStream authoritiesStore = null;
    try {
      store.storeIfDifferent(new File(dir, "authorities.jks"));
    } finally {
      IOUtils.closeQuietly(authoritiesStore);
    }
  }
示例#18
0
  public static boolean CopyResourceToStorage(int resourceId, String path, boolean force) {
    File file = new File(path);

    // 파일이 존재하면 true return
    if (file.exists() && !force) {
      return true;
    }

    InputStream inputStream = null;
    OutputStream outputStream = null;

    try {
      // Stream 복사
      inputStream = context.getResources().openRawResource(resourceId);
      outputStream = context.openFileOutput(path, Context.MODE_PRIVATE);

      IOUtils.copy(inputStream, outputStream);
    } catch (Exception e) {
      path = e.getMessage();
      return false;
    } finally {
      IOUtils.closeQuietly(inputStream);
      IOUtils.closeQuietly(outputStream);
    }

    return true;
  }
  @Test
  public void testUpdateWithoutConditionalUrl() throws Exception {

    Patient patient = new Patient();
    patient.addIdentifier().setValue("002");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/2");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(patient),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);

    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info("Response was:\n{}", responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("location").getValue());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("content-location").getValue());

    assertEquals("Patient/2", new IdType(ourLastId).toUnqualified().getValue());
    assertEquals("Patient/2", ourLastIdParam.toUnqualified().getValue());
    assertNull(ourLastConditionalUrl);
  }
示例#20
0
 private JarFile loadModuleJarFile(String moduleId, String version) throws IOException {
   InputStream moduleStream = null;
   File tempFile = null;
   OutputStream tempFileStream = null;
   JarFile jarFile = null;
   try {
     moduleStream =
         getClass()
             .getClassLoader()
             .getResourceAsStream(
                 "org/openmrs/module/include/" + moduleId + "-" + version + ".omod");
     Assert.assertNotNull(moduleStream);
     tempFile = File.createTempFile("moduleTest", "omod");
     tempFileStream = new FileOutputStream(tempFile);
     IOUtils.copy(moduleStream, tempFileStream);
     jarFile = new JarFile(tempFile);
   } finally {
     IOUtils.closeQuietly(moduleStream);
     IOUtils.closeQuietly(tempFileStream);
     if (tempFile != null) {
       tempFile.delete();
     }
   }
   return jarFile;
 }
  public String copyLibraryToTempFile(String library) throws IOException {
    InputStream in = null;
    OutputStream out = null;

    try {
      String libraryName = getContextAwareLibraryName(library);
      in = getClass().getClassLoader().getResourceAsStream("lib/" + libraryName);

      if (in == null) {
        fail("runtime not supported, '%s' missing in native bundle", libraryName);
      }

      File file = createTempFile(library);
      out = new FileOutputStream(file);

      int cnt;
      byte buf[] = new byte[16 * 1024];
      while ((cnt = in.read(buf)) >= 1) {
        out.write(buf, 0, cnt);
      }

      return file.getAbsolutePath();
    } finally {
      IOUtils.closeQuietly(in);
      IOUtils.closeQuietly(out);
    }
  }
  @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));
  }
 public void send(
     SlingHttpServletRequest request, SlingHttpServletResponse response, HtmlLibrary library) {
   InputStream libraryInputStream = null;
   // NOTE: HtmlLibraryManager#getLibrary should have prepared ClientLibraryImpl
   // and related binary stream should be ready
   try {
     Node node =
         JcrUtils.getNodeIfExists(getLibraryNode(request, library), JcrConstants.JCR_CONTENT);
     response.setDateHeader(
         "Last-Modified", JcrUtils.getLongProperty(node, JcrConstants.JCR_LASTMODIFIED, 0L));
     response.setContentType(library.getType().contentType);
     response.setCharacterEncoding("utf-8");
     libraryInputStream = JcrUtils.readFile(node);
   } catch (RepositoryException re) {
     log.debug("JCR issue retrieving library node at {}: ", library.getPath(), re.getMessage());
   }
   try {
     if (libraryManager.isGzipEnabled()) {
       response.setHeader("Content-Encoding", "gzip");
       GZIPOutputStream gzipOut = new GZIPOutputStream(response.getOutputStream());
       IOUtils.copy(libraryInputStream, gzipOut);
       gzipOut.finish();
     } else {
       IOUtils.copy(libraryInputStream, response.getOutputStream());
     }
   } catch (IOException ioe) {
     log.debug("gzip IO issue for library {}: ", library.getPath(), ioe.getMessage());
   } finally {
     IOUtils.closeQuietly(libraryInputStream);
   }
 }
示例#24
0
  private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
      throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
      throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    FileInputStream input = new FileInputStream(srcFile);
    try {
      FileOutputStream output = new FileOutputStream(destFile);
      try {
        IOUtils.copy(input, output);
      } finally {
        IOUtils.closeQuietly(output);
      }
    } finally {
      IOUtils.closeQuietly(input);
    }

    if (srcFile.length() != destFile.length()) {
      throw new IOException(
          "Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
    }
    if (preserveFileDate) {
      destFile.setLastModified(srcFile.lastModified());
    }
  }
示例#25
0
 private void createWindowsScript(
     String jarPath, File scriptDestinationDir, String wrapperPropertiesPath) throws IOException {
   String windowsWrapperScriptHead =
       IOUtils.toString(getClass().getResourceAsStream("windowsWrapperScriptHead.txt"));
   String windowsWrapperScriptTail =
       IOUtils.toString(getClass().getResourceAsStream("windowsWrapperScriptTail.txt"));
   String fillingWindows =
       ""
           + WINDOWS_NL
           + "set STARTER_MAIN_CLASS="
           + FULLY_QUALIFIED_WRAPPER_NAME
           + WINDOWS_NL
           + "set CLASSPATH="
           + CURRENT_DIR_WINDOWS
           + "\\"
           + FilenameUtils.separatorsToWindows(jarPath)
           + WINDOWS_NL
           + "set WRAPPER_PROPERTIES="
           + CURRENT_DIR_WINDOWS
           + "\\"
           + FilenameUtils.separatorsToWindows(wrapperPropertiesPath)
           + WINDOWS_NL;
   String windowsScript = windowsWrapperScriptHead + fillingWindows + windowsWrapperScriptTail;
   File windowsScriptFile = new File(scriptDestinationDir, "gradlew.bat");
   FileUtils.writeStringToFile(windowsScriptFile, transformIntoWindowsNewLines(windowsScript));
 }
  /**
   * Gobbles up all the stuff coming from the InputStream and sends it to the OutputStream specified
   * during object construction.
   */
  public void run() {

    InputStreamReader isr = null;
    BufferedReader br = null;
    try {

      // Set up the input stream
      isr = new InputStreamReader(in);
      br = new BufferedReader(isr);

      // Initialize the temporary results containers
      String line = null;

      // Main processing loop which captures the output
      while ((line = br.readLine()) != null) {
        if (quit) {
          break;
        } else {
          pwOut.println(line);
        }
      }

    } catch (final Throwable e) {
      LogUtils.debugf(this, e, "Unable to read lines.");
    } finally {
      IOUtils.closeQuietly(br);
      IOUtils.closeQuietly(isr);
    }
  }
示例#27
0
  /**
   * Copy a file into another. The directory structure of target file will be created if needed.
   *
   * @param source the source file
   * @param destination the target file
   * @return true if the copy happened without error, false otherwise
   */
  public static boolean copy(final File source, final File destination) {
    FileUtils.mkdirs(destination.getParentFile());

    InputStream input = null;
    OutputStream output = null;
    boolean copyDone = false;

    try {
      input = new BufferedInputStream(new FileInputStream(source));
      output = new BufferedOutputStream(new FileOutputStream(destination));
      copyDone = copy(input, output);
      // close here already to catch any issue with closing
      input.close();
      output.close();
    } catch (final FileNotFoundException e) {
      Log.e("LocalStorage.copy: could not copy file", e);
      return false;
    } catch (final IOException e) {
      Log.e("LocalStorage.copy: could not copy file", e);
      return false;
    } finally {
      // close here quietly to clean up in all situations
      IOUtils.closeQuietly(input);
      IOUtils.closeQuietly(output);
    }

    return copyDone;
  }
  /**
   * Optionally accepts 1 argument. If the argument evaluates to true ({@link
   * Boolean#parseBoolean(String)}, the main method will NOT run the SQL statements in the
   * "destroyDdl" Resource.
   *
   * @param args
   */
  public static void main(String[] args) throws Exception {
    LOG.info("loading applicationContext: " + CONFIG);
    ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG);

    boolean firstRun = false;
    if (args.length == 1) {
      firstRun = Boolean.parseBoolean(args[0]);
    }
    InitializeSchedulingAssistantDatabase init = new InitializeSchedulingAssistantDatabase();
    init.setDataSource((DataSource) context.getBean("dataSource"));

    if (!firstRun) {
      Resource destroyDdl = (Resource) context.getBean("destroyDdl");
      if (null != destroyDdl) {
        String destroySql = IOUtils.toString(destroyDdl.getInputStream());
        init.executeDdl(destroySql);
        LOG.warn("existing tables removed");
      }
    }

    Resource createDdl = (Resource) context.getBean("createDdl");
    String createSql = IOUtils.toString(createDdl.getInputStream());

    init.executeDdl(createSql);
    LOG.info("database initialization complete");
  }
示例#29
0
  protected void check(String layoutName, String lang) throws Exception {
    LayoutConversionContext ctx = new LayoutConversionContext(lang, null);
    LayoutDefinition layoutDef =
        service.getLayoutDefinition(WebLayoutManager.JSF_CATEGORY, layoutName);
    Layout layout =
        jsfService.getLayout(
            null, ctx, TEST_CATEGORY, layoutDef, BuiltinModes.VIEW, "currentDocument", null, false);
    String langFilePath = lang;
    if (langFilePath == null) {
      langFilePath = "nolang";
    }
    File file = Framework.createTempFile("layout-instance-export-" + langFilePath, ".json");
    FileOutputStream out = new FileOutputStream(file);
    JSONObject res = JSONLayoutExporter.exportToJson(layout);
    out.write(res.toString(2).getBytes(JSONLayoutExporter.ENCODED_VALUES_ENCODING));
    out.close();

    InputStream written = new FileInputStream(file);
    InputStream expected =
        new FileInputStream(
            FileUtils.getResourcePathFromContext(
                "layout-instance-export-" + langFilePath + ".json"));

    String expectedString = IOUtils.toString(expected, Charsets.UTF_8);
    String writtenString = IOUtils.toString(written, Charsets.UTF_8);
    // order of select options may depend on directory database => do not
    // check order of element by using the NON_EXTENSIBLE mode
    JSONAssert.assertEquals(expectedString, writtenString, JSONCompareMode.NON_EXTENSIBLE);
  }
  /**
   * 文件解压
   *
   * @param file 压缩文件
   * @param destDir 解压目录
   */
  public static void decompress(File file, File destDir, String encoding) {

    if (!file.exists()) {
      return;
    }

    InputStream is = null;
    ZipArchiveInputStream zis = null;

    try {
      is = new FileInputStream(file);
      zis = new ZipArchiveInputStream(new FileInputStream(file), encoding);

      ArchiveEntry archiveEntry = null;

      while ((archiveEntry = zis.getNextEntry()) != null) {
        CompressUtilsHelper.decompress(zis, archiveEntry, destDir);
      }
    } catch (Exception e) {
      throw new CommonsException(
          "Decompress " + file.getPath() + " to " + destDir.getPath() + " failed!", e);
    } finally {
      IOUtils.closeQuietly(zis);
      IOUtils.closeQuietly(is);
    }
  }