Example usage for java.io File equals

List of usage examples for java.io File equals

Introduction

In this page you can find the example usage for java.io File equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Tests this abstract pathname for equality with the given object.

Usage

From source file:de.innovationgate.wgpublisher.plugins.WGAPluginSet.java

protected synchronized WGAPlugin installPlugin(File file, int updateStrategy, boolean workspace,
        boolean defaultPlugin, String replaceKey) throws PluginException {

    try {/*from  w  w  w  .  ja va2s.co  m*/

        WGAPlugin sourcePlugin = createPlugin(file.getAbsolutePath());

        if (!_workspaceSet) {
            _core.getLog().info("Installing plugin " + sourcePlugin.getPluginID().getUniqueName() + " Version "
                    + sourcePlugin.getPluginID().getVersion().toString());
        }

        // Determine if a plugin of that id already exists
        boolean existed = false;

        WGAPlugin previousPlugin = getPluginByID(sourcePlugin.getPluginID());
        if (previousPlugin != null) {
            if (!_workspaceSet) {
                File prevPluginFile = previousPlugin.getPluginFile();
                if (!prevPluginFile.exists()) {
                    _core.getLog().info("Previous plugin file does no longer exist");
                } else if (prevPluginFile.isFile()) {
                    if (!previousPlugin.isDefaultPlugin()) {
                        _core.getLog().info(
                                "Removing previous file for plugin " + previousPlugin.getPluginID().toString());
                        prevPluginFile.delete();
                    } else {
                        _core.getLog().warn(
                                "You are overwriting a default plugin. The previous version, if still available, will stay and may be reinstalled automatically.");
                    }
                } else {
                    _core.getLog().info("Previous plugin file was a directory and will not be deleted");
                }
            }
            existed = true;
        }

        String fileName = sourcePlugin.getPluginID().buildQualifiedFileName();
        File targetFile = new File(getPluginFilesDir(), fileName);

        // Normal mode: Copy source to target file. 
        if (!workspace && !defaultPlugin && file.isFile() && !targetFile.equals(file)) {
            InputStream in = new FileInputStream(file);
            OutputStream out = new FileOutputStream(targetFile);
            WGUtils.inToOut(in, out, 2048);
            in.close();
            out.close();

        }
        // Developer plugins, default plugins or reinstalled plugin from plugins folder: Just use the source file
        else {
            targetFile = file;
        }

        WGAPlugin targetPlugin = null;

        // If there already was a plugin file try to find an existing plugin definition. 
        // If so, just tell it to reconnect, change nothing else
        if (existed) {
            targetPlugin = getPluginByID(sourcePlugin.getPluginID());
            if (targetPlugin != null) {
                targetPlugin.setFilePath(getCore().createWGAFilePath(targetFile));
                targetPlugin.setDefaultPlugin(defaultPlugin);
                targetPlugin.setReconnectDatabase(true);
                targetPlugin.setUpdateStatus(WGAPlugin.UPDATESTATUS_UPDATE_IDENTICAL);
                targetPlugin.getRuntimeContext().setUpdated(true);
                targetPlugin.init();
                if (!workspace) {
                    if (targetPlugin.isActive()) {
                        return activatePlugin(targetPlugin, updateStrategy, workspace,
                                targetPlugin.getInstallationKey());
                    }
                } else {
                    // In workspace mode we must fake that the source plugin was installed, as we do not touch the target plugin
                    sourcePlugin.setInstallationKey(targetPlugin.getInstallationKey());
                    sourcePlugin.setActive(targetPlugin.isActive());
                    return sourcePlugin;
                }
            }
        }

        // If plugin did not exist yet, create a new one for the target
        targetPlugin = createPlugin(getCore().createWGAFilePath(targetFile));
        targetPlugin.setDefaultPlugin(defaultPlugin);

        // Determine if the current installation status of this plugin is deactivated (plugins exist but are all inactive) REMOVED PER #00000867
        // boolean isPluginDeactivated = isPluginDeactivated(targetPlugin.getPluginID().getUniqueName());

        // Install it and activate it unless it was deactivated before
        _plugins.add(targetPlugin);
        return activatePlugin(targetPlugin, updateStrategy, workspace, replaceKey);

    } catch (PluginException e) {
        throw e;
    } catch (InvalidPluginException e) {
        throw new PluginException(e.getMessage(), e.getCause());
    } catch (Exception e) {
        throw new PluginException("Exception installing plugin", e);
    }

}

From source file:org.apache.hadoop.hdfs.server.namenode.TestNameNodeMXBean.java

