Ejemplo n.º 1
0
  private void createThumbnail(ContentValues map) throws IOException {
    File videoFile = fileFromResourceMap(map);

    Log.d("Creating thumbnail from video file " + videoFile.toString());

    Bitmap bitmap =
        ThumbnailUtils.createVideoThumbnail(
            videoFile.toString(), MediaStore.Video.Thumbnails.MINI_KIND);
    if (bitmap == null) {
      Log.w("Error creating thumbnail");
      return;
    }

    String filename = (String) map.get(Resources.FILENAME);
    if (TextUtils.isEmpty(filename)) {
      throw new IOException("Must specify FILENAME when inserting Resource");
    }
    Uri thumbnailUri = Resources.buildThumbnailUri(filename + THUMBNAIL_EXT);
    OutputStream ostream;
    try {
      ostream = getContext().getContentResolver().openOutputStream(thumbnailUri);
    } catch (FileNotFoundException e) {
      Log.d("Could not open output stream for thumbnail storage: " + e.getLocalizedMessage());
      return;
    }

    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
    ostream.flush();
    IOUtilities.closeStream(ostream);

    map.put(Resources.THUMBNAIL, thumbnailUri.toString());
  }
Ejemplo n.º 2
0
 /**
  * Loads the grid in memory.
  *
  * <p>If file cannot be loaded, the cause is logged at {@link Level#SEVERE severe level}.
  *
  * @param location the NTv2 file absolute path
  * @return the grid, or {@code null} on error
  * @throws FactoryException
  */
 private GridShiftFile loadNTv2Grid(URL location) throws FactoryException {
   InputStream in = null;
   try {
     GridShiftFile grid = new GridShiftFile();
     in = new BufferedInputStream(location.openStream());
     grid.loadGridShiftFile(in, false); // Load full grid in memory
     in.close();
     return grid;
   } catch (FileNotFoundException e) {
     LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
     return null;
   } catch (IOException e) {
     LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
     return null;
   } catch (IllegalArgumentException e) {
     LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
     throw new FactoryException(e.getLocalizedMessage(), e);
   } finally {
     try {
       if (in != null) {
         in.close();
       }
     } catch (IOException e) {
       // never mind
     }
   }
 }
Ejemplo n.º 3
0
 /**
  * Configuration method invoked by framework while initializing Class. Following are the
  * parameters used :
  *
  * <p>
  *
  * <blockquote>
  *
  * <pre>
  * resource-file - oneinc-resource.properties
  * validation-file - validation-rules.xml
  * </pre>
  *
  * </blockquote>
  *
  * <p>This method initialize the ValidatorResources by reading the validation-file passed and then
  * initialize different forms defined in this file. It also initialize the validation resource
  * bundle i.e. oneinc-resource.properties from where user friendly message would be picked in case
  * of validation failure.
  *
  * <p>Member-variable needs to be initialized/assigned once while initializing the class, and is
  * being passed from the XML is initialized in this method.
  *
  * <p>In XML, use the following tag to define the property:
  *
  * <p>&lt;property name="resource-file" value="oneinc-resource" /&gt;
  *
  * <p>corresponding code to get the property is as follow:
  *
  * <p>String resourceName = cfg.get("resource-file");
  *
  * @param cfg - Configuration object holds the property defined in the XML.
  * @throws ConfigurationException
  */
 public void setConfiguration(Configuration cfg) throws ConfigurationException {
   try {
     String resourceName = cfg.get("resource-file");
     apps = ResourceBundle.getBundle(resourceName);
     validationFileName = cfg.get("validation-file");
     InputStream in = null;
     in = BaseValidation.class.getClassLoader().getResourceAsStream(validationFileName);
     try {
       resources = new ValidatorResources(in);
       form = resources.getForm(Locale.getDefault(), "ValidateBean");
       provForm = resources.getForm(Locale.getDefault(), "ValidateProvBean");
     } finally {
       if (in != null) {
         in.close();
       }
     }
     prepareTxnMap();
   } catch (FileNotFoundException e) {
     throw new ConfigurationException(e.getLocalizedMessage(), e);
   } catch (IOException e) {
     throw new ConfigurationException(e.getLocalizedMessage(), e);
   } catch (Exception e) {
     throw new ConfigurationException(e.getLocalizedMessage(), e);
   }
 }
Ejemplo n.º 4
0
 /**
  * This is the starting point of the compiler.
  *
  * @param args Command line arguments to control the compiler
  */
 public static void main(String[] args) {
   try {
     run(args);
   } catch (FileNotFoundException e) {
     System.err.println("FILE NOT FOUND: " + e.getLocalizedMessage());
     System.exit(FILE_NOT_FOUND_ERROR);
   } catch (ParseException e) {
     System.err.println("PARSE ERROR: " + e.getLocalizedMessage());
     System.exit(PARSE_ERROR);
   } catch (ShadowException e) {
     System.err.println("ERROR IN FILE: " + e.getLocalizedMessage());
     e.printStackTrace();
     System.exit(TYPE_CHECK_ERROR);
   } catch (IOException e) {
     System.err.println("FILE DEPENDENCY ERROR: " + e.getLocalizedMessage());
     e.printStackTrace();
     System.exit(TYPE_CHECK_ERROR);
   } catch (org.apache.commons.cli.ParseException e) {
     System.err.println("COMMAND LINE ERROR: " + e.getLocalizedMessage());
     Arguments.printHelp();
     System.exit(COMMAND_LINE_ERROR);
   } catch (ConfigurationException e) {
     System.err.println("CONFIGURATION ERROR: " + e.getLocalizedMessage());
     Arguments.printHelp();
     System.exit(CONFIGURATION_ERROR);
   } catch (TypeCheckException e) {
     System.err.println("TYPE CHECK ERROR: " + e.getLocalizedMessage());
     System.exit(TYPE_CHECK_ERROR);
   } catch (CompileException e) {
     System.err.println("COMPILATION ERROR: " + e.getLocalizedMessage());
     System.exit(COMPILE_ERROR);
   }
 }
