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

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

Introduction

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

Prototype

public static void forceDelete(File file) throws IOException 

Source Link

Document

Deletes a file.

Usage

From source file:ZipUtilTest.java

public void testUnwrapStream() throws Exception {
    File dest = File.createTempFile("temp", null);
    File destDir = File.createTempFile("tempDir", null);
    InputStream is = null;//from  w w w  .  ja  v a2s .  c  o m
    try {
        destDir.delete();
        destDir.mkdir();
        String child = "TestFile.txt";
        File parent = new File(getClass().getResource(child).getPath()).getParentFile();
        ZipUtil.pack(parent, dest, true);
        is = new FileInputStream(dest);
        ZipUtil.unwrap(is, destDir);
        assertTrue((new File(destDir, child)).exists());
    } finally {
        IOUtils.closeQuietly(is);
        FileUtils.forceDelete(destDir);
    }
}

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

protected void deleteManifest(Long instanceNo) {
    Instance instance = instanceDao.read(instanceNo);

    // ??/*from   w w  w . j  av  a 2  s  .  c o  m*/
    final String fqdn = instance.getFqdn();
    File[] manifestFiles = manifestDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.startsWith(fqdn) && name.endsWith(".pp");
        }
    });

    // ?
    for (File manifestFile : manifestFiles) {
        try {
            if (manifestFile.exists()) {
                FileUtils.forceDelete(manifestFile);
            }
        } catch (IOException e) {
            // ?
            log.warn(e.getMessage());
        }
    }
}

From source file:gui.DownloadPanel.java