@SuppressWarnings({ "unchecked" })
@Test//from w  w w. j a va 2  s .co m
public void testNameNodeMXBeanInfo() throws Exception {
    Configuration conf = new Configuration();
    conf.setLong(DFSConfigKeys.DFS_DATANODE_MAX_LOCKED_MEMORY_KEY,
            NativeIO.POSIX.getCacheManipulator().getMemlockLimit());
    MiniDFSCluster cluster = null;

    try {
        cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
        cluster.waitActive();

        FSNamesystem fsn = cluster.getNameNode().namesystem;

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName mxbeanName = new ObjectName("Hadoop:service=NameNode,name=NameNodeInfo");
        // get attribute "ClusterId"
        String clusterId = (String) mbs.getAttribute(mxbeanName, "ClusterId");
        assertEquals(fsn.getClusterId(), clusterId);
        // get attribute "BlockPoolId"
        String blockpoolId = (String) mbs.getAttribute(mxbeanName, "BlockPoolId");
        assertEquals(fsn.getBlockPoolId(), blockpoolId);
        // get attribute "Version"
        String version = (String) mbs.getAttribute(mxbeanName, "Version");
        assertEquals(fsn.getVersion(), version);
        assertTrue(version.equals(VersionInfo.getVersion() + ", r" + VersionInfo.getRevision()));
        // get attribute "Used"
        Long used = (Long) mbs.getAttribute(mxbeanName, "Used");
        assertEquals(fsn.getUsed(), used.longValue());
        // get attribute "Total"
        Long total = (Long) mbs.getAttribute(mxbeanName, "Total");
        assertEquals(fsn.getTotal(), total.longValue());
        // get attribute "safemode"
        String safemode = (String) mbs.getAttribute(mxbeanName, "Safemode");
        assertEquals(fsn.getSafemode(), safemode);
        // get attribute nondfs
        Long nondfs = (Long) (mbs.getAttribute(mxbeanName, "NonDfsUsedSpace"));
        assertEquals(fsn.getNonDfsUsedSpace(), nondfs.longValue());
        // get attribute percentremaining
        Float percentremaining = (Float) (mbs.getAttribute(mxbeanName, "PercentRemaining"));
        assertEquals(fsn.getPercentRemaining(), percentremaining, DELTA);
        // get attribute Totalblocks
        Long totalblocks = (Long) (mbs.getAttribute(mxbeanName, "TotalBlocks"));
        assertEquals(fsn.getTotalBlocks(), totalblocks.longValue());
        // get attribute alivenodeinfo
        String alivenodeinfo = (String) (mbs.getAttribute(mxbeanName, "LiveNodes"));
        Map<String, Map<String, Object>> liveNodes = (Map<String, Map<String, Object>>) JSON
                .parse(alivenodeinfo);
        assertTrue(liveNodes.size() == 2);
        for (Map<String, Object> liveNode : liveNodes.values()) {
            assertTrue(liveNode.containsKey("nonDfsUsedSpace"));
            assertTrue(((Long) liveNode.get("nonDfsUsedSpace")) > 0);
            assertTrue(liveNode.containsKey("capacity"));
            assertTrue(((Long) liveNode.get("capacity")) > 0);
            assertTrue(liveNode.containsKey("numBlocks"));
            assertTrue(((Long) liveNode.get("numBlocks")) == 0);
        }
        assertEquals(fsn.getLiveNodes(), alivenodeinfo);
        // get attribute deadnodeinfo
        String deadnodeinfo = (String) (mbs.getAttribute(mxbeanName, "DeadNodes"));
        assertEquals(fsn.getDeadNodes(), deadnodeinfo);
        // get attribute NodeUsage
        String nodeUsage = (String) (mbs.getAttribute(mxbeanName, "NodeUsage"));
        assertEquals("Bad value for NodeUsage", fsn.getNodeUsage(), nodeUsage);
        // get attribute NameJournalStatus
        String nameJournalStatus = (String) (mbs.getAttribute(mxbeanName, "NameJournalStatus"));
        assertEquals("Bad value for NameJournalStatus", fsn.getNameJournalStatus(), nameJournalStatus);
        // get attribute JournalTransactionInfo
        String journalTxnInfo = (String) mbs.getAttribute(mxbeanName, "JournalTransactionInfo");
        assertEquals("Bad value for NameTxnIds", fsn.getJournalTransactionInfo(), journalTxnInfo);
        // get attribute "NNStarted"
        String nnStarted = (String) mbs.getAttribute(mxbeanName, "NNStarted");
        assertEquals("Bad value for NNStarted", fsn.getNNStarted(), nnStarted);
        // get attribute "CompileInfo"
        String compileInfo = (String) mbs.getAttribute(mxbeanName, "CompileInfo");
        assertEquals("Bad value for CompileInfo", fsn.getCompileInfo(), compileInfo);
        // get attribute CorruptFiles
        String corruptFiles = (String) (mbs.getAttribute(mxbeanName, "CorruptFiles"));
        assertEquals("Bad value for CorruptFiles", fsn.getCorruptFiles(), corruptFiles);
        // get attribute NameDirStatuses
        String nameDirStatuses = (String) (mbs.getAttribute(mxbeanName, "NameDirStatuses"));
        assertEquals(fsn.getNameDirStatuses(), nameDirStatuses);
        Map<String, Map<String, String>> statusMap = (Map<String, Map<String, String>>) JSON
                .parse(nameDirStatuses);
        Collection<URI> nameDirUris = cluster.getNameDirs(0);
        for (URI nameDirUri : nameDirUris) {
            File nameDir = new File(nameDirUri);
            System.out.println("Checking for the presence of " + nameDir + " in active name dirs.");
            assertTrue(statusMap.get("active").containsKey(nameDir.getAbsolutePath()));
        }
        assertEquals(2, statusMap.get("active").size());
        assertEquals(0, statusMap.get("failed").size());

        // This will cause the first dir to fail.
        File failedNameDir = new File(nameDirUris.iterator().next());
        assertEquals(0, FileUtil.chmod(new File(failedNameDir, "current").getAbsolutePath(), "000"));
        cluster.getNameNodeRpc().rollEditLog();

        nameDirStatuses = (String) (mbs.getAttribute(mxbeanName, "NameDirStatuses"));
        statusMap = (Map<String, Map<String, String>>) JSON.parse(nameDirStatuses);
        for (URI nameDirUri : nameDirUris) {
            File nameDir = new File(nameDirUri);
            String expectedStatus = nameDir.equals(failedNameDir) ? "failed" : "active";
            System.out.println(
                    "Checking for the presence of " + nameDir + " in " + expectedStatus + " name dirs.");
            assertTrue(statusMap.get(expectedStatus).containsKey(nameDir.getAbsolutePath()));
        }
        assertEquals(1, statusMap.get("active").size());
        assertEquals(1, statusMap.get("failed").size());
        assertEquals(0L, mbs.getAttribute(mxbeanName, "CacheUsed"));
        assertEquals(NativeIO.POSIX.getCacheManipulator().getMemlockLimit() * cluster.getDataNodes().size(),
                mbs.getAttribute(mxbeanName, "CacheCapacity"));
        assertNull("RollingUpgradeInfo should be null when there is no rolling" + " upgrade",
                mbs.getAttribute(mxbeanName, "RollingUpgradeStatus"));
    } finally {
        if (cluster != null) {
            for (URI dir : cluster.getNameDirs(0)) {
                FileUtil.chmod(new File(new File(dir), "current").getAbsolutePath(), "755");
            }
            cluster.shutdown();
        }
    }
}