Ejemplo n.º 5
0
 private List<String[]> readStrings(String name) {
   List<String[]> content = new ArrayList<>();
   try {
     content = readStrings(create(name));
   } catch (FileNotFoundException ex) {
     LOG.warn(ex.getLocalizedMessage(), ex);
   }
   return content;
 }
  public static void imageConverter() {
    System.out.println("…ffene Datei...");
    File file = new File("./PDFFile/01 Access2010 EinfŸhrung.pdf");
    RandomAccessFile raf;

    try {

      raf = new RandomAccessFile(file, "r");

      FileChannel channel = raf.getChannel();
      ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
      PDFFile pdfFile = new PDFFile(buf);

      // konvertiere erste seite in ein bild
      int num = pdfFile.getNumPages();
      for (int i = 0; i < num; i++) {
        PDFPage page = pdfFile.getPage(i);

        // ermittle Hoehe und Breite
        int width = (int) page.getBBox().getWidth();
        int height = (int) page.getBBox().getHeight();

        // AWT
        Rectangle rect = new Rectangle(0, 0, width, height);
        int rotation = page.getRotation();
        Rectangle rectl = rect;

        if (rotation == 90 || rotation == 270) {
          rectl = new Rectangle(0, 0, rect.height, rect.width);
        }

        // generiere Bild
        BufferedImage img =
            (BufferedImage)
                page.getImage(
                    rect.width,
                    rect.height, // Breite Hoehe
                    rectl,
                    null,
                    true, // Fuelle Hintergrund weiss aus
                    true);

        ImageIO.write(img, "png", new File("./PDFImages/" + i + ".png"));
        System.out.println("Bild {" + i + " }erzeugt");
        img.flush();
      }
      System.out.println("Bilder erzeugt!");
    }

    // Catcher
    catch (FileNotFoundException e1) {
      System.err.println(e1.getLocalizedMessage());
    } catch (IOException e2) {
      System.err.println(e2.getLocalizedMessage());
    }
  }
 public InputStream getResourceStream(String name) throws ResourceNotFoundException {
   // The following code assumes File.separator is a single character.
   if (File.separator.length() > 1) throw new Error("File.separator length is greater than 1");
   String realName = name.replace('#', File.separator.charAt(0));
   try {
     return new FileInputStream(getSourceDirectory() + File.separator + realName);
   } catch (FileNotFoundException ex) {
     throw new ResourceNotFoundException(
         ex.getLocalizedMessage() + ": " + getSourceDirectory() + File.separator + realName);
   }
 }
Ejemplo n.º 8
0
  // Create and save hashed pin.
  private void onNext() {
    char[] inputPin1 = new char[firstPin.getText().length()];
    for (int i = 0; i < firstPin.getText().length(); i++)
      inputPin1[i] = firstPin.getText().charAt(i);

    char[] inputPin2 = new char[confirmPin.getText().length()];
    for (int i = 0; i < confirmPin.getText().length(); i++)
      inputPin2[i] = confirmPin.getText().charAt(i);

    String FILENAME1 = (mAccount.getEmail().toString() + ".pin2").toLowerCase();
    if (!Arrays.equals(inputPin1, inputPin2)) {
      Toast.makeText(EncryptionPin.this, "PINs to not match!", Toast.LENGTH_SHORT).show();
      return;
    } else if (inputPin1.length < 4) {
      Toast.makeText(EncryptionPin.this, "PIN must be at least 4 characters", Toast.LENGTH_SHORT)
          .show();
      return;
    } else if (pinStatus
        .getText()
        .equals("PIN is currently disabled and not linked to this account")) {
      try {
        // save .pin2
        String hash = Hash.setHash(mAccount.getEmail().toString(), inputPin1, EncryptionPin.this);

        FileOutputStream fos1 = openFileOutput(FILENAME1, Context.MODE_PRIVATE);
        fos1.write(hash.getBytes());
        fos1.close();
        // Alert user that process is completed, then return to settings page.
        Toast.makeText(EncryptionPin.this, "Hash saved successfully", Toast.LENGTH_SHORT).show();

        // Hide keyboard
        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
            .hideSoftInputFromWindow(confirmPin.getWindowToken(), 0);
      } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        Log.v("Fie not found", e.getLocalizedMessage());
      } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.v("IO Exception", e.getLocalizedMessage());
      }

      redraw();
      MessageList.actionHandleFolder(this, mAccount, mAccount.getAutoExpandFolderName());
      finish();

    } else if (firstPin.getText().toString().equals(confirmPin.getText().toString())
        && pinStatus.getText().equals("PIN is enabled and linked to this account"))
      Toast.makeText(
              EncryptionPin.this,
              "PIN already configured.  Remove current pin and create a new one to change.",
              Toast.LENGTH_LONG)
          .show();
  }
Ejemplo n.º 9
0
 /*
  * (non-Javadoc)
  *
  * @see javax.swing.tree.TreeModel#getChildCount(java.lang.Object)
  */
 public int getChildCount(Object parent) {
   if (parent == root) {
     return rootDirectories.size();
   }
   Directory dir = (Directory) parent;
   try {
     return dir.getSubDirs().size();
   } catch (FileNotFoundException fnf) {
     MapTool.showError(fnf.getLocalizedMessage(), fnf);
     return 0;
   }
 }
