List of usage examples for java.io File equals
public boolean equals(Object obj)
From source file:net.sf.jsignpdf.SignPdfForm.java
/** * Checks if inFile and outFile are different. * //from w w w. j a v a 2 s . c o m * @return result of the check */ private boolean checkInOutDiffers() { final String tmpInName = tfInPdfFile.getText(); final String tmpOutName = tfOutPdfFile.getText(); boolean tmpResult = true; if (tmpInName != null && StringUtils.isNotEmpty(tmpOutName)) { try { final File tmpInFile = (new File(tmpInName)).getAbsoluteFile(); final File tmpOutFile = (new File(tmpOutName)).getAbsoluteFile(); if (tmpInFile.equals(tmpOutFile)) { tmpResult = false; JOptionPane.showMessageDialog(this, RES.get("gui.filesEqual.error"), RES.get("gui.check.error.title"), JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { tmpResult = false; JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } return tmpResult; }
From source file:org.madsonic.service.LastFMService.java
private void saveCoverArt(String path, String url, boolean isArtist) throws Exception { InputStream input = null;/* ww w .j av a 2 s . c o m*/ HttpClient client = new DefaultHttpClient(); try { HttpConnectionParams.setConnectionTimeout(client.getParams(), 20 * 1000); // 20 seconds HttpConnectionParams.setSoTimeout(client.getParams(), 20 * 1000); // 20 seconds HttpGet method = new HttpGet(url); org.apache.http.HttpResponse response = client.execute(method); input = response.getEntity().getContent(); // Attempt to resolve proper suffix. String suffix = "jpg"; if (url.toLowerCase().endsWith(".gif")) { suffix = "gif"; } else if (url.toLowerCase().endsWith(".png")) { suffix = "png"; } String coverName = "cover."; if (isArtist == true) { coverName = "artist."; } // Check permissions. File newCoverFile = new File(path, coverName + suffix); if (!securityService.isWriteAllowed(newCoverFile)) { throw new Exception("Permission denied: " + StringUtil.toHtml(newCoverFile.getPath())); } // If file exists, create a backup. backup(newCoverFile, new File(path, coverName + "backup." + suffix)); // Write file. IOUtils.copy(input, new FileOutputStream(newCoverFile)); MediaFile mediaFile = mediaFileService.getMediaFile(path); // Rename existing cover file if new cover file is not the preferred. try { File coverFile = mediaFileService.getCoverArt(mediaFile); if (coverFile != null) { if (!newCoverFile.equals(coverFile)) { coverFile.renameTo(new File(coverFile.getCanonicalPath() + ".old")); LOG.info("Renamed old image file " + coverFile); } } } catch (Exception x) { LOG.warn("Failed to rename existing cover file.", x); } mediaFileService.refreshMediaFile(mediaFile); } finally { IOUtils.closeQuietly(input); client.getConnectionManager().shutdown(); } }
From source file:org.clickframes.util.CodeGenerator.java
/** * * @param params// www . ja va 2 s. c o m * map of substitution variables * @param realDir * code should be generated in this directory for creation only, * no overwrite allowed * @param targetDir * this is the fallback directory, overwriting existing file is * allowed in this directory * @param templateName * the template to be used to generated code * @param filename * the name of the output file * * @author Vineet Manohar * @return * @throws IOException */ File generateCode(CodeOverwritePolicy policy, Map<String, Object> params, File realDir, File targetDir, String templateName, String filename) throws IOException { File generatedFile = File.createTempFile("clickframes-", filename); generatedFile.deleteOnExit(); VelocityHelper.runMacro(params, templateName, generatedFile); File realFile = new File(realDir, filename); File targetFile = new File(targetDir, filename); File destinationFile; switch (policy) { case OVERWRITE_ALLOWED: destinationFile = realFile; break; case OVERWRITE_NOT_ALLOWED: destinationFile = targetFile; break; case OVERWRITE_IF_UNCHANGED: if (!realFile.exists()) { destinationFile = realFile; break; } if (!modifiedSinceLastGeneration(realFile)) { // quit, if the new file is 'logically' same as the next // file. e.g. if // only white space changes have been made if (generatedFileLogicallySameAsExistingFile(generatedFile, realFile)) { return realFile; } destinationFile = realFile; break; } destinationFile = targetFile; break; default: throw new RuntimeException( "Developer exception: CodeOverwritePolicy not implemented for this policy: " + policy); } if (log.isDebugEnabled() && destinationFile.equals(realFile)) { if (realFile.exists()) { // log.debug(filename + " updated, being replaced."); // log.debug(realFile.getAbsolutePath() + // " updated, being replaced."); } else { // log.debug(filename + " created."); } } destinationFile.getParentFile().mkdirs(); // cannot rename to an existing file with windows if (destinationFile.exists()) { destinationFile.delete(); } storeChecksumInFile(generatedFile); FileUtils.copyFile(generatedFile, destinationFile); return destinationFile; }
From source file:ir.ac.iust.nlp.postagger.POSTaggerForm.java
private void btnStartTaggingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartTaggingActionPerformed wordModel.clear();/*from w ww .ja va2 s.c om*/ predModel.clear(); goldModel.clear(); txtTagLog.setText(""); btnStartTagging.setEnabled(false); tabTag.setSelectedIndex(0); tabTag.setEnabledAt(1, false); File modelFrom = new File(txtModelPath.getText()); File modelTo = new File(System.getProperty("user.dir") + File.separator + modelFrom.getName()); if (!modelFrom.equals(modelTo)) { modelTo.mkdirs(); copyDirectory(modelFrom, modelTo); } PrintStream out = new PrintStream(new OutputStream() { private StringBuffer buffer = new StringBuffer(); @Override public void write(int b) throws IOException { this.buffer.append((char) b); txtTagLog.setText(buffer.toString()); txtTagLog.setCaretPosition(txtTagLog.getDocument().getLength() - 1); } }); RunnableTagging.out = out; String gold = null; if (chkGoldFile.isSelected() == true) { gold = txtGoldFile.getText(); } // Run in a new thread Runnable job = new RunnableTagging(this, modelFrom.getName(), txtInputFile.getText(), txtOutputPath.getText() + "tagged_output.lbl", gold); ExecutorService threadPool = Executors.newFixedThreadPool(1); threadPool.execute(job); threadPool.shutdown(); }
From source file:ch.bender.evacuate.EvacuateMain.java
/** * init// www .j a v a 2 s . c om * <p> */ public void init() { myDryRun = false; myMove = false; if (myArgs.length < 3) { usage(); throw new IllegalArgumentException("Too less parameters"); } int index = 0; for (int i = 0; i < myArgs.length; i++) { String arg = myArgs[i]; if ("-d".equals(arg) || "--dry-run".equals(arg)) { myDryRun = true; index++; continue; } if ("-m".equals(arg) || "--move".equals(arg)) { myMove = true; index++; continue; } if ("-e".equals(arg) || "--exclude".equals(arg)) { index++; i++; if (i >= myArgs.length) { throw new IllegalArgumentException("File URL expected after option " + arg); } myExcludePatterns = initExcludePattersFromFile(myArgs[i]); index++; continue; } } int needed = index + 3; if (myArgs.length < needed) { usage(); throw new IllegalArgumentException("Too less parameters"); } myOrigDir = myArgs[index]; index++; myBackupDir = myArgs[index]; index++; myEvacuateDir = myArgs[index]; index++; myLog.debug("Extracted command line parameters:" + "\n Original directory : " + myOrigDir + "\n Backup directory : " + myBackupDir + "\n Evacuation directory: " + myEvacuateDir + "\n Dry-Run : " + myDryRun + "\n Move : " + myMove + "\n ExcludePatterns : " + myExcludePatterns); File origDir = new File(myOrigDir); if (!origDir.exists()) { usage(); throw new IllegalArgumentException("Original directory does not exist: " + myOrigDir); } File backupDir = new File(myBackupDir); if (!backupDir.exists()) { usage(); throw new IllegalArgumentException("Backup directory does not exist: " + myBackupDir); } File evacuateDir = new File(myEvacuateDir); if (!evacuateDir.exists()) { if (!evacuateDir.mkdirs()) { usage(); throw new IllegalArgumentException("Evacuation directory cannot be created: " + myEvacuateDir); } } if (!origDir.isDirectory()) { usage(); throw new IllegalArgumentException("Evacuation directory is not a directory: " + myOrigDir); } if (!backupDir.isDirectory()) { usage(); throw new IllegalArgumentException("Evacuation directory is not a directory: " + myBackupDir); } if (!evacuateDir.isDirectory()) { usage(); throw new IllegalArgumentException("Evacuation directory is not a directory: " + myEvacuateDir); } if ((origDir.equals(backupDir)) || (origDir.equals(evacuateDir)) || (backupDir.equals(evacuateDir))) { usage(); throw new IllegalArgumentException("At least two of the given directories are equal."); } }
From source file:ir.ac.iust.nlp.postagger.POSTaggerForm.java
private void btnStartTrainingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartTrainingActionPerformed try {/* www .ja v a 2s.com*/ txtTrainLog.setText(""); btnStartTraining.setEnabled(false); PrintStream out = new PrintStream(new OutputStream() { private StringBuffer buffer = new StringBuffer(); @Override public void write(int b) throws IOException { this.buffer.append((char) b); txtTrainLog.setText(buffer.toString()); txtTrainLog.setCaretPosition(txtTrainLog.getDocument().getLength() - 1); } }); RunnableTrain.out = out; File trainFrom = new File(txtTrainFile.getText()); File trainTo = new File(System.getProperty("user.dir") + File.separator + trainFrom.getName()); if (!trainFrom.equals(trainTo)) FileUtils.copyFile(trainFrom, trainTo); File modelTo = new File(txtTrainModelPath.getText()); File modelFrom = new File(System.getProperty("user.dir") + File.separator + modelTo.getName()); modelFrom.mkdirs(); // Run in a new thread Runnable job = new RunnableTrain(this, modelTo.getName(), trainFrom.getName(), Integer.parseInt(spMaxIters.getValue().toString())); ExecutorService threadPool = Executors.newFixedThreadPool(1); threadPool.execute(job); threadPool.shutdown(); } catch (IOException | NumberFormatException ex) { } }
From source file:org.opendatakit.services.submissions.provider.SubmissionProvider.java
/** * The incoming URI is of the form://from w w w . j a v a 2 s . c o m * ..../appName/tableId/instanceId?formId=&formVersion= * * where instanceId is the DataTableColumns._ID */ @SuppressWarnings("unchecked") @Override public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException { possiblyWaitForContentProviderDebugger(); final boolean asXml = uri.getAuthority().equalsIgnoreCase(ProviderConsts.XML_SUBMISSION_AUTHORITY); if (mode != null && !mode.equals("r")) { throw new IllegalArgumentException("Only read access is supported"); } // URI == ..../appName/tableId/instanceId?formId=&formVersion= List<String> segments = uri.getPathSegments(); if (segments.size() != 4) { throw new IllegalArgumentException("Unknown URI (incorrect number of path segments!) " + uri); } PropertyManager propertyManager = new PropertyManager(getContext()); final String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); WebLoggerIf logger = WebLogger.getLogger(appName); final String tableId = segments.get(1); final String instanceId = segments.get(2); final String submissionInstanceId = segments.get(3); PropertiesSingleton props = CommonToolProperties.get(getContext(), appName); String userEmail = props.getProperty(CommonToolProperties.KEY_ACCOUNT); String username = props.getProperty(CommonToolProperties.KEY_USERNAME); String activeUser = props.getActiveUser(); String rolesList = props.getProperty(CommonToolProperties.KEY_ROLES_LIST); String currentLocale = props.getLocale(); DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); OdkConnectionInterface db = null; try { // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName, dbHandleName); boolean success = false; try { success = ODKDatabaseImplUtils.get().hasTableId(db, tableId); } catch (Exception e) { logger.printStackTrace(e); throw new SQLException("Unknown URI (exception testing for tableId) " + uri); } if (!success) { throw new SQLException("Unknown URI (missing data table for tableId) " + uri); } // Get the table properties specific to XML submissions String xmlInstanceName = null; String xmlRootElementName = null; String xmlDeviceIdPropertyName = null; String xmlUserIdPropertyName = null; String xmlBase64RsaPublicKey = null; try { Cursor c = null; try { c = db.query(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, new String[] { KeyValueStoreColumns.KEY, KeyValueStoreColumns.VALUE }, KeyValueStoreColumns.TABLE_ID + "=? AND " + KeyValueStoreColumns.PARTITION + "=? AND " + KeyValueStoreColumns.ASPECT + "=? AND " + KeyValueStoreColumns.KEY + " IN (?,?,?,?,?)", new String[] { tableId, KeyValueStoreConstants.PARTITION_TABLE, KeyValueStoreConstants.ASPECT_DEFAULT, KeyValueStoreConstants.XML_INSTANCE_NAME, KeyValueStoreConstants.XML_ROOT_ELEMENT_NAME, KeyValueStoreConstants.XML_DEVICE_ID_PROPERTY_NAME, KeyValueStoreConstants.XML_USER_ID_PROPERTY_NAME, KeyValueStoreConstants.XML_BASE64_RSA_PUBLIC_KEY }, null, null, null, null); c.moveToFirst(); if (c.getCount() > 0) { int idxKey = c.getColumnIndex(KeyValueStoreColumns.KEY); int idxValue = c.getColumnIndex(KeyValueStoreColumns.VALUE); do { String key = c.getString(idxKey); String value = c.getString(idxValue); if (KeyValueStoreConstants.XML_INSTANCE_NAME.equals(key)) { xmlInstanceName = value; } else if (KeyValueStoreConstants.XML_ROOT_ELEMENT_NAME.equals(key)) { xmlRootElementName = value; } else if (KeyValueStoreConstants.XML_DEVICE_ID_PROPERTY_NAME.equals(key)) { xmlDeviceIdPropertyName = value; } else if (KeyValueStoreConstants.XML_USER_ID_PROPERTY_NAME.equals(key)) { xmlUserIdPropertyName = value; } else if (KeyValueStoreConstants.XML_BASE64_RSA_PUBLIC_KEY.equals(key)) { xmlBase64RsaPublicKey = value; } } while (c.moveToNext()); } } finally { c.close(); c = null; } OrderedColumns orderedDefns = ODKDatabaseImplUtils.get().getUserDefinedColumns(db, tableId); // Retrieve the values of the record to be emitted... HashMap<String, Object> values = new HashMap<String, Object>(); // issue query to retrieve the most recent non-checkpoint data record // for the instanceId StringBuilder b = new StringBuilder(); b.append("SELECT * FROM ").append(tableId).append(" as T WHERE ").append(DataTableColumns.ID) .append("=?").append(" AND ").append(DataTableColumns.SAVEPOINT_TYPE) .append(" IS NOT NULL AND ").append(DataTableColumns.SAVEPOINT_TIMESTAMP) .append("=(SELECT max(V.").append(DataTableColumns.SAVEPOINT_TIMESTAMP).append(") FROM ") .append(tableId).append(" as V WHERE V.").append(DataTableColumns.ID).append("=T.") .append(DataTableColumns.ID).append(" AND V.").append(DataTableColumns.SAVEPOINT_TYPE) .append(" IS NOT NULL").append(")"); String[] selectionArgs = new String[] { instanceId }; FileSet freturn = new FileSet(appName); String datestamp = null; try { ODKDatabaseImplUtils.AccessContext accessContext = ODKDatabaseImplUtils.get() .getAccessContext(db, tableId, activeUser, rolesList); c = ODKDatabaseImplUtils.get().rawQuery(db, b.toString(), selectionArgs, null, accessContext); b.setLength(0); if (c.moveToFirst() && c.getCount() == 1) { String rowETag = null; String filterType = null; String filterValue = null; String formId = null; String locale = null; String savepointType = null; String savepointCreator = null; String savepointTimestamp = null; String instanceName = null; // OK. we have the record -- work through all the terms for (int i = 0; i < c.getColumnCount(); ++i) { ColumnDefinition defn = null; String columnName = c.getColumnName(i); try { defn = orderedDefns.find(columnName); } catch (IllegalArgumentException e) { // ignore... } if (defn != null && !c.isNull(i)) { if (xmlInstanceName != null && defn.getElementName().equals(xmlInstanceName)) { instanceName = CursorUtils.getIndexAsString(c, i); } // user-defined column ElementType type = defn.getType(); ElementDataType dataType = type.getDataType(); logger.i(t, "element type: " + defn.getElementType()); if (dataType == ElementDataType.integer) { Integer value = CursorUtils.getIndexAsType(c, Integer.class, i); putElementValue(values, defn, value); } else if (dataType == ElementDataType.number) { Double value = CursorUtils.getIndexAsType(c, Double.class, i); putElementValue(values, defn, value); } else if (dataType == ElementDataType.bool) { Integer tmp = CursorUtils.getIndexAsType(c, Integer.class, i); Boolean value = tmp == null ? null : (tmp != 0); putElementValue(values, defn, value); } else if (type.getElementType().equals("date")) { String value = CursorUtils.getIndexAsString(c, i); String jrDatestamp = (value == null) ? null : (new SimpleDateFormat(ISO8601_DATE_ONLY_FORMAT, Locale.US)) .format(new Date(TableConstants.milliSecondsFromNanos(value))); putElementValue(values, defn, jrDatestamp); } else if (type.getElementType().equals("dateTime")) { String value = CursorUtils.getIndexAsString(c, i); String jrDatestamp = (value == null) ? null : (new SimpleDateFormat(ISO8601_DATE_FORMAT, Locale.US)) .format(new Date(TableConstants.milliSecondsFromNanos(value))); putElementValue(values, defn, jrDatestamp); } else if (type.getElementType().equals("time")) { String value = CursorUtils.getIndexAsString(c, i); putElementValue(values, defn, value); } else if (dataType == ElementDataType.array) { ArrayList<Object> al = CursorUtils.getIndexAsType(c, ArrayList.class, i); putElementValue(values, defn, al); } else if (dataType == ElementDataType.string) { String value = CursorUtils.getIndexAsString(c, i); putElementValue(values, defn, value); } else /* unrecognized */ { throw new IllegalStateException( "unrecognized data type: " + defn.getElementType()); } } else if (columnName.equals(DataTableColumns.SAVEPOINT_TIMESTAMP)) { savepointTimestamp = CursorUtils.getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.ROW_ETAG)) { rowETag = CursorUtils.getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.FILTER_TYPE)) { filterType = CursorUtils.getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.FILTER_VALUE)) { filterValue = CursorUtils.getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.FORM_ID)) { formId = CursorUtils.getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.LOCALE)) { locale = CursorUtils.getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.FORM_ID)) { formId = CursorUtils.getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.SAVEPOINT_TYPE)) { savepointType = CursorUtils.getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.SAVEPOINT_CREATOR)) { savepointCreator = CursorUtils.getIndexAsString(c, i); } } // OK got all the values into the values map -- emit // contents b.setLength(0); File submissionXml = new File(ODKFileUtils.getInstanceFolder(appName, tableId, instanceId), (asXml ? "submission.xml" : "submission.json")); File manifest = new File(ODKFileUtils.getInstanceFolder(appName, tableId, instanceId), "manifest.json"); submissionXml.delete(); manifest.delete(); freturn.instanceFile = submissionXml; if (asXml) { // Pre-processing -- collapse all geopoints into a // string-valued representation for (ColumnDefinition defn : orderedDefns.getColumnDefinitions()) { ElementType type = defn.getType(); ElementDataType dataType = type.getDataType(); if (dataType == ElementDataType.object && (type.getElementType().equals("geopoint") || type.getElementType().equals("mimeUri"))) { Map<String, Object> parent = null; List<ColumnDefinition> parents = new ArrayList<ColumnDefinition>(); ColumnDefinition d = defn.getParent(); while (d != null) { parents.add(d); d = d.getParent(); } parent = values; for (int i = parents.size() - 1; i >= 0; --i) { Object o = parent.get(parents.get(i).getElementName()); if (o == null) { parent = null; break; } parent = (Map<String, Object>) o; } if (parent != null) { Object o = parent.get(defn.getElementName()); if (o != null) { if (type.getElementType().equals("geopoint")) { Map<String, Object> geopoint = (Map<String, Object>) o; // OK. we have geopoint -- get the // lat, long, alt, etc. Double latitude = (Double) geopoint.get("latitude"); Double longitude = (Double) geopoint.get("longitude"); Double altitude = (Double) geopoint.get("altitude"); Double accuracy = (Double) geopoint.get("accuracy"); String gpt = "" + latitude + " " + longitude + " " + altitude + " " + accuracy; parent.put(defn.getElementName(), gpt); } else if (type.getElementType().equals("mimeUri")) { Map<String, Object> mimeuri = (Map<String, Object>) o; String uriFragment = (String) mimeuri.get("uriFragment"); String contentType = (String) mimeuri.get("contentType"); if (uriFragment != null) { File f = ODKFileUtils.getAsFile(appName, uriFragment); if (f.equals(manifest)) { throw new IllegalStateException( "Unexpected collision with manifest.json"); } freturn.addAttachmentFile(f, contentType); parent.put(defn.getElementName(), f.getName()); } } else { throw new IllegalStateException("Unhandled transform case"); } } } } } datestamp = (new SimpleDateFormat(ISO8601_DATE_FORMAT, Locale.US)) .format(new Date(TableConstants.milliSecondsFromNanos(savepointTimestamp))); // For XML, we traverse the map to serialize it DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); Document d = docBuilder.newDocument(); d.setXmlStandalone(true); Element e = d.createElement((xmlRootElementName == null) ? "data" : xmlRootElementName); d.appendChild(e); e.setAttribute("id", tableId); DynamicPropertiesCallback cb = new DynamicPropertiesCallback(appName, tableId, instanceId, activeUser, currentLocale, username, userEmail); int idx = 0; Element meta = d.createElementNS(XML_OPENROSA_NAMESPACE, "meta"); meta.setPrefix("jr"); Element v = d.createElementNS(XML_OPENROSA_NAMESPACE, "instanceID"); Text txtNode = d.createTextNode(submissionInstanceId); v.appendChild(txtNode); meta.appendChild(v); if (xmlDeviceIdPropertyName != null) { String deviceId = propertyManager.getSingularProperty(xmlDeviceIdPropertyName, cb); if (deviceId != null) { v = d.createElementNS(XML_OPENROSA_NAMESPACE, "deviceID"); txtNode = d.createTextNode(deviceId); v.appendChild(txtNode); meta.appendChild(v); } } if (xmlUserIdPropertyName != null) { String userId = propertyManager.getSingularProperty(xmlUserIdPropertyName, cb); if (userId != null) { v = d.createElementNS(XML_OPENROSA_NAMESPACE, "userID"); txtNode = d.createTextNode(userId); v.appendChild(txtNode); meta.appendChild(v); } } v = d.createElementNS(XML_OPENROSA_NAMESPACE, "timeEnd"); txtNode = d.createTextNode(datestamp); v.appendChild(txtNode); meta.appendChild(v); // these are extra metadata tags... if (instanceName != null) { v = d.createElement("instanceName"); txtNode = d.createTextNode(instanceName); v.appendChild(txtNode); meta.appendChild(v); } else { v = d.createElement("instanceName"); txtNode = d.createTextNode(savepointTimestamp); v.appendChild(txtNode); meta.appendChild(v); } // these are extra metadata tags... // rowID v = d.createElement("rowID"); txtNode = d.createTextNode(instanceId); v.appendChild(txtNode); meta.appendChild(v); // rowETag v = d.createElement("rowETag"); if (rowETag != null) { txtNode = d.createTextNode(rowETag); v.appendChild(txtNode); } meta.appendChild(v); // filterType v = d.createElement("filterType"); if (filterType != null) { txtNode = d.createTextNode(filterType); v.appendChild(txtNode); } meta.appendChild(v); // filterValue v = d.createElement("filterValue"); if (filterValue != null) { txtNode = d.createTextNode(filterValue); v.appendChild(txtNode); } meta.appendChild(v); // formID v = d.createElement("formID"); txtNode = d.createTextNode(formId); v.appendChild(txtNode); meta.appendChild(v); // locale v = d.createElement("locale"); txtNode = d.createTextNode(locale); v.appendChild(txtNode); meta.appendChild(v); // savepointType v = d.createElement("savepointType"); txtNode = d.createTextNode(savepointType); v.appendChild(txtNode); meta.appendChild(v); // savepointCreator v = d.createElement("savepointCreator"); if (savepointCreator != null) { txtNode = d.createTextNode(savepointCreator); v.appendChild(txtNode); } meta.appendChild(v); // savepointTimestamp v = d.createElement("savepointTimestamp"); txtNode = d.createTextNode(savepointTimestamp); v.appendChild(txtNode); meta.appendChild(v); // and insert the meta block into the XML e.appendChild(meta); idx = 3; ArrayList<String> entryNames = new ArrayList<String>(); entryNames.addAll(values.keySet()); Collections.sort(entryNames); for (String name : entryNames) { idx = generateXmlHelper(d, e, idx, name, values, logger); } TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); Properties outFormat = new Properties(); outFormat.setProperty(OutputKeys.INDENT, "no"); outFormat.setProperty(OutputKeys.METHOD, "xml"); outFormat.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); outFormat.setProperty(OutputKeys.VERSION, "1.0"); outFormat.setProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperties(outFormat); ByteArrayOutputStream out = new ByteArrayOutputStream(); DOMSource domSource = new DOMSource(d.getDocumentElement()); StreamResult result = new StreamResult(out); transformer.transform(domSource, result); out.flush(); out.close(); b.append(out.toString(CharEncoding.UTF_8)); // OK we have the document in the builder (b). String doc = b.toString(); freturn.instanceFile = submissionXml; // see if the form is encrypted and we can // encrypt it... EncryptedFormInformation formInfo = EncryptionUtils.getEncryptedFormInformation(appName, tableId, xmlBase64RsaPublicKey, instanceId); if (formInfo != null) { File submissionXmlEnc = new File(submissionXml.getParentFile(), submissionXml.getName() + ".enc"); submissionXmlEnc.delete(); // if we are encrypting, the form cannot be // reopened afterward // and encrypt the submission (this is a // one-way operation)... if (!EncryptionUtils.generateEncryptedSubmission(freturn, doc, submissionXml, submissionXmlEnc, formInfo)) { return null; } // at this point, the freturn object has // been re-written with the encrypted media // and xml files. } else { exportFile(doc, submissionXml, logger); } } else { // Pre-processing -- collapse all mimeUri into filename for (ColumnDefinition defn : orderedDefns.getColumnDefinitions()) { ElementType type = defn.getType(); ElementDataType dataType = type.getDataType(); if (dataType == ElementDataType.object && type.getElementType().equals("mimeUri")) { Map<String, Object> parent = null; List<ColumnDefinition> parents = new ArrayList<ColumnDefinition>(); ColumnDefinition d = defn.getParent(); while (d != null) { parents.add(d); d = d.getParent(); } parent = values; for (int i = parents.size() - 1; i >= 0; --i) { Object o = parent.get(parents.get(i).getElementName()); if (o == null) { parent = null; break; } parent = (Map<String, Object>) o; } if (parent != null) { Object o = parent.get(defn.getElementName()); if (o != null) { if (dataType == ElementDataType.object && type.getElementType().equals("mimeUri")) { Map<String, Object> mimeuri = (Map<String, Object>) o; String uriFragment = (String) mimeuri.get("uriFragment"); String contentType = (String) mimeuri.get("contentType"); File f = ODKFileUtils.getAsFile(appName, uriFragment); if (f.equals(manifest)) { throw new IllegalStateException( "Unexpected collision with manifest.json"); } freturn.addAttachmentFile(f, contentType); parent.put(defn.getElementName(), f.getName()); } else { throw new IllegalStateException("Unhandled transform case"); } } } } } // For JSON, we construct the model, then emit model + // meta + data HashMap<String, Object> wrapper = new HashMap<String, Object>(); wrapper.put("tableId", tableId); wrapper.put("instanceId", instanceId); HashMap<String, Object> formDef = new HashMap<String, Object>(); formDef.put("table_id", tableId); formDef.put("model", orderedDefns.getDataModel()); wrapper.put("formDef", formDef); wrapper.put("data", values); wrapper.put("metadata", new HashMap<String, Object>()); HashMap<String, Object> elem = (HashMap<String, Object>) wrapper.get("metadata"); if (instanceName != null) { elem.put("instanceName", instanceName); } elem.put("saved", "COMPLETE"); elem.put("timestamp", datestamp); b.append(ODKFileUtils.mapper.writeValueAsString(wrapper)); // OK we have the document in the builder (b). String doc = b.toString(); exportFile(doc, submissionXml, logger); } exportFile(freturn.serializeUriFragmentList(getContext()), manifest, logger); return ParcelFileDescriptor.open(manifest, ParcelFileDescriptor.MODE_READ_ONLY); } } finally { if (c != null && !c.isClosed()) { c.close(); c = null; } } } catch (ParserConfigurationException e) { logger.printStackTrace(e); } catch (TransformerException e) { logger.printStackTrace(e); } catch (JsonParseException e) { logger.printStackTrace(e); } catch (JsonMappingException e) { logger.printStackTrace(e); } catch (IOException e) { logger.printStackTrace(e); } } finally { if (db != null) { try { // release the reference... // this does not necessarily close the db handle // or terminate any pending transaction db.releaseReference(); } finally { // this will release the final reference and close the database OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName, dbHandleName); } } } return null; }
From source file:adalid.util.meta.sql.MetaFolderSql.java
private void updateFolders(FileWrapper fileWrapper) { File parent = fileWrapper.getFile().getParentFile(); if (parent != null) { FolderWrapper parentWrapper;//from w w w . j a va2 s . co m Path parentPath = getRelativeToBasePath(parent); if (folders.containsKey(parentPath)) { parentWrapper = folders.get(parentPath); } else { parentWrapper = new FolderWrapper(parent); folders.put(parentPath, parentWrapper); } parentWrapper.getBytesSizes().get(fileWrapper.getBytesSize()).next(); parentWrapper.getLinesSizes().get(fileWrapper.getLinesSize()).next(); parentWrapper.setLocalFiles(parentWrapper.getLocalFiles() + 1); parentWrapper.setLocalBytes(parentWrapper.getLocalBytes() + fileWrapper.getBytes()); parentWrapper.setLocalLines(parentWrapper.getLocalLines() + fileWrapper.getLines()); parentWrapper.setTotalFiles(parentWrapper.getTotalFiles() + 1); parentWrapper.setTotalBytes(parentWrapper.getTotalBytes() + fileWrapper.getBytes()); parentWrapper.setTotalLines(parentWrapper.getTotalLines() + fileWrapper.getLines()); if (parent.equals(metaFolder)) { } else { updateFolders(fileWrapper, parent); } } }
From source file:ome.services.blitz.repo.PublicRepositoryI.java
/** * Get the file object at a path.// w w w .ja va 2 s . c om * * @param path * A path on a repository. * @return File object * */ private File checkPath(String path) throws ValidationException { if (path == null || path.length() == 0) { throw new ValidationException(null, null, "Path is empty"); } boolean found = false; File file = new File(path).getAbsoluteFile(); while (true) { if (file.equals(root)) { found = true; break; } file = file.getParentFile(); if (file == null) { break; } } if (!found) { throw new ValidationException(null, null, path + " is not within " + root.getAbsolutePath()); } return new File(path).getAbsoluteFile(); }
From source file:com.android.sdklib.internal.repository.archives.ArchiveInstaller.java
/** * Install the given archive in the given folder. *//*ww w . j a va 2s. c om*/ private boolean unarchive(ArchiveReplacement archiveInfo, String osSdkRoot, File archiveFile, SdkManager sdkManager, ITaskMonitor monitor) { boolean success = false; Archive newArchive = archiveInfo.getNewArchive(); Package pkg = newArchive.getParentPackage(); String pkgName = pkg.getShortDescription(); monitor.setDescription("Installing %1$s", pkgName); monitor.log("Installing %1$s", pkgName); // Ideally we want to always unzip in a temp folder which name depends on the package // type (e.g. addon, tools, etc.) and then move the folder to the destination folder. // If the destination folder exists, it will be renamed and deleted at the very // end if everything succeeded. This provides a nice atomic swap and should leave the // original folder untouched in case something wrong (e.g. program crash) in the // middle of the unzip operation. // // However that doesn't work on Windows, we always end up not being able to move the // new folder. There are actually 2 cases: // A- A process such as a the explorer is locking the *old* folder or a file inside // (e.g. adb.exe) // In this case we really shouldn't be tried to work around it and we need to let // the user know and let it close apps that access that folder. // B- A process is locking the *new* folder. Very often this turns to be a file indexer // or an anti-virus that is busy scanning the new folder that we just unzipped. // // So we're going to change the strategy: // 1- Try to move the old folder to a temp/old folder. This might fail in case of issue A. // Note: for platform-tools, we can try killing adb first. // If it still fails, we do nothing and ask the user to terminate apps that can be // locking that folder. // 2- Once the old folder is out of the way, we unzip the archive directly into the // optimal new location. We no longer unzip it in a temp folder and move it since we // know that's what fails in most of the cases. // 3- If the unzip fails, remove everything and try to restore the old folder by doing // a *copy* in place and not a folder move (which will likely fail too). String pkgKind = pkg.getClass().getSimpleName(); File destFolder = null; File oldDestFolder = null; try { // -0- Compute destination directory and check install pre-conditions destFolder = pkg.getInstallFolder(osSdkRoot, sdkManager); if (destFolder == null) { // this should not seriously happen. monitor.log("Failed to compute installation directory for %1$s.", pkgName); return false; } if (!pkg.preInstallHook(newArchive, monitor, osSdkRoot, destFolder)) { monitor.log("Skipping archive: %1$s", pkgName); return false; } // -1- move old folder. if (mFileOp.exists(destFolder)) { // Create a new temp/old dir if (oldDestFolder == null) { oldDestFolder = getNewTempFolder(osSdkRoot, pkgKind, "old"); //$NON-NLS-1$ } if (oldDestFolder == null) { // this should not seriously happen. monitor.logError("Failed to find a temp directory in %1$s.", osSdkRoot); return false; } // Try to move the current dest dir to the temp/old one. Tell the user if it failed. while (true) { if (!moveFolder(destFolder, oldDestFolder)) { monitor.logError("Failed to rename directory %1$s to %2$s.", destFolder.getPath(), oldDestFolder.getPath()); if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_WINDOWS) { boolean tryAgain = true; tryAgain = windowsDestDirLocked(osSdkRoot, destFolder, monitor); if (tryAgain) { // loop, trying to rename the temp dir into the destination continue; } else { return false; } } } break; } } assert !mFileOp.exists(destFolder); // -2- Unzip new content directly in place. if (!mFileOp.mkdirs(destFolder)) { monitor.logError("Failed to create directory %1$s", destFolder.getPath()); return false; } if (!unzipFolder(archiveInfo, archiveFile, destFolder, monitor)) { return false; } if (!generateSourceProperties(newArchive, destFolder)) { monitor.logError("Failed to generate source.properties in directory %1$s", destFolder.getPath()); return false; } // In case of success, if we were replacing an archive // and the older one had a different path, remove it now. Archive oldArchive = archiveInfo.getReplaced(); if (oldArchive != null && oldArchive.isLocal()) { String oldPath = oldArchive.getLocalOsPath(); File oldFolder = oldPath == null ? null : new File(oldPath); if (oldFolder == null && oldArchive.getParentPackage() != null) { oldFolder = oldArchive.getParentPackage().getInstallFolder(osSdkRoot, sdkManager); } if (oldFolder != null && mFileOp.exists(oldFolder) && !oldFolder.equals(destFolder)) { monitor.logVerbose("Removing old archive at %1$s", oldFolder.getAbsolutePath()); mFileOp.deleteFileOrFolder(oldFolder); } } success = true; pkg.postInstallHook(newArchive, monitor, destFolder); return true; } finally { if (!success) { // In case of failure, we try to restore the old folder content. if (oldDestFolder != null) { restoreFolder(oldDestFolder, destFolder); } // We also call the postInstallHool with a null directory to give a chance // to the archive to cleanup after preInstallHook. pkg.postInstallHook(newArchive, monitor, null /*installDir*/); } // Cleanup if the unzip folder is still set. mFileOp.deleteFileOrFolder(oldDestFolder); } }