From source file:org.opendatakit.survey.android.provider.SubmissionProvider.java

/**
 * The incoming URI is of the form:/*from   w w  w.  jav a2s.c om*/
 * ..../appName/tableId/instanceId?formId=&formVersion=
 *
 * where instanceId is the DataTableColumns._ID
 */
@SuppressWarnings("unchecked")
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
    final boolean asXml = uri.getAuthority().equalsIgnoreCase(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);
    }

    final String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    final String tableId = segments.get(1);
    final String instanceId = segments.get(2);
    final String submissionInstanceId = segments.get(3);

    SQLiteDatabase db = null;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);

        boolean success = false;
        try {
            success = ODKDatabaseUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("Unknown URI (exception testing for tableId) " + uri);
        }
        if (!success) {
            throw new SQLException("Unknown URI (missing data table for tableId) " + uri);
        }

        final String dbTableName = "\"" + tableId + "\"";

        // 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);
                if (c.getCount() > 0) {
                    c.moveToFirst();
                    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;
            }

            ArrayList<ColumnDefinition> orderedDefns = TableUtil.get().getColumnDefinitions(db, appName,
                    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(dbTableName).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(dbTableName).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 {
                c = db.rawQuery(b.toString(), selectionArgs);
                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 = ColumnDefinition.find(orderedDefns, columnName);
                        } catch (IllegalArgumentException e) {
                            // ignore...
                        }
                        if (defn != null && !c.isNull(i)) {
                            if (xmlInstanceName != null && defn.getElementName().equals(xmlInstanceName)) {
                                instanceName = ODKDatabaseUtils.get().getIndexAsString(c, i);
                            }
                            // user-defined column
                            ElementType type = defn.getType();
                            ElementDataType dataType = type.getDataType();

                            log.i(t, "element type: " + defn.getElementType());
                            if (dataType == ElementDataType.integer) {
                                Integer value = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.number) {
                                Double value = ODKDatabaseUtils.get().getIndexAsType(c, Double.class, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.bool) {
                                Integer tmp = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class, i);
                                Boolean value = tmp == null ? null : (tmp != 0);
                                putElementValue(values, defn, value);
                            } else if (type.getElementType().equals("date")) {
                                String value = ODKDatabaseUtils.get().getIndexAsString(c, i);
                                String jrDatestamp = (value == null) ? null
                                        : (new SimpleDateFormat(ISO8601_DATE_ONLY_FORMAT, Locale.ENGLISH))
                                                .format(new Date(TableConstants.milliSecondsFromNanos(value)));
                                putElementValue(values, defn, jrDatestamp);
                            } else if (type.getElementType().equals("dateTime")) {
                                String value = ODKDatabaseUtils.get().getIndexAsString(c, i);
                                String jrDatestamp = (value == null) ? null
                                        : (new SimpleDateFormat(ISO8601_DATE_FORMAT, Locale.ENGLISH))
                                                .format(new Date(TableConstants.milliSecondsFromNanos(value)));
                                putElementValue(values, defn, jrDatestamp);
                            } else if (type.getElementType().equals("time")) {
                                String value = ODKDatabaseUtils.get().getIndexAsString(c, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.array) {
                                ArrayList<Object> al = ODKDatabaseUtils.get().getIndexAsType(c, ArrayList.class,
                                        i);
                                putElementValue(values, defn, al);
                            } else if (dataType == ElementDataType.string) {
                                String value = ODKDatabaseUtils.get().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 = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.ROW_ETAG)) {
                            rowETag = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FILTER_TYPE)) {
                            filterType = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FILTER_VALUE)) {
                            filterValue = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FORM_ID)) {
                            formId = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.LOCALE)) {
                            locale = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FORM_ID)) {
                            formId = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.SAVEPOINT_TYPE)) {
                            savepointType = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.SAVEPOINT_CREATOR)) {
                            savepointCreator = ODKDatabaseUtils.get().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) {
                            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.ENGLISH))
                                .format(new Date(TableConstants.milliSecondsFromNanos(savepointTimestamp)));

                        // For XML, we traverse the map to serialize it
                        Document d = new Document();
                        d.setStandalone(true);
                        d.setEncoding(CharEncoding.UTF_8);
                        Element e = d.createElement(XML_DEFAULT_NAMESPACE,
                                (xmlRootElementName == null) ? "data" : xmlRootElementName);
                        e.setPrefix("jr", XML_OPENROSA_NAMESPACE);
                        e.setPrefix("", XML_DEFAULT_NAMESPACE);
                        d.addChild(0, Node.ELEMENT, e);
                        e.setAttribute("", "id", tableId);
                        DynamicPropertiesCallback cb = new DynamicPropertiesCallback(getContext(), appName,
                                tableId, instanceId);

                        int idx = 0;
                        Element meta = d.createElement(XML_OPENROSA_NAMESPACE, "meta");

                        Element v = d.createElement(XML_OPENROSA_NAMESPACE, "instanceID");
                        v.addChild(0, Node.TEXT, submissionInstanceId);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        if (xmlDeviceIdPropertyName != null) {
                            String deviceId = propertyManager.getSingularProperty(xmlDeviceIdPropertyName, cb);
                            if (deviceId != null) {
                                v = d.createElement(XML_OPENROSA_NAMESPACE, "deviceID");
                                v.addChild(0, Node.TEXT, deviceId);
                                meta.addChild(idx++, Node.ELEMENT, v);
                                meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                            }
                        }
                        if (xmlUserIdPropertyName != null) {
                            String userId = propertyManager.getSingularProperty(xmlUserIdPropertyName, cb);
                            if (userId != null) {
                                v = d.createElement(XML_OPENROSA_NAMESPACE, "userID");
                                v.addChild(0, Node.TEXT, userId);
                                meta.addChild(idx++, Node.ELEMENT, v);
                                meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                            }
                        }
                        v = d.createElement(XML_OPENROSA_NAMESPACE, "timeEnd");
                        v.addChild(0, Node.TEXT, datestamp);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // these are extra metadata tags...
                        if (instanceName != null) {
                            v = d.createElement(XML_DEFAULT_NAMESPACE, "instanceName");
                            v.addChild(0, Node.TEXT, instanceName);
                            meta.addChild(idx++, Node.ELEMENT, v);
                            meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                        } else {
                            v = d.createElement(XML_DEFAULT_NAMESPACE, "instanceName");
                            v.addChild(0, Node.TEXT, savepointTimestamp);
                            meta.addChild(idx++, Node.ELEMENT, v);
                            meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                        }

                        // these are extra metadata tags...
                        // rowID
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "rowID");
                        v.addChild(0, Node.TEXT, instanceId);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // rowETag
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "rowETag");
                        if (rowETag != null) {
                            v.addChild(0, Node.TEXT, rowETag);
                        }
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // filterType
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "filterType");
                        if (filterType != null) {
                            v.addChild(0, Node.TEXT, filterType);
                        }
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // filterValue
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "filterValue");
                        if (filterValue != null) {
                            v.addChild(0, Node.TEXT, filterValue);
                        }
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // formID
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "formID");
                        v.addChild(0, Node.TEXT, formId);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // locale
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "locale");
                        v.addChild(0, Node.TEXT, locale);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // savepointType
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "savepointType");
                        v.addChild(0, Node.TEXT, savepointType);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // savepointCreator
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "savepointCreator");
                        if (savepointCreator != null) {
                            v.addChild(0, Node.TEXT, savepointCreator);
                        }
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // savepointTimestamp
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "savepointTimestamp");
                        v.addChild(0, Node.TEXT, savepointTimestamp);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // and insert the meta block into the XML

                        e.addChild(0, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                        e.addChild(1, Node.ELEMENT, meta);
                        e.addChild(2, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        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, log);
                        }

                        KXmlSerializer serializer = new KXmlSerializer();

                        ByteArrayOutputStream bo = new ByteArrayOutputStream();
                        serializer.setOutput(bo, CharEncoding.UTF_8);
                        // setting the response content type emits the
                        // xml header.
                        // just write the body here...
                        d.writeChildren(serializer);
                        serializer.flush();
                        bo.close();

                        b.append(bo.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, log);
                        }

                    } else {
                        // Pre-processing -- collapse all mimeUri into filename
                        for (ColumnDefinition defn : orderedDefns) {
                            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", ColumnDefinition.getDataModel(orderedDefns));
                        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, log);
                    }
                    exportFile(freturn.serializeUriFragmentList(getContext()), manifest, log);
                    return ParcelFileDescriptor.open(manifest, ParcelFileDescriptor.MODE_READ_ONLY);

                }
            } finally {
                if (c != null && !c.isClosed()) {
                    c.close();
                }
            }

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } finally {
        if (db != null) {
            db.close();
        }
    }
    return null;
}

