List of usage examples for java.io File equals
public boolean equals(Object obj)
From source file:de.fhg.igd.mapviewer.server.file.FileTiler.java
/** * Ask the user for an image file for that a tiled map shall be created *///from ww w . jav a 2s. c om public void run() { JFileChooser fileChooser = new JFileChooser(); // load current dir fileChooser.setCurrentDirectory( new File(pref.get(PREF_DIR, fileChooser.getCurrentDirectory().getAbsolutePath()))); // open int returnVal = fileChooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { // save current dir pref.put(PREF_DIR, fileChooser.getCurrentDirectory().getAbsolutePath()); // get file File imageFile = fileChooser.getSelectedFile(); // get image dimension Dimension size = getSize(imageFile); log.info("Image size: " + size); // ask for min tile size int minTileSize = 0; while (minTileSize <= 0) { try { minTileSize = Integer.parseInt( JOptionPane.showInputDialog("Minimal tile size", String.valueOf(DEF_MIN_TILE_SIZE))); } catch (Exception e) { minTileSize = 0; } } // determine min map width int width = size.width; while (width / 2 > minTileSize && width % 2 == 0) { width = width / 2; } int minMapWidth = width; // min map width log.info("Minimal map width: " + minMapWidth); // determine min map height int height = size.height; while (height / 2 > minTileSize && height % 2 == 0) { height = height / 2; // min map height } int minMapHeight = height; log.info("Minimal map height: " + minMapHeight); // ask for min map size int minMapSize = 0; while (minMapSize <= 0) { try { minMapSize = Integer.parseInt( JOptionPane.showInputDialog("Minimal map size", String.valueOf(DEF_MIN_MAP_SIZE))); } catch (Exception e) { minMapSize = 0; } } // determine zoom levels int zoomLevels = 1; width = size.width; height = size.height; while (width % 2 == 0 && height % 2 == 0 && width / 2 >= Math.max(minMapWidth, minMapSize) && height / 2 >= Math.max(minMapHeight, minMapSize)) { zoomLevels++; width = width / 2; height = height / 2; } log.info("Number of zoom levels: " + zoomLevels); // determine tile width width = minMapWidth; int tileWidth = minMapWidth; for (int i = 3; i < Math.sqrt(minMapWidth) && width > minTileSize;) { tileWidth = width; if (width % i == 0) { width = width / i; } else i++; } // determine tile height height = minMapHeight; int tileHeight = minMapHeight; for (int i = 3; i < Math.sqrt(minMapHeight) && height > minTileSize;) { tileHeight = height; if (height % i == 0) { height = height / i; } else i++; } // create tiles for each zoom level if (JOptionPane.showConfirmDialog(null, "Create tiles (" + tileWidth + "x" + tileHeight + ") for " + zoomLevels + " zoom levels?", "Create tiles", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) { int currentWidth = size.width; int currentHeight = size.height; File currentImage = imageFile; Properties properties = new Properties(); properties.setProperty(PROP_TILE_WIDTH, String.valueOf(tileWidth)); properties.setProperty(PROP_TILE_HEIGHT, String.valueOf(tileHeight)); properties.setProperty(PROP_ZOOM_LEVELS, String.valueOf(zoomLevels)); List<File> files = new ArrayList<File>(); for (int i = 0; i < zoomLevels; i++) { int mapWidth = currentWidth / tileWidth; int mapHeight = currentHeight / tileHeight; log.info("Creating tiles for zoom level " + i); log.info("Map width: " + currentWidth + " pixels, " + mapWidth + " tiles"); log.info("Map height: " + currentHeight + " pixels, " + mapHeight + " tiles"); // create tiles tile(currentImage, TILE_FILE_PREFIX + i + TILE_FILE_SEPARATOR + "%d", TILE_FILE_EXTENSION, tileWidth, tileHeight); // add files to list for (int num = 0; num < mapWidth * mapHeight; num++) { files.add(new File(imageFile.getParentFile().getAbsolutePath() + File.separator + TILE_FILE_PREFIX + i + TILE_FILE_SEPARATOR + num + TILE_FILE_EXTENSION)); } // store map width and height at current zoom properties.setProperty(PROP_MAP_WIDTH + i, String.valueOf(mapWidth)); properties.setProperty(PROP_MAP_HEIGHT + i, String.valueOf(mapHeight)); // create image for next zoom level currentWidth /= 2; currentHeight /= 2; // create temp image file name File nextImage = suffixFile(imageFile, i + 1); // resize image convert(currentImage, nextImage, currentWidth, currentHeight, 100); // delete previous temp file if (!currentImage.equals(imageFile)) { if (!currentImage.delete()) { log.warn("Error deleting " + imageFile.getAbsolutePath()); } } currentImage = nextImage; } // delete previous temp file if (!currentImage.equals(imageFile)) { if (!currentImage.delete()) { log.warn("Error deleting " + imageFile.getAbsolutePath()); } } // write properties file File propertiesFile = new File( imageFile.getParentFile().getAbsolutePath() + File.separator + MAP_PROPERTIES_FILE); try { FileWriter propertiesWriter = new FileWriter(propertiesFile); try { properties.store(propertiesWriter, "Map generated from " + imageFile.getName()); // add properties file to list files.add(propertiesFile); } finally { propertiesWriter.close(); } } catch (IOException e) { log.error("Error writing map properties file", e); } // add a converter properties file String convProperties = askForPath(fileChooser, new ExactFileFilter(CONVERTER_PROPERTIES_FILE), "Select a converter properties file"); File convFile = null; if (convProperties != null) { convFile = new File(convProperties); files.add(convFile); } // create jar file log.info("Creating jar archive..."); if (createJarArchive(replaceExtension(imageFile, MAP_ARCHIVE_EXTENSION), files)) { log.info("Archive successfully created, deleting tiles..."); // don't delete converter properties if (convFile != null) files.remove(files.size() - 1); // delete files for (File file : files) { if (!file.delete()) { log.warn("Error deleting " + file.getAbsolutePath()); } } } log.info("Fin."); } } }
From source file:github.daneren2005.dsub.service.DownloadService.java
private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) { try {//from ww w . j av a2s. c o m downloadFile.setPlaying(true); final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile() : downloadFile.getPartialFile(); boolean isPartial = file.equals(downloadFile.getPartialFile()); downloadFile.updateModificationDate(); subtractPosition = 0; mediaPlayer.setOnCompletionListener(null); mediaPlayer.setOnPreparedListener(null); mediaPlayer.setOnErrorListener(null); mediaPlayer.reset(); setPlayerState(IDLE); try { mediaPlayer.setAudioSessionId(audioSessionId); } catch (Throwable e) { mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); } String dataSource = file.getAbsolutePath(); if (isPartial && !Util.isOffline(this)) { if (proxy == null) { proxy = new BufferProxy(this); proxy.start(); } proxy.setBufferFile(downloadFile); dataSource = proxy.getPrivateAddress(dataSource); Log.i(TAG, "Data Source: " + dataSource); } else if (proxy != null) { proxy.stop(); proxy = null; } mediaPlayer.setDataSource(dataSource); setPlayerState(PREPARING); mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { public void onBufferingUpdate(MediaPlayer mp, int percent) { Log.i(TAG, "Buffered " + percent + "%"); if (percent == 100) { mediaPlayer.setOnBufferingUpdateListener(null); } } }); mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { public void onPrepared(MediaPlayer mediaPlayer) { try { setPlayerState(PREPARED); synchronized (DownloadService.this) { if (position != 0) { Log.i(TAG, "Restarting player from position " + position); mediaPlayer.seekTo(position); } cachedPosition = position; applyReplayGain(mediaPlayer, downloadFile); if (start || autoPlayStart) { mediaPlayer.start(); setPlayerState(STARTED); // Disable autoPlayStart after done autoPlayStart = false; } else { setPlayerState(PAUSED); onSongProgress(); } } // Only call when starting, setPlayerState(PAUSED) already calls this if (start) { lifecycleSupport.serializeDownloadQueue(); } } catch (Exception x) { handleError(x); } } }); setupHandlers(downloadFile, isPartial, start); mediaPlayer.prepareAsync(); } catch (Exception x) { handleError(x); } }
From source file:org.eclipse.orion.internal.server.core.metastore.SimpleMetaStore.java
public void updateProject(ProjectInfo projectInfo) throws CoreException { String userId = SimpleMetaStoreUtil.decodeUserIdFromWorkspaceId(projectInfo.getWorkspaceId()); String encodedWorkspaceName = SimpleMetaStoreUtil .decodeWorkspaceNameFromWorkspaceId(projectInfo.getWorkspaceId()); File userMetaFolder = SimpleMetaStoreUtil.readMetaUserFolder(rootLocation, userId); File workspaceMetaFolder = SimpleMetaStoreUtil.readMetaFolder(userMetaFolder, encodedWorkspaceName); if (!SimpleMetaStoreUtil.isMetaFile(workspaceMetaFolder, projectInfo.getUniqueId())) { throw new CoreException(new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE, 1, "SimpleMetaStore.updateProject: could not update project: " + projectInfo.getFullName() + " for workspace " + encodedWorkspaceName, null));//from ww w .j a va 2 s. co m } JSONObject jsonObject = SimpleMetaStoreUtil.readMetaFile(workspaceMetaFolder, projectInfo.getUniqueId()); if (!projectInfo.getUniqueId().equals(projectInfo.getFullName())) { // full name has changed, this is a project move if (!SimpleMetaStoreUtil.moveMetaFile(workspaceMetaFolder, projectInfo.getUniqueId(), projectInfo.getFullName())) { throw new CoreException(new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE, 1, "SimpleMetaStore.updateProject: could not move project: " + projectInfo.getUniqueId() + " to " + projectInfo.getFullName() + " for workspace " + encodedWorkspaceName, null)); } if (!SimpleMetaStoreUtil.moveMetaFolder(workspaceMetaFolder, projectInfo.getUniqueId(), projectInfo.getFullName())) { throw new CoreException(new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE, 1, "SimpleMetaStore.updateProject: could not move project: " + projectInfo.getUniqueId() + " to " + projectInfo.getFullName() + " for workspace " + encodedWorkspaceName, null)); } // if the content location is local, update the content location with the new name if (projectInfo.getContentLocation().getScheme().equals("file")) { File oldContentLocation = new File(projectInfo.getContentLocation()); if (workspaceMetaFolder.equals(oldContentLocation.getParent())) { projectInfo .setContentLocation(new File(workspaceMetaFolder, projectInfo.getFullName()).toURI()); } } // Update the workspace with the new projectName WorkspaceInfo workspaceInfo; try { workspaceInfo = readWorkspace(projectInfo.getWorkspaceId()); } catch (CoreException exception) { throw new CoreException(new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE, 1, "SimpleMetaStore.updateProject: could not find workspace with id:" + projectInfo.getWorkspaceId() + ".", null)); } List<String> newProjectNames = new ArrayList<String>(); newProjectNames.addAll(workspaceInfo.getProjectNames()); newProjectNames.remove(projectInfo.getUniqueId()); newProjectNames.add(projectInfo.getFullName()); workspaceInfo.setProjectNames(newProjectNames); updateWorkspace(workspaceInfo); // update unique id with the new name projectInfo.setUniqueId(projectInfo.getFullName()); } else if (projectInfo.getProperty("newUserId") != null) { // Found the temporary properties to indicate a userId change String newUserId = projectInfo.getProperty("newUserId"); String newWorkspaceId = projectInfo.getProperty("newWorkspaceId"); projectInfo.setWorkspaceId(newWorkspaceId); // if the content location is local, update the content location with the new name if (projectInfo.getContentLocation().getScheme().equals("file")) { try { File oldContentLocation = new File(projectInfo.getContentLocation()); if (workspaceMetaFolder.getCanonicalPath().equals(oldContentLocation.getParent())) { String newEncodedWorkspaceName = SimpleMetaStoreUtil .decodeWorkspaceNameFromWorkspaceId(newWorkspaceId); File newUserMetaFolder = SimpleMetaStoreUtil.readMetaUserFolder(rootLocation, newUserId); File newWorkspaceMetaFolder = new File(newUserMetaFolder, newEncodedWorkspaceName); projectInfo.setContentLocation( new File(newWorkspaceMetaFolder, projectInfo.getFullName()).toURI()); } } catch (IOException e) { throw new CoreException( new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE, 1, "SimpleMetaStore.updateProject: could not update project: " + projectInfo.getFullName() + " for workspace " + encodedWorkspaceName, null)); } } // remove the temporary properties projectInfo.setProperty("newUserId", null); projectInfo.setProperty("newWorkspaceId", null); } try { jsonObject.put(ORION_VERSION, VERSION); jsonObject.put("UniqueId", projectInfo.getUniqueId()); jsonObject.put("WorkspaceId", projectInfo.getWorkspaceId()); jsonObject.put("FullName", projectInfo.getFullName()); jsonObject.put("ContentLocation", projectInfo.getContentLocation()); JSONObject properties = new JSONObject(projectInfo.getProperties()); jsonObject.put("Properties", properties); } catch (JSONException e) { throw new CoreException(new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE, 1, "SimpleMetaStore.updateProject: could not update project: " + projectInfo.getFullName() + " for workspace " + encodedWorkspaceName, null)); } if (!SimpleMetaStoreUtil.updateMetaFile(workspaceMetaFolder, projectInfo.getFullName(), jsonObject)) { throw new CoreException(new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE, 1, "SimpleMetaStore.updateProject: could not update project: " + projectInfo.getFullName() + " for workspace " + encodedWorkspaceName, null)); } }
From source file:com.boundlessgeo.geoserver.api.controllers.ImportController.java
/** * Moves uploaded files from the temp upload directory to the appropriate store folder * Updates the ImportContext tasks and stores with the new location. * Updates the catalog store with the new location. * /*w w w.jav a 2 s . co m*/ * @param t ImportTask containing data about a single import */ void moveFile(ImportTask t) { Catalog catalog = geoServer.getCatalog(); StoreInfo store = catalog.getStore(t.getStore().getId(), StoreInfo.class); if (store == null) { LOG.warning("Trying to move files to a non-existant store"); return; } if (!(t.getData() instanceof FileData)) { LOG.warning("Trying to move non-file data"); return; } if (!t.isDirect()) { LOG.warning("Trying to move files from an indirect import"); return; } WorkspaceInfo ws = store.getWorkspace(); //Special behavior for SpatialFile - linked files FileData srcData = (FileData) t.getData(); File srcFile = srcData.getFile().file(); File storeFile; File destDir; FileData destData; File destFile; try { destDir = uploadDir(catalog, ws, store); destFile = new File(destDir, srcData.getFile().file().getName()); if (srcFile.getAbsoluteFile().equals(destFile.getAbsoluteFile())) { LOG.warning("Trying to move file to itself"); return; } destDir.mkdirs(); //Update Store File baseDirectory = catalog.getResourceLoader().getBaseDirectory(); if (store instanceof CoverageStoreInfo) { storeFile = catalog.getResourceLoader().url(((CoverageStoreInfo) store).getURL()); //A CoverageStore needs a single file String url = "file:" + Paths.convert(baseDirectory, destFile); if (!(srcData.getFile().file().getAbsolutePath().equals(storeFile.getAbsolutePath()))) { throw new RuntimeException("CoverageStore file not the same as imported file"); } ((CoverageStoreInfo) store).setURL(url); } else if (store instanceof DataStoreInfo) { storeFile = catalog.getResourceLoader().url(store.getConnectionParameters().get("url").toString()); /* A DataStore may contain multiple files as separate "tables". * Therefore, we use the store dir for the URL, and ensure the file location is * somewhere in this directory. * * If the store file is the same as the destination directory, then we may be in * progress moving files. * * If the store file is a prefix of the source data file, then all is well * * Otherwise, we have a problem and should abort. */ String url = "file:" + Paths.convert(baseDirectory, destDir); if (!(storeFile.equals(destDir.getAbsoluteFile()) || srcData.getFile().file().getAbsolutePath().startsWith(storeFile.getAbsolutePath()))) { throw new RuntimeException("DataStore file not the same as imported file"); } store.getConnectionParameters().put("url", url); } else { throw new RuntimeException("Invalid store type: " + store.getClass()); } //Test if we can actually move the file; otherwise copy the file. boolean move = srcFile.renameTo(srcFile); if (move) { Files.move(srcFile.toPath(), destFile.toPath()); } else { Files.copy(srcFile.toPath(), destFile.toPath()); } //move any supplementary files, update ImportData if (srcData instanceof SpatialFile) { destData = new SpatialFile(destFile); if (((SpatialFile) srcData).getPrjFile() != null) { File prjFile = new File(destDir, ((SpatialFile) srcData).getPrjFile().file().getName()); if (move) { Files.move(((SpatialFile) srcData).getPrjFile().file().toPath(), prjFile.toPath()); } else { Files.copy(((SpatialFile) srcData).getPrjFile().file().toPath(), prjFile.toPath()); } ((SpatialFile) destData).setPrjFile(org.geoserver.platform.resource.Files.asResource(prjFile)); } for (Resource r : ((SpatialFile) srcData).getSuppFiles()) { File suppFile = new File(destDir, r.file().getName()); if (move) { Files.move(r.file().toPath(), suppFile.toPath()); } else { Files.copy(r.file().toPath(), suppFile.toPath()); } ((SpatialFile) destData).getSuppFiles() .add(org.geoserver.platform.resource.Files.asResource(suppFile)); } } else if (srcData instanceof ASpatialFile) { destData = new ASpatialFile(org.geoserver.platform.resource.Files.asResource(destFile)); } else { destData = new FileData(org.geoserver.platform.resource.Files.asResource(destFile)); } } catch (Exception e) { //If this occurs, the store files will be in a temporary folder, so we should abort the import t.setError(e); t.setState(State.ERROR); store.accept(new CascadeDeleteVisitor(catalog)); throw new RuntimeException("Failed to move imported files to uploads directory", e); } //Copy over attributes from srcData destData.setFormat(srcData.getFormat()); destData.setMessage(srcData.getMessage()); destData.setCharsetEncoding(srcData.getCharsetEncoding()); //Update data t.setData(destData); t.setStore(store); //Save the updated store to the catalog catalog.save(store); }
From source file:com.alibaba.citrus.maven.eclipse.base.eclipse.EclipsePlugin.java
final void extractResourceDirs(Set directories, List resources, File basedir, File workspaceProjectBaseDir, boolean test, final String output) throws MojoExecutionException { for (Iterator it = resources.iterator(); it.hasNext();) { Resource resource = (Resource) it.next(); getLog().debug("Processing resource dir: " + resource.getDirectory()); List excludes = new ArrayList(resource.getExcludes()); // automatically exclude java files: eclipse doesn't have the concept of resource directory so it will // try to compile any java file found in maven resource dirs excludes.add(JAVA_FILE_PATTERN); // TODO: figure out how to merge if the same dir is specified twice // with different in/exclude patterns. File resourceDirectory = new File( /* basedir, */resource.getDirectory()); if (!resourceDirectory.exists() || !resourceDirectory.isDirectory()) { getLog().debug("Resource dir: " + resourceDirectory + " either missing or not a directory."); continue; }/* w w w .j a v a2 s .com*/ String resourcePath = IdeUtils.toRelativeAndFixSeparator(workspaceProjectBaseDir, resourceDirectory, !workspaceProjectBaseDir.equals(basedir)); String thisOutput = output; if (thisOutput != null) { // sometimes thisOutput is already an absolute path File outputFile = new File(thisOutput); if (!outputFile.isAbsolute()) { outputFile = new File(workspaceProjectBaseDir, thisOutput); } // create output dir if it doesn't exist outputFile.mkdirs(); if (!StringUtils.isEmpty(resource.getTargetPath())) { outputFile = new File(outputFile, resource.getTargetPath()); // create output dir if it doesn't exist outputFile.mkdirs(); } getLog().debug("Making relative and fixing separator: { " + workspaceProjectBaseDir + ", " + outputFile + ", false }."); thisOutput = IdeUtils.toRelativeAndFixSeparator(workspaceProjectBaseDir, outputFile, false); } EclipseSourceDir resourceDir = new EclipseSourceDir(resourcePath, thisOutput, true, test, resource.getIncludes(), excludes, resource.isFiltering()); if (!directories.add(resourceDir)) { EclipseSourceDir originalDir = (EclipseSourceDir) get(directories, resourceDir); boolean merged = originalDir.merge(resourceDir); if (merged) { getLog().info( "Resource directory's path matches an existing source directory. Resources have been merged with the source directory " + originalDir.getPath()); } else { getLog().info( "Resource directory's path matches an existing source directory but \"test\", \"filtering\" or \"output\" were different." + "The resulting eclipse configuration may not accurately reflect the project configuration for " + originalDir.getPath()); } } } }
From source file:com.haw3d.jadvalKalemat.versions.GingerbreadUtil.java
@Override @SuppressWarnings("unused") // Ignore dead code warning public void downloadFile(URL url, Map<String, String> headers, File destination, boolean notification, String title, HttpContext httpContext) throws IOException { // The DownloadManager can sometimes be buggy and can cause spurious // errors, see // http://code.google.com/p/android/issues/detail?id=18462 // Since puzzle files are very small (a few KB), we don't need to use // any of the useful features the DownloadManager provides, such as // resuming interrupted downloads and resuming downloads across // system reboots. So for now, just use the ordinary // DefaultHttpClient. ///*from w ww.ja v a 2 s .c o m*/ // Also, pre-ICS download managers don't support HTTPS. if (!USE_DOWNLOAD_MANAGER || "https".equals(url.getProtocol()) && android.os.Build.VERSION.SDK_INT < 15) { super.downloadFile(url, headers, destination, notification, title, httpContext); return; } DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Request request = new Request(Uri.parse(url.toString())); File tempFile = new File(jadvalKalematApplication.TEMP_DIR, destination.getName()); request.setDestinationUri(Uri.fromFile(tempFile)); for (Entry<String, String> entry : headers.entrySet()) { request.addRequestHeader(entry.getKey(), entry.getValue()); } request.setMimeType("application/x-crossword"); setNotificationVisibility(request, notification); request.setTitle(title); long id = mgr.enqueue(request); Long idObj = id; String scrubbedUrl = AbstractDownloader.scrubUrl(url); LOG.info("Downloading " + scrubbedUrl + " ==> " + tempFile + " (id=" + id + ")"); // If the request completed really fast, we're done DownloadingFile downloadingFile; boolean completed = false; boolean succeeded = false; int status = -1; synchronized (completedDownloads) { downloadingFile = completedDownloads.remove(idObj); if (downloadingFile != null) { completed = true; succeeded = downloadingFile.succeeded; status = downloadingFile.status; } else { downloadingFile = new DownloadingFile(); waitingDownloads.put(idObj, downloadingFile); } } // Wait for the request to complete, if it hasn't completed already if (!completed) { try { synchronized (downloadingFile) { if (!downloadingFile.completed) { downloadingFile.wait(); } succeeded = downloadingFile.succeeded; status = downloadingFile.status; } } catch (InterruptedException e) { LOG.warning("Download interrupted: " + scrubbedUrl); throw new IOException("Download interrupted"); } } LOG.info("Download " + (succeeded ? "succeeded" : "failed") + ": " + scrubbedUrl); if (succeeded) { if (!destination.equals(tempFile) && !tempFile.renameTo(destination)) { LOG.warning("Failed to rename " + tempFile + " to " + destination); throw new IOException("Failed to rename " + tempFile + " to " + destination); } } else { throw new HTTPException(status); } }
From source file:com.adamrosenfield.wordswithcrosses.versions.GingerbreadUtil.java
@Override @SuppressWarnings("unused") // Ignore dead code warning public void downloadFile(URL url, Map<String, String> headers, File destination, boolean notification, String title, HttpContext httpContext) throws IOException { // The DownloadManager can sometimes be buggy and can cause spurious // errors, see // http://code.google.com/p/android/issues/detail?id=18462 // Since puzzle files are very small (a few KB), we don't need to use // any of the useful features the DownloadManager provides, such as // resuming interrupted downloads and resuming downloads across // system reboots. So for now, just use the ordinary // DefaultHttpClient. ////w w w . j a v a2 s . c om // Also, pre-ICS download managers don't support HTTPS. if (!USE_DOWNLOAD_MANAGER || "https".equals(url.getProtocol()) && android.os.Build.VERSION.SDK_INT < 15) { super.downloadFile(url, headers, destination, notification, title, httpContext); return; } DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Request request = new Request(Uri.parse(url.toString())); File tempFile = new File(WordsWithCrossesApplication.TEMP_DIR, destination.getName()); request.setDestinationUri(Uri.fromFile(tempFile)); for (Entry<String, String> entry : headers.entrySet()) { request.addRequestHeader(entry.getKey(), entry.getValue()); } request.setMimeType("application/x-crossword"); setNotificationVisibility(request, notification); request.setTitle(title); long id = mgr.enqueue(request); Long idObj = id; String scrubbedUrl = AbstractDownloader.scrubUrl(url); LOG.info("Downloading " + scrubbedUrl + " ==> " + tempFile + " (id=" + id + ")"); // If the request completed really fast, we're done DownloadingFile downloadingFile; boolean completed = false; boolean succeeded = false; int status = -1; synchronized (completedDownloads) { downloadingFile = completedDownloads.remove(idObj); if (downloadingFile != null) { completed = true; succeeded = downloadingFile.succeeded; status = downloadingFile.status; } else { downloadingFile = new DownloadingFile(); waitingDownloads.put(idObj, downloadingFile); } } // Wait for the request to complete, if it hasn't completed already if (!completed) { try { synchronized (downloadingFile) { if (!downloadingFile.completed) { downloadingFile.wait(); } succeeded = downloadingFile.succeeded; status = downloadingFile.status; } } catch (InterruptedException e) { LOG.warning("Download interrupted: " + scrubbedUrl); throw new IOException("Download interrupted"); } } LOG.info("Download " + (succeeded ? "succeeded" : "failed") + ": " + scrubbedUrl); if (succeeded) { if (!destination.equals(tempFile) && !tempFile.renameTo(destination)) { LOG.warning("Failed to rename " + tempFile + " to " + destination); throw new IOException("Failed to rename " + tempFile + " to " + destination); } } else { throw new HTTPException(status); } }
From source file:github.popeen.dsub.service.DownloadService.java
private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) { try {/* w w w .ja v a 2 s.c o m*/ subtractPosition = 0; mediaPlayer.setOnCompletionListener(null); mediaPlayer.setOnPreparedListener(null); mediaPlayer.setOnErrorListener(null); mediaPlayer.reset(); setPlayerState(IDLE); try { mediaPlayer.setAudioSessionId(audioSessionId); } catch (Throwable e) { mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); } String dataSource; boolean isPartial = false; if (downloadFile.isStream()) { dataSource = downloadFile.getStream(); Log.i(TAG, "Data Source: " + dataSource); } else { downloadFile.setPlaying(true); final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile() : downloadFile.getPartialFile(); isPartial = file.equals(downloadFile.getPartialFile()); downloadFile.updateModificationDate(); dataSource = file.getAbsolutePath(); if (isPartial && !Util.isOffline(this)) { if (proxy == null) { proxy = new BufferProxy(this); proxy.start(); } proxy.setBufferFile(downloadFile); dataSource = proxy.getPrivateAddress(dataSource); Log.i(TAG, "Data Source: " + dataSource); } else if (proxy != null) { proxy.stop(); proxy = null; } } mediaPlayer.setDataSource(dataSource); setPlayerState(PREPARING); mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { public void onBufferingUpdate(MediaPlayer mp, int percent) { Log.i(TAG, "Buffered " + percent + "%"); if (percent == 100) { mediaPlayer.setOnBufferingUpdateListener(null); } } }); mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { public void onPrepared(MediaPlayer mediaPlayer) { try { setPlayerState(PREPARED); synchronized (DownloadService.this) { if (position != 0) { Log.i(TAG, "Restarting player from position " + position); mediaPlayer.seekTo(position); } cachedPosition = position; applyReplayGain(mediaPlayer, downloadFile); if (start || autoPlayStart) { mediaPlayer.start(); applyPlaybackParamsMain(); setPlayerState(STARTED); // Disable autoPlayStart after done autoPlayStart = false; } else { setPlayerState(PAUSED); onSongProgress(); } updateRemotePlaylist(); } // Only call when starting, setPlayerState(PAUSED) already calls this if (start) { lifecycleSupport.serializeDownloadQueue(); } } catch (Exception x) { handleError(x); } } }); setupHandlers(downloadFile, isPartial, start); mediaPlayer.prepareAsync(); } catch (Exception x) { handleError(x); } }
From source file:net.sf.jabref.external.MoveFileAction.java
@Override public void actionPerformed(ActionEvent event) { int selected = editor.getSelectedRow(); if (selected == -1) { return;/*from ww w .j a va 2 s . com*/ } FileListEntry entry = editor.getTableModel().getEntry(selected); // Check if the current file exists: String ln = entry.link; boolean httpLink = ln.toLowerCase(Locale.ENGLISH).startsWith("http"); if (httpLink) { // TODO: notify that this operation cannot be done on remote links return; } // Get an absolute path representation: List<String> dirs = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectory(); int found = -1; for (int i = 0; i < dirs.size(); i++) { if (new File(dirs.get(i)).exists()) { found = i; break; } } if (found < 0) { JOptionPane.showMessageDialog(frame, Localization.lang("File_directory_is_not_set_or_does_not_exist!"), MOVE_RENAME, JOptionPane.ERROR_MESSAGE); return; } File file = new File(ln); if (!file.isAbsolute()) { file = FileUtil.expandFilename(ln, dirs).orElse(null); } if ((file != null) && file.exists()) { // Ok, we found the file. Now get a new name: String extension = null; if (entry.type.isPresent()) { extension = "." + entry.type.get().getExtension(); } File newFile = null; boolean repeat = true; while (repeat) { repeat = false; String chosenFile; if (toFileDir) { // Determine which name to suggest: String suggName = FileUtil .createFileNameFromPattern(eEditor.getDatabase(), eEditor.getEntry(), Globals.journalAbbreviationLoader, Globals.prefs) .concat(entry.type.isPresent() ? "." + entry.type.get().getExtension() : ""); CheckBoxMessage cbm = new CheckBoxMessage(Localization.lang("Move file to file directory?"), Localization.lang("Rename to '%0'", suggName), Globals.prefs.getBoolean(JabRefPreferences.RENAME_ON_MOVE_FILE_TO_FILE_DIR)); int answer; // Only ask about renaming file if the file doesn't have the proper name already: if (suggName.equals(file.getName())) { answer = JOptionPane.showConfirmDialog(frame, Localization.lang("Move file to file directory?"), MOVE_RENAME, JOptionPane.YES_NO_OPTION); } else { answer = JOptionPane.showConfirmDialog(frame, cbm, MOVE_RENAME, JOptionPane.YES_NO_OPTION); } if (answer != JOptionPane.YES_OPTION) { return; } Globals.prefs.putBoolean(JabRefPreferences.RENAME_ON_MOVE_FILE_TO_FILE_DIR, cbm.isSelected()); StringBuilder sb = new StringBuilder(dirs.get(found)); if (!dirs.get(found).endsWith(File.separator)) { sb.append(File.separator); } if (cbm.isSelected()) { // Rename: sb.append(suggName); } else { // Do not rename: sb.append(file.getName()); } chosenFile = sb.toString(); } else { chosenFile = FileDialogs.getNewFile(frame, file, Collections.singletonList(extension), JFileChooser.SAVE_DIALOG, false); } if (chosenFile == null) { return; // canceled } newFile = new File(chosenFile); // Check if the file already exists: if (newFile.exists() && (JOptionPane.showConfirmDialog(frame, Localization.lang("'%0' exists. Overwrite file?", newFile.getName()), MOVE_RENAME, JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION)) { if (toFileDir) { return; } else { repeat = true; } } } if (!newFile.equals(file)) { try { boolean success = file.renameTo(newFile); if (!success) { success = FileUtil.copyFile(file, newFile, true); } if (success) { // Remove the original file: if (!file.delete()) { LOGGER.info("Cannot delete original file"); } // Relativise path, if possible. String canPath = new File(dirs.get(found)).getCanonicalPath(); if (newFile.getCanonicalPath().startsWith(canPath)) { if ((newFile.getCanonicalPath().length() > canPath.length()) && (newFile .getCanonicalPath().charAt(canPath.length()) == File.separatorChar)) { String newLink = newFile.getCanonicalPath().substring(1 + canPath.length()); editor.getTableModel().setEntry(selected, new FileListEntry(entry.description, newLink, entry.type)); } else { String newLink = newFile.getCanonicalPath().substring(canPath.length()); editor.getTableModel().setEntry(selected, new FileListEntry(entry.description, newLink, entry.type)); } } else { String newLink = newFile.getCanonicalPath(); editor.getTableModel().setEntry(selected, new FileListEntry(entry.description, newLink, entry.type)); } eEditor.updateField(editor); //JOptionPane.showMessageDialog(frame, Globals.lang("File moved"), // Globals.lang("Move/Rename file"), JOptionPane.INFORMATION_MESSAGE); frame.output(Localization.lang("File moved")); } else { JOptionPane.showMessageDialog(frame, Localization.lang("Move file failed"), MOVE_RENAME, JOptionPane.ERROR_MESSAGE); } } catch (SecurityException | IOException ex) { LOGGER.warn("Could not move file", ex); JOptionPane.showMessageDialog(frame, Localization.lang("Could not move file '%0'.", file.getAbsolutePath()) + ex.getMessage(), MOVE_RENAME, JOptionPane.ERROR_MESSAGE); } } } else { // File doesn't exist, so we can't move it. JOptionPane.showMessageDialog(frame, Localization.lang("Could not find file '%0'.", entry.link), Localization.lang("File not found"), JOptionPane.ERROR_MESSAGE); } }
From source file:org.codehaus.mojo.VeraxxMojo.java
protected OutputStream getOutputStreamErr() { String OutputReportName = new String(); if (reportsfileDir.isAbsolute()) { OutputReportName = reportsfileDir.getAbsolutePath() + "/" + getReportFileName(); } else {// w w w .j a v a 2 s . c om OutputReportName = basedir.getAbsolutePath() + "/" + reportsfileDir.getPath() + "/" + getReportFileName(); } getLog().info("Vera++ report location " + OutputReportName); OutputStream output = System.err; File file = new File(OutputReportName); try { new File(file.getParent()).mkdirs(); file.createNewFile(); output = new FileOutputStream(file); } catch (IOException e) { getLog().error("Vera++ report redirected to stderr since " + OutputReportName + " can't be opened"); return output; } final DataOutputStream out = new DataOutputStream(output); try { out.writeBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); out.writeBytes("<checkstyle version=\"5.0\">\n"); } catch (IOException e) { getLog().error("Vera++ xml report write failure"); } OutputStream outErrFilter = new OutputStream() { StringBuffer sb = new StringBuffer(); public void write(int b) throws IOException { if ((b == '\n') || (b == '\r')) { transformCurrentLine(); // cleanup for next line sb.delete(0, sb.length()); } else { sb.append((char) b); } } public void flush() throws IOException { transformCurrentLine(); getLog().debug("Vera++ xml flush() called"); if (!StringUtils.isEmpty(lastfile)) { out.writeBytes("\t</file>\n"); } out.writeBytes("</checkstyle>\n"); out.flush(); } String lastfile; private void transformCurrentLine() { if (sb.length() > 0) { // parse current line // try to replace ' (RULENumber) ' with 'RULENumber:' String p = "^(.+) \\((.+)\\) (.+)$"; Pattern pattern = Pattern.compile(p); Matcher matcher = pattern.matcher(sb); getLog().debug("match " + sb + " on " + p); boolean bWinPath = false; if (sb.charAt(1) == ':') { bWinPath = true; sb.setCharAt(1, '_'); } if (matcher.matches()) { String sLine = matcher.group(1) + matcher.group(2) + ":" + matcher.group(3); getLog().debug("rebuild line = " + sLine); // extract informations pattern = Pattern.compile(":"); String[] items = pattern.split(sLine); String file, line, rule, comment, severity; file = items.length > 0 ? items[0] : ""; line = items.length > 1 ? items[1] : ""; rule = items.length > 2 ? items[2] : ""; comment = items.length > 3 ? items[3] : ""; severity = "warning"; if (bWinPath) { StringBuilder s = new StringBuilder(file); s.setCharAt(1, ':'); file = s.toString(); } // output Xml errors try { // handle <file/> tags if (!file.equals(lastfile)) { if (!StringUtils.isEmpty(lastfile)) { out.writeBytes("\t</file>\n"); } out.writeBytes("\t<file name=\"" + file + "\">\n"); lastfile = file; } out.writeBytes("\t\t<error line=\"" + line + "\" severity=\"" + severity + "\" message=\"" + comment + "\" source=\"" + rule + "\"/>\n"); } catch (IOException e) { getLog().error("Vera++ xml report write failure"); } } } } }; return outErrFilter; }