Example usage for org.apache.commons.io FileUtils moveFile

List of usage examples for org.apache.commons.io FileUtils moveFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils moveFile.

Prototype

public static void moveFile(File srcFile, File destFile) throws IOException 

Source Link

Document

Moves a file.

Usage

From source file:com.silverpeas.form.displayers.WysiwygFCKFieldDisplayer.java

private void moveOrCopy(ForeignPK fromPK, ForeignPK toPK, boolean copy, Map<String, String> oldAndNewFileIds)
        throws IOException {
    String fromPath = getPath(fromPK.getInstanceId());
    String toPath = getPath(toPK.getInstanceId());

    File from = new File(fromPath);
    if (from.exists()) {
        List<File> files = (List<File>) FileFolderManager.getAllFile(fromPath);
        for (File file : files) {
            String fileName = file.getName();
            if (fileName.startsWith(fromPK.getId() + "_")) {
                String fieldName = fileName.substring(fromPK.getId().length() + 1);
                File srcFile = new File(fromPath, file.getName());
                File destFile = new File(toPath, getFileName(fieldName, toPK.getId()));
                if (copy) {
                    // copy file and change images path (instanceId and imageId) inside
                    FileUtils.copyFile(srcFile, destFile);
                    changeImagePath(destFile, fromPK.getInstanceId(), toPK.getInstanceId(), oldAndNewFileIds);
                } else {
                    // move file and change images path (instanceId only) inside
                    FileUtils.moveFile(srcFile, destFile);
                    changeInstanceId(destFile, fromPK.getInstanceId(), toPK.getInstanceId());
                }//from ww w. ja  v a  2 s.  c om
                Iterator<String> languages = I18NHelper.getLanguages();
                while (languages.hasNext()) {
                    String language = languages.next();

                    if (fieldName.startsWith(language + "_")) {
                        fieldName = fieldName.substring(3); // skip en_
                        srcFile = new File(fromPath, file.getName());
                        destFile = new File(toPath, getFileName(fieldName, toPK.getId(), language));
                        if (copy) {
                            // copy file and change images path (instanceId and imageId) inside
                            FileUtils.copyFile(srcFile, destFile);
                            changeImagePath(destFile, fromPK.getInstanceId(), toPK.getInstanceId(),
                                    oldAndNewFileIds);
                        } else {
                            // move file and change images path (instanceId only) inside
                            FileUtils.moveFile(srcFile, destFile);
                            changeInstanceId(destFile, fromPK.getInstanceId(), toPK.getInstanceId());
                        }
                    }
                }
            }
        }
    }
}

From source file:au.org.ala.layers.intersect.Grid.java