Ejemplo n.º 10
0
 /*
  * (non-Javadoc)
  *
  * @see javax.swing.tree.TreeModel#getIndexOfChild(java.lang.Object, java.lang.Object)
  */
 public int getIndexOfChild(Object parent, Object child) {
   if (parent == root) {
     return rootDirectories.indexOf(child);
   }
   Directory dir = (Directory) parent;
   try {
     return dir.getSubDirs().indexOf(child);
   } catch (FileNotFoundException fnf) {
     MapTool.showError(fnf.getLocalizedMessage(), fnf);
     // Returning '0' should be okay, since getChildCount will always return 0 for this exception
     return 0;
   }
 }
Ejemplo n.º 11
0
 /*
  * (non-Javadoc)
  *
  * @see javax.swing.tree.TreeModel#getChild(java.lang.Object, int)
  */
 public Object getChild(Object parent, int index) {
   if (parent == root) {
     return rootDirectories.get(index);
   }
   Directory dir = (Directory) parent;
   try {
     return dir.getSubDirs().get(index);
   } catch (FileNotFoundException fnf) {
     MapTool.showError(fnf.getLocalizedMessage(), fnf);
     // Returning 'null' should be okay, since getChildCount will always return 0 for this
     // exception
     return null;
   }
 }
Ejemplo n.º 12
0
 /** Load all monitors from persistent storage. */
 private void loadMonitors() {
   try {
     FileReader reader = new FileReader(getSaveLocation());
     IMemento memento = XMLMemento.createReadRoot(reader);
     IMemento[] monitorsMemento = memento.getChildren(MONITOR_ID_ATTR);
     for (IMemento monitorMemento : monitorsMemento) {
       loadMonitor(monitorMemento);
     }
   } catch (FileNotFoundException e) {
     LMLMonitorCorePlugin.log(e.getLocalizedMessage());
   } catch (WorkbenchException e) {
     LMLMonitorCorePlugin.log(e.getLocalizedMessage());
   }
 }
  /**
   * @param filters
   * @return <code>true</code> if the transfer was succesful, and <code>false</code> otherwise
   */
  protected boolean transfer(IPreferenceFilter[] filters) {
    File importFile = new File(getDestinationValue());
    FileInputStream fis = null;
    try {
      if (filters.length > 0) {
        try {
          fis = new FileInputStream(importFile);
        } catch (FileNotFoundException e) {
          WorkbenchPlugin.log(e.getMessage(), e);
          MessageDialog.open(
              MessageDialog.ERROR,
              getControl().getShell(),
              new String(),
              e.getLocalizedMessage(),
              SWT.SHEET);
          return false;
        }
        IPreferencesService service = Platform.getPreferencesService();
        try {
          IExportedPreferences prefs = service.readPreferences(fis);

          service.applyPreferences(prefs, filters);
        } catch (CoreException e) {
          WorkbenchPlugin.log(e.getMessage(), e);
          MessageDialog.open(
              MessageDialog.ERROR,
              getControl().getShell(),
              new String(),
              e.getLocalizedMessage(),
              SWT.SHEET);
          return false;
        }
      }
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
          WorkbenchPlugin.log(e.getMessage(), e);
          MessageDialog.open(
              MessageDialog.ERROR,
              getControl().getShell(),
              new String(),
              e.getLocalizedMessage(),
              SWT.SHEET);
        }
      }
    }
    return true;
  }
Ejemplo n.º 14
0
 @Override
 public InputStream openInputStream() throws IOException, MissingBlobException {
   if (this.conn.isClosed()) {
     throw new IllegalStateException("Unable to open Inputstream, because connection is closed");
   }
   try {
     try {
       // return from cache
       return conn.cache.getInputStream(uri.toString());
     } catch (FileNotFoundException e) {
       // if return from cache did not succeed, return from HDFS.
       return this.conn.getFileSystem().open(path);
     }
   } catch (FileNotFoundException e) {
     throw new MissingBlobException(uri, e.getLocalizedMessage());
   }
 }
Ejemplo n.º 15
0
 public static void copyfile(File source, File dest) {
   try {
     InputStream in = new FileInputStream(source);
     OutputStream out = new FileOutputStream(dest);
     byte[] buf = new byte[1024];
     int len;
     while ((len = in.read(buf)) > 0) {
       out.write(buf, 0, len);
     }
     in.close();
     out.close();
   } catch (FileNotFoundException e) {
     Log.e(TAG, e.getLocalizedMessage());
   } catch (IOException e) {
     Log.e(TAG, e.getLocalizedMessage());
   }
 }
Ejemplo n.º 16
0
 private CIJob getJob(ApplicationInfo appInfo) throws PhrescoException {
   Gson gson = new Gson();
   try {
     BufferedReader br = new BufferedReader(new FileReader(getCIJobPath(appInfo)));
     CIJob job = gson.fromJson(br, CIJob.class);
     br.close();
     return job;
   } catch (FileNotFoundException e) {
     S_LOGGER.debug(e.getLocalizedMessage());
     return null;
   } catch (com.google.gson.JsonParseException e) {
     S_LOGGER.debug("it is already adpted project !!!!! " + e.getLocalizedMessage());
     return null;
   } catch (IOException e) {
     S_LOGGER.debug(e.getLocalizedMessage());
     return null;
   }
 }