From source file:org.datacleaner.user.DataCleanerConfigurationReader.java

private void loadExtensions(UserPreferences userPreferences) {
    final String dumpInstallKey = "org.datacleaner.extension.dumpinstall";
    final File extensionsDirectory = userPreferences.getExtensionsDirectory();

    final Set<String> extensionFilenames = new HashSet<String>();
    final List<ExtensionPackage> extensionPackages = userPreferences.getExtensionPackages();
    for (Iterator<ExtensionPackage> it = extensionPackages.iterator(); it.hasNext();) {
        final ExtensionPackage extensionPackage = (ExtensionPackage) it.next();

        // some extensions may be installed simply by "dumping" a JAR in the
        // extension folder. Such installs will have this key registered.
        final boolean dumpInstalled = "true"
                .equals(extensionPackage.getAdditionalProperties().get(dumpInstallKey));
        boolean remove = false;

        final File[] files = extensionPackage.getFiles();
        for (File file : files) {
            if (dumpInstalled && !file.exists()) {
                // file has been removed, we'll remove this extension
                remove = true;/*from   w w  w.j av a 2s.co  m*/
                break;
            } else {
                final File directory = file.getParentFile();
                if (extensionsDirectory.equals(directory)) {
                    extensionFilenames.add(file.getName());
                }
            }
        }

        if (remove) {
            it.remove();
        } else {
            extensionPackage.loadExtension();
        }
    }

    // Read all JAR files in the 'extensions' directory and register those
    // that are not already loaded.
    final File[] jarFiles = extensionsDirectory.listFiles(FileFilters.JAR);
    if (jarFiles != null) {
        for (File file : jarFiles) {
            final String filename = file.getName();
            if (!extensionFilenames.contains(filename)) {
                logger.info("Adding extension from 'extension' folder: {}", file.getName());
                ExtensionReader reader = new ExtensionReader();
                ExtensionPackage extension = reader.readExternalExtension(file);
                userPreferences.addExtensionPackage(extension);
                extension.getAdditionalProperties().put(dumpInstallKey, "true");
                extension.loadExtension();
            }
        }
    }

    // List directories and treat each sub directory with JAR files as
    // an extension
    final File[] subDirectories = extensionsDirectory.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            return file.isDirectory();
        }
    });
    if (subDirectories != null) {
        for (File subDirectory : subDirectories) {
            final String directoryName = subDirectory.getName();
            if (!extensionFilenames.contains(directoryName)) {
                logger.info("Adding extension from 'extension' folder: {}", directoryName);
                ExtensionReader reader = new ExtensionReader();
                ExtensionPackage extension = reader.readExternalExtension(subDirectory);
                if (extension != null) {
                    userPreferences.addExtensionPackage(extension);
                    extension.getAdditionalProperties().put(dumpInstallKey, "true");
                    extension.loadExtension();
                }
            }
        }
    }
}

