Java Code Examples for org.apache.commons.io.FileUtils

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project accesointeligente, under directory /src/org/accesointeligente/server/robots/.

Source file: ResponseChecker.java

  15 
vote

private Attachment cloneAttachment(Attachment attachment){
  org.hibernate.Session hibernate=HibernateUtil.getSession();
  hibernate.beginTransaction();
  Attachment newAttachment=new Attachment();
  hibernate.save(newAttachment);
  hibernate.getTransaction().commit();
  File oldFile=new File(ApplicationProperties.getProperty("attachment.directory") + attachment.getId().toString() + "/"+ attachment.getName());
  File newDirectory=new File(ApplicationProperties.getProperty("attachment.directory") + newAttachment.getId().toString());
  try {
    newDirectory.mkdir();
    FileUtils.copyFileToDirectory(oldFile,newDirectory);
  }
 catch (  Exception e) {
    hibernate=HibernateUtil.getSession();
    hibernate.beginTransaction();
    hibernate.delete(attachment);
    hibernate.getTransaction().commit();
    logger.error("Error saving " + newDirectory.getAbsolutePath() + "/"+ attachment.getName(),e);
    return null;
  }
  String baseUrl=ApplicationProperties.getProperty("attachment.baseurl") + newAttachment.getId().toString();
  newAttachment.setName(attachment.getName());
  newAttachment.setType(attachment.getType());
  newAttachment.setUrl(baseUrl + "/" + newAttachment.getName());
  hibernate=HibernateUtil.getSession();
  hibernate.beginTransaction();
  hibernate.update(newAttachment);
  hibernate.getTransaction().commit();
  return newAttachment;
}
 

Example 2

From project AdServing, under directory /modules/tools/import/src/main/java/net/mad/ads/base/api/importer/.

Source file: Importer.java

  15 
vote

private JsonElement getJsonObject(File jobFile){
  try {
    String jsonContent=FileUtils.readFileToString(jobFile,"UTF-8");
    Gson gson=GSON_BUILDER.create();
    JsonElement element=gson.fromJson(jsonContent,JsonElement.class);
    return element;
  }
 catch (  Exception e) {
    logger.error("",e);
  }
  return null;
}
 

Example 3

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.

Source file: DataManagement.java

  15 
vote

private void removeUploadedFiles(TableInfo table,int rowId){
  for (  BaseField field : table.getFields()) {
    if (field instanceof FileField) {
      String folderName=this.getWebAppRoot() + "uploads/" + table.getInternalTableName()+ "/"+ field.getInternalFieldName()+ "/"+ rowId;
      File folder=new File(folderName);
      if (folder.exists()) {
        try {
          FileUtils.deleteDirectory(folder);
        }
 catch (        IOException e) {
          logger.warn("Unable to remove " + folderName + " when removing field "+ table+ "."+ field+ ": "+ e);
        }
      }
    }
  }
}
 

Example 4

From project Aion-Extreme, under directory /AE-go_DataPack/gameserver/data/scripts/system/handlers/admincommands/.

Source file: SendRawPacket.java

  15 
vote

@Override public void executeCommand(Player admin,String[] params){
  if (params.length != 1) {
    PacketSendUtility.sendMessage(admin,"Usage: //raw [name]");
    return;
  }
  File file=new File(ROOT,params[0] + ".txt");
  if (!file.exists() || !file.canRead()) {
    PacketSendUtility.sendMessage(admin,"Wrong file selected.");
    return;
  }
  try {
    @SuppressWarnings({"unchecked"}) List<String> lines=FileUtils.readLines(file);
    SM_CUSTOM_PACKET packet=null;
    for (    String row : lines) {
      String[] tokens=row.substring(0,48).trim().split(" ");
      int len=tokens.length;
      for (int i=0; i < len; i++) {
        if (i == 0) {
          packet=new SM_CUSTOM_PACKET(Integer.valueOf(tokens[i],16));
        }
 else         if (i > 2) {
          packet.addElement(PacketElementType.C,"0x" + tokens[i]);
        }
      }
    }
    if (packet != null)     PacketSendUtility.sendPacket(admin,packet);
  }
 catch (  IOException e) {
    PacketSendUtility.sendMessage(admin,"An error has occurred.");
    logger.warn("IO Error.",e);
  }
}
 

Example 5

From project akubra, under directory /akubra-mux/src/test/java/org/akubraproject/mux/.

Source file: MuxStoreTCKTest.java

  15 
vote

private BlobStore createTxnStore(String name,BlobStore backingStore) throws IOException {
  File base=new File(System.getProperty("basedir"),"target");
  File dbDir=new File(base,name);
  FileUtils.deleteDirectory(dbDir);
  dbDir.getParentFile().mkdirs();
  System.setProperty("derby.stream.error.file",new File(base,"derby.log").toString());
  BlobStore store=new TransactionalStore(URI.create("urn:" + name),backingStore,dbDir.getPath());
  return store;
}
 

Example 6

From project ALP, under directory /workspace/alp-flexpilot/src/main/java/com/lohika/alp/flexpilot/pagefactory/.

Source file: FlexPilotFactoryJAXB.java

  15 
vote

