Esempio n. 1
0
 @Override
 public Iterable<NamedValue> loadSymbols(Context context) throws IOException {
   LazyLoadFrame frame =
       new LazyLoadFrame(context, Resources.newInputStreamSupplier(getEnvironmentUrl()));
   List<NamedValue> values = Lists.newArrayList();
   for (Symbol name : frame.getNames()) {
     values.add(new PackageValue(name, frame.get(name)));
   }
   return values;
 }
    public void process(File f) throws Exception {
      if (f.isDirectory()) {
        File[] files =
            f.listFiles(
                new FilenameFilter() {

                  @Override
                  public boolean accept(File dir, String name) {
                    return name.matches(FILE_PATTERN);
                  }
                });
        for (File ff : files) {
          byte[] bindingBytes = Files.toByteArray(ff);
          this.addCurrentBinding(bindingBytes, ff.getName(), "file:" + ff.getAbsolutePath());
        }
      } else {
        String digest = new BigInteger(Files.getDigest(f, Digest.MD5.get())).abs().toString(16);
        CURRENT_PROPS.put(BINDING_CACHE_JAR_PREFIX + f.getName(), digest);
        final JarFile jar = new JarFile(f);
        final List<JarEntry> jarList = Collections.list(jar.entries());
        for (final JarEntry j : jarList) {
          try {
            if (j.getName().matches(FILE_PATTERN)) {
              byte[] bindingBytes = ByteStreams.toByteArray(jar.getInputStream(j));
              String bindingName = j.getName();
              String bindingFullPath = "jar:file:" + f.getAbsolutePath() + "!/" + bindingName;
              this.addCurrentBinding(bindingBytes, bindingName, bindingFullPath);
            } else if (j.getName().matches(".*\\.class.{0,1}")) {
              final String classGuess =
                  j.getName().replaceAll("/", ".").replaceAll("\\.class.{0,1}", "");
              final Class candidate = ClassLoader.getSystemClassLoader().loadClass(classGuess);
              if (MSG_BASE_CLASS.isAssignableFrom(candidate)
                  || MSG_DATA_CLASS.isAssignableFrom(candidate)) {
                InputSupplier<InputStream> classSupplier =
                    Resources.newInputStreamSupplier(ClassLoader.getSystemResource(j.getName()));
                File destClassFile = SubDirectory.CLASSCACHE.getChildFile(j.getName());
                if (!destClassFile.exists()) {
                  Files.createParentDirs(destClassFile);
                  Files.copy(classSupplier, destClassFile);
                  Logs.extreme()
                      .debug("Caching: " + j.getName() + " => " + destClassFile.getAbsolutePath());
                }
                BINDING_CLASS_MAP.putIfAbsent(classGuess, candidate);
              }
            }
          } catch (RuntimeException ex) {
            LOG.error(ex, ex);
            jar.close();
            throw ex;
          }
        }
        jar.close();
      }
    }
 public static File readResourceToTempFile(String resourceName) throws IOException {
   InputSupplier<? extends InputStream> inSupplier;
   try {
     URL resourceURL = Resources.getResource(GroupLensRecommender.class, resourceName);
     inSupplier = Resources.newInputStreamSupplier(resourceURL);
   } catch (IllegalArgumentException iae) {
     File resourceFile = new File("src/main/java" + resourceName);
     inSupplier = Files.newInputStreamSupplier(resourceFile);
   }
   File tempFile = File.createTempFile("taste", null);
   tempFile.deleteOnExit();
   Files.copy(inSupplier, tempFile);
   return tempFile;
 }
Esempio n. 4
0
  public static InputSupplier<InputStream> newConfigEntrySupplier(
      Repository repository, String config, final String entryName) {
    URI uri = repository.configToHttpUri(config);
    if (uri == null) {
      return null;
    }

    URL configUrl;
    try {
      configUrl = uri.toURL();
    } catch (MalformedURLException e) {
      throw new RuntimeException("Invalid config bundle location " + uri);
    }

    return ConfigUtils.newConfigEntrySupplier(
        Resources.newInputStreamSupplier(configUrl), entryName);
  }
Esempio n. 5
0
 @Override
 public void handle(RestxRouteMatch match, RestxRequest req, RestxResponse resp, RestxContext ctx)
     throws IOException {
   String relativePath = req.getRestxPath().substring(baseRestPath.length());
   relativePath = Optional.fromNullable(aliases.get(relativePath)).or(relativePath);
   try {
     URL resource =
         MoreResources.getResource(
             baseResourcePath + relativePath, RestxContext.Modes.DEV.equals(ctx.getMode()));
     resp.setStatus(HttpStatus.OK.getCode());
     resp.setContentType(
         HTTP.getContentTypeFromExtension(relativePath).or("application/octet-stream"));
     ByteStreams.copy(Resources.newInputStreamSupplier(resource), resp.getOutputStream());
   } catch (IllegalArgumentException e) {
     notFound(resp, relativePath);
   }
 }