From source file:fr.msch.wissl.server.REST.java

@POST
@Path("folders/remove")
public void removeMusicFolders(@FormParam("directory[]") String[] directory)
        throws SecurityError, SQLException {
    long l1 = System.nanoTime();
    String sid = (sessionIdHeader == null ? sessionIdGet : sessionIdHeader);
    Session sess = Session.check(sid, request.getRemoteAddr(), userAgent, true);

    if (directory != null) {
        List<String> music = Config.getMusicPath();
        for (String dir : directory) {
            if (!music.contains(dir)) {
                throw new IllegalArgumentException("Directory '" + dir + "' is not a music folder");
            }/*from   w  ww.  j  av a 2 s . c  o  m*/
        }

        for (String dir : directory) {
            File toDelete = new File(dir);
            for (Iterator<String> it = music.iterator(); it.hasNext();) {
                String path = it.next();
                File f = new File(path);
                if (f.equals(toDelete)) {
                    it.remove();
                    DB.get().removeFolder(path);
                }
            }
        }
    }
    Library.interrupt();

    nocache();
    log(sess, l1);
}

From source file:org.eobjects.datacleaner.user.DataCleanerConfigurationReader.java

private void loadExtensions(UserPreferences userPreferences) {
    final String dumpInstallKey = "org.eobjects.datacleaner.extension.dumpinstall";
    final File extensionsDirectory = userPreferences.getExtensionsDirectory();

    final Set<String> extensionFilenames = new HashSet<String>();
    final List<ExtensionPackage> extensionPackages = userPreferences.getExtensionPackages();
    for (Iterator<ExtensionPackage> it = extensionPackages.iterator(); it.hasNext();) {
        final ExtensionPackage extensionPackage = (ExtensionPackage) it.next();

        // some extensions may be installed simply by "dumping" a JAR in the
        // extension folder. Such installs will have this key registered.
        final boolean dumpInstalled = "true"
                .equals(extensionPackage.getAdditionalProperties().get(dumpInstallKey));
        boolean remove = false;

        final File[] files = extensionPackage.getFiles();
        for (File file : files) {
            if (dumpInstalled && !file.exists()) {
                // file has been removed, we'll remove this extension
                remove = true;//from   w  ww  . j  a v a 2 s .  co  m
                break;
            } else {
                final File directory = file.getParentFile();
                if (extensionsDirectory.equals(directory)) {
                    extensionFilenames.add(file.getName());
                }
            }
        }

        if (remove) {
            it.remove();
        } else {
            extensionPackage.loadExtension();
        }
    }

    // Read all JAR files in the 'extensions' directory and register those
    // that are not already loaded.
    final File[] jarFiles = extensionsDirectory.listFiles(FileFilters.JAR);
    if (jarFiles != null) {
        for (File file : jarFiles) {
            final String filename = file.getName();
            if (!extensionFilenames.contains(filename)) {
                logger.info("Adding extension from 'extension' folder: {}", file.getName());
                ExtensionReader reader = new ExtensionReader();
                ExtensionPackage extension = reader.readExternalExtension(file);
                userPreferences.addExtensionPackage(extension);
                extension.getAdditionalProperties().put(dumpInstallKey, "true");
                extension.loadExtension();
            }
        }
    }

    // List directories and treat each sub directory with JAR files as
    // an extension
    final File[] subDirectories = extensionsDirectory.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            return file.isDirectory();
        }
    });
    if (subDirectories != null) {
        for (File subDirectory : subDirectories) {
            final String directoryName = subDirectory.getName();
            if (!extensionFilenames.contains(directoryName)) {
                logger.info("Adding extension from 'extension' folder: {}", directoryName);
                ExtensionReader reader = new ExtensionReader();
                ExtensionPackage extension = reader.readExternalExtension(subDirectory);
                if (extension != null) {
                    userPreferences.addExtensionPackage(extension);
                    extension.getAdditionalProperties().put(dumpInstallKey, "true");
                    extension.loadExtension();
                }
            }
        }
    }
}