public void actionReDownload() {
    int action = JOptionPane.showConfirmDialog(parent, "Do you realy want to redownload the file?",
            "Confirm Redownload", JOptionPane.OK_CANCEL_OPTION);
    if (action == JOptionPane.OK_OPTION) {
        Download newDownload = selectedDownload;
        try {//from   w  w  w .  j a  va2  s.c o  m
            FileUtils.forceDelete(new File(selectedDownload.getDownloadRangePath() + File.separator
                    + selectedDownload.getDownloadName())); // todo must again
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (newDownload.getStatus() == DownloadStatus.COMPLETE) {
            newDownload.resetData();
            newDownload.resume();
            tableSelectionChanged();
        }
    }
}

From source file:com.taobao.android.builder.tasks.tpatch.TPatchTask.java

@TaskAction
public void doTPatch() throws Exception {

    patchContext = getPatchContext();//from  ww  w  . j a v a  2 s  . c o  m
    signingConfig = getSigningConfig();
    outPatchFolder = getOutPatchFolder();

    // ?
    String baseApkVersion = patchContext.getBaseVersionName();
    String newApkVersion = patchContext.versionName;

    File baseApk = patchContext.getBaseApk();

    File newApk = patchContext.diffApkFile;
    boolean retainMainBundleRes = true;

    if (null == newApk || !newApk.exists()) {
        newApk = patchContext.newApk;
        retainMainBundleRes = false;
    }

    getLogger().info("BaseApk:" + baseApk + ",baseVersion:" + baseApkVersion + ",newApk:" + newApk
            + ",newApkVersion:" + newApkVersion);

    ApkBO apkBO = new ApkBO(baseApk, baseApkVersion, baseApk.getName());
    ApkBO newApkBO = new ApkBO(newApk, newApkVersion, newApk.getName());

    TPatchTool tPatchTool = new TPatchTool(apkBO, newApkBO, patchContext.diffBundleDex);

    List<Pair<BundleBO, BundleBO>> remoteBundles = new ArrayList<>();

    //?bundle
    for (AwbBundle awbBundle : AtlasBuildContext.awbBundleMap.values()) {
        if (awbBundle.isRemote) {

            File bundleFile = awbBundle.outputBundleFile;

            getProject().getLogger().error("add bundle compare " + bundleFile.getAbsolutePath());

            BundleBO newBundleBO = new BundleBO(bundleFile.getName(), bundleFile, "");

            File baseBundleFile = new File(patchContext.apExplodeFolder,
                    "remotebundles/" + bundleFile.getName());

            getProject().getLogger().error("add bundle compare base : " + baseBundleFile.getAbsolutePath());

            BundleBO baseBundleBO = null;
            if (baseBundleFile.exists()) {

                getProject().getLogger().error("add bundle compare " + baseBundleFile.getAbsolutePath() + "->"
                        + bundleFile.getAbsolutePath());

                baseBundleBO = new BundleBO(baseBundleFile.getName(), baseBundleFile, "");
            }
            remoteBundles.add(Pair.of(baseBundleBO, newBundleBO));
        }
    }

    if (remoteBundles.size() > 0) {
        tPatchTool.setSplitDiffBundle(remoteBundles);
    }

    tPatchTool.setMainBundleName(patchContext.mainBundleName);
    if (StringUtils.isNotBlank(patchContext.excludeFiles)) {
        tPatchTool.setNotIncludeFiles(patchContext.excludeFiles.split(","));
    }
    tPatchTool.setRetainMainBundleRes(retainMainBundleRes);
    if (null != patchContext.artifactBundleInfos) {
        tPatchTool.setArtifactBundleInfos(patchContext.artifactBundleInfos);
    }

    tPatchTool.setBaseApkFileList(patchContext.getBaseApkFiles());
    tPatchTool.setNewApkFileList(patchContext.getNewApkFiles());
    tPatchTool.setLogger(getILogger());
    tPatchTool.setOnlyIncludeModifyBundle(patchContext.onlyBuildModifyAwb);

    if (StringUtils.isNotBlank(patchContext.excludeFiles)) {
        tPatchTool.setNotIncludeFiles(patchContext.excludeFiles.split(","));
    }

    ApkFileList apkFileList = AtlasBuildContext.finalApkFileList;
    try {

        tPatchTool.setCreateAll(StringUtils.isEmpty(patchContext.tpatchHistoryUrl));
        FileUtils.writeStringToFile(new File(getOutPatchFolder(), "tpatch-bundles.json"),
                JSON.toJSONString(patchContext.artifactBundleInfos));

        getLogger().info("start to do patch");
        tPatchTool.doPatch(outPatchFolder, true, new File(getOutPatchFolder(), "patchs.json"),
                StringUtils.isNotEmpty(patchContext.tpatchHistoryUrl), patchContext.tpatchHistoryUrl,
                patchContext.appSignName);
        getLogger().info("finish  do patch");

        File patchJson = new File(getOutPatchFolder(), "patchs.json");
        File updateJson = new File(getOutPatchFolder(), "update.json");
        String json = FileUtils.readFileToString(patchJson);
        BuildPatchInfos patchInfos = JSON.parseObject(json, BuildPatchInfos.class);
        UpdateInfo updateInfo = new UpdateInfo(patchInfos);
        FileUtils.writeStringToFile(updateJson, JSON.toJSONString(updateInfo, true));

        File baseVesrionApk = new File(patchContext.newApk.getParentFile(),
                patchContext.newApk.getName().replace(".apk", "-" + baseApkVersion + ".apk"));
        FileUtils.copyFile(patchContext.getBaseApk(), baseVesrionApk);
        if (patchContext.writeBuildInfo && StringUtils.isNotEmpty(patchContext.buildId)) {
            File buildFile = new File(getOutPatchFolder(), "build.txt");
            FileUtils.writeStringToFile(buildFile, patchContext.buildId + "," + patchContext.versionName + ","
                    + apkFileList.getMainBundle().get("classes.dex"));
            if (buildFile != null && buildFile.exists()) {
                getLogger().debug("write build to apk!");
                BuildHelper.writeFileToApk(buildFile, baseVesrionApk, "assets/build.txt");
            }
            BuildHelper.reSign(baseVesrionApk, signingConfig);
        }

        FileUtils.forceDelete(patchContext.newApk);

    } catch (Exception e) {
        throw new GradleException(e.getMessage(), e);
    }

}

From source file:jp.primecloud.auto.process.lb.PuppetLoadBalancerProcess.java

protected void restoreManifest(File manifestFile) {
    // ?/*ww 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:ZipUtilTest.java

public void testUnwrapEntriesInRoot() throws Exception {
    File src = new File(getClass().getResource("demo.zip").getPath());
    File destDir = File.createTempFile("tempDir", null);
    try {/*from  w w w  .  j a va2  s  .c  o  m*/
        destDir.delete();
        destDir.mkdir();
        ZipUtil.unwrap(src, destDir);
        fail("expected a ZipException, unwraping with multiple roots is not supproted");
    } catch (ZipException e) {
        // this is normal outcome
    } finally {
        FileUtils.forceDelete(destDir);
    }
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.TestConsoleLicenseGenerator.java

@Test
public void testInitializeLicenseCreator03() throws Exception {
    this.resetLicenseCreator();

    String fileName = "testInitializeLicenseCreator03.properties";
    File file = new File(fileName);
    if (file.exists())
        FileUtils.forceDelete(file);

    FileUtils.writeStringToFile(file,/*w w  w . j a  v a  2s .c o  m*/
            "net.nicholaswilliams.java.licensing.privateKeyFile=testInitializeLicenseCreator03.key\r\n"
                    + "net.nicholaswilliams.java.licensing.privateKeyPassword=testPassword03");

    this.console.cli = EasyMock.createMockBuilder(CommandLine.class).withConstructor()
            .addMockedMethod("hasOption", String.class).addMockedMethod("getOptionValue", String.class)
            .createStrictMock();

    EasyMock.expect(this.console.cli.hasOption("config")).andReturn(true);
    EasyMock.expect(this.console.cli.getOptionValue("config")).andReturn(fileName);

    EasyMock.replay(this.console.cli, this.device);

    try {
        this.console.initializeLicenseCreator();
        fail("Expected exception FileNotFoundException.");
    } catch (FileNotFoundException e) {
    } finally {
        this.resetLicenseCreator();

        FileUtils.forceDelete(file);

        EasyMock.verify(this.console.cli);
    }
}

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

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

    // ?/*from ww w . j  a  v  a2  s.  c  o  m*/
    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:eu.udig.tools.jgrass.navigationview.NavigationView.java

public void createPartControl(Composite theparent) {

    ScrolledComposite scrolledComposite = new ScrolledComposite(theparent, SWT.H_SCROLL | SWT.V_SCROLL);
    scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    scrolledComposite.setExpandVertical(true);
    scrolledComposite.setExpandHorizontal(true);

    Composite parent = new Composite(scrolledComposite, SWT.NONE);
    parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    parent.setLayout(new GridLayout(1, true));

    org.eclipse.swt.graphics.Point point = parent.computeSize(SWT.DEFAULT, SWT.DEFAULT);
    parent.setSize(point);/*  www. j av a 2  s.c o  m*/
    scrolledComposite.setMinSize(280, 575);
    scrolledComposite.setContent(parent);

    Group boundsGroup = new Group(parent, SWT.NONE);
    boundsGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
    boundsGroup.setLayout(new GridLayout(2, false));
    boundsGroup.setText("Corners");

    Label lowerLeftLabel = new Label(boundsGroup, SWT.NONE);
    lowerLeftLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
    lowerLeftLabel.setText("Lower left (w,s)");
    lowerLeftText = new Text(boundsGroup, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
    lowerLeftText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    lowerLeftText.setText("");
    lowerLeftText.setEditable(false);

    Label upperRightLabel = new Label(boundsGroup, SWT.NONE);
    upperRightLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
    upperRightLabel.setText("Upper right (e,n)");
    upperRightText = new Text(boundsGroup, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
    upperRightText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    upperRightText.setText("");
    upperRightText.setEditable(false);

    Group scaleGroup = new Group(parent, SWT.NONE);
    scaleGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
    scaleGroup.setLayout(new GridLayout(3, false));
    scaleGroup.setText("Scale");
    scaleDownButton = new Button(scaleGroup, SWT.ARROW | SWT.DOWN);
    scaleDownButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
    scaleDownButton.addSelectionListener(this);
    scaleCombo = new Combo(scaleGroup, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);
    scaleCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    scaleCombo.addSelectionListener(this);
    scaleUpButton = new Button(scaleGroup, SWT.ARROW | SWT.UP);
    scaleUpButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
    scaleUpButton.addSelectionListener(this);

    Group dateTimeGroup = new Group(parent, SWT.NONE);
    dateTimeGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
    dateTimeGroup.setLayout(new GridLayout(3, false));
    dateTimeGroup.setText("Date and Time");
    dtDownButton = new Button(dateTimeGroup, SWT.ARROW | SWT.DOWN);
    dtDownButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
    dtDownButton.addSelectionListener(this);
    dateTimeCombo = new Combo(dateTimeGroup, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);
    dateTimeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    dateTimeCombo.addSelectionListener(this);
    dtUpButton = new Button(dateTimeGroup, SWT.ARROW | SWT.UP);
    dtUpButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
    dtUpButton.addSelectionListener(this);

    Group verticalGroup = new Group(parent, SWT.NONE);
    verticalGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
    verticalGroup.setLayout(new GridLayout(3, false));
    verticalGroup.setText("Vertical axis");
    verticalDownButton = new Button(verticalGroup, SWT.ARROW | SWT.DOWN);
    verticalDownButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
    verticalDownButton.addSelectionListener(this);
    verticalCombo = new Combo(verticalGroup, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);
    verticalCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    verticalCombo.addSelectionListener(this);
    verticalUpButton = new Button(verticalGroup, SWT.ARROW | SWT.UP);
    verticalUpButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
    verticalUpButton.addSelectionListener(this);

    Group overviewGroups = new Group(parent, SWT.NONE);
    GridData gd1 = new GridData(SWT.CENTER, SWT.CENTER, false, false);
    overviewGroups.setLayoutData(gd1);
    overviewGroups.setLayout(new GridLayout(1, false));
    overviewGroups.setText("Overview");

    canvas = new Canvas(overviewGroups, SWT.NONE);
    GridData gd2 = new GridData(SWT.FILL, SWT.FILL, false, false);
    gd2.widthHint = 250;
    gd2.heightHint = 121;
    canvas.setLayoutData(gd2);
    canvas.addPaintListener(new PaintListener() {

        public void paintControl(PaintEvent e) {
            Rectangle canvasBounds = canvas.getBounds();
            Rectangle imageBounds = worldImage.getBounds();
            int h = (int) ((float) canvasBounds.width * (float) imageBounds.height / (float) imageBounds.width);
            e.gc.drawImage(worldImage, 0, 0, imageBounds.width, imageBounds.height, 0, 0, canvasBounds.width,
                    h);

            IMap activeMap = ApplicationGIS.getActiveMap();
            ViewportModel viewportModel = (ViewportModel) activeMap.getViewportModel();
            ReferencedEnvelope bounds = viewportModel.getBounds();

            CoordinateReferenceSystem mapCrs = viewportModel.getCRS();
            CoordinateReferenceSystem imageCrs = DefaultGeographicCRS.WGS84;
            try {
                MathTransform transform = CRS.findMathTransform(mapCrs, imageCrs);
                Envelope targetEnv = JTS.transform(bounds, transform);
                double west = targetEnv.getMinX();
                double north = targetEnv.getMaxY();
                double east = targetEnv.getMaxX();
                double south = targetEnv.getMinY();

                if (west < -180) {
                    west = -180;
                }
                if (west > 180) {
                    west = 180;
                }
                if (north < -90) {
                    north = -90;
                }
                if (north > 90) {
                    north = 90;
                }
                if (east < -180) {
                    east = -180;
                }
                if (east > 180) {
                    east = 180;
                }
                if (south < -90) {
                    south = -90;
                }
                if (south > 90) {
                    south = 90;
                }
                west = 180.0 + west;
                north = 90.0 + north;
                east = 180.0 + east;
                south = 90.0 + south;
                double width = east - west;
                double height = north - south;
                if (width < 1) {
                    width = 1;
                }
                if (height < 1) {
                    height = 1;
                }

                int x = (int) ((double) canvasBounds.width * west / 360.0);
                int y = (int) ((double) h * north / 180.0);
                int fw = (int) ((double) canvasBounds.width * width / 360.0);
                if (fw <= 1)
                    fw = 2;
                int fh = (int) ((double) h * height / 180.0);
                if (fh <= 1)
                    fh = 2;
                int newy = h - y;
                e.gc.setForeground(color);
                e.gc.setBackground(color);
                e.gc.setAlpha(80);
                e.gc.fillRectangle(x, newy, fw, fh);

                e.gc.drawLine(x + fw / 2, 0, x + fw / 2, newy);
                // e.gc.drawLine(x + fw / 2, newy + fh, x + fw / 2, h);
                //
                e.gc.drawLine(0, newy + fh / 2, x, newy + fh / 2);
                e.gc.drawLine(x + fw, newy + fh / 2, canvasBounds.width, newy + fh / 2);

            } catch (FactoryException e1) {
                e1.printStackTrace();
            } catch (TransformException e1) {
                e1.printStackTrace();
            }

        }
    });

    // Label fillLabel = new Label(parent, SWT.NONE);
    // fillLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    Group geonamesGroup = new Group(parent, SWT.NONE);
    geonamesGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    geonamesGroup.setLayout(new GridLayout(4, false));
    geonamesGroup.setText("Geonames");

    Label availableLabel = new Label(geonamesGroup, SWT.NONE);
    availableLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
    availableLabel.setText("Available geonames data");

    URL folderUrl = Platform.getBundle(JGrassToolsPlugin.PLUGIN_ID).getResource("/geonamesfiles");
    String folderPath = null;
    try {
        folderPath = FileLocator.toFileURL(folderUrl).getPath();
        folderFile = new File(folderPath);

        String[] namesArray = loadGeonamesFiles();

        countriesCombo = new Combo(geonamesGroup, SWT.DROP_DOWN | SWT.READ_ONLY);
        countriesCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
        countriesCombo.setItems(namesArray);
        countriesCombo.select(0);
        countriesCombo.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                int selectionIndex = countriesCombo.getSelectionIndex();
                String item = countriesCombo.getItem(selectionIndex);
                final String file = folderFile.getAbsolutePath() + File.separator + item + ".txt";

                IRunnableWithProgress operation = new IRunnableWithProgress() {
                    public void run(IProgressMonitor pm)
                            throws InvocationTargetException, InterruptedException {
                        try {
                            populatePlacesMap(placesMap, file);
                        } catch (FileNotFoundException e1) {
                            e1.printStackTrace();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                };
                PlatformGIS.runInProgressDialog("Loading geonames data...", true, operation, true);
            }
        });

        Button addNewButton = new Button(geonamesGroup, SWT.PUSH);
        addNewButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
        addNewButton.setText("+");
        addNewButton.setToolTipText(
                "Add a new geonames file (get it at http://download.geonames.org/export/dump/)");
        addNewButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                FileDialog fileDialog = new FileDialog(countriesCombo.getShell(), SWT.OPEN);
                fileDialog.setFilterExtensions(new String[] { "*.txt" });
                String newFilePath = fileDialog.open();
                try {
                    if (newFilePath != null) {
                        File newFile = new File(newFilePath);
                        if (newFile.exists()) {
                            File copiedFile = new File(folderFile, newFile.getName());
                            FileUtils.copyFile(newFile, copiedFile);
                        }
                    }
                    String[] geonamesFiles = loadGeonamesFiles();
                    if (geonamesFiles.length > 0) {
                        countriesCombo.setItems(geonamesFiles);
                        countriesCombo.select(0);
                    } else {
                        countriesCombo.setItems(new String[] { "   --   " });
                    }
                } catch (IOException e1) {
                    String message = "An error occurred while copying the new geonames file into the application.";
                    ExceptionDetailsDialog.openError(null, message, IStatus.ERROR, JGrassToolsPlugin.PLUGIN_ID,
                            e1);
                    e1.printStackTrace();
                }
            }
        });

        Button removeButton = new Button(geonamesGroup, SWT.PUSH);
        removeButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
        removeButton.setText("-");
        removeButton.setToolTipText("Remove a geonames file");
        removeButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                int selectionIndex = countriesCombo.getSelectionIndex();
                String item = countriesCombo.getItem(selectionIndex);

                try {
                    File namesFile = new File(folderFile, item + ".txt");
                    if (namesFile.exists()) {
                        FileUtils.forceDelete(namesFile);
                    }
                    String[] geonamesFiles = loadGeonamesFiles();
                    if (geonamesFiles.length > 0) {
                        countriesCombo.setItems(geonamesFiles);
                        countriesCombo.select(0);
                    } else {
                        countriesCombo.setItems(new String[] { "   --   " });
                    }
                } catch (IOException e1) {
                    String message = "An error occurred while removing the old geonames file into the application.";
                    ExceptionDetailsDialog.openError(null, message, IStatus.ERROR, JGrassToolsPlugin.PLUGIN_ID,
                            e1);
                    e1.printStackTrace();
                }
            }
        });

        Group placesGroup = new Group(geonamesGroup, SWT.NONE);
        GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, false);
        layoutData.horizontalSpan = 4;
        placesGroup.setLayoutData(layoutData);
        placesGroup.setLayout(new GridLayout(2, false));
        placesGroup.setText("places");

        placesMap = new HashMap<String, Coordinate>(1000);
        populatePlacesMap(placesMap, first.getAbsolutePath());
        keySet = placesMap.keySet();

        final Text placesText = new Text(placesGroup, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
        placesText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
        placesText.setText("");

        Button searchButton = new Button(placesGroup, SWT.PUSH);
        searchButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
        searchButton.setText("search");
        searchButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                String text = placesText.getText();
                if (text.length() < 3) {
                    MessageBox msgBox = new MessageBox(placesText.getShell(), SWT.ICON_WARNING);
                    msgBox.setMessage("At least 3 letters are needed to do a search.");
                    msgBox.open();
                    return;
                }

                List<String> matchedList = new ArrayList<String>();
                for (String name : keySet) {
                    if (name.toLowerCase().matches(".*" + text.toLowerCase() + ".*")) {
                        matchedList.add(name);
                    }
                }
                String[] matchedArray = (String[]) matchedList.toArray(new String[matchedList.size()]);
                Arrays.sort(matchedArray);
                placesCombo.setItems(matchedArray);
                placesCombo.select(0);
            }
        });

        placesCombo = new Combo(placesGroup, SWT.DROP_DOWN);
        placesCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
        placesCombo.setItems(new String[] { ENTER_SEARCH_STRING });

        Button goButton = new Button(placesGroup, SWT.PUSH);
        goButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
        goButton.setText("go");
        goButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                IMap map = ApplicationGIS.getActiveMap();
                if (map.getMapLayers().size() < 1) {
                    return;
                }

                ReferencedEnvelope bounds = map.getViewportModel().getBounds();
                CoordinateReferenceSystem mapCrs = map.getViewportModel().getCRS();

                try {
                    GeometryFactory gF = new GeometryFactory();
                    CoordinateReferenceSystem placeCrs = CRS.decode("EPSG:4326");
                    // transform coordinates before check
                    MathTransform transform = CRS.findMathTransform(placeCrs, mapCrs, true);
                    // jts geometry
                    int selectionIndex = placesCombo.getSelectionIndex();
                    String item = placesCombo.getItem(selectionIndex);
                    Coordinate coordinate = placesMap.get(item);
                    Point pt = gF.createPoint(coordinate);
                    Geometry targetGeometry = JTS.transform(pt, transform);
                    Coordinate position = targetGeometry.getCoordinate();

                    Coordinate centre = bounds.centre();
                    double xTrans = position.x - centre.x;
                    double yTrans = position.y - centre.y;

                    bounds.translate(xTrans, yTrans);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                map.sendCommandASync(
                        NavigationCommandFactory.getInstance().createSetViewportBBoxCommand(bounds));
            }
        });

        Button loadShapeButton = new Button(placesGroup, SWT.PUSH);
        GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, false);
        gridData.horizontalSpan = 2;
        loadShapeButton.setLayoutData(gridData);
        loadShapeButton.setText("Load all places as feature layer");
        loadShapeButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {

                IRunnableWithProgress operation = new IRunnableWithProgress() {

                    public void run(IProgressMonitor pm)
                            throws InvocationTargetException, InterruptedException {

                        try {
                            GeometryFactory gF = new GeometryFactory();
                            // create the feature type
                            SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
                            b.setName("places");
                            b.setCRS(DefaultGeographicCRS.WGS84);
                            b.add("the_geom", MultiPoint.class);
                            b.add("name", String.class);
                            SimpleFeatureType type = b.buildFeatureType();

                            FeatureCollection<SimpleFeatureType, SimpleFeature> newCollection = FeatureCollections
                                    .newCollection();

                            int size = keySet.size();

                            pm.beginTask("Converting geometries of places...", size);
                            int id = 0;
                            for (String name : keySet) {
                                Coordinate coordinate = placesMap.get(name);
                                MultiPoint point = gF.createMultiPoint(new Coordinate[] { coordinate });
                                SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
                                Object[] values = new Object[] { point, name };
                                builder.addAll(values);
                                SimpleFeature feature = builder.buildFeature(type.getTypeName() + "." + id);
                                id++;
                                newCollection.add(feature);
                                pm.worked(1);
                            }
                            pm.done();

                            IGeoResource resource = CatalogPlugin.getDefault().getLocalCatalog()
                                    .createTemporaryResource(type);

                            resource.resolve(FeatureStore.class, pm).addFeatures(newCollection);
                            ApplicationGIS.addLayersToMap(ApplicationGIS.getActiveMap(),
                                    Collections.singletonList(resource), -1);
                        } catch (Exception e) {
                            e.printStackTrace();
                            String message = "An error occurred while loading the places to map";
                            ExceptionDetailsDialog.openError(null, message, IStatus.ERROR,
                                    JGrassToolsPlugin.PLUGIN_ID, e);

                        }

                    }

                };

                PlatformGIS.runInProgressDialog("Loading places in temporary layer...", true, operation, true);

            }
        });

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

    updateData();

}

From source file:ZipUtilTest.java

public void testUnwrapMultipleRoots() throws Exception {
    File src = new File(getClass().getResource("demo-dirs-only.zip").getPath());
    File destDir = File.createTempFile("tempDir", null);
    try {/*from w  w  w. ja  va2  s  . c om*/
        destDir.delete();
        destDir.mkdir();
        ZipUtil.unwrap(src, destDir);
        fail("expected a ZipException, unwraping with multiple roots is not supproted");
    } catch (ZipException e) {
        // this is normal outcome
    } finally {
        FileUtils.forceDelete(destDir);
    }
}