void put(final URI uri, ArtifactData data) throws Exception { reporter.trace("put %s %s", uri, data); File tmp = createTempFile(repoDir, "mtp", ".whatever"); tmp.deleteOnExit(); try { copy(uri.toURL(), tmp); byte[] sha = SHA1.digest(tmp).digest(); reporter.trace("SHA %s %s", uri, Hex.toHexString(sha)); ArtifactData existing = get(sha); if (existing != null) { reporter.trace("existing"); xcopy(existing, data); return; } File meta = new File(repoDir, Hex.toHexString(sha) + ".json"); File file = new File(repoDir, Hex.toHexString(sha)); rename(tmp, file); reporter.trace("file %s", file); data.file = file.getAbsolutePath(); data.sha = sha; data.busy = false; CommandData cmddata = parseCommandData(data); if (cmddata.bsn != null) { data.name = cmddata.bsn + "-" + cmddata.version; } else data.name = Strings.display(cmddata.title, cmddata.bsn, cmddata.name, uri); codec.enc().to(meta).put(data); reporter.trace("TD = " + data); } finally { tmp.delete(); reporter.trace("puted %s %s", uri, data); } }
/** * Load image from resource path (using getResource). Note that GIFs are loaded as _translucent_ * indexed images. Images are cached: loading an image with the same name twice will get the * cached image the second time. If you want to remove an image from the cache, use purgeImage. * Throws JGError when there was an error. */ @SuppressWarnings({"deprecation", "unchecked"}) public JGImage loadImage(String imgfile) { Image img = (Image) loadedimages.get(imgfile); if (img == null) { URL imgurl = getClass().getResource(imgfile); if (imgurl == null) { try { File imgf = new File(imgfile); if (imgf.canRead()) { imgurl = imgf.toURL(); } else { imgurl = new URL(imgfile); // throw new JGameError( // "File "+imgfile+" not found.",true); } } catch (MalformedURLException e) { // e.printStackTrace(); throw new JGameError("File not found or malformed path or URL '" + imgfile + "'.", true); } } img = output_comp.getToolkit().createImage(imgurl); loadedimages.put(imgfile, img); } try { ensureLoaded(img); } catch (Exception e) { // e.printStackTrace(); throw new JGameError("Error loading image " + imgfile); } return new JREImage(img); }
static void genclass(DelegatorGenerator dg, Class intfcl, String fqcn, File srcroot) throws IOException { File genDir = new File(srcroot, dirForFqcn(fqcn)); if (!genDir.exists()) { System.err.println( JdbcProxyGenerator.class.getName() + " -- creating directory: " + genDir.getAbsolutePath()); genDir.mkdirs(); } String fileName = CodegenUtils.fqcnLastElement(fqcn) + ".java"; Writer w = null; try { w = new BufferedWriter(new FileWriter(new File(genDir, fileName))); dg.writeDelegator(intfcl, fqcn, w); w.flush(); System.err.println("Generated " + fileName); } finally { try { if (w != null) w.close(); } catch (Exception e) { e.printStackTrace(); } } }
/** * 'handler' can be of any type that implements 'exportedInterface', but only methods declared by * the interface (and its superinterfaces) will be invocable. */ public <T> InAppServer( String name, String portFilename, InetAddress inetAddress, Class<T> exportedInterface, T handler) { this.fullName = name + "Server"; this.exportedInterface = exportedInterface; this.handler = handler; // In the absence of authentication, we shouldn't risk starting a server as root. if (System.getProperty("user.name").equals("root")) { Log.warn( "InAppServer: refusing to start unauthenticated server \"" + fullName + "\" as root!"); return; } try { File portFile = FileUtilities.fileFromString(portFilename); secretFile = new File(portFile.getPath() + ".secret"); Thread serverThread = new Thread(new ConnectionAccepter(portFile, inetAddress), fullName); // If there are no other threads left, the InApp server shouldn't keep us alive. serverThread.setDaemon(true); serverThread.start(); } catch (Throwable th) { Log.warn("InAppServer: couldn't start \"" + fullName + "\".", th); } writeNewSecret(); }
private Service getService(File base) throws Exception { File dataFile = new File(base, "data"); if (!dataFile.isFile()) return null; ServiceData data = getData(ServiceData.class, dataFile); return new Service(this, data); }
private byte[] loadClassData(String className) throws IOException { Playground.println("Loading class " + className + ".class", warning); File f = new File(System.getProperty("user.dir") + "/" + className + ".class"); byte[] b = new byte[(int) f.length()]; new FileInputStream(f).read(b); return b; }
private static byte[] getBytes(String file) throws Exception { File f = new File(file); byte[] b = new byte[(int) f.length()]; FileInputStream fis = new FileInputStream(f); fis.read(b); fis.close(); return b; }
public IncrementalJUnit4Runner() { File testRunFile = new File("testRun.properties"); if (testRunFile.exists() && !testRunFile.canWrite()) { throw new IllegalStateException(); } coverageMap = new Properties(); testMethods = new HashMap<Method, Boolean>(); }
/** * Locate the given file. * * @return Returns null if file couldn't be found. */ private File locate(String fileName) { if (fileName != null) { fileName = fileName.replace('.', '/') + ".class"; File path = null; for (int i = 0; i < fPathItems.length; i++) { path = new File(fPathItems[i], fileName); if (path.exists()) return path; } } return null; }
// When already existing adapted project is created , need to move to new adapted project private boolean deleteCIJobFile(ApplicationInfo appInfo) throws PhrescoException { S_LOGGER.debug("Entering Method ProjectAdministratorImpl.deleteCI()"); try { File ciJobInfo = new File(getCIJobPath(appInfo)); return ciJobInfo.delete(); } catch (ClientHandlerException ex) { S_LOGGER.error( "Entered into catch block of ProjectAdministratorImpl.deleteCI()" + ex.getLocalizedMessage()); throw new PhrescoException(ex); } }
public String _isdir(String args[]) { if (args.length < 2) { domain.warning("Need at least one file name for ${isdir;...}"); return null; } boolean isdir = true; for (int i = 1; i < args.length; i++) { File f = new File(args[i]).getAbsoluteFile(); isdir &= f.isDirectory(); } return isdir ? "true" : "false"; }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String filePickerResult = ""; if (data != null && resultCode == RESULT_OK) { try { ContentResolver cr = getContentResolver(); Uri uri = data.getData(); Cursor cursor = GeckoApp.mAppContext .getContentResolver() .query(uri, new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null); String name = null; if (cursor != null) { try { if (cursor.moveToNext()) { name = cursor.getString(0); } } finally { cursor.close(); } } String fileName = "tmp_"; String fileExt = null; int period; if (name == null || (period = name.lastIndexOf('.')) == -1) { String mimeType = cr.getType(uri); fileExt = "." + GeckoAppShell.getExtensionFromMimeType(mimeType); } else { fileExt = name.substring(period); fileName = name.substring(0, period); } File file = File.createTempFile(fileName, fileExt, sGREDir); FileOutputStream fos = new FileOutputStream(file); InputStream is = cr.openInputStream(uri); byte[] buf = new byte[4096]; int len = is.read(buf); while (len != -1) { fos.write(buf, 0, len); len = is.read(buf); } fos.close(); filePickerResult = file.getAbsolutePath(); } catch (Exception e) { Log.e(LOG_FILE_NAME, "showing file picker", e); } } try { mFilePickerResult.put(filePickerResult); } catch (InterruptedException e) { Log.i(LOG_FILE_NAME, "error returning file picker result", e); } }
public List<CommandData> getCommands(File commandDir) throws Exception { List<CommandData> result = new ArrayList<CommandData>(); if (!commandDir.exists()) { return result; } for (File f : commandDir.listFiles()) { CommandData data = getData(CommandData.class, f); if (data != null) result.add(data); } return result; }
void removeFiles() throws IOException { BufferedReader reader = new BufferedReader(new FileReader(new File(sGREDir, "removed-files"))); try { for (String removedFileName = reader.readLine(); removedFileName != null; removedFileName = reader.readLine()) { File removedFile = new File(sGREDir, removedFileName); if (removedFile.exists()) removedFile.delete(); } } finally { reader.close(); } }
private boolean unpackFile(ZipFile zip, byte[] buf, ZipEntry fileEntry, String name) throws IOException, FileNotFoundException { if (fileEntry == null) fileEntry = zip.getEntry(name); if (fileEntry == null) throw new FileNotFoundException("Can't find " + name + " in " + zip.getName()); File outFile = new File(sGREDir, name); if (outFile.lastModified() == fileEntry.getTime() && outFile.length() == fileEntry.getSize()) return false; File dir = outFile.getParentFile(); if (!dir.exists()) dir.mkdirs(); InputStream fileStream; fileStream = zip.getInputStream(fileEntry); OutputStream outStream = new FileOutputStream(outFile); while (fileStream.available() > 0) { int read = fileStream.read(buf, 0, buf.length); outStream.write(buf, 0, read); } fileStream.close(); outStream.close(); outFile.setLastModified(fileEntry.getTime()); return true; }
String ls(String args[], boolean relative) { if (args.length < 2) throw new IllegalArgumentException( "the ${ls} macro must at least have a directory as parameter"); File dir = domain.getFile(args[1]); if (!dir.isAbsolute()) throw new IllegalArgumentException( "the ${ls} macro directory parameter is not absolute: " + dir); if (!dir.exists()) throw new IllegalArgumentException( "the ${ls} macro directory parameter does not exist: " + dir); if (!dir.isDirectory()) throw new IllegalArgumentException( "the ${ls} macro directory parameter points to a file instead of a directory: " + dir); Collection<File> files = new ArrayList<File>(new SortedList<File>(dir.listFiles())); for (int i = 2; i < args.length; i++) { Instructions filters = new Instructions(args[i]); files = filters.select(files, true); } List<String> result = new ArrayList<String>(); for (File file : files) result.add(relative ? file.getName() : file.getAbsolutePath()); return Processor.join(result, ","); }
private static void scanDir(File dir, String prefix, Set<String> names) throws Exception { File[] files = dir.listFiles(); if (files == null) return; for (int i = 0; i < files.length; i++) { File f = files[i]; String name = f.getName(); String p = (prefix.equals("")) ? name : prefix + "." + name; if (f.isDirectory()) scanDir(f, p, names); else if (name.endsWith(".class")) { p = p.substring(0, p.length() - 6); names.add(p); } } }
public String _fmodified(String args[]) throws Exception { verifyCommand(args, _fmodifiedHelp, null, 2, Integer.MAX_VALUE); long time = 0; Collection<String> names = new ArrayList<String>(); for (int i = 1; i < args.length; i++) { Processor.split(args[i], names); } for (String name : names) { File f = new File(name); if (f.exists() && f.lastModified() > time) time = f.lastModified(); } return "" + time; }
public List<ServiceData> getServices(File serviceDir) throws Exception { List<ServiceData> result = new ArrayList<ServiceData>(); if (!serviceDir.exists()) { return result; } for (File sdir : serviceDir.listFiles()) { File dataFile = new File(sdir, "data"); ServiceData data = getData(ServiceData.class, dataFile); result.add(data); } return result; }
/** * Get the contents of a file. * * @param in * @return * @throws IOException */ public String _cat(String args[]) throws IOException { verifyCommand(args, "${cat;<in>}, get the content of a file", null, 2, 2); File f = domain.getFile(args[1]); if (f.isFile()) { return IO.collect(f); } else if (f.isDirectory()) { return Arrays.toString(f.list()); } else { try { URL url = new URL(args[1]); return IO.collect(url, "UTF-8"); } catch (MalformedURLException mfue) { // Ignore here } return null; } }
public String _basename(String args[]) { if (args.length < 2) { domain.warning("Need at least one file name for ${basename;...}"); return null; } String del = ""; StringBuilder sb = new StringBuilder(); for (int i = 1; i < args.length; i++) { File f = domain.getFile(args[i]); if (f.exists() && f.getParentFile().exists()) { sb.append(del); sb.append(f.getName()); del = ","; } } return sb.toString(); }
public void init() throws IOException { URL s = getClass().getClassLoader().getResource(SERVICE_JAR_FILE); if (s == null) if (underTest) return; else throw new Error("No " + SERVICE_JAR_FILE + " resource in jar"); service.getParentFile().mkdirs(); IO.copy(s, service); }
protected void unpackComponents() throws IOException, FileNotFoundException { File applicationPackage = new File(getApplication().getPackageResourcePath()); File componentsDir = new File(sGREDir, "components"); if (componentsDir.lastModified() == applicationPackage.lastModified()) return; componentsDir.mkdir(); componentsDir.setLastModified(applicationPackage.lastModified()); GeckoAppShell.killAnyZombies(); ZipFile zip = new ZipFile(applicationPackage); byte[] buf = new byte[32768]; try { if (unpackFile(zip, buf, null, "removed-files")) removeFiles(); } catch (Exception ex) { // This file may not be there, so just log any errors and move on Log.w(LOG_FILE_NAME, "error removing files", ex); } // copy any .xpi file into an extensions/ directory Enumeration<? extends ZipEntry> zipEntries = zip.entries(); while (zipEntries.hasMoreElements()) { ZipEntry entry = zipEntries.nextElement(); if (entry.getName().startsWith("extensions/") && entry.getName().endsWith(".xpi")) { Log.i("GeckoAppJava", "installing extension : " + entry.getName()); unpackFile(zip, buf, entry, entry.getName()); } } }
public Graph(WeightedBVGraph graph, String[] names) { org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("it.unimi.dsi.webgraph.ImmutableGraph"); logger.setLevel(org.apache.log4j.Level.FATAL); if (names.length != graph.numNodes()) throw new Error("Problem with the list of names for the nodes in the graph."); try { File auxFile = File.createTempFile("graph-maps-" + System.currentTimeMillis(), "aux"); auxFile.deleteOnExit(); RecordManager recMan = RecordManagerFactory.createRecordManager(auxFile.getAbsolutePath()); nodes = recMan.hashMap("nodes"); nodesReverse = recMan.hashMap("nodesReverse"); } catch (IOException ex) { throw new Error(ex); } nodes.clear(); nodesReverse.clear(); Constructor[] cons = WeightedArc.class.getDeclaredConstructors(); for (int i = 0; i < cons.length; i++) cons[i].setAccessible(true); this.graph = graph; WeightedArcSet list = new WeightedArcSet(); ArcLabelledNodeIterator it = graph.nodeIterator(); while (it.hasNext()) { if (commit++ % COMMIT_SIZE == 0) { commit(); list.commit(); } Integer aux1 = it.nextInt(); Integer aux2 = null; ArcLabelledNodeIterator.LabelledArcIterator suc = it.successors(); while ((aux2 = suc.nextInt()) != null && aux2 >= 0 && (aux2 < graph.numNodes())) try { WeightedArc arc = (WeightedArc) cons[0].newInstance(aux2, aux1, suc.label().getFloat()); list.add(arc); this.nodes.put(aux1, names[aux1]); this.nodes.put(aux2, names[aux2]); this.nodesReverse.put(names[aux1], aux1); this.nodesReverse.put(names[aux2], aux2); } catch (Exception ex) { throw new Error(ex); } } reverse = new WeightedBVGraph(list.toArray(new WeightedArc[0])); numArcs = list.size(); iterator = nodeIterator(); try { File auxFile = File.createTempFile("graph" + System.currentTimeMillis(), "aux"); auxFile.deleteOnExit(); String basename = auxFile.getAbsolutePath(); store(basename); } catch (IOException ex) { throw new Error(ex); } commit(); }
public static String getBase() throws Exception { if (PKCS11_BASE != null) { return PKCS11_BASE; } File cwd = new File(System.getProperty("test.src", ".")).getCanonicalFile(); while (true) { File file = new File(cwd, "TEST.ROOT"); if (file.isFile()) { break; } cwd = cwd.getParentFile(); if (cwd == null) { throw new Exception("Test root directory not found"); } } PKCS11_BASE = new File(cwd, PKCS11_REL_PATH.replace('/', SEP)).getAbsolutePath(); return PKCS11_BASE; }
private String listFiles(final File cache, List<File> toDelete) throws Exception { boolean stopServices = false; if (toDelete == null) { toDelete = new ArrayList<File>(); } else { stopServices = true; } int count = 0; Formatter f = new Formatter(); f.format(" - Cache:%n * %s%n", cache.getCanonicalPath()); f.format(" - Commands:%n"); for (CommandData cdata : getCommands(new File(cache, COMMANDS))) { f.format(" * %s \t0 handle for \"%s\"%n", cdata.bin, cdata.name); toDelete.add(new File(cdata.bin)); count++; } f.format(" - Services:%n"); for (ServiceData sdata : getServices(new File(cache, SERVICE))) { if (sdata != null) { f.format(" * %s \t0 service directory for \"%s\"%n", sdata.sdir, sdata.name); toDelete.add(new File(sdata.sdir)); File initd = platform.getInitd(sdata); if (initd != null && initd.exists()) { f.format(" * %s \t0 init.d file for \"%s\"%n", initd.getCanonicalPath(), sdata.name); toDelete.add(initd); } if (stopServices) { Service s = getService(sdata); try { s.stop(); } catch (Exception e) { } } count++; } } f.format("%n"); String result = (count > 0) ? f.toString() : null; f.close(); return result; }
public ArtifactData get(byte[] sha) throws Exception { String name = Hex.toHexString(sha); File data = IO.getFile(repoDir, name + ".json"); reporter.trace("artifact data file %s", data); if (data.isFile()) { // Bin + metadata ArtifactData artifact = codec.dec().from(data).get(ArtifactData.class); artifact.file = IO.getFile(repoDir, name).getAbsolutePath(); return artifact; } File bin = IO.getFile(repoDir, name); if (bin.exists()) { // Only bin ArtifactData artifact = new ArtifactData(); artifact.file = bin.getAbsolutePath(); artifact.sha = sha; return artifact; } return null; }
private Manifest getJarManifest(final File container) throws IOException { if (container.isDirectory()) { return null; } final JarFile jarFile = this.jarFiles.get(container); if (jarFile == null) { return null; } return jarFile.getManifest(); }
private String listSupportFiles(List<File> toDelete) throws Exception { Formatter f = new Formatter(); try { if (toDelete == null) { toDelete = new ArrayList<File>(); } int precount = toDelete.size(); File confFile = IO.getFile(platform.getConfigFile()).getCanonicalFile(); if (confFile.exists()) { f.format(" * %s \t0 Config file%n", confFile); toDelete.add(confFile); } String result = (toDelete.size() > precount) ? f.toString() : null; return result; } finally { f.close(); } }
public static void main(final String[] args) { File logdir = new File(LOG_DIR); if (!logdir.exists()) logdir.mkdirs(); File log = new File(logdir, "client.log"); // redirect all console output to the file try { PrintStream out = new PrintStream(new FileOutputStream(log, true), true); out.format("[%s] ===== Client started =====%n", timestampf.format(new Date())); System.setOut(out); System.setErr(out); } catch (FileNotFoundException e) { e.printStackTrace(); } /* Set up the error handler as early as humanly possible. */ ThreadGroup g = new ThreadGroup("Haven main group"); String ed; if (!(ed = Utils.getprop("haven.errorurl", "")).equals("")) { try { final haven.error.ErrorHandler hg = new haven.error.ErrorHandler(new java.net.URL(ed)); hg.sethandler( new haven.error.ErrorGui(null) { public void errorsent() { hg.interrupt(); } }); g = hg; } catch (java.net.MalformedURLException e) { } } Thread main = new HackThread( g, new Runnable() { public void run() { main2(args); } }, "Haven main thread"); main.start(); }