From source file:fr.avianey.androidsvgdrawable.SvgDrawablePlugin.java

public void execute() {
    // validating target densities specified in pom.xml
    // untargetted densities will be ignored except for the fallback density if specified
    final Set<Density> targetDensities = new HashSet<>(Arrays.asList(parameters.getTargetedDensities()));
    if (targetDensities.isEmpty()) {
        targetDensities.addAll(EnumSet.allOf(Density.class));
    }/*from www.  ja  v  a2  s.c o  m*/
    getLog().info("Targeted densities : " + Joiner.on(", ").join(targetDensities));

    /********************************
     * Load NinePatch configuration *
     ********************************/

    NinePatchMap ninePatchMap = new NinePatchMap();
    if (parameters.getNinePatchConfig() != null && parameters.getNinePatchConfig().isFile()) {
        getLog().info(
                "Loading NinePatch configuration file " + parameters.getNinePatchConfig().getAbsolutePath());
        try (final Reader reader = new FileReader(parameters.getNinePatchConfig())) {
            Type t = new TypeToken<Set<NinePatch>>() {
            }.getType();
            Set<NinePatch> ninePathSet = (Set<NinePatch>) (new GsonBuilder().create().fromJson(reader, t));
            ninePatchMap = NinePatch.init(ninePathSet);
        } catch (IOException e) {
            getLog().error(e);
        }
    } else {
        getLog().info("No NinePatch configuration file specified");
    }

    /*****************************
     * List input svg to convert *
     *****************************/

    getLog().info("Listing SVG files in " + parameters.getFrom().getAbsolutePath());
    final Collection<QualifiedResource> svgToConvert = listQualifiedResources(parameters.getFrom(), "svg");
    getLog().info("SVG files : " + Joiner.on(", ").join(svgToConvert));

    /*****************************
     * List input svgmask to use *
     *****************************/

    File svgMaskDirectory = parameters.getSvgMaskDirectory();
    File svgMaskResourcesDirectory = parameters.getSvgMaskResourcesDirectory();
    if (svgMaskDirectory == null) {
        svgMaskDirectory = parameters.getFrom();
    }
    if (svgMaskResourcesDirectory == null) {
        svgMaskResourcesDirectory = svgMaskDirectory;
    }
    getLog().info("Listing SVGMASK files in " + svgMaskDirectory.getAbsolutePath());
    final Collection<QualifiedResource> svgMasks = listQualifiedResources(svgMaskDirectory, "svgmask");
    final Collection<QualifiedResource> svgMaskResources = new ArrayList<>();
    getLog().info("SVGMASK files : " + Joiner.on(", ").join(svgMasks));
    if (!svgMasks.isEmpty()) {
        // list masked resources
        if (svgMaskResourcesDirectory.equals(parameters.getFrom())) {
            svgMaskResources.addAll(svgToConvert);
        } else {
            svgMaskResources.addAll(listQualifiedResources(svgMaskResourcesDirectory, "svg"));
        }
        getLog().info("SVG files to mask : " + Joiner.on(", ").join(svgMaskResources));
        // generate masked svg
        for (QualifiedResource maskFile : svgMasks) {
            getLog().info("Generating masked files for " + maskFile);
            try {
                Collection<QualifiedResource> generatedResources = new SvgMask(maskFile)
                        .generatesMaskedResources(parameters.getSvgMaskedSvgOutputDirectory(), svgMaskResources,
                                parameters.isUseSameSvgOnlyOnceInMask(), parameters.getOverrideMode());
                getLog().debug("+ " + Joiner.on(", ").join(generatedResources));
                svgToConvert.addAll(generatedResources);
            } catch (XPathExpressionException | TransformerException | ParserConfigurationException
                    | SAXException | IOException e) {
                getLog().error(e);
            }
        }
    } else {
        getLog().info("No SVGMASK file found.");
    }

    QualifiedResource highResIcon = null;

    /*********************************
     * Create svg in res/* folder(s) *
     *********************************/

    for (QualifiedResource svg : svgToConvert) {
        try {
            getLog().info(
                    "Transcoding " + FilenameUtils.getName(svg.getAbsolutePath()) + " to targeted densities");
            Rectangle bounds = extractSVGBounds(svg);
            if (getLog().isDebugEnabled()) {
                getLog().debug("+ source dimensions [width=" + bounds.getWidth() + " - height="
                        + bounds.getHeight() + "]");
            }
            if (parameters.getHighResIcon() != null && parameters.getHighResIcon().equals(svg.getName())) {
                highResIcon = svg;
            }
            // for each target density :
            // - find matching destinations :
            //   - matches all extra qualifiers
            //   - no other output with a qualifiers set that is a subset of this output
            // - if no match, create required directories
            for (Density d : targetDensities) {
                NinePatch ninePatch = ninePatchMap.getBestMatch(svg);
                File destination = svg.getOutputFor(d, parameters.getTo(),
                        ninePatch == null ? parameters.getOutputType() : OutputType.drawable);
                if (!destination.exists() && parameters.isCreateMissingDirectories()) {
                    destination.mkdirs();
                }
                if (destination.exists()) {
                    getLog().debug("Transcoding " + svg.getName() + " to " + destination.getName());
                    transcode(svg, d, bounds, destination, ninePatch);
                } else {
                    getLog().info("Qualified output " + destination.getName() + " does not exists. "
                            + "Set 'createMissingDirectories' to true if you want it to be created if missing...");
                }
            }
        } catch (IOException | TranscoderException | InstantiationException | IllegalAccessException e) {
            getLog().error("Error while converting " + svg, e);
        }
    }

    /******************************************
     * Generates the play store high res icon *
     ******************************************/

    if (highResIcon != null) {
        try {
            // TODO : add a garbage density (NO_DENSITY) for the highResIcon
            // TODO : make highResIcon size configurable
            // TODO : generates other play store assets
            // TODO : parameterized SIZE
            getLog().info("Generating high resolution icon");
            transcode(highResIcon, Density.mdpi, new File("."), 512, 512, null);
        } catch (IOException | TranscoderException | InstantiationException | IllegalAccessException e) {
            getLog().error("Error while converting " + highResIcon, e);
        }
    }
}