public Object screenshot(TakesScreenshot takesScreenshot,String description){
  Screenshot screenshot=factory.createScreenshot();
  screenshot.setDescription(description);
  File tempFile=takesScreenshot.getScreenshotAs(OutputType.FILE);
  File attachmentFile=null;
  try {
    attachmentFile=LogFileAttachment.getAttachmentFile("","png");
    FileUtils.copyFile(tempFile,attachmentFile);
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  if (attachmentFile != null)   screenshot.setUrl(attachmentFile.getName());
  return screenshot;
}
 

Example 7

From project ANNIS, under directory /annis-gui/src/main/java/annis/gui/visualizers/component/.

Source file: AbstractDotVisualizer.java

  15 
vote

public void writeOutput(VisualizerInput input,OutputStream outstream){
  StringBuilder dot=new StringBuilder();
  try {
    File tmpInput=File.createTempFile("annis-dot-input",".dot");
    tmpInput.deleteOnExit();
    StringBuilder dotContent=new StringBuilder();
    createDotContent(input,dotContent);
    FileUtils.writeStringToFile(tmpInput,dotContent.toString());
    ProcessBuilder pBuilder=new ProcessBuilder(input.getMappings().getProperty("dotpath","dot"),"-Tpng",tmpInput.getCanonicalPath());
    pBuilder.redirectErrorStream(false);
    Process process=pBuilder.start();
    int resultCode=process.waitFor();
    if (resultCode != 0) {
      InputStream stderr=process.getErrorStream();
      StringBuilder errorMessage=new StringBuilder();
      for (int chr=stderr.read(); chr != -1; chr=stderr.read()) {
        errorMessage.append((char)chr);
      }
      if (!"".equals(errorMessage.toString())) {
        log.error("Could not execute dot graph-layouter.\ncommand line:\n{}\n\nstderr:\n{}\n\nstdin:\n{}",new Object[]{StringUtils.join(pBuilder.command()," "),errorMessage.toString(),dot.toString()});
      }
    }
    InputStream fileInput=process.getInputStream();
    for (int chr=fileInput.read(); chr != -1; chr=fileInput.read()) {
      outstream.write(chr);
    }
    fileInput.close();
    if (!tmpInput.delete()) {
      log.warn("Cannot delete " + tmpInput.getAbsolutePath());
    }
  }
 catch (  Exception ex) {
    log.error(null,ex);
  }
}
 

Example 8

From project api-sdk-java, under directory /api-sdk/src/main/java/com/smartling/api/sdk/file/commandline/.

Source file: RetrieveFile.java

  15 
vote

protected static File retrieve(String[] args) throws FileApiException, IOException {
  RetrieveFileParams retrieveFileParams=getParameters(args);
  File file=new File(retrieveFileParams.getPathToFile());
  FileApiClientAdapter smartlingFAPI=new FileApiClientAdapterImpl(retrieveFileParams.isProductionMode(),retrieveFileParams.getApiKey(),retrieveFileParams.getProjectId());
  StringResponse response=smartlingFAPI.getFile(file.getName(),retrieveFileParams.getLocale(),null);
  File translatedFile=new File(getTranslatedFilePath(file,retrieveFileParams.getLocale(),retrieveFileParams.getPathToStoreFile()));
  FileUtils.writeStringToFile(translatedFile,response.getContents(),response.getEncoding());
  return translatedFile;
}
 

Example 9

From project apollo, under directory /injector/src/main/java/com/bskyb/cg/environments/hash/.

Source file: PersistentHash.java

  15 
vote

private synchronized void refreshStore() throws IOException {
  String refreshedDirName=dirname + TEMPFILEPOSTFIX;
  writeHash(refreshedDirName);
  File refreshedDir=new File(refreshedDirName);
  File originalDir=new File(dirname);
  FileUtils.deleteDirectory(originalDir);
  if (!refreshedDir.renameTo(originalDir)) {
    throw new IOException("Unable to rename " + refreshedDir + " to "+ dirname);
  }
}
 

Example 10

From project aranea, under directory /core/src/main/java/no/dusken/aranea/service/.

Source file: StoreImageServiceImpl.java

  15 
vote

public Image changeImage(File file,Image image) throws IOException {
  String hash=MD5.asHex(MD5.getHash(file));
  if (isBlank(hash)) {
    throw new IOException("Could not get hash from " + file.getAbsolutePath());
  }
  Image existingImage=imageService.getImageByHash(hash);
  if (existingImage != null) {
    log.info("Imported existing Image: {} from the user",existingImage.toString());
    file.delete();
    return existingImage;
  }
 else {
    image.setHash(hash);
    BufferedImage rendImage=ImageIO.read(file);
    image.setHeight(rendImage.getHeight());
    image.setWidth(rendImage.getWidth());
    image.setFileSize(file.length());
    FileUtils.copyFile(file,new File(imageDirectory + "/" + image.getUrl()));
    file.delete();
    log.debug("Imported Image: {} from {}",image.toString(),file.getAbsolutePath());
    return imageService.saveOrUpdate(image);
  }
}
 

Example 11

From project Arecibo, under directory /collector/src/main/java/com/ning/arecibo/collector/persistent/.

Source file: EventReplayingLoadGenerator.java

  15 
vote

public void generateEventStream(){
  resetSecondCounter();
  replayIterationStartTime=new DateTime();
  for (int i=0; i < REPLAY_REPEAT_COUNT; i++) {
    final Collection<File> files=FileUtils.listFiles(new File(REPLAY_FILE_DIRECTORY),new String[]{"bin"},false);
    firstReplayEventTimestamp=null;
    resetSecondCounter();
    for (    final File file : Replayer.FILE_ORDERING.sortedCopy(files)) {
      try {
        log.info("About to read file %s",file.getAbsolutePath());
        replayer.read(file,new Function<HostSamplesForTimestamp,Void>(){
          @Override public Void apply(          HostSamplesForTimestamp hostSamples){
            if (shuttingDown.get()) {
              return null;
            }
            processSamples(hostSamples);
            return null;
          }
        }
);
      }
 catch (      IOException e) {
        log.warn(e,"Exception replaying file: %s",file.getAbsolutePath());
      }
      if (shuttingDown.get()) {
        log.info("Exiting generateEventStream() because shutdown is true");
      }
    }
    latestHostTimes.clear();
    replayIterationStartTime=lastEndTime.plusSeconds(30);
  }
}
 

Example 12

From project arquillian-extension-drone, under directory /drone-webdriver/src/main/java/org/jboss/arquillian/drone/webdriver/factory/remote/reusable/.

Source file: ReusedSessionPernamentFileStorage.java

  15 
vote

private byte[] readStore(File file) throws IOException {
  if (Validate.readable(file)) {
    return FileUtils.readFileToByteArray(file);
  }
  log.info("Reused session store is not available at " + file + ", a new one will be created.");
  return null;
}
 

Example 13

From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/result/storage/.

Source file: FileStorage.java

  15 
vote

@Override public String store(Test test,Pattern pattern,BufferedImage differenceImage){
  File directory=new File((String)properties.getProperty("file-storage-directory"));
  File addition=new File(test.getName() + "." + pattern.getName()+ ".png");
  File file=new File(directory,addition.getPath());
  try {
    FileUtils.forceMkdir(file.getParentFile());
    ImageIO.write(differenceImage,"PNG",file);
  }
 catch (  IOException e) {
    throw new IllegalStateException("was not able to write difference image");
  }
  return addition.getPath();
}
 

Example 14

From project as-subsystem, under directory /src/test/java/test/org/picketlink/as/subsystem/parser/.

Source file: AbstractPicketLinkSubsystemTestCase.java

  15 
vote

/** 
 * Returns a valid XML for the subsystem.
 * @return
 */
protected String getValidSubsystemXML(){
  String content=null;
  try {
    content=FileUtils.readFileToString(new File(Thread.currentThread().getContextClassLoader().getResource("picketlink-subsystem.xml").getFile()));
  }
 catch (  IOException e) {
    Assert.fail("Error while reading the subsystem configuration file.");
  }
  return content;
}
 

Example 15

From project asadmin, under directory /asadmin-java/src/main/java/org/n0pe/asadmin/commands/.

Source file: CreateFileUser.java

  15 
vote

@Override public String handlePasswordFile(String configuredPasswordFile) throws AsAdminException {
  try {
    File passwordTempFile=File.createTempFile("asadmin-create-file-user",".pwd");
    passwordTempFile.deleteOnExit();
    FileUtils.copyFile(new File(configuredPasswordFile),passwordTempFile);
    BufferedWriter out=new BufferedWriter(new FileWriter(passwordTempFile));
    out.write("AS_ADMIN_USERPASSWORD=" + new String(password));
    out.close();
    return passwordTempFile.getAbsolutePath();
  }
 catch (  IOException ex) {
    throw new AsAdminException("Unable to handle password file for CreateFileUser command",ex);
  }
}
 

Example 16

From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/keypairs/.

Source file: KeyPairManager.java

  15 
vote

/** 
 * Attempts to convert any legacy private key files by renaming them.
 */
public static void convertLegacyPrivateKeyFiles() throws IOException {
  String accountId=AwsToolkitCore.getDefault().getCurrentAccountId();
  File pluginStateLocation=Ec2Plugin.getDefault().getStateLocation().toFile();
  File keyPairsFile=new File(pluginStateLocation,getKeyPropertiesFileName(accountId));
  if (!keyPairsFile.exists()) {
    File legacyKeyPairsFile=new File(pluginStateLocation,"registeredKeyPairs.properties");
    if (legacyKeyPairsFile.exists()) {
      FileUtils.copyFile(legacyKeyPairsFile,keyPairsFile);
    }
  }
}
 

Example 17

From project azkaban, under directory /azkaban/src/java/azkaban/app/.

Source file: JobManager.java

  15 
vote

public void deployJobDir(String localPath,String destPath){
  File targetPath=new File(this._jobDirs.get(0),destPath);
  verifyPathValidity(new File(localPath),targetPath);
  if (targetPath.exists()) {
    logger.info("Undeploying job at " + destPath);
    try {
      FileUtils.deleteDirectory(targetPath);
    }
 catch (    Exception e) {
      throw new RuntimeException(e);
    }
  }
  if (!targetPath.mkdirs())   throw new RuntimeException("Failed to create target directory " + targetPath);
  File currPath=new File(localPath);
  if (currPath.renameTo(targetPath))   logger.info(destPath + " deployed.");
 else   throw new RuntimeException("Deploy failed because " + currPath + " could not be moved to "+ destPath);
  updateFlowManager();
}
 

Example 18

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/servlet/.

Source file: RequestProcessors.java

  15 
vote

/** 
 * Scans classpath (classes directory) to discover request processor classes.
 */
private static void discoverFromClassesDir(){
  final String webRoot=AbstractServletListener.getWebRoot();
  final File classesDir=new File(webRoot + File.separator + "WEB-INF"+ File.separator+ "classes"+ File.separator);
  @SuppressWarnings("unchecked") final Collection<File> classes=FileUtils.listFiles(classesDir,new String[]{"class"},true);
  final ClassLoader classLoader=RequestProcessors.class.getClassLoader();
  try {
    for (    final File classFile : classes) {
      final String path=classFile.getPath();
      final String className=StringUtils.substringBetween(path,"WEB-INF" + File.separator + "classes"+ File.separator,".class").replaceAll("\\/",".").replaceAll("\\\\",".");
      final Class<?> clz=classLoader.loadClass(className);
      if (clz.isAnnotationPresent(RequestProcessor.class)) {
        LOGGER.log(Level.FINER,"Found a request processor[className={0}]",className);
        final Method[] declaredMethods=clz.getDeclaredMethods();
        for (int i=0; i < declaredMethods.length; i++) {
          final Method mthd=declaredMethods[i];
          final RequestProcessing annotation=mthd.getAnnotation(RequestProcessing.class);
          if (null == annotation) {
            continue;
          }
          addProcessorMethod(annotation,clz,mthd);
        }
      }
    }
  }
 catch (  final Exception e) {
    LOGGER.log(Level.SEVERE,"Scans classpath (classes directory) failed",e);
  }
}
 

Example 19

From project backup-plugin, under directory /src/main/java/org/jvnet/hudson/plugins/backup/utils/compress/.

Source file: AbstractUnArchiver.java

  15 
vote

public void unArchive(File archive,String toDir) throws ArchiverException {
  org.codehaus.plexus.archiver.AbstractUnArchiver unarchiver=getUnArchiver();
  File destDir=new File(toDir);
  if (!destDir.exists()) {
    try {
      FileUtils.forceMkdir(destDir);
    }
 catch (    IOException e) {
      String message="Unable to created directory " + destDir.getAbsolutePath();
      LOGGER.severe(message);
      throw new ArchiverException(message,e);
    }
  }
  unarchiver.enableLogging(new ConsoleLogger(org.codehaus.plexus.logging.Logger.LEVEL_INFO,"UnArchiver"));
  unarchiver.setSourceFile(archive);
  unarchiver.setDestDirectory(destDir);
  try {
    unarchiver.extract();
  }
 catch (  org.codehaus.plexus.archiver.ArchiverException e) {
    String message="Unable to extract " + archive.getAbsolutePath() + " content to "+ toDir;
    LOGGER.log(Level.SEVERE,message,e);
    throw new ArchiverException(message,e);
  }
catch (  Exception e) {
    LOGGER.severe(e.getMessage());
  }
}
 

Example 20

From project bdd-security, under directory /src/main/java/net/continuumsecurity/runner/.

Source file: StoryRunner.java

  15 
vote

private void copyResultsToStampedReportsDir() throws IOException {
  SimpleDateFormat formatter=new SimpleDateFormat("yyyy.MM.dd-HH.mm.ss",Locale.getDefault());
  File dirName=new File(REPORTS_DIR + File.separator + formatter.format(new Date()));
  FileUtils.forceMkdir(dirName);
  FileUtils.copyDirectory(new File(LATEST_REPORTS),dirName);
}
 

Example 21

From project bioportal-service, under directory /src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/rest/.

Source file: BioportalRestService.java

  15 
vote

/** 
 * Gets the last update.
 * @return the last update
 */
protected Date getLastUpdate(){
  File file=this.getUpdateLogFile();
  if (!file.exists()) {
    return null;
  }
 else {
    byte[] data;
    try {
      data=FileUtils.readFileToByteArray(file);
    }
 catch (    IOException e) {
      throw new RuntimeException(e);
    }
    Date date=(Date)SerializationUtils.deserialize(data);
    return date;
  }
}
 

Example 22

From project BlameSubversion-plugin, under directory /src/main/java/hudson/scm/.

Source file: BlameSubversionSCM.java

  15 
vote

/** 
 * @param keyFile stores SSH private key. The file will be copied.
 */
public SshPublicKeyCredential(String userName,String passphrase,File keyFile) throws SVNException {
  this.userName=userName;
  this.passphrase=Scrambler.scramble(passphrase);
  Random r=new Random();
  StringBuilder buf=new StringBuilder();
  for (int i=0; i < 16; i++)   buf.append(Integer.toHexString(r.nextInt(16)));
  this.id=buf.toString();
  try {
    FileUtils.copyFile(keyFile,getKeyFile());
  }
 catch (  IOException e) {
    throw new SVNException(SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to save private key"),e);
  }
}
 

Example 23

From project Blister, under directory /code/modules/src/main/java/uk/co/sromo/blister/.

Source file: App.java

  15 
vote

private void doMain(String[] args){
  CmdLineParser parser=new CmdLineParser(this);
  parser.setUsageWidth(160);
  try {
    parser.parseArgument(args);
    if (!input.exists()) {
      throw new CmdLineException("Input file didn't exist");
    }
switch (mode) {
case NONE:
      throw new CmdLineException("Mode not specified");
case ENCODE:
    throw new CmdLineException("Encoding not supported yet");
case DECODE:
  byte[] bytes=FileUtils.readFileToByteArray(input);
BPItem root=BinaryPlist.decode(bytes);
String result=BinaryPlist.dump(root);
FileUtils.writeStringToFile(output,result);
break;
}
}
 catch (CmdLineException e) {
System.err.println(e.getMessage());
System.err.println("java App [options...] arguments...");
parser.printUsage(System.err);
System.err.println();
}
catch (Exception e) {
e.printStackTrace();
}
}
 

Example 24

From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/control/deploy/activebpel/.

Source file: BPRDeployRequestEntity.java

  15 
vote

@Override protected void populateMessage(SOAPMessage message) throws SOAPException, IOException {
  SOAPElement xmlDeployBpr=addRootElement(message,new QName(ACTIVEBPEL_ELEMENT_DEPLOYBPR));
  SOAPElement xmlBprFilename=xmlDeployBpr.addChildElement(ACTIVEBPEL_ELEMENT_ABPRFILENAME);
  xmlBprFilename.addAttribute(new QName(ActiveBPELRequestEntityBase.NS_XMLSCHEMA_INSTANCE,"type"),XSD_STRING);
  xmlBprFilename.setTextContent(FilenameUtils.getName(file.toString()));
  SOAPElement xmlBase64File=xmlDeployBpr.addChildElement(ACTIVEBPEL_ELEMENT_ABASE64FILE);
  xmlBase64File.addAttribute(new QName(ActiveBPELRequestEntityBase.NS_XMLSCHEMA_INSTANCE,"type"),XSD_STRING);
  StringBuilder content=new StringBuilder();
  byte[] arr=FileUtils.readFileToByteArray(file);
  byte[] encoded=Base64.encodeBase64Chunked(arr);
  for (int i=0; i < encoded.length; i++) {
    content.append((char)encoded[i]);
  }
  xmlBase64File.setTextContent(content.toString());
}
 

Example 25

From project c10n, under directory /core/src/test/java/c10n/resources/.

Source file: ExternalResourceTest.java

  15 
vote

@Test public void loadingExternalResource() throws IOException {
  C10N.configure(new DefaultC10NAnnotations());
  File englishText=new File(tmp.dir,"english.txt");
  FileUtils.writeStringToFile(englishText,"hello" + NL + "world!");
  File japaneseText=new File(tmp.dir,"japanese.txt");
  FileUtils.writeStringToFile(japaneseText,"konnichiwa" + NL + "world!");
  ExtMessages msg=C10N.get(ExtMessages.class);
  Locale.setDefault(Locale.ENGLISH);
  assertThat(msg.fromTextFile("substitute"),is("hello" + NL + "world!"));
  assertThat(msg.normalText(),is("english"));
  Locale.setDefault(Locale.JAPANESE);
  assertThat(msg.fromTextFile("substitute"),is("konnichiwa" + NL + "world!"));
  assertThat(msg.normalText(),is("japanese"));
}
 

Example 26

From project c2dm4j, under directory /src/main/java/org/whispercomm/c2dm4j/auth/.

Source file: FileAuthTokenProvider.java

  15 
vote

@Override protected AuthToken readToken() throws IOException {
  try {
    return new AuthToken(FileUtils.readFileToString(file,ENCODING).trim());
  }
 catch (  IOException e) {
    String msg=String.format("Failed to read C2DM authentication token from file %s",this.file);
    LOGGER.warn(msg);
    throw new IOException(msg,e);
  }
}
 

Example 27

From project candlepin, under directory /src/main/java/org/candlepin/util/.

Source file: CrlFileUtil.java

  15 
vote

public byte[] writeCRLFile(File file,X509CRL crl) throws CRLException, CertificateException, IOException {
  byte[] encoded=pkiUtility.getPemEncoded(crl);
  ByteArrayOutputStream stream=new ByteArrayOutputStream();
  try {
    stream.write(encoded);
    log.info("Completed generating CRL. Writing it to disk");
    FileUtils.writeByteArrayToFile(file,stream.toByteArray());
  }
  finally {
    if (stream != null) {
      try {
        stream.close();
      }
 catch (      IOException e) {
        log.error("exception when closing a CRL file: " + file.getAbsolutePath());
      }
    }
  }
  return encoded;
}
 

Example 28

From project cascading, under directory /src/test/cascading/.

Source file: ComparePlatformsTest.java

  15 
vote

public static Test suite() throws Exception {
  String root=getTestRoot();
  File localRoot=new File(root + "/local");
  File hadoopRoot=new File(root + "/hadoop");
  LinkedList<File> localFiles=new LinkedList<File>(FileUtils.listFiles(localRoot,new RegexFileFilter("^[\\w-]+"),TrueFileFilter.INSTANCE));
  LinkedList<File> hadoopFiles=new LinkedList<File>();
  int rootLength=localRoot.toString().length() + 1;
  ListIterator<File> iterator=localFiles.listIterator();
  while (iterator.hasNext()) {
    File localFile=iterator.next();
    File file=new File(hadoopRoot,localFile.toString().substring(rootLength));
    if (localFile.toString().endsWith(NONDETERMINISTIC))     iterator.remove();
 else     if (file.exists())     hadoopFiles.add(file);
 else     iterator.remove();
  }
  LOG.info("running {} comparisons",localFiles.size());
  TestSuite suite=new TestSuite();
  for (int i=0; i < localFiles.size(); i++) {
    File localFile=localFiles.get(i);
    File hadoopFile=hadoopFiles.get(i);
    suite.addTest(new CompareTestCase(localFile,hadoopFile));
  }
  return suite;
}
 

Example 29

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/datacollection/adaptor/.

Source file: DirTailingAdaptor.java

  15 
vote

private void scanDirHierarchy(File dir) throws IOException {
  if (!dir.exists())   return;
  if (!dir.isDirectory()) {
    if (dir.lastModified() >= lastSweepStartTime) {
      String newAdaptorID=control.processAddCommand(getAdaptorAddCommand(dir));
      log.info("DirTailingAdaptor " + adaptorID + "  started new adaptor "+ newAdaptorID);
    }
  }
 else {
    log.info("Scanning directory: " + dir.getName());
    for (    Object f : FileUtils.listFiles(dir,fileFilter,FileFilterUtils.trueFileFilter())) {
      scanDirHierarchy((File)f);
    }
  }
}
 

Example 30

From project cloudbees-deployer-plugin, under directory /src/main/java/org/jenkins/plugins/cloudbees/.

Source file: CloudbeesDeployer.java

  15 
vote

private void doDeploy(AbstractBuild<?,?> build,BuildListener listener,String warPath) throws IOException {
  CloudbeesApiHelper.CloudbeesApiRequest apiRequest=new CloudbeesApiHelper.CloudbeesApiRequest(CloudbeesApiHelper.CLOUDBEES_API_URL,cloudbeesAccount.apiKey,cloudbeesAccount.secretKey);
  File tmpArchive=File.createTempFile("jenkins","temp-cloudbees-deploy");
  try {
    Node buildNode=Hudson.getInstance().getNode(build.getBuiltOnStr());
    FilePath filePath=new FilePath(tmpArchive);
    FilePath remoteWar=build.getWorkspace().child(warPath);
    remoteWar.copyTo(filePath);
    warPath=tmpArchive.getPath();
    listener.getLogger().println(Messages.CloudbeesPublisher_Deploying(applicationId));
    String description="Jenkins build " + build.getId();
    CloudbeesApiHelper.getBeesClient(apiRequest).applicationDeployWar(applicationId,"environnement",description,warPath,warPath,new ConsoleListenerUploadProgress(listener));
    CloudbeesDeployerAction cloudbeesDeployerAction=new CloudbeesDeployerAction(applicationId);
    cloudbeesDeployerAction.setDescription(description);
    build.addAction(cloudbeesDeployerAction);
  }
 catch (  Exception e) {
    listener.getLogger().println("issue during deploying war " + e.getMessage());
    throw new IOException2(e.getMessage(),e);
  }
 finally {
    FileUtils.deleteQuietly(tmpArchive);
  }
}
 

Example 31

From project cloudify, under directory /CLI/src/main/java/org/cloudifysource/shell/commands/.

Source file: InstallApplication.java

  15 
vote

private File createCloudConfigurationZipFile() throws CLIStatusException, IOException {
  if (this.cloudConfiguration == null) {
    return null;
  }
  if (!this.cloudConfiguration.exists()) {
    throw new CLIStatusException("cloud_configuration_file_not_found",this.cloudConfiguration.getAbsolutePath());
  }
  final File tempDir=File.createTempFile("__Cloudify_Cloud_configuration",".tmp");
  FileUtils.forceDelete(tempDir);
  tempDir.mkdirs();
  final File tempFile=new File(tempDir,CloudifyConstants.SERVICE_CLOUD_CONFIGURATION_FILE_NAME);
  tempFile.deleteOnExit();
  tempDir.deleteOnExit();
  if (this.cloudConfiguration.isDirectory()) {
    ZipUtils.zip(this.cloudConfiguration,tempFile);
  }
 else   if (this.cloudConfiguration.isFile()) {
    ZipUtils.zipSingleFile(this.cloudConfiguration,tempFile);
  }
 else {
    throw new IOException(this.cloudConfiguration + " is neither a file nor a directory");
  }
  return tempFile;
}
 

Example 32

From project collector, under directory /src/main/java/com/ning/metrics/collector/hadoop/processing/.

Source file: LocalSpoolManager.java

  15 
vote

public static Collection<File> findFilesInSpoolDirectory(final File spoolDirectory){
  if (!spoolDirectory.isDirectory()) {
    log.warn("Asked to find files in spool directory but [" + spoolDirectory + "] is not a directory!");
    return Collections.emptyList();
  }
  return FileUtils.listFiles(spoolDirectory,FileFilterUtils.trueFileFilter(),FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter("_tmp")));
}
 

Example 33

From project com.cedarsoft.serialization, under directory /generator/common/src/test/java/com/cedarsoft/serialization/generator/common/.

Source file: DaGeneratorTest.java

  15 
vote

@Before public void setUp() throws Exception {
  myGenerator=new MyGenerator();
  sourceFile=tmp.newFile("MyClass.java");
  FileUtils.writeByteArrayToFile(sourceFile,IOUtils.toByteArray(getClass().getResourceAsStream("MyClass.java")));
  List<File> sourceFiles=Lists.newArrayList(sourceFile);
  out=new StringWriter();
  generatorConfiguration=new GeneratorConfiguration(sourceFiles,tmp.newFolder("dest"),tmp.newFolder("resources-dest"),tmp.newFolder("test-dest"),tmp.newFolder("test-resources-dest"),null,new PrintWriter(out));
}
 

Example 34

From project commons-io, under directory /src/main/java/org/apache/commons/io/comparator/.

Source file: SizeFileComparator.java

  15 
vote

/** 
 * Compare the length of two files.
 * @param file1 The first file to compare
 * @param file2 The second file to compare
 * @return a negative value if the first file's lengthis less than the second, zero if the lengths are the same and a positive value if the first files length is greater than the second file.
 */
public int compare(File file1,File file2){
  long size1=0;
  if (file1.isDirectory()) {
    size1=sumDirectoryContents && file1.exists() ? FileUtils.sizeOfDirectory(file1) : 0;
  }
 else {
    size1=file1.length();
  }
  long size2=0;
  if (file2.isDirectory()) {
    size2=sumDirectoryContents && file2.exists() ? FileUtils.sizeOfDirectory(file2) : 0;
  }
 else {
    size2=file2.length();
  }
  long result=size1 - size2;
  if (result < 0) {
    return -1;
  }
 else   if (result > 0) {
    return 1;
  }
 else {
    return 0;
  }
}
 

Example 35

From project components-ness-pg, under directory /pg-embedded/src/main/java/com/nesscomputing/db/postgres/embedded/.

Source file: EmbeddedPostgreSQL.java

  15 
vote

@Override public void close() throws IOException {
  if (closed.getAndSet(true)) {
    return;
  }
  StopWatch watch=new StopWatch();
  watch.start();
  try {
    pgCtl(dataDirectory,"stop");
    LOG.info("%s shut down postmaster in %s",instanceId,watch);
  }
 catch (  Exception e) {
    LOG.error(e,"Could not stop postmaster %s",instanceId);
  }
  if (lock != null) {
    lock.release();
  }
  Closeables.closeQuietly(lockStream);
  if (System.getProperty("ness.epg.no-cleanup") == null) {
    FileUtils.deleteDirectory(dataDirectory);
  }
 else {
    LOG.info("Did not clean up directory %s",dataDirectory.getAbsolutePath());
  }
}
 

Example 36

From project core_5, under directory /exo.core.component.organization.ldap/src/test/java/org/exoplatform/services/organization/.

Source file: DummyLDAPServiceImpl.java

  15 
vote

protected void doDelete(File wkdir) throws IOException {
  if (doDelete) {
    if (wkdir.exists()) {
      FileUtils.deleteDirectory(wkdir);
    }
    if (wkdir.exists()) {
      throw new IOException("Failed to delete: " + wkdir);
    }
  }
}
 

Example 37

From project couchdb-lucene, under directory /src/main/java/com/github/rnewson/couchdb/lucene/.

Source file: LuceneServlet.java

  15 
vote

private void cleanup(final HttpServletRequest req,final HttpServletResponse resp) throws IOException, JSONException {
  final Couch couch=getCouch(req);
  final Set<String> dbKeep=new HashSet<String>();
  final JSONArray databases=couch.getAllDatabases();
  for (int i=0; i < databases.length(); i++) {
    final Database db=couch.getDatabase(databases.getString(i));
    final UUID uuid=db.getUuid();
    if (uuid == null) {
      continue;
    }
    dbKeep.add(uuid.toString());
    final Set<String> viewKeep=new HashSet<String>();
    for (    final DesignDocument ddoc : db.getAllDesignDocuments()) {
      for (      final View view : ddoc.getAllViews().values()) {
        viewKeep.add(view.getDigest());
      }
    }
    final File[] dirs=DatabaseIndexer.uuidDir(root,db.getUuid()).listFiles();
    if (dirs != null) {
      for (      final File dir : dirs) {
        if (!viewKeep.contains(dir.getName())) {
          LOG.info("Cleaning old index at " + dir);
          FileUtils.deleteDirectory(dir);
        }
      }
    }
  }
  for (  final File dir : root.listFiles()) {
    if (!dbKeep.contains(dir.getName())) {
      LOG.info("Cleaning old index at " + dir);
      FileUtils.deleteDirectory(dir);
    }
  }
  resp.setStatus(202);
  ServletUtils.sendJsonSuccess(req,resp);
}
 

Example 38

From project Cyborg, under directory /src/main/java/com/alta189/cyborg/api/plugin/.

Source file: CommonPluginManager.java

  15 
vote

public synchronized Plugin loadPlugin(File paramFile,boolean ignoresoftdepends) throws InvalidPluginException, InvalidDescriptionFileException, UnknownDependencyException {
  File update=null;
  if (updateDir != null && updateDir.isDirectory()) {
    update=new File(updateDir,paramFile.getName());
    if (update.exists() && update.isFile()) {
      try {
        FileUtils.copyFile(update,paramFile);
      }
 catch (      IOException e) {
        CyborgLogger.getLogger().log(Level.SEVERE,new StringBuilder().append("Error copying file '").append(update.getPath()).append("' to its new destination at '").append(paramFile.getPath()).append("': ").append(e.getMessage()).toString(),e);
      }
      update.delete();
    }
  }
  Set<Pattern> patterns=loaders.keySet();
  Plugin result=null;
  for (  Pattern pattern : patterns) {
    String name=paramFile.getName();
    Matcher m=pattern.matcher(name);
    if (m.find()) {
      PluginLoader loader=loaders.get(pattern);
      result=loader.loadPlugin(paramFile,ignoresoftdepends);
      if (result != null) {
        break;
      }
    }
  }
  if (result != null) {
    plugins.add(result);
    names.put(result.getDescription().getName(),result);
  }
  return result;
}
 

Example 39

From project data-access, under directory /test-src/org/pentaho/platform/dataaccess/datasource/wizard/csv/.

Source file: SerializeMultiTableServiceTest.java

  15 
vote

@Test public void testSerialize() throws Exception {
  try {
    KettleEnvironment.init();
    Props.init(Props.TYPE_PROPERTIES_EMPTY);
  }
 catch (  Exception e) {
  }
  String solutionStorage=AgileHelper.getDatasourceSolutionStorage();
  String path=solutionStorage + ISolutionRepository.SEPARATOR + "resources"+ ISolutionRepository.SEPARATOR+ "metadata"+ ISolutionRepository.SEPARATOR;
  String olapPath=null;
  IApplicationContext appContext=PentahoSystem.getApplicationContext();
  if (appContext != null) {
    path=PentahoSystem.getApplicationContext().getSolutionPath(path);
    olapPath=PentahoSystem.getApplicationContext().getSolutionPath("system" + ISolutionRepository.SEPARATOR + "olap"+ ISolutionRepository.SEPARATOR);
  }
  File olap1=new File(olapPath + "datasources.xml");
  File olap2=new File(olapPath + "tmp_datasources.xml");
  FileUtils.copyFile(olap1,olap2);
  DatabaseMeta database=getDatabaseMeta();
  MultiTableModelerSource multiTable=new MultiTableModelerSource(database,getSchema(),database.getName(),Arrays.asList("CUSTOMERS","PRODUCTS","CUSTOMERNAME","PRODUCTCODE"));
  Domain domain=multiTable.generateDomain();
  List<OlapDimension> olapDimensions=new ArrayList<OlapDimension>();
  OlapDimension dimension=new OlapDimension();
  dimension.setName("test");
  dimension.setTimeDimension(false);
  olapDimensions.add(dimension);
  domain.getLogicalModels().get(0).setProperty("olap_dimensions",olapDimensions);
  ModelerService service=new ModelerService();
  service.serializeModels(domain,"test_file");
  Assert.assertEquals(domain.getLogicalModels().get(0).getProperty("MondrianCatalogRef"),"SampleData");
}
 

Example 40

From project datasalt-utils, under directory /src/contrib/java/org/apache/solr/common/cloud/.

Source file: SolrZkClient.java

  15 
vote

/** 
 * Write file to ZooKeeper - default system encoding used.
 * @param path path to upload file to e.g. /solr/conf/solrconfig.xml
 * @param file path to file to be uploaded
 * @throws IOException
 * @throws KeeperException
 * @throws InterruptedException
 */
public void setData(String path,File file) throws IOException, KeeperException, InterruptedException {
  if (log.isInfoEnabled()) {
    log.info("Write to ZooKeepeer " + file.getAbsolutePath() + " to "+ path);
  }
  String data=FileUtils.readFileToString(file);
  setData(path,data.getBytes("UTF-8"));
}
 

Example 41

From project DB-Builder, under directory /src/main/java/org/silverpeas/dbbuilder/util/.

Source file: DynamicLoader.java

  15 
vote

public DynamicLoader(){
  File jarDirectory=new File(Configuration.getPiecesFilesDir(),JAR_DIRECTORY);
  URL[] classpath=new URL[]{};
  if (jarDirectory.exists() && jarDirectory.isDirectory()) {
    @SuppressWarnings("unchecked") Collection<File> jars=FileUtils.listFiles(jarDirectory,new String[]{"jar"},true);
    List<URL> urls=new ArrayList<URL>(jars.size());
    DBBuilder.printMessage("We have found " + jars.size() + " jars files");
    for (    File jar : jars) {
      try {
        urls.add(jar.toURI().toURL());
        for (        URL url : urls) {
          DBBuilder.printError(url.toString());
        }
      }
 catch (      MalformedURLException ex) {
        Logger.getLogger(DynamicLoader.class.getName()).log(Level.SEVERE,null,ex);
      }
    }
    classpath=urls.toArray(new URL[urls.size()]);
  }
  ClassLoader parent=Thread.currentThread().getContextClassLoader();
  if (parent == null) {
    parent=getClass().getClassLoader();
  }
  loader=new URLClassLoader(classpath,parent);
}
 

Example 42

From project Diktofon, under directory /app/src/kaljurand_at_gmail_dot_com/diktofon/.

Source file: MyFileUtils.java

  15 
vote

public static String getSizeAsString(long size){
  String sizeAsString;
  if (size > FileUtils.ONE_MB) {
    sizeAsString=(long)(size / FileUtils.ONE_MB) + "MB";
  }
 else   if (size > FileUtils.ONE_KB) {
    sizeAsString=(long)(size / FileUtils.ONE_KB) + "kB";
  }
 else {
    sizeAsString=size + "b";
  }
  if (size > NetSpeechApiUtils.MAX_AUDIO_FILE_LENGTH) {
    sizeAsString+=" !!!";
  }
  return sizeAsString;
}
 

Example 43

From project dimdwarf, under directory /test-utils/src/main/java/net/orfjackal/dimdwarf/testutils/.

Source file: Sandbox.java

  15 
vote

private static void retryingForceDelete(File dir) throws IOException {
  long limit=System.currentTimeMillis() + 1000;
  IOException unableToDelete;
  do {
    try {
      FileUtils.forceDelete(dir);
      return;
    }
 catch (    IOException e) {
      System.err.println("WARNING: " + e.getMessage() + " Retrying...");
      unableToDelete=e;
    }
    sleep(10);
  }
 while (System.currentTimeMillis() < limit);
  throw unableToDelete;
}
 

Example 44

From project EasySOA, under directory /easysoa-proxy/easysoa-proxy-core/easysoa-proxy-core-httpdiscoveryproxy-test/src/test/java/org/easysoa/test/util/.

Source file: AbstractProxyTestStarter.java

  15 
vote

/** 
 * Start FraSCAti
 * @throws Exception
 */
protected void startFraSCAti() throws Exception {
  if (frascati == null) {
    char sep=File.separatorChar;
    configure();
    StringBuilder srcBuilder=new StringBuilder("target").append(sep).append("test-classes").append(sep).append("easysoa-proxy-core-httpdiscoveryproxy.jar");
    File srcFile=new File(srcBuilder.toString());
    FileUtils.copyFileToDirectory(srcFile.getAbsoluteFile(),remoteFrascatiLibDir);
    StringBuilder libBuilder=new StringBuilder(remoteFrascatiLibDir.getAbsolutePath()).append(sep).append("easysoa-proxy-core-httpdiscoveryproxy.jar");
    lib=new File(libBuilder.toString());
    logger.info("FraSCATI Starting");
    componentList=new ArrayList<Composite>();
    serviceProvider=new RemoteFraSCAtiServiceProvider(null);
    frascati=serviceProvider.getFraSCAtiService();
  }
}
 

Example 45

From project Ebselen, under directory /ebselen-core/src/main/java/com/lazerycode/ebselen/handlers/.

Source file: FileHandler.java

  15 
vote

/** 
 * Copy the file to a specific location
 * @param absoluteFileName - Target location for copy.
 * @return
 * @throws Exception
 */
public boolean copyFileTo(String absoluteFileName) throws Exception {
  if (this.fileIsReadable != true) {
    this.openFile();
  }
  File fileDestination=new File(absoluteFileName);
  if (this.currentFile.exists()) {
    if (this.currentFile.canRead()) {
      try {
        FileUtils.copyFile(this.currentFile,fileDestination);
        return true;
      }
 catch (      Exception Ex) {
        LOGGER.warn("Failed to copy file to '{}'",absoluteFileName);
        return false;
      }
    }
 else {
      LOGGER.error("Unable to read '{}'",this.filePath + this.fileName);
      throw new IOException("Unable to read file " + this.filePath + this.fileName);
    }
  }
 else {
    LOGGER.error("'{}' does not exist!",this.filePath + this.fileName);
    throw new IOException(this.filePath + this.fileName + "does not exist!");
  }
}
 

Example 46

From project eclipse-integration-gradle, under directory /org.springsource.ide.eclipse.gradle.core/src/org/springsource/ide/eclipse/gradle/core/samples/.

Source file: LocalSample.java

  15 
vote

@Override public void createAt(final File location) throws CoreException {
  try {
    FileUtils.copyDirectory(copyFrom,location);
  }
 catch (  Exception e) {
    throw ExceptionUtil.coreException(e);
  }
}
 

Example 47

From project embedmongo.flapdoodle.de, under directory /src/main/java/de/flapdoodle/embedmongo/.

Source file: Files.java

  15 
vote

public static boolean forceDelete(File fileOrDir){
  boolean ret=false;
  try {
    if (fileOrDir != null) {
      FileUtils.forceDelete(fileOrDir);
      _logger.info("Could delete " + fileOrDir);
      ret=true;
    }
  }
 catch (  IOException e) {
    _logger.warning("Could not delete " + fileOrDir + ". Will try to delete it again when program exits.");
    try {
      FileUtils.forceDeleteOnExit(fileOrDir);
      ret=true;
    }
 catch (    IOException ioe) {
      _logger.severe("Could not delete " + fileOrDir);
      throw new IllegalStateException("Could not delete " + fileOrDir);
    }
  }
  return ret;
}
 

Example 48

From project enterprise, under directory /backup/src/test/java/org/neo4j/backup/.

Source file: TestBackup.java

  15 
vote

@Test public void backupEmptyIndex() throws Exception {
  String key="name";
  String value="Neo";
  GraphDatabaseService db=new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(serverPath).setConfig(OnlineBackupSettings.online_backup_enabled,GraphDatabaseSetting.TRUE).newGraphDatabase();
  Index<Node> index=db.index().forNodes(key);
  Transaction tx=db.beginTx();
  Node node=db.createNode();
  node.setProperty(key,value);
  tx.success();
  tx.finish();
  OnlineBackup.from("localhost").full(backupPath);
  assertEquals(DbRepresentation.of(db),DbRepresentation.of(backupPath));
  FileUtils.deleteDirectory(new File(backupPath));
  OnlineBackup.from("localhost").full(backupPath);
  assertEquals(DbRepresentation.of(db),DbRepresentation.of(backupPath));
  tx=db.beginTx();
  index.add(node,key,value);
  tx.success();
  tx.finish();
  FileUtils.deleteDirectory(new File(backupPath));
  OnlineBackup.from("localhost").full(backupPath);
  assertEquals(DbRepresentation.of(db),DbRepresentation.of(backupPath));
  db.shutdown();
}
 

Example 49

From project farebot, under directory /src/com/codebutler/farebot/fragments/.

Source file: CardsFragment.java

  15 
vote

@Override public void onActivityResult(int requestCode,int resultCode,Intent data){
  try {
    if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_SELECT_FILE) {
      Uri uri=data.getData();
      String xml=org.apache.commons.io.FileUtils.readFileToString(new File(uri.getPath()));
      onCardsImported(ExportHelper.importCardsXml(getActivity(),xml));
    }
  }
 catch (  Exception ex) {
    Utils.showError(getActivity(),ex);
  }
}
 