public void replaceValues(Map<Integer, Integer> translation) {

    long length = ((long) nrows) * ((long) ncols);

    Integer minv = null;//from   ww  w .  jav  a  2s  .c  om
    Integer maxv = null;
    for (Integer i : translation.values()) {
        if (minv == null || i < minv)
            minv = i;
        if (maxv == null || i > maxv)
            maxv = i;
    }

    RandomAccessFile afile = null;
    RandomAccessFile out = null;
    File f2 = new File(filename + ".GRI");
    File newGrid = new File(filename + ".gri.new");

    try { //read of random access file can throw an exception
        out = new RandomAccessFile(newGrid, "rw");

        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        byte[] b = new byte[65536];
        byte[] bout = new byte[65536];

        long i = 0;
        long max = 0;
        long len;
        float v;
        float ndv = (float) nodatavalue;

        while ((len = afile.read(b)) > 0) {
            ByteBuffer bb = ByteBuffer.wrap(b);
            ByteBuffer bbout = ByteBuffer.wrap(bout);

            if (byteorderLSB) {
                bb.order(ByteOrder.LITTLE_ENDIAN);
                bbout.order(ByteOrder.LITTLE_ENDIAN);
            }

            if (datatype.equalsIgnoreCase("UBYTE")) {
                throw new Exception("UBYTE translation not supported");
            } else if (datatype.equalsIgnoreCase("BYTE")) {
                throw new Exception("BYTE translation not supported");
            } else if (datatype.equalsIgnoreCase("SHORT")) {
                max += len / 2;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getShort();
                    if (v != ndv && translation.get((int) (v * rescale)) == null) {
                        v = v;
                    }
                    if (v != ndv && translation.get((int) (v * rescale)) != null)
                        v = translation.get((int) (v * rescale));
                    bbout.putShort((short) v);
                }
            } else if (datatype.equalsIgnoreCase("INT")) {
                max += len / 4;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getInt();
                    if (v != ndv && translation.get((int) (v * rescale)) != null)
                        v = translation.get((int) (v * rescale));
                    bbout.putInt((int) v);
                }
            } else if (datatype.equalsIgnoreCase("LONG")) {
                max += len / 8;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getLong();
                    if (v != ndv && translation.get((int) (v * rescale)) != null)
                        v = translation.get((int) (v * rescale));
                    bbout.putLong((long) v);
                }
            } else if (datatype.equalsIgnoreCase("FLOAT")) {
                throw new Exception("FLOAT translation not supported");
            } else if (datatype.equalsIgnoreCase("DOUBLE")) {
                throw new Exception("DOUBLE translation not supported");
            } else {
                max += len / 4;
                for (; i < max; i++) {
                    // should not happen; catch anyway...
                }
            }

            out.write(bout, 0, (int) len);
        }

        writeHeader(filename + ".new", xmin, ymin, xmin + xres * ncols, ymin + yres * nrows, xres, yres, nrows,
                ncols, minv, maxv, datatype, nodatavalue + "");
    } catch (Exception e) {
        logger.error("An error has occurred getting grid class stats", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }

        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    try {
        if (!new File(filename + ".gri.old").exists())
            FileUtils.moveFile(new File(filename + ".gri"), new File(filename + ".gri.old"));
        if (!new File(filename + ".grd.old").exists())
            FileUtils.moveFile(new File(filename + ".grd"), new File(filename + ".grd.old"));

        FileUtils.moveFile(new File(filename + ".gri.new"), new File(filename + ".gri"));
        FileUtils.moveFile(new File(filename + ".new.grd"), new File(filename + ".grd"));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:ddf.test.itests.platform.TestConfiguration.java

private void backupCrl(Path source, Path destination) throws IOException {
    FileUtils.moveFile(source.toFile(), destination.toFile());
}

From source file:com.taobao.android.FastPatchTool.java

public void doPatch() throws IOException, PatchException, RecognitionException {
    MappingReader mappingReader = null;/* ww  w .  ja  v  a 2  s .  c  o  m*/
    MappingProcessor mappingProcessor = null;

    if (outDir == null || !outDir.exists()) {
        return;
    }
    outPatchFile = new File(outDir, "apatch-unsigned.apatch");

    if (mappingFile != null && mappingFile.exists()) {
        mappingReader = new MappingReader(mappingFile);
        mappingProcessor = new MappingProcessorImpl(superClassMap);
        mappingReader.pump(mappingProcessor);
        mappingProcessor.updateMethod();
        mappingProcessor.updateFieldType();
    }

    for (FastPatchObject fastPatchObject : patchObjects) {
        Set<ClassDef> classes = new HashSet<ClassDef>();
        Map<ClassDef, List<Method>> patchClassDefs = new HashMap<ClassDef, List<Method>>();
        Set<ClassDef> addedClasses = new HashSet<ClassDef>();
        Map<ClassDef, List<Method>> newClassDef = new HashMap<ClassDef, List<Method>>();

        ArrayList<Method> methods = new ArrayList<Method>();

        for (File dexFile : fastPatchObject.DexFiles) {
            DexFile dFile = DexFileFactory.loadDexFile(dexFile.getAbsolutePath(), 19, true);
            classes.addAll(dFile.getClasses());
        }
        final Set<ClassDef> newClasses = new HashSet<ClassDef>();
        for (ClassDef classDef : classes) {
            String type = classDef.getType();
            if (fastPatchObject.addedClass.contains(SmaliUtils.getDalvikClassName(type))) {
                System.out.println("patch added class:" + type);
                addedClasses.add(classDef);
                continue;
            }
            for (Map.Entry<String, List<String>> entry : fastPatchObject.modifyClasses.entrySet()) {
                if (entry.getKey().equals(SmaliUtils.getDalvikClassName(type))) {
                    ArrayList<Method> newMethods = new ArrayList<Method>();
                    for (Method method : classDef.getMethods()) {
                        System.err.println(getMethodFullName(method));
                        if (entry.getValue().contains(getMethodFullName(method))) {
                            newMethods.add(method);
                        }

                    }
                    patchClassDefs.put(classDef, newMethods);
                    break;
                }
            }
        }
        if (patchClassDefs.size() == 0 && addedClasses.size() == 0) {
            continue;
        }

        if (mappingFile != null && mappingFile.exists()) {
            //prepareclass
            for (String className : fastPatchObject.prepareClasses) {
                ApkPatch.prepareClasses.add(mappingProcessor.getNewClassName(className).className);
            }
            //replaceanatation
            MethodReplaceAnnotation.ANNOTATION = DefineUtils
                    .getDefineClassName(mappingProcessor.getNewClassName(DefineUtils.getDalvikClassName(
                            "Lcom/alipay/euler/andfix/annotation/MethodReplace;")).className, false);
            //dex?
            InsTructionsReIClassDef insTructionsReDef = new InsTructionsReIClassDef(
                    new MappingClassProcessor(mappingProcessor));
            for (ClassDef c : classes) {
                if (patchClassDefs.containsKey(c)) {
                    for (Method method : c.getMethods()) {
                        if (patchClassDefs.get(c).contains(method)) {
                            methods.add(insTructionsReDef.reMethod(method));
                        }
                    }
                    newClassDef.put(insTructionsReDef.reClassDef(c), methods);
                } else if (addedClasses.contains(c)) {
                    newClassDef.put(insTructionsReDef.reClassDef(c), new ArrayList<Method>());
                }
                if (c.getType().contains("/R$")) {
                    continue;
                }
                newClasses.add(insTructionsReDef.reClassDef(c));
            }

        } else {
            ApkPatch.prepareClasses.addAll(fastPatchObject.prepareClasses);
        }

        File patchDexFile = new File(outDir, "patch.dex");
        for (ClassDef classDef : newClassDef.keySet()) {
            System.out.println("modify class:" + classDef.getType());
        }
        if (newClassDef.size() > 0) {
            DexFileFactory.writeDexFile(patchDexFile.getAbsolutePath(),
                    new ImmutableDexFile(newClassDef.keySet()));
        } else if (patchClassDefs.size() > 0) {
            DexFileFactory.writeDexFile(patchDexFile.getAbsolutePath(),
                    new ImmutableDexFile(patchClassDefs.keySet()));
        }

        File tempDexFile = new File(outDir, "temp.dex");
        if (newClasses.size() > 0) {
            DexFileFactory.writeDexFile(tempDexFile.getAbsolutePath(), new DexFile() {
                @Nonnull
                @Override
                public Set<? extends ClassDef> getClasses() {
                    return new AbstractSet<ClassDef>() {
                        @Nonnull
                        @Override
                        public Iterator<ClassDef> iterator() {
                            return newClasses.iterator();
                        }

                        @Override
                        public int size() {
                            return newClasses.size();
                        }
                    };
                }
            });
        } else if (classes.size() > 0) {
            DexFileFactory.writeDexFile(tempDexFile.getAbsolutePath(), new ImmutableDexFile(classes));

        }

        SmaliDiffUtils.scanClasses(new File(outDir, "smali2"), Lists.newArrayList(tempDexFile));

        DexFile patchDex = DexFileFactory.loadDexFile(patchDexFile.getAbsolutePath(), 19, true);
        DexFile tempDex = DexFileFactory.loadDexFile(tempDexFile.getAbsolutePath(), 19, true);
        Set<? extends ClassDef> patchClasses = patchDex.getClasses();
        DexDiffInfo dexDiffInfo = new DexDiffInfo();
        for (ClassDef patchClassDef : patchClasses) {
            String type = patchClassDef.getType();
            if (fastPatchObject.addedClass.contains(SmaliUtils.getDalvikClassName(type))) {
                dexDiffInfo.getAddedClasses().add((DexBackedClassDef) patchClassDef);
                dexDiffInfo.addManifestAddClass(type);
                continue;
            }

            for (Method method : patchClassDef.getMethods()) {
                List<? extends CharSequence> parameters = method.getParameterTypes();
                if (methods.size() > 0) {
                    for (Method modifyMethod : methods) {
                        List<? extends CharSequence> modifyParameters = modifyMethod.getParameterTypes();
                        if (parameters.size() != modifyParameters.size()
                                || !isEqualObj(parameters, modifyParameters)) {
                            continue;
                        }

                        if (modifyMethod.getName().equals(method.getName()))
                            dexDiffInfo.addModifiedMethods((DexBackedMethod) method);
                    }
                } else if (patchClassDefs.size() > 0) {
                    for (ClassDef classDef : patchClassDefs.keySet()) {
                        if (classDef.getType().equals(patchClassDef.getType())) {
                            List<Method> methodList = patchClassDefs.get(classDef);
                            for (Method method1 : methodList) {
                                if (method1.getName().equals(method.getName())) {
                                    dexDiffInfo.addModifiedMethods((DexBackedMethod) method);
                                }
                            }
                        }
                    }

                }
            }
        }
        FastBuild fastBuild = new FastBuild(fastPatchObject.bundleName, new File(outDir, bundleName));
        fastBuild.setClasses(tempDex.getClasses());
        fastBuild.setDiffInfo(dexDiffInfo);
        new AndFixFilterImpl(dexDiffInfo).filterDex();
        dexDiffInfo.update();
        APatchTool.isApatch = true;
        File adiffFile = new File(outDir, "apatch-diff.txt");
        File adiffJsonFile = new File(outDir, "apatch-diff.json");
        dexDiffInfo.writeToFile(fastPatchObject.bundleName, adiffFile, adiffJsonFile);
        try {
            File patchJarFile = fastBuild.dopatch();
            patchJarFiles.add(patchJarFile);
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (UnrecoverableEntryException e) {
            e.printStackTrace();
        }
    }

    File[] aPatchFiles = new File[patchJarFiles.size()];
    aPatchFiles = patchJarFiles.toArray(aPatchFiles);
    File mergePatchFile = null;
    if (null != aPatchFiles && aPatchFiles.length > 1) {
        MergePatch mergePatch = new MergePatch(aPatchFiles, "com_taobao_android", outDir);
        mergePatchFile = mergePatch.doMerge();
    } else if (null != aPatchFiles && aPatchFiles.length == 1) {
        mergePatchFile = aPatchFiles[0];
    }
    if (null != mergePatchFile && mergePatchFile.exists()) {
        FileUtils.moveFile(mergePatchFile, outPatchFile);
    }

}

From source file:com.taobao.android.tools.FastPatchTool.java

public void doPatch() throws IOException, PatchException, RecognitionException {
    MappingReader mappingReader = null;//ww w . ja v  a 2  s .c  o  m
    MappingProcessor mappingProcessor = null;

    if (outDir == null || !outDir.exists()) {
        return;
    }
    outPatchFile = new File(outDir, "apatch-unsigned.apatch");

    if (mappingFile != null && mappingFile.exists()) {
        mappingReader = new MappingReader(mappingFile);
        mappingProcessor = new MappingProcessorImpl(superClassMap);
        mappingReader.pump(mappingProcessor);
        mappingProcessor.updateMethod();
        mappingProcessor.updateFieldType();
    }

    for (FastPatchObject fastPatchObject : patchObjects) {
        Set<ClassDef> classes = new HashSet<ClassDef>();
        Map<ClassDef, List<Method>> patchClassDefs = new HashMap<ClassDef, List<Method>>();
        Set<ClassDef> addedClasses = new HashSet<ClassDef>();
        Map<ClassDef, List<Method>> newClassDef = new HashMap<ClassDef, List<Method>>();

        ArrayList<Method> methods = new ArrayList<Method>();

        for (File dexFile : fastPatchObject.DexFiles) {
            DexFile dFile = DexFileFactory.loadDexFile(dexFile.getAbsolutePath(), Opcodes.getDefault());
            classes.addAll(dFile.getClasses());
        }
        final Set<ClassDef> newClasses = new HashSet<ClassDef>();
        for (ClassDef classDef : classes) {
            String type = classDef.getType();
            if (fastPatchObject.addedClass.contains(SmaliUtils.getDalvikClassName(type))) {
                System.out.println("patch added class:" + type);
                addedClasses.add(classDef);
                continue;
            }
            for (Map.Entry<String, List<String>> entry : fastPatchObject.modifyClasses.entrySet()) {
                if (entry.getKey().equals(SmaliUtils.getDalvikClassName(type))) {
                    ArrayList<Method> newMethods = new ArrayList<Method>();
                    for (Method method : classDef.getMethods()) {
                        System.err.println(getMethodFullName(method));
                        if (entry.getValue().contains(getMethodFullName(method))) {
                            newMethods.add(method);
                        }

                    }
                    patchClassDefs.put(classDef, newMethods);
                    break;
                }
            }
        }
        if (patchClassDefs.size() == 0 && addedClasses.size() == 0) {
            continue;
        }

        if (mappingFile != null && mappingFile.exists()) {
            //prepareclass
            for (String className : fastPatchObject.prepareClasses) {
                ApkPatch.prepareClasses.add(mappingProcessor.getNewClassName(className).className);
            }
            //replaceanatation
            MethodReplaceAnnotation.ANNOTATION = DefineUtils
                    .getDefineClassName(mappingProcessor.getNewClassName(DefineUtils.getDalvikClassName(
                            "Lcom/alipay/euler/andfix/annotation/MethodReplace;")).className, false);
            //dex?
            InsTructionsReIClassDef insTructionsReDef = new InsTructionsReIClassDef(
                    new MappingClassProcessor(mappingProcessor));
            for (ClassDef c : classes) {
                if (patchClassDefs.containsKey(c)) {
                    for (Method method : c.getMethods()) {
                        if (patchClassDefs.get(c).contains(method)) {
                            methods.add(insTructionsReDef.reMethod(method));
                        }
                    }
                    newClassDef.put(insTructionsReDef.reClassDef(c), methods);
                } else if (addedClasses.contains(c)) {
                    newClassDef.put(insTructionsReDef.reClassDef(c), new ArrayList<Method>());
                }
                if (c.getType().contains("/R$")) {
                    continue;
                }
                newClasses.add(insTructionsReDef.reClassDef(c));
            }

        } else {
            ApkPatch.prepareClasses.addAll(fastPatchObject.prepareClasses);
        }

        File patchDexFile = new File(outDir, "patch.dex");
        for (ClassDef classDef : newClassDef.keySet()) {
            System.out.println("modify class:" + classDef.getType());
        }
        if (newClassDef.size() > 0) {
            DexFileFactory.writeDexFile(patchDexFile.getAbsolutePath(),
                    new ImmutableDexFile(Opcodes.getDefault(), newClassDef.keySet()));
        } else if (patchClassDefs.size() > 0) {
            DexFileFactory.writeDexFile(patchDexFile.getAbsolutePath(),
                    new ImmutableDexFile(Opcodes.getDefault(), patchClassDefs.keySet()));
        }

        File tempDexFile = new File(outDir, "temp.dex");
        if (newClasses.size() > 0) {
            DexFileFactory.writeDexFile(tempDexFile.getAbsolutePath(), new DexFile() {
                @Nonnull
                @Override
                public Set<? extends ClassDef> getClasses() {
                    return new AbstractSet<ClassDef>() {
                        @Nonnull
                        @Override
                        public Iterator<ClassDef> iterator() {
                            return newClasses.iterator();
                        }

                        @Override
                        public int size() {
                            return newClasses.size();
                        }
                    };
                }

                @Nonnull
                @Override
                public Opcodes getOpcodes() {
                    return Opcodes.getDefault();
                }
            });
        } else if (classes.size() > 0) {
            DexFileFactory.writeDexFile(tempDexFile.getAbsolutePath(),
                    new ImmutableDexFile(Opcodes.getDefault(), classes));

        }

        SmaliDiffUtils.scanClasses(new File(outDir, "smali2"), Lists.newArrayList(tempDexFile));

        DexFile patchDex = DexFileFactory.loadDexFile(patchDexFile.getAbsolutePath(), Opcodes.getDefault());
        DexFile tempDex = DexFileFactory.loadDexFile(tempDexFile.getAbsolutePath(), Opcodes.getDefault());
        Set<? extends ClassDef> patchClasses = patchDex.getClasses();
        DexDiffInfo dexDiffInfo = new DexDiffInfo();
        for (ClassDef patchClassDef : patchClasses) {
            String type = patchClassDef.getType();
            if (fastPatchObject.addedClass.contains(SmaliUtils.getDalvikClassName(type))) {
                dexDiffInfo.getAddedClasses().add((DexBackedClassDef) patchClassDef);
                dexDiffInfo.addManifestAddClass(type);
                continue;
            }

            for (Method method : patchClassDef.getMethods()) {
                List<? extends CharSequence> parameters = method.getParameterTypes();
                if (methods.size() > 0) {
                    for (Method modifyMethod : methods) {
                        List<? extends CharSequence> modifyParameters = modifyMethod.getParameterTypes();
                        if (parameters.size() != modifyParameters.size()
                                || !isEqualObj(parameters, modifyParameters)) {
                            continue;
                        }

                        if (modifyMethod.getName().equals(method.getName()))
                            dexDiffInfo.addModifiedMethods((DexBackedMethod) method);
                    }
                } else if (patchClassDefs.size() > 0) {
                    for (ClassDef classDef : patchClassDefs.keySet()) {
                        if (classDef.getType().equals(patchClassDef.getType())) {
                            List<Method> methodList = patchClassDefs.get(classDef);
                            for (Method method1 : methodList) {
                                if (method1.getName().equals(method.getName())) {
                                    dexDiffInfo.addModifiedMethods((DexBackedMethod) method);
                                }
                            }
                        }
                    }

                }
            }
        }
        FastBuild fastBuild = new FastBuild(fastPatchObject.bundleName, new File(outDir, bundleName));
        fastBuild.setClasses(tempDex.getClasses());
        fastBuild.setDiffInfo(dexDiffInfo);
        new AndFixFilterImpl(dexDiffInfo).filterDex();
        dexDiffInfo.update();
        File adiffFile = new File(outDir, "apatch-diff.txt");
        File adiffJsonFile = new File(outDir, "apatch-diff.json");
        dexDiffInfo.writeToFile(fastPatchObject.bundleName, adiffFile, adiffJsonFile);
        try {
            File patchJarFile = fastBuild.dopatch();
            patchJarFiles.add(patchJarFile);
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (UnrecoverableEntryException e) {
            e.printStackTrace();
        }
    }

    File[] aPatchFiles = new File[patchJarFiles.size()];
    aPatchFiles = patchJarFiles.toArray(aPatchFiles);
    File mergePatchFile = null;
    if (null != aPatchFiles && aPatchFiles.length > 1) {
        MergePatch mergePatch = new MergePatch(aPatchFiles, "com_taobao_android", outDir);
        mergePatchFile = mergePatch.doMerge();
    } else if (null != aPatchFiles && aPatchFiles.length == 1) {
        mergePatchFile = aPatchFiles[0];
    }
    if (null != mergePatchFile && mergePatchFile.exists()) {
        FileUtils.moveFile(mergePatchFile, outPatchFile);
    }

}

From source file:ddf.test.itests.platform.TestConfiguration.java

private void restoreBackup(Path copy, Path original) throws IOException {
    if (Files.exists(copy) && Files.isDirectory(copy)) {
        FileUtils.deleteQuietly(original.toFile());
        FileUtils.moveDirectory(copy.toFile(), original.toFile());
    } else if (Files.exists(copy) && !Files.isDirectory(copy)) {
        FileUtils.deleteQuietly(original.toFile());
        FileUtils.moveFile(copy.toFile(), original.toFile());
    }//from  w w w.j  av  a2s .  com
}

From source file:com.taobao.android.builder.tools.manifest.ManifestFileUtils.java

public static void removeProvider(File androidManifestFile) throws IOException, DocumentException {
    File backupFile = new File(androidManifestFile.getParentFile(), "AndroidManifest-backup.xml");
    FileUtils.deleteQuietly(backupFile);
    FileUtils.moveFile(androidManifestFile, backupFile);

    XMLWriter writer = null;// XML
    SAXReader reader = new SAXReader();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");// XML??
    FileOutputStream fos = new FileOutputStream(androidManifestFile);

    if (androidManifestFile.exists()) {
        try {/*from  www  .  j av a2  s .  co  m*/
            Document document = reader.read(backupFile);// ?XML
            Element root = document.getRootElement();// 
            List<? extends Node> nodes = root.selectNodes("//provider");
            for (Node node : nodes) {
                Element element = (Element) node;
                String name = element.attributeValue("name");
                logger.info("[Remove Provider]" + name);
                element.getParent().remove(element);
            }
            writer = new XMLWriter(fos, format);
            writer.write(document);
        } finally {
            if (null != writer) {
                writer.close();
            }
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:com.fota.fota3g.deviceSetupMgt.controller.FrimwareMgtCTR.java

/**
 *  ?//w  w w  . j  a va2 s.  c o  m
 * @param vo
 * @param model
 * @return
 */
@RequestMapping(value = "/deviceSetup/setFirmwareDetailInfo")
@ResponseBody
public ModelAndView setFirmwareDetailInfo(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute("FirmwareMgtDiffPackageDetailVo") FirmwareMgtDiffPackageDetailVo vo, ModelMap model)
        throws Exception {
    //      Date now = new Date();
    //      logger.info("setFirmwareDetailInfo, File update start : " + now.toString());
    //      logger.info("setFirmwareDetailInfo, File update start \r\n"
    //            + "gSaveFilePath : " + gSaveFilePath + "\r\n"
    //            );

    //      String saveFilePath = "D:\\dms_workspace\\firmwareDiffPackage\\";
    //      gSaveFilePath = "./firmwareDiffPackage/";

    //    ? ?
    File temp_folder = new File(gSaveFilePath);
    if (!temp_folder.exists() || !temp_folder.isDirectory()) {
        //         logger.error("File Save Directory Not Exists : " + gSaveFilePath);
        response.setStatus(500);

        temp_folder.mkdirs();
        //         return new ModelAndView (ajaxMainView, model);
    }

    //      logger.warn("temp_folder create end.... path : " + gSaveFilePath);

    MultipartRequest multi = null;
    File upfile = null;

    try {
        //  ?
        multi = new MultipartRequest(request, gSaveFilePath, MAX_FILE_SIZE, "utf-8");
        //         logger.warn("MultipartRequest get....");

        upfile = new File(gSaveFilePath + multi.getFilesystemName("file"));
        //         logger.warn("upfile get....");

        //         logger.info("setFirmwareDetailInfo >>>>>>> file name : " + upfile.getName());
        //         vo.setDiffPackageName(VoV.valid(upfile.getName(), 200, 8));
        vo.setDiffPackageName(multi.getParameter("diffPackageName"));
        //         vo.setDiffPackageSize(String.valueOf(upfile.length()));
        vo.setDiffPackageSize(multi.getParameter("diffPackageSize"));
        //         (   model, firmware_version, description, diff_package, firmware_diff_name
        //         ,diff_package_name, diff_package_size, application_firmware_version
        //         ,estimated_download_time, estimated_upload_time, state
        //         ,inner_description, release_notes
        //         ,descriptor_mime_type, firmware_mime_type
        //           ,write_id, write_date, modify_date   )      
        vo.setLoginId(VoV.valid(multi.getParameter("UserLoginId"), 30));
        vo.setModel(VoV.valid(multi.getParameter("model"), 30));
        vo.setFirmwareVersion(VoV.valid(multi.getParameter("version"), 30)); // ?  
        //         vo.setOsNextVersion(VoV.valid(multi.getParameter("osNextVersion"), 64)); // os ?  
        //         vo.setOsPrevVersion(VoV.valid(multi.getParameter("osPrevVersion"), 64)); // os ?  
        //         vo.setFirmwareType(VoV.valid(multi.getParameter("firmwareType"), 16)); // ?  
        vo.setMaker(VoV.valid(multi.getParameter("maker"), 30));
        vo.setDocument(VoV.valid(multi.getParameter("document"), 1000));
        vo.setDiffPackage(VoV.valid(multi.getParameter("diffPackage"), 100));
        vo.setApplicationFirmwareVersion(multi.getParameter("selectPackage")); // ? 
        if (multi.getParameter("downTime") == null || multi.getParameter("downTime") == "") {
            vo.setEstimatedDownloadTime("0"); // ? ?
        } else {
            vo.setEstimatedDownloadTime(multi.getParameter("downTime")); // ? ?
        }
        if (multi.getParameter("installTime") == null || multi.getParameter("installTime") == "") {
            vo.setEstimatedUploadTime("0"); // ? ?
        } else {
            vo.setEstimatedUploadTime(multi.getParameter("installTime")); // ? ?
        }

        vo.setOsNextVersion(multi.getParameter("osNextVersion")); // os ?  
        vo.setOsPrevVersion(multi.getParameter("osPrevVersion")); // os ?  
        vo.setFirmwareType(multi.getParameter("firmwareType")); // ?  

        //         logger.warn("os : " + vo.getOsPrevVersion() + " / " + vo.getOsNextVersion());

        vo.setState("N"); // new , ?
        vo.setDocument(multi.getParameter("document"));
        vo.setDocumentIn(multi.getParameter("documentIn"));
        vo.setReleaseNote(multi.getParameter("releaseNote"));
        vo.setDescMimeType(multi.getParameter("descMimeType"));
        vo.setFirmMimeType(multi.getParameter("firmMimeType"));
        // firmware diff name ? model_ApplicationFirmwareVersion 
        vo.setFirmwareDiffName(vo.getModel() + "_" + vo.getApplicationFirmwareVersion());
        //         if (!vo.getFotaType().equals("") && !vo.getFotaType().equals("PUSH") && !vo.getFotaType().equals("POLLING") && !vo.getFotaType().equals("PUSHPOLLING"))
        //            throw new Exception();
        //         vo.setDiffPackage(gSaveFilePath + vo.getDiffPackageName());

        //         logger.warn("diff pkg : " + vo.getDiffPackage());

        //vo.setFirmwareId(VoV.valid(multi.getParameter("firmwareId"), 30, 4));
        //vo.setFirmwareDesc(VoV.valid(multi.getParameter("firmwareDesc"), 1000, 9));
        //         vo.setFirmwareVer(VoV.valid(multi.getParameter("firmwareVer"), 100, 4));
        //         vo.setFirmwareMakerVer(VoV.valid(multi.getParameter("firmwareMakerVer"), 100, 8));
        //         vo.setVerMemo(VoV.valid(multi.getParameter("verMemo"), 1000, 9));

        //         logger.warn("file upload vo setting completed...");

        //   ? ?
        //         String path = gSaveFilePath + "realFile/";
        String path = gSaveFilePath + vo.getModel() + "/";
        File pysicalfolder = new File(path);
        if (!pysicalfolder.exists() || !pysicalfolder.isDirectory()) {
            pysicalfolder.mkdirs();
        }
        //         vo.setDiffPackage(VoV.valid(gPath, 200)); // diff package file save info

        //  ???
        File destFile = new File(path + upfile.getName());
        if (destFile.exists()) {
            destFile.delete(); //  ??   ?.
        }

        FileUtils.moveFile(upfile, destFile);

        vo.setDiffPackage(path + vo.getDiffPackageName());

        //CRC, '0' 
        //         vo.setCrc("0");
        //         vo.setCretNm(((UserLoginVO)request.getSession().getAttribute("userInfo")).getUserNm());

    } catch (Exception e) { //  ?? 
        // ??? ? ? 
        if (upfile != null && upfile.exists()) {
            upfile.delete();
        }

        String errorMSG = e.getMessage();
        if (errorMSG != null && !errorMSG.isEmpty() && errorMSG.indexOf("exceeds") != 0) {
            model.addAttribute("error", "?? 10MB ?.");
        } else {
            logger.error("Firm Upload Exception Msg : " + errorMSG);
            e.printStackTrace();
        }

        //         logger.info("File update error : " + errorMSG);
        response.setStatus(500);
        return new ModelAndView(ajaxMainView, model);
    }

    String innerDescription = getMD5Checksum(vo.getDiffPackage());
    vo.setDocumentIn(innerDescription);

    //      logger.warn(" << diff pkg insert info >> \r\n"
    //            + "model : " + vo.getModel() + "\r\n"
    //            + "firmwareVersion : " + vo.getFirmwareVersion() + "\r\n"
    //            + "document : " + vo.getDocument() + "\r\n"
    //            + "diffPackage : " + vo.getDiffPackage() + "\r\n"
    //            + "firmwareDiffName : " + vo.getFirmwareDiffName() + "\r\n"
    //            + "diffPackageName : " + vo.getDiffPackageName() + "\r\n"
    //            + "diffPackageSize : " + vo.getDiffPackageSize() + "\r\n"
    //            + "applicationFirmwareVersion : " + vo.getApplicationFirmwareVersion() + "\r\n"
    //            + "estimatedDownloadTime : " + vo.getEstimatedDownloadTime() + "\r\n"
    //            + "estimatedUploadTime : " + vo.getEstimatedUploadTime() + "\r\n"
    //            + "state : " + vo.getState() + "\r\n"
    //            + "documentIn : " + vo.getDocumentIn() + "\r\n"
    //            + "releaseNote : " + vo.getReleaseNote() + "\r\n"
    //            + "osVersion : " + vo.getOsVersion() + "\r\n"
    //            + "osPrevVersion : " + vo.getOsPrevVersion() + "\r\n"
    //            + "osNextVersion : " + vo.getOsNextVersion() + "\r\n"
    //            + "descMimeType : " + vo.getDescMimeType() + "\r\n"
    //            + "firmMimeType : " + vo.getFirmMimeType() + "\r\n"
    //            + "firmwareType : " + vo.getFirmwareType() + "\r\n"
    //            + "loginId : " + vo.getLoginId() + "\r\n"
    //            );

    // insert  ? '-'  
    if (vo.getApplicationFirmwareVersion().isEmpty()) {
        vo.setApplicationFirmwareVersion("-");
    }
    if (vo.getFirmwareVersion().isEmpty()) {
        vo.setFirmwareVersion("-");
    }
    if (vo.getOsVersion().isEmpty()) {
        vo.setOsVersion("-");
    }
    if (vo.getOsPrevVersion().isEmpty()) {
        vo.setOsPrevVersion("-");
    }
    if (vo.getOsNextVersion().isEmpty()) {
        vo.setOsNextVersion("-");
    }

    //      mySVC.regi(vo);
    // firmware detail info 
    int retValueHistory = -1;
    int retValue = firmMgtSVC.setFirmwareDetailInfo(vo);

    //      logger.warn("insert retValue : " + retValue);
    if (retValue == -1) {
        //         logger.warn(">>>setFirmwareDetailInfo Fail....");
    } else {
        //  diff package insert  ?, history ? insert 
        vo.setHistoryId(CommUtil.getUniqueNumber() + ""); // history id 
        //         logger.warn(">>>setFirmwareHistoryInfo : historyId : " + vo.getHistoryId());
        retValueHistory = firmMgtSVC.setFirmwareHistoryInfo(vo);
    }

    //      logger.warn(">>>setFirmwareDetailInfo retValue : " + retValue + ", setFirmwareHistoryInfo retValue : " + retValueHistory);
    model.addAttribute("retValue", retValue);
    model.addAttribute("retValueHistory", retValueHistory);

    //      now = new Date();
    //      logger.info(">>>>File update end : " + now.toString());

    return new ModelAndView(ajaxMainView, model);
}

From source file:jp.primecloud.auto.process.puppet.PuppetComponentProcess.java

protected void restoreManifest(Long componentNo, Long instanceNo) {
    Component component = componentDao.read(componentNo);
    Instance instance = instanceDao.read(instanceNo);
    File manifestFile = new File(manifestDir, instance.getFqdn() + "." + component.getComponentName() + ".pp");

    // ?//from  w w  w .ja  v a2s. c om
    File backupDir = new File(manifestDir, "backup");
    File backupFile = new File(backupDir, manifestFile.getName());

    if (!backupFile.exists()) {
        return;
    }

    try {
        if (manifestFile.exists()) {
            FileUtils.forceDelete(manifestFile);
        }
        FileUtils.moveFile(backupFile, manifestFile);
    } catch (IOException e) {
        // ?
        log.warn(e.getMessage());
    }
}

From source file:jp.primecloud.auto.process.puppet.PuppetComponentProcess.java

protected void backupManifest(Long componentNo, Long instanceNo) {
    Component component = componentDao.read(componentNo);
    Instance instance = instanceDao.read(instanceNo);
    File manifestFile = new File(manifestDir, instance.getFqdn() + "." + component.getComponentName() + ".pp");

    if (!manifestFile.exists()) {
        return;/*from w  w  w. java 2 s  . c om*/
    }

    // ??
    File backupDir = new File(manifestDir, "backup");
    File backupFile = new File(backupDir, manifestFile.getName());
    try {
        if (!backupDir.exists()) {
            backupDir.mkdir();
        }
        if (backupFile.exists()) {
            FileUtils.forceDelete(backupFile);
        }
        FileUtils.moveFile(manifestFile, backupFile);
    } catch (IOException e) {
        // ??
        log.warn(e.getMessage());
    }
}