Ejemplo n.º 17
0
  protected boolean finalStore(Element root, File file) {
    try {
      // Document doc = newDocument(root, dtdLocation+"layout-config-"+dtdVersion+".dtd");
      Document doc = newDocument(root);

      // add XSLT processing instruction
      // <?xml-stylesheet type="text/xsl" href="XSLT/panelfile"+schemaVersion+".xsl"?>
      java.util.Map<String, String> m = new java.util.HashMap<String, String>();
      m.put("type", "text/xsl");
      m.put("href", xsltLocation + "panelfile" + schemaVersion + ".xsl");
      ProcessingInstruction p = new ProcessingInstruction("xml-stylesheet", m);
      doc.addContent(0, p);

      // add version at front
      storeVersion(root);

      writeXML(file, doc);
    } catch (java.io.FileNotFoundException ex3) {
      storingErrorEncountered(
          null,
          "storing to file " + file.getName(),
          "File not found " + file.getName(),
          null,
          null,
          ex3);
      log.error("FileNotFound error writing file: " + ex3.getLocalizedMessage());
      return false;
    } catch (java.io.IOException ex2) {
      storingErrorEncountered(
          null,
          "storing to file " + file.getName(),
          "IO error writing file " + file.getName(),
          null,
          null,
          ex2);
      log.error("IO error writing file: " + ex2.getLocalizedMessage());
      return false;
    }
    return true;
  }
  @Override
  protected boolean executeAction() {
    boolean result = true;
    try {
      ReportSpec reportSpec = getReportSpec();
      if (reportSpec != null) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ReportGenerationUtility.createJFreeReportXML(
            reportSpec, outputStream, 0, 0, false, "", 0, 0); // $NON-NLS-1$
        String reportDefinition = new String(outputStream.toByteArray());
        addTempParameterObject(
            AbstractJFreeReportComponent.REPORTGENERATEDEFN_REPORTDEFN, reportDefinition);

        // if that parameter is not defined, we do query for backward compatibility.
        if (!isDefinedInput(AbstractJFreeReportComponent.REPORTGENERATEDEFN_REPORTTEMP_PERFQRY)
            || "true"
                .equals(
                    getInputParameter(
                        AbstractJFreeReportComponent
                            .REPORTGENERATEDEFN_REPORTTEMP_PERFQRY))) { //$NON-NLS-1$
          if (reportSpec.getReportSpecChoice().getXqueryUrl() != null) {
            // handle xquery
          } else {
            try {
              addTempParameterObject(
                  AbstractJFreeReportComponent.DATACOMPONENT_DATAINPUT, getResultSet(reportSpec));
            } catch (Exception e) {
              result = false;
            }
          }
        }
      }
    } catch (FileNotFoundException ex) {
      error(ex.getLocalizedMessage());
      result = false;
    }
    return result;
  }
Ejemplo n.º 19
0
 public static MappingTool loadTool(String toolDirectory) throws DAOException {
   MappingTool tool = new MappingTool();
   Properties prop = new Properties();
   FileInputStream in = null;
   try {
     // load a properties file
     in = new FileInputStream(toolDirectory + "/" + "tool.properties");
     prop.load(in);
     tool.setName(toolDirectory.substring(toolDirectory.lastIndexOf(File.separator) + 1));
     tool.setMappingFilePath(
         Utils.toAbsolutePath(toolDirectory, prop.getProperty(tool.getName() + ".mapping_file")));
     tool.setTranslatedInstancePath(
         Utils.toAbsolutePath(
             toolDirectory, prop.getProperty(tool.getName() + ".instance_translated_file")));
     String script = prop.getProperty(tool.getName() + ".script_file");
     if (script != null) {
       tool.setFileScript(Utils.toAbsolutePath(toolDirectory, script));
     }
     tool.setDirectory(toolDirectory);
     in.close();
     return tool;
   } catch (FileNotFoundException fe) {
     logger.error("File tool.properties not found: " + fe.getLocalizedMessage());
     return null;
   } catch (IOException ex) {
     logger.error(ex.getLocalizedMessage());
     throw new DAOException("Problem to load the tool.properties file");
   } finally {
     if (in != null) {
       try {
         in.close();
       } catch (IOException ex) {
       }
     }
   }
 }
Ejemplo n.º 20
0
  private CoordinateReferenceSystem getCRS(Object source) {
    CoordinateReferenceSystem crs = null;
    if (source instanceof File
        || (source instanceof URL && (((URL) source).getProtocol() == "file"))) {
      // getting name for the prj file
      final String sourceAsString;

      if (source instanceof File) {
        sourceAsString = ((File) source).getAbsolutePath();
      } else {
        String auth = ((URL) source).getAuthority();
        String path = ((URL) source).getPath();
        if (auth != null && !auth.equals("")) {
          sourceAsString = "//" + auth + path;
        } else {
          sourceAsString = path;
        }
      }

      final int index = sourceAsString.lastIndexOf(".");
      final String base =
          index > 0 ? sourceAsString.substring(0, index) + ".prj" : sourceAsString + ".prj";

      // does it exist?
      final File prjFile = new File(base.toString());
      if (prjFile.exists()) {
        // it exists then we have top read it
        PrjFileReader projReader = null;
        FileInputStream instream = null;
        try {
          instream = new FileInputStream(prjFile);
          final FileChannel channel = instream.getChannel();
          projReader = new PrjFileReader(channel);
          crs = projReader.getCoordinateReferenceSystem();
        } catch (FileNotFoundException e) {
          // warn about the error but proceed, it is not fatal
          // we have at least the default crs to use
          LOGGER.log(Level.INFO, e.getLocalizedMessage(), e);
        } catch (IOException e) {
          // warn about the error but proceed, it is not fatal
          // we have at least the default crs to use
          LOGGER.log(Level.INFO, e.getLocalizedMessage(), e);
        } catch (FactoryException e) {
          // warn about the error but proceed, it is not fatal
          // we have at least the default crs to use
          LOGGER.log(Level.INFO, e.getLocalizedMessage(), e);
        } finally {
          if (projReader != null)
            try {
              projReader.close();
            } catch (IOException e) {
              // warn about the error but proceed, it is not fatal
              // we have at least the default crs to use
              LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
            }

          if (instream != null)
            try {
              instream.close();
            } catch (IOException e) {
              // warn about the error but proceed, it is not fatal
              // we have at least the default crs to use
              LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
            }
        }
      }
    }
    return crs;
  }