From source file:org.omegat.util.FileUtilTest.java

public void testCopyFilesTo() throws Exception {
    File targetDir = makeDir(base, "target");

    // Make structure to copy into targetDir
    File sourceDir = makeDir(base, "source");
    File file1 = writeFile(new File(sourceDir, "file1"), "file1-first");
    File file2 = writeFile(new File(sourceDir, "sub1/file2"), "file2-first");

    // Copy all files. Make sure they are identical.
    FileUtil.copyFilesTo(targetDir, sourceDir.listFiles(), null);
    final File file1trg = new File(targetDir, "file1");
    final File sub1trg = new File(targetDir, "sub1");
    final File file2trg = new File(targetDir, "sub1/file2");
    assertTrue(fileContentsAreEqual(file1, file1trg));
    assertTrue(new File(targetDir, "sub1").isDirectory());
    assertTrue(fileContentsAreEqual(file2, file2trg));

    // Modify source files.
    File file3 = new File(sourceDir, "file3");
    writeFile(file3, "file3-first");
    writeFile(file1, "file1-second");
    writeFile(file2, "file2-second");

    // Do copy but don't overwrite anything. Only file3 should be copied.
    FileUtil.copyFilesTo(targetDir, sourceDir.listFiles(), new ICollisionCallback() {
        @Override/*  w  w  w.j  a  v a  2s . co  m*/
        public boolean shouldReplace(File file, int thisFile, int totalFiles) {
            return false;
        }

        @Override
        public boolean isCanceled() {
            return false;
        }
    });
    File file3trg = new File(targetDir, "file3");
    assertFalse(fileContentsAreEqual(file1, file1trg));
    assertFalse(fileContentsAreEqual(file2, file2trg));
    assertTrue(fileContentsAreEqual(file3, file3trg));

    // Add sub1/file4 to target; this will disappear after replacing sub1. 
    File file4trg = writeFile(new File(targetDir, "sub1/file4"), "file4");

    // Do copy and overwrite sub1 only. sub1/file2 should be replaced
    // and sub1/file4 should disappear.
    FileUtil.copyFilesTo(targetDir, sourceDir.listFiles(), new ICollisionCallback() {
        @Override
        public boolean shouldReplace(File file, int thisFile, int totalFiles) {
            return file.equals(sub1trg);
        }

        @Override
        public boolean isCanceled() {
            return false;
        }
    });
    assertFalse(fileContentsAreEqual(file1, file1trg));
    assertTrue(fileContentsAreEqual(file2, file2trg));
    assertTrue(fileContentsAreEqual(file3, file3trg));
    assertFalse(file4trg.exists());

    // Do copy and cancel on last file. None of the files should be changed.
    // shouldReplace() should be called once for all files in source/.
    CountingCallback callback = new CountingCallback() {
        private boolean isCanceled = false;

        @Override
        public boolean shouldReplace(File file, int thisFile, int totalFiles) {
            calledTimes++;
            isCanceled = thisFile + 1 == totalFiles;
            return !isCanceled();
        }

        @Override
        public boolean isCanceled() {
            return isCanceled;
        }
    };
    FileUtil.copyFilesTo(targetDir, sourceDir.listFiles(), callback);
    assertEquals(sourceDir.listFiles().length, callback.calledTimes);
    assertFalse(fileContentsAreEqual(file1, file1trg));
    assertTrue(fileContentsAreEqual(file2, file2trg));
    assertTrue(fileContentsAreEqual(file3, file3trg));

    // Try copying to non-existent destination.
    File newTarget = new File(base, "newtarget");
    FileUtil.copyFilesTo(newTarget, sourceDir.listFiles(), null);
    assertTrue(newTarget.isDirectory());
    assertTrue(fileContentsAreEqual(file1, new File(newTarget, "file1")));

    // Try copying to destination that exists but is a file.
    File targetFile = writeFile(new File(base, "targetFile"), "");
    try {
        FileUtil.copyFilesTo(targetFile, sourceDir.listFiles(), null);
        fail("copyFilesTo should fail when target dir is a file.");
    } catch (IOException ex) {
    }
}