Example 50

From project fastjson, under directory /src/test/java/com/alibaba/json/test/performance/case1/.

Source file: GenerateTest.java

  15 
vote

public void testGenInt() throws Exception {
  JSONObject json=new JSONObject(true);
  for (int i=0; i < 100; ++i) {
    json.put("f" + i,i);
  }
  String text=JSON.toJSONString(json,false);
  System.out.println(text);
  FileUtils.writeStringToFile(new File("d:/int_array_1000.json"),text);
}
 

Example 51

From project fedora-client, under directory /fedora-client-core/src/test/java/com/yourmediashelf/fedora/util/.

Source file: XmlSerializerTest.java

  15 
vote

private void testCanonicalization(String prefix) throws Exception {
  String input=String.format("%s-input.xml",prefix);
  String canonical=String.format("%s-canonical.xml",prefix);
  InputStream in=new FileInputStream(new File(testDir,input));
  ByteArrayOutputStream bout=new ByteArrayOutputStream();
  XmlSerializer.canonicalize(in,bout);
  String control=FileUtils.readFileToString(new File(testDir,canonical));
  assertEquals(input + " did not match " + canonical,control,bout.toString("UTF-8"));
}
 

Example 52

From project flexmojos, under directory /flexmojos-maven-plugin/src/main/java/net/flexmojos/oss/plugin/source/.