Ejemplo n.º 21
0
  public ApplicationArchive getApplicationArchive(IProgressMonitor monitor) throws CoreException {

    if (!initialized) {
      // Seems like initialize() wasn't invoked prior to this call
      throw CloudErrorUtil.toCoreException(
          Messages.JavaCloudFoundryArchiver_ERROR_ARCHIVER_NOT_INITIALIZED);
    }

    ApplicationArchive archive =
        JavaWebApplicationDelegate.getArchiveFromManifest(appModule, cloudServer);

    if (archive == null) {

      File packagedFile = null;

      IJavaProject javaProject = CloudFoundryProjectUtil.getJavaProject(appModule);

      if (javaProject == null) {
        handleApplicationDeploymentFailure(
            Messages.JavaCloudFoundryArchiver_ERROR_NO_JAVA_PROJ_RESOLVED);
      }

      JavaPackageFragmentRootHandler rootResolver =
          getPackageFragmentRootHandler(javaProject, monitor);

      IType mainType = rootResolver.getMainType(monitor);

      final IPackageFragmentRoot[] roots = rootResolver.getPackageFragmentRoots(monitor);

      if (roots == null || roots.length == 0) {
        handleApplicationDeploymentFailure(
            Messages.JavaCloudFoundryArchiver_ERROR_NO_PACKAGE_FRAG_ROOTS);
      }

      JarPackageData jarPackageData = getJarPackageData(roots, mainType, monitor);

      boolean isBoot = CloudFoundryProjectUtil.isSpringBoot(appModule);

      // Search for existing MANIFEST.MF
      IFile metaFile = getManifest(roots, javaProject);

      // Only use existing manifest files for non-Spring boot, as Spring
      // boot repackager will
      // generate it own manifest file.
      if (!isBoot && metaFile != null) {
        // If it is not a boot project, use a standard library jar
        // builder
        jarPackageData.setJarBuilder(getDefaultLibJarBuilder());

        jarPackageData.setManifestLocation(metaFile.getFullPath());
        jarPackageData.setSaveManifest(false);
        jarPackageData.setGenerateManifest(false);
        // Check manifest accessibility through the jar package data
        // API
        // to verify the packaging won't fail
        if (!jarPackageData.isManifestAccessible()) {
          handleApplicationDeploymentFailure(
              NLS.bind(
                  Messages.JavaCloudFoundryArchiver_ERROR_MANIFEST_NOT_ACCESSIBLE,
                  metaFile.getLocation().toString()));
        }

        InputStream inputStream = null;
        try {

          inputStream = new FileInputStream(metaFile.getLocation().toFile());
          Manifest manifest = new Manifest(inputStream);
          Attributes att = manifest.getMainAttributes();
          if (att.getValue("Main-Class") == null) { // $NON-NLS-1$
            handleApplicationDeploymentFailure(
                Messages.JavaCloudFoundryArchiver_ERROR_NO_MAIN_CLASS_IN_MANIFEST);
          }
        } catch (FileNotFoundException e) {
          handleApplicationDeploymentFailure(
              NLS.bind(
                  Messages.JavaCloudFoundryArchiver_ERROR_FAILED_READ_MANIFEST,
                  e.getLocalizedMessage()));

        } catch (IOException e) {
          handleApplicationDeploymentFailure(
              NLS.bind(
                  Messages.JavaCloudFoundryArchiver_ERROR_FAILED_READ_MANIFEST,
                  e.getLocalizedMessage()));

        } finally {

          if (inputStream != null) {
            try {
              inputStream.close();

            } catch (IOException io) {
              // Ignore
            }
          }
        }

      } else {
        // Otherwise generate a manifest file. Note that manifest files
        // are only generated in the temporary jar meant only for
        // deployment.
        // The associated Java project is no modified.
        jarPackageData.setGenerateManifest(true);

        // This ensures that folders in output folders appear at root
        // level
        // Example: src/main/resources, which is in the project's
        // classpath, contains non-Java templates folder and
        // has output folder target/classes. If not exporting output
        // folder,
        // templates will be packaged in the jar using this path:
        // resources/templates
        // This may cause problems with the application's dependencies
        // if they are looking for just /templates at top level of the
        // jar
        // If exporting output folders, templates folder will be
        // packaged at top level in the jar.
        jarPackageData.setExportOutputFolders(true);
      }

      try {
        packagedFile = packageApplication(jarPackageData, monitor);
      } catch (CoreException e) {
        handleApplicationDeploymentFailure(
            NLS.bind(Messages.JavaCloudFoundryArchiver_ERROR_JAVA_APP_PACKAGE, e.getMessage()));
      }

      if (packagedFile == null || !packagedFile.exists()) {
        handleApplicationDeploymentFailure(
            Messages.JavaCloudFoundryArchiver_ERROR_NO_PACKAGED_FILE_CREATED);
      }

      if (isBoot) {
        bootRepackage(roots, packagedFile);
      }

      // At this stage a packaged file should have been created or found
      try {
        archive = new CloudZipApplicationArchive(new ZipFile(packagedFile));
      } catch (IOException ioe) {
        handleApplicationDeploymentFailure(
            NLS.bind(Messages.JavaCloudFoundryArchiver_ERROR_CREATE_CF_ARCHIVE, ioe.getMessage()));
      }
    }

    return archive;
  }