Esempio n. 6
0
  public Poll call() throws Exception {
    long start = System.nanoTime();
    try {
      ByteStreams.readBytes(
          Resources.newInputStreamSupplier(new URL(this.url)),
          new ByteProcessor<Object>() {
            public boolean processBytes(byte[] buf, int off, int len) throws IOException {
              return true;
            }

            public Object getResult() {
              return null;
            }
          });
    } catch (IOException e) {
      e.printStackTrace();
    }

    long stop = System.nanoTime();
    long duration_nanos = stop - start;
    long millis = TimeUnit.MILLISECONDS.convert(duration_nanos, TimeUnit.NANOSECONDS);
    return new Poll(url, millis);
  }
  /** Reads the template file, parsing all data to TemplateContentData object */
  private TemplateContentData getContentDataFromTemplate(String templateName) {
    TemplateContentData templateContentData = new TemplateContentData();
    StringBuilder contentPart = new StringBuilder();

    BufferedReader reader = null;
    try {
      reader =
          new BufferedReader(
              new InputStreamReader(
                  Resources.newInputStreamSupplier(Resources.getResource(templateName)).getInput(),
                  Charset.defaultCharset()));

      String line;
      while ((line = reader.readLine()) != null) {
        if (line.toLowerCase().startsWith(KEY_SUBJECT)) {
          templateContentData.setSubject(line.substring(KEY_SUBJECT.length()).trim());
        } else if (!line.startsWith("#")) {
          contentPart.append(line);
        }
      }
      templateContentData.setContent(contentPart.toString());
    } catch (FileNotFoundException e) {
      throw new RuntimeException("Couldn't find template: " + templateName);
    } catch (IOException e) {
      throw new RuntimeException("I/O exception while reading template: " + templateName);
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    return templateContentData;
  }
  @Override
  public Deployment install(Installation installation) {
    Preconditions.checkNotNull(installation, "installation is null");

    File deploymentDir = new File(baseDir, "installation");

    Assignment assignment = installation.getAssignment();

    Deployment newDeployment =
        new Deployment(
            slotId, location, deploymentDir, getDataDir(), assignment, installation.getResources());
    File tempDir = createTempDir(baseDir, "tmp-install");
    try {
      // download the binary
      File binary = new File(tempDir, "airship-binary.tar.gz");
      try {
        Files.copy(Resources.newInputStreamSupplier(installation.getBinaryFile().toURL()), binary);
      } catch (IOException e) {
        throw new RuntimeException(
            "Unable to download binary "
                + assignment.getBinary()
                + " from "
                + installation.getBinaryFile(),
            e);
      }

      // unpack the binary into a temp unpack dir
      File unpackDir = new File(tempDir, "unpack");
      unpackDir.mkdirs();
      try {
        extractTar(binary, unpackDir, tarTimeout);
      } catch (CommandFailedException e) {
        throw new RuntimeException(
            "Unable to extract tar file " + assignment.getBinary() + ": " + e.getMessage());
      }

      // find the archive root dir (it should be the only file in the temp unpack dir)
      List<File> files = listFiles(unpackDir);
      if (files.size() != 1) {
        throw new RuntimeException(
            "Invalid tar file: file does not have a root directory " + assignment.getBinary());
      }
      File binaryRootDir = files.get(0);

      // unpack config bundle
      try {
        URL url = installation.getConfigFile().toURL();
        ConfigUtils.unpackConfig(Resources.newInputStreamSupplier(url), binaryRootDir);
      } catch (Exception e) {
        throw new RuntimeException(
            "Unable to extract config bundle " + assignment.getConfig() + ": " + e.getMessage());
      }

      // installation is good, clear the current deployment
      if (this.deployment != null) {
        this.deploymentFile.delete();
        deleteRecursively(this.deployment.getDeploymentDir());
        this.deployment = null;
      }

      // save deployment versions file
      try {
        save(newDeployment);
      } catch (IOException e) {
        throw new RuntimeException("Unable to save deployment file", e);
      }

      // move the binary root directory to the final target
      try {
        Files.move(binaryRootDir, deploymentDir);
      } catch (IOException e) {
        throw new RuntimeException("Unable to move deployment to final location", e);
      }
    } finally {
      if (!deleteRecursively(tempDir)) {
        log.warn("Unable to delete temp directory: %s", tempDir.getAbsolutePath());
      }
    }

    this.deployment = newDeployment;
    return newDeployment;
  }
Esempio n. 9
0
 /**
  * Loads the default properties that define the {@code RestContext} objects.
  *
  * <h3>properties file format</h3>
  *
  * Two properties are needed per context:
  *
  * <ul>
  *   <li>tag.contextbuilder=classname extends RestContextBuilder
  *   <li>tag.propertiesbuilder=classname extends HttpPropertiesBuilder
  * </ul>
  *
  * Ex.
  *
  * <pre>
  * azureblob.contextbuilder=org.jclouds.azure.storage.blob.blobstore.AzureRestContextBuilder
  * azureblob.propertiesbuilder=org.jclouds.azure.storage.blob.AzureBlobPropertiesBuilder
  * </pre>
  *
  * @param filename name of file to load from in the resource path
  * @return properties object with these items loaded for each tag
  * @throws IOException if {@code filename} cannot load.
  */
 public static Properties getPropertiesFromResource(String filename) throws IOException {
   Properties properties = new Properties();
   properties.load(Resources.newInputStreamSupplier(Resources.getResource(filename)).getInput());
   properties.putAll(System.getProperties());
   return properties;
 }
Esempio n. 10
0
 @Override
 public InputSupplier<InputStream> getResource(String name) throws IOException {
   return Resources.newInputStreamSupplier(
       Resources.getResource((groupId + "/" + name).replace('.', '/')));
 }
Esempio n. 11
0
 private void copy(String resourceName, File dest) throws IOException {
   Files.copy(Resources.newInputStreamSupplier(Resources.getResource(resourceName)), dest);
 }
Esempio n. 12
0
 public static InputSupplier<InputStream> inputStreamTo(URL url) {
   return Resources.newInputStreamSupplier(url);
 }