From source file:ir.ac.iust.nlp.postagger.POSTaggerForm.java

public void tagThreadFinished(String res) {
    btnStartTagging.setEnabled(true);/*w  w w .  java  2s .  c  om*/
    tabTag.setEnabledAt(1, true);

    lblTagEvaluation.setText(res);

    File modelFrom = new File(txtModelPath.getText());
    File modelTo = new File(System.getProperty("user.dir") + File.separator + modelFrom.getName());
    if (!modelFrom.equals(modelTo)) {
        deleteDirectory(modelTo);
    }
}

From source file:ir.ac.iust.nlp.postagger.POSTaggerForm.java

public void trainThreadFinished() {
    btnStartTraining.setEnabled(true);/* ww w  .  j a  va2s  . c  o  m*/

    File trainFrom = new File(txtTrainFile.getText());
    File trainTo = new File(System.getProperty("user.dir") + File.separator + trainFrom.getName());
    if (!trainFrom.equals(trainTo))
        trainTo.delete();

    File modelTo = new File(txtTrainModelPath.getText());
    File modelFrom = new File(System.getProperty("user.dir") + File.separator + modelTo.getName());
    if (!modelFrom.equals(modelTo)) {
        copyDirectory(modelFrom, modelTo);
        deleteDirectory(modelFrom);
    }
}