Ejemplo n.º 22
0
  /** Test of execute method, of class HeightMapUpdate. */
  @Test
  public void testExecute() {
    System.out.println("execute");
    HeightMapUpdate instance = null;
    com.novusradix.JavaPop.Server.HeightMap serverh;
    com.novusradix.JavaPop.Client.HeightMap clienth;
    serverh = new com.novusradix.JavaPop.Server.HeightMap(new Dimension(128, 128));
    clienth = new com.novusradix.JavaPop.Client.HeightMap(new Dimension(128, 128), null);

    serverh.up(0, 0);
    serverh.up(0, 0);
    serverh.up(5, 5);
    serverh.up(106, 7);
    serverh.up(106, 7);
    serverh.up(106, 7);
    serverh.up(106, 7);

    serverh.up(112, 25);
    serverh.up(112, 25);

    serverh.up(112, 125);
    serverh.up(112, 125);
    serverh.up(127, 127);
    serverh.up(127, 127);
    serverh.setTile(0, 0, Tile.BASALT);
    serverh.setTile(126, 126, Tile.BURNT);

    instance = serverh.GetUpdate();
    try {
      FileOutputStream fo;
      fo = new FileOutputStream("HeightMapUpdateTest.dat");
      ObjectOutputStream oos;

      oos = new ObjectOutputStream(fo);

      oos.writeObject(instance);
      oos.close();
      fo.close();

      instance = null;

      FileInputStream fi = new FileInputStream("HeightMapUpdateTest.dat");
      ObjectInputStream ois = new ObjectInputStream(fi);

      instance = (HeightMapUpdate) ois.readObject();
      ois.close();
      fi.close();
    } catch (ClassNotFoundException ex) {
      fail(ex.getLocalizedMessage());
    } catch (FileNotFoundException ex) {
      fail(ex.getLocalizedMessage());
    } catch (IOException ex) {
      fail(ex.getLocalizedMessage());
    }

    instance.clientMap = clienth;

    instance.texture = new HashMap<Integer, Byte>();
    instance.execute();
    assertTrue(clienth.getHeight(0, 0) == 2);
    assertTrue(clienth.getHeight(5, 5) == 1);
    assertTrue(clienth.getHeight(106, 7) == 4);
    assertTrue(clienth.getHeight(112, 25) == 2);
    assertTrue(clienth.getHeight(112, 125) == 2);
  }