Source file: SourceViewMojo.java

  15 
vote

/** 
 * Syntax highlight and/or copy the source file to the target directory.
 * @param file The file to process.
 * @param targetDirectory The directory where to store the output.
 * @throws IOException If there was a file read/write exception.
 */
protected void processFile(File file,File targetDirectory) throws IOException {
  getLog().debug("Processing file " + file.getName());
  String destinationFilePath=targetDirectory.getCanonicalPath() + File.separator + file.getName();
  String extension=file.getName().substring(file.getName().lastIndexOf('.') + 1);
  String highlightFilter=getHighlightFilter(extension);
  if (highlightFilter != null) {
    getLog().debug("Converting " + file.getName() + "to HTML.");
    destinationFilePath+=".html";
    XhtmlRendererFactory.getRenderer(highlightFilter).highlight(file.getName(),new FileInputStream(file),new FileOutputStream(destinationFilePath),Charset.forName(outputEncoding).name(),false);
  }
 else {
    getLog().debug("Copying " + file.getName());
    FileUtils.copyFileToDirectory(file,targetDirectory);
  }
}
 

Example 53

From project FlipDroid, under directory /app/src/com/goal98/flipdroid2/model/rss/.

Source file: RssParser.java

  15 
vote

public static void main(String[] args){
  String url="\t\n" + "http://feed.feedsky.com/alibuybuy";
  String cat="????";
  String template=",{\n" + "        \"name\": \"$name\",\n" + "        \"id\": \"$id\",\n"+ "        \"desc\": \"$desc\",\n"+ "        \"image_url\": \"$imageUrl\",\n"+ "        \"content_url\":\"$contentUrl\",\n"+ "        \"cat\":\"$cat\"\n"+ "    }";
  RssParser rp=new RssParser(url);
  try {
    rp.parse();
    RssParser.RssFeed feed=rp.getFeed();
    final String title=feed.title;
    final String description=feed.description == null ? "" : feed.description;
    final String imageUrl=feed.imageUrl == null ? "" : feed.imageUrl;
    final String contentUrl=url;
    String json=template.replace("$name",title).replace("$desc",description).replace("$imageUrl",imageUrl.trim()).replace("$contentUrl",contentUrl.trim());
    System.out.println(json);
    File f=new File("G:\\androidprj\\FlipDroid\\app\\assets\\RSS_RECOMMAND_SOURCE_DATA.json");
    String content=FileUtils.readFileToString(f);
    JSONArray array=new JSONArray(content);
    int id=0;
    for (int i=0; i < array.length(); i++) {
      JSONObject object=(JSONObject)array.get(i);
      id=Integer.valueOf((String)object.get("id"));
    }
    id++;
    json=json.replace("$id",id + "");
    json=json.replace("$cat",cat);
    content=content.replace("]","") + "\n" + json+ "]";
    FileUtils.writeStringToFile(f,content);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 54

From project FluentLenium, under directory /fluentlenium-core/src/main/java/org/fluentlenium/core/.

Source file: Fluent.java

  15 
vote

/** 
 * Take a snapshot of the browser into a file given by the fileName param.
 * @param fileName
 */
public Fluent takeScreenShot(String fileName){
  File scrFile=((TakesScreenshot)getDriver()).getScreenshotAs(OutputType.FILE);
  try {
    File destFile=new File(fileName);
    FileUtils.copyFile(scrFile,destFile);
  }
 catch (  IOException e) {
    e.printStackTrace();
    throw new RuntimeException("error when taking the snapshot",e);
  }
  return this;
}
 

Example 55

From project flume, under directory /flume-ng-channels/flume-file-channel/src/test/java/org/apache/flume/channel/file/.

Source file: TestFileChannelBase.java

  15 
vote

@After public void teardown(){
  if (channel != null && channel.isOpen()) {
    channel.stop();
  }
  FileUtils.deleteQuietly(baseDir);
}
 

Example 56

From project frame, under directory /src/main/java/twigkit/frame/.

Source file: CachedImageIOService.java

  15 
vote

public CachedImageIOService(String offlinePath){
  if (offlinePath != null && offlinePath.length() > 0) {
    repository=new File(offlinePath);
    if (!repository.exists()) {
      try {
        FileUtils.forceMkdir(repository);
        logger.info("CachedImageIOService created offline repository: " + repository.getAbsolutePath());
      }
 catch (      IOException e) {
        logger.error("Failed to create offline repository",e);
      }
    }
    logger.info("CachedImageIOService offline path: " + repository.getAbsolutePath());
  }
 else {
    logger.info("CachedImageIOService disabled! An offline path must be specified!");
  }
}
 

Example 57

From project gadget-server, under directory /gadget-web/src/main/java/org/overlord/gadgets/web/server/.

Source file: EncryptedBlobSecurityTokenService.java

  15 
vote

public EncryptedBlobSecurityTokenService(String container,String domain,String encryptionKey){
  this.container=container;
  this.domain=domain;
  try {
    File file=new File(encryptionKey);
    this.blobCrypter=new BasicBlobCrypter(FileUtils.readFileToString(file,"UTF-8"));
  }
 catch (  IOException e) {
    throw new SecurityException("Unable to load encryption key from file: " + encryptionKey);
  }
}
 

Example 58

From project GenericKnimeNodes, under directory /com.genericworkflownodes.knime.node_generator/src/org/ballproject/knime/nodegeneration/model/directories/source/.

Source file: PayloadDirectory.java

  15 
vote

/** 
 * Copies all valid ini and zip files to the specified  {@link File directory}.
 * @param destDir
 * @throws IOException
 */
public void copyPayloadTo(File destDir) throws IOException {
  for (  String filename : this.list(new FilenameFilter(){
    @Override public boolean accept(    File dir,    String filename){
      if (filename.endsWith(".ini")) {
        return true;
      }
      if (filename.endsWith(".zip")) {
        return true;
      }
      return false;
    }
  }
)) {
    FileUtils.copyFileToDirectory(new File(this,filename),destDir);
  }
}