function_id_one
float64
44.9k
21.2M
function_one
stringlengths
114
15.1k
function_id_two
float64
81.3k
23.7M
function_two
stringlengths
134
11.3k
functionality_type
stringclasses
18 values
big_clone_types
stringclasses
1 value
is_clone
bool
2 classes
2,861,198
public static PO FactoryPO (Class < ? > c, Properties ctx, ResultSet rs, String trx) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Constructor < ? > con = c.getConstructor (Properties.class, ResultSet.class, String.class); PO p = (PO) con.newInstance (ctx, rs, trx); return p; }
2,917,117
protected Object instantiate (Class < ? > type, Object [] args) { try { if (args.length == 0 || this.constructors.length == 0) return type.newInstance (); if (this.constructors.length == 1) if (this.constructors [0].getParameterTypes ().length == 0) return this.constructors [0].newInstance (new Object [0]); else return this.constructors [0].newInstance (args); else { Class < ? > [] types = new Class < ? > [args.length]; for (int i = 0; i < args.length; i ++) types [i] = args [i].getClass (); try { return type.getConstructor (types).newInstance (args); } catch (NoSuchMethodException e) { return type.newInstance (); } } } catch (InstantiationException e) { throw new RuntimeException (instantiationError (type, "It is probably a non-static inner class or an abstract class."), e); } catch (IllegalAccessException e) { throw new RuntimeException (instantiationError (type, "Either the class itself or its constructor are not public."), e); } catch (IllegalArgumentException e) { List < String > types = new ArrayList < String > (); for (Object arg : args) types.add (arg.getClass ().getName ()); throw new RuntimeException (instantiationError (type, "Argument mismatch in calling the constructor with arguments." + "\nExpected types are (probably): " + Arrays.asList (this.constructors [0].getParameterTypes ()) + "\nProvided types are (sure): " + types.toString ()), e); } catch (InvocationTargetException e) { throw new RuntimeException (instantiationError (type, "Its construtor has thrown an exception, probably of type: " + e.getCause () + ". See the stack trace for details"), e); } }
Instantiate Using Reflection
Type-3 (WT3/4)
true
10,840,966
public void copy (String sourcePath, String targetPath) throws IOException { File sourceFile = new File (sourcePath); File targetFile = new File (targetPath); FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream (sourceFile); fileOutputStream = new FileOutputStream (targetFile); byte [] buffer = new byte [4096]; int bytesRead; while ((bytesRead = fileInputStream.read (buffer)) != - 1) fileOutputStream.write (buffer, 0, bytesRead); } finally { if (fileInputStream != null) try { fileInputStream.close (); } catch (IOException exception) { JOptionPane.showMessageDialog (null, AcideLanguageManager.getInstance ().getLabels ().getString ("s265") + sourcePath, AcideLanguageManager.getInstance ().getLabels ().getString ("s266"), JOptionPane.ERROR_MESSAGE); AcideLog.getLog ().error (exception.getMessage ()); } if (fileOutputStream != null) try { fileOutputStream.close (); } catch (IOException exception) { JOptionPane.showMessageDialog (null, AcideLanguageManager.getInstance ().getLabels ().getString ("s267") + targetPath, AcideLanguageManager.getInstance ().getLabels ().getString ("268"), JOptionPane.ERROR_MESSAGE); AcideLog.getLog ().error (exception.getMessage ()); } } }
23,252,484
public static void copy (File file1, File file2) throws IOException { FileReader in = new FileReader (file1); FileWriter out = new FileWriter (file2); int c; while ((c = in.read ()) != - 1) out.write (c); in.close (); out.close (); }
Copy File
Type-3 (WT3/4)
true
1,407,918
public CustomArticle NewInstance (NpsContext ctxt, Topic top, ResultSet rs) throws Exception { if (top == null) throw new NpsException (ErrorHelper.SYS_NOTOPIC); if (top.GetTable () == null || top.GetTable ().length () == 0) throw new NpsException (ErrorHelper.SYS_NEED_CUSTOM_TOPIC); String table_name = top.GetTable ().toUpperCase (); if (classes == null || classes.isEmpty () || ! classes.containsKey (table_name)) { return new CustomArticle (ctxt, top, rs); } Class clazz = GetArticleClass (table_name); java.lang.reflect.Constructor aconstructor = clazz.getConstructor (new Class [] {NpsContext.class, Topic.class, ResultSet.class}); return (CustomArticle) aconstructor.newInstance (new Object [] {ctxt, top, rs}); }
2,218,179
private AppNode getAppNode (AppContext app) { AppDescriptor appDescriptor = app.getDescriptor (); ClassLoader classLoader = Thread.currentThread ().getContextClassLoader (); ImageIcon icon = null; try { String pkg = Tools.getPackage (appDescriptor.getClassName ()); URL url = classLoader.getResource (pkg + "/icon.png"); if (url == null) url = classLoader.getResource ("icon.png"); icon = new ImageIcon (new ImageIcon (url).getImage ().getScaledInstance (16, 16, Image.SCALE_SMOOTH)); } catch (Exception ex) { Tools.logException (OptionsPanelManager.class, ex, "Could not load icon " + " for app " + appDescriptor.getClassName ()); } if (! appDescriptor.isHME ()) { AppConfigurationPanel appConfigurationPanel = null; try { Class configurationPanel = classLoader.loadClass (appDescriptor.getConfigurationPanel ()); Class [] parameters = new Class [1]; parameters [0] = AppConfiguration.class; Constructor constructor = configurationPanel.getConstructor (parameters); AppConfiguration [] values = new AppConfiguration [1]; values [0] = (AppConfiguration) app.getConfiguration (); appConfigurationPanel = (AppConfigurationPanel) constructor.newInstance ((Object []) values); } catch (Exception ex) { ex.printStackTrace (); Tools.logException (OptionsPanelManager.class, ex, "Could not load configuration panel " + appDescriptor.getConfigurationPanel () + " for app " + appDescriptor.getClassName ()); } AppNode appNode = new AppNode (app, icon, appConfigurationPanel); return appNode; } else { return new AppNode (app, icon, new HMEConfigurationPanel (app.getConfiguration ())); } }
Instantiate Using Reflection
Type-3 (WT3/4)
true
12,523,607
public void render (ServiceContext serviceContext) throws Exception { if (serviceContext.getTemplateName () == null) throw new Exception ("no Template defined for service: " + serviceContext.getServiceInfo ().getRefName ()); File f = new File (serviceContext.getTemplateName ()); serviceContext.getResponse ().setContentLength ((int) f.length ()); InputStream in = new FileInputStream (f); IOUtils.copy (in, serviceContext.getResponse ().getOutputStream (), 0, (int) f.length ()); in.close (); }
13,362,846
public static void setContenu (ContenuFichierElectronique contenuFichier, FichierElectronique fichierElectronique, UtilisateurIFGD utilisateurCourant) throws IOException, DocumentVideException { if (contenuFichier != null) { SupportDocument support = fichierElectronique.getSupport (); support.setFichierElectronique (fichierElectronique); FicheDocument ficheDocument = support.getFicheDocument (); String nomFichier = contenuFichier.getNomFichier (); String extension = FilenameUtils.getExtension (nomFichier); if (ficheDocument.getFichierElectronique (nomFichier) != null) { FichierElectronique fichierElectroniqueExistant = ficheDocument.getFichierElectronique (nomFichier); if (fichierElectroniqueExistant.getId () != null && ! fichierElectroniqueExistant.getId ().equals (fichierElectronique.getId ())) { throw new FichierElectroniqueExistantException (nomFichier, ficheDocument); } } if (fichierElectronique.getId () == null) { if (OfficeDocumentPropertiesUtil.canWriteIdIGID (extension)) { Long idIgid = OfficeDocumentPropertiesUtil.getIdIGID (contenuFichier); if (idIgid != null) { throw new FichierElectroniqueExistantException (nomFichier, idIgid, ficheDocument); } } } InputStream inputStream = contenuFichier.getInputStream (); OutputStream outputStream = fichierElectronique.getOutputStream (); try { IOUtils.copy (inputStream, outputStream); } finally { try { inputStream.close (); } finally { outputStream.close (); } } String typeMime = contenuFichier.getContentType (); long tailleFichier = contenuFichier.getTailleFichier (); Date dateDerniereModification = new Date (); fichierElectronique.setNom (nomFichier); fichierElectronique.setTypeMime (extension); creerFormatSiNecessaire (typeMime, extension); fichierElectronique.setTaille (tailleFichier); fichierElectronique.setDateDerniereModification (dateDerniereModification); fichierElectronique.setSoumetteur (utilisateurCourant); if (extension.endsWith ("msg")) { CourrielUtils.peuplerMetadonneesCourriel (fichierElectronique.getNom (), ficheDocument, contenuFichier.getInputStream (), utilisateurCourant); } else if (extension.endsWith ("eml")) { Map < String, Object > properties = new GestionnaireProprietesMimeMessageParser ().parseMsg (contenuFichier.getInputStream ()); CourrielUtils.peuplerMetadonneesCourriel (fichierElectronique.getNom (), ficheDocument, properties, utilisateurCourant); } else { FGDProprietesDocumentUtils.copierMetadonneesProprietes (fichierElectronique, ficheDocument); } } }
Copy File
Type-3 (WT3/4)
true
1,977,837
public void copyFile (File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte [] buffer; int bytes_read; File toFile = new File (toDir); if (create && ! toFile.exists ()) toFile.mkdirs (); if (toFile.exists ()) { File destFile = new File (toDir + "/" + sourceFile.getName ()); try { if (! destFile.exists () || overwrite) { source = new FileInputStream (sourceFile); destination = new FileOutputStream (destFile); buffer = new byte [1024]; while (true) { bytes_read = source.read (buffer); if (bytes_read == - 1) break; destination.write (buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace (); } finally { if (source != null) try { source.close (); } catch (IOException e) { } if (destination != null) try { destination.close (); } catch (IOException e) { } } } }
11,875,445
private static void loadFromZip () { InputStream in = Resources.class.getResourceAsStream ("data.zip"); if (in == null) { return; } ZipInputStream zipIn = new ZipInputStream (in); try { while (true) { ZipEntry entry = zipIn.getNextEntry (); if (entry == null) { break; } String entryName = entry.getName (); if (! entryName.startsWith ("/")) { entryName = "/" + entryName; } ByteArrayOutputStream out = new ByteArrayOutputStream (); IOUtils.copy (zipIn, out); zipIn.closeEntry (); FILES.put (entryName, out.toByteArray ()); } zipIn.close (); } catch (IOException e) { e.printStackTrace (); } }
Copy File
Type-3 (WT3/4)
true
482,330
public void convert (File src, File dest) throws IOException { InputStream in = new BufferedInputStream (new FileInputStream (src)); DcmParser p = pfact.newDcmParser (in); Dataset ds = fact.newDataset (); p.setDcmHandler (ds.getDcmHandler ()); try { FileFormat format = p.detectFileFormat (); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println ("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile (format, Tags.PixelData); if (ds.contains (Tags.StudyInstanceUID) || ds.contains (Tags.SeriesInstanceUID) || ds.contains (Tags.SOPInstanceUID) || ds.contains (Tags.SOPClassUID)) { System.out.println ("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag () == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt (Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength (); if (hasPixelData) { if (inflate) { ds.putUS (Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt (Tags.BitsAllocated, 0)>>> 3) * ds.getInt (Tags.Rows, 0) * ds.getInt (Tags.Columns, 0) * ds.getInt (Tags.NumberOfFrames, 1) * ds.getInt (Tags.NumberOfSamples, 1)) { System.out.println ("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI (Tags.StudyInstanceUID, uid (studyUID)); ds.putUI (Tags.SeriesInstanceUID, uid (seriesUID)); ds.putUI (Tags.SOPInstanceUID, uid (instUID)); ds.putUI (Tags.SOPClassUID, classUID); if (! ds.contains (Tags.NumberOfSamples)) { ds.putUS (Tags.NumberOfSamples, 1); } if (! ds.contains (Tags.PhotometricInterpretation)) { ds.putCS (Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo (fact.newFileMetaInfo (ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream (new FileOutputStream (dest)); try { } finally { ds.writeFile (out, encodeParam ()); if (hasPixelData) { if (! skipGroupLen) { out.write (PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write ((byte) grlen); out.write ((byte) (grlen>> 8)); out.write ((byte) (grlen>> 16)); out.write ((byte) (grlen>> 24)); } out.write (PXDATA_TAG); out.write ((byte) pxlen); out.write ((byte) (pxlen>> 8)); out.write ((byte) (pxlen>> 16)); out.write ((byte) (pxlen>> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write (in.read ()); b2 = in.read (); b3 = in.read (); out.write (b2 & 0x0f); out.write (b2>> 4 | ((b3 & 0x0f) << 4)); out.write (b3>> 4); } } else { for (; pxlen > 0; -- pxlen) { out.write (in.read ()); } } out.close (); } System.out.print ('.'); } finally { in.close (); } }
9,257,486
public static boolean dumpFile (String from, File to, String lineBreak) { try { BufferedReader in = new BufferedReader (new InputStreamReader (new FileInputStream (from))); BufferedWriter out = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (to))); String line = null; while ((line = in.readLine ()) != null) out.write (Main.getInstance ().resolve (line) + lineBreak); in.close (); out.close (); } catch (Exception e) { Installer.getInstance ().getLogger ().log (StringUtils.getStackTrace (e)); return false; } return true; }
Copy File
Type-3 (WT3/4)
true
3,265,819
@Test public void testLargePut () throws Throwable { int size = CommonParameters.BLOCK_SIZE; InputStream is = new FileInputStream (_fileName); RepositoryFileOutputStream ostream = new RepositoryFileOutputStream (_nodeName, _putHandle, CommonParameters.local); int readLen = 0; int writeLen = 0; byte [] buffer = new byte [CommonParameters.BLOCK_SIZE]; while ((readLen = is.read (buffer, 0, size)) != - 1) { ostream.write (buffer, 0, readLen); writeLen += readLen; } ostream.close (); CCNStats stats = _putHandle.getNetworkManager ().getStats (); Assert.assertEquals (0, stats.getCounter ("DeliverInterestFailed")); }
22,900,247
public static void copyDirectory (File sourceDirectory, File targetDirectory) throws IOException { File [] sourceFiles = sourceDirectory.listFiles (FILE_FILTER); File [] sourceDirectories = sourceDirectory.listFiles (DIRECTORY_FILTER); targetDirectory.mkdirs (); if (sourceFiles != null && sourceFiles.length > 0) { for (int i = 0; i < sourceFiles.length; i ++) { File sourceFile = sourceFiles [i]; FileInputStream fis = new FileInputStream (sourceFile); FileOutputStream fos = new FileOutputStream (targetDirectory + File.separator + sourceFile.getName ()); FileChannel fcin = fis.getChannel (); FileChannel fcout = fos.getChannel (); ByteBuffer buf = ByteBuffer.allocateDirect (8192); long size = fcin.size (); long n = 0; while (n < size) { buf.clear (); if (fcin.read (buf) < 0) { break; } buf.flip (); n += fcout.write (buf); } fcin.close (); fcout.close (); fis.close (); fos.close (); } } if (sourceDirectories != null && sourceDirectories.length > 0) { for (int i = 0; i < sourceDirectories.length; i ++) { File directory = sourceDirectories [i]; File newTargetDirectory = new File (targetDirectory, directory.getName ()); copyDirectory (directory, newTargetDirectory); } } }
Copy File
Type-3 (WT3/4)
true
10,927,176
private static void recursivelyZipFiles (final String extension, String currentRelativePath, File currentDir, ZipOutputStream zipOutputStream) throws IOException { String [] files = currentDir.list (new FilenameFilter () { public boolean accept (File dir, String name) { File f = new File (dir, name); if (extension == null) return true; else return f.isDirectory () || name.endsWith (extension); }} ); for (String filename : files) { File f = new File (currentDir, filename); String fileRelativePath = currentRelativePath + (Helper.isNullOrEmpty (currentRelativePath) ? "" : File.separator) + filename; if (f.isDirectory ()) recursivelyZipFiles (extension, fileRelativePath, f, zipOutputStream); else { BufferedInputStream in = null; byte [] data = new byte [1024]; in = new BufferedInputStream (new FileInputStream (f), 1000); zipOutputStream.putNextEntry (new ZipEntry (fileRelativePath)); int count; while ((count = in.read (data, 0, data.length)) != - 1) { zipOutputStream.write (data, 0, count); } zipOutputStream.closeEntry (); } } }
18,348,106
public static File zipFile (File f, boolean absolutePaths, boolean deleteOriginal, boolean forceDelete, int level) throws IOException { if (! f.exists ()) { throw new FileNotFoundException ("file " + f + " does not exist"); } File destination = new File (f.getAbsolutePath () + ".zip"); if (destination.exists ()) { throw new IOException ("zipped file " + destination + " exists"); } ZipOutputStream zout = new ZipOutputStream (new BufferedOutputStream (new FileOutputStream (destination))); zout.setLevel (level); NSArray < File > files = f.isDirectory () ? arrayByAddingFilesInDirectory (f, true) : new NSArray < File > (f); try { BufferedInputStream origin = null; byte data [] = new byte [2048]; for (int i = 0; i < files.count (); i ++) { File currentFile = files.objectAtIndex (i); FileInputStream fi = new FileInputStream (currentFile); origin = new BufferedInputStream (fi, 2048); String entryName = currentFile.getAbsolutePath (); if (! absolutePaths) { if (f.isDirectory ()) { entryName = entryName.substring (f.getAbsolutePath ().length () + 1, entryName.length ()); } else { entryName = entryName.substring (f.getParentFile ().getAbsolutePath ().length () + 1, entryName.length ()); } } ZipEntry entry = new ZipEntry (entryName); zout.putNextEntry (entry); int count; while ((count = origin.read (data, 0, 2048)) != - 1) { zout.write (data, 0, count); } origin.close (); } zout.close (); } catch (Exception e) { e.printStackTrace (); } if (deleteOriginal) { if (f.canWrite () || forceDelete) { if (! deleteDirectory (f)) { deleteDirectory (f); } } } return destination; }
Zip Files
Type-3 (WT3/4)
true
1,184,290
@Override public void execute () { File currentModelDirectory = new File (this.globalData.getData (String.class, GlobalData.MODEL_INSTALL_DIRECTORY)); File mobileDirectory = new File (currentModelDirectory, "mobile"); mobileDirectory.mkdir (); File mobileModelFile = new File (mobileDirectory, "mobile_model.zip"); FileOutputStream outputStream = null; ZipOutputStream zipStream = null; BusinessModel businessModel = BusinessUnit.getInstance ().getBusinessModel (); try { mobileModelFile.createNewFile (); outputStream = new FileOutputStream (mobileModelFile); zipStream = new ZipOutputStream (outputStream); Dictionary dictionary = businessModel.getDictionary (); for (Definition definition : dictionary.getAllDefinitions ()) { ZipEntry entry = new ZipEntry (definition.getRelativeFileName ()); zipStream.putNextEntry (entry); writeBinary (definition.getAbsoluteFileName (), zipStream); } final String modelFilename = "model.xml"; ZipEntry entry = new ZipEntry (modelFilename); zipStream.putNextEntry (entry); writeBinary (businessModel.getAbsoluteFilename (modelFilename), zipStream); final String logoFilename = dictionary.getModel ().getImageSource (LogoType.mobile); entry = new ZipEntry (logoFilename); zipStream.putNextEntry (entry); writeBinary (businessModel.getAbsoluteFilename (logoFilename), zipStream); } catch (IOException e) { agentLogger.error (e); } finally { StreamHelper.close (zipStream); StreamHelper.close (outputStream); } }
4,013,457
public int addDirectory (ZipOutputStream zosFile, File dirSource, String preSource) throws Exception { String ldirSource = dirSource.getName (); String lpreSource = preSource; int lcntEntries = 0; if (! (isRelativeDirectory ())) { ldirSource = dirSource.getAbsolutePath (); lpreSource = ""; } else { ldirSource = dirSource.getName (); lpreSource = preSource; } File [] files = dirSource.listFiles (); for (int i = 0; i < files.length; i ++) { if (files [i].isDirectory () && isTraverseDirectory ()) { if (isRelativeDirectory ()) { lpreSource = lpreSource + File.separator + ldirSource; getLog ().debug ("Adding directory " + lpreSource + File.separator + files [i].getName ()); addDirectory (zosFile, files [i], lpreSource); lpreSource = preSource; } else { getLog ().debug ("Adding directory " + ldirSource); addDirectory (zosFile, files [i], ""); } } else if (! (files [i].isDirectory ())) { try { byte [] buffer = new byte [1024]; FileInputStream fin = new FileInputStream (files [i]); if (isRelativeDirectory ()) { getLog ().debug ("Adding file [" + lpreSource + File.separator + ldirSource + File.separator + files [i].getName () + "]"); zosFile.putNextEntry (new ZipEntry (lpreSource + File.separator + ldirSource + File.separator + files [i].getName ())); } else { getLog ().debug ("Adding file [" + ldirSource + File.separator + files [i].getName () + "]"); zosFile.putNextEntry (new ZipEntry (ldirSource + File.separator + files [i].getName ())); } int length; while ((length = fin.read (buffer)) > 0) { zosFile.write (buffer, 0, length); } zosFile.closeEntry (); fin.close (); } catch (IOException ioe) { getLog ().fatal (ioe); throw ioe; } catch (Exception ltheXcp) { getLog ().fatal (ltheXcp); throw ltheXcp; } } lcntEntries ++; } return lcntEntries; }
Zip Files
Type-3 (WT3/4)
false
3,609,806
private static String getData (String myurl) throws Exception { System.out.println ("getdata"); URL url = new URL (myurl); uc = (HttpURLConnection) url.openConnection (); br = new BufferedReader (new InputStreamReader (uc.getInputStream ())); String temp = "", k = ""; while ((temp = br.readLine ()) != null) { System.out.println (temp); k += temp; } br.close (); return k; }
14,090,536
private String [] read (String path) throws Exception { final String [] names = {"index.txt", "", "index.html", "index.htm"}; String [] list = null; for (int i = 0; i < names.length; i ++) { URL url = new URL (path + names [i]); try { BufferedReader in = new BufferedReader (new InputStreamReader (url.openStream ())); StringBuffer sb = new StringBuffer (); String s = null; while ((s = in.readLine ()) != null) { s = s.trim (); if (s.length () > 0) { sb.append (s + "\n"); } } in.close (); if (sb.indexOf ("<") != - 1 && sb.indexOf (">") != - 1) { List links = LinkExtractor.scan (url, sb.toString ()); HashSet set = new HashSet (); int prefixLen = path.length (); for (Iterator it = links.iterator (); it.hasNext ();) { String link = it.next ().toString (); if (! link.startsWith (path)) { continue; } link = link.substring (prefixLen); int idx = link.indexOf ("/"); int idxq = link.indexOf ("?"); if (idx > 0 && (idxq == - 1 || idx < idxq)) { set.add (link.substring (0, idx + 1)); } else { set.add (link); } } list = (String []) set.toArray (new String [0]); } else { list = sb.toString ().split ("\n"); } return list; } catch (FileNotFoundException e) { e.printStackTrace (); continue; } } return new String [0]; }
Download From Web
Type-3 (WT3/4)
true
2,177,123
public void hyperlinkUpdate (HyperlinkEvent event) { URL url = event.getURL (); if (event.getEventType () == HyperlinkEvent.EventType.ENTERED && ! event.getDescription ().startsWith ("copyUrl:")) { updatesEditorPane.setToolTipText (url.toString ()); } else if (event.getEventType () == HyperlinkEvent.EventType.EXITED) { updatesEditorPane.setToolTipText (null); } else if (event.getEventType () == HyperlinkEvent.EventType.ACTIVATED) { if (event.getDescription ().startsWith ("copyUrl:")) { String toCopy = event.getDescription ().replaceFirst ("copyUrl:", ""); StringSelection data = new StringSelection (toCopy); Clipboard clipboard = Toolkit.getDefaultToolkit ().getSystemClipboard (); clipboard.setContents (data, data); } else { String browser = configManager.getBrowser (); if (! Desktop.isDesktopSupported ()) { try { if (! browser.equals ("")) { Runtime.getRuntime ().exec (browser + " " + url.toString ()); } else { Runtime.getRuntime ().exec ("firefox " + url.toString ()); } } catch (Exception ex) { JOptionPane.showMessageDialog (this, "Unable to find a web browser, please set up one on settings window", "Web browser error", JOptionPane.WARNING_MESSAGE); } } try { Desktop desktop = Desktop.getDesktop (); URI uri = new URI (url.toString ()); desktop.browse (uri); } catch (Exception e) { return; } } } }
6,663,397
public void hyperlinkUpdate (HyperlinkEvent e) { if (e.getEventType () == HyperlinkEvent.EventType.ACTIVATED) { try { if (Desktop.isDesktopSupported ()) { Desktop.getDesktop ().browse (e.getURL ().toURI ()); } else Tools.openURL (e.getURL ().toString ()); } catch (Exception x) { JOptionPane.showMessageDialog (null, x.getMessage ()); } } }
Open URL in System Browser
Type-3 (WT3/4)
true
5,318,545
public static long calculateCheckSum (CharSequence data) { final Checksum checksummer = new CRC32 (); for (int i = 0; i < data.length (); i ++) { checksummer.update (data.charAt (i)); } return checksummer.getValue (); }
16,244,025
private byte [] gettEXtBytes (String keyword, String content) { byte [] keywordBytes = getISO8859_1Bytes (keyword); byte [] contentBytes = getISO8859_1Bytes (content); byte [] array = new byte [keywordBytes.length + contentBytes.length + 13]; ByteBuffer buffer = ByteBuffer.wrap (array); buffer.putInt (keywordBytes.length + contentBytes.length + 1); buffer.put (getISO8859_1Bytes (CHUNK_TYPE_tEXT)); buffer.put (keywordBytes); buffer.put ((byte) 0); buffer.put (contentBytes); CRC32 crc = new CRC32 (); crc.update (array, 4, keywordBytes.length + contentBytes.length + 5); buffer.putInt ((int) crc.getValue ()); return array; }
CRC32 File Checksum
Type-3 (WT3/4)
false
44,949
private static void readAndRewrite (File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream (new BufferedInputStream (new FileInputStream (inFile))); DcmParser dcmParser = DcmParserFactory.getInstance ().newDcmParser (iis); Dataset ds = DcmObjectFactory.getInstance ().newDataset (); dcmParser.setDcmHandler (ds.getDcmHandler ()); dcmParser.parseDcmFile (null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader (ds, iis, dcmParser.getDcmDecodeParam ().byteOrder, dcmParser.getReadVR ()); System.out.println ("reading " + inFile + "..."); pdReader.readPixelData (false); ImageOutputStream out = ImageIO.createImageOutputStream (new BufferedOutputStream (new FileOutputStream (outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset (out, dcmEncParam); ds.writeHeader (out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR (), dcmParser.getReadLength ()); System.out.println ("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter (pdReader.getPixelDataArray (), false, ds, out, dcmParser.getDcmDecodeParam ().byteOrder, dcmParser.getReadVR ()); pdWriter.writePixelData (); out.flush (); out.close (); System.out.println ("done!"); }
81,287
public void convert (File src, File dest) throws IOException { InputStream in = new BufferedInputStream (new FileInputStream (src)); DcmParser p = pfact.newDcmParser (in); Dataset ds = fact.newDataset (); p.setDcmHandler (ds.getDcmHandler ()); try { FileFormat format = p.detectFileFormat (); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println ("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile (format, Tags.PixelData); if (ds.contains (Tags.StudyInstanceUID) || ds.contains (Tags.SeriesInstanceUID) || ds.contains (Tags.SOPInstanceUID) || ds.contains (Tags.SOPClassUID)) { System.out.println ("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag () == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt (Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength (); if (hasPixelData) { if (inflate) { ds.putUS (Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt (Tags.BitsAllocated, 0)>>> 3) * ds.getInt (Tags.Rows, 0) * ds.getInt (Tags.Columns, 0) * ds.getInt (Tags.NumberOfFrames, 1) * ds.getInt (Tags.NumberOfSamples, 1)) { System.out.println ("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI (Tags.StudyInstanceUID, uid (studyUID)); ds.putUI (Tags.SeriesInstanceUID, uid (seriesUID)); ds.putUI (Tags.SOPInstanceUID, uid (instUID)); ds.putUI (Tags.SOPClassUID, classUID); if (! ds.contains (Tags.NumberOfSamples)) { ds.putUS (Tags.NumberOfSamples, 1); } if (! ds.contains (Tags.PhotometricInterpretation)) { ds.putCS (Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo (fact.newFileMetaInfo (ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream (new FileOutputStream (dest)); try { } finally { ds.writeFile (out, encodeParam ()); if (hasPixelData) { if (! skipGroupLen) { out.write (PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write ((byte) grlen); out.write ((byte) (grlen>> 8)); out.write ((byte) (grlen>> 16)); out.write ((byte) (grlen>> 24)); } out.write (PXDATA_TAG); out.write ((byte) pxlen); out.write ((byte) (pxlen>> 8)); out.write ((byte) (pxlen>> 16)); out.write ((byte) (pxlen>> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write (in.read ()); b2 = in.read (); b3 = in.read (); out.write (b2 & 0x0f); out.write (b2>> 4 | ((b3 & 0x0f) << 4)); out.write (b3>> 4); } } else { for (; pxlen > 0; -- pxlen) { out.write (in.read ()); } } out.close (); } System.out.print ('.'); } finally { in.close (); } }
Copy File
Type-3 (WT3/4)
true
1,287,483
protected void doGet (HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { keysString = req.getParameter ("resultKeys"); if (req.getParameter ("mode") != null && ! req.getParameter ("mode").equals ("")) { archiveHelper.setMode (req.getParameter ("mode")); } SecurityAdvisor secAdvisor = null; try { secAdvisor = (SecurityAdvisor) req.getSession ().getAttribute (SecurityAdvisor.SECURITY_ADVISOR_SESSION_KEY); if (secAdvisor != null) { response.setContentType ("application/x-download"); response.setHeader ("Content-Disposition", "attachment;filename=microarray.zip"); response.setHeader ("Cache-Control", "max-age=0, must-revalidate"); long time1 = System.currentTimeMillis (); Session sess = secAdvisor.getHibernateSession (req.getUserPrincipal () != null ? req.getUserPrincipal ().getName () : "guest"); DictionaryHelper dh = DictionaryHelper.getInstance (sess); baseDir = dh.getAnalysisReadDirectory (req.getServerName ()); archiveHelper.setTempDir (dh.getPropertyDictionary (PropertyDictionary.TEMP_DIRECTORY)); Map fileNameMap = new HashMap (); long compressedFileSizeTotal = getFileNamesToDownload (baseDir, keysString, fileNameMap); ZipOutputStream zipOut = null; TarArchiveOutputStream tarOut = null; if (archiveHelper.isZipMode ()) { zipOut = new ZipOutputStream (response.getOutputStream ()); } else { tarOut = new TarArchiveOutputStream (response.getOutputStream ()); } int totalArchiveSize = 0; for (Iterator i = fileNameMap.keySet ().iterator (); i.hasNext ();) { String analysisNumber = (String) i.next (); Analysis analysis = null; List analysisList = sess.createQuery ("SELECT a from Analysis a where a.number = '" + analysisNumber + "'").list (); if (analysisList.size () == 1) { analysis = (Analysis) analysisList.get (0); } if (analysis == null) { log.error ("Unable to find request " + analysisNumber + ". Bypassing download for user " + req.getUserPrincipal ().getName () + "."); continue; } if (! secAdvisor.canRead (analysis)) { log.error ("Insufficient permissions to read analysis " + analysisNumber + ". Bypassing download for user " + req.getUserPrincipal ().getName () + "."); continue; } List fileNames = (List) fileNameMap.get (analysisNumber); for (Iterator i1 = fileNames.iterator (); i1.hasNext ();) { String filename = (String) i1.next (); String zipEntryName = "bioinformatics-analysis-" + filename.substring (baseDir.length ()); archiveHelper.setArchiveEntryName (zipEntryName); TransferLog xferLog = new TransferLog (); xferLog.setFileName (filename.substring (baseDir.length () + 5)); xferLog.setStartDateTime (new java.util.Date (System.currentTimeMillis ())); xferLog.setTransferType (TransferLog.TYPE_DOWNLOAD); xferLog.setTransferMethod (TransferLog.METHOD_HTTP); xferLog.setPerformCompression ("Y"); xferLog.setIdAnalysis (analysis.getIdAnalysis ()); xferLog.setIdLab (analysis.getIdLab ()); InputStream in = archiveHelper.getInputStreamToArchive (filename, zipEntryName); ZipEntry zipEntry = null; if (archiveHelper.isZipMode ()) { zipEntry = new ZipEntry (archiveHelper.getArchiveEntryName ()); zipOut.putNextEntry (zipEntry); } else { TarArchiveEntry entry = new TarArchiveEntry (archiveHelper.getArchiveEntryName ()); entry.setSize (archiveHelper.getArchiveFileSize ()); tarOut.putArchiveEntry (entry); } OutputStream out = null; if (archiveHelper.isZipMode ()) { out = zipOut; } else { out = tarOut; } int size = archiveHelper.transferBytes (in, out); totalArchiveSize += size; xferLog.setFileSize (new BigDecimal (size)); xferLog.setEndDateTime (new java.util.Date (System.currentTimeMillis ())); sess.save (xferLog); if (archiveHelper.isZipMode ()) { zipOut.closeEntry (); totalArchiveSize += zipEntry.getCompressedSize (); } else { tarOut.closeArchiveEntry (); totalArchiveSize += archiveHelper.getArchiveFileSize (); } archiveHelper.removeTemporaryFile (); } sess.flush (); } response.setContentLength (totalArchiveSize); if (archiveHelper.isZipMode ()) { zipOut.finish (); zipOut.flush (); } else { tarOut.close (); tarOut.flush (); } } else { response.setStatus (999); System.out.println ("DownloadAnalyisFolderServlet: You must have a SecurityAdvisor in order to run this command."); } } catch (Exception e) { response.setStatus (999); System.out.println ("DownloadAnalyisFolderServlet: An exception occurred " + e.toString ()); e.printStackTrace (); } finally { if (secAdvisor != null) { try { secAdvisor.closeHibernateSession (); } catch (Exception e) { } } archiveHelper.removeTemporaryFile (); } }
9,318,114
private void writeClassFile (File zipFile, ZipOutputStream out, JAssembler asm) { ClassDef def = asm.def; Box box = asm.classFile; String path = def.ns.replace ('.', '/') + '/' + def.name + ".class"; try { out.putNextEntry (new ZipEntry (path)); out.write (box.buf, 0, box.len); out.closeEntry (); } catch (IOException e) { throw err ("Cannot write zip entry " + path, zipFile); } }
Zip Files
Type-3 (WT3/4)
false
2,721,038
public File copyFile (File f) throws IOException { File t = createNewFile ("fm", "cpy"); FileOutputStream fos = new FileOutputStream (t); FileChannel foc = fos.getChannel (); FileInputStream fis = new FileInputStream (f); FileChannel fic = fis.getChannel (); foc.transferFrom (fic, 0, fic.size ()); foc.close (); fic.close (); return t; }
10,287,986
public static boolean encodeFileToFile (String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream (new java.io.BufferedInputStream (new java.io.FileInputStream (infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream (new java.io.FileOutputStream (outfile)); byte [] buffer = new byte [65536]; int read = - 1; while ((read = in.read (buffer)) >= 0) { out.write (buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace (); } finally { try { in.close (); } catch (Exception exc) { } try { out.close (); } catch (Exception exc) { } } return success; }
Copy File
Type-3 (WT3/4)
true
160,739
public BufferedWriter createOutputStream (String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char [] buf = new char [k_blockSize]; File ofp = new File (outFile); ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (ofp)); zos.setMethod (ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter (zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter (osw); ZipEntry zot = null; File ifp = new File (inFile); ZipInputStream zis = new ZipInputStream (new FileInputStream (ifp)); InputStreamReader isr = new InputStreamReader (zis, "ISO-8859-1"); BufferedReader br = new BufferedReader (isr); ZipEntry zit = null; while ((zit = zis.getNextEntry ()) != null) { if (zit.getName ().equals ("content.xml")) { continue; } zot = new ZipEntry (zit.getName ()); zos.putNextEntry (zot); while ((byteCount = br.read (buf, 0, k_blockSize)) >= 0) bw.write (buf, 0, byteCount); bw.flush (); zos.closeEntry (); } zos.putNextEntry (new ZipEntry ("content.xml")); bw.flush (); osw = new OutputStreamWriter (zos, "UTF8"); bw = new BufferedWriter (osw); return bw; }
20,601,765
private static void addToZip (File [] files, ZipOutputStream out) throws IOException { byte [] buf = new byte [1024]; for (int i = 0; i < files.length; i ++) { if (files [i].isDirectory ()) { addToZip (files [i].listFiles (), out); } else { FileInputStream in = new FileInputStream (files [i]); out.putNextEntry (new ZipEntry (files [i].getPath ())); int len; while ((len = in.read (buf)) > 0) { out.write (buf, 0, len); } out.closeEntry (); in.close (); } } }
Zip Files
Type-3 (WT3/4)
false
6,430,125
protected Object openDialogBox (Control cellEditorWindow) { FileDialog dialog = new FileDialog (parent.getShell (), SWT.OPEN); dialog.setFilterExtensions (new String [] {"*.jpg;*.JPG;*.JPEG;*.gif;*.GIF;*.png;*.PNG", "*.jpg;*.JPG;*.JPEG", "*.gif;*.GIF", "*.png;*.PNG"}); dialog.setFilterNames (new String [] {"All", "Joint Photographic Experts Group (JPEG)", "Graphics Interchange Format (GIF)", "Portable Network Graphics (PNG)"}); String imagePath = dialog.open (); if (imagePath == null) return null; IProject project = ProjectManager.getInstance ().getCurrentProject (); String projectFolderPath = project.getLocation ().toOSString (); File imageFile = new File (imagePath); String fileName = imageFile.getName (); ImageData imageData = null; try { imageData = new ImageData (imagePath); } catch (SWTException e) { UserErrorException error = new UserErrorException (PropertyHandler.getInstance ().getProperty ("_invalid_image_title"), PropertyHandler.getInstance ().getProperty ("_invalid_image_text")); UserErrorService.INSTANCE.showError (error); return null; } if (imageData == null) { UserErrorException error = new UserErrorException (PropertyHandler.getInstance ().getProperty ("_invalid_image_title"), PropertyHandler.getInstance ().getProperty ("_invalid_image_text")); UserErrorService.INSTANCE.showError (error); return null; } File copiedImageFile = new File (projectFolderPath + File.separator + imageFolderPath + File.separator + fileName); if (copiedImageFile.exists ()) { Path path = new Path (copiedImageFile.getPath ()); copiedImageFile = new File (projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID ().toString () + "." + path.getFileExtension ()); } try { copiedImageFile.createNewFile (); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException (e1); copiedImageFile = null; } if (copiedImageFile == null) { copiedImageFile = new File (projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID ().toString ()); try { copiedImageFile.createNewFile (); } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException (e); return ""; } } FileReader in = null; FileWriter out = null; try { in = new FileReader (imageFile); out = new FileWriter (copiedImageFile); int c; while ((c = in.read ()) != - 1) out.write (c); in.close (); out.close (); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException (e); return ""; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException (e); return ""; } return imageFolderPath + File.separator + copiedImageFile.getName (); }
10,824,317
public static void copyFile (File from, File to) throws Exception { if (! from.exists ()) return; FileInputStream in = new FileInputStream (from); FileOutputStream out = new FileOutputStream (to); byte [] buffer = new byte [8192]; int bytes_read; while (true) { bytes_read = in.read (buffer); if (bytes_read == - 1) break; out.write (buffer, 0, bytes_read); } out.flush (); out.close (); in.close (); }
Copy File
Type-3 (WT3/4)
true
15,595,627
private float [] [] Transpose (float [] [] a) { if (INFO) { System.out.println ("Performing Transpose..."); } float m [] [] = new float [a [0].length] [a.length]; for (int i = 0; i < a.length; i ++) for (int j = 0; j < a [i].length; j ++) m [j] [i] = a [i] [j]; return m; }
21,505,623
private void updateWeightAnalog (int trackID, int k, float ts, boolean increase) { if (increase) { float targetV = neurons [trackID].getV (ts); float otherV = neurons [k].getV (ts); float targetMean = neurons [trackID].getMeanActivation (); float otherMean = neurons [k].getMeanActivation (); float delta1 = otherV * (otherV - otherMean) * targetV; float delta2 = targetV * (targetV - targetMean) * otherV; float mDelta = sigmoid ((delta1 + delta2) / 2.0f); w [trackID] [k] += alpha * mDelta; if (w [trackID] [k] > 1.0f) w [trackID] [k] = 1.0f; w [k] [trackID] = w [trackID] [k]; } else { w [trackID] [k] -= reduceW; if (w [trackID] [k] < - 1.0f) w [trackID] [k] = - 1.0f; w [k] [trackID] = w [trackID] [k]; } }
Transpose a Matrix.
Type-3 (WT3/4)
true
5,102,752
public String stringOfUrl (String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream (); URL url = new URL (addr); IOUtils.copy (url.openStream (), output); return output.toString (); }
11,092,394
private void copy (final File file) throws IOException { String targetFilename = targetFilename (file); FileInputStream fis = new FileInputStream (file); try { FileChannel source = fis.getChannel (); try { FileOutputStream fos = new FileOutputStream (targetFilename); try { FileChannel target = fos.getChannel (); try { target.transferFrom (source, 0, source.size ()); } finally { target.close (); } } finally { fos.close (); } } finally { source.close (); } } finally { fis.close (); } }
Copy File
Type-3 (WT3/4)
true
1,903,107
private void writeEntry (JarOutputStream jos, ZipEntry entry, InputStream data) throws IOException { jos.putNextEntry (entry); byte [] newBytes = InputStreamUtil.createReadBuffer (); int size = data.read (newBytes); while (size != - 1) { jos.write (newBytes, 0, size); size = data.read (newBytes); } data.close (); }
8,305,219
@Override protected void handleFile (File file, int depth, Collection results) throws IOException { String path = ""; File parent = file.getParentFile (); for (int i = 0; i < depth - 1; i ++) { path = parent.getName () + "/" + path; parent = parent.getParentFile (); } ZipEntry entry = new ZipEntry (path + file.getName ()); output.putNextEntry (entry); int size = (int) file.length (); byte [] buffer = new byte [size]; FileInputStream fis = new FileInputStream (file); fis.read (buffer); output.write (buffer); }
Zip Files
Type-3 (WT3/4)
true
1,282,532
void initOut () throws IOException { if (zipped) { zout = new ZipOutputStream (sink); zout.putNextEntry (new ZipEntry ("file.xml")); this.xout = new OutputStreamWriter (zout, "UTF8"); } else { this.xout = new OutputStreamWriter (sink, "UTF8"); } }
10,062,086
private void addToJar (JarOutputStream out, InputStream in, String entryName, long length) throws IOException { byte [] buf = new byte [2048]; ZipEntry entry = new ZipEntry (entryName); CRC32 crc = new CRC32 (); entry.setSize (length); entry.setCrc (crc.getValue ()); out.putNextEntry (entry); int read = in.read (buf); while (read > 0) { crc.update (buf, 0, read); out.write (buf, 0, read); read = in.read (buf); } entry.setCrc (crc.getValue ()); in.close (); out.closeEntry (); }
Zip Files
Type-3 (WT3/4)
false
1,093,295
private static void createZip (final File destinationFile, final List < File > files, final int cutFileNameIndex) throws IOException { final ZipOutputStream oStream = new ZipOutputStream (new FileOutputStream (destinationFile)); for (final File file : files) { final String fullFileName = file.getAbsolutePath (); final String cuttedFileName = fullFileName.substring (cutFileNameIndex); final String osIndependendFileName = cuttedFileName.replace (File.separatorChar, '/'); oStream.putNextEntry (new ZipEntry (osIndependendFileName)); final FileInputStream iStream = new FileInputStream (file); FileOperations.copy (iStream, oStream); oStream.closeEntry (); iStream.close (); } oStream.close (); }
9,609,404
private void addFile (ZipOutputStream zos, String path, Element details, String name) throws Exception { ZipEntry entry = new ZipEntry (name); zos.putNextEntry (entry); BinaryFile.write (details, zos); zos.closeEntry (); }
Zip Files
Type-3 (WT3/4)
false
61,823
public void mousePressed (MouseEvent e) { if (e.getClickCount () == 2) { String S, S2, S3, Temp; int i; String [] projstr; switch (ListCommande.getSelectedIndex ()) { case 0 : case 12 : S = JOptionPane.showInputDialog (null, "Entrez le message", "Message", 1); if (S != null) { S = "'" + S; if (ListCommande.getSelectedIndex () == 0) { Temp = ""; if (JOptionPane.showConfirmDialog (null, "Voulez vous positionner le message?", "Option", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) { jump = new JumpTo (null, true); Temp = jump.Ed_X.getText () + "," + jump.Ed_Y.getText (); jump.dispose (); jump = new JumpTo (null, false); jump.setVisible (false); jump.setModal (true); jump.setTitle ("Largeur/Hauteur"); jump.LblX.setText ("W"); jump.LblY.setText ("H"); jump.setVisible (true); Temp += "," + jump.Ed_X.getText () + "," + jump.Ed_Y.getText () + ","; jump.dispose (); S = Temp + S; } Ed_Commande.setText ("Message(" + S + "')"); } if (ListCommande.getSelectedIndex () == 12) Ed_Commande.setText ("OnResultQuery('" + S + "')"); } break; case 1 : cd = new CondDecl (projet, "", null, true); if (cd.status == 1) Ed_Commande.setText ("Condition('" + cd.Commande + "')"); cd.dispose (); break; case 2 : case 3 : values = new String [projet.getObjets ().size ()]; for (int j = 0; j < projet.getObjets ().size (); j ++) values [j] = projet.getObjetByIndex (j).Name; liste = new JListe (values, null, "Choisissez l'objet", true); if (liste.status == 1) { S = "1"; S = (String) JOptionPane.showInputDialog (null, "Entrez la quantité de l'objet", "Quantité", 1, null, null, S); if (S != null) { if (S.compareTo ("") != 0) { if (S.compareTo ("1") == 0) { if (ListCommande.getSelectedIndex () == 2) Ed_Commande.setText ("AddObject(" + liste.ListBox.getSelectedValue ().toString () + ")"); else Ed_Commande.setText ("DelObject(" + liste.ListBox.getSelectedValue ().toString () + ")"); } else { if (ListCommande.getSelectedIndex () == 2) Ed_Commande.setText ("AddObject(" + liste.ListBox.getSelectedValue ().toString () + "," + S + ")"); else Ed_Commande.setText ("DelObject(" + liste.ListBox.getSelectedValue ().toString () + "," + S + ")"); } } } } liste.dispose (); break; case 4 : case 5 : ArrayList < Carte > carte = projet.getCartes (); ArrayList < String > nomcarte = new ArrayList < String > (); for (i = 0; i < carte.size (); i ++) nomcarte.add (carte.get (i).Name); projstr = new String [nomcarte.size ()]; projstr = nomcarte.toArray (projstr); liste = new JListe (projstr, null, "Choisissez la carte", true); if (liste.status == 1) { jump = new JumpTo (null, true); if (jump.status == 1) { if (ListCommande.getSelectedIndex () == 4) Ed_Commande.setText ("Teleport(" + liste.ListBox.getSelectedValue ().toString () + "," + jump.Ed_X.getText () + "," + jump.Ed_Y.getText () + ")"); else Ed_Commande.setText ("ChangeResPoint(" + liste.ListBox.getSelectedValue ().toString () + "," + jump.Ed_X.getText () + "," + jump.Ed_Y.getText () + ")"); } jump.dispose (); } liste.dispose (); break; case 6 : jump = new JumpTo (null, true); if (jump.status == 1) Ed_Commande.setText ("SScroll(" + jump.Ed_X.getText () + "," + jump.Ed_Y.getText () + ")"); jump.dispose (); break; case 7 : ArrayList < String > nomclasses = new ArrayList < String > (); for (i = 0; i < projet.getClassesJoueur ().size (); i ++) nomclasses.add (projet.getClassesJoueur ().get (i).Name); projstr = new String [nomclasses.size ()]; projstr = nomclasses.toArray (projstr); liste = new JListe (projstr, null, "Choisissez la classe(vide=aucune)", true); if (liste.status == 1) { Ed_Commande.setText ("ChangeClasse('" + liste.ListBox.getSelectedValue ().toString () + "')"); } break; case 8 : case 17 : case 19 : case 20 : case 21 : JFileChooser choix = new JFileChooser (); if (ListCommande.getSelectedIndex () == 7) choix.setCurrentDirectory (new java.io.File (projet.getName () + "/Chipset/")); else choix.setCurrentDirectory (new java.io.File (projet.getName () + "/Sound/")); int retour = choix.showOpenDialog (null); if (retour == JFileChooser.APPROVE_OPTION) { switch (ListCommande.getSelectedIndex ()) { case 8 : Ed_Commande.setText ("ChangeSkin('Chipset\\" + choix.getSelectedFile ().getName () + "')"); break; case 17 : Ed_Commande.setText ("PlayMusic('Sound\\" + choix.getSelectedFile ().getName () + "')"); break; case 29 : Ed_Commande.setText ("PlaySound('Sound\\" + choix.getSelectedFile ().getName () + "')"); break; case 20 : Ed_Commande.setText ("ChAttaqueSound('Sound\\" + choix.getSelectedFile ().getName () + "')"); break; case 21 : Ed_Commande.setText ("ChBlesseSound('Sound\\" + choix.getSelectedFile ().getName () + "')"); break; } } break; case 9 : values = new String [projet.getMonstres ().size ()]; for (int j = 0; j < projet.getMonstres ().size (); j ++) values [j] = projet.getMonstreByIndex (j).Name; liste = new JListe (values, null, "Choisissez le monstre", true); if (liste.status == 1) { jump = new JumpTo (null, true); if (jump.status == 1) { S = JOptionPane.showInputDialog (null, "Entrez le nombre de Monstre", "Monstre", 1); if (S != null) { S2 = JOptionPane.showInputDialog (null, "Vitesse de respawn?(0=ne respawn pas)", "Monstre", 1); if (S2 != null) { S3 = JOptionPane.showInputDialog (null, "Monstres donnent de l'xp? (0=non, 1=oui)", "Monstre", 1); if (S3 != null) { Ed_Commande.setText ("GenereMonstre(" + liste.ListBox.getSelectedValue ().toString () + "," + jump.Ed_X.getText () + "," + jump.Ed_Y.getText () + "," + S + "," + S2 + "," + S3 + ")"); } } } } jump.dispose (); } liste.dispose (); break; case 11 : Temp = ""; if (JOptionPane.showConfirmDialog (null, "Voulez vous positionner le query?", "Option", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) { jump = new JumpTo (null, true); if (jump.status == 1) Temp = "InputQuery(" + jump.Ed_X.getText () + "," + jump.Ed_Y.getText (); jump.dispose (); } S = JOptionPane.showInputDialog (null, "Entrez la question", "Message", 1); if (S != null) { i = 0; if (Temp.compareTo ("") == 0) Temp = "InputQuery('" + S + "'"; else Temp += ",'" + S + "'"; do { S = ""; S = JOptionPane.showInputDialog (null, "Entrez la réponse " + (i + 1), "Message", 1); if (S == null) S = ""; if (S != "") Temp += ",'" + S + "'"; i ++; } while (S != ""); Temp += ")"; Ed_Commande.setText (Temp); } break; case 14 : S = JOptionPane.showInputDialog (null, "Entrez la question", "Message", 1); if (S != null) Ed_Commande.setText (Ed_Commande.getText () + "InputString('" + S + "')"); break; case 15 : S = JOptionPane.showInputDialog (null, "Entrez le message du magasin", "Message", 1); if (S != null) { values = new String [projet.getObjets ().size ()]; for (int j = 0; j < projet.getObjets ().size (); j ++) values [j] = projet.getObjetByIndex (j).Name; liste = new JListe (values, null, "Choisissez les objets", true); if (liste.status == 1) { Ed_Commande.setText ("Magasin('" + S + "'"); Object [] obj = liste.ListBox.getSelectedValues (); for (int j = 0; j < obj.length; j ++) Ed_Commande.setText (Ed_Commande.getText () + ",'" + obj [j].toString () + "'"); Ed_Commande.setText (Ed_Commande.getText () + ")"); } liste.dispose (); } break; case 16 : S = JOptionPane.showInputDialog (null, "Entrez le temps d'attente", "Timer", 1); if (S != null) Ed_Commande.setText ("Attente(" + S + ")"); break; case 22 : case 23 : values = new String [projet.getMagies ().size ()]; for (int j = 0; j < projet.getMagies ().size (); j ++) values [j] = projet.getMagieByIndex (j).Name; liste = new JListe (values, null, "Choisissez la magie", true); if (liste.status == 1) { if (ListCommande.getSelectedIndex () == 23) Ed_Commande.setText ("AddMagie(" + liste.ListBox.getSelectedValue ().toString () + ")"); else Ed_Commande.setText ("DelMagie(" + liste.ListBox.getSelectedValue ().toString () + ")"); } liste.dispose (); break; case 26 : case 27 : S = JOptionPane.showInputDialog (null, "Entrez le nom de la sauvegarde(Vide = Choix du joueur)", "Sauvegarde", 1); if (S != null) { if (ListCommande.getSelectedIndex () == 27) Ed_Commande.setText ("Chargement('" + S + "')"); else Ed_Commande.setText ("Sauvegarde('" + S + "')"); } break; case 33 : case 34 : projstr = new String [verifie.getMenuPossibles ().size ()]; projstr = verifie.getMenuPossibles ().toArray (projstr); liste = new JListe (projstr, null, "Choisissez le menu", true); if (liste.status == 1) { if (ListCommande.getSelectedIndex () == 32) Ed_Commande.setText ("AddMenu(" + liste.ListBox.getSelectedValue ().toString () + ")"); else Ed_Commande.setText ("DelMenu(" + liste.ListBox.getSelectedValue ().toString () + ")"); } break; default : Ed_Commande.setText (Ed_Commande.getText () + ListCommande.getSelectedValue ().toString ()); } } }
280,540
private void readNormalButtonActionPerformed (java.awt.event.ActionEvent evt) { int returnVal = fc.showOpenDialog (this); if (returnVal == JFileChooser.APPROVE_OPTION) { input = fc.getSelectedFile (); } else return; try { FileInputStream fis = new FileInputStream (input); InputStreamReader isr = new InputStreamReader (fis, "UTF8"); BufferedReader uni = new BufferedReader (isr); String line = "", s = ""; while (line != null) { line = uni.readLine (); if (line != null) { s += line + "\n"; } } jTextArea1.setText (s); jTextPane1.setText (s); } catch (Exception ex) { String oops = ex.toString (); } }
File Dialog
Type-3 (WT3/4)
true
413,237
public void convert (File src, File dest) throws IOException { InputStream in = new BufferedInputStream (new FileInputStream (src)); DcmParser p = pfact.newDcmParser (in); Dataset ds = fact.newDataset (); p.setDcmHandler (ds.getDcmHandler ()); try { FileFormat format = p.detectFileFormat (); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println ("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile (format, Tags.PixelData); if (ds.contains (Tags.StudyInstanceUID) || ds.contains (Tags.SeriesInstanceUID) || ds.contains (Tags.SOPInstanceUID) || ds.contains (Tags.SOPClassUID)) { System.out.println ("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag () == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt (Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength (); if (hasPixelData) { if (inflate) { ds.putUS (Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt (Tags.BitsAllocated, 0)>>> 3) * ds.getInt (Tags.Rows, 0) * ds.getInt (Tags.Columns, 0) * ds.getInt (Tags.NumberOfFrames, 1) * ds.getInt (Tags.NumberOfSamples, 1)) { System.out.println ("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI (Tags.StudyInstanceUID, uid (studyUID)); ds.putUI (Tags.SeriesInstanceUID, uid (seriesUID)); ds.putUI (Tags.SOPInstanceUID, uid (instUID)); ds.putUI (Tags.SOPClassUID, classUID); if (! ds.contains (Tags.NumberOfSamples)) { ds.putUS (Tags.NumberOfSamples, 1); } if (! ds.contains (Tags.PhotometricInterpretation)) { ds.putCS (Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo (fact.newFileMetaInfo (ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream (new FileOutputStream (dest)); try { } finally { ds.writeFile (out, encodeParam ()); if (hasPixelData) { if (! skipGroupLen) { out.write (PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write ((byte) grlen); out.write ((byte) (grlen>> 8)); out.write ((byte) (grlen>> 16)); out.write ((byte) (grlen>> 24)); } out.write (PXDATA_TAG); out.write ((byte) pxlen); out.write ((byte) (pxlen>> 8)); out.write ((byte) (pxlen>> 16)); out.write ((byte) (pxlen>> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write (in.read ()); b2 = in.read (); b3 = in.read (); out.write (b2 & 0x0f); out.write (b2>> 4 | ((b3 & 0x0f) << 4)); out.write (b3>> 4); } } else { for (; pxlen > 0; -- pxlen) { out.write (in.read ()); } } out.close (); } System.out.print ('.'); } finally { in.close (); } }
3,660,402
public void importCertFile (File file) throws IOException { File kd; File cd; synchronized (this) { kd = keysDir; cd = certsDir; } if (! cd.isDirectory ()) { kd.mkdirs (); cd.mkdirs (); } String newName = file.getName (); File dest = new File (cd, newName); FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream (file).getChannel (); destinationChannel = new FileOutputStream (dest).getChannel (); sourceChannel.transferTo (0, sourceChannel.size (), destinationChannel); } finally { if (sourceChannel != null) { try { sourceChannel.close (); } catch (IOException e) { } } if (destinationChannel != null) { try { destinationChannel.close (); } catch (IOException e) { } } } }
Copy File
Type-3 (WT3/4)
true
468,954
private byte [] getFileContents (String fileName) throws Exception { ByteArrayOutputStream ba = new ByteArrayOutputStream (); FileInputStream fis = new FileInputStream (fileName); byte [] data = new byte [1024]; int read = fis.read (data, 0, 1024); while (read > - 1) { ba.write (data, 0, read); read = fis.read (data, 0, 1024); } fis.close (); return ba.toByteArray (); }
6,033,123
public static boolean unZip (String zipname, String extractTo) { InputStream is; ZipInputStream zis; try { is = new FileInputStream (extractTo + zipname); zis = new ZipInputStream (new BufferedInputStream (is)); ZipEntry ze; while ((ze = zis.getNextEntry ()) != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; int count; String filename = ze.getName (); FileOutputStream fout = new FileOutputStream (extractTo + filename); while ((count = zis.read (buffer)) != - 1) { baos.write (buffer, 0, count); byte [] bytes = baos.toByteArray (); fout.write (bytes); baos.reset (); } fout.flush (); fout.close (); zis.closeEntry (); } zis.close (); } catch (IOException e) { e.printStackTrace (); return false; } return true; }
Load File into Byte Array
Type-3 (WT3/4)
true
469,518
public synchronized void writeFile (String filename) throws IOException { int amount; byte buffer [] = new byte [4096]; File f = new File (filename); FileInputStream in = new FileInputStream (f); putNextEntry (new ZipEntry (f.getName ())); while ((amount = in.read (buffer)) != - 1) write (buffer, 0, amount); closeEntry (); in.close (); }
16,171,577
private void zipTempDir (String dir2zip, ZipOutputStream zos) { try { File zipDir = new File (dir2zip); String [] dirList = zipDir.list (); byte [] readBuffer = new byte [2156]; int bytesIn = 0; for (int i = 0; i < dirList.length; i ++) { File f = new File (zipDir, dirList [i]); if (f.isDirectory ()) { String filePath = f.getPath (); zipTempDir (filePath, zos); continue; } FileInputStream fis = new FileInputStream (f); String filePath = f.getPath (); filePath = getZipPath (filePath); ZipEntry anEntry = new ZipEntry (filePath); zos.putNextEntry (anEntry); while ((bytesIn = fis.read (readBuffer)) != - 1) { zos.write (readBuffer, 0, bytesIn); } fis.close (); } } catch (Exception e) { System.out.println ("Could not do the zipDir process. debug zipDir()"); System.out.println ("This would be an internal variable configuration error. I guess you'll have to debug it"); e.printStackTrace (); System.exit (1); } }
Zip Files
Type-3 (WT3/4)
false
732,800
public BufferedWriter createOutputStream (String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char [] buf = new char [k_blockSize]; File ofp = new File (outFile); ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (ofp)); zos.setMethod (ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter (zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter (osw); ZipEntry zot = null; File ifp = new File (inFile); ZipInputStream zis = new ZipInputStream (new FileInputStream (ifp)); InputStreamReader isr = new InputStreamReader (zis, "ISO-8859-1"); BufferedReader br = new BufferedReader (isr); ZipEntry zit = null; while ((zit = zis.getNextEntry ()) != null) { if (zit.getName ().equals ("content.xml")) { continue; } zot = new ZipEntry (zit.getName ()); zos.putNextEntry (zot); while ((byteCount = br.read (buf, 0, k_blockSize)) >= 0) bw.write (buf, 0, byteCount); bw.flush (); zos.closeEntry (); } zos.putNextEntry (new ZipEntry ("content.xml")); bw.flush (); osw = new OutputStreamWriter (zos, "UTF8"); bw = new BufferedWriter (osw); return bw; }
9,744,794
public static void saveToZipFile (File f, ByteBuffer buf) { try { FileOutputStream fOut = new FileOutputStream (f); ZipOutputStream zipOut = new ZipOutputStream (fOut); zipOut.putNextEntry (new ZipEntry ("contents")); zipOut.write (buf.getBytes ()); zipOut.closeEntry (); zipOut.close (); fOut.close (); } catch (Exception e) { e.printStackTrace (); } }
Zip Files
Type-3 (WT3/4)
false
778,875
public BufferedWriter createOutputStream (String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char [] buf = new char [k_blockSize]; File ofp = new File (outFile); ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (ofp)); zos.setMethod (ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter (zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter (osw); ZipEntry zot = null; File ifp = new File (inFile); ZipInputStream zis = new ZipInputStream (new FileInputStream (ifp)); InputStreamReader isr = new InputStreamReader (zis, "ISO-8859-1"); BufferedReader br = new BufferedReader (isr); ZipEntry zit = null; while ((zit = zis.getNextEntry ()) != null) { if (zit.getName ().equals ("content.xml")) { continue; } zot = new ZipEntry (zit.getName ()); zos.putNextEntry (zot); while ((byteCount = br.read (buf, 0, k_blockSize)) >= 0) bw.write (buf, 0, byteCount); bw.flush (); zos.closeEntry (); } zos.putNextEntry (new ZipEntry ("content.xml")); bw.flush (); osw = new OutputStreamWriter (zos, "UTF8"); bw = new BufferedWriter (osw); return bw; }
10,287,019
public static File fileToZipFile (File file) throws Exception { ZipOutputStream out = null; FileInputStream in = null; File retFile = changeFileNameSuffix (file, "zip"); try { byte [] buf = new byte [1024]; out = new ZipOutputStream (new FileOutputStream (retFile)); in = new FileInputStream (file); out.putNextEntry (new ZipEntry (file.getName ())); int len; while ((len = in.read (buf)) > 0) { out.write (buf, 0, len); } out.closeEntry (); } finally { if (in != null) { in.close (); } if (out != null) { out.close (); } } file.delete (); return retFile; }
Zip Files
Type-3 (WT3/4)
false
2,238,218
public void includeCss (Group group, Writer out, PageContext pageContext) throws IOException { ByteArrayOutputStream outtmp = new ByteArrayOutputStream (); if (AbstractGroupBuilder.getInstance ().buildGroupJsIfNeeded (group, outtmp, pageContext.getServletContext ())) { FileOutputStream fileStream = null; try { fileStream = new FileOutputStream (new File (RetentionHelper.buildFullRetentionFilePath (group, ".css"))); IOUtils.copy (new ByteArrayInputStream (outtmp.toByteArray ()), fileStream); } finally { if (fileStream != null) fileStream.close (); } } }
9,857,695
private void copyArtifact (String name) throws IOException { IOUtils.copyFromClassPath (name, model.getOutputFolder () + name); }
Copy File
Type-3 (WT3/4)
true
892,279
File zip (File dir, File zipFile) throws IOException { ZipOutputStream zipOut = new ZipOutputStream (new FileOutputStream (zipFile)); for (File file : dir.listFiles ()) { if (file.isFile ()) { byte [] data = new byte [(int) file.length ()]; DataInputStream in = new DataInputStream (new FileInputStream (file)); in.readFully (data); in.close (); zipOut.putNextEntry (new ZipEntry (file.getName ())); zipOut.write (data, 0, data.length); zipOut.closeEntry (); } } zipOut.close (); return zipFile; }
18,517,649
void signJar (String jarName, String alias, String [] args) throws Exception { boolean aliasUsed = false; X509Certificate tsaCert = null; if (sigfile == null) { sigfile = alias; aliasUsed = true; } if (sigfile.length () > 8) { sigfile = sigfile.substring (0, 8).toUpperCase (Locale.ENGLISH); } else { sigfile = sigfile.toUpperCase (Locale.ENGLISH); } StringBuilder tmpSigFile = new StringBuilder (sigfile.length ()); for (int j = 0; j < sigfile.length (); j ++) { char c = sigfile.charAt (j); if (! ((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '-') || (c == '_'))) { if (aliasUsed) { c = '_'; } else { throw new RuntimeException (rb.getString ("signature filename must consist of the following characters: A-Z, 0-9, _ or -")); } } tmpSigFile.append (c); } sigfile = tmpSigFile.toString (); String tmpJarName; if (signedjar == null) tmpJarName = jarName + ".sig"; else tmpJarName = signedjar; File jarFile = new File (jarName); File signedJarFile = new File (tmpJarName); try { zipFile = new ZipFile (jarName); } catch (IOException ioe) { error (rb.getString ("unable to open jar file: ") + jarName, ioe); } FileOutputStream fos = null; try { fos = new FileOutputStream (signedJarFile); } catch (IOException ioe) { error (rb.getString ("unable to create: ") + tmpJarName, ioe); } PrintStream ps = new PrintStream (fos); ZipOutputStream zos = new ZipOutputStream (ps); String sfFilename = (META_INF + sigfile + ".SF").toUpperCase (Locale.ENGLISH); String bkFilename = (META_INF + sigfile + ".DSA").toUpperCase (Locale.ENGLISH); Manifest manifest = new Manifest (); Map < String, Attributes > mfEntries = manifest.getEntries (); Attributes oldAttr = null; boolean mfModified = false; boolean mfCreated = false; byte [] mfRawBytes = null; try { MessageDigest digests [] = {MessageDigest.getInstance (digestalg)}; ZipEntry mfFile; if ((mfFile = getManifestFile (zipFile)) != null) { mfRawBytes = getBytes (zipFile, mfFile); manifest.read (new ByteArrayInputStream (mfRawBytes)); oldAttr = (Attributes) (manifest.getMainAttributes ().clone ()); } else { Attributes mattr = manifest.getMainAttributes (); mattr.putValue (Attributes.Name.MANIFEST_VERSION.toString (), "1.0"); String javaVendor = System.getProperty ("java.vendor"); String jdkVersion = System.getProperty ("java.version"); mattr.putValue ("Created-By", jdkVersion + " (" + javaVendor + ")"); mfFile = new ZipEntry (JarFile.MANIFEST_NAME); mfCreated = true; } BASE64Encoder encoder = new JarBASE64Encoder (); Vector < ZipEntry > mfFiles = new Vector < ZipEntry > (); for (Enumeration < ? extends ZipEntry > enum_ = zipFile.entries (); enum_.hasMoreElements ();) { ZipEntry ze = enum_.nextElement (); if (ze.getName ().startsWith (META_INF)) { mfFiles.addElement (ze); if (signatureRelated (ze.getName ())) { continue; } } if (manifest.getAttributes (ze.getName ()) != null) { if (updateDigests (ze, zipFile, digests, encoder, manifest) == true) { mfModified = true; } } else if (! ze.isDirectory ()) { Attributes attrs = getDigestAttributes (ze, zipFile, digests, encoder); mfEntries.put (ze.getName (), attrs); mfModified = true; } } if (mfModified) { ByteArrayOutputStream baos = new ByteArrayOutputStream (); manifest.write (baos); byte [] newBytes = baos.toByteArray (); if (mfRawBytes != null && oldAttr.equals (manifest.getMainAttributes ())) { int newPos = findHeaderEnd (newBytes); int oldPos = findHeaderEnd (mfRawBytes); if (newPos == oldPos) { System.arraycopy (mfRawBytes, 0, newBytes, 0, oldPos); } else { byte [] lastBytes = new byte [oldPos + newBytes.length - newPos]; System.arraycopy (mfRawBytes, 0, lastBytes, 0, oldPos); System.arraycopy (newBytes, newPos, lastBytes, oldPos, newBytes.length - newPos); newBytes = lastBytes; } } mfRawBytes = newBytes; } if (mfModified) { mfFile = new ZipEntry (JarFile.MANIFEST_NAME); } if (verbose != null) { if (mfCreated) { System.out.println (rb.getString (" adding: ") + mfFile.getName ()); } else if (mfModified) { System.out.println (rb.getString (" updating: ") + mfFile.getName ()); } } zos.putNextEntry (mfFile); zos.write (mfRawBytes); ManifestDigester manDig = new ManifestDigester (mfRawBytes); SignatureFile sf = new SignatureFile (digests, manifest, manDig, sigfile, signManifest); if (tsaAlias != null) { tsaCert = getTsaCert (tsaAlias); } SignatureFile.Block block = null; try { block = sf.generateBlock (privateKey, sigalg, certChain, externalSF, tsaUrl, tsaCert, signingMechanism, args, zipFile); } catch (SocketTimeoutException e) { error (rb.getString ("unable to sign jar: ") + rb.getString ("no response from the Timestamping Authority. ") + rb.getString ("When connecting from behind a firewall then an HTTP proxy may need to be specified. ") + rb.getString ("Supply the following options to jarsigner: ") + "\n -J-Dhttp.proxyHost=<hostname> " + "\n -J-Dhttp.proxyPort=<portnumber> ", e); } sfFilename = sf.getMetaName (); bkFilename = block.getMetaName (); ZipEntry sfFile = new ZipEntry (sfFilename); ZipEntry bkFile = new ZipEntry (bkFilename); long time = System.currentTimeMillis (); sfFile.setTime (time); bkFile.setTime (time); zos.putNextEntry (sfFile); sf.write (zos); if (verbose != null) { if (zipFile.getEntry (sfFilename) != null) { System.out.println (rb.getString (" updating: ") + sfFilename); } else { System.out.println (rb.getString (" adding: ") + sfFilename); } } if (verbose != null) { if (tsaUrl != null || tsaCert != null) { System.out.println (rb.getString ("requesting a signature timestamp")); } if (tsaUrl != null) { System.out.println (rb.getString ("TSA location: ") + tsaUrl); } if (tsaCert != null) { String certUrl = TimestampedSigner.getTimestampingUrl (tsaCert); if (certUrl != null) { System.out.println (rb.getString ("TSA location: ") + certUrl); } System.out.println (rb.getString ("TSA certificate: ") + printCert ("", tsaCert, false, 0)); } if (signingMechanism != null) { System.out.println (rb.getString ("using an alternative signing mechanism")); } } zos.putNextEntry (bkFile); block.write (zos); if (verbose != null) { if (zipFile.getEntry (bkFilename) != null) { System.out.println (rb.getString (" updating: ") + bkFilename); } else { System.out.println (rb.getString (" adding: ") + bkFilename); } } for (int i = 0; i < mfFiles.size (); i ++) { ZipEntry ze = mfFiles.elementAt (i); if (! ze.getName ().equalsIgnoreCase (JarFile.MANIFEST_NAME) && ! ze.getName ().equalsIgnoreCase (sfFilename) && ! ze.getName ().equalsIgnoreCase (bkFilename)) { writeEntry (zipFile, zos, ze); } } for (Enumeration < ? extends ZipEntry > enum_ = zipFile.entries (); enum_.hasMoreElements ();) { ZipEntry ze = enum_.nextElement (); if (! ze.getName ().startsWith (META_INF)) { if (verbose != null) { if (manifest.getAttributes (ze.getName ()) != null) System.out.println (rb.getString (" signing: ") + ze.getName ()); else System.out.println (rb.getString (" adding: ") + ze.getName ()); } writeEntry (zipFile, zos, ze); } } } catch (IOException ioe) { error (rb.getString ("unable to sign jar: ") + ioe, ioe); } finally { if (zipFile != null) { zipFile.close (); zipFile = null; } if (zos != null) { zos.close (); } } if (signedjar == null) { if (! signedJarFile.renameTo (jarFile)) { File origJar = new File (jarName + ".orig"); if (jarFile.renameTo (origJar)) { if (signedJarFile.renameTo (jarFile)) { origJar.delete (); } else { MessageFormat form = new MessageFormat (rb.getString ("attempt to rename signedJarFile to jarFile failed")); Object [] source = {signedJarFile, jarFile}; error (form.format (source)); } } else { MessageFormat form = new MessageFormat (rb.getString ("attempt to rename jarFile to origJar failed")); Object [] source = {jarFile, origJar}; error (form.format (source)); } } } if (hasExpiredCert || hasExpiringCert || notYetValidCert || badKeyUsage || badExtendedKeyUsage || badNetscapeCertType || chainNotValidated) { System.out.println (); System.out.println (rb.getString ("Warning: ")); if (badKeyUsage) { System.out.println (rb.getString ("The signer certificate's KeyUsage extension doesn't allow code signing.")); } if (badExtendedKeyUsage) { System.out.println (rb.getString ("The signer certificate's ExtendedKeyUsage extension doesn't allow code signing.")); } if (badNetscapeCertType) { System.out.println (rb.getString ("The signer certificate's NetscapeCertType extension doesn't allow code signing.")); } if (hasExpiredCert) { System.out.println (rb.getString ("The signer certificate has expired.")); } else if (hasExpiringCert) { System.out.println (rb.getString ("The signer certificate will expire within six months.")); } else if (notYetValidCert) { System.out.println (rb.getString ("The signer certificate is not yet valid.")); } if (chainNotValidated) { System.out.println (rb.getString ("The signer's certificate chain is not validated.")); } } }
Zip Files
Type-3 (WT3/4)
true
16,930,290
public void writeTo (OutputStream out) throws IOException { IOUtils.copy (tempFile.getInputStream (), out); }
21,715,891
protected void copy (File src, File dest) throws IOException { if (src.isDirectory () && dest.isFile ()) throw new IOException ("Cannot copy a directory to a file"); if (src.isDirectory ()) { File newDir = new File (dest, src.getName ()); if (! newDir.mkdirs ()) throw new IOException ("Cannot create a new Directory"); File [] entries = src.listFiles (); for (int i = 0; i < entries.length; ++ i) copy (entries [i], newDir); return; } if (dest.isDirectory ()) { File newFile = new File (dest, src.getName ()); newFile.createNewFile (); copy (src, newFile); return; } try { if (src.length () == 0) { dest.createNewFile (); return; } FileChannel fc = new FileInputStream (src).getChannel (); FileChannel dstChannel = new FileOutputStream (dest).getChannel (); long transfered = 0; long totalLength = src.length (); while (transfered < totalLength) { long num = fc.transferTo (transfered, totalLength - transfered, dstChannel); if (num == 0) throw new IOException ("Error while copying"); transfered += num; } dstChannel.close (); fc.close (); } catch (IOException e) { if (os.equals ("Unix")) { _logger.fine ("Trying to use cp to copy file..."); File cp = new File ("/usr/bin/cp"); if (! cp.exists ()) cp = new File ("/bin/cp"); if (! cp.exists ()) cp = new File ("/usr/local/bin/cp"); if (! cp.exists ()) cp = new File ("/sbin/cp"); if (! cp.exists ()) cp = new File ("/usr/sbin/cp"); if (! cp.exists ()) cp = new File ("/usr/local/sbin/cp"); if (cp.exists ()) { Process cpProcess = Runtime.getRuntime ().exec (cp.getAbsolutePath () + " '" + src.getAbsolutePath () + "' '" + dest.getAbsolutePath () + "'"); int errCode; try { errCode = cpProcess.waitFor (); } catch (java.lang.InterruptedException ie) { throw e; } return; } } throw e; } }
Copy File
Type-3 (WT3/4)
true
1,409,148
public static int save () { try { String filename = "tyrant.sav"; FileDialog fd = new FileDialog (new Frame (), "Save Game", FileDialog.SAVE); fd.setFile (filename); fd.setVisible (true); if (fd.getFile () != null) { filename = fd.getDirectory () + fd.getFile (); } else { return 0; } FileOutputStream f = new FileOutputStream (filename); ZipOutputStream z = new ZipOutputStream (f); z.putNextEntry (new ZipEntry ("data.xml")); if (! save (new ObjectOutputStream (z))) { throw new Error ("Save game failed"); } Game.message ("Game saved - " + filename); z.closeEntry (); z.close (); if (saveHasBeenCalledAlready) Game.message ("Please note that you can only restore the game with the same version of Tyrant (v" + VERSION + ")."); saveHasBeenCalledAlready = false; } catch (Exception e) { Game.message ("Error while saving: " + e.toString ()); if (QuestApp.isapplet) { Game.message ("This may be due to your browser security restrictions"); Game.message ("If so, run the web start or downloaded application version instead"); } System.out.println (e); return - 1; } return 1; }
19,534,212
@SuppressWarnings("unchecked") public void doGetZip (HashMap < String, String > args, HttpServletResponse res) throws ServletException, IOException { try { int dayIdFrom = Integer.parseInt (args.get ("dateFrom")); int dayIdTo = Integer.parseInt (args.get ("dateTo")); WDCDay dateFrom = new WDCDay (dayIdFrom); WDCDay dateTo = new WDCDay (dayIdTo); DateInterval dateInterval = new DateInterval (dateFrom, dateTo); String dataTimeFormat = args.get ("timeFormat"); int sampling = 0; String s = args.get ("sampling"); if (s != null) { sampling = Integer.parseInt (s); } String parameters = args.get ("param"); String [] paramArray = parameters.split (";"); long curTime = (new java.util.Date ()).getTime (); res.addHeader ("content-disposition", "attachment; filename=spidr_" + curTime + ".zip"); Connection con = null; Statement stmt = null; WDCTable metaElem = null; try { con = ConnectionPool.getConnection ("metadata"); stmt = con.createStatement (); metaElem = new WDCTable (stmt, SQL_LOAD_META_ELEMENTS); stmt.close (); } finally { try { ConnectionPool.releaseConnection (con); } catch (Exception ignore) { } } LocalApi api = new LocalApi (); DataSequenceSet dss = new DataSequenceSet (""); for (int i = 0; i < paramArray.length; i ++) { Vector < ? > p = getParameter (paramArray [i]); String elem = (String) p.get (0); String table = (String) p.get (1); String station = (String) p.get (2); Station stn = null; if (station != null) { stn = new Station (station, table, ""); } int indElemElement = metaElem.getColumnIndex ("element"); int indElemTable = metaElem.getColumnIndex ("elemTable"); int indElemDescription = metaElem.getColumnIndex ("description"); int indElemMultiplier = metaElem.getColumnIndex ("multiplier"); int indElemMissingValue = metaElem.getColumnIndex ("missingValue"); int indElemUnits = metaElem.getColumnIndex ("units"); int elInd = metaElem.findRow (indElemTable, table, indElemElement, elem); String elemDescr = (String) metaElem.getValueAt (elInd, indElemDescription); String elemUnits = (String) metaElem.getValueAt (elInd, indElemUnits); float multiplier = Float.parseFloat ((String) metaElem.getValueAt (elInd, indElemMultiplier)); float missingValue = Float.parseFloat ((String) metaElem.getValueAt (elInd, indElemMissingValue)); DataDescription descr = new DataDescription (table, elem, "", elemDescr, elemUnits, elem); descr.setMultiplier (multiplier); descr.setMissingValue (missingValue); Vector < ? > v = api.getData (descr, stn, dateInterval, sampling); if (v != null && v.size () != 0) { DataSequence ds = (DataSequence) v.get (0); dss.add (ds); } } for (int i = 0; i < dss.size (); i ++) { String group = ""; DailyData dd = null; try { dd = (DailyData) ((DataSequence) dss.elementAt (i)).elementAt (0); DataDescription ddescr = dd.getDescription (); String table = ddescr.getTable (); String [] groupList = Utilities.splitString (Settings.get ("viewGroups.groupOrder")); boolean flag = false; for (int k = 0; (k < groupList.length) && ! flag; k ++) { String [] tables = UpdateMetadata.getTablesForGroup (groupList [k]); for (int j = 0; (j < tables.length) && ! flag; j ++) { if (tables [j].equals (table)) { flag = true; group = groupList [k]; } } } } catch (Exception e) { log.error ("Unexpected error: " + e.toString ()); } ZipOutputStream zos = new ZipOutputStream (res.getOutputStream ()); for (int j = 0; j <= dss.size (); j ++) { dd = (DailyData) ((DataSequence) dss.elementAt (i)).elementAt (0); try { String spidrServerName = Settings.get ("sites.localSite"); String spidrServerUrl = Settings.get ("sites." + spidrServerName + ".url"); String metadataCollection = Settings.get ("viewGroups." + group + ".metadataCollection"); String fileUrl = spidrServerUrl + (spidrServerUrl.endsWith ("/") ? "" : "/") + "osproxy.do?specialRequest=document&docId=" + metadataCollection + dd.getStation ().getStn ().split ("_") [0]; BufferedReader in = new BufferedReader (new InputStreamReader ((new URL (fileUrl)).openStream ())); zos.putNextEntry (new ZipEntry (dd.getStation ().getStn () + ".xml")); int buf; while ((buf = in.read ()) != - 1) { zos.write (buf); } in.close (); } catch (Exception e) { log.error ("Couldn't add metadata to ZIP file: " + e.toString ()); } } String entryFileName = "spidr_" + curTime + "_" + i + ".txt"; zos.putNextEntry (new ZipEntry (entryFileName)); PrintWriter plt = new PrintWriter (zos); if (log.isDebugEnabled ()) { log.debug ("asciiExportDataSet() files are ready"); } String dateFormat = "yyyy-MM-dd HH:mm"; TimeZone tz = new SimpleTimeZone (0, "GMT"); Calendar utc = new GregorianCalendar (tz); utc.setTime (new java.util.Date ()); SimpleDateFormat df = new SimpleDateFormat (dateFormat, Locale.US); df.setTimeZone (tz); df.setCalendar (utc); plt.println ("#Spidr data output file in ASCII format created at " + df.format (utc.getTime ())); if (log.isDebugEnabled ()) { log.debug ("asciiExportDataSet() datestamp is ready"); } plt.println ("#GMT time is used"); plt.println ("#param: " + parameters); plt.println ("#meta: http://spidr.ngdc.noaa.gov/spidr/GetMetadata?describe&param=" + parameters); plt.println ("#"); plt.println ("#"); plt.println ("#--------------------------------------------------"); for (int j = 0; j < dss.size (); j ++) { DSSExport.vec2stream (plt, (DataSequence) dss.elementAt (j), dataTimeFormat); } plt.close (); } } catch (Exception e) { throw new ServletException (e); } }
Zip Files
Type-3 (WT3/4)
false
2,217,508
public static void copyFile (final File sourceFile, final File destFile) throws IOException { if (destFile.getParentFile () != null && ! destFile.getParentFile ().mkdirs ()) { LOG.error ("GeneralHelper.copyFile(): Cannot create parent directories from " + destFile); } FileInputStream fIn = null; FileOutputStream fOut = null; FileChannel source = null; FileChannel destination = null; try { fIn = new FileInputStream (sourceFile); source = fIn.getChannel (); fOut = new FileOutputStream (destFile); destination = fOut.getChannel (); long transfered = 0; final long bytes = source.size (); while (transfered < bytes) { transfered += destination.transferFrom (source, 0, source.size ()); destination.position (transfered); } } finally { if (source != null) { source.close (); } else if (fIn != null) { fIn.close (); } if (destination != null) { destination.close (); } else if (fOut != null) { fOut.close (); } } }
8,437,742
protected void copy (URL url, File file) throws IOException { InputStream in = null; FileOutputStream out = null; try { in = url.openStream (); out = new FileOutputStream (file); IOUtils.copy (in, out); } finally { if (out != null) { out.close (); } if (in != null) { in.close (); } } }
Copy File
Type-3 (WT3/4)
true
6,503,293
public long checksumFile (String name) throws IOException { byte [] buffer = new byte [4000]; InputStream in = new FileInputStream (new File (dir, name)); Checksum cksum = new CRC32 (); while (true) { int n = in.read (buffer); if (n < 0) break; cksum.update (buffer, 0, n); } return cksum.getValue (); }
13,101,897
private boolean isNotCorrupted (String fileName) throws Exception { FileReader xmlFile; FileReader checksumFile; CRC32 check = new CRC32 (); int c; String compareCheck = ""; check.reset (); try { xmlFile = new FileReader (fileName); while ((c = xmlFile.read ()) != - 1) { check.update ((char) c); } } catch (FileNotFoundException e) { System.out.println ("[ERROR] was not possible to open xml file: " + fileName); throw e; } catch (IOException e) { System.out.println ("[ERROR] was not possible to read xml file: " + fileName); throw e; } try { checksumFile = new FileReader (fileName.substring (0, fileName.length () - 4) + ".crc32"); while ((c = checksumFile.read ()) != - 1) { compareCheck += (char) c; } } catch (FileNotFoundException e) { System.out.println ("[ERROR] was not possible to open checksum file: " + fileName.substring (0, fileName.length () - 4) + ".crc32"); throw e; } catch (IOException e) { System.out.println ("[ERROR] was not possible to read checksum file: " + fileName.substring (0, fileName.length () - 4) + ".crc32"); throw e; } return compareCheck.trim ().equalsIgnoreCase (String.valueOf (check.getValue ())); }
CRC32 File Checksum
Type-3 (WT3/4)
false
1,446,728
private void backupFile (ZipOutputStream out, String base, String fn) throws IOException { String f = FileUtils.getAbsolutePath (fn); base = FileUtils.getAbsolutePath (base); if (! f.startsWith (base)) { Message.throwInternalError (f + " does not start with " + base); } f = f.substring (base.length ()); f = correctFileName (f); out.putNextEntry (new ZipEntry (f)); InputStream in = FileUtils.openFileInputStream (fn); IOUtils.copyAndCloseInput (in, out); out.closeEntry (); }
22,792,098
public static void addToZip (ZipOutputStream zos, String filename, String nameInArchive) throws Exception { File file = new File (filename); if (! file.exists ()) { System.err.println ("File does not exist, skipping: " + filename); return; } BufferedInputStream bis = new BufferedInputStream (new FileInputStream (file)); int bytesRead; byte [] buffer = new byte [1024]; CRC32 crc = new CRC32 (); crc.reset (); while ((bytesRead = bis.read (buffer)) != - 1) { crc.update (buffer, 0, bytesRead); } bis.close (); bis = new BufferedInputStream (new FileInputStream (file)); String nameInArchiveFixed = nameInArchive.replace ("\\", "/"); ZipEntry entry = new ZipEntry (nameInArchiveFixed); entry.setMethod (ZipEntry.STORED); entry.setCompressedSize (file.length ()); entry.setSize (file.length ()); entry.setCrc (crc.getValue ()); zos.putNextEntry (entry); while ((bytesRead = bis.read (buffer)) != - 1) { zos.write (buffer, 0, bytesRead); } bis.close (); }
Zip Files
Type-3 (WT3/4)
false
11,046,598
private String hash (String clearPassword) { if (salt == 0) return null; MessageDigest md = null; try { md = MessageDigest.getInstance ("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError ("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf (salt); md.update (saltString.getBytes ()); md.update (clearPassword.getBytes ()); byte [] digestBytes = md.digest (); StringBuffer digestSB = new StringBuffer (); for (int i = 0; i < digestBytes.length; i ++) { int lowNibble = digestBytes [i] & 0x0f; int highNibble = (digestBytes [i]>> 4) & 0x0f; digestSB.append (Integer.toHexString (highNibble)); digestSB.append (Integer.toHexString (lowNibble)); } String digestStr = digestSB.toString (); return digestStr; }
12,730,349
public static String do_checksum (String data) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance ("MD5"); StringBuffer strbuf = new StringBuffer (); md5.update (data.getBytes (), 0, data.length ()); byte [] digest = md5.digest (); for (int i = 0; i < digest.length; i ++) { strbuf.append (toHexString (digest [i])); } return strbuf.toString (); }
Secure Hash
Type-3 (WT3/4)
true
3,577,507
public static void copyFile (File in, File out) throws IOException { FileChannel inChannel = new FileInputStream (in).getChannel (); FileChannel outChannel = new FileOutputStream (out).getChannel (); try { inChannel.transferTo (0, inChannel.size (), outChannel); } finally { if (inChannel != null) inChannel.close (); if (outChannel != null) outChannel.close (); } }
9,339,937
public FileReader (String filePath, Configuration aConfiguration) throws IOException { file = new File (URLDecoder.decode (filePath, "UTF-8")).getCanonicalFile (); readerConf = aConfiguration; if (file.isDirectory ()) { File indexFile = new File (file, "index.php"); File indexFile_1 = new File (file, "index.html"); if (indexFile.exists () && ! indexFile.isDirectory ()) { file = indexFile; } else if (indexFile_1.exists () && ! indexFile_1.isDirectory ()) { file = indexFile_1; } else { if (! readerConf.getOption ("showFolders").equals ("Yes")) { makeErrorPage (503, "Permision denied"); } else { FileOutputStream out = new FileOutputStream (readerConf.getOption ("wwwPath") + "/temp/temp.php"); File [] files = file.listFiles (); makeHeader (200, - 1, new Date (System.currentTimeMillis ()).toString (), "text/html"); String title = "Index of " + file; out.write (("<html><head><title>" + title + "</title></head><body><h3>Index of " + file + "</h3><p>\n").getBytes ()); for (int i = 0; i < files.length; i ++) { file = files [i]; String filename = file.getName (); String description = ""; if (file.isDirectory ()) { description = "&lt;DIR&gt;"; } out.write (("<a href=\"" + file.getPath ().substring (readerConf.getOption ("wwwPath").length ()) + "\">" + filename + "</a> " + description + "<br>\n").getBytes ()); } out.write (("</p><hr><p>yawwwserwer</p></body><html>").getBytes ()); file = new File (URLDecoder.decode (readerConf.getOption ("wwwPath") + "/temp/temp.php", "UTF-8")).getCanonicalFile (); } } } else if (! file.exists ()) { makeErrorPage (404, "File Not Found."); } else if (getExtension () == ".exe" || getExtension ().contains (".py")) { FileOutputStream out = new FileOutputStream (readerConf.getOption ("wwwPath") + "/temp/temp.php"); out.write ((runCommand (filePath)).getBytes ()); file = new File (URLDecoder.decode (readerConf.getOption ("wwwPath") + "/temp/temp.php", "UTF-8")).getCanonicalFile (); } else { System.out.println (getExtension ()); makeHeader (200, file.length (), new Date (file.lastModified ()).toString (), TYPES.get (getExtension ()).toString ()); } System.out.println (file); }
Copy File
Type-3 (WT3/4)
true
1,121,468
private static PrintWriter getOut (int first, int last, String dir, String lang) throws IOException { if (dir == null) return null; File file = new File (dir, lang + ".wikipedia.zip"); if (! file.exists ()) file.createNewFile (); if (! file.canWrite ()) throw new IllegalArgumentException ("can't write " + file); log (true, "Writing Wikipedia events into " + file.getAbsolutePath ()); System.setProperty ("line.separator", "\n"); ZipOutputStream out = new ZipOutputStream (new FileOutputStream (file)); out.putNextEntry (new ZipEntry (lang + ".wikipedia")); return new PrintWriter (new OutputStreamWriter (out, UTF8)); }
2,668,636
protected void addFile (String path, InputStream source, JarOutputStream jos) throws IOException { jos.putNextEntry (new ZipEntry (path)); try { int count; while ((count = source.read (buffer)) > 0) { jos.write (buffer, 0, count); } } finally { jos.closeEntry (); } }
Zip Files
Type-3 (WT3/4)
false
8,759,736
public File convert (URI uri) throws DjatokaException { processing.add (uri.toString ()); File urlLocal = null; try { logger.info ("processingRemoteURI: " + uri.toURL ()); boolean isJp2 = false; InputStream src = IOUtils.getInputStream (uri.toURL ()); String ext = uri.toURL ().toString ().substring (uri.toURL ().toString ().lastIndexOf (".") + 1).toLowerCase (); if (ext.equals (FORMAT_ID_TIF) || ext.equals (FORMAT_ID_TIFF)) { urlLocal = File.createTempFile ("convert" + uri.hashCode (), "." + FORMAT_ID_TIF); } else if (formatMap.containsKey (ext) && (formatMap.get (ext).equals (FORMAT_MIMEYPE_JP2) || formatMap.get (ext).equals (FORMAT_MIMEYPE_JPX))) { urlLocal = File.createTempFile ("cache" + uri.hashCode (), "." + ext); isJp2 = true; } else { if (src.markSupported ()) src.mark (15); if (ImageProcessingUtils.checkIfJp2 (src)) urlLocal = File.createTempFile ("cache" + uri.hashCode (), "." + FORMAT_ID_JP2); if (src.markSupported ()) src.reset (); else { src.close (); src = IOUtils.getInputStream (uri.toURL ()); } } if (urlLocal == null) { urlLocal = File.createTempFile ("convert" + uri.hashCode (), ".img"); } urlLocal.deleteOnExit (); FileOutputStream dest = new FileOutputStream (urlLocal); IOUtils.copyStream (src, dest); if (! isJp2) urlLocal = processImage (urlLocal, uri); src.close (); dest.close (); return urlLocal; } catch (Exception e) { urlLocal.delete (); throw new DjatokaException (e); } finally { if (processing.contains (uri.toString ())) processing.remove (uri.toString ()); } }
23,241,192
private void publishMap (LWMap map) throws IOException { File savedMap = PublishUtil.saveMap (map); InputStream istream = new BufferedInputStream (new FileInputStream (savedMap)); OutputStream ostream = new BufferedOutputStream (new FileOutputStream (ActionUtil.selectFile ("ConceptMap", "vue"))); int fileLength = (int) savedMap.length (); byte bytes [] = new byte [fileLength]; while (istream.read (bytes, 0, fileLength) != - 1) ostream.write (bytes, 0, fileLength); istream.close (); ostream.close (); }
Copy File
Type-3 (WT3/4)
true
1,121,468
private static PrintWriter getOut (int first, int last, String dir, String lang) throws IOException { if (dir == null) return null; File file = new File (dir, lang + ".wikipedia.zip"); if (! file.exists ()) file.createNewFile (); if (! file.canWrite ()) throw new IllegalArgumentException ("can't write " + file); log (true, "Writing Wikipedia events into " + file.getAbsolutePath ()); System.setProperty ("line.separator", "\n"); ZipOutputStream out = new ZipOutputStream (new FileOutputStream (file)); out.putNextEntry (new ZipEntry (lang + ".wikipedia")); return new PrintWriter (new OutputStreamWriter (out, UTF8)); }
21,057,916
public void zipDir (File zipDir, ZipOutputStream zos, File root) { try { String [] dirList = zipDir.list (); byte [] readBuffer = new byte [1024]; int bytesIn = 0; for (int i = 0; i < dirList.length; i ++) { File f = new File (zipDir, dirList [i]); if (f.isDirectory ()) { zipDir (f, zos, root); continue; } FileInputStream fis = new FileInputStream (f); ZipEntry anEntry = new ZipEntry (f.getPath ().replace (root + File.separator, "")); zos.putNextEntry (anEntry); while ((bytesIn = fis.read (readBuffer)) != - 1) { zos.write (readBuffer, 0, bytesIn); } fis.close (); } } catch (Exception e) { e.printStackTrace (); } }
Zip Files
Type-3 (WT3/4)
false
5,352,578
protected int writeEntry (ZipOutputStream jar, Filelike entry, ULog log) throws IOException, ValidationException { String archiveName = getNameStrategy ().getArchiveName (log, entry); if (archiveName != null && archiveName.length () > 0) { ZipEntry ze = new ZipEntry (archiveName); log.fine ("writing entry {0} ({1} bytes)", new Quote (ze.getName ()), SIZE_FORMAT.format (entry.getSize ())); byte [] bytes = entry.readWhole (); if (! compressed) { ze.setMethod (ZipEntry.STORED); ze.setSize (entry.getSize ()); ze.setCompressedSize (entry.getSize ()); CRC32 crc = new CRC32 (); crc.update (bytes); ze.setCrc (crc.getValue ()); } jar.putNextEntry (ze); jar.write (bytes); jar.closeEntry (); return bytes.length; } else { return 0; } }
16,244,015
private byte [] getgAMABytes () { byte [] array = new byte [16]; ByteBuffer buffer = ByteBuffer.wrap (array); buffer.putInt (4); buffer.put (getISO8859_1Bytes (CHUNK_TYPE_gAMA)); buffer.putInt (gamma); CRC32 crc = new CRC32 (); crc.update (array, 4, 8); buffer.putInt ((int) crc.getValue ()); return array; }
CRC32 File Checksum
Type-3 (WT3/4)
false
12,977,779
public void run () { FileInputStream src; FileOutputStream dest; try { dest = new FileOutputStream (srcName); } catch (FileNotFoundException e) { e.printStackTrace (); return; } FileChannel destC = dest.getChannel (); FileChannel srcC; ByteBuffer buf = ByteBuffer.allocateDirect (BUFFER_SIZE); try { int fileNo = 0; while (true) { int i = 1; String destName = srcName + "_" + fileNo; src = new FileInputStream (destName); srcC = src.getChannel (); while ((i > 0)) { i = srcC.read (buf); buf.flip (); destC.write (buf); buf.compact (); } srcC.close (); src.close (); fileNo ++; } } catch (IOException e1) { e1.printStackTrace (); return; } }
14,652,853
public static void main (String args []) { String midletClass = null; File appletInputFile = null; File deviceInputFile = null; File midletInputFile = null; File htmlOutputFile = null; File appletOutputFile = null; File deviceOutputFile = null; File midletOutputFile = null; List params = new ArrayList (); for (int i = 0; i < args.length; i ++) { params.add (args [i]); } Iterator argsIterator = params.iterator (); while (argsIterator.hasNext ()) { String arg = (String) argsIterator.next (); argsIterator.remove (); if ((arg.equals ("--help")) || (arg.equals ("-help"))) { System.out.println (usage ()); System.exit (0); } else if (arg.equals ("--midletClass")) { midletClass = (String) argsIterator.next (); argsIterator.remove (); } else if (arg.equals ("--appletInput")) { appletInputFile = new File ((String) argsIterator.next ()); argsIterator.remove (); } else if (arg.equals ("--deviceInput")) { deviceInputFile = new File ((String) argsIterator.next ()); argsIterator.remove (); } else if (arg.equals ("--midletInput")) { midletInputFile = new File ((String) argsIterator.next ()); argsIterator.remove (); } else if (arg.equals ("--htmlOutput")) { htmlOutputFile = new File ((String) argsIterator.next ()); argsIterator.remove (); } else if (arg.equals ("--appletOutput")) { appletOutputFile = new File ((String) argsIterator.next ()); argsIterator.remove (); } else if (arg.equals ("--deviceOutput")) { deviceOutputFile = new File ((String) argsIterator.next ()); argsIterator.remove (); } else if (arg.equals ("--midletOutput")) { midletOutputFile = new File ((String) argsIterator.next ()); argsIterator.remove (); } } if (midletClass == null || appletInputFile == null || deviceInputFile == null || midletInputFile == null || htmlOutputFile == null || appletOutputFile == null || deviceOutputFile == null || midletOutputFile == null) { System.out.println (usage ()); System.exit (0); } try { DeviceImpl device = null; String descriptorLocation = null; JarFile jar = new JarFile (deviceInputFile); for (Enumeration en = jar.entries (); en.hasMoreElements ();) { String entry = ((JarEntry) en.nextElement ()).getName (); if ((entry.toLowerCase ().endsWith (".xml") || entry.toLowerCase ().endsWith ("device.txt")) && ! entry.toLowerCase ().startsWith ("meta-inf")) { descriptorLocation = entry; break; } } if (descriptorLocation != null) { EmulatorContext context = new EmulatorContext () { private DisplayComponent displayComponent = new NoUiDisplayComponent (); private InputMethod inputMethod = new J2SEInputMethod (); private DeviceDisplay deviceDisplay = new J2SEDeviceDisplay (this); private FontManager fontManager = new J2SEFontManager (); private DeviceComponent deviceComponent = new SwingDeviceComponent (true); public DisplayComponent getDisplayComponent () { return displayComponent; } public InputMethod getDeviceInputMethod () { return inputMethod; } public DeviceDisplay getDeviceDisplay () { return deviceDisplay; } public FontManager getDeviceFontManager () { return fontManager; } public InputStream getResourceAsStream (String name) { return MIDletBridge.getCurrentMIDlet ().getClass ().getResourceAsStream (name); } public DeviceComponent getDeviceComponent () { return deviceComponent; }} ; URL [] urls = new URL [1]; urls [0] = deviceInputFile.toURI ().toURL (); ClassLoader classLoader = new ExtensionsClassLoader (urls, urls.getClass ().getClassLoader ()); device = DeviceImpl.create (context, classLoader, descriptorLocation, J2SEDevice.class); } if (device == null) { System.out.println ("Error parsing device package: " + descriptorLocation); System.exit (0); } createHtml (htmlOutputFile, device, midletClass, midletOutputFile, appletOutputFile, deviceOutputFile); createMidlet (midletInputFile.toURI ().toURL (), midletOutputFile); IOUtils.copyFile (appletInputFile, appletOutputFile); IOUtils.copyFile (deviceInputFile, deviceOutputFile); } catch (IOException ex) { ex.printStackTrace (); } System.exit (0); }
Copy File
Type-3 (WT3/4)
true
12,883,117
public PhoneSetImpl (URL url) throws IOException { BufferedReader reader; String line; phonesetMap = new HashMap (); reader = new BufferedReader (new InputStreamReader (url.openStream ())); line = reader.readLine (); lineCount ++; while (line != null) { if (! line.startsWith ("***")) { parseAndAdd (line); } line = reader.readLine (); } reader.close (); }
18,196,382
public static List importDate (Report report, TradingDate date) throws ImportExportException { List quotes = new ArrayList (); String urlString = constructURL (date); EODQuoteFilter filter = new MetaStockQuoteFilter (); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.getProxySettings (); try { URL url = new URL (urlString); InputStreamReader input = new InputStreamReader (url.openStream ()); BufferedReader bufferedInput = new BufferedReader (input); String line = null; do { line = bufferedInput.readLine (); if (line != null) { try { EODQuote quote = filter.toEODQuote (line); quotes.add (quote); verify (report, quote); } catch (QuoteFormatException e) { report.addError (Locale.getString ("DFLOAT_DISPLAY_URL") + ":" + date + ":" + Locale.getString ("ERROR") + ": " + e.getMessage ()); } } } while (line != null); bufferedInput.close (); } catch (BindException e) { throw new ImportExportException (Locale.getString ("UNABLE_TO_CONNECT_ERROR", e.getMessage ())); } catch (ConnectException e) { throw new ImportExportException (Locale.getString ("UNABLE_TO_CONNECT_ERROR", e.getMessage ())); } catch (UnknownHostException e) { throw new ImportExportException (Locale.getString ("UNKNOWN_HOST_ERROR", e.getMessage ())); } catch (NoRouteToHostException e) { throw new ImportExportException (Locale.getString ("DESTINATION_UNREACHABLE_ERROR", e.getMessage ())); } catch (MalformedURLException e) { throw new ImportExportException (Locale.getString ("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { report.addError (Locale.getString ("FLOAT_DISPLAY_URL") + ":" + date + ":" + Locale.getString ("ERROR") + ": " + Locale.getString ("NO_QUOTES_FOUND")); } catch (IOException e) { throw new ImportExportException (Locale.getString ("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
Download From Web
Type-3 (WT3/4)
true
291,207
public synchronized void writeFile (String filename) throws IOException { int amount; byte buffer [] = new byte [4096]; File f = new File (filename); FileInputStream in = new FileInputStream (f); putNextEntry (new ZipEntry (f.getName ())); while ((amount = in.read (buffer)) != - 1) write (buffer, 0, amount); closeEntry (); in.close (); }
18,721,146
private void addAllUploadedFiles (Environment en, ZipOutputStream zipout, int progressStart, int progressLength) throws IOException, FileNotFoundException { File uploadPath = en.uploadPath (virtualWiki, ""); String [] files = uploadPath.list (); int bytesRead = 0; byte byteArray [] = new byte [4096]; for (int i = 0; i < files.length; i ++) { progress = Math.min (progressStart + (int) ((double) i * (double) progressLength / (double) files.length), 99); logger.debug ("Adding uploaded file " + files [i]); ZipEntry entry = new ZipEntry (safename (files [i])); try { FileInputStream in = new FileInputStream (en.uploadPath (virtualWiki, files [i])); zipout.putNextEntry (entry); while (in.available () > 0) { bytesRead = in.read (byteArray, 0, Math.min (4096, in.available ())); zipout.write (byteArray, 0, bytesRead); } zipout.closeEntry (); zipout.flush (); } catch (FileNotFoundException e) { logger.warn ("Could not open file!", e); } catch (IOException e) { logger.warn ("IOException!", e); try { zipout.closeEntry (); zipout.flush (); } catch (IOException e1) { } } } }
Zip Files
Type-3 (WT3/4)
true
1,707,074
public void addMetadata (Request request, Entry entry, ZipOutputStream zos, Metadata metadata, Element node) throws Exception { MetadataType type = getType (metadata.getType ()); if (type == null) { throw new IllegalStateException ("Unknown metadata type:" + metadata.getType ()); } Document doc = node.getOwnerDocument (); Element metadataNode = XmlUtil.create (doc, TAG_METADATA, node, new String [] {ATTR_TYPE, metadata.getType ()}); for (MetadataElement element : type.getChildren ()) { int index = element.getIndex (); String value = metadata.getAttr (index); if (value == null) { continue; } Element attrNode = XmlUtil.create (doc, Metadata.TAG_ATTR, metadataNode, new String [] {Metadata.ATTR_INDEX, "" + index}); attrNode.appendChild (XmlUtil.makeCDataNode (doc, value, true)); if (zos != null && element.getDataType ().equals (element.DATATYPE_FILE)) { File f = type.getFile (entry, metadata, element); if (f == null || ! f.exists ()) continue; String fileName = repository.getGUID (); attrNode.setAttribute ("fileid", fileName); zos.putNextEntry (new ZipEntry (fileName)); InputStream fis = getStorageManager ().getFileInputStream (f.toString ()); try { IOUtil.writeTo (fis, zos); } finally { IOUtil.close (fis); zos.closeEntry (); } } } }
20,251,977
private void createTextFile (ZipOutputStream zipOut, String str, String basename, boolean utf8, boolean utf16) throws IOException { byte [] bytes = null; if (utf8) { bytes = str.getBytes ("utf-8"); zipOut.putNextEntry (new ZipEntry (basename + ".txt")); zipOut.write (bytes, 0, bytes.length); } if (utf16) { bytes = str.getBytes ("utf-16"); zipOut.putNextEntry (new ZipEntry (basename + ".utf-16.txt")); zipOut.write (bytes, 0, bytes.length); } }
Zip Files
Type-3 (WT3/4)
false
302,936
public static void copy (String from_name, String to_name, boolean overwriteOk) throws IOException { File from_file = new File (from_name); File to_file = new File (to_name); if (! from_file.exists ()) abort ("FileCopy: no such source file: " + from_name); if (! from_file.isFile ()) abort ("FileCopy: can't copy directory: " + from_name); if (! from_file.canRead ()) abort ("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory ()) to_file = new File (to_file, from_file.getName ()); if (to_file.exists ()) { if (! to_file.canWrite ()) abort ("FileCopy: destination file is unwriteable: " + to_name); if (! overwriteOk) { System.out.print ("Overwrite existing file " + to_name + "? (Y/N): "); System.out.flush (); BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); String response = in.readLine (); if (! response.equals ("Y") && ! response.equals ("y")) abort ("FileCopy: existing file was not overwritten."); } } else { String parent = to_file.getParent (); if (parent == null) parent = System.getProperty ("user.dir"); File dir = new File (parent); if (! dir.exists ()) abort ("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile ()) abort ("FileCopy: destination is not a directory: " + parent); if (! dir.canWrite ()) abort ("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream (from_file); to = new FileOutputStream (to_file); byte [] buffer = new byte [4096]; int bytes_read; while ((bytes_read = from.read (buffer)) != - 1) to.write (buffer, 0, bytes_read); } finally { if (from != null) try { from.close (); } catch (IOException e) { } if (to != null) try { to.close (); } catch (IOException e) { } } }
9,186,582
private static void unzipEntry (ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory ()) { createDir (new File (outputDir, entry.getName ())); return; } File outputFile = new File (outputDir, entry.getName ()); if (! outputFile.getParentFile ().exists ()) { createDir (outputFile.getParentFile ()); } BufferedInputStream inputStream = new BufferedInputStream (zipfile.getInputStream (entry)); BufferedOutputStream outputStream = new BufferedOutputStream (new FileOutputStream (outputFile)); try { IOUtils.copy (inputStream, outputStream); } finally { outputStream.close (); inputStream.close (); } }
Copy File
Type-3 (WT3/4)
true
14,144,378
private static void addToZip (ZipOutputStream zout, String file, String code, String currentDirectory) { try { ZipEntry entry = new ZipEntry (currentDirectory + file); zout.putNextEntry (entry); zout.write (code.getBytes (), 0, code.length ()); zout.closeEntry (); } catch (IOException e) { e.printStackTrace (); } }
16,540,059
public static void makeArchiveFromFolder (@NotNull File folder, File toZipFile, int method) throws IOException, IllegalArgumentException { if (folder == null) { throw new IllegalArgumentException ("the folder can't be null!"); } if (! folder.exists ()) { throw new IllegalArgumentException ("the folder = " + folder.getAbsolutePath () + " don't exist!"); } if (! folder.isDirectory ()) { throw new IllegalArgumentException ("the folder = " + folder.getAbsolutePath () + " is a file and not a folder!"); } BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream (toZipFile); ZipOutputStream out = new ZipOutputStream (new BufferedOutputStream (dest)); out.setMethod (method); byte data [] = new byte [BUFFER]; File files [] = folder.listFiles (); for (int i = 0; i < files.length; i ++) { FileInputStream fi = new FileInputStream (files [i]); origin = new BufferedInputStream (fi, BUFFER); ZipEntry entry = new ZipEntry (files [i].getName ()); out.putNextEntry (entry); int count; while ((count = origin.read (data, 0, BUFFER)) != - 1) { out.write (data, 0, count); } origin.close (); } out.close (); }
Zip Files
Type-3 (WT3/4)
true
2,687,277
@Override protected void copy (Reader reader, OutputStream outputs) throws IOException { if (outputs == null) { throw new NullPointerException (); } if (reader == null) { throw new NullPointerException (); } ZipOutputStream zipoutputs = null; try { zipoutputs = new ZipOutputStream (outputs); zipoutputs.putNextEntry (new ZipEntry ("default")); IOUtils.copy (reader, zipoutputs); } catch (IOException e) { e.printStackTrace (); throw e; } finally { if (zipoutputs != null) { zipoutputs.close (); } if (reader != null) { reader.close (); } } }
11,149,084
private void deleteProject (String uid, String home, HttpServletRequest request, HttpServletResponse response) throws Exception { String project = request.getParameter ("project"); String line; response.setContentType ("text/html"); PrintWriter out = response.getWriter (); htmlHeader (out, "Project Status", ""); try { synchronized (Class.forName ("com.sun.gep.SunTCP")) { Vector list = new Vector (); String directory = home; Runtime.getRuntime ().exec ("/usr/bin/rm -rf " + directory + project); FilePermission perm = new FilePermission (directory + SUNTCP_LIST, "read,write,execute"); File listfile = new File (directory + SUNTCP_LIST); BufferedReader read = new BufferedReader (new FileReader (listfile)); while ((line = read.readLine ()) != null) { if (! ((new StringTokenizer (line, "\t")).nextToken ().equals (project))) { list.addElement (line); } } read.close (); if (list.size () > 0) { PrintWriter write = new PrintWriter (new BufferedWriter (new FileWriter (listfile))); for (int i = 0; i < list.size (); i ++) { write.println ((String) list.get (i)); } write.close (); } else { listfile.delete (); } out.println ("The project was successfully deleted."); } } catch (Exception e) { out.println ("Error accessing this project."); } out.println ("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>"); htmlFooter (out); }
Copy File
Type-3 (WT3/4)
true
9,905,889
public void relativateFiles (String graphName, Node node, ZipOutputStream out) { if (node.getContent () instanceof ImageContent) { try { ImageContent content = (ImageContent) node.getContent (); File file = content.getFile (); String newFileName = graphName + ".files/" + file.getName (); out.putNextEntry (new ZipEntry (newFileName)); content.setFile (new File (newFileName)); byte [] arr = new byte [(int) file.length ()]; (new FileInputStream (file)).read (arr, 0, (int) file.length ()); out.write (arr, 0, (int) file.length ()); out.closeEntry (); } catch (IOException exc) { } } for (int i = 0; i < node.getChildren ().size (); i ++) { relativateFiles (graphName, (Node) node.getChildren ().get (i), out); } }
20,709,172
private final int addFilesToZip (ArrayList < File > files) throws IOException { File old_file = null; try { byte [] buf = new byte [BLOCK_SIZE]; ZipOutputStream out; if (newZip) { out = new ZipOutputStream (new FileOutputStream (zipFile)); } else { ZipFile zf = new ZipFile (zipFile); int num_entries = zf.size (); long total_size = zipFile.length (), bytes_saved = 0; old_file = new File (zipFile.getAbsolutePath () + "_tmp_" + (new Date ()).getSeconds () + ".zip"); if (! zipFile.renameTo (old_file)) throw new RuntimeException ("could not rename the file " + zipFile.getAbsolutePath () + " to " + old_file.getAbsolutePath ()); ZipInputStream zin = new ZipInputStream (new FileInputStream (old_file)); out = new ZipOutputStream (new FileOutputStream (zipFile)); int e_i = 0, pp; ZipEntry entry = zin.getNextEntry (); while (entry != null) { if (isStopReq ()) break; pp = e_i ++ * 100 / num_entries; sendProgress (prep, pp, 0); String name = entry.getName (); boolean notInFiles = true; for (File f : files) { if (isStopReq ()) break; String f_path = f.getAbsolutePath (); if (f_path.regionMatches (true, basePathLen, name, 0, name.length ())) { notInFiles = false; break; } } if (notInFiles) { out.putNextEntry (new ZipEntry (name)); int len; while ((len = zin.read (buf)) > 0) { if (isStopReq ()) break; out.write (buf, 0, len); bytes_saved += len; sendProgress (prep, pp, (int) (bytes_saved * 100 / total_size)); } } entry = zin.getNextEntry (); } zin.close (); if (isStopReq ()) { out.close (); zipFile.delete (); old_file.renameTo (zipFile); return 0; } } double conv = 100./ (double) totalSize; long byte_count = 0; int i; for (i = 0; i < files.size (); i ++) { if (isStopReq ()) break; File f = files.get (i); String fn = f.getAbsolutePath (); String rfn = destPath + fn.substring (basePathLen); if (f.isDirectory ()) { out.putNextEntry (new ZipEntry (rfn + SLS)); } else { out.putNextEntry (new ZipEntry (rfn)); String pack_s = ctx.getString (R.string.packing, fn); InputStream in = new FileInputStream (f); int len; int so_far = (int) (byte_count * conv); while ((len = in.read (buf)) > 0) { if (isStopReq ()) break; out.write (buf, 0, len); byte_count += len; sendProgress (pack_s, so_far, (int) (byte_count * conv)); } in.close (); } out.closeEntry (); if (move) f.delete (); } out.close (); if (isStopReq ()) { zipFile.delete (); if (! newZip) old_file.renameTo (zipFile); return 0; } if (! newZip) old_file.delete (); return i; } catch (Exception e) { error (e.getMessage ()); e.printStackTrace (); if (! newZip) { zipFile.delete (); if (! newZip && old_file != null) old_file.renameTo (zipFile); } return 0; } }
Zip Files
Type-3 (WT3/4)
true
1,514,106
private void exportLearningUnitView (File selectedFile) { if (learningUnitViewElementsManager.isOriginalElementsOnly ()) { String [] elementIds = learningUnitViewElementsManager.getAllLearningUnitViewElementIds (); for (int i = 0; i < elementIds.length; i ++) { FSLLearningUnitViewElement element = learningUnitViewElementsManager.getLearningUnitViewElement (elementIds [i], false); if (element.getLastModificationDate () == null) { element.setLastModificationDate (String.valueOf (new Date ().getTime ())); element.setModified (true); } } learningUnitViewElementsManager.setModified (true); learningUnitViewManager.saveLearningUnitViewData (); if (selectedFile != null) { try { File outputFile = selectedFile; String fileName = outputFile.getName (); StringBuffer extension = new StringBuffer (); if (fileName.length () >= 5) { for (int i = 5; i > 0; i --) { extension.append (fileName.charAt (fileName.length () - i)); } } if (! extension.toString ().equals (".fslv")) { outputFile.renameTo (new File (outputFile.getAbsolutePath () + ".fslv")); outputFile = new File (outputFile.getAbsolutePath () + ".fslv"); } File files [] = selectedFile.getParentFile ().listFiles (); int returnValue = FLGOptionPane.OK_OPTION; for (int i = 0; i < files.length; i ++) { if (outputFile.getAbsolutePath ().equals (files [i].getAbsolutePath ())) { returnValue = FLGOptionPane.showConfirmDialog (internationalization.getString ("dialog.exportLearningUnitView.fileExits.message"), internationalization.getString ("dialog.exportLearningUnitView.fileExits.title"), FLGOptionPane.OK_CANCEL_OPTION, FLGOptionPane.QUESTION_MESSAGE); break; } } if (returnValue == FLGOptionPane.OK_OPTION) { FileOutputStream os = new FileOutputStream (outputFile); ZipOutputStream zipOutputStream = new ZipOutputStream (os); ZipEntry zipEntry = new ZipEntry ("dummy"); zipOutputStream.putNextEntry (zipEntry); zipOutputStream.closeEntry (); zipOutputStream.flush (); zipOutputStream.finish (); zipOutputStream.close (); final File outFile = outputFile; (new Thread () { public void run () { try { ZipOutputStream zipOutputStream = new ZipOutputStream (new FileOutputStream (outFile)); File [] files = (new File (learningUnitViewManager.getLearningUnitViewOriginalDataDirectory ().getPath ())).listFiles (); int maxSteps = files.length; int step = 1; exportProgressDialog = new FLGImageProgressDialog (null, 0, maxSteps, 0, getClass ().getClassLoader ().getResource ("freestyleLearning/homeCore/images/fsl.gif"), (Color) UIManager.get ("FSLColorBlue"), (Color) UIManager.get ("FSLColorRed"), internationalization.getString ("learningUnitViewExport.rogressbarText")); exportProgressDialog.setCursor (new Cursor (Cursor.WAIT_CURSOR)); exportProgressDialog.setBarValue (step); buildExportZipFile ("", zipOutputStream, files, step); zipOutputStream.flush (); zipOutputStream.finish (); zipOutputStream.close (); exportProgressDialog.setBarValue (maxSteps); exportProgressDialog.setCursor (new Cursor (Cursor.DEFAULT_CURSOR)); exportProgressDialog.dispose (); } catch (Exception e) { e.printStackTrace (); } }} ).start (); os.close (); } } catch (Exception exp) { exp.printStackTrace (); } } } else { } }
18,583,911
private static void addDirectoryToJar (File file, ZipOutputStream targetStream, String path) throws IOException { File [] files = file.listFiles (); for (File f : files) { if (f.getName ().startsWith (".")) { continue; } if (f.isDirectory ()) { addDirectoryToJar (f, targetStream, path + "/" + f.getName ()); } else { String dataFileName = path + "/" + f.getName (); InputStream is = new FileInputStream (f); BufferedInputStream sourceStream = new BufferedInputStream (is); ZipEntry theEntry = new ZipEntry (dataFileName); targetStream.putNextEntry (theEntry); byte [] data = new byte [1024]; int bCnt; while ((bCnt = sourceStream.read (data, 0, 1024)) != - 1) { targetStream.write (data, 0, bCnt); } targetStream.flush (); targetStream.closeEntry (); sourceStream.close (); } } }
Zip Files
Type-3 (WT3/4)
false
21,044,594
public void run () { final String basename = FilenameUtils.removeExtension (file.getName ()); final File compressed = new File (logDirectory, basename + ".gz"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream (file); out = new GZIPOutputStream (new FileOutputStream (compressed)); IOUtils.copy (in, out); in.close (); out.close (); } catch (IOException e) { reportError ("Error compressing olg log file after file rotation", e, ErrorManager.GENERIC_FAILURE); } finally { IOUtils.closeQuietly (in); IOUtils.closeQuietly (out); } Collections.replaceAll (files, file, compressed); }
22,717,685
public static final void copy (File src, File dest) throws IOException { FileInputStream source = null; FileOutputStream destination = null; byte [] buffer; int bytes_read; if (! src.exists ()) { throw new IOException ("Source not found: " + src); } if (! src.canRead ()) { throw new IOException ("Source is unreadable: " + src); } if (src.isFile ()) { if (! dest.exists ()) { File parentdir = parent (dest); if (! parentdir.exists ()) { parentdir.mkdir (); } } else if (dest.isDirectory ()) { dest = new File (dest + File.separator + src); } } else if (src.isDirectory ()) { if (dest.isFile ()) { throw new IOException ("Cannot copy directory " + src + " to file " + dest); } if (! dest.exists ()) { dest.mkdir (); } } if (src.isFile ()) { try { source = new FileInputStream (src); destination = new FileOutputStream (dest); buffer = new byte [1024]; while (true) { bytes_read = source.read (buffer); if (bytes_read == - 1) { break; } destination.write (buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close (); } catch (IOException e) { } } if (destination != null) { try { destination.close (); } catch (IOException e) { } } } } else if (src.isDirectory ()) { String targetfile, target, targetdest; String [] files = src.list (); for (int i = 0; i < files.length; i ++) { targetfile = files [i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File (target)).isDirectory ()) { copy (new File (target), new File (targetdest)); } else { try { source = new FileInputStream (target); destination = new FileOutputStream (targetdest); buffer = new byte [1024]; while (true) { bytes_read = source.read (buffer); if (bytes_read == - 1) { break; } destination.write (buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close (); } catch (IOException e) { } } if (destination != null) { try { destination.close (); } catch (IOException e) { } } } } } } }
Copy File
Type-3 (WT3/4)
true
513,417
@Override public void run () { final Counter counter = new Counter ("TRANSMIT", plotter); counter.start (); try { final DataInputStream dis = new DataInputStream (s.getInputStream ()); while (! Thread.interrupted ()) { if (! running.get ()) { Thread.sleep (1000); continue; } final int nextPacketSize = dis.readInt (); counter.addBytes (INTEGER_BYTES); final byte [] packet = new byte [nextPacketSize]; dis.readFully (packet); counter.addBytes (nextPacketSize); final long otherSideCrc = dis.readLong (); counter.addBytes (CRC_BYTES); final CRC32 crc = new CRC32 (); crc.update (packet); if (otherSideCrc != crc.getValue ()) { throw new RuntimeException ("CRC values don't match: this: " + crc.getValue () + ", other: " + otherSideCrc); } } } catch (InterruptedException e) { System.out.println ("Receiver thread interrupted!"); } catch (Exception e) { System.err.println ("Unexpected error in receiver thread: " + e.getMessage ()); } finally { abortLatch.countDown (); counter.interrupt (); } }
6,195,313
protected void zipFile (InputStream in, ZipOutputStream zOut, String vPath, long lastModified, File fromArchive, int mode, ZipExtraField [] extra) throws IOException { if (entries.contains (vPath)) { if (duplicate.equals ("preserve")) { logWhenWriting (vPath + " already added, skipping", Project.MSG_INFO); return; } else if (duplicate.equals ("fail")) { throw new BuildException ("Duplicate file " + vPath + " was found and the duplicate " + "attribute is 'fail'."); } else { logWhenWriting ("duplicate file " + vPath + " found, adding.", Project.MSG_VERBOSE); } } else { logWhenWriting ("adding entry " + vPath, Project.MSG_VERBOSE); } entries.put (vPath, vPath); if (! skipWriting) { ZipEntry ze = new ZipEntry (vPath); ze.setTime (lastModified); ze.setMethod (doCompress ? ZipEntry.DEFLATED : ZipEntry.STORED); if (! zOut.isSeekable () && ! doCompress) { long size = 0; CRC32 cal = new CRC32 (); if (! in.markSupported ()) { ByteArrayOutputStream bos = new ByteArrayOutputStream (); byte [] buffer = new byte [BUFFER_SIZE]; int count = 0; do { size += count; cal.update (buffer, 0, count); bos.write (buffer, 0, count); count = in.read (buffer, 0, buffer.length); } while (count != - 1); in = new ByteArrayInputStream (bos.toByteArray ()); } else { in.mark (Integer.MAX_VALUE); byte [] buffer = new byte [BUFFER_SIZE]; int count = 0; do { size += count; cal.update (buffer, 0, count); count = in.read (buffer, 0, buffer.length); } while (count != - 1); in.reset (); } ze.setSize (size); ze.setCrc (cal.getValue ()); } ze.setUnixMode (mode); zOut.putNextEntry (ze); if (extra != null) { ze.setExtraFields (extra); } byte [] buffer = new byte [BUFFER_SIZE]; int count = 0; do { if (count != 0) { zOut.write (buffer, 0, count); } count = in.read (buffer, 0, buffer.length); } while (count != - 1); } addedFiles.addElement (vPath); }
CRC32 File Checksum
Type-3 (WT3/4)
false
3,880,859
public static final long crc32 (byte [] data) { CRC32 crc32 = new CRC32 (); crc32.update (data); return crc32.getValue (); }
5,352,578
protected int writeEntry (ZipOutputStream jar, Filelike entry, ULog log) throws IOException, ValidationException { String archiveName = getNameStrategy ().getArchiveName (log, entry); if (archiveName != null && archiveName.length () > 0) { ZipEntry ze = new ZipEntry (archiveName); log.fine ("writing entry {0} ({1} bytes)", new Quote (ze.getName ()), SIZE_FORMAT.format (entry.getSize ())); byte [] bytes = entry.readWhole (); if (! compressed) { ze.setMethod (ZipEntry.STORED); ze.setSize (entry.getSize ()); ze.setCompressedSize (entry.getSize ()); CRC32 crc = new CRC32 (); crc.update (bytes); ze.setCrc (crc.getValue ()); } jar.putNextEntry (ze); jar.write (bytes); jar.closeEntry (); return bytes.length; } else { return 0; } }
CRC32 File Checksum
Type-3 (WT3/4)
false
3,880,859
public static final long crc32 (byte [] data) { CRC32 crc32 = new CRC32 (); crc32.update (data); return crc32.getValue (); }
5,277,473
public long computeCRC32 () throws IOException { CRC32 compCRC32 = new CRC32 (); for (int i = 0; i < numDataRecords; i ++) { try { compCRC32.update (readRecord (i + 1)); } catch (ArrayIndexOutOfBoundsException e) { throw new IOException ("computeCRC32: Index out of bounds reading record " + (i + 1)); } catch (IOException e) { throw new IOException ("computeCRC32: error reading record " + (i + 1)); } } return compCRC32.getValue (); }
CRC32 File Checksum
Type-3 (WT3/4)
false
1,874,753
public static Object deleteElements (Object array, int firstElement, int nElements) { if (nElements == 0 || array == null) return array; int oldLength = Array.getLength (array); if (firstElement >= oldLength) return array; int n = oldLength - (firstElement + nElements); if (n < 0) n = 0; Object t = Array.newInstance (array.getClass ().getComponentType (), firstElement + n); if (firstElement > 0) System.arraycopy (array, 0, t, 0, firstElement); if (n > 0) System.arraycopy (array, firstElement + nElements, t, firstElement, n); return t; }
11,099,387
private static Object extendArray (Object a1) { int n = Array.getLength (a1); Object a2 = Array.newInstance (a1.getClass ().getComponentType (), n + ARRAY_SIZE_INCREMENT); System.arraycopy (a1, 0, a2, 0, n); return a2; }
Resize Array
Type-3 (WT3/4)
true
1,347,808
public static void main (String [] args) throws IOException { FileOutputStream f = new FileOutputStream ("test.zip"); CheckedOutputStream csum = new CheckedOutputStream (f, new Adler32 ()); ZipOutputStream zos = new ZipOutputStream (csum); BufferedOutputStream out = new BufferedOutputStream (zos); zos.setComment ("A test of Java Zipping"); for (String arg : args) { print ("Writing file " + arg); BufferedReader in = new BufferedReader (new FileReader (arg)); zos.putNextEntry (new ZipEntry (arg)); int c; while ((c = in.read ()) != - 1) out.write (c); in.close (); out.flush (); } out.close (); print ("Checksum: " + csum.getChecksum ().getValue ()); print ("Reading file"); FileInputStream fi = new FileInputStream ("test.zip"); CheckedInputStream csumi = new CheckedInputStream (fi, new Adler32 ()); ZipInputStream in2 = new ZipInputStream (csumi); BufferedInputStream bis = new BufferedInputStream (in2); ZipEntry ze; while ((ze = in2.getNextEntry ()) != null) { print ("Reading file " + ze); int x; while ((x = bis.read ()) != - 1) System.out.write (x); } if (args.length == 1) print ("Checksum: " + csumi.getChecksum ().getValue ()); bis.close (); ZipFile zf = new ZipFile ("test.zip"); Enumeration e = zf.entries (); while (e.hasMoreElements ()) { ZipEntry ze2 = (ZipEntry) e.nextElement (); print ("File: " + ze2); } }
12,002,709
private static void zipDirectory (ZipOutputStream zos, File files, String entry) throws IOException { if (files.isDirectory ()) { if (entry != null) { zos.putNextEntry (new ZipEntry (entry + "/")); entry = entry + "/"; } else { zos.putNextEntry (new ZipEntry ("/")); entry = "/"; } String [] names = files.list (); File [] files0 = files.listFiles (); for (int i = 0; i < files0.length; i ++) { zipDirectory (zos, files0 [i], entry + names [i]); } zos.closeEntry (); } else { if (entry != null) { zos.putNextEntry (new ZipEntry (entry)); } byte [] data = new byte [1000]; BufferedInputStream in = new BufferedInputStream (new FileInputStream (files), 1000); int count; while ((count = in.read (data, 0, 1000)) != - 1) { zos.write (data, 0, count); } zos.closeEntry (); in.close (); } }
Zip Files
Type-3 (WT3/4)
false
1,171,511
public void saveAttributes (Attributes a) throws IOException { String extension = fileResourceExtent.getUpperCaseExtension (); if ("XML".equals (extension)) { this.saveExtentsXML (a); } else { File file = new File (fileResourceExtent.getAbsoluteFilename ()); FileOutputStream fos = new FileOutputStream (file); ZipOutputStream zout = new ZipOutputStream (fos); zout.putNextEntry (new ZipEntry ("Extents")); DataOutputStream out = new DataOutputStream (zout); saveExtentsBinary (out, a); out.close (); fos.close (); } extension = fileResourceMatrix.getUpperCaseExtension (); if ("XML".equals (extension)) { } else { File file = new File (fileResourceMatrix.getAbsoluteFilename ()); FileOutputStream fos = new FileOutputStream (file); ZipOutputStream zout = new ZipOutputStream (fos); zout.putNextEntry (new ZipEntry ("Matrix")); DataOutputStream out = new DataOutputStream (zout); saveMatrixBinary (out, a); out.close (); fos.close (); } extension = fileResourceAttributes.getUpperCaseExtension (); if ("XML".equals (extension)) { this.saveAttributeXML (a); } else { File file = new File (fileResourceAttributes.getAbsoluteFilename ()); FileOutputStream fos = new FileOutputStream (file); ZipOutputStream zout = new ZipOutputStream (fos); zout.putNextEntry (new ZipEntry ("Attributes")); DataOutputStream out = new DataOutputStream (zout); saveAttributesBinary (out, a); out.close (); fos.close (); } String extent_tree_filename_stem = "extent_tree_"; for (int i = 0; i < a.getExtents ().size (); i ++) { try { saveXMLDocument (extent_tree_filename_stem + i + ".xml", a.getExtents ().at (i).getExtentXML ()); } catch (Exception e) { } } }
18,757,376
public static File zipFile (String pathToBeZipped, String pathZippedFile) throws IOException { if (pathZippedFile.indexOf (".zip") < 0) { pathZippedFile += ".zip"; } File fileASerZipado = new File (pathToBeZipped); byte [] buf = new byte [BUFFER_SIZE]; ZipOutputStream out = new ZipOutputStream (new FileOutputStream (pathZippedFile)); FileInputStream in = new FileInputStream (pathToBeZipped); out.putNextEntry (new ZipEntry (fileASerZipado.getName ())); int len; while ((len = in.read (buf)) > 0) { out.write (buf, 0, len); } out.closeEntry (); in.close (); out.close (); return new File (pathZippedFile); }
Zip Files
Type-3 (WT3/4)
false
1,588,099
private void packFile (final File file, final ZipOutputStream out, final String name, final FileFilter filter) throws IOException { if (filter != null && ! filter.accept (file)) return; if (file.isDirectory ()) { final File [] list = file.listFiles (); if (list == null) return; for (final File element : list) if (name == null) packFile (element, out, file.getName (), filter); else packFile (element, out, name + "/" + file.getName (), filter); } else { ZipEntry entry = null; if (name == null) entry = new ZipEntry (file.getName ()); else entry = new ZipEntry (name + "/" + file.getName ()); try { out.putNextEntry (entry); } catch (final ZipException e) { throw new C4JRuntimeException (format ("Could not pack file ‘%s’.", file.getPath ()), e); } InputStream fileIn = null; try { fileIn = new FileInputStream (file); use_filetools ().copyStream2Stream (fileIn, out); } finally { if (fileIn != null) fileIn.close (); } out.closeEntry (); } }
7,320,433
private void writeDynData (int time_s) throws IOException { this.zos.putNextEntry (new ZipEntry ("step." + time_s + ".bin")); this.outFile = new DataOutputStream (this.zos); this.buf.position (0); this.outFile.writeDouble (time_s); this.quad.writeDynData (null, this.buf); this.outFile.writeInt (this.buf.position ()); this.outFile.write (this.buf.array (), 0, this.buf.position ()); this.zos.closeEntry (); }
Zip Files
Type-3 (WT3/4)
false
16,301,512
public static void copy (File src, File dst) throws IOException { FileChannel inChannel; FileChannel outChannel; inChannel = new FileInputStream (src).getChannel (); outChannel = new FileOutputStream (dst).getChannel (); outChannel.transferFrom (inChannel, 0, inChannel.size ()); inChannel.close (); outChannel.close (); }
21,246,898
public static void main (String [] args) throws ParseException, FileNotFoundException, IOException { InputStream input = new BufferedInputStream (UpdateLanguages.class.getResourceAsStream ("definition_template")); Translator t = new Translator (input, "UTF8"); Node template = Translator.Start (); File langs = new File ("support/support/translate/languages"); for (File f : langs.listFiles ()) { if (f.getName ().endsWith (".lng")) { input = new BufferedInputStream (new FileInputStream (f)); try { Translator.ReInit (input, "UTF8"); } catch (java.lang.NullPointerException e) { new Translator (input, "UTF8"); } Node newFile = Translator.Start (); ArrayList < Addition > additions = new ArrayList < Addition > (); syncKeys (template, newFile, additions); ArrayList < String > fileLines = new ArrayList < String > (); Scanner scanner = new Scanner (new BufferedReader (new FileReader (f))); while (scanner.hasNextLine ()) { fileLines.add (scanner.nextLine ()); } int offset = 0; for (Addition a : additions) { System.out.println ("Key added " + a + " to " + f.getName ()); if (a.afterLine < 0 || a.afterLine >= fileLines.size ()) { fileLines.add (a.getAddition (0)); } else { fileLines.add (a.afterLine + (offset ++) + 1, a.getAddition (0)); } } f.delete (); Writer writer = new BufferedWriter (new FileWriter (f)); for (String s : fileLines) writer.write (s + "\n"); writer.close (); System.out.println ("Language " + f.getName () + " had " + additions.size () + " additions"); } } File defFile = new File (langs, "language.lng"); defFile.delete (); defFile.createNewFile (); InputStream copyStream = new BufferedInputStream (UpdateLanguages.class.getResourceAsStream ("definition_template")); OutputStream out = new BufferedOutputStream (new FileOutputStream (defFile)); int c = 0; while ((c = copyStream.read ()) >= 0) out.write (c); out.close (); System.out.println ("Languages updated."); }
Copy File
Type-3 (WT3/4)
true
12,440,169
public String openFileAsText (String resource) throws IOException { StringWriter wtr = new StringWriter (); InputStreamReader rdr = new InputStreamReader (openFile (resource)); try { IOUtils.copy (rdr, wtr); } finally { IOUtils.closeQuietly (rdr); } return wtr.toString (); }
17,456,566
public static boolean decodeFileToFile (String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream (new java.io.BufferedInputStream (new java.io.FileInputStream (infile)), Base64.DECODE); out = new java.io.BufferedOutputStream (new java.io.FileOutputStream (outfile)); byte [] buffer = new byte [65536]; int read = - 1; while ((read = in.read (buffer)) >= 0) { out.write (buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace (); } finally { try { in.close (); } catch (Exception exc) { } try { out.close (); } catch (Exception exc) { } } return success; }
Copy File
Type-3 (WT3/4)
true
6,008,880
protected void updateJava2ScriptProject (String prjFolder, String binRelative) { try { File cpFile = new File (prjFolder, ".classpath"); FileInputStream fis = new FileInputStream (cpFile); String classpath = J2SLaunchingUtil.readAFile (fis); if (classpath != null) { boolean needUpdate = false; if (classpath.indexOf ("ECLIPSE_SWT") == - 1 && classpath.indexOf ("SWT_LIBRARY") == - 1 && classpath.indexOf ("eclipse.swt") == - 1) { int idx = classpath.lastIndexOf ("<"); classpath = classpath.substring (0, idx) + "\t<classpathentry kind=\"var\" path=\"ECLIPSE_SWT\"/>\r\n" + classpath.substring (idx); needUpdate = true; } if (classpath.indexOf ("AJAX_SWT") == - 1 && classpath.indexOf ("ajaxswt.jar") == - 1) { int idx = classpath.lastIndexOf ("<"); classpath = classpath.substring (0, idx) + "\t<classpathentry sourcepath=\"AJAX_SWT_SRC\" kind=\"var\" path=\"AJAX_SWT\"/>\r\n" + classpath.substring (idx); needUpdate = true; } if (classpath.indexOf ("AJAX_RPC") == - 1 && classpath.indexOf ("ajaxrpc.jar") == - 1) { int idx = classpath.lastIndexOf ("<"); classpath = classpath.substring (0, idx) + "\t<classpathentry sourcepath=\"AJAX_RPC_SRC\" kind=\"var\" path=\"AJAX_RPC\"/>\r\n" + classpath.substring (idx); needUpdate = true; } if (classpath.indexOf ("AJAX_PIPE") == - 1 && classpath.indexOf ("ajaxpipe.jar") == - 1) { int idx = classpath.lastIndexOf ("<"); classpath = classpath.substring (0, idx) + "\t<classpathentry sourcepath=\"AJAX_PIPE_SRC\" kind=\"var\" path=\"AJAX_PIPE\"/>\r\n" + classpath.substring (idx); needUpdate = true; } if (needUpdate) { try { FileOutputStream fos = new FileOutputStream (cpFile); fos.write (classpath.getBytes ("utf-8")); fos.close (); } catch (FileNotFoundException e) { e.printStackTrace (); } catch (IOException e) { e.printStackTrace (); } } } File webinf = new File (prjFolder, "WEB-INF"); webinf.mkdir (); new File (webinf, "classes").mkdir (); File lib = new File (webinf, "lib"); lib.mkdir (); IPath newPath = null; URL starterURL = AjaxPlugin.getDefault ().getBundle ().getEntry (File.separator); String root = "."; try { root = Platform.asLocalURL (starterURL).getFile (); } catch (IOException e1) { e1.printStackTrace (); } newPath = Path.fromPortableString (root + "/ajaxrpc.jar"); File rpcFile = new File (newPath.toOSString ()); try { FileInputStream is = new FileInputStream (rpcFile); FileOutputStream os = new FileOutputStream (new File (lib, "ajaxrpc.jar")); byte [] buf = new byte [1024]; int read = - 1; while ((read = is.read (buf)) != - 1) { os.write (buf, 0, read); } os.close (); is.close (); } catch (IOException e1) { e1.printStackTrace (); } newPath = Path.fromPortableString (root + "/ajaxpipe.jar"); File pipeFile = new File (newPath.toOSString ()); try { FileInputStream is = new FileInputStream (pipeFile); FileOutputStream os = new FileOutputStream (new File (lib, "ajaxpipe.jar")); byte [] buf = new byte [1024]; int read = - 1; while ((read = is.read (buf)) != - 1) { os.write (buf, 0, read); } os.close (); is.close (); } catch (IOException e1) { e1.printStackTrace (); } StringBuffer buildxml = new StringBuffer (); buildxml.append ("<?xml version=\"1.0\"?>\r\n"); buildxml.append ("<project name=\"java2script.servlet.pack\" default=\"pack.war\" basedir=\".\">\r\n"); buildxml.append (" <description>Pack Java2Script Servlet Application</description>\r\n"); buildxml.append ("\r\n"); String name = new File (prjFolder).getName (); buildxml.append (" <property name=\"java2script.app.name\" value=\"" + name + "\"/>\r\n"); buildxml.append (" <property name=\"bin.folder\" value=\"${basedir}/../" + binRelative + "\"/>\r\n"); buildxml.append ("\r\n"); buildxml.append (" <target name=\"pack.war\" depends=\"pack.jar\">\r\n"); buildxml.append (" <tstamp>\r\n"); buildxml.append (" <format property=\"now\" pattern=\"yyyy-MM-dd-HH-mm-ss\"/>\r\n"); buildxml.append (" </tstamp>\r\n"); buildxml.append (" <delete file=\"${basedir}/../${java2script.app.name}.war\" quiet=\"true\"/>\r\n"); buildxml.append (" <zip destfile=\"${basedir}/../${java2script.app.name}.${now}.war\">\r\n"); buildxml.append (" <fileset dir=\"${basedir}/../\">\r\n"); buildxml.append (" <exclude name=\"src/**\"/>\r\n"); buildxml.append (" <exclude name=\"META-INF/**\"/>\r\n"); buildxml.append (" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.java\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.class\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append (" <exclude name=\".classpath\"/>\r\n"); buildxml.append (" <exclude name=\".project\"/>\r\n"); buildxml.append (" <exclude name=\".j2s\"/>\r\n"); buildxml.append (" <exclude name=\"web.xml\"/>\r\n"); buildxml.append (" <exclude name=\"build.xml\"/>\r\n"); buildxml.append (" <exclude name=\"build.properties\"/>\r\n"); buildxml.append (" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append (" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append (" </fileset>\r\n"); buildxml.append (" <fileset dir=\"${basedir}/..\">\r\n"); buildxml.append (" <include name=\"WEB-INF/**\"/>\r\n"); buildxml.append (" <exclude name=\"WEB-INF/build.xml\"/>\r\n"); buildxml.append (" </fileset>\r\n"); buildxml.append (" </zip>\r\n"); buildxml.append (" <copy file=\"${basedir}/../${java2script.app.name}.${now}.war\"\r\n"); buildxml.append (" tofile=\"${basedir}/../${java2script.app.name}.war\"/>\r\n"); buildxml.append (" </target>\r\n"); buildxml.append ("\r\n"); buildxml.append (" <target name=\"pack.jar\">\r\n"); buildxml.append (" <delete file=\"${basedir}/lib/${java2script.app.name}.jar\" quiet=\"true\"/>\r\n"); buildxml.append (" <zip destfile=\"${basedir}/lib/${java2script.app.name}.jar\">\r\n"); buildxml.append (" <fileset dir=\"${bin.folder}\">\r\n"); buildxml.append (" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.html\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.js\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.css\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.bmp\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.gif\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.png\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.jpg\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.jpeg\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append (" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append (" <exclude name=\".classpath\"/>\r\n"); buildxml.append (" <exclude name=\".project\"/>\r\n"); buildxml.append (" <exclude name=\".j2s\"/>\r\n"); buildxml.append (" <exclude name=\"web.xml\"/>\r\n"); buildxml.append (" <exclude name=\"build.xml\"/>\r\n"); buildxml.append (" <exclude name=\"build.properties\"/>\r\n"); buildxml.append (" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append (" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append (" </fileset>\r\n"); buildxml.append (" </zip>\r\n"); buildxml.append (" </target>\r\n"); buildxml.append ("\r\n"); starterURL = AjaxPlugin.getDefault ().getBundle ().getEntry (File.separator); root = "."; try { root = Platform.asLocalURL (starterURL).getFile (); } catch (IOException e1) { e1.printStackTrace (); } newPath = Path.fromPortableString (root); String ajaxPath = newPath.toOSString (); String key = "net.sf.j2s.ajax"; int idx = ajaxPath.lastIndexOf (key); if (idx != - 1) { ajaxPath = ajaxPath.substring (0, idx) + "net.sf.j2s.lib" + ajaxPath.substring (idx + key.length ()); } File libFile = new File (ajaxPath); String j2sRelativePath = FileUtil.toRelativePath (libFile.getAbsolutePath (), webinf.getAbsolutePath ()); if (j2sRelativePath.length () > 0 && ! j2sRelativePath.endsWith ("/")) { j2sRelativePath += "/"; } int slashIndex = j2sRelativePath.lastIndexOf ('/', j2sRelativePath.length () - 2); String pluginPath = j2sRelativePath.substring (0, slashIndex); String libPluginPath = j2sRelativePath.substring (slashIndex + 1, j2sRelativePath.length () - 1); buildxml.append (" <target name=\"pack.plugins.j2slib.war\">\r\n"); buildxml.append (" <delete file=\"${basedir}/../plugins.war\" quiet=\"true\"/>\r\n"); buildxml.append (" <zip destfile=\"${basedir}/../plugins.war\">\r\n"); buildxml.append (" <fileset dir=\"${basedir}/" + pluginPath + "/\">\r\n"); buildxml.append (" <include name=\"" + libPluginPath + "/**\"/>\r\n"); buildxml.append (" <exclude name=\"" + libPluginPath + "/library.jar\"/>\r\n"); buildxml.append (" <exclude name=\"" + libPluginPath + "/plugin.xml\"/>\r\n"); buildxml.append (" <exclude name=\"" + libPluginPath + "/META-INF/**\"/>\r\n"); buildxml.append (" </fileset>\r\n"); buildxml.append (" </zip>\r\n"); buildxml.append (" </target>\r\n"); buildxml.append ("\r\n"); buildxml.append ("</project>\r\n"); try { FileOutputStream fos = new FileOutputStream (new File (webinf, "build.xml")); fos.write (buildxml.toString ().getBytes ()); fos.close (); } catch (FileNotFoundException e) { e.printStackTrace (); } catch (IOException e) { e.printStackTrace (); } StringBuffer webxml = new StringBuffer (); webxml.append ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n"); webxml.append ("<!DOCTYPE web-app\r\n"); webxml.append (" PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\r\n"); webxml.append (" \"http://java.sun.com/dtd/web-app_2_3.dtd\">\r\n"); webxml.append ("<web-app>\r\n"); webxml.append (" <display-name>Java2Script</display-name>\r\n"); webxml.append (" <description>Java2Script application</description>\r\n"); webxml.append (genereateServlet ("simplerpc", "net.sf.j2s.ajax.SimpleRPCHttpServlet")); webxml.append (genereateServlet ("piperpc", "net.sf.j2s.ajax.CompoundPipeRPCHttpServlet")); webxml.append (" <servlet>\r\n"); webxml.append (" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append (" <servlet-class>net.sf.j2s.ajax.SimplePipeHttpServlet</servlet-class>\r\n"); webxml.append (" <init-param>\r\n"); webxml.append (" <param-name>simple.pipe.query.timeout</param-name>\r\n"); webxml.append (" <param-value>20000</param-value>\r\n"); webxml.append (" </init-param>\r\n"); webxml.append (" <init-param>\r\n"); webxml.append (" <param-name>simple.pipe.script.breakout</param-name>\r\n"); webxml.append (" <param-value>1200000</param-value>\r\n"); webxml.append (" </init-param>\r\n"); webxml.append (" <init-param>\r\n"); webxml.append (" <param-name>simple.pipe.max.items.per.query</param-name>\r\n"); webxml.append (" <param-value>60</param-value>\r\n"); webxml.append (" </init-param>\r\n"); webxml.append (" </servlet>\r\n"); webxml.append (" <servlet-mapping>\r\n"); webxml.append (" <servlet-name>simplerpc</servlet-name>\r\n"); webxml.append (" <url-pattern>/simplerpc</url-pattern>\r\n"); webxml.append (" </servlet-mapping>\r\n"); webxml.append (" <servlet-mapping>\r\n"); webxml.append (" <servlet-name>piperpc</servlet-name>\r\n"); webxml.append (" <url-pattern>/piperpc</url-pattern>\r\n"); webxml.append (" </servlet-mapping>\r\n"); webxml.append (" <servlet-mapping>\r\n"); webxml.append (" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append (" <url-pattern>/simplepipe</url-pattern>\r\n"); webxml.append (" </servlet-mapping>\r\n"); webxml.append ("</web-app>\r\n"); try { FileOutputStream fos = new FileOutputStream (new File (webinf, "web.xml")); fos.write (webxml.toString ().getBytes ()); fos.close (); } catch (FileNotFoundException e) { e.printStackTrace (); } catch (IOException e) { e.printStackTrace (); } } catch (FileNotFoundException e1) { e1.printStackTrace (); } }
21,057,438
public void run () { try { Socket socket = getSocket (); System.out.println ("opening socket to " + address + " on " + port); InputStream in = socket.getInputStream (); for (;;) { FileTransferHeader header = FileTransferHeader.readHeader (in); if (header == null) break; System.out.println ("header: " + header); String [] parts = header.getFilename ().getSegments (); String filename; if (parts.length > 0) filename = "dl-" + parts [parts.length - 1]; else filename = "dl-" + session.getScreenname (); System.out.println ("writing to file " + filename); long sum = 0; if (new File (filename).exists ()) { FileInputStream fis = new FileInputStream (filename); byte [] block = new byte [10]; for (int i = 0; i < block.length;) { int count = fis.read (block); if (count == - 1) break; i += count; } FileTransferChecksum summer = new FileTransferChecksum (); summer.update (block, 0, 10); sum = summer.getValue (); } FileChannel fileChannel = new FileOutputStream (filename).getChannel (); FileTransferHeader outHeader = new FileTransferHeader (header); outHeader.setHeaderType (FileTransferHeader.HEADERTYPE_ACK); outHeader.setIcbmMessageId (cookie); outHeader.setBytesReceived (0); outHeader.setReceivedChecksum (sum); OutputStream socketOut = socket.getOutputStream (); System.out.println ("sending header: " + outHeader); outHeader.write (socketOut); for (int i = 0; i < header.getFileSize ();) { long transferred = fileChannel.transferFrom (Channels.newChannel (in), 0, header.getFileSize () - i); System.out.println ("transferred " + transferred); if (transferred == - 1) return; i += transferred; } System.out.println ("finished transfer!"); fileChannel.close (); FileTransferHeader doneHeader = new FileTransferHeader (header); doneHeader.setHeaderType (FileTransferHeader.HEADERTYPE_RECEIVED); doneHeader.setFlags (doneHeader.getFlags () | FileTransferHeader.FLAG_DONE); doneHeader.setBytesReceived (doneHeader.getBytesReceived () + 1); doneHeader.setIcbmMessageId (cookie); doneHeader.setFilesLeft (doneHeader.getFilesLeft () - 1); doneHeader.write (socketOut); if (doneHeader.getFilesLeft () - 1 <= 0) { socket.close (); break; } } } catch (IOException e) { e.printStackTrace (); return; } }
Copy File
Type-3 (WT3/4)
true
1,093,295
private static void createZip (final File destinationFile, final List < File > files, final int cutFileNameIndex) throws IOException { final ZipOutputStream oStream = new ZipOutputStream (new FileOutputStream (destinationFile)); for (final File file : files) { final String fullFileName = file.getAbsolutePath (); final String cuttedFileName = fullFileName.substring (cutFileNameIndex); final String osIndependendFileName = cuttedFileName.replace (File.separatorChar, '/'); oStream.putNextEntry (new ZipEntry (osIndependendFileName)); final FileInputStream iStream = new FileInputStream (file); FileOperations.copy (iStream, oStream); oStream.closeEntry (); iStream.close (); } oStream.close (); }
6,195,313
protected void zipFile (InputStream in, ZipOutputStream zOut, String vPath, long lastModified, File fromArchive, int mode, ZipExtraField [] extra) throws IOException { if (entries.contains (vPath)) { if (duplicate.equals ("preserve")) { logWhenWriting (vPath + " already added, skipping", Project.MSG_INFO); return; } else if (duplicate.equals ("fail")) { throw new BuildException ("Duplicate file " + vPath + " was found and the duplicate " + "attribute is 'fail'."); } else { logWhenWriting ("duplicate file " + vPath + " found, adding.", Project.MSG_VERBOSE); } } else { logWhenWriting ("adding entry " + vPath, Project.MSG_VERBOSE); } entries.put (vPath, vPath); if (! skipWriting) { ZipEntry ze = new ZipEntry (vPath); ze.setTime (lastModified); ze.setMethod (doCompress ? ZipEntry.DEFLATED : ZipEntry.STORED); if (! zOut.isSeekable () && ! doCompress) { long size = 0; CRC32 cal = new CRC32 (); if (! in.markSupported ()) { ByteArrayOutputStream bos = new ByteArrayOutputStream (); byte [] buffer = new byte [BUFFER_SIZE]; int count = 0; do { size += count; cal.update (buffer, 0, count); bos.write (buffer, 0, count); count = in.read (buffer, 0, buffer.length); } while (count != - 1); in = new ByteArrayInputStream (bos.toByteArray ()); } else { in.mark (Integer.MAX_VALUE); byte [] buffer = new byte [BUFFER_SIZE]; int count = 0; do { size += count; cal.update (buffer, 0, count); count = in.read (buffer, 0, buffer.length); } while (count != - 1); in.reset (); } ze.setSize (size); ze.setCrc (cal.getValue ()); } ze.setUnixMode (mode); zOut.putNextEntry (ze); if (extra != null) { ze.setExtraFields (extra); } byte [] buffer = new byte [BUFFER_SIZE]; int count = 0; do { if (count != 0) { zOut.write (buffer, 0, count); } count = in.read (buffer, 0, buffer.length); } while (count != - 1); } addedFiles.addElement (vPath); }
Zip Files
Type-3 (WT3/4)
false
4,736,223
public int checksum () { if (checksumset) return checksum_value; CRC32 crc32 = new CRC32 (); crc32.update ((byte) channel); crc32.update ((byte) program); crc32.update ((byte) pitchbend_data1); crc32.update ((byte) pitchbend_data2); for (int i = 0; i < events.length; i ++) { crc32.update (events [i].getMessage ().getMessage ()); } if (controls != null) { int [] sorted = new int [controls.length]; for (int i = 0; i < controls.length; i ++) { sorted [i] = (controls [i] << 2) + controls_values [i]; } Arrays.sort (sorted); for (int i = 0; i < sorted.length; i ++) { crc32.update ((byte) (sorted [i] & 0xFF)); crc32.update ((byte) ((sorted [i] & 0xFF00)>> 2)); } } if (activenotes != null) { int [] sorted = new int [activenotes.length]; for (int i = 0; i < activenotes.length; i ++) { sorted [i] = (activenotes [i] << 2) + activenotes_velocity [i]; } Arrays.sort (sorted); for (int i = 0; i < sorted.length; i ++) { crc32.update ((byte) (sorted [i] & 0xFF)); crc32.update ((byte) ((sorted [i] & 0xFF00)>> 2)); } } checksumset = true; checksum_value = (int) crc32.getValue (); return checksum_value; }
20,943,990
private long getCRC (InputStream stream) { CRC32 crc = new CRC32 (); try { byte [] buffer = new byte [1024]; int length; while ((length = stream.read (buffer)) != - 1) { crc.update (buffer, 0, length); } } catch (IOException e) { IdeLog.logError (SyncingPlugin.getDefault (), "Error retrieving CRC", e); } return crc.getValue (); }
CRC32 File Checksum
Type-3 (WT3/4)
false
3,456,233
public ActionForward downloadDS (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (log.isDebugEnabled ()) { log.debug ("Entering 'datastore download' method"); } DocServiceManager mgr = (DocServiceManager) getBean ("docServiceManager"); List < Document > docsInDS = mgr.listDocuments (); response.setContentType ("application/zip"); response.setHeader ("Content-Disposition", "attachment; filename=\"" + "safe-ds.zip\""); ZipOutputStream zipOut = new ZipOutputStream (response.getOutputStream ()); try { CRC32 crc = new CRC32 (); for (Document doc : docsInDS) { String fileName = doc.getDocumentID (); if (! fileName.endsWith (".xml")) { fileName += ".xml"; } byte [] docData = mgr.getDocXML (doc.getDocumentID ()); ZipEntry entry = new ZipEntry (fileName); entry.setSize (docData.length); crc.reset (); crc.update (docData); entry.setCrc (crc.getValue ()); zipOut.putNextEntry (entry); try { zipOut.write (docData); } finally { zipOut.closeEntry (); } } } finally { zipOut.close (); } return null; }
8,347,589
protected void commonInit (String displayName, IDataSource [] dataSource, Unit unit) { this.displayName = displayName; CRC32 crc = new CRC32 (); crc.update (canonicalName.getBytes ()); this.hashedId = crc.getValue (); this.unit = unit; this.cursors = new long [this.dataSources.length]; getStreamManager ().addStream (this); }
CRC32 File Checksum
Type-3 (WT3/4)
false
1,086,128
public void streamDataToZip (VolumeTimeSeries vol, ZipOutputStream zout) throws Exception { ZipEntry entry = new ZipEntry (vol.getId () + ".dat"); zout.putNextEntry (entry); if (vol instanceof FloatVolumeTimeSeries) { streamData (((FloatVolumeTimeSeries) vol).getData (), zout); } else if (vol instanceof RGBVolumeTimeSeries) { streamData (((RGBVolumeTimeSeries) vol).getARGBData (), zout); } else if (vol instanceof BinaryVolumeTimeSeries) { streamData (((BinaryVolumeTimeSeries) vol).getBinaryData (), zout); } }
8,504,294
private void storeProcessList (Date date, List < ProcessList > processListes, boolean doNotOverrideFile) { final int BUFFER = 2048; String filename = BASE_FILES_PATH + serverGroup + "/processlist/" + sdf.format (date) + ".zip"; if (doNotOverrideFile && new File (filename).exists ()) return; try { FileOutputStream dest = new FileOutputStream (filename); ZipOutputStream out = new ZipOutputStream (new BufferedOutputStream (dest)); byte data [] = new byte [BUFFER]; for (ProcessList processList : processListes) { ByteArrayInputStream fi = new ByteArrayInputStream (buildProcessListText (processList).getBytes ()); BufferedInputStream origin = new BufferedInputStream (fi, BUFFER); ZipEntry entry = new ZipEntry (processList.getMysqlServer ().getName () + ".txt"); out.putNextEntry (entry); int count; while ((count = origin.read (data, 0, BUFFER)) != - 1) { out.write (data, 0, count); } origin.close (); } out.close (); } catch (Exception e) { e.printStackTrace (); } }
Zip Files
Type-3 (WT3/4)
false
621,362
private static void readAndRewrite (File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream (new BufferedInputStream (new FileInputStream (inFile))); DcmParser dcmParser = DcmParserFactory.getInstance ().newDcmParser (iis); Dataset ds = DcmObjectFactory.getInstance ().newDataset (); dcmParser.setDcmHandler (ds.getDcmHandler ()); dcmParser.parseDcmFile (null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader (ds, iis, dcmParser.getDcmDecodeParam ().byteOrder, dcmParser.getReadVR ()); System.out.println ("reading " + inFile + "..."); pdReader.readPixelData (false); ImageOutputStream out = ImageIO.createImageOutputStream (new BufferedOutputStream (new FileOutputStream (outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset (out, dcmEncParam); ds.writeHeader (out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR (), dcmParser.getReadLength ()); System.out.println ("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter (pdReader.getPixelDataArray (), false, ds, out, dcmParser.getDcmDecodeParam ().byteOrder, dcmParser.getReadVR ()); pdWriter.writePixelData (); out.flush (); out.close (); System.out.println ("done!"); }
18,809,148
public static void moveOutputAsmFile (File inputLocation, File outputLocation) throws Exception { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream (inputLocation); outputStream = new FileOutputStream (outputLocation); byte buffer [] = new byte [1024]; while (inputStream.available () > 0) { int read = inputStream.read (buffer); outputStream.write (buffer, 0, read); } inputLocation.delete (); } finally { IOUtil.closeAndIgnoreErrors (inputStream); IOUtil.closeAndIgnoreErrors (outputStream); } }
Copy File
Type-3 (WT3/4)
true
15,570,948
private String generate (String value) throws Exception { String resStr = null; try { MessageDigest md = MessageDigest.getInstance ("MD5"); md.update (value.getBytes ("utf-8"), 0, value.length ()); byte [] result = md.digest (); resStr = FTGenerate.convertToHex (result); md.reset (); } catch (NoSuchAlgorithmException nae) { this.getLog ().severe ("Hash no funcionando"); nae.printStackTrace (); throw new Exception ("Hash no funcionando"); } catch (UnsupportedEncodingException ee) { this.getLog ().severe ("Encoding no funcionando"); ee.printStackTrace (); throw new Exception ("Encoding no funcionando"); } return resStr; }
23,034,378
private JeeObserverServerContext (JeeObserverServerContextProperties properties) throws DatabaseException, ServerException { super (); try { final MessageDigest md5 = MessageDigest.getInstance ("MD5"); md5.update (("JE" + System.currentTimeMillis ()).getBytes ()); final BigInteger hash = new BigInteger (1, md5.digest ()); this.sessionId = hash.toString (16).toUpperCase (); } catch (final Exception e) { this.sessionId = "JE" + System.currentTimeMillis (); JeeObserverServerContext.logger.log (Level.WARNING, "JeeObserver Server session ID MD5 error: {0}", this.sessionId); JeeObserverServerContext.logger.log (Level.FINEST, e.getMessage (), e); } try { @SuppressWarnings("unchecked") final Class < DatabaseHandler > databaseHandlerClass = (Class < DatabaseHandler >) Class.forName (properties.getDatabaseHandler ()); final Constructor < DatabaseHandler > handlerConstructor = databaseHandlerClass.getConstructor (new Class < ? > [] {String.class, String.class, String.class, String.class, String.class, Integer.class}); this.databaseHandler = handlerConstructor.newInstance (new Object [] {properties.getDatabaseDriver (), properties.getDatabaseUrl (), properties.getDatabaseUser (), properties.getDatabasePassword (), properties.getDatabaseSchema (), new Integer (properties.getDatabaseConnectionPoolSize ())}); } catch (final Exception e) { throw new ServerException ("Database handler loading exception.", e); } this.databaseHandlerTimer = new Timer (JeeObserverServerContext.DATABASE_HANDLER_TASK_NAME, true); this.server = new JeeObserverServer (properties.getServerPort ()); this.enabled = true; this.properties = properties; this.startTimestamp = new Date (); try { this.ip = InetAddress.getLocalHost ().getHostAddress (); } catch (final UnknownHostException e) { JeeObserverServerContext.logger.log (Level.SEVERE, e.getMessage (), e); } this.operatingSystemName = System.getProperty ("os.name"); this.operatingSystemVersion = System.getProperty ("os.version"); this.operatingSystemArchitecture = System.getProperty ("os.arch"); this.javaVersion = System.getProperty ("java.version"); this.javaVendor = System.getProperty ("java.vendor"); }
Secure Hash
Type-3 (WT3/4)
true
2,767,060
void process (SourceMetricsDataBuilder data) { data.set (SourceMetricsData.SIZE, size); Set < String > operators = new HashSet < String > (); int standAlone = 0; for (SourceTokens.Token token : sourceTokens) { if (token.isEOF ()) { SourceTokens.Token prev = token.previousToken (); if (null == prev) { data.set (SourceMetricsData.LINES, 0); } else if (prev.getTokenText ().endsWith ("\r") || prev.getTokenText ().endsWith ("\n")) { data.set (SourceMetricsData.LINES, token.getLineNumber () - 1L); } else { data.set (SourceMetricsData.LINES, token.getLineNumber ()); } break; } if (token.isLineComment ()) { if (isFirstOnLine (token)) { data.bump (SourceMetricsData.LINE_COMMENT); if (endOfMultipleLineComments (token)) { bumpCommentLocationMetrics (data, token); } } } else if (token.isBlockComment ()) { processMultilineComment (data, token, SourceMetricsData.BLOCK_COMMENT); } else if (token.isJavadocComment ()) { processMultilineComment (data, token, SourceMetricsData.DOC_COMMENT); } else if (token.isWhitespace ()) { int lineCount = token.getNewlineCount (); SourceTokens.Token prev = token.previousToken (); if ((null != prev) && prev.isLineComment ()) { lineCount ++; } if (1 < lineCount) { data.bump (SourceMetricsData.WHITESPACE, lineCount - 1L); } } else if (";".equals (token.getTokenText ())) { data.bump (SourceMetricsData.LOGICAL_LINES); } else if (- 1 != "(){}".indexOf (token.getTokenText ())) { if (isAloneOnLine (token)) { standAlone ++; } } if (token.isLiteral ()) { data.bump (SourceMetricsData.OPERANDS); } else if (! token.isComment () && ! token.isWhitespace ()) { data.bump (SourceMetricsData.OPERATORS); operators.add (token.getTokenText ()); } } data.set (SourceMetricsData.UNIQUE_OPERATORS, operators.size ()); data.set (SourceMetricsData.LOC, data.get (SourceMetricsData.LINES) - data.get (SourceMetricsData.WHITESPACE) - data.get (SourceMetricsData.LINE_COMMENT) - data.get (SourceMetricsData.BLOCK_COMMENT) - data.get (SourceMetricsData.DOC_COMMENT)); data.set (SourceMetricsData.ELOC, data.get (SourceMetricsData.LOC) - standAlone); data.set (SourceMetricsData.COMMENTS, data.get (SourceMetricsData.LINE_COMMENT) + data.get (SourceMetricsData.BLOCK_COMMENT) + data.get (SourceMetricsData.DOC_COMMENT)); String chunk = new String (sourceTokens.getChunk ()); byte [] bytes = chunk.getBytes (); CRC32 crc = new CRC32 (); crc.update (bytes); data.set (SourceMetricsData.CRC, Double.longBitsToDouble (crc.getValue ())); }
12,611,963
public static String generateEmailHash (String email) { email = email.trim ().toLowerCase (); CRC32 crc = new CRC32 (); crc.update (email.getBytes ()); String md5 = generateMD5 (email); return crc.getValue () + "_" + md5; }
CRC32 File Checksum
Type-3 (WT3/4)
false
225,907
private int CalculateTreeWidth (int myGraph [] [], int SolutionVector [], int zaehler) { int [] [] TreeDecompositionGraph; int [] [] DecompositionedMatrix; int [] ConnectedNodes; int [] NextSolutionVector; int TreeWidth; int NumVerticesOfMyGraph; int DeeperTreeWidth; int LineIndex; NumVerticesOfMyGraph = myGraph.length; DecompositionedMatrix = new int [NumVerticesOfMyGraph - 1] [NumVerticesOfMyGraph - 1]; ConnectedNodes = new int [NumVerticesOfMyGraph]; TreeWidth = 0; DeeperTreeWidth = 0; LineIndex = 0; NextSolutionVector = new int [SolutionVector.length - 1]; for (int i = 1; i < NumVerticesOfMyGraph; i ++) { if (SolutionVector [0] == myGraph [i] [0]) { LineIndex = i; } } for (int j = 1; j < NumVerticesOfMyGraph; j ++) { if (myGraph [LineIndex] [j] == 1) { ConnectedNodes [TreeWidth] = myGraph [0] [j]; TreeWidth ++; } } for (int i = 0; i < NumVerticesOfMyGraph; i ++) { if (i < LineIndex) { for (int j = 0; j < NumVerticesOfMyGraph; j ++) { if (j < LineIndex) { DecompositionedMatrix [i] [j] = myGraph [i] [j]; } else if (j > LineIndex) { DecompositionedMatrix [i] [j - 1] = myGraph [i] [j]; } } } else if (i > LineIndex) { for (int j = 0; j < NumVerticesOfMyGraph; j ++) { if (j < LineIndex) { DecompositionedMatrix [i - 1] [j] = myGraph [i] [j]; } else if (j > LineIndex) { DecompositionedMatrix [i - 1] [j - 1] = myGraph [i] [j]; } } } } for (int k = 0; k < TreeWidth; k ++) { for (int i = 0; i < DecompositionedMatrix.length; i ++) { if (DecompositionedMatrix [i] [0] == ConnectedNodes [k]) { for (int l = 0; l < TreeWidth; l ++) { for (int j = 0; j < DecompositionedMatrix.length; j ++) { if (DecompositionedMatrix [0] [j] == ConnectedNodes [l]) { DecompositionedMatrix [i] [j] = 1; } } } } } } for (int i = 1; i < DecompositionedMatrix.length; i ++) { DecompositionedMatrix [i] [i] = 0; for (int j = 1; j < DecompositionedMatrix.length; j ++) { DecompositionedMatrix [i] [j] = DecompositionedMatrix [j] [i]; } } for (int l = 1; l < SolutionVector.length; l ++) { NextSolutionVector [l - 1] = SolutionVector [l]; } if (NextSolutionVector.length > 1) { DeeperTreeWidth = CalculateTreeWidth (DecompositionedMatrix, NextSolutionVector, zaehler + 1); if (TreeWidth < DeeperTreeWidth) { TreeWidth = DeeperTreeWidth; } } return TreeWidth; }
19,332,616
public double [] [] getFSDistances () { int size = getMatrix ().size (); double [] [] distances; try { distances = new double [size] [size]; for (int i = 0; i < size; i ++) { double distii = get (i, i); for (int j = i; j < size; j ++) { distances [i] [j] = Math.sqrt (distii + get (j, j) - 2 * get (i, j)); distances [j] [i] = distances [i] [j]; } } } catch (OutOfMemoryError e) { distances = null; System.err.println ("Not enough memory for distances!"); System.gc (); } return distances; }
Transpose a Matrix.
Type-3 (WT3/4)
true
3,076,854
public static byte [] SHA1 (String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance ("SHA-1"); byte [] sha1hash = new byte [40]; md.update (text.getBytes ("iso-8859-1"), 0, text.length ()); sha1hash = md.digest (); return sha1hash; }
6,176,440
public static String encrypt (String password, String algorithm, byte [] salt) { StringBuffer buffer = new StringBuffer (); MessageDigest digest = null; int size = 0; if ("CRYPT".equalsIgnoreCase (algorithm)) { throw new InternalError ("Not implemented"); } else if ("SHA".equalsIgnoreCase (algorithm) || "SSHA".equalsIgnoreCase (algorithm)) { size = 20; if (salt != null && salt.length > 0) { buffer.append ("{SSHA}"); } else { buffer.append ("{SHA}"); } try { digest = MessageDigest.getInstance ("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError ("Invalid algorithm"); } } else if ("MD5".equalsIgnoreCase (algorithm) || "SMD5".equalsIgnoreCase (algorithm)) { size = 16; if (salt != null && salt.length > 0) { buffer.append ("{SMD5}"); } else { buffer.append ("{MD5}"); } try { digest = MessageDigest.getInstance ("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError ("Invalid algorithm"); } } int outSize = size; digest.reset (); digest.update (password.getBytes ()); if (salt != null && salt.length > 0) { digest.update (salt); outSize += salt.length; } byte [] out = new byte [outSize]; System.arraycopy (digest.digest (), 0, out, 0, size); if (salt != null && salt.length > 0) { System.arraycopy (salt, 0, out, size, salt.length); } buffer.append (Base64.encode (out)); return buffer.toString (); }
Secure Hash
Type-3 (WT3/4)
true
951,388
public static void zipFile (String file, String entry) throws IOException { FileInputStream in = new FileInputStream (file); ZipOutputStream out = new ZipOutputStream (new FileOutputStream (file + ".zip")); out.putNextEntry (new ZipEntry (entry)); byte [] buffer = new byte [4096]; int bytes_read; while ((bytes_read = in.read (buffer)) != - 1) out.write (buffer, 0, bytes_read); in.close (); out.closeEntry (); out.close (); File fin = new File (file); fin.delete (); }
11,915,880
private static void cut () { File inputFile = new File (inputFileName); BufferedReader in = null; try { in = new BufferedReader (new InputStreamReader (new FileInputStream (inputFile), inputCharSet)); } catch (FileNotFoundException e) { System.err.print ("Invalid File Name!"); System.err.flush (); System.exit (1); } catch (UnsupportedEncodingException e) { System.err.print ("Invalid Char Set Name!"); System.err.flush (); System.exit (1); } switch (cutMode) { case charMode : { int outputFileIndex = 1; char [] readBuf = new char [charPerFile]; while (true) { int readCount = 0; try { readCount = in.read (readBuf); } catch (IOException e) { System.err.println ("Read IO Error!"); System.err.flush (); System.exit (1); } if (- 1 == readCount) break; else { try { int ppos = inputFileName.lastIndexOf ("."); String prefixInputFileName = inputFileName.substring (0, ppos); String postfixInputFileName = "html"; DecimalFormat outputFileIndexFormat = new DecimalFormat ("0000"); File outputFile = new File (prefixInputFileName + "-" + outputFileIndexFormat.format (outputFileIndex) + "." + postfixInputFileName); BufferedWriter out = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (outputFile), outputCharSet)); out.write (readBuf, 0, readCount); out.flush (); out.close (); outputFileIndex ++; } catch (IOException e) { System.err.println ("Write IO Error!"); System.err.flush (); System.exit (1); } } } break; } case lineMode : { boolean isFileEnd = false; int outputFileIndex = 1; while (! isFileEnd) { try { int ppos = inputFileName.lastIndexOf ("."); String prefixInputFileName = inputFileName.substring (0, ppos); String postfixInputFileName = inputFileName.substring (ppos + 1); DecimalFormat outputFileIndexFormat = new DecimalFormat ("0000"); File outputFile = new File (prefixInputFileName + outputFileIndexFormat.format (outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream (new FileOutputStream (outputFile), false, outputCharSet); int p = 0; while (p < linePerFile) { String line = in.readLine (); if (null == line) { isFileEnd = true; break; } out.println (line); ++ p; } out.flush (); out.close (); } catch (IOException e) { System.err.println ("Write IO Error!"); System.err.flush (); System.exit (1); } ++ outputFileIndex; } break; } case htmlMode : { boolean isFileEnd = false; int outputFileIndex = 1; int ppos = inputFileName.lastIndexOf ("."); String prefixInputFileName = inputFileName.substring (0, ppos); String postfixInputFileName = "html"; DecimalFormat df = new DecimalFormat ("0000"); while (! isFileEnd) { try { File outputFile = new File (prefixInputFileName + "-" + df.format (outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream (new FileOutputStream (outputFile), false, outputCharSet); out.println ("<html><head><title>" + prefixInputFileName + "-" + df.format (outputFileIndex) + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><div id=\"content\">"); int p = 0; while (p < pPerFile) { String line = in.readLine (); if (null == line) { isFileEnd = true; break; } if (line.length () > 0) out.println ("<p>" + line + "</p>"); ++ p; } out.println ("</div><a href=\"" + prefixInputFileName + "-" + df.format (outputFileIndex + 1) + "." + postfixInputFileName + "\">NEXT</a></body></html>"); out.flush (); out.close (); } catch (IOException e) { System.err.println ("Write IO Error!"); System.err.flush (); System.exit (1); } ++ outputFileIndex; } try { File indexFile = new File ("index.html"); PrintStream out = new PrintStream (new FileOutputStream (indexFile), false, outputCharSet); out.println ("<html><head><title>" + "Index" + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><h2>" + htmlTitle + "</h2><div id=\"content\"><ul>"); for (int i = 1; i < outputFileIndex; i ++) { out.println ("<li><a href=\"" + prefixInputFileName + "-" + df.format (i) + "." + postfixInputFileName + "\">" + df.format (i) + "</a></li>"); } out.println ("</ul></body></html>"); out.flush (); out.close (); } catch (IOException e) { System.err.println ("Write IO Error!"); System.err.flush (); System.exit (1); } break; }} }
Copy File
Type-3 (WT3/4)
true
2,049,240
private void writeInfos () throws IOException { zos.putNextEntry (new ZipEntry ("info.bin")); outFile = new DataOutputStream (zos); outFile.writeInt (VERSION); outFile.writeInt (MINORVERSION); outFile.writeDouble (intervall_s); zos.closeEntry (); }
4,078,781
public static boolean zipFiles (File output, File...input) { if (output == null || input == null || input.length == 0) { return false; } if (! deleteFile (output)) { return false; } byte [] buf = new byte [1024]; ZipOutputStream out = null; try { out = new ZipOutputStream (new FileOutputStream (output)); for (int i = 0; i < input.length; i ++) { FileInputStream in = null; try { in = new FileInputStream (input [i]); out.putNextEntry (new ZipEntry (input [i].getName ())); int len; while ((len = in.read (buf)) > 0) { out.write (buf, 0, len); } out.closeEntry (); } finally { FileUtil.close (in); } } } catch (IOException ex) { ShowDownLog.getInstance ().logError (ex.getLocalizedMessage (), ex); return false; } finally { FileUtil.close (out); } return true; }
Zip Files
Type-3 (WT3/4)
false
12,821,749
public static void fastBackup (File file) { FileChannel in = null; FileChannel out = null; FileInputStream fin = null; FileOutputStream fout = null; try { in = (fin = new FileInputStream (file)).getChannel (); out = (fout = new FileOutputStream (file.getAbsolutePath () + ".bak")).getChannel (); in.transferTo (0, in.size (), out); } catch (IOException e) { Logging.getErrorLog ().reportError ("Fast backup failure (" + file.getAbsolutePath () + "): " + e.getMessage ()); } finally { if (fin != null) { try { fin.close (); } catch (IOException e) { Logging.getErrorLog ().reportException ("Failed to close file input stream", e); } } if (fout != null) { try { fout.close (); } catch (IOException e) { Logging.getErrorLog ().reportException ("Failed to close file output stream", e); } } if (in != null) { try { in.close (); } catch (IOException e) { Logging.getErrorLog ().reportException ("Failed to close file channel", e); } } if (out != null) { try { out.close (); } catch (IOException e) { Logging.getErrorLog ().reportException ("Failed to close file channel", e); } } } }
18,034,383
public static File copy (String inFileName, String outFileName) throws IOException { File inputFile = new File (inFileName); File outputFile = new File (outFileName); FileReader in = new FileReader (inputFile); FileWriter out = new FileWriter (outputFile); int c; while ((c = in.read ()) != - 1) out.write (c); in.close (); out.close (); return outputFile; }
Copy File
Type-3 (WT3/4)
true
891,055
@Override public void run () { final Random r = new Random (); final Counter counter = new Counter ("TRANSMIT", plotter); counter.start (); try { final DataOutputStream dos = new DataOutputStream (new BufferedOutputStream (s.getOutputStream ())); while (! Thread.interrupted ()) { if (! running.get ()) { Thread.sleep (1000); continue; } final int packetSize = r.nextInt (8192) + 2048; final byte [] packet = new byte [packetSize]; r.nextBytes (packet); final CRC32 crc = new CRC32 (); crc.update (packet); dos.writeInt (packetSize); counter.addBytes (INTEGER_BYTES); dos.write (packet); counter.addBytes (packetSize); dos.writeLong (crc.getValue ()); counter.addBytes (CRC_BYTES); dos.flush (); } } catch (InterruptedException e) { System.out.println ("Transmitter thread interrupted!"); } catch (Exception e) { System.err.println ("Unexpected error in transmitter thread: " + e.getMessage ()); } finally { abortLatch.countDown (); counter.interrupt (); } }
15,357,608
private void cRC32Test (byte [] values, long expected) { CRC32 crc = new CRC32 (); crc.update (values); assertEquals (crc.getValue (), expected); crc.reset (); for (int i = 0; i < values.length; i ++) { crc.update (values [i]); } assertEquals (crc.getValue (), expected); }
CRC32 File Checksum
Type-3 (WT3/4)
false
742,784
public boolean create () { DirectoryManager d = new DirectoryManager (dirSource); Vector < String > filenames = new Vector < String > (); d.getAllMyFileNames (filenames, true, false); byte [] buf = new byte [1024]; try { ZipOutputStream out = null; BufferedOutputStream outStream = null; SevenZip.Compression.LZMA.Encoder encoder = null; boolean eos = false; if (! useLZMA) { out = new ZipOutputStream (new FileOutputStream (zip)); } else { outStream = new BufferedOutputStream (new FileOutputStream (new File (zip))); encoder = new SevenZip.Compression.LZMA.Encoder (); encoder.SetAlgorithm (2); encoder.SetDictionarySize (1 << 21); encoder.SeNumFastBytes (128); encoder.SetMatchFinder (1); encoder.SetLcLpPb (3, 0, 2); encoder.SetEndMarkerMode (eos); encoder.WriteCoderProperties (outStream); } for (int i = 0; i < filenames.size (); i ++) { myMaster.writeOnLog ("processing : " + filenames.elementAt (i) + " to create " + filenames.elementAt (i).replace (d.getDirectory (), "")); if (! useLZMA) { FileInputStream in = new FileInputStream (filenames.elementAt (i)); out.putNextEntry (new ZipEntry (filenames.elementAt (i).replace (d.getDirectory (), ""))); int len; while ((len = in.read (buf)) > 0) { out.write (buf, 0, len); } out.closeEntry (); in.close (); } else { File inFile = new File (filenames.elementAt (i)); BufferedInputStream inStream = new BufferedInputStream (new FileInputStream (new File (filenames.elementAt (i)))); long fileSize; if (eos) fileSize = - 1; else fileSize = inFile.length (); for (int j = 0; j < 8; j ++) outStream.write ((int) (fileSize>>> (8 * j)) & 0xFF); encoder.Code (inStream, outStream, - 1, - 1, null); inStream.close (); } myMaster.setProgress (1); } if (! useLZMA) out.close (); else { outStream.flush (); outStream.close (); } } catch (IOException e) { myMaster.writeOnLog ("error while creating zip file : " + e); return false; } return true; }
1,312,065
public void addFile (ZipOutputStream out, String filename) { try { byte [] buf = new byte [1024]; String filePath = projHandler.getProjectPath () + File.separator + filename; File file = new File (filePath); if (file.exists ()) { FileInputStream fis = new FileInputStream (filePath); out.putNextEntry (new ZipEntry (filename)); int len; while ((len = fis.read (buf)) > 0) { out.write (buf, 0, len); } out.closeEntry (); fis.close (); } } catch (Exception e) { e.printStackTrace (); } }
Zip Files
Type-3 (WT3/4)
false
418,257
public BufferedWriter createOutputStream (String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char [] buf = new char [k_blockSize]; File ofp = new File (outFile); ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (ofp)); zos.setMethod (ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter (zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter (osw); ZipEntry zot = null; File ifp = new File (inFile); ZipInputStream zis = new ZipInputStream (new FileInputStream (ifp)); InputStreamReader isr = new InputStreamReader (zis, "ISO-8859-1"); BufferedReader br = new BufferedReader (isr); ZipEntry zit = null; while ((zit = zis.getNextEntry ()) != null) { if (zit.getName ().equals ("content.xml")) { continue; } zot = new ZipEntry (zit.getName ()); zos.putNextEntry (zot); while ((byteCount = br.read (buf, 0, k_blockSize)) >= 0) bw.write (buf, 0, byteCount); bw.flush (); zos.closeEntry (); } zos.putNextEntry (new ZipEntry ("content.xml")); bw.flush (); osw = new OutputStreamWriter (zos, "UTF8"); bw = new BufferedWriter (osw); return bw; }
1,467,288
private static String addFile (File ff, ZipOutputStream zipOutPic, String filename) throws Exception { FileInputStream file = new FileInputStream (ff); String ext = getFileExt (ff.getName ()); if (! ext.equals ("")) { ext = "." + ext; } int randomString = ((int) (Math.random () * 1000000)); while (randomList.contains (randomString)) { randomString = ((int) (Math.random () * 1000000)); } randomList.add (randomString); String newFilename = filename == null ? randomString + ext : filename; ZipEntry entryPic = new ZipEntry (newFilename); zipOutPic.putNextEntry (entryPic); byte [] buf = new byte [1024]; int len; while ((len = file.read (buf)) > 0) { zipOutPic.write (buf, 0, len); } zipOutPic.closeEntry (); return newFilename; }
Zip Files
Type-3 (WT3/4)
false
778,875
public BufferedWriter createOutputStream (String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char [] buf = new char [k_blockSize]; File ofp = new File (outFile); ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (ofp)); zos.setMethod (ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter (zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter (osw); ZipEntry zot = null; File ifp = new File (inFile); ZipInputStream zis = new ZipInputStream (new FileInputStream (ifp)); InputStreamReader isr = new InputStreamReader (zis, "ISO-8859-1"); BufferedReader br = new BufferedReader (isr); ZipEntry zit = null; while ((zit = zis.getNextEntry ()) != null) { if (zit.getName ().equals ("content.xml")) { continue; } zot = new ZipEntry (zit.getName ()); zos.putNextEntry (zot); while ((byteCount = br.read (buf, 0, k_blockSize)) >= 0) bw.write (buf, 0, byteCount); bw.flush (); zos.closeEntry (); } zos.putNextEntry (new ZipEntry ("content.xml")); bw.flush (); osw = new OutputStreamWriter (zos, "UTF8"); bw = new BufferedWriter (osw); return bw; }
20,967,084
private void writeIntoZip (ZipOutputStream output, String name, InputStream input) throws Exception { output.putNextEntry (new ZipEntry (name)); int size = 0; byte [] buffer = new byte [1024]; while ((size = input.read (buffer, 0, buffer.length)) > 0) { output.write (buffer, 0, size); } output.closeEntry (); input.close (); }
Zip Files
Type-3 (WT3/4)
false
11,322,590
private static void addFileToZip (String path, String srcFile, ZipOutputStream zip) throws Exception { File folder = new File (srcFile); if (folder.isDirectory ()) { addFolderToZip (path, srcFile, zip); } else { byte [] buf = new byte [1024]; int len; FileInputStream in = new FileInputStream (srcFile); zip.putNextEntry (new ZipEntry (path + "\\" + folder.getName ())); while ((len = in.read (buf)) > 0) { zip.write (buf, 0, len); } } }
14,138,100
public static void insertModuleinfo (ZipOutputStream dest, ModuleInfo info) throws IOException { ZipEntry zse = new ZipEntry (ModuleInfo.MODULEINFO_RAK); dest.putNextEntry (zse); info.write (dest); dest.flush (); }
Zip Files
Type-3 (WT3/4)
true
1,446,727
private void backupDiskFile (ZipOutputStream out, String fileName, DiskFile file) throws SQLException, IOException { Database db = session.getDatabase (); fileName = FileUtils.getFileName (fileName); out.putNextEntry (new ZipEntry (fileName)); int pos = - 1; int max = file.getReadCount (); while (true) { pos = file.copyDirect (pos, out); if (pos < 0) { break; } db.setProgress (DatabaseEventListener.STATE_BACKUP_FILE, fileName, pos, max); } out.closeEntry (); }
10,062,068
private void addToArchive (ZipOutputStream stream, File file, FileFilter filter, String entryName, int recurseDepth) throws IOException { if (file.exists ()) { if (file.isDirectory ()) { File [] ls = file.listFiles (filter); if (ls.length == 0) { if (archiveEntryList_.contains (entryName + "/")) { System.err.println (" warning: duplicate entry: " + entryName + "/" + ". Skipping."); } else { System.out.println (" " + file); ZipEntry newEntry = new ZipEntry (entryName + "/"); stream.putNextEntry (newEntry); stream.closeEntry (); archiveEntryList_.add (entryName + "/"); } } for (int i = 0; i < ls.length; i ++) { String ename = ls [i].getAbsolutePath (); ename = entryName + ename.substring (file.getAbsolutePath ().length ()); ename = convertToGenericPath (ename); if (ename.startsWith ("/")) ename = ename.substring (1); if (recurseDepth > 0) addToArchive (stream, ls [i], filter, ename, recurseDepth - 1); } } else if (archiveEntryList_.contains (entryName)) { System.err.println (" warning: duplicate entry: " + entryName + ". Skipping."); } else { System.out.println (" " + file); archivecount_ ++; ZipEntry newEntry = new ZipEntry (entryName); stream.putNextEntry (newEntry); FileInputStream in = new FileInputStream (file); byte [] buf = new byte [2048]; int read = in.read (buf, 0, buf.length); while (read > 0) { stream.write (buf, 0, read); read = in.read (buf, 0, buf.length); } in.close (); stream.closeEntry (); archiveEntryList_.add (entryName); } } else { System.err.println (" error: file " + file + " does not exist. Skipping."); } }
Zip Files
Type-3 (WT3/4)
false
7,556,871
private static byte [] createMD5 (String seed) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance ("MD5"); md5.reset (); md5.update (seed.getBytes ("UTF-8")); return md5.digest (); }
19,474,501
private void getRandomGUID (boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer (); try { md5 = MessageDigest.getInstance ("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println ("Error: " + e); } try { long time = System.currentTimeMillis (); long rand = 0; if (secure) { rand = mySecureRand.nextLong (); } else { rand = myRand.nextLong (); } sbValueBeforeMD5.append (s_id); sbValueBeforeMD5.append (":"); sbValueBeforeMD5.append (Long.toString (time)); sbValueBeforeMD5.append (":"); sbValueBeforeMD5.append (Long.toString (rand)); valueBeforeMD5 = sbValueBeforeMD5.toString (); md5.update (valueBeforeMD5.getBytes ()); byte [] array = md5.digest (); StringBuffer sb = new StringBuffer (); for (int j = 0; j < array.length; ++ j) { int b = array [j] & 0xFF; if (b < 0x10) sb.append ('0'); sb.append (Integer.toHexString (b)); } valueAfterMD5 = sb.toString (); } catch (Exception e) { System.out.println ("Error:" + e); } }
Secure Hash
Type-3 (WT3/4)
true
469,376
protected void flatten (File dir) { assert dir.isDirectory (); File [] files = dir.listFiles (); for (int i = 0; i < files.length; i ++) { File subfile = files [i]; if (subfile.isFile ()) { continue; } else { flatten (subfile); File [] subfiles = subfile.listFiles (); for (int j = 0; j < subfiles.length; j ++) { File f = subfiles [j]; File temp = new File (subfile.getParent () + '\\' + subfile.getName () + '_' + f.getName ()); if (f.renameTo (temp) == false) { throw new RuntimeException ("Cannot rename: " + f.toString ()); } else { System.out.println (f.toString () + ". Rename OK!"); } } if (subfile.delete () == false) { throw new RuntimeException ("Cannot delete: " + subfile.toString ()); } } } }
662,161
public static boolean deleteDirectory (File path) { if (path.exists ()) { File [] files = path.listFiles (); for (int i = 0; i < files.length; i ++) { if (files [i].isDirectory ()) { deleteDirectory (files [i]); } else { files [i].delete (); } } } return (path.delete ()); }
Delete Folder and Contents
Type-3 (WT3/4)
false
13,374,130
private void zipLog (InfoRolling info) { boolean zipped = false; File [] logFiles = info.getFiles (); try { GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance (); gc.roll (Calendar.DAY_OF_MONTH, info.getBackRolling ()); final String prefixFileName = logFileName.substring (0, logFileName.indexOf (".")); final String date = sdf.format (gc.getTime ()); String tarName = new StringBuffer (prefixFileName).append (date).append (".tar").toString (); String gzipFileName = new StringBuffer (tarName).append (".zip").toString (); String tarPath = new StringBuffer (logDir).append (File.separator).append (tarName).toString (); TarArchive ta = new TarArchive (new FileOutputStream (tarPath)); for (int i = 0; i < logFiles.length; i ++) { File file = logFiles [i]; TarEntry te = new TarEntry (file); ta.writeEntry (te, true); } ta.closeArchive (); ZipEntry zipEntry = new ZipEntry (tarName); zipEntry.setMethod (ZipEntry.DEFLATED); ZipOutputStream zout = new ZipOutputStream (new FileOutputStream (new StringBuffer (logDir).append (File.separator).append (gzipFileName).toString ())); zout.putNextEntry (zipEntry); InputStream in = new FileInputStream (tarPath); byte [] buffer = new byte [2048]; int ch = 0; while ((ch = in.read (buffer)) >= 0) { zout.write (buffer, 0, ch); } zout.flush (); zout.close (); in.close (); logFiles = new File (getFile ().substring (0, getFile ().lastIndexOf (File.separator))).listFiles (new FileFilter () { public boolean accept (File file) { return file.getName ().endsWith (".tar"); }} ); for (int i = 0; i < logFiles.length; i ++) { File file = logFiles [i]; System.out.println ("cancello : " + file.getAbsolutePath () + " : " + file.delete ()); } logFiles = new File (getFile ().substring (0, getFile ().lastIndexOf (File.separator))).listFiles (new FileFilter () { public boolean accept (File file) { return file.getName ().indexOf (prefixFileName + ".log" + date) != - 1 && ! file.getName ().endsWith (".zip"); }} ); for (int i = 0; i < logFiles.length; i ++) { File file = logFiles [i]; System.out.println ("cancello : " + file.getAbsolutePath () + " : " + file.delete ()); } zipped = true; } catch (FileNotFoundException ex) { LogLog.error ("Filenotfound: " + ex.getMessage (), ex); } catch (IOException ex) { LogLog.error ("IOException: " + ex.getMessage (), ex); } finally { if (zipped) { for (int i = 0; i < logFiles.length; i ++) { File file = logFiles [i]; file.delete (); } } } }
14,548,451
private static final void zipEntry (File sourceFile, String sourcePath, ZipOutputStream zos) throws IOException { if (sourceFile.isDirectory ()) { if (sourceFile.getName ().equalsIgnoreCase (".metadata")) { return; } File [] fileArray = sourceFile.listFiles (); for (int i = 0; i < fileArray.length; i ++) { zipEntry (fileArray [i], sourcePath, zos); } } else { BufferedInputStream bis = null; String sFilePath = sourceFile.getPath (); String zipEntryName = sFilePath.substring (sourcePath.length () + 1, sFilePath.length ()); bis = new BufferedInputStream (new FileInputStream (sourceFile)); ZipEntry zentry = new ZipEntry (zipEntryName); zentry.setTime (sourceFile.lastModified ()); zos.putNextEntry (zentry); byte [] buffer = new byte [BUFFER_SIZE]; int cnt = 0; while ((cnt = bis.read (buffer, 0, BUFFER_SIZE)) != - 1) { zos.write (buffer, 0, cnt); } zos.closeEntry (); bis.close (); } }
Zip Files
Type-3 (WT3/4)
true
469,518
public synchronized void writeFile (String filename) throws IOException { int amount; byte buffer [] = new byte [4096]; File f = new File (filename); FileInputStream in = new FileInputStream (f); putNextEntry (new ZipEntry (f.getName ())); while ((amount = in.read (buffer)) != - 1) write (buffer, 0, amount); closeEntry (); in.close (); }
1,719,182
public void actionPerformed (ActionEvent evt) { Object src = evt.getSource (); if (src == scanForImages) { JFileChooser chooser = (JFileChooser) objects.getObject (JFileChooser.class); if (chooser.showOpenDialog (this) != JFileChooser.APPROVE_OPTION) { return; } File dir = chooser.getSelectedFile (); if (! dir.isDirectory ()) { dir = dir.getParentFile (); } resyncImageSelection (dir); } else if (src == createPC) { try { File floppyImage = floppyDisk.getSelectedFile (); File hardImage = hardDisk.getSelectedFile (); File cdImage = cdrom.getSelectedFile (); DriveSet.BootType bootType; if (floppyDisk.isBootDevice ()) { if (! floppyImage.exists ()) { alert ("Floppy Image: " + floppyImage + " does not exist", "Boot", JOptionPane.ERROR_MESSAGE); return; } bootType = DriveSet.BootType.FLOPPY; } else if (hardDisk.isBootDevice ()) { if (! hardImage.exists ()) { alert ("Hard disk Image: " + hardImage + " does not exist", "Boot", JOptionPane.ERROR_MESSAGE); return; } bootType = DriveSet.BootType.HARD_DRIVE; } else { if (! cdImage.exists ()) { alert ("CD Image: " + cdImage + " does not exist", "Boot", JOptionPane.ERROR_MESSAGE); return; } bootType = DriveSet.BootType.CDROM; } String [] args; int argc = 0; if (floppyImage != null) { argc += 2; } if (hardImage != null) { argc += 2; } if (cdImage != null) { argc += 2; } if (argc > 2) { argc += 2; } args = new String [argc]; int pos = 0; if (floppyImage != null) { args [pos ++] = "-fda"; args [pos ++] = floppyImage.getAbsolutePath (); } if (hardImage != null) { args [pos ++] = "-hda"; args [pos ++] = hardImage.getAbsolutePath (); } if (cdImage != null) { args [pos ++] = "-cdrom"; args [pos ++] = cdImage.getAbsolutePath (); } if (pos <= (argc - 2)) { args [pos ++] = "-boot"; if (bootType == DriveSet.BootType.HARD_DRIVE) { args [pos ++] = "hda"; } else if (bootType == DriveSet.BootType.CDROM) { args [pos ++] = "cdrom"; } else { args [pos ++] = "fda"; } } instance.createPC (args); resyncImageSelection (new File (System.getProperty ("user.dir"))); } catch (Exception e) { alert ("Failed to create PC: " + e, "Boot", JOptionPane.ERROR_MESSAGE); } } else if (src == loadSnapshot) { runMenu.stop (); JFileChooser fc = new JFileChooser (); try { BufferedReader in = new BufferedReader (new FileReader ("prefs.txt")); String path = in.readLine (); in.close (); if (path != null) { File f = new File (path); if (f.isDirectory ()) { fc.setCurrentDirectory (f); } } } catch (Exception e) { } int returnVal = fc.showDialog (this, "Load JPC Snapshot"); File file = fc.getSelectedFile (); try { if (file != null) { BufferedWriter out = new BufferedWriter (new FileWriter ("prefs.txt")); out.write (file.getPath ()); out.close (); } } catch (Exception e) { e.printStackTrace (); } if (returnVal == 0) { try { System.out.println ("Loading a snapshot of JPC"); ZipInputStream zin = new ZipInputStream (new FileInputStream (file)); zin.getNextEntry (); ((PC) objects.getObject (PC.class)).loadState (zin); zin.closeEntry (); ((PCMonitorFrame) objects.getObject (PCMonitorFrame.class)).resizeDisplay (); zin.getNextEntry (); ((PCMonitorFrame) objects.getObject (PCMonitorFrame.class)).loadMonitorState (zin); zin.closeEntry (); zin.close (); System.out.println ("done"); } catch (IOException e) { e.printStackTrace (); } } } else if (src == saveSnapshot) { runMenu.stop (); JFileChooser fc = new JFileChooser (); try { BufferedReader in = new BufferedReader (new FileReader ("prefs.txt")); String path = in.readLine (); in.close (); if (path != null) { File f = new File (path); if (f.isDirectory ()) { fc.setCurrentDirectory (f); } } } catch (Exception e) { } int returnVal = fc.showDialog (this, "Save JPC Snapshot"); File file = fc.getSelectedFile (); try { if (file != null) { BufferedWriter out = new BufferedWriter (new FileWriter ("prefs.txt")); out.write (file.getPath ()); out.close (); } } catch (Exception e) { e.printStackTrace (); } if (returnVal == 0) { try { ZipOutputStream zip = new ZipOutputStream (new FileOutputStream (file)); zip.putNextEntry (new ZipEntry ("pc")); ((PC) objects.getObject (PC.class)).saveState (zip); zip.closeEntry (); zip.putNextEntry (new ZipEntry ("monitor")); ((PCMonitorFrame) objects.getObject (PCMonitorFrame.class)).saveState (zip); zip.closeEntry (); zip.finish (); zip.close (); } catch (IOException e) { e.printStackTrace (); } } } else if (src == processorFrame) { ProcessorFrame pf = (ProcessorFrame) objects.getObject (ProcessorFrame.class); if (pf != null) { bringToFront (pf); } else { pf = new ProcessorFrame (); addInternalFrame (desktop, 10, 10, pf); } } else if (src == physicalMemoryViewer) { MemoryViewer mv = (MemoryViewer) objects.getObject (MemoryViewer.class); if (mv != null) { bringToFront (mv); } else { mv = new MemoryViewer ("Physical Memory"); addInternalFrame (desktop, 360, 50, mv); } } else if (src == linearMemoryViewer) { LinearMemoryViewer lmv = (LinearMemoryViewer) objects.getObject (LinearMemoryViewer.class); if (lmv != null) { bringToFront (lmv); } else { lmv = new LinearMemoryViewer ("Linear Memory"); addInternalFrame (desktop, 360, 50, lmv); } } else if (src == breakpoints) { BreakpointsFrame bp = (BreakpointsFrame) objects.getObject (BreakpointsFrame.class); if (bp != null) { bringToFront (bp); } else { bp = new BreakpointsFrame (); addInternalFrame (desktop, 550, 360, bp); } } else if (src == watchpoints) { WatchpointsFrame wp = (WatchpointsFrame) objects.getObject (WatchpointsFrame.class); if (wp != null) { bringToFront (wp); } else { wp = new WatchpointsFrame (); addInternalFrame (desktop, 550, 360, wp); } } else if (src == opcodeFrame) { OpcodeFrame op = (OpcodeFrame) objects.getObject (OpcodeFrame.class); if (op != null) { bringToFront (op); } else { op = new OpcodeFrame (); addInternalFrame (desktop, 100, 200, op); } } else if (src == traceFrame) { ExecutionTraceFrame tr = (ExecutionTraceFrame) objects.getObject (ExecutionTraceFrame.class); if (tr != null) { bringToFront (tr); } else { tr = new ExecutionTraceFrame (); addInternalFrame (desktop, 30, 100, tr); } } else if (src == monitor) { PCMonitorFrame m = (PCMonitorFrame) objects.getObject (PCMonitorFrame.class); if (m != null) { bringToFront (m); } else { m = new PCMonitorFrame (); addInternalFrame (desktop, 30, 30, m); } } refresh (); }
Zip Files
Type-3 (WT3/4)
false
9,781,386
public void run () { root.setCursor (Cursor.getPredefinedCursor (3)); try { tempArchiveFile = File.createTempFile ("JZip", ".zip"); if (table.getRowCount () != delRows.length) { stream = new FileOutputStream (tempArchiveFile); out = new ZipOutputStream (stream); boolean aflag [] = new boolean [table.getRowCount ()]; for (int i = 0; i < table.getRowCount (); i ++) { aflag [i] = false; } for (int j = 0; j < delRows.length; j ++) { aflag [delRows [j]] = true; } ZipFile zipfile = new ZipFile (archiveFile); for (int k = 0; k < table.getRowCount (); k ++) { if (! aflag [k]) { Object obj = ziptm.getRealValueAt (k, 6); String s1 = ziptm.getRealValueAt (k, 0).toString (); String s2 = s1; String s3 = ""; if (obj != null) { String s4 = obj.toString (); s2 = s4 + s1; } ZipEntry zipentry = zipfile.getEntry (s2.replace (File.separatorChar, '/')); if (zipentry == null) { System.out.println ("The entry with name<" + s2 + "> is null"); } else { InputStream inputstream = zipfile.getInputStream (zipentry); out.putNextEntry (zipentry); do { int l = inputstream.read (buffer, 0, buffer.length); if (l <= 0) { break; } out.write (buffer, 0, l); } while (true); inputstream.close (); out.closeEntry (); } } } zipfile.close (); out.close (); stream.close (); } String s = archiveFile.getAbsolutePath (); archiveFile.delete (); tempArchiveFile.renameTo (new File (s)); tempArchiveFile.getCanonicalPath (); openArchive (new File (s)); table.clearSelection (); setStatus ("Totally " + delRows.length + " file(s) deleted from this archive!"); } catch (Exception exception) { exception.printStackTrace (); setStatus ("Error: " + exception.getMessage ()); } root.setCursor (Cursor.getPredefinedCursor (0)); notifyAll (); }
12,498,692
public void outputCitation (OutputStream outputStream, DataResourceAuditor resultsOutputter, String citationFileName, Locale locale, String hostUrl) throws IOException { if (outputStream instanceof ZipOutputStream) { ((ZipOutputStream) outputStream).putNextEntry (new ZipEntry (citationFileName)); } Map < String, String > dataResources = resultsOutputter.getDataResources (); CitationCreator cc = new CitationCreator (); StringBuffer csb = cc.createCitation (dataResources, messageSource, locale, hostUrl + datasetBaseUrl); outputStream.write (csb.toString ().getBytes ()); if (outputStream instanceof ZipOutputStream) { ((ZipOutputStream) outputStream).closeEntry (); } }
Zip Files
Type-3 (WT3/4)
true
9,856,200
public static void copyFile (File srcFile, File destFolder) { try { File destFile = new File (destFolder, srcFile.getName ()); if (destFile.exists ()) { throw new BuildException ("Could not copy " + srcFile + " to " + destFolder + " as " + destFile + " already exists"); } FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream (srcFile).getChannel (); destChannel = new FileOutputStream (destFile).getChannel (); destChannel.transferFrom (srcChannel, 0, srcChannel.size ()); } finally { if (srcChannel != null) { srcChannel.close (); } if (destChannel != null) { destChannel.close (); } } destFile.setLastModified ((srcFile.lastModified ())); } catch (IOException e) { throw new BuildException ("Could not copy " + srcFile + " to " + destFolder + ": " + e, e); } }
22,556,551
private void copyOneFile (String oldPath, String newPath) { File copiedFile = new File (newPath); try { FileInputStream source = new FileInputStream (oldPath); FileOutputStream destination = new FileOutputStream (copiedFile); FileChannel sourceFileChannel = source.getChannel (); FileChannel destinationFileChannel = destination.getChannel (); long size = sourceFileChannel.size (); sourceFileChannel.transferTo (0, size, destinationFileChannel); source.close (); destination.close (); } catch (Exception exc) { exc.printStackTrace (); } }
Copy File
Type-3 (WT3/4)
true
1,282,820
public TaskListPanel () { setLayout (new BorderLayout (0, 0)); JScrollPane scrollPane = new JScrollPane (); table = new JTable (); table.addMouseListener (new MouseAdapter () { @Override public void mouseReleased (MouseEvent e) { }} ); table.setModel (SMTSingleton.getSingletonInstance ().getCurrentSearch ().getTasks ()); scrollPane.setViewportView (table); add (scrollPane, BorderLayout.CENTER); JPopupMenu popupMenu = new JPopupMenu (); addPopup (table, popupMenu); JMenuItem mntmPrintTaskAssignment = new JMenuItem ("Print Task Assignment Form"); mntmPrintTaskAssignment.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent e) { int row = table.getSelectedRow (); String taskid = ((TaskList) table.getModel ()).getTaskAt (row).getIdentifier (); ((TaskList) table.getModel ()).getTaskAt (row).writeToPdf (taskid.replace (' ', '_') + "_ICS-204a-OS" + ".pdf"); }} ); JMenuItem mntmEditTask = new JMenuItem ("Edit Task"); mntmEditTask.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent e) { int row = table.getSelectedRow (); TaskDialog d = new TaskDialog (((TaskList) table.getModel ()).getTaskAt (row)); d.setVisible (true); }} ); popupMenu.add (mntmEditTask); popupMenu.add (mntmPrintTaskAssignment); popupMenu.addSeparator (); JMenuItem mntmPrintTaskAssignments = new JMenuItem ("Print All Task Assignment Forms"); mntmPrintTaskAssignments.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent e) { Document document = new Document (); if ("A4".equals (SMTSingleton.getSingletonInstance ().getProperties ().getProperties ().get (SMTProperties.KEY_PAPERSIZE))) { document.setPageSize (PageSize.A4); } else { document.setPageSize (PageSize.LETTER); } try { String filename = "TaskList_ICS-204_with_Appendixes.pdf"; PdfWriter.getInstance (document, new FileOutputStream (filename)); document.open (); TaskList tasks = ((TaskList) table.getModel ()); tasks.writeToPdf (document); for (int i = 0; i < tasks.getRowCount (); i ++) { tasks.getTaskAt (i).writeToPdf (document); } document.close (); } catch (FileNotFoundException ex) { ex.printStackTrace (); } catch (DocumentException ex) { ex.printStackTrace (); } }} ); popupMenu.add (mntmPrintTaskAssignments); JMenuItem mntmPrintTaskAssignments2 = new JMenuItem ("Print All Task Assignment Forms"); mntmPrintTaskAssignments2.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent e) { Document document = new Document (); if ("A4".equals (SMTSingleton.getSingletonInstance ().getProperties ().getProperties ().get (SMTProperties.KEY_PAPERSIZE))) { document.setPageSize (PageSize.A4); } else { document.setPageSize (PageSize.LETTER); } try { String filename = "TaskList_ICS-204_with_Appendixes.pdf"; PdfWriter.getInstance (document, new FileOutputStream (filename)); document.open (); TaskList tasks = ((TaskList) table.getModel ()); tasks.writeToPdf (document); for (int i = 0; i < tasks.getRowCount (); i ++) { tasks.getTaskAt (i).writeToPdf (document); } document.close (); } catch (FileNotFoundException ex) { ex.printStackTrace (); } catch (DocumentException ex) { ex.printStackTrace (); } }} ); JMenuBar menuBar = new JMenuBar (); add (menuBar, BorderLayout.NORTH); menuBar.add (getTaskCreationMenu ()); menuBar.add (mntmPrintTaskAssignments2); }
2,111,179
public static void main (String [] args) { Document document = new Document (); try { PdfWriter writer = PdfWriter.getInstance (document, new FileOutputStream ("results/in_action/chapterX/tooltip3.pdf")); document.open (); writer.setPageEvent (new TooltipExample3 ()); Paragraph p = new Paragraph ("Hello World "); Chunk c = new Chunk ("tooltip"); c.setGenericTag ("This is my tooltip."); p.add (c); document.add (p); } catch (DocumentException de) { System.err.println (de.getMessage ()); } catch (IOException ioe) { System.err.println (ioe.getMessage ()); } document.close (); }
Write PDF File
Type-3 (WT3/4)
false
2,016,059
private void ZipCode (NpsContext ctxt, ZipOutputStream out) throws Exception { String filename = "JOB" + GetId () + ".data"; out.putNextEntry (new ZipEntry (filename)); try { ZipWriter writer = new ZipWriter (out); writer.print (code); } finally { out.closeEntry (); } }
15,375,411
public synchronized void backupStore (String name) throws IOException { if (null != name && name.length () > 0) { String path = this.directoryPath + File.separator + name; File file = new File (path); if (file.exists () && file.isDirectory ()) { String list [] = file.list (); byte [] buf = new byte [1024]; ZipOutputStream out = null; String zipFileName = null; try { zipFileName = this.directoryPath + File.separator + "backup_" + System.currentTimeMillis () + "_" + name + ".zip"; out = new ZipOutputStream (new FileOutputStream (zipFileName)); } catch (FileNotFoundException x) { getLogger ().error ("This should never happen", x); throw new IOException ("Couldn't get ZipFile (" + zipFileName + ")!"); } for (int i = 0; i < list.length; i ++) { try { FileInputStream in = new FileInputStream (path + File.separator + list [i]); out.putNextEntry (new ZipEntry (list [i])); int len; while ((len = in.read (buf)) > 0) { out.write (buf, 0, len); } out.closeEntry (); in.close (); } catch (IOException x) { getLogger ().error (x.getMessage (), x); } } out.close (); } else { throw new IOException ("Invalid Store (" + name + ")!"); } } else { throw new IOException ("Invalid Store (" + name + ")!"); } }
Zip Files
Type-3 (WT3/4)
false
2,014,383
public static void copyFile (String source, String destination, TimeSlotTracker timeSlotTracker) { LOG.info ("copying [" + source + "] to [" + destination + "]"); BufferedInputStream sourceStream = null; BufferedOutputStream destStream = null; try { File destinationFile = new File (destination); if (destinationFile.exists ()) { destinationFile.delete (); } sourceStream = new BufferedInputStream (new FileInputStream (source)); destStream = new BufferedOutputStream (new FileOutputStream (destinationFile)); int readByte; while ((readByte = sourceStream.read ()) > 0) { destStream.write (readByte); } Object [] arg = {destinationFile.getName ()}; String msg = timeSlotTracker.getString ("datasource.xml.copyFile.copied", arg); LOG.fine (msg); } catch (Exception e) { Object [] expArgs = {e.getMessage ()}; String expMsg = timeSlotTracker.getString ("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog (expMsg); timeSlotTracker.errorLog (e); } finally { try { if (destStream != null) { destStream.close (); } if (sourceStream != null) { sourceStream.close (); } } catch (Exception e) { Object [] expArgs = {e.getMessage ()}; String expMsg = timeSlotTracker.getString ("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog (expMsg); timeSlotTracker.errorLog (e); } } }
9,746,855
public static boolean copy (InputStream is, File file) { try { FileOutputStream fos = new FileOutputStream (file); IOUtils.copy (is, fos); is.close (); fos.close (); return true; } catch (Exception e) { System.err.println (e.getMessage ()); return false; } }
Copy File
Type-3 (WT3/4)
true
742,784
public boolean create () { DirectoryManager d = new DirectoryManager (dirSource); Vector < String > filenames = new Vector < String > (); d.getAllMyFileNames (filenames, true, false); byte [] buf = new byte [1024]; try { ZipOutputStream out = null; BufferedOutputStream outStream = null; SevenZip.Compression.LZMA.Encoder encoder = null; boolean eos = false; if (! useLZMA) { out = new ZipOutputStream (new FileOutputStream (zip)); } else { outStream = new BufferedOutputStream (new FileOutputStream (new File (zip))); encoder = new SevenZip.Compression.LZMA.Encoder (); encoder.SetAlgorithm (2); encoder.SetDictionarySize (1 << 21); encoder.SeNumFastBytes (128); encoder.SetMatchFinder (1); encoder.SetLcLpPb (3, 0, 2); encoder.SetEndMarkerMode (eos); encoder.WriteCoderProperties (outStream); } for (int i = 0; i < filenames.size (); i ++) { myMaster.writeOnLog ("processing : " + filenames.elementAt (i) + " to create " + filenames.elementAt (i).replace (d.getDirectory (), "")); if (! useLZMA) { FileInputStream in = new FileInputStream (filenames.elementAt (i)); out.putNextEntry (new ZipEntry (filenames.elementAt (i).replace (d.getDirectory (), ""))); int len; while ((len = in.read (buf)) > 0) { out.write (buf, 0, len); } out.closeEntry (); in.close (); } else { File inFile = new File (filenames.elementAt (i)); BufferedInputStream inStream = new BufferedInputStream (new FileInputStream (new File (filenames.elementAt (i)))); long fileSize; if (eos) fileSize = - 1; else fileSize = inFile.length (); for (int j = 0; j < 8; j ++) outStream.write ((int) (fileSize>>> (8 * j)) & 0xFF); encoder.Code (inStream, outStream, - 1, - 1, null); inStream.close (); } myMaster.setProgress (1); } if (! useLZMA) out.close (); else { outStream.flush (); outStream.close (); } } catch (IOException e) { myMaster.writeOnLog ("error while creating zip file : " + e); return false; } return true; }
6,418,269
protected void packRec (File file, ZipOutputStream zos) throws IOException { if (file.isDirectory ()) { String [] children = file.list (); for (int i = 0; i < children.length; i ++) { packRec (new File (file, children [i]), zos); } } else { String filePath = file.getPath (); String entryPath = filePath.substring (dir.length () + 1).replace ('\\', '/'); ZipEntry entry = new ZipEntry (entryPath); zos.putNextEntry (entry); FileInputStream fis = new FileInputStream (file); byte [] b = new byte [2048]; int tmpLen; while ((tmpLen = fis.read (b)) != - 1) { zos.write (b, 0, tmpLen); } zos.flush (); fis.close (); } }
Zip Files
Type-3 (WT3/4)
false
13,210,305
public static final String encryptMD5 (String decrypted) { try { MessageDigest md5 = MessageDigest.getInstance ("MD5"); md5.update (decrypted.getBytes ()); byte hash [] = md5.digest (); md5.reset (); return hashToHex (hash); } catch (NoSuchAlgorithmException _ex) { return null; } }
19,178,250
public static String createMD5 (String str) { String sig = null; String strSalt = str + sSalt; try { MessageDigest md5 = MessageDigest.getInstance ("MD5"); md5.update (strSalt.getBytes (), 0, strSalt.length ()); byte byteData [] = md5.digest (); StringBuffer sb = new StringBuffer (); for (int i = 0; i < byteData.length; i ++) { sb.append (Integer.toString ((byteData [i] & 0xff) + 0x100, 16).substring (1)); } sig = sb.toString (); } catch (NoSuchAlgorithmException e) { System.err.println ("Can not use md5 algorithm"); } return sig; }
Secure Hash
Type-3 (WT3/4)
true
6,856,298
public static void copyFile (File from, File to) throws IOException { ensureFile (to); FileChannel srcChannel = new FileInputStream (from).getChannel (); FileChannel dstChannel = new FileOutputStream (to).getChannel (); dstChannel.transferFrom (srcChannel, 0, srcChannel.size ()); srcChannel.close (); dstChannel.close (); }
20,508,693
private void zip (FileHolder fileHolder, int zipCompressionLevel) { byte [] buffer = new byte [BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size () == 0) { return; } File zipDestFile = new File (fileHolder.destFiles [0]); try { ZipOutputStream outStream = new ZipOutputStream (new FileOutputStream (zipDestFile)); for (int i = 0; i < fileHolder.selectedFileList.size (); i ++) { File selectedFile = fileHolder.selectedFileList.get (i); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream (selectedFile); ZipEntry entry = new ZipEntry (selectedFile.getName ()); outStream.setLevel (zipCompressionLevel); outStream.putNextEntry (entry); while ((bytes_read = this.inStream.read (buffer)) != - 1) { outStream.write (buffer, 0, bytes_read); } outStream.closeEntry (); this.inStream.close (); } outStream.close (); } catch (IOException e) { errEntry.setThrowable (e); errEntry.setAppContext ("gzip()"); errEntry.setAppMessage ("Error zipping: " + zipDestFile); logger.logError (errEntry); } return; }
Copy File
Type-3 (WT3/4)
true
10,673,772
private File extractResource (String resourceName, File destDir) { File file = new File (destDir, resourceName); InputStream in = getClass ().getResourceAsStream (resourceName); try { FileOutputStream out = FileUtils.openOutputStream (file); try { IOUtils.copy (in, out); } finally { if (out != null) { out.close (); } } } finally { if (in != null) { in.close (); } } return file; }
11,499,032
private void outputSignedOpenDocument (byte [] signatureData) throws IOException { LOG.debug ("output signed open document"); OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream (); if (null == signedOdfOutputStream) { throw new NullPointerException ("signedOpenDocumentOutputStream is null"); } ZipOutputStream zipOutputStream = new ZipOutputStream (signedOdfOutputStream); ZipInputStream zipInputStream = new ZipInputStream (this.getOpenDocumentURL ().openStream ()); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry ())) { if (! zipEntry.getName ().equals (ODFUtil.SIGNATURE_FILE)) { zipOutputStream.putNextEntry (zipEntry); IOUtils.copy (zipInputStream, zipOutputStream); } } zipInputStream.close (); zipEntry = new ZipEntry (ODFUtil.SIGNATURE_FILE); zipOutputStream.putNextEntry (zipEntry); IOUtils.write (signatureData, zipOutputStream); zipOutputStream.close (); }
Copy File
Type-3 (WT3/4)
true
1,579,007
private void nextZipEntry (String url, int level) throws IOException { if (! url.startsWith ("META-INF/") && ! url.startsWith ("OEBPS/")) url = "OEBPS/" + url; ZipEntry ze = new ZipEntry (url); ze.setMethod (ZipEntry.DEFLATED); tmpzos.putNextEntry (ze); }
10,041,940
public void zipFile (FileEntry fileEntry) { String zipfilename = fileEntry.getPath (); if (fileEntry.isDir ()) { zipfilename += ".zip"; } else { zipfilename = zipfilename.substring (0, zipfilename.length () - 4) + ".zip"; } try { ZipOutputStream out = new ZipOutputStream (new BufferedOutputStream (new FileOutputStream (zipfilename))); out.setLevel (Deflater.DEFAULT_COMPRESSION); byte [] data = new byte [1000]; BufferedInputStream in = new BufferedInputStream (new FileInputStream (fileEntry.getPath ())); int count; out.putNextEntry (new ZipEntry (fileEntry.getName ())); while ((count = in.read (data, 0, 1000)) != - 1) { out.write (data, 0, count); } in.close (); out.flush (); out.close (); } catch (Exception e) { e.printStackTrace (); } }
Zip Files
Type-3 (WT3/4)
false
427,727
public BufferedWriter createOutputStream (String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char [] buf = new char [k_blockSize]; File ofp = new File (outFile); ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (ofp)); zos.setMethod (ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter (zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter (osw); ZipEntry zot = null; File ifp = new File (inFile); ZipInputStream zis = new ZipInputStream (new FileInputStream (ifp)); InputStreamReader isr = new InputStreamReader (zis, "ISO-8859-1"); BufferedReader br = new BufferedReader (isr); ZipEntry zit = null; while ((zit = zis.getNextEntry ()) != null) { if (zit.getName ().equals ("content.xml")) { continue; } zot = new ZipEntry (zit.getName ()); zos.putNextEntry (zot); while ((byteCount = br.read (buf, 0, k_blockSize)) >= 0) bw.write (buf, 0, byteCount); bw.flush (); zos.closeEntry (); } zos.putNextEntry (new ZipEntry ("content.xml")); bw.flush (); osw = new OutputStreamWriter (zos, "UTF8"); bw = new BufferedWriter (osw); return bw; }
13,901,736
public void archive (String [] fileNames, String archiveName) { byte [] buffer = new byte [1024]; try { ZipOutputStream zipOut = new ZipOutputStream (new FileOutputStream (archiveName)); for (int i = 0; i < fileNames.length; i ++) { FileInputStream fileIn = new FileInputStream (fileNames [i]); zipOut.putNextEntry (new ZipEntry (fileNames [i].replace ('\\', '/'))); int length; while ((length = fileIn.read (buffer)) > 0) { zipOut.write (buffer, 0, length); } zipOut.closeEntry (); fileIn.close (); } zipOut.close (); } catch (IOException e) { } }
Zip Files
Type-3 (WT3/4)
false
778,875
public BufferedWriter createOutputStream (String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char [] buf = new char [k_blockSize]; File ofp = new File (outFile); ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (ofp)); zos.setMethod (ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter (zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter (osw); ZipEntry zot = null; File ifp = new File (inFile); ZipInputStream zis = new ZipInputStream (new FileInputStream (ifp)); InputStreamReader isr = new InputStreamReader (zis, "ISO-8859-1"); BufferedReader br = new BufferedReader (isr); ZipEntry zit = null; while ((zit = zis.getNextEntry ()) != null) { if (zit.getName ().equals ("content.xml")) { continue; } zot = new ZipEntry (zit.getName ()); zos.putNextEntry (zot); while ((byteCount = br.read (buf, 0, k_blockSize)) >= 0) bw.write (buf, 0, byteCount); bw.flush (); zos.closeEntry (); } zos.putNextEntry (new ZipEntry ("content.xml")); bw.flush (); osw = new OutputStreamWriter (zos, "UTF8"); bw = new BufferedWriter (osw); return bw; }
23,247,096
void copyResourceToZip (String entryName, InputStream is, ZipOutputStream zos) throws Exception { ZipEntry entry = new ZipEntry (entryName); zos.putNextEntry (entry); BufferedInputStream bis = new BufferedInputStream (is); int avail = bis.available (); byte [] buffer = new byte [avail]; bis.read (buffer, 0, avail); zos.write (buffer, 0, avail); zos.closeEntry (); }
Zip Files
Type-3 (WT3/4)
false
1,514,106
private void exportLearningUnitView (File selectedFile) { if (learningUnitViewElementsManager.isOriginalElementsOnly ()) { String [] elementIds = learningUnitViewElementsManager.getAllLearningUnitViewElementIds (); for (int i = 0; i < elementIds.length; i ++) { FSLLearningUnitViewElement element = learningUnitViewElementsManager.getLearningUnitViewElement (elementIds [i], false); if (element.getLastModificationDate () == null) { element.setLastModificationDate (String.valueOf (new Date ().getTime ())); element.setModified (true); } } learningUnitViewElementsManager.setModified (true); learningUnitViewManager.saveLearningUnitViewData (); if (selectedFile != null) { try { File outputFile = selectedFile; String fileName = outputFile.getName (); StringBuffer extension = new StringBuffer (); if (fileName.length () >= 5) { for (int i = 5; i > 0; i --) { extension.append (fileName.charAt (fileName.length () - i)); } } if (! extension.toString ().equals (".fslv")) { outputFile.renameTo (new File (outputFile.getAbsolutePath () + ".fslv")); outputFile = new File (outputFile.getAbsolutePath () + ".fslv"); } File files [] = selectedFile.getParentFile ().listFiles (); int returnValue = FLGOptionPane.OK_OPTION; for (int i = 0; i < files.length; i ++) { if (outputFile.getAbsolutePath ().equals (files [i].getAbsolutePath ())) { returnValue = FLGOptionPane.showConfirmDialog (internationalization.getString ("dialog.exportLearningUnitView.fileExits.message"), internationalization.getString ("dialog.exportLearningUnitView.fileExits.title"), FLGOptionPane.OK_CANCEL_OPTION, FLGOptionPane.QUESTION_MESSAGE); break; } } if (returnValue == FLGOptionPane.OK_OPTION) { FileOutputStream os = new FileOutputStream (outputFile); ZipOutputStream zipOutputStream = new ZipOutputStream (os); ZipEntry zipEntry = new ZipEntry ("dummy"); zipOutputStream.putNextEntry (zipEntry); zipOutputStream.closeEntry (); zipOutputStream.flush (); zipOutputStream.finish (); zipOutputStream.close (); final File outFile = outputFile; (new Thread () { public void run () { try { ZipOutputStream zipOutputStream = new ZipOutputStream (new FileOutputStream (outFile)); File [] files = (new File (learningUnitViewManager.getLearningUnitViewOriginalDataDirectory ().getPath ())).listFiles (); int maxSteps = files.length; int step = 1; exportProgressDialog = new FLGImageProgressDialog (null, 0, maxSteps, 0, getClass ().getClassLoader ().getResource ("freestyleLearning/homeCore/images/fsl.gif"), (Color) UIManager.get ("FSLColorBlue"), (Color) UIManager.get ("FSLColorRed"), internationalization.getString ("learningUnitViewExport.rogressbarText")); exportProgressDialog.setCursor (new Cursor (Cursor.WAIT_CURSOR)); exportProgressDialog.setBarValue (step); buildExportZipFile ("", zipOutputStream, files, step); zipOutputStream.flush (); zipOutputStream.finish (); zipOutputStream.close (); exportProgressDialog.setBarValue (maxSteps); exportProgressDialog.setCursor (new Cursor (Cursor.DEFAULT_CURSOR)); exportProgressDialog.dispose (); } catch (Exception e) { e.printStackTrace (); } }} ).start (); os.close (); } } catch (Exception exp) { exp.printStackTrace (); } } } else { } }
20,482,640
private void performFileStream (StreamService streamService, final StreamSession session, SubMonitor subMonitor, int numberOfFilesToSend) throws SarosCancellationException { OutputStream output = session.getOutputStream (0); ZipOutputStream zout = new ZipOutputStream (output); int worked = 0; int lastWorked = 0; int filesSent = 0; double increment = 0.0; if (numberOfFilesToSend >= 1) { increment = (double) 100 / numberOfFilesToSend; subMonitor.beginTask ("Streaming files...", 100); } else { subMonitor.worked (100); } try { for (String projectID : this.projectFilesToSend.keySet ()) { List < IPath > toSend = this.projectFilesToSend.get (projectID); zout = new ZipOutputStream (output); for (IPath path : toSend) { IFile file = sarosSession.getProject (projectID).getFile (path); String absPath = file.getLocation ().toPortableString (); byte [] buffer = new byte [streamService.getChunkSize () [0]]; InputStream input = new FileInputStream (absPath); ZipEntry ze = new ZipEntry (path.toPortableString ()); ze.setExtra (projectID.getBytes ()); zout.putNextEntry (ze); int numRead = 0; while ((numRead = input.read (buffer)) > 0) { zout.write (buffer, 0, numRead); } input.close (); zout.flush (); zout.closeEntry (); worked = (int) Math.round (increment * filesSent); if ((worked - lastWorked) > 0) { subMonitor.worked ((worked - lastWorked)); lastWorked = worked; } filesSent ++; checkCancellation (CancelOption.NOTIFY_PEER); } } } catch (IOException e) { error = true; log.error ("Error while sending file: ", e); localCancel ("An I/O problem occurred while the project's files were being sent: \"" + e.getMessage () + "\" The invitation was cancelled.", CancelOption.NOTIFY_PEER); executeCancellation (); } catch (SarosCancellationException e) { log.debug ("Invitation process was cancelled."); } catch (Exception e) { log.error ("Unknown exception: ", e); } finally { try { if (filesSent >= 1) zout.finish (); } catch (IOException e) { log.warn ("IOException occurred when finishing the ZipOutputStream."); } IOUtils.closeQuietly (output); IOUtils.closeQuietly (zout); } subMonitor.done (); }
Zip Files
Type-3 (WT3/4)
false
106,523
private void saveZipEntries (Object [] entries, ZipOutputStream zos) throws IOException { for (int i = 0; i < entries.length;) { String entryName = (String) entries [i ++]; Object entry = entries [i ++]; zos.putNextEntry (new ZipEntry (entryName)); if (entry instanceof String) { this.saveContents ((String) entry, zos); } else { this.saveZipEntries ((Object []) entry, zos); } } }
10,378,347
private List < ? extends Attachment > createZipAttachment (List < FileSystemItem > nodes, boolean withFolders) throws IOException { File tmp = File.createTempFile ("securus", null); ZipOutputStream zip = new ZipOutputStream (new FileOutputStream (tmp)); try { for (FileSystemItem node : nodes) { String path; if (withFolders) { path = node.getFile (); } else { path = node.getFile (); } zip.putNextEntry (new ZipEntry (path)); InputStream in = new BufferedInputStream (node.getContent ()); int b; while ((b = in.read ()) != - 1) { zip.write (b); } zip.closeEntry (); } } finally { zip.close (); } return Arrays.asList (new ZipAttachment (tmp)); }
Zip Files
Type-3 (WT3/4)
false
5,701,319
public static Object [] addObjectToArray (Object [] array, Object obj) { Class compType = Object.class; if (array != null) { compType = array.getClass ().getComponentType (); } else if (obj != null) { compType = obj.getClass (); } int newArrLength = (array != null ? array.length + 1 : 1); Object [] newArr = (Object []) Array.newInstance (compType, newArrLength); if (array != null) { System.arraycopy (array, 0, newArr, 0, array.length); } newArr [newArr.length - 1] = obj; return newArr; }
14,519,972
public static Object resizeArrayIfDifferent (Object source, int newsize) { int oldsize = Array.getLength (source); if (oldsize == newsize) { return source; } Object newarray = Array.newInstance (source.getClass ().getComponentType (), newsize); if (oldsize < newsize) { newsize = oldsize; } System.arraycopy (source, 0, newarray, 0, newsize); return newarray; }
Resize Array
Type-3 (WT3/4)
true
10,349,782
public static byte [] encode (String origin, String algorithm) throws NoSuchAlgorithmException { String resultStr = null; resultStr = new String (origin); MessageDigest md = MessageDigest.getInstance (algorithm); md.update (resultStr.getBytes ()); return md.digest (); }
23,517,481
private String md5 (String uri) throws ConnoteaRuntimeException { try { MessageDigest messageDigest = MessageDigest.getInstance ("MD5"); messageDigest.update (uri.getBytes ()); byte [] bytes = messageDigest.digest (); StringBuffer stringBuffer = new StringBuffer (); for (byte b : bytes) { String hex = Integer.toHexString (0xff & b); if (hex.length () == 1) { stringBuffer.append ('0'); } stringBuffer.append (hex); } return stringBuffer.toString (); } catch (NoSuchAlgorithmException e) { throw new ConnoteaRuntimeException (e); } }
Secure Hash
Type-3 (WT3/4)
true
1,951,108
private void zipStream (InputStream inStream, String streamName, File zipFile) throws IOException { if (inStream == null) { log.warn ("No stream to zip."); } else { try { FileOutputStream dest = new FileOutputStream (zipFile); ZipOutputStream out = new ZipOutputStream (new BufferedOutputStream (dest)); ZipEntry entry = new ZipEntry (streamName); out.putNextEntry (entry); copyInputStream (inStream, out); out.close (); dest.close (); inStream.close (); } catch (IOException e) { log.error ("IOException while zipping stream"); throw e; } } }
8,504,294
private void storeProcessList (Date date, List < ProcessList > processListes, boolean doNotOverrideFile) { final int BUFFER = 2048; String filename = BASE_FILES_PATH + serverGroup + "/processlist/" + sdf.format (date) + ".zip"; if (doNotOverrideFile && new File (filename).exists ()) return; try { FileOutputStream dest = new FileOutputStream (filename); ZipOutputStream out = new ZipOutputStream (new BufferedOutputStream (dest)); byte data [] = new byte [BUFFER]; for (ProcessList processList : processListes) { ByteArrayInputStream fi = new ByteArrayInputStream (buildProcessListText (processList).getBytes ()); BufferedInputStream origin = new BufferedInputStream (fi, BUFFER); ZipEntry entry = new ZipEntry (processList.getMysqlServer ().getName () + ".txt"); out.putNextEntry (entry); int count; while ((count = origin.read (data, 0, BUFFER)) != - 1) { out.write (data, 0, count); } origin.close (); } out.close (); } catch (Exception e) { e.printStackTrace (); } }
Zip Files
Type-3 (WT3/4)
false