Ejemplo n.º 23
0
  @Override
  public void run() {

    try {
      initLocalDirectories();
      initStdOutFiles();

    } catch (FileNotFoundException e1) {

      setEndTime(System.currentTimeMillis());

      setState(Job.ERROR);
      log.error("Job " + getId() + ": initialization failed.", e1);
      writeLog("Initialization failed: " + e1.getLocalizedMessage());
      return;
    }

    setState(Job.RUNNING);
    setStartTime(System.currentTimeMillis());
    writeLog("Details:");
    writeLog("  Name: " + getName());
    writeLog("  Job-Id: " + getId());
    writeLog("  Started At: " + getStartTime());
    writeLog("  Finished At: " + getExecutionTime());
    writeLog("  Execution Time: " + getExecutionTime());

    writeLog("  Inputs:");
    for (Parameter parameter : inputParams) {
      writeLog("    " + parameter.getDescription() + ": " + parameter.getValue());
    }

    writeLog("  Outputs:");
    for (Parameter parameter : outputParams) {
      writeLog("    " + parameter.getDescription() + ": " + parameter.getValue());
    }

    writeLog("Preparing Job....");
    boolean successfulBefore = before();

    if (!successfulBefore) {

      setState(Job.ERROR);
      log.error("Job " + getId() + ": job preparation failed.");
      writeLog("Job preparation failed.");

    } else {

      log.info("Job " + getId() + ": executing.");
      writeLog("Executing Job....");

      boolean succesfull = execute();

      if (succesfull) {

        log.info("Job " + getId() + ":  executed successful.");

        writeLog("Job executed successful.");
        writeLog("Exporting Data...");

        setState(Job.EXPORTING_DATA);

        try {

          boolean successfulAfter = after();

          if (successfulAfter) {

            setEndTime(System.currentTimeMillis());

            setState(Job.FINISHED);
            log.info("Job " + getId() + ": data export successful.");
            writeLog("Data export successful.");

          } else {

            setEndTime(System.currentTimeMillis());

            setState(Job.ERROR);
            log.error("Job " + getId() + ": data export failed.");
            writeLog("Data export failed.");
          }

        } catch (Exception e) {

          setEndTime(System.currentTimeMillis());

          setState(Job.ERROR);
          log.error("Job " + getId() + ": data export failed.", e);
          writeLog("Data export failed: " + e.getLocalizedMessage());
        }

      } else {

        setEndTime(System.currentTimeMillis());

        setState(Job.ERROR);
        log.error("Job " + getId() + ": execution failed. " + getError());
        writeLog("Job execution failed: " + getError());
      }
    }

    closeStdOutFiles();

    exportStdOutToS3();
  }
  /**
   * Synchronous call to the OCC web services
   *
   * @param url The url
   * @param isAuthorizedRequest Whether this request requires the authorization token sending
   * @param httpMethod method type (GET, PUT, POST, DELETE)
   * @param httpBody Data to be sent in the body (Can be empty)
   * @return The data from the server as a string, in almost all cases JSON
   * @throws MalformedURLException
   * @throws IOException
   * @throws ProtocolException
   */
  public static String getResponse(
      Context context, String url, Boolean isAuthorizedRequest, String httpMethod, Bundle httpBody)
      throws MalformedURLException, IOException, ProtocolException, JSONException {
    // Refresh if necessary
    if (isAuthorizedRequest && WebServiceAuthProvider.tokenExpiredHint(context)) {
      WebServiceAuthProvider.refreshAccessToken(context);
    }

    boolean refreshLimitReached = false;
    int refreshed = 0;

    String response = "";
    while (!refreshLimitReached) {
      // If we have refreshed max number of times, we will not do so again
      if (refreshed == 1) {
        refreshLimitReached = true;
      }

      // Make the connection and get the response
      OutputStream os;
      HttpURLConnection connection;

      if (httpMethod.equals("GET") && httpBody != null && !httpBody.isEmpty()) {
        url = url + "?" + encodePostBody(httpBody);
      }
      URL requestURL = new URL(addParameters(context, url));

      if (StringUtils.equalsIgnoreCase(requestURL.getProtocol(), "https")) {
        HttpsURLConnection https = createSecureConnection(requestURL);
        if (isAuthorizedRequest) {
          String authValue =
              "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token");
          https.setRequestProperty("Authorization", authValue);
        }
        connection = https;
      } else {
        connection = createConnection(requestURL);
      }
      connection.setRequestMethod(httpMethod);

      if (!httpMethod.equals("GET") && !httpMethod.equals("DELETE")) {
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        if (httpBody != null && !httpBody.isEmpty()) {
          os = new BufferedOutputStream(connection.getOutputStream());
          os.write(encodePostBody(httpBody).getBytes());
          os.flush();
        }
      }

      response = "";
      try {
        LoggingUtils.d(LOG_TAG, connection.toString());
        response = readFromStream(connection.getInputStream());
      } catch (FileNotFoundException e) {
        LoggingUtils.e(
            LOG_TAG,
            "Error reading stream \""
                + connection.getInputStream()
                + "\". "
                + e.getLocalizedMessage(),
            context);
        response = readFromStream(connection.getErrorStream());
      } finally {
        connection.disconnect();
      }

      // Allow for calls to return nothing
      if (response.length() == 0) {
        return "";
      }

      // Check for JSON parsing errors (will throw JSONException is can't be parsed)
      JSONObject object = new JSONObject(response);

      // If no error, return response
      if (!object.has("error")) {
        return response;
      }
      // If there is a refresh token error, refresh the token
      else if (object.getString("error").equals("invalid_token")) {
        if (refreshLimitReached) {
          // Give up
          return response;
        } else {
          // Refresh the token
          WebServiceAuthProvider.refreshAccessToken(context);
          refreshed++;
        }
      }
    } // while(!refreshLimitReached)

    // There is an error other than a refresh error, so return the response
    return response;
  }
  /**
   * Gets the coordinate reference system that will be associated to the {@link GridCoverage} by
   * looking for a related PRJ.
   */
  protected void parsePRJFile() {
    String prjPath = null;

    this.crs = null;
    prjPath = this.parentPath + File.separatorChar + coverageName + ".prj";

    // read the prj serviceInfo from the file
    PrjFileReader projReader = null;

    FileInputStream inStream = null;
    FileChannel channel = null;
    try {
      final File prj = new File(prjPath);
      if (prj.exists() && prj.canRead()) {

        inStream = new FileInputStream(prj);
        channel = inStream.getChannel();
        projReader = new PrjFileReader(channel);
        this.crs = projReader.getCoordinateReferenceSystem();
      }
      // If some exception occurs, warn about the error but proceed
      // using a default CRS
    } catch (FileNotFoundException e) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
      }
    } catch (IOException e) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
      }
    } catch (FactoryException e) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
      }
    } finally {
      if (projReader != null) {
        try {
          projReader.close();
        } catch (IOException e) {
          if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
          }
        }
      }

      if (inStream != null) {
        try {
          inStream.close();
        } catch (Throwable e) {
          if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
          }
        }
      }

      if (channel != null) {
        try {
          channel.close();
        } catch (Throwable e) {
          if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
          }
        }
      }
    }
  }
Ejemplo n.º 26
0
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.one_photo);

    findviews();

    locLatitude = -1;
    locLongitute = -1;

    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    imgUtil = new ImageUtil();

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
      mFileName = extras.getString("FILE");
      ftID = extras.getString("_ID");
    }

    if (ftID != null) {
      updateMode = true;

      mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

      Cursor c = ForTour.mDbHelper.ftStoryFetchByID(ftID);

      mFileName = c.getString(0);

      editTextOPStory.setText(c.getString(1));

      mLocName = c.getString(2);
      editTextOPLocation.setText(mLocName);

      hasRecord = (c.getInt(3) == 0) ? false : true;

      ftStoryTime = c.getLong(4);
      mCalendar = Util.setCalendarInMSec(ftStoryTime);

      locLatitude = c.getDouble(5);
      locLongitute = c.getDouble(6);
      mMoodIndex = c.getInt(7);

      c.close();

      buttonOPSticker.setImageResource(ImageUtil.imageMoodFiles[mMoodIndex]);
    }

    /* It mFileName is NULL, leave */
    if (mFileName == null) {
      Toast.makeText(
              EditPage.this, getString(R.string.stringUnableToProcessDataNow), Toast.LENGTH_LONG)
          .show();
      finish();
    }

    mMediaFileName = mFileName.replace(ForTour.EXT_PHOTO, ForTour.EXT_RECORD);

    bmUriPath =
        Uri.fromFile(
            new File(
                Environment.getExternalStorageDirectory(), ForTour.DIR_WORK + "/" + mFileName));

    /* NOTE: All the buttons MUST AFTER ALL INITIAL READY, due to UPDATE mode */
    setButtonListener();
    setDateTimePicker();

    try {
      bm = MediaStore.Images.Media.getBitmap(this.getContentResolver(), bmUriPath);
    } catch (FileNotFoundException e) {
      Toast.makeText(EditPage.this, "File Not Found: " + e.getLocalizedMessage(), Toast.LENGTH_LONG)
          .show();
    } catch (IOException e) {
      Toast.makeText(EditPage.this, "IO Exception: " + e.getLocalizedMessage(), Toast.LENGTH_LONG)
          .show();
    }

    imageViewOPImage.setImageBitmap(
        imgUtil.imageBorderMerge(getResources().getDrawable(R.drawable.photo_frame), bm));
  }
  /* (non-Javadoc)
   * @see com.aptana.ide.core.io.vfs.IConnectionFileManager#connect(org.eclipse.core.runtime.IProgressMonitor)
   */
  public void connect(IProgressMonitor monitor) throws CoreException {
    Assert.isTrue(ftpClient != null, Messages.FTPConnectionFileManager_not_initialized);
    monitor = Policy.monitorFor(monitor);
    try {
      cwd = null;
      cleanup();

      ConnectionContext context = CoreIOPlugin.getConnectionContext(this);

      if (messageLogWriter == null) {
        if (context != null) {
          Object object = context.get(ConnectionContext.COMMAND_LOG);
          if (object instanceof PrintWriter) {
            messageLogWriter = (PrintWriter) object;
          } else if (object instanceof OutputStream) {
            messageLogWriter = new PrintWriter((OutputStream) object);
          }
        }
        if (messageLogWriter == null) {
          messageLogWriter = FTPPlugin.getDefault().getFTPLogWriter();
        }
        if (messageLogWriter != null) {
          messageLogWriter.println(StringUtils.format("---------- FTP {0} ----------", host));
          setMessageLogger(ftpClient, messageLogWriter);
        }
      } else {
        messageLogWriter.println(
            StringUtils.format("---------- RECONNECTING - FTP {0} ----------", host));
      }

      monitor.beginTask(
          Messages.FTPConnectionFileManager_establishing_connection, IProgressMonitor.UNKNOWN);
      ftpClient.setRemoteHost(host);
      ftpClient.setRemotePort(port);
      while (true) {
        monitor.subTask(Messages.FTPConnectionFileManager_connecting);
        ftpClient.connect();
        if (password.length == 0
            && !IFTPConstants.LOGIN_ANONYMOUS.equals(login)
            && (context == null || !context.getBoolean(ConnectionContext.NO_PASSWORD_PROMPT))) {
          getOrPromptPassword(
              StringUtils.format(Messages.FTPConnectionFileManager_ftp_auth, host),
              Messages.FTPConnectionFileManager_specify_password);
        }
        Policy.checkCanceled(monitor);
        monitor.subTask(Messages.FTPConnectionFileManager_authenticating);
        try {
          ftpClient.login(login, String.copyValueOf(password));
        } catch (FTPException e) {
          Policy.checkCanceled(monitor);
          if (ftpClient.getLastValidReply() == null
              || "331".equals(ftpClient.getLastValidReply().getReplyCode())) { // $NON-NLS-1$
            if (context != null && context.getBoolean(ConnectionContext.NO_PASSWORD_PROMPT)) {
              throw new CoreException(
                  new Status(
                      Status.ERROR,
                      FTPPlugin.PLUGIN_ID,
                      StringUtils.format("Authentication failed: {0}", e.getLocalizedMessage()),
                      e));
            }
            promptPassword(
                StringUtils.format(Messages.FTPConnectionFileManager_ftp_auth, host),
                Messages.FTPConnectionFileManager_invalid_password);
            safeQuit();
            continue;
          }
          throw e;
        }
        break;
      }

      Policy.checkCanceled(monitor);
      changeCurrentDir(basePath);

      ftpClient.setType(
          IFTPConstants.TRANSFER_TYPE_ASCII.equals(transferType)
              ? FTPTransferType.ASCII
              : FTPTransferType.BINARY);

      if ((hasServerInfo
              || (context != null && context.getBoolean(ConnectionContext.QUICK_CONNECT)))
          && !(context != null && context.getBoolean(ConnectionContext.DETECT_TIMEZONE))) {
        return;
      }
      getherServerInfo(context, monitor);

    } catch (OperationCanceledException e) {
      safeQuit();
      throw e;
    } catch (CoreException e) {
      safeQuit();
      throw e;
    } catch (UnknownHostException e) {
      safeQuit();
      throw new CoreException(
          new Status(
              Status.ERROR,
              FTPPlugin.PLUGIN_ID,
              "Host name not found: " + e.getLocalizedMessage(),
              e));
    } catch (FileNotFoundException e) {
      safeQuit();
      throw new CoreException(
          new Status(
              Status.ERROR,
              FTPPlugin.PLUGIN_ID,
              "Remote folder not found: " + e.getLocalizedMessage(),
              e));
    } catch (Exception e) {
      safeQuit();
      throw new CoreException(
          new Status(
              Status.ERROR,
              FTPPlugin.PLUGIN_ID,
              Messages.FTPConnectionFileManager_connection_failed + e.getLocalizedMessage(),
              e));
    } finally {
      monitor.done();
    }
  }