ML4SE23
Collection
Collection of models for the course. Naming convention: ML4SE23_G{group_number}_{model_name}
•
27 items
•
Updated
•
2
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 |
---|---|---|---|---|---|---|
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);
}
}
| 23,247,094 | void copyZipToZip (ZipInputStream zis, ZipOutputStream zos) throws Exception {
ZipEntry entry;
byte [] buffer = new byte [1];
while ((entry = zis.getNextEntry ()) != null) {
zos.putNextEntry (new ZipEntry (entry.getName ()));
while (zis.available () == 1) {
zis.read (buffer, 0, buffer.length);
zos.write (buffer, 0, buffer.length);
}
zis.closeEntry ();
zos.closeEntry ();
}
}
| Zip Files | Type-3 (WT3/4) | false |
3,596,849 | private static void solve_l1r_l2_svc (Problem prob_col, double [] w, double eps, double Cp, double Cn) {
int l = prob_col.l;
int w_size = prob_col.n;
int j, s, iter = 0;
int max_iter = 1000;
int active_size = w_size;
int max_num_linesearch = 20;
double sigma = 0.01;
double d, G_loss, G, H;
double Gmax_old = Double.POSITIVE_INFINITY;
double Gmax_new;
double Gmax_init = 0;
double d_old, d_diff;
double loss_old = 0;
double loss_new;
double appxcond, cond;
int [] index = new int [w_size];
byte [] y = new byte [l];
double [] b = new double [l];
double [] xj_sq = new double [w_size];
double [] C = new double [] {Cn, 0, Cp};
for (j = 0; j < l; j ++) {
b [j] = 1;
if (prob_col.y [j] > 0) y [j] = 1;
else y [j] = - 1;
}
for (j = 0; j < w_size; j ++) {
w [j] = 0;
index [j] = j;
xj_sq [j] = 0;
for (FeatureNode xi : prob_col.x [j]) {
int ind = xi.index - 1;
double val = xi.value;
xi.value *= y [ind];
xj_sq [j] += C [GETI (y, ind)] * val * val;
}
}
while (iter < max_iter) {
Gmax_new = 0;
for (j = 0; j < active_size; j ++) {
int i = j + random.nextInt (active_size - j);
swap (index, i, j);
}
for (s = 0; s < active_size; s ++) {
j = index [s];
G_loss = 0;
H = 0;
for (FeatureNode xi : prob_col.x [j]) {
int ind = xi.index - 1;
if (b [ind] > 0) {
double val = xi.value;
double tmp = C [GETI (y, ind)] * val;
G_loss -= tmp * b [ind];
H += tmp * val;
}
}
G_loss *= 2;
G = G_loss;
H *= 2;
H = Math.max (H, 1e-12);
double Gp = G + 1;
double Gn = G - 1;
double violation = 0;
if (w [j] == 0) {
if (Gp < 0) violation = - Gp;
else if (Gn > 0) violation = Gn;
else if (Gp > Gmax_old / l && Gn < - Gmax_old / l) {
active_size --;
swap (index, s, active_size);
s --;
continue;
}
} else if (w [j] > 0) violation = Math.abs (Gp);
else violation = Math.abs (Gn);
Gmax_new = Math.max (Gmax_new, violation);
if (Gp <= H * w [j]) d = - Gp / H;
else if (Gn >= H * w [j]) d = - Gn / H;
else d = - w [j];
if (Math.abs (d) < 1.0e-12) continue;
double delta = Math.abs (w [j] + d) - Math.abs (w [j]) + G * d;
d_old = 0;
int num_linesearch;
for (num_linesearch = 0; num_linesearch < max_num_linesearch; num_linesearch ++) {
d_diff = d_old - d;
cond = Math.abs (w [j] + d) - Math.abs (w [j]) - sigma * delta;
appxcond = xj_sq [j] * d * d + G_loss * d + cond;
if (appxcond <= 0) {
for (FeatureNode x : prob_col.x [j]) {
b [x.index - 1] += d_diff * x.value;
}
break;
}
if (num_linesearch == 0) {
loss_old = 0;
loss_new = 0;
for (FeatureNode x : prob_col.x [j]) {
int ind = x.index - 1;
if (b [ind] > 0) {
loss_old += C [GETI (y, ind)] * b [ind] * b [ind];
}
double b_new = b [ind] + d_diff * x.value;
b [ind] = b_new;
if (b_new > 0) {
loss_new += C [GETI (y, ind)] * b_new * b_new;
}
}
} else {
loss_new = 0;
for (FeatureNode x : prob_col.x [j]) {
int ind = x.index - 1;
double b_new = b [ind] + d_diff * x.value;
b [ind] = b_new;
if (b_new > 0) {
loss_new += C [GETI (y, ind)] * b_new * b_new;
}
}
}
cond = cond + loss_new - loss_old;
if (cond <= 0) break;
else {
d_old = d;
d *= 0.5;
delta *= 0.5;
}
}
w [j] += d;
if (num_linesearch >= max_num_linesearch) {
info ("#");
for (int i = 0;
i < l; i ++) b [i] = 1;
for (int i = 0;
i < w_size; i ++) {
if (w [i] == 0) continue;
for (FeatureNode x : prob_col.x [i]) {
b [x.index - 1] -= w [i] * x.value;
}
}
}
}
if (iter == 0) Gmax_init = Gmax_new;
iter ++;
if (iter % 10 == 0) info (".");
if (Gmax_new <= eps * Gmax_init) {
if (active_size == w_size) break;
else {
active_size = w_size;
info ("*");
Gmax_old = Double.POSITIVE_INFINITY;
continue;
}
}
Gmax_old = Gmax_new;
}
info ("%noptimization finished, #iter = %d%n", iter);
if (iter >= max_iter) info ("%nWARNING: reaching max number of iterations%n");
double v = 0;
int nnz = 0;
for (j = 0; j < w_size; j ++) {
for (FeatureNode x : prob_col.x [j]) {
x.value *= prob_col.y [x.index - 1];
}
if (w [j] != 0) {
v += Math.abs (w [j]);
nnz ++;
}
}
for (j = 0; j < l; j ++) if (b [j] > 0) v += C [GETI (y, j)] * b [j] * b [j];
info ("Objective value = %f%n", v);
info ("#nonzeros/#features = %d/%d%n", nnz, w_size);
}
| 8,533,735 | public void shuffle () {
Card tempCard = new Card ();
for (int i = 0;
i < NUM_CARDS; i ++) {
int j = i + r.nextInt (NUM_CARDS - i);
tempCard = cards [j];
cards [j] = cards [i];
cards [i] = tempCard;
}
position = 0;
}
| Shuffle Array in Place | Type-3 (WT3/4) | false |
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 ();
}
| 21,524,576 | private static void zip (File srcDir, File originSrcDir, ZipOutputStream dstStream) throws IOException {
byte [] buffer = new byte [ZIP_BUFFER_SIZE];
int bytes = 0;
String [] dirList = srcDir.list ();
for (int i = 0;
i < dirList.length; i ++) {
File file = new File (srcDir, dirList [i]);
if (file.isDirectory ()) {
zip (file, originSrcDir, dstStream);
continue;
}
FileInputStream fis = new FileInputStream (file);
ZipEntry entry = new ZipEntry (TFileHandler.removeDirectoryPath (originSrcDir.getAbsolutePath (), file.getAbsolutePath ()));
dstStream.putNextEntry (entry);
while ((bytes = fis.read (buffer)) != - 1) dstStream.write (buffer, 0, bytes);
fis.close ();
}
}
| Zip Files | Type-3 (WT3/4) | false |
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");
}
}
| 13,877,913 | public static boolean addZipEntry (String srcZipFile, String newEntryFile, String dstFile) {
java.util.zip.ZipOutputStream zout = null;
InputStream is = null;
try {
if (new File (newEntryFile).isDirectory () && ! newEntryFile.substring (newEntryFile.length () - 1).equals (File.separator)) {
newEntryFile = newEntryFile + File.separator;
}
System.err.println ("============");
File fn = new File (dstFile);
if (! fn.exists ()) {
fn.createNewFile ();
}
zout = new java.util.zip.ZipOutputStream (new FileOutputStream (dstFile));
ZipFile zipfile = new ZipFile (srcZipFile);
ZipEntry entry = null;
Enumeration e = zipfile.entries ();
byte [] buffer = new byte [1024];
while (e.hasMoreElements ()) {
entry = (ZipEntry) e.nextElement ();
System.err.println (entry.getName ());
zout.putNextEntry (entry);
is = new BufferedInputStream (zipfile.getInputStream (entry));
int count;
while ((count = is.read (buffer, 0, 1024)) != - 1) {
zout.write (buffer, 0, count);
zout.flush ();
}
is.close ();
zout.closeEntry ();
}
zipFile (null, newEntryFile, "*.*", zout);
zout.close ();
return true;
} catch (java.io.IOException ioex) {
LogUtil.getLogger ().error (ioex.getMessage (), ioex);
ioex.printStackTrace ();
return false;
} finally {
try {
if (zout != null) {
zout.close ();
}
} catch (Exception ex) {
}
try {
if (is != null) {
is.close ();
}
} catch (Exception ex) {
}
}
}
| Zip Files | Type-3 (WT3/4) | false |
4,932,279 | public void testSavepoint4 () throws Exception {
Statement stmt = con.createStatement ();
stmt.execute ("CREATE TABLE #savepoint4 (data int)");
stmt.close ();
con.setAutoCommit (false);
for (int i = 0;
i < 3; i ++) {
PreparedStatement pstmt = con.prepareStatement ("INSERT INTO #savepoint4 (data) VALUES (?)");
pstmt.setInt (1, 1);
assertTrue (pstmt.executeUpdate () == 1);
Savepoint savepoint = con.setSavepoint ();
assertNotNull (savepoint);
assertTrue (savepoint.getSavepointId () == 1);
try {
savepoint.getSavepointName ();
assertTrue (false);
} catch (SQLException e) {
}
pstmt.setInt (1, 2);
assertTrue (pstmt.executeUpdate () == 1);
pstmt.close ();
pstmt = con.prepareStatement ("SELECT SUM(data) FROM #savepoint4");
ResultSet rs = pstmt.executeQuery ();
assertTrue (rs.next ());
assertTrue (rs.getInt (1) == 3);
assertTrue (! rs.next ());
pstmt.close ();
rs.close ();
con.rollback (savepoint);
pstmt = con.prepareStatement ("SELECT SUM(data) FROM #savepoint4");
rs = pstmt.executeQuery ();
assertTrue (rs.next ());
assertTrue (rs.getInt (1) == 1);
assertTrue (! rs.next ());
pstmt.close ();
rs.close ();
con.rollback ();
}
con.setAutoCommit (true);
}
| 19,147,301 | public boolean actualizarIdPartida (int idJugadorDiv, int idRonda, int idPartida) {
int intResult = 0;
String sql = "UPDATE jugadorxdivxronda " + " SET idPartida = " + idPartida + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda;
try {
connection = conexionBD.getConnection ();
connection.setAutoCommit (false);
ps = connection.prepareStatement (sql);
intResult = ps.executeUpdate ();
connection.commit ();
} catch (SQLException ex) {
ex.printStackTrace ();
try {
connection.rollback ();
} catch (SQLException exe) {
exe.printStackTrace ();
}
} finally {
conexionBD.close (ps);
conexionBD.close (connection);
}
return (intResult > 0);
}
| Execute update and rollback. | Type-3 (WT3/4) | true |
1,023,289 | public static String MD5 (String s) {
try {
MessageDigest m = MessageDigest.getInstance ("MD5");
m.update (s.getBytes (), 0, s.length ());
return new BigInteger (1, m.digest ()).toString (16);
} catch (NoSuchAlgorithmException ex) {
return "";
}
}
| 14,032,835 | private byte [] szyfrujKlucz (byte [] kluczSesyjny) {
byte [] zaszyfrowanyKlucz = null;
byte [] klucz = null;
try {
MessageDigest skrot = MessageDigest.getInstance ("SHA-1");
skrot.update (haslo.getBytes ());
byte [] skrotHasla = skrot.digest ();
Object kluczDoKlucza = MARS_Algorithm.makeKey (skrotHasla);
int resztaKlucza = this.dlugoscKlucza % ROZMIAR_BLOKU;
if (resztaKlucza == 0) {
klucz = kluczSesyjny;
zaszyfrowanyKlucz = new byte [this.dlugoscKlucza];
} else {
int liczbaBlokow = this.dlugoscKlucza / ROZMIAR_BLOKU + 1;
int nowyRozmiar = liczbaBlokow * ROZMIAR_BLOKU;
zaszyfrowanyKlucz = new byte [nowyRozmiar];
klucz = new byte [nowyRozmiar];
byte roznica = (byte) (ROZMIAR_BLOKU - resztaKlucza);
System.arraycopy (kluczSesyjny, 0, klucz, 0, kluczSesyjny.length);
for (int i = kluczSesyjny.length;
i < nowyRozmiar; i ++) klucz [i] = (byte) roznica;
}
byte [] szyfrogram = null;
int liczbaBlokow = klucz.length / ROZMIAR_BLOKU;
int offset = 0;
for (offset = 0; offset < liczbaBlokow; offset ++) {
szyfrogram = MARS_Algorithm.blockEncrypt (klucz, offset * ROZMIAR_BLOKU, kluczDoKlucza);
System.arraycopy (szyfrogram, 0, zaszyfrowanyKlucz, offset * ROZMIAR_BLOKU, szyfrogram.length);
}
} catch (InvalidKeyException ex) {
Logger.getLogger (SzyfrowaniePliku.class.getName ()).log (Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace ();
}
return zaszyfrowanyKlucz;
}
| Secure Hash | 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 ();
}
}
| 18,643,979 | private static void addTargetFile (ZipOutputStream zos, File file) throws FileNotFoundException, ZipException, IOException {
try {
BufferedInputStream bis = new BufferedInputStream (new FileInputStream (file));
String file_path = file.getPath ();
if (file_path.startsWith (OctopusApplication.PATH_EXPORT_FOLDER)) {
file_path = file_path.substring (OctopusApplication.PATH_EXPORT_FOLDER.length (), file_path.length ());
}
ZipEntry target = new ZipEntry (file_path);
zos.putNextEntry (target);
int c;
while ((c = bis.read ()) != - 1) {
zos.write ((byte) c);
}
bis.close ();
zos.closeEntry ();
} catch (FileNotFoundException e) {
throw e;
} catch (ZipException e) {
throw e;
} catch (IOException e) {
throw e;
}
}
| Zip Files | Type-3 (WT3/4) | false |
4,140,310 | public boolean verify (final char [] password, final String encryptedPassword) {
MessageDigest digest = null;
int size = 0;
String base64 = null;
if (encryptedPassword.regionMatches (true, 0, "{SHA}", 0, 5)) {
size = 20;
base64 = encryptedPassword.substring (5);
try {
digest = MessageDigest.getInstance ("SHA-1");
} catch (final NoSuchAlgorithmException e) {
throw new IllegalStateException ("Invalid algorithm");
}
} else if (encryptedPassword.regionMatches (true, 0, "{SSHA}", 0, 6)) {
size = 20;
base64 = encryptedPassword.substring (6);
try {
digest = MessageDigest.getInstance ("SHA-1");
} catch (final NoSuchAlgorithmException e) {
throw new IllegalStateException ("Invalid algorithm");
}
} else if (encryptedPassword.regionMatches (true, 0, "{MD5}", 0, 5)) {
size = 16;
base64 = encryptedPassword.substring (5);
try {
digest = MessageDigest.getInstance ("MD5");
} catch (final NoSuchAlgorithmException e) {
throw new IllegalStateException ("Invalid algorithm");
}
} else if (encryptedPassword.regionMatches (true, 0, "{SMD5}", 0, 6)) {
size = 16;
base64 = encryptedPassword.substring (6);
try {
digest = MessageDigest.getInstance ("MD5");
} catch (final NoSuchAlgorithmException e) {
throw new IllegalStateException ("Invalid algorithm");
}
} else {
return false;
}
try {
final byte [] data = Base64.decodeBase64 (base64.getBytes ("UTF-8"));
final byte [] orig = new byte [size];
System.arraycopy (data, 0, orig, 0, size);
digest.reset ();
digest.update (new String (password).getBytes ("UTF-8"));
if (data.length > size) {
digest.update (data, size, data.length - size);
}
return MessageDigest.isEqual (digest.digest (), orig);
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException ("UTF-8 Unsupported");
}
}
| 6,659,731 | public static String hashStringMD5 (String string) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance ("MD5");
md.update (string.getBytes ());
byte byteData [] = md.digest ();
StringBuffer sb = new StringBuffer ();
for (int i = 0;
i < byteData.length; i ++) {
sb.append (Integer.toString ((byteData [i] & 0xff) + 0x100, 16).substring (1));
}
StringBuffer hexString = new StringBuffer ();
for (int i = 0;
i < byteData.length; i ++) {
String hex = Integer.toHexString (0xff & byteData [i]);
if (hex.length () == 1) hexString.append ('0');
hexString.append (hex);
}
return hexString.toString ();
}
| Secure Hash | Type-3 (WT3/4) | true |
945,981 | private void displayDiffResults () throws IOException {
File outFile = File.createTempFile ("diff", ".htm");
outFile.deleteOnExit ();
FileOutputStream outStream = new FileOutputStream (outFile);
BufferedWriter out = new BufferedWriter (new OutputStreamWriter (outStream));
out.write ("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n");
if (addedTable.length () > 0) {
out.write ("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>");
out.write (addedTable.toString ());
out.write ("</table><br><br>");
}
if (modifiedTable.length () > 0) {
out.write ("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>");
out.write (modifiedTable.toString ());
out.write ("</table><br><br>");
}
if (deletedTable.length () > 0) {
out.write ("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>");
out.write (deletedTable.toString ());
out.write ("</table><br><br>");
}
out.write ("<table name=METRICS BORDER>\n");
if (modifiedTable.length () > 0 || deletedTable.length () > 0) {
out.write ("<tr><td>Base: </td><td>");
out.write (Long.toString (base));
out.write ("</td></tr>\n<tr><td>Deleted: </td><td>");
out.write (Long.toString (deleted));
out.write ("</td></tr>\n<tr><td>Modified: </td><td>");
out.write (Long.toString (modified));
out.write ("</td></tr>\n<tr><td>Added: </td><td>");
out.write (Long.toString (added));
out.write ("</td></tr>\n<tr><td>New & Changed: </td><td>");
out.write (Long.toString (added + modified));
out.write ("</td></tr>\n");
}
out.write ("<tr><td>Total: </td><td>");
out.write (Long.toString (total));
out.write ("</td></tr>\n</table></div>");
redlinesOut.close ();
out.flush ();
InputStream redlines = new FileInputStream (redlinesTempFile);
byte [] buffer = new byte [4096];
int bytesRead;
while ((bytesRead = redlines.read (buffer)) != - 1) outStream.write (buffer, 0, bytesRead);
outStream.write ("</BODY></HTML>".getBytes ());
outStream.close ();
Browser.launch (outFile.toURL ().toString ());
}
| 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 ();
}
| Copy File | 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;
}
}
}
| 14,787,145 | public void setVariables (Properties varDef) throws Exception {
sendMsg ("Setting the variables ...");
outJar.putNextEntry (new ZipEntry ("vars"));
ObjectOutputStream objOut = new ObjectOutputStream (outJar);
objOut.writeObject (varDef);
objOut.flush ();
outJar.closeEntry ();
}
| Zip Files | Type-3 (WT3/4) | false |
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));
}
| 23,160,103 | public void writeJar (JarOutputStream out) throws IOException, Pack200Exception {
String [] fileName = fileBands.getFileName ();
int [] fileModtime = fileBands.getFileModtime ();
long [] fileSize = fileBands.getFileSize ();
byte [] [] fileBits = fileBands.getFileBits ();
int classNum = 0;
int numberOfFiles = header.getNumberOfFiles ();
long archiveModtime = header.getArchiveModtime ();
for (int i = 0;
i < numberOfFiles; i ++) {
String name = fileName [i];
long modtime = 1000 * (archiveModtime + fileModtime [i]);
boolean deflate = fileDeflate [i];
JarEntry entry = new JarEntry (name);
if (deflate) {
entry.setMethod (ZipEntry.DEFLATED);
} else {
entry.setMethod (ZipEntry.STORED);
CRC32 crc = new CRC32 ();
if (fileIsClass [i]) {
crc.update (classFilesContents [classNum]);
entry.setSize (classFilesContents [classNum].length);
} else {
crc.update (fileBits [i]);
entry.setSize (fileSize [i]);
}
entry.setCrc (crc.getValue ());
}
entry.setTime (modtime - TimeZone.getDefault ().getRawOffset ());
out.putNextEntry (entry);
if (fileIsClass [i]) {
entry.setSize (classFilesContents [classNum].length);
out.write (classFilesContents [classNum]);
classNum ++;
} else {
entry.setSize (fileSize [i]);
out.write (fileBits [i]);
}
}
}
| Zip Files | Type-3 (WT3/4) | false |
850,680 | 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!");
}
| 3,024,971 | @Test
public void testCopy_inputStreamToOutputStream_nullIn () throws Exception {
OutputStream out = new ByteArrayOutputStream ();
try {
IOUtils.copy ((InputStream) null, out);
fail ();
} catch (NullPointerException ex) {
}
}
| Copy File | Type-3 (WT3/4) | true |
337,322 | static void copy (String src, String dest) throws IOException {
File ifp = new File (src);
File ofp = new File (dest);
if (ifp.exists () == false) {
throw new IOException ("file '" + src + "' does not exist");
}
FileInputStream fis = new FileInputStream (ifp);
FileOutputStream fos = new FileOutputStream (ofp);
byte [] b = new byte [1024];
while (fis.read (b) > 0) fos.write (b);
fis.close ();
fos.close ();
}
| 12,859,344 | private void sendFile (File file, HttpServletResponse response) throws IOException {
response.setContentLength ((int) file.length ());
InputStream inputStream = null;
try {
inputStream = new FileInputStream (file);
IOUtils.copy (inputStream, response.getOutputStream ());
} finally {
IOUtils.closeQuietly (inputStream);
}
}
| Copy File | 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");
}
}
| 16,062,997 | public static boolean zipDirectoryRecursive (File path, File zipFileName, String excludeRegEx, boolean relative, boolean compress) {
ArrayList < File > filesToZip = new ArrayList < File > ();
if (path.exists ()) {
File [] files = path.listFiles ();
for (int i = 0;
i < files.length; i ++) {
if (files [i].isDirectory ()) {
FileTools.listFilesRecursive (files [i], filesToZip);
} else {
filesToZip.add (files [i]);
}
}
}
try {
byte [] buffer = new byte [18024];
ZipOutputStream out = new ZipOutputStream (new FileOutputStream (zipFileName));
if (! compress) {
out.setLevel (Deflater.NO_COMPRESSION);
} else {
out.setLevel (Deflater.DEFAULT_COMPRESSION);
}
for (int i = 0;
i < filesToZip.size (); i ++) {
if (excludeRegEx == null || ! filesToZip.get (i).getName ().contains (excludeRegEx)) {
FileInputStream in = new FileInputStream (filesToZip.get (i));
String filePath = filesToZip.get (i).getPath ();
if (relative) {
filePath = filePath.replaceFirst (path.getAbsolutePath () + File.separator, "");
}
System.out.println ("Deflating: " + filePath);
out.putNextEntry (new ZipEntry (filePath));
int len;
while ((len = in.read (buffer)) > 0) {
out.write (buffer, 0, len);
}
out.closeEntry ();
in.close ();
}
}
out.close ();
} catch (IllegalArgumentException iae) {
iae.printStackTrace ();
return (false);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace ();
return (false);
} catch (IOException ioe) {
ioe.printStackTrace ();
return (false);
}
return (true);
}
| Zip Files | Type-3 (WT3/4) | false |
6,961,676 | public void actionPerformed (ActionEvent e) {
if (SAVEPICTURE.equals (e.getActionCommand ())) {
byte [] data = ((PicturePane) picturesPane.getSelectedComponent ()).getImage ();
if (data == null) {
return;
}
File f = Util.getFile (this, "Save file", true);
if (f != null) {
try {
Files.writeFile (f, data);
} catch (Exception ex) {
ex.printStackTrace ();
}
}
} else if (SAVEDL.equals (e.getActionCommand ())) {
JFileChooser fileChooser = new JFileChooser ();
fileChooser.setFileFilter (net.sourceforge.scuba.util.Files.ZIP_FILE_FILTER);
int choice = fileChooser.showSaveDialog (getContentPane ());
switch (choice) {
case JFileChooser.APPROVE_OPTION :
try {
File file = fileChooser.getSelectedFile ();
FileOutputStream fileOut = new FileOutputStream (file);
ZipOutputStream zipOut = new ZipOutputStream (fileOut);
for (short fid : dl.getFileList ()) {
String entryName = Hex.shortToHexString (fid) + ".bin";
InputStream dg = dl.getInputStream (fid);
zipOut.putNextEntry (new ZipEntry (entryName));
int bytesRead;
byte [] dgBytes = new byte [1024];
while ((bytesRead = dg.read (dgBytes)) > 0) {
zipOut.write (dgBytes, 0, bytesRead);
}
zipOut.closeEntry ();
}
zipOut.finish ();
zipOut.close ();
fileOut.flush ();
fileOut.close ();
break;
} catch (IOException fnfe) {
fnfe.printStackTrace ();
}
default :
break;
}
} else if (VIEWDOCCERT.equals (e.getActionCommand ())) {
try {
X509Certificate c = sodFile.getDocSigningCertificate ();
viewData (c.toString (), c.getEncoded ());
} catch (Exception ex) {
ex.printStackTrace ();
}
} else if (VIEWAAKEY.equals (e.getActionCommand ())) {
PublicKey k = dg13file.getPublicKey ();
viewData (k.toString (), k.getEncoded ());
} else if (VIEWEAPKEYS.equals (e.getActionCommand ())) {
String s = "";
int count = 0;
Set < Integer > ids = dg14file.getIds ();
List < byte [] > keys = new ArrayList < byte [] > ();
for (Integer id : ids) {
if (count != 0) {
s += "\n";
}
if (id != - 1) {
s += "Key identifier: " + id + "\n";
}
PublicKey k = dg14file.getKey (id);
s += k.toString ();
keys.add (k.getEncoded ());
count ++;
}
viewData (s, keys);
}
}
| 8,954,798 | public static void writeProject (ProjectModel projectModel, String path) throws IOException {
log.info ("Writing project file to " + path);
File file = JDemResourceLoader.getAsFile (path);
ZipOutputStream zos = new ZipOutputStream (new BufferedOutputStream (new FileOutputStream (file)));
ZipEntry settingsEntry = new ZipEntry ("project.json");
zos.putNextEntry (settingsEntry);
JsonProjectFileWriter.writeProject (projectModel, zos);
if (projectModel.getUserScript () != null) {
ZipEntry scriptEntry = null;
if (projectModel.getScriptLanguage () == ScriptLanguageEnum.GROOVY) {
scriptEntry = new ZipEntry ("script.groovy");
} else if (projectModel.getScriptLanguage () == ScriptLanguageEnum.JYTHON) {
scriptEntry = new ZipEntry ("script.py");
}
if (scriptEntry != null) {
zos.putNextEntry (scriptEntry);
zos.write (projectModel.getUserScript ().getBytes ());
}
} else {
log.info ("User script is null, cannot write.");
}
zos.close ();
}
| Zip Files | Type-3 (WT3/4) | true |
5,389,884 | public static long getDummyCRC (long count) throws IOException {
CRC32 crc = new CRC32 ();
byte [] data = new byte [1024];
int done = 0;
while (done < count) {
int tbw = (int) Math.min (count - done, data.length);
crc.update (data, 0, tbw);
done += tbw;
}
return crc.getValue ();
}
| 8,849,605 | public void decode (File input) throws DecoderException {
try {
YEncFile yencFile = new YEncFile (input);
StringBuffer outputName = new StringBuffer (outputDirName);
outputName.append (File.separator);
outputName.append (yencFile.getHeader ().getName ());
RandomAccessFile output = new RandomAccessFile (outputName.toString (), "rw");
long pos = yencFile.getDataBegin ();
yencFile.getInput ().seek (pos);
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
while (pos < yencFile.getDataEnd ()) {
baos.write (yencFile.getInput ().read ());
pos ++;
}
byte [] buff = decoder.decode (baos.toByteArray ());
output.write (buff);
output.close ();
CRC32 crc32 = new CRC32 ();
crc32.update (buff);
if (! yencFile.getTrailer ().getCrc32 ().equals (Long.toHexString (crc32.getValue ()).toUpperCase ())) throw new DecoderException ("Error in CRC32 check.");
} catch (YEncException ye) {
throw new DecoderException ("Input file is not a YEnc file or contains error : " + ye.getMessage ());
} catch (FileNotFoundException fnfe) {
throw new DecoderException ("Enable to create output file : " + fnfe.getMessage ());
} catch (IOException ioe) {
throw new DecoderException ("Enable to read input file : " + ioe.getMessage ());
}
}
| CRC32 File Checksum | Type-3 (WT3/4) | false |
6,168,797 | public byte [] buildPacket (int padding, SecureRandom random) {
byte [] packet = new byte [PACKET_SIZE + padding];
byte [] buffer = m_buffer.getBytes ();
if (random != null) {
random.nextBytes (packet);
} else {
for (int i = 10 + buffer.length;
i < packet.length; i ++) {
packet [i] = 0;
}
}
packet [0] = (byte) ((m_version>> 8) & 0xff);
packet [1] = (byte) (m_version & 0xff);
packet [2] = (byte) ((m_type>> 8) & 0xff);
packet [3] = (byte) (m_type & 0xff);
packet [4] = 0;
packet [5] = 0;
packet [6] = 0;
packet [7] = 0;
packet [8] = (byte) ((m_resultCode>> 8) & 0xff);
packet [9] = (byte) (m_resultCode & 0xff);
System.arraycopy (buffer, 0, packet, 10, buffer.length);
if ((10 + buffer.length) < PACKET_SIZE - 1) {
packet [10 + buffer.length] = 0;
}
packet [PACKET_SIZE - 1] = 0;
CRC32 crc = new CRC32 ();
crc.update (packet);
long crc_l = crc.getValue ();
packet [4] = (byte) ((crc_l>> 24) & 0xff);
packet [5] = (byte) ((crc_l>> 16) & 0xff);
packet [6] = (byte) ((crc_l>> 8) & 0xff);
packet [7] = (byte) (crc_l & 0xff);
return packet;
}
| 8,653,093 | public static boolean decode (String fileName, ByteArrayOutputStream bos) throws IOException {
byte [] buffer = new byte [BUFFERSIZE];
int bufferLength = 0;
BufferedReader file = new BufferedReader (new InputStreamReader (new FileInputStream (fileName)));
String line = file.readLine ();
while (line != null && ! line.startsWith ("=ybegin")) {
line = file.readLine ();
}
if (line == null) throw new IOException ("Error while looking for start of a file. Could not locate line starting with \"=ybegin\".");
fileName = parseForName (line);
if (fileName == null) fileName = "Unknown.blob";
String partNo = parseForString (line, "part");
if (partNo != null) {
while (line != null && ! line.startsWith ("=ypart")) {
line = file.readLine ();
}
if (line == null) throw new IOException ("Error while handling a multipart file. Could not locate line starting with \"=ypart\".");
}
int character;
boolean special = false;
line = file.readLine ();
CRC32 crc = new CRC32 ();
while (line != null && ! line.startsWith ("=yend")) {
for (int lcv = 0;
lcv < line.length (); lcv ++) {
character = (int) line.charAt (lcv);
if (character != 61) {
buffer [bufferLength] = (byte) (special ? character - 106 : character - 42);
bufferLength ++;
if (bufferLength == BUFFERSIZE) {
bos.write (buffer);
crc.update (buffer);
bufferLength = 0;
}
special = false;
} else special = true;
}
line = file.readLine ();
}
if (bufferLength > 0) {
bos.write (buffer, 0, bufferLength);
crc.update (buffer, 0, bufferLength);
}
file.close ();
Debug.debug ("Size of output file = " + bos.size ());
if (line != null && line.startsWith ("=yend")) {
long fileCRC = - 1;
String crcVal = parseForString (line, "pcrc32");
if (crcVal == null) {
crcVal = parseForCRC (line);
}
if (crcVal != null) fileCRC = Long.parseLong (crcVal, 16);
return fileCRC == crc.getValue ();
} else return false;
}
| CRC32 File Checksum | Type-3 (WT3/4) | false |
5,936,119 | public boolean batchFinished () throws Exception {
Instances data = getInputFormat ();
if (data == null) throw new IllegalStateException ("No input instance format defined");
if (m_Converter == null) {
int [] randomIndices = new int [m_ClassCounts.length];
for (int i = 0;
i < randomIndices.length; i ++) {
randomIndices [i] = i;
}
for (int j = randomIndices.length - 1;
j > 0; j --) {
int toSwap = m_Random.nextInt (j + 1);
int tmpIndex = randomIndices [j];
randomIndices [j] = randomIndices [toSwap];
randomIndices [toSwap] = tmpIndex;
}
double [] randomizedCounts = new double [m_ClassCounts.length];
for (int i = 0;
i < randomizedCounts.length; i ++) {
randomizedCounts [i] = m_ClassCounts [randomIndices [i]];
}
if (m_ClassOrder == RANDOM) {
m_Converter = randomIndices;
m_ClassCounts = randomizedCounts;
} else {
int [] sorted = Utils.sort (randomizedCounts);
m_Converter = new int [sorted.length];
if (m_ClassOrder == FREQ_ASCEND) {
for (int i = 0;
i < sorted.length; i ++) {
m_Converter [i] = randomIndices [sorted [i]];
}
} else if (m_ClassOrder == FREQ_DESCEND) {
for (int i = 0;
i < sorted.length; i ++) {
m_Converter [i] = randomIndices [sorted [sorted.length - i - 1]];
}
} else {
throw new IllegalArgumentException ("Class order not defined!");
}
double [] tmp2 = new double [m_ClassCounts.length];
for (int i = 0;
i < m_Converter.length; i ++) {
tmp2 [i] = m_ClassCounts [m_Converter [i]];
}
m_ClassCounts = tmp2;
}
FastVector values = new FastVector (data.classAttribute ().numValues ());
for (int i = 0;
i < data.numClasses (); i ++) {
values.addElement (data.classAttribute ().value (m_Converter [i]));
}
FastVector newVec = new FastVector (data.numAttributes ());
for (int i = 0;
i < data.numAttributes (); i ++) {
if (i == data.classIndex ()) {
newVec.addElement (new Attribute (data.classAttribute ().name (), values, data.classAttribute ().getMetadata ()));
} else {
newVec.addElement (data.attribute (i));
}
}
Instances newInsts = new Instances (data.relationName (), newVec, 0);
newInsts.setClassIndex (data.classIndex ());
setOutputFormat (newInsts);
int [] temp = new int [m_Converter.length];
for (int i = 0;
i < temp.length; i ++) {
temp [m_Converter [i]] = i;
}
m_Converter = temp;
for (int xyz = 0;
xyz < data.numInstances (); xyz ++) {
Instance datum = data.instance (xyz);
if (! datum.isMissing (datum.classIndex ())) {
datum.setClassValue ((float) m_Converter [(int) datum.classValue ()]);
}
push (datum);
}
}
flushInput ();
m_NewBatch = true;
return (numPendingOutput () != 0);
}
| 16,380,022 | public void shuffle (Random rand) {
for (int i = cards.length - 1;
i >= 0; i --) {
int r = rand.nextInt (i + 1);
Card t = cards [i];
cards [i] = cards [r];
cards [r] = t;
}
nextCard = 0;
}
| Shuffle Array in Place | Type-3 (WT3/4) | false |
150,036 | public static long compute (String str) {
CRC32 crc = new CRC32 ();
Adler32 adler = new Adler32 ();
crc.update (str.getBytes ());
adler.update (str.getBytes ());
long dg1 = crc.getValue ();
long dg2 = adler.getValue ();
crc.update (String.valueOf (dg2).getBytes ());
adler.update (String.valueOf (dg1).getBytes ());
long d3 = crc.getValue ();
long d4 = adler.getValue ();
dg1 ^= d4;
dg2 ^= d3;
return (dg2 ^ ((dg1>>> 32) | (dg1 << 32)));
}
| 10,905,580 | public String getID () {
CRC32 checksum = new CRC32 ();
int i = 0;
checksum.reset ();
while ((i < data.length ()) && (i < 5000)) {
checksum.update ((int) data.charAt (i));
i ++;
}
return (Long.toHexString (checksum.getValue ()) + Integer.toHexString (data.hashCode ()));
}
| CRC32 File Checksum | Type-3 (WT3/4) | false |
1,262,021 | public void execute () throws BuildException {
boolean manifestFound = false;
ZipFile zipFile = null;
ZipInputStream zipInputStream = null;
ZipOutputStream zipFileOutputStream = null;
FileInputStream fileInputStream = null;
File fileIn = new File (m_jarPath);
if (! fileIn.exists ()) {
throw new BuildException ("File " + m_jarPath + " does not exists.");
}
File fileOut = new File (m_jarPath + ".new");
try {
zipFile = new ZipFile (fileIn);
fileInputStream = new FileInputStream (fileIn);
zipInputStream = new ZipInputStream (fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream (fileOut);
zipFileOutputStream = new ZipOutputStream (fileOutputStream);
ZipEntry entry = zipInputStream.getNextEntry ();
while (entry != null) {
if (entry.isDirectory ()) {
} else {
InputStream in = zipFile.getInputStream (entry);
byte [] content = readInputStream (in);
if (entry.getName ().endsWith ("manifest.mf")) {
manifestFound = true;
String contenu = incrementVersionInManifest (content);
zipFileOutputStream.putNextEntry (entry);
zipFileOutputStream.write (contenu.getBytes ());
zipFileOutputStream.flush ();
} else {
zipFileOutputStream.putNextEntry (entry);
zipFileOutputStream.write (content);
zipFileOutputStream.flush ();
}
}
entry = zipInputStream.getNextEntry ();
}
if (! manifestFound) {
ZipEntry newEntry = new ZipEntry ("/meta-inf/manifest.mf");
zipFileOutputStream.putNextEntry (newEntry);
if (m_newMajorRelease == null) {
m_newMajorRelease = "1.0";
}
if (m_newMinorRelease == null) {
m_newMinorRelease = "1";
}
String content = "Manifest-Version: " + m_newMajorRelease + "\nImplementation-Version: \"Build (" + m_newMinorRelease + ")\"";
if ((m_envType != null) && (m_envType.length () > 0)) {
content += (ENVTYPE_HEADER_STRING + m_envType + "\n");
}
zipFileOutputStream.write (content.getBytes ());
zipFileOutputStream.flush ();
m_newVersion = m_newMajorRelease + "." + m_newMinorRelease;
}
} catch (Exception e) {
throw new BuildException (e.getMessage (), e);
} finally {
try {
if (zipFileOutputStream != null) {
zipFileOutputStream.close ();
}
if (zipInputStream != null) {
zipInputStream.close ();
}
if (zipFile != null) {
zipFile.close ();
}
} catch (IOException e) {
}
}
fileIn.delete ();
fileOut.renameTo (fileIn);
System.out.println ("Version increased in jar " + m_jarPath + " to " + m_newVersion);
}
| 1,669,328 | public static byte [] zipEntriesAndFiles (Map < ZipEntry, byte [] > files) throws Exception {
ByteArrayOutputStream dest = new ByteArrayOutputStream ();
ZipOutputStream out = new ZipOutputStream (new BufferedOutputStream (dest));
byte [] data = new byte [2048];
Iterator < ZipEntry > itr = files.keySet ().iterator ();
while (itr.hasNext ()) {
ZipEntry entry = itr.next ();
byte [] tempFile = files.get (entry);
ByteArrayInputStream bytesIn = new ByteArrayInputStream (tempFile);
BufferedInputStream origin = new BufferedInputStream (bytesIn, 2048);
out.putNextEntry (entry);
int count;
while ((count = origin.read (data, 0, 2048)) != - 1) {
out.write (data, 0, count);
}
bytesIn.close ();
origin.close ();
}
out.close ();
byte [] outBytes = dest.toByteArray ();
dest.close ();
return outBytes;
}
| Zip Files | Type-3 (WT3/4) | false |
606,859 | 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!");
}
| 21,834,878 | protected void renderResource (final HttpServletRequest request, final HttpServletResponse response, final InputStream is) throws IOException {
try {
IOUtils.copy (is, response.getOutputStream ());
} finally {
IOUtils.closeQuietly (is);
}
}
| Copy File | 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 ();
}
| 16,900,371 | 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 ++) {
String fileName = files [i];
File file = en.uploadPath (virtualWiki, fileName);
if (file.isDirectory ()) {
continue;
}
progress = Math.min (progressStart + (int) ((double) i * (double) progressLength / files.length), 99);
logger.fine ("Adding uploaded file " + fileName);
ZipEntry entry = new ZipEntry (safename (fileName));
try {
FileInputStream in = new FileInputStream (file);
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.log (Level.WARNING, "Could not open file!", e);
} catch (IOException e) {
logger.log (Level.WARNING, "IOException!", e);
try {
zipout.closeEntry ();
zipout.flush ();
} catch (IOException e1) {
}
}
}
}
| 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;
}
| 6,973,739 | private void writeManifestEntry (File f, JarOutputStream out) {
byte [] buffer = new byte [BUFFERSIZE];
int bytes_read;
try {
BufferedInputStream in = new BufferedInputStream (new FileInputStream (f), BUFFERSIZE);
String en = "META-INF" + "/" + "MANIFEST.MF";
out.putNextEntry (new ZipEntry (en));
while ((bytes_read = in.read (buffer)) != - 1) {
out.write (buffer, 0, bytes_read);
}
in.close ();
out.closeEntry ();
} catch (Exception e) {
System.out.println ("[writeManifestEntry(), JarWriter] ERROR\n" + e);
}
}
| Zip Files | Type-3 (WT3/4) | false |
6,368,468 | boolean copyFileStructure (File oldFile, File newFile) {
if (oldFile == null || newFile == null) return false;
File searchFile = newFile;
do {
if (oldFile.equals (searchFile)) return false;
searchFile = searchFile.getParentFile ();
} while (searchFile != null);
if (oldFile.isDirectory ()) {
if (progressDialog != null) {
progressDialog.setDetailFile (oldFile, ProgressDialog.COPY);
}
if (simulateOnly) {
} else {
if (! newFile.mkdirs ()) return false;
}
File [] subFiles = oldFile.listFiles ();
if (subFiles != null) {
if (progressDialog != null) {
progressDialog.addWorkUnits (subFiles.length);
}
for (int i = 0;
i < subFiles.length; i ++) {
File oldSubFile = subFiles [i];
File newSubFile = new File (newFile, oldSubFile.getName ());
if (! copyFileStructure (oldSubFile, newSubFile)) return false;
if (progressDialog != null) {
progressDialog.addProgress (1);
if (progressDialog.isCancelled ()) return false;
}
}
}
} else {
if (simulateOnly) {
} else {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader (oldFile);
out = new FileWriter (newFile);
int count;
while ((count = in.read ()) != - 1) out.write (count);
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
} finally {
try {
if (in != null) in.close ();
if (out != null) out.close ();
} catch (IOException e) {
return false;
}
}
}
}
return true;
}
| 8,625,346 | 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 |
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 {
}
}
| 7,577,030 | private void zipFiles (File file, File [] fa) throws Exception {
File f = new File (file, ALL_FILES_NAME);
if (f.exists ()) {
f.delete ();
f = new File (file, ALL_FILES_NAME);
}
ZipOutputStream zoutstrm = new ZipOutputStream (new FileOutputStream (f));
for (int i = 0;
i < fa.length; i ++) {
ZipEntry zipEntry = new ZipEntry (fa [i].getName ());
zoutstrm.putNextEntry (zipEntry);
FileInputStream fr = new FileInputStream (fa [i]);
byte [] buffer = new byte [1024];
int readCount = 0;
while ((readCount = fr.read (buffer)) > 0) {
zoutstrm.write (buffer, 0, readCount);
}
fr.close ();
zoutstrm.closeEntry ();
}
zoutstrm.close ();
log ("created zip file: " + file.getName () + "/" + ALL_FILES_NAME);
}
| Zip Files | Type-3 (WT3/4) | false |
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);
}
| 22,055,554 | protected void addFileToJar (JarOutputStream jStream, File inputFile, String logicalFilename) throws BuildException {
FileInputStream iStream = null;
try {
if (! addedfiles.contains (logicalFilename)) {
iStream = new FileInputStream (inputFile);
ZipEntry zipEntry = new ZipEntry (logicalFilename.replace ('\\', '/'));
jStream.putNextEntry (zipEntry);
byte [] byteBuffer = new byte [2 * DEFAULT_BUFFER_SIZE];
int count = 0;
do {
jStream.write (byteBuffer, 0, count);
count = iStream.read (byteBuffer, 0, byteBuffer.length);
} while (count != - 1);
addedfiles.add (logicalFilename);
}
} catch (IOException ioe) {
log ("WARNING: IOException while adding entry " + logicalFilename + " to jarfile from " + inputFile.getPath () + " " + ioe.getClass ().getName () + "-" + ioe.getMessage (), Project.MSG_WARN);
} finally {
if (iStream != null) {
try {
iStream.close ();
} catch (IOException closeException) {
}
}
}
}
| Zip Files | Type-3 (WT3/4) | false |
9,275,622 | private boolean copyFile (File _file1, File _file2) {
FileInputStream fis;
FileOutputStream fos;
try {
fis = new FileInputStream (_file1);
fos = new FileOutputStream (_file2);
FileChannel canalFuente = fis.getChannel ();
canalFuente.transferTo (0, canalFuente.size (), fos.getChannel ());
fis.close ();
fos.close ();
return true;
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return false;
}
| 12,312,915 | public static void entering (String [] args) throws IOException, CodeCheckException {
ClassWriter writer = new ClassWriter ();
writer.readClass (new BufferedInputStream (new FileInputStream (args [0])));
int constantIndex = writer.getStringConstantIndex ("Entering ");
int fieldRefIndex = writer.getReferenceIndex (ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;");
int printlnRefIndex = writer.getReferenceIndex (ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
int printRefIndex = writer.getReferenceIndex (ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "print", "(Ljava/lang/String;)V");
for (Iterator i = writer.getMethods ().iterator ();
i.hasNext ();) {
MethodInfo method = (MethodInfo) i.next ();
if (method.getName ().equals ("readConstant")) continue;
CodeAttribute attribute = method.getCodeAttribute ();
ArrayList instructions = new ArrayList (10);
byte [] operands;
operands = new byte [2];
NetByte.intToPair (fieldRefIndex, operands, 0);
instructions.add (new Instruction (OpCode.getOpCodeByMnemonic ("getstatic"), 0, operands, false));
instructions.add (new Instruction (OpCode.getOpCodeByMnemonic ("dup"), 0, null, false));
instructions.add (Instruction.appropriateLdc (constantIndex, false));
operands = new byte [2];
NetByte.intToPair (printRefIndex, operands, 0);
instructions.add (new Instruction (OpCode.getOpCodeByMnemonic ("invokevirtual"), 0, operands, false));
instructions.add (Instruction.appropriateLdc (writer.getStringConstantIndex (method.getName ()), false));
operands = new byte [2];
NetByte.intToPair (printlnRefIndex, operands, 0);
instructions.add (new Instruction (OpCode.getOpCodeByMnemonic ("invokevirtual"), 0, operands, false));
attribute.insertInstructions (0, 0, instructions);
attribute.codeCheck ();
}
BufferedOutputStream outStream = new BufferedOutputStream (new FileOutputStream (args [1]));
writer.writeClass (outStream);
outStream.close ();
}
| Copy File | Type-3 (WT3/4) | true |
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;
}
| 10,620,258 | private void writeFileToZip (ZipOutputStream out, String sourceFilename, String vPath) throws IOException {
FileInputStream in = new FileInputStream (sourceFilename);
out.putNextEntry (new ZipEntry (vPath));
int len;
byte [] buf = new byte [1024];
while ((len = in.read (buf)) > 0) {
out.write (buf, 0, len);
}
out.closeEntry ();
in.close ();
}
| Zip Files | Type-3 (WT3/4) | false |
268,806 | 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 ();
}
}
| 17,296,395 | public static File copyToLibDirectory (final File file) throws FileNotFoundException, IOException {
if (file == null || ! file.exists ()) {
throw new FileNotFoundException ();
}
File directory = new File ("lib/");
File dest = new File (directory, file.getName ());
File parent = dest.getParentFile ();
while (parent != null && ! parent.equals (directory)) {
parent = parent.getParentFile ();
}
if (parent.equals (directory)) {
return file;
}
FileChannel in = null;
FileChannel out = null;
try {
in = new FileInputStream (file).getChannel ();
out = new FileOutputStream (dest).getChannel ();
in.transferTo (0, in.size (), out);
} finally {
if (in != null) {
try {
in.close ();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close ();
} catch (IOException e) {
}
}
}
return dest;
}
| Copy File | Type-3 (WT3/4) | true |
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;
}
| 23,309,807 | public OCFContainerWriter (OutputStream out, String mime) throws IOException {
zip = new ZipOutputStream (out);
try {
byte [] bytes = mime.getBytes ("UTF-8");
ZipEntry mimetype = new ZipEntry ("mimetype");
mimetype.setMethod (ZipOutputStream.STORED);
mimetype.setSize (bytes.length);
mimetype.setCompressedSize (bytes.length);
CRC32 crc = new CRC32 ();
crc.update (bytes);
mimetype.setCrc (crc.getValue ());
zip.putNextEntry (mimetype);
zip.write (bytes);
zip.closeEntry ();
} catch (UnsupportedEncodingException e) {
e.printStackTrace ();
}
}
| Zip Files | Type-3 (WT3/4) | false |
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 ();
}
| 22,572,311 | public static byte [] zipFiles (Map < String, byte [] > files) throws IOException {
ByteArrayOutputStream dest = new ByteArrayOutputStream ();
ZipOutputStream out = new ZipOutputStream (new BufferedOutputStream (dest));
Iterator < Entry < String, byte [] > > itr = files.entrySet ().iterator ();
while (itr.hasNext ()) {
Entry < String, byte [] > entry = itr.next ();
ZipEntry zipEntry = new ZipEntry (entry.getKey ());
out.putNextEntry (zipEntry);
IOUtils.write (entry.getValue (), out);
}
out.close ();
byte [] outBytes = dest.toByteArray ();
dest.close ();
return outBytes;
}
| Zip Files | Type-3 (WT3/4) | false |
3,266,833 | public MotixFileItem (final InputStream is, final String name, final String contentType, final int index) throws IOException {
this.name = name;
this.contentType = contentType;
this.index = index;
this.extension = FilenameUtils.getExtension (this.name);
this.isImage = ImageUtils.isImage (name);
ArrayInputStream isAux = null;
final ByteArrayOutputStream out = new ByteArrayOutputStream ();
try {
IOUtils.copy (is, out);
isAux = new ArrayInputStream (out.toByteArray ());
if (this.isImage) {
this.bufferedImage = imaging.read (isAux);
}
} finally {
IOUtils.closeQuietly (out);
IOUtils.closeQuietly (isAux);
}
this.inputStream = new ArrayInputStream (out.toByteArray ());
}
| 18,400,649 | public static void copyFiles (String strPath, String dstPath) throws IOException {
File src = new File (strPath);
File dest = new File (dstPath);
if (src.isDirectory ()) {
dest.mkdirs ();
String list [] = src.list ();
for (int i = 0;
i < list.length; i ++) {
if (list [i].lastIndexOf (SVN) != - 1) {
if (! SVN.equalsIgnoreCase (list [i].substring (list [i].length () - 4, list [i].length ()))) {
String dest1 = dest.getAbsolutePath () + "\\" + list [i];
String src1 = src.getAbsolutePath () + "\\" + list [i];
copyFiles (src1, dest1);
}
} else {
String dest1 = dest.getAbsolutePath () + "\\" + list [i];
String src1 = src.getAbsolutePath () + "\\" + list [i];
copyFiles (src1, dest1);
}
}
} else {
FileInputStream fin = new FileInputStream (src);
FileOutputStream fout = new FileOutputStream (dest);
int c;
while ((c = fin.read ()) >= 0) fout.write (c);
fin.close ();
fout.close ();
}
}
| Copy File | Type-3 (WT3/4) | true |
7,209,802 | public static void main (String [] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket (4444);
} catch (IOException e) {
System.err.println ("Could not listen on port: 4444.");
System.exit (1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept ();
} catch (IOException e) {
System.err.println ("Accept failed.");
System.exit (1);
}
DataOutputStream out = new DataOutputStream (clientSocket.getOutputStream ());
BufferedReader in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
String inputLine, outputLine;
inputLine = in.readLine ();
String dist_metric = in.readLine ();
File outFile = new File ("data.txt");
FileWriter outw = new FileWriter (outFile);
outw.write (inputLine);
outw.close ();
File sample_coords = new File ("sample_coords.txt");
sample_coords.delete ();
File sp_coords = new File ("sp_coords.txt");
sp_coords.delete ();
try {
System.out.println ("Running python script...");
System.out.println ("Command: " + "python l19test.py " + "\"" + dist_metric + "\"");
Process pr = Runtime.getRuntime ().exec ("python l19test.py " + dist_metric);
BufferedReader br = new BufferedReader (new InputStreamReader (pr.getErrorStream ()));
String line;
while ((line = br.readLine ()) != null) {
System.out.println (line);
}
int exitVal = pr.waitFor ();
System.out.println ("Process Exit Value: " + exitVal);
System.out.println ("done.");
} catch (Exception e) {
System.out.println ("Unable to run python script for PCoA analysis");
}
File myFile = new File ("sp_coords.txt");
byte [] mybytearray = new byte [(new Long (myFile.length ())).intValue ()];
FileInputStream fis = new FileInputStream (myFile);
System.out.println (".");
System.out.println (myFile.length ());
out.writeInt ((int) myFile.length ());
for (int i = 0;
i < myFile.length (); i ++) {
out.writeByte (fis.read ());
}
myFile = new File ("sample_coords.txt");
mybytearray = new byte [(int) myFile.length ()];
fis = new FileInputStream (myFile);
fis.read (mybytearray);
System.out.println (".");
System.out.println (myFile.length ());
out.writeInt ((int) myFile.length ());
out.write (mybytearray);
myFile = new File ("evals.txt");
mybytearray = new byte [(new Long (myFile.length ())).intValue ()];
fis = new FileInputStream (myFile);
fis.read (mybytearray);
System.out.println (".");
System.out.println (myFile.length ());
out.writeInt ((int) myFile.length ());
out.write (mybytearray);
out.flush ();
out.close ();
in.close ();
clientSocket.close ();
serverSocket.close ();
}
| 12,440,171 | public void writeFile (String resource, InputStream is) throws IOException {
File f = prepareFsReferenceAsFile (resource);
FileOutputStream fos = new FileOutputStream (f);
BufferedOutputStream bos = new BufferedOutputStream (fos);
try {
IOUtils.copy (is, bos);
} finally {
IOUtils.closeQuietly (is);
IOUtils.closeQuietly (bos);
}
}
| Copy File | Type-3 (WT3/4) | true |
12,819,863 | public static String generatePassword (String userKey, int applicationId, String applicationKey) {
String nonce = generateNonce ();
String createDate = fmtDate.format (new Date ());
String keyDigest = null;
MessageDigest sha1 = null;
try {
sha1 = MessageDigest.getInstance ("SHA1");
sha1.update (nonce.getBytes ("UTF-8"));
sha1.update (createDate.getBytes ("UTF-8"));
sha1.update (userKey.getBytes ("UTF-8"));
sha1.update (applicationKey.getBytes ("UTF-8"));
keyDigest = getHexaDecimal (sha1.digest ());
} catch (Exception e) {
throw new RuntimeException (e);
}
StringBuilder sb = new StringBuilder ();
sb.append (applicationId);
sb.append (',');
sb.append (nonce);
sb.append (',');
sb.append (createDate);
sb.append (',');
sb.append (keyDigest);
return sb.toString ();
}
| 22,915,885 | public Login authenticateClient () {
Object o;
String user, password;
Vector < Login > clientLogins = ClientLoginsTableModel.getClientLogins ();
Login login = null;
try {
socket.setSoTimeout (25000);
objectOut.writeObject ("JFRITZ SERVER 1.1");
objectOut.flush ();
o = objectIn.readObject ();
if (o instanceof String) {
user = (String) o;
objectOut.flush ();
for (Login l : clientLogins) {
if (l.getUser ().equals (user)) {
login = l;
break;
}
}
if (login != null) {
MessageDigest md = MessageDigest.getInstance ("MD5");
md.update (login.getPassword ().getBytes ());
DESKeySpec desKeySpec = new DESKeySpec (md.digest ());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance ("DES");
SecretKey secretKey = keyFactory.generateSecret (desKeySpec);
Cipher desCipher = Cipher.getInstance ("DES/ECB/PKCS5Padding");
desCipher.init (Cipher.ENCRYPT_MODE, secretKey);
byte [] dataKeySeed = new byte [32];
Random random = new Random ();
random.nextBytes (dataKeySeed);
md.reset ();
md.update (dataKeySeed);
dataKeySeed = md.digest ();
SealedObject dataKeySeedSealed;
dataKeySeedSealed = new SealedObject (dataKeySeed, desCipher);
objectOut.writeObject (dataKeySeedSealed);
objectOut.flush ();
desKeySpec = new DESKeySpec (dataKeySeed);
secretKey = keyFactory.generateSecret (desKeySpec);
inCipher = Cipher.getInstance ("DES/ECB/PKCS5Padding");
outCipher = Cipher.getInstance ("DES/ECB/PKCS5Padding");
inCipher.init (Cipher.DECRYPT_MODE, secretKey);
outCipher.init (Cipher.ENCRYPT_MODE, secretKey);
SealedObject sealedObject = (SealedObject) objectIn.readObject ();
o = sealedObject.getObject (inCipher);
if (o instanceof String) {
String response = (String) o;
if (response.equals ("OK")) {
SealedObject ok_sealed = new SealedObject ("OK", outCipher);
objectOut.writeObject (ok_sealed);
return login;
} else {
Debug.netMsg ("Client sent false response to challenge!");
}
} else {
Debug.netMsg ("Client sent false object as response to challenge!");
}
} else {
Debug.netMsg ("client sent unkown username: " + user);
}
}
} catch (IllegalBlockSizeException e) {
Debug.netMsg ("Wrong blocksize for sealed object!");
Debug.error (e.toString ());
e.printStackTrace ();
} catch (ClassNotFoundException e) {
Debug.netMsg ("received unrecognized object from client!");
Debug.error (e.toString ());
e.printStackTrace ();
} catch (NoSuchAlgorithmException e) {
Debug.netMsg ("MD5 Algorithm not present in this JVM!");
Debug.error (e.toString ());
e.printStackTrace ();
} catch (InvalidKeySpecException e) {
Debug.netMsg ("Error generating cipher, problems with key spec?");
Debug.error (e.toString ());
e.printStackTrace ();
} catch (InvalidKeyException e) {
Debug.netMsg ("Error genertating cipher, problems with key?");
Debug.error (e.toString ());
e.printStackTrace ();
} catch (NoSuchPaddingException e) {
Debug.netMsg ("Error generating cipher, problems with padding?");
Debug.error (e.toString ());
e.printStackTrace ();
} catch (IOException e) {
Debug.netMsg ("Error authenticating client!");
Debug.error (e.toString ());
e.printStackTrace ();
} catch (BadPaddingException e) {
Debug.netMsg ("Bad padding exception!");
Debug.error (e.toString ());
e.printStackTrace ();
}
return null;
}
| Secure Hash | Type-3 (WT3/4) | true |
891,054 | public Thread transmitThread (final Socket s, final CountDownLatch abortLatch) {
final Thread theThread = new Thread () {
@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 ();
}
}}
;
return theThread;
}
| 1,302,030 | private static String getUnicodeStringIfOriginalMatches (AbstractUnicodeExtraField f, byte [] orig) {
if (f != null) {
CRC32 crc32 = new CRC32 ();
crc32.update (orig);
long origCRC32 = crc32.getValue ();
if (origCRC32 == f.getNameCRC32 ()) {
try {
return ZipEncodingHelper.UTF8_ZIP_ENCODING.decode (f.getUnicodeName ());
} catch (IOException ex) {
return null;
}
}
}
return null;
}
| CRC32 File Checksum | Type-3 (WT3/4) | false |
16,319,456 | @Override
public List < SectionFinderResult > lookForSections (String text, Section < ? > father, Type type) {
ArrayList < SectionFinderResult > result = new ArrayList < SectionFinderResult > ();
Pattern TABLE_LINE = Pattern.compile (TABLE_LINE_REGEXP, Pattern.MULTILINE);
Matcher m = TABLE_LINE.matcher (text);
int end = 0;
int tableStart = - 1;
int tableEnd = - 1;
while (m.find (end)) {
int start = m.start ();
end = m.end ();
if (tableEnd == start) {
tableEnd = end;
} else {
addResultIfAvailable (result, tableStart, tableEnd);
tableStart = start;
tableEnd = end;
}
if (end >= text.length ()) break;
}
addResultIfAvailable (result, tableStart, tableEnd);
return result;
}
| 19,047,757 | public LinkedList < SearchResult > search (String strRequest) {
LinkedList < SearchResult > ret = new LinkedList < SearchResult > ();
HttpClient h = new HttpClient ();
try {
String strRequestUrl = "http://www.youporn.com/search";
if (strRequest.toLowerCase ().contains ("straight!")) {
strRequestUrl += "?type=straight";
strRequest = strRequest.replaceAll ("straight!", "");
}
if (strRequest.toLowerCase ().contains ("gay!")) {
strRequestUrl += "?type=gay";
strRequest = strRequest.replaceAll ("gay!", "");
}
if (strRequest.toLowerCase ().contains ("cocks!")) {
strRequestUrl += "?type=cocks";
strRequest = strRequest.replaceAll ("cocks!", "");
}
if (! strRequestUrl.endsWith ("search")) strRequestUrl += "&";
else strRequestUrl += "?";
strRequestUrl += "query=" + URLEncoder.encode (strRequest, "UTF-8");
if (NoMuleRuntime.DEBUG) System.out.println (strRequestUrl);
GetMethod get = new GetMethod (strRequestUrl);
Date d = new Date ((new Date ()).getTime () + (1 * 24 * 3600 * 1000));
h.getState ().addCookie (new Cookie (".youporn.com", "age_check", "1", "/", d, false));
h.executeMethod (get);
BufferedReader in = new BufferedReader (new InputStreamReader (get.getResponseBodyAsStream ()));
String s = "";
String res = "";
while ((s = in.readLine ()) != null) {
res += s;
}
get.releaseConnection ();
if (NoMuleRuntime.DEBUG) System.out.println (res);
String regexp = "\\<a href\\=\"\\/watch\\/[^\"]+\"\\>[^\\<]+";
Pattern p = Pattern.compile (regexp);
Matcher m = p.matcher (res);
while (m.find ()) {
int startPos = m.start () + "<a href=\"".length ();
String strUrl = "http://www.youporn.com";
int pos = 0;
for (pos = startPos; pos < m.end () && (res.charAt (pos) != '\"'); pos ++) {
strUrl += res.charAt (pos);
}
String strTitle = res.substring (pos + 2, m.end ());
if (strTitle.trim ().length () > 0) ret.add (new SearchResult (strTitle + " at YouPorn", strUrl));
}
return ret;
} catch (UnsupportedEncodingException e) {
e.printStackTrace ();
} catch (HttpException e) {
e.printStackTrace ();
} catch (IOException e) {
e.printStackTrace ();
}
return null;
}
| Extract Matches Using Regex | Type-3 (WT3/4) | true |
7,990,229 | public static InputStream gunzip (final InputStream inputStream) throws IOException {
Assert.notNull (inputStream, "inputStream");
GZIPInputStream gzipInputStream = new GZIPInputStream (inputStream);
InputOutputStream inputOutputStream = new InputOutputStream ();
IOUtils.copy (gzipInputStream, inputOutputStream);
return inputOutputStream.getInputStream ();
}
| 15,520,770 | public void writeConfigurationFile () throws IOException, ComponentException {
SystemConfig config = parent.getParentSystem ().getConfiguration ();
File original = config.getLocation ();
File backup = new File (original.getParentFile (), original.getName () + "." + System.currentTimeMillis ());
FileInputStream in = new FileInputStream (original);
FileOutputStream out = new FileOutputStream (backup);
byte [] buffer = new byte [2048];
try {
int bytesread = 0;
while ((bytesread = in.read (buffer)) > 0) {
out.write (buffer, 0, bytesread);
}
} catch (IOException e) {
logger.warn ("Failed to copy backup of configuration file");
throw e;
} finally {
in.close ();
out.close ();
}
FileWriter replace = new FileWriter (original);
replace.write (config.toFileFormat ());
replace.close ();
logger.info ("Re-wrote configuration file " + original.getPath ());
}
| Copy File | Type-3 (WT3/4) | true |
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);
}
}
| 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 ();
}
}
}
}
| Zip Files | Type-3 (WT3/4) | false |
9,371,509 | public SWORDEntry ingestDepost (final DepositCollection pDeposit, final ServiceDocument pServiceDocument) throws SWORDException {
try {
ZipFileAccess tZipFile = new ZipFileAccess (super.getTempDir ());
LOG.debug ("copying file");
String tZipTempFileName = super.getTempDir () + "uploaded-file.tmp";
IOUtils.copy (pDeposit.getFile (), new FileOutputStream (tZipTempFileName));
Datastream tDatastream = new LocalDatastream (super.getGenericFileName (pDeposit), this.getContentType (), tZipTempFileName);
_datastreamList.add (tDatastream);
_datastreamList.addAll (tZipFile.getFiles (tZipTempFileName));
int i = 0;
boolean found = false;
for (i = 0; i < _datastreamList.size (); i ++) {
if (_datastreamList.get (i).getId ().equalsIgnoreCase ("mets")) {
found = true;
break;
}
}
if (found) {
SAXBuilder tBuilder = new SAXBuilder ();
_mets = new METSObject (tBuilder.build (((LocalDatastream) _datastreamList.get (i)).getPath ()));
LocalDatastream tLocalMETSDS = (LocalDatastream) _datastreamList.remove (i);
new File (tLocalMETSDS.getPath ()).delete ();
_datastreamList.add (_mets.getMETSDs ());
_datastreamList.addAll (_mets.getMetadataDatastreams ());
} else {
throw new SWORDException ("Couldn't find a METS document in the zip file, ensure it is named mets.xml or METS.xml");
}
SWORDEntry tEntry = super.ingestDepost (pDeposit, pServiceDocument);
tZipFile.removeLocalFiles ();
return tEntry;
} catch (IOException tIOExcpt) {
String tMessage = "Couldn't retrieve METS from deposit: " + tIOExcpt.toString ();
LOG.error (tMessage);
tIOExcpt.printStackTrace ();
throw new SWORDException (tMessage, tIOExcpt);
} catch (JDOMException tJDOMExcpt) {
String tMessage = "Couldn't build METS from deposit: " + tJDOMExcpt.toString ();
LOG.error (tMessage);
tJDOMExcpt.printStackTrace ();
throw new SWORDException (tMessage, tJDOMExcpt);
}
}
| 19,687,456 | public void testReadPerMemberSixSmall () throws IOException {
GZIPMembersInputStream gzin = new GZIPMembersInputStream (new ByteArrayInputStream (sixsmall_gz));
gzin.setEofEachMember (true);
for (int i = 0;
i < 3; i ++) {
int count2 = IOUtils.copy (gzin, new NullOutputStream ());
assertEquals ("wrong 1-byte member count", 1, count2);
gzin.nextMember ();
int count3 = IOUtils.copy (gzin, new NullOutputStream ());
assertEquals ("wrong 5-byte member count", 5, count3);
gzin.nextMember ();
}
int countEnd = IOUtils.copy (gzin, new NullOutputStream ());
assertEquals ("wrong eof count", 0, countEnd);
}
| 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,178,914 | private void writeEntry (File file, ZipOutputStream output, File oya) throws IOException {
BufferedInputStream input = new BufferedInputStream (new FileInputStream (file));
String fn = extractRelativeZipPath (file.getAbsolutePath (), oya.getAbsolutePath ());
ZipEntry entry = new ZipEntry (this.convertZipEntrySeparator (fn));
output.putNextEntry (entry);
int b;
while ((b = input.read ()) != - 1) {
output.write (b);
}
input.close ();
output.closeEntry ();
}
| Zip Files | Type-3 (WT3/4) | false |
792,644 | 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!");
}
| 7,119,938 | public void putFile (CompoundName file, FileInputStream fileInput) throws IOException {
File fullDir = new File (REMOTE_BASE_DIR.getCanonicalPath ());
for (int i = 0;
i < file.size () - 1; i ++) fullDir = new File (fullDir, file.get (i));
fullDir.mkdirs ();
File outputFile = new File (fullDir, file.get (file.size () - 1));
FileOutputStream outStream = new FileOutputStream (outputFile);
for (int byteIn = fileInput.read ();
byteIn != - 1; byteIn = fileInput.read ()) outStream.write (byteIn);
fileInput.close ();
outStream.close ();
}
| Copy File | Type-3 (WT3/4) | true |
4,200,038 | public static int getCrc32asInt (byte [] in) {
if (in == null || in.length == 0) return - 1;
CRC32 crc = new CRC32 ();
crc.update (in);
return (int) crc.getValue ();
}
| 11,911,260 | private void readHeader () throws IOException {
CRC32 headCRC = new CRC32 ();
int magic = in.read ();
if (magic < 0) {
eos = true;
return;
}
headCRC.update (magic);
if (magic != (GZIP_MAGIC>> 8)) throw new IOException ("Error in GZIP header, first byte doesn't match");
magic = in.read ();
if (magic != (GZIP_MAGIC & 0xff)) throw new IOException ("Error in GZIP header, second byte doesn't match");
headCRC.update (magic);
int CM = in.read ();
if (CM != 8) throw new IOException ("Error in GZIP header, data not in deflate format");
headCRC.update (CM);
int flags = in.read ();
if (flags < 0) throw new EOFException ("Early EOF in GZIP header");
headCRC.update (flags);
if ((flags & 0xd0) != 0) throw new IOException ("Reserved flag bits in GZIP header != 0");
for (int i = 0;
i < 6; i ++) {
int readByte = in.read ();
if (readByte < 0) throw new EOFException ("Early EOF in GZIP header");
headCRC.update (readByte);
}
if ((flags & FEXTRA) != 0) {
for (int i = 0;
i < 2; i ++) {
int readByte = in.read ();
if (readByte < 0) throw new EOFException ("Early EOF in GZIP header");
headCRC.update (readByte);
}
if (in.read () < 0 || in.read () < 0) throw new EOFException ("Early EOF in GZIP header");
int len1, len2, extraLen;
len1 = in.read ();
len2 = in.read ();
if ((len1 < 0) || (len2 < 0)) throw new EOFException ("Early EOF in GZIP header");
headCRC.update (len1);
headCRC.update (len2);
extraLen = (len1 << 8) | len2;
for (int i = 0;
i < extraLen; i ++) {
int readByte = in.read ();
if (readByte < 0) throw new EOFException ("Early EOF in GZIP header");
headCRC.update (readByte);
}
}
if ((flags & FNAME) != 0) {
int readByte;
while ((readByte = in.read ()) > 0) headCRC.update (readByte);
if (readByte < 0) throw new EOFException ("Early EOF in GZIP file name");
headCRC.update (readByte);
}
if ((flags & FCOMMENT) != 0) {
int readByte;
while ((readByte = in.read ()) > 0) headCRC.update (readByte);
if (readByte < 0) throw new EOFException ("Early EOF in GZIP comment");
headCRC.update (readByte);
}
if ((flags & FHCRC) != 0) {
int tempByte;
int crcval = in.read ();
if (crcval < 0) throw new EOFException ("Early EOF in GZIP header");
tempByte = in.read ();
if (tempByte < 0) throw new EOFException ("Early EOF in GZIP header");
crcval = (crcval << 8) | tempByte;
if (crcval != ((int) headCRC.getValue () & 0xffff)) throw new IOException ("Header CRC value mismatch");
}
readGZIPHeader = true;
}
| CRC32 File Checksum | Type-3 (WT3/4) | false |
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;
}
}
}
| 15,891,912 | public void close () {
logger.debug ("Closing output file.");
outfile.close ();
tempFile.renameTo (new File (fileName));
if (toZIP) {
logger.debug ("ZIPping output file.");
try {
ZipOutputStream zipout = new ZipOutputStream (new FileOutputStream (fileName + ".zip"));
zipout.setLevel (9);
String outfilezipname = fileName.substring (fileName.lastIndexOf (System.getProperty ("file.separator")) + 1);
zipout.putNextEntry (new ZipEntry (outfilezipname));
FileInputStream fis = new FileInputStream (fileName);
byte [] buffer = new byte [65536];
int len;
while ((len = fis.read (buffer)) > 0) {
zipout.write (buffer, 0, len);
}
zipout.close ();
fis.close ();
logger.debug ("ZIPping output file ok.");
logger.debug ("Removing " + fileName);
(new File (fileName)).delete ();
} catch (IOException ex) {
logger.debug ("Error when zipping file", ex);
}
}
}
| Zip Files | Type-3 (WT3/4) | false |
1,751,009 | @BeforeClass
public static void createProblem () throws IOException, ParserConfigurationException, TransformerException {
problem = File.createTempFile ("___prb___", ".problem");
System.out.println ("created temporary problem " + problem);
ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (problem));
PrintStream ps = new PrintStream (zos);
zos.putNextEntry (new ZipEntry ("MANIFEST"));
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance ();
DocumentBuilder builder = builderFactory.newDocumentBuilder ();
Document doc = builder.newDocument ();
Element root = doc.createElement ("resources");
doc.appendChild (root);
Element alias = doc.createElement ("alias");
alias.setAttribute ("path", "STATEMENT");
alias.setAttribute ("target", "statement.txt");
root.appendChild (alias);
Element contents1 = doc.createElement ("contents");
contents1.setAttribute ("path", "ANSWER");
contents1.setTextContent ("42");
root.appendChild (contents1);
Element contents2 = doc.createElement ("contents");
contents2.setAttribute ("path", "STATEMENT EXT");
contents2.setTextContent ("TXT");
root.appendChild (contents2);
Element teacher = doc.createElement ("teacher");
teacher.setAttribute ("path", "ANSWER");
root.appendChild (teacher);
Source source = new DOMSource (doc);
Result result = new StreamResult (zos);
Transformer xformer = TransformerFactory.newInstance ().newTransformer ();
xformer.transform (source, result);
zos.putNextEntry (new ZipEntry ("statement.txt"));
ps.println ("���� ����� ������������ ����� � ����?");
zos.closeEntry ();
zos.close ();
}
| 13,994,366 | public static boolean exportStandalone (String projectDirectory, String destinyJARPath) {
boolean exported = true;
try {
File destinyJarFile = new File (destinyJARPath);
FileOutputStream mergedFile = new FileOutputStream (destinyJarFile);
ZipOutputStream os = new ZipOutputStream (mergedFile);
String manifest = Writer.defaultManifestFile ("es.eucm.eadventure.engine.EAdventureStandalone");
ZipEntry manifestEntry = new ZipEntry ("META-INF/MANIFEST.MF");
os.putNextEntry (manifestEntry);
os.write (manifest.getBytes ());
os.closeEntry ();
os.flush ();
File.mergeZipAndDirToJar ("web/eAdventure_temp.jar", projectDirectory, os);
addNeededLibrariesToJar (os, Controller.getInstance ());
os.close ();
} catch (FileNotFoundException e) {
exported = false;
ReportDialog.GenerateErrorReport (e, true, "UNKNOWNERROR");
} catch (IOException e) {
exported = false;
ReportDialog.GenerateErrorReport (e, true, "UNKNOWNERROR");
}
return exported;
}
| Zip Files | Type-3 (WT3/4) | false |
10,407,191 | @Override
public boolean copy (Document document, Folder folder) throws Exception {
boolean isCopied = false;
if (document.getId () != null && folder.getId () != null) {
Document copiedDoc = new DocumentModel ();
copiedDoc.setValues (document.getValues ());
copiedDoc.setFolder (folder);
copiedDoc.setId (null);
em.persist (copiedDoc);
resourceAuthorityService.applyAuthority (copiedDoc);
List < Preference > preferences = prefService.findAll ();
Preference preference = new PreferenceModel ();
if (preferences != null && ! preferences.isEmpty ()) {
preference = preferences.get (0);
}
String repo = preference.getRepository ();
SimpleDateFormat sdf = new SimpleDateFormat (Constants.DATEFORMAT_YYYYMMDD);
Calendar calendar = Calendar.getInstance ();
StringBuffer sbRepo = new StringBuffer (repo);
sbRepo.append (File.separator);
StringBuffer sbFolder = new StringBuffer (sdf.format (calendar.getTime ()));
sbFolder.append (File.separator).append (calendar.get (Calendar.HOUR_OF_DAY));
File fFolder = new File (sbRepo.append (sbFolder).toString ());
if (! fFolder.exists ()) {
fFolder.mkdirs ();
}
copiedDoc.setLocation (sbFolder.toString ());
em.merge (copiedDoc);
File in = new File (repo + File.separator + document.getLocation () + File.separator + document.getId () + "." + document.getExt ());
File out = new File (fFolder.getAbsolutePath () + File.separator + copiedDoc.getId () + "." + copiedDoc.getExt ());
FileChannel inChannel = new FileInputStream (in).getChannel ();
FileChannel outChannel = new FileOutputStream (out).getChannel ();
try {
inChannel.transferTo (0, inChannel.size (), outChannel);
} catch (IOException e) {
throw e;
} finally {
if (inChannel != null) inChannel.close ();
if (outChannel != null) outChannel.close ();
}
}
return isCopied;
}
| 18,583,832 | private static void copy (File source, File target) throws IOException {
FileInputStream from = null;
FileOutputStream to = null;
try {
from = new FileInputStream (source);
to = new FileOutputStream (target);
byte [] buffer = new byte [4096];
int bytesRead;
while ((bytesRead = from.read (buffer)) != - 1) to.write (buffer, 0, bytesRead);
} finally {
if (from != null) try {
from.close ();
} catch (IOException e) {
}
if (to != null) try {
to.close ();
} catch (IOException e) {
}
}
}
| Copy File | Type-3 (WT3/4) | true |
251,963 | File createJar (File jar, String...entries) throws IOException {
OutputStream out = new FileOutputStream (jar);
try {
JarOutputStream jos = new JarOutputStream (out);
for (String e : entries) {
jos.putNextEntry (new JarEntry (getPathForZipEntry (e)));
jos.write (getBodyForEntry (e).getBytes ());
}
jos.close ();
} finally {
out.close ();
}
return jar;
}
| 23,188,868 | public void run (IProgressMonitor runnerMonitor) throws CoreException {
try {
Map < String, File > projectFiles = new HashMap < String, File > ();
IPath basePath = new Path ("/");
for (File nextLocation : filesToZip) {
projectFiles.putAll (getFilesToZip (nextLocation, basePath, fileFilter));
}
if (projectFiles.isEmpty ()) {
PlatformActivator.logDebug ("Zip file (" + zipFileName + ") not created because there were no files to zip");
return;
}
IPath resultsPath = PlatformActivator.getDefault ().getResultsPath ();
File copyRoot = resultsPath.toFile ();
copyRoot.mkdirs ();
IPath zipFilePath = resultsPath.append (new Path (finalZip));
String zipFileName = zipFilePath.toPortableString ();
ZipOutputStream out = new ZipOutputStream (new FileOutputStream (zipFileName));
try {
out.setLevel (Deflater.DEFAULT_COMPRESSION);
for (String filePath : projectFiles.keySet ()) {
File nextFile = projectFiles.get (filePath);
FileInputStream fin = new FileInputStream (nextFile);
try {
out.putNextEntry (new ZipEntry (filePath));
try {
byte [] bin = new byte [4096];
int bread = fin.read (bin, 0, 4096);
while (bread != - 1) {
out.write (bin, 0, bread);
bread = fin.read (bin, 0, 4096);
}
} finally {
out.closeEntry ();
}
} finally {
fin.close ();
}
}
} finally {
out.close ();
}
} catch (FileNotFoundException e) {
Status error = new Status (Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage (), e);
throw new CoreException (error);
} catch (IOException e) {
Status error = new Status (Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage (), e);
throw new CoreException (error);
}
}
| Zip Files | Type-3 (WT3/4) | false |
3,230,278 | public static long getCRC (String content) {
if (content.length () == 0) return 0;
final java.util.zip.CRC32 crc = new java.util.zip.CRC32 ();
java.io.OutputStream crcOut = new java.io.OutputStream () {
@Override
public void write (int b) throws java.io.IOException {
crc.update (b);
}}
;
try {
new java.io.OutputStreamWriter (crcOut).write (content);
} catch (java.io.IOException e) {
throw new IllegalStateException ("Could not check CRC of message");
}
return crc.getValue ();
}
| 23,677,203 | public static long checksum1 (File file) throws IOException {
CRC32 crc = new CRC32 ();
FileReader fr = new FileReader (file);
int data;
while ((data = fr.read ()) != - 1) {
crc.update (data);
}
fr.close ();
return crc.getValue ();
}
| CRC32 File Checksum | Type-3 (WT3/4) | false |
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;
}
| 18,875,576 | public static < T extends ZipNode > void saveAll (OutputStream outputstream, Collection < T > list, ZipStreamFilter filter) throws Exception {
ZipOutputStream zip_out = new ZipOutputStream (outputstream);
try {
ZipEntry entry = new ZipEntry (".info/info.properties");
entry.setTime (0);
zip_out.putNextEntry (entry);
String info = "filter = " + filter.getClass ().getName () + "\n" + "count = " + list.size () + "\n";
zip_out.write (info.getBytes ());
for (T object : list) {
save (zip_out, object, filter);
}
} catch (Throwable ex) {
ex.printStackTrace ();
} finally {
try {
zip_out.close ();
} catch (IOException e) {
}
}
}
| Zip Files | Type-3 (WT3/4) | false |
1,936,137 | public void preparaEscrita (DadosSeriais dados, String dir) throws BasicException {
String idArquivo = dados.getIdColeta ().toString ();
if (dados.getIdResumo () != null) {
idArquivo += "_" + dados.getIdResumo ().toString ();
}
if (dir == null || dir.trim ().equals ("")) {
throw BasicException.errorHandling ("Diret�rio Imagem de Dados n�o foi definido.", "msgErroNaoExisteDiretorioImagem", new String [] {}, log);
}
try {
fos = new FileOutputStream (new File (dir.trim (), "pdump." + idArquivo + ".data.xml.zip"));
} catch (FileNotFoundException e) {
throw BasicException.errorHandling ("Erro ao abrir arquivo de dados xml para escrita", "msgErroCriarArquivoDadosXML", e, log);
}
zipOutputStream = new ZipOutputStream (fos);
zipOutputStream.setLevel (Deflater.DEFAULT_COMPRESSION);
try {
zipOutputStream.putNextEntry (new ZipEntry ("pdump." + idArquivo + ".data.xml"));
xmlWriter = XMLOutputFactory.newInstance ().createXMLStreamWriter (zipOutputStream, ENCODING);
} catch (Exception e) {
throw BasicException.errorHandling ("Erro ao criar entrada em arquivo compactado", "msgErroCriarEntradaZipArquivoDadosXML", e, log);
}
XMLStreamWriter osw = null;
try {
xmlWriter = XMLOutputFactory.newInstance ().createXMLStreamWriter (zipOutputStream, ENCODING);
} catch (Exception e) {
throw BasicException.errorHandling ("Erro ao criar entrada em arquivo compactado", "msgErroCriarEntradaZipArquivoDadosXML", e, log);
}
SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss");
if (dados.getTipos ().size () > 0) {
tipos = new int [dados.getTipos ().size ()];
for (int c = 0;
c < dados.getTipos ().size (); c ++) {
String tipo = dados.getTipos ().get (c);
if (tipo.equals (LIT_INTEIRO)) {
tipos [c] = INTEIRO;
} else if (tipo.equals (LIT_DECIMAL)) {
tipos [c] = DECIMAL;
} else if (tipo.equals (LIT_DATA)) {
tipos [c] = DATA;
} else {
tipos [c] = TEXTO;
}
}
}
try {
xmlWriter.writeStartDocument (ENCODING, "1.0");
xmlWriter.writeStartElement ("coleta");
xmlWriter.writeAttribute ("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlWriter.writeAttribute ("xsi:noNamespaceSchemaLocation", "http://www.pingifes.lcc.ufmg.br/dtd/pingifes_dados_seriais.xsd");
xmlWriter.writeStartElement ("id");
xmlWriter.writeCharacters (idArquivo);
xmlWriter.writeEndElement ();
xmlWriter.writeStartElement ("data");
xmlWriter.writeCharacters (dateFormat.format (dados.getDataColeta ()));
xmlWriter.writeEndElement ();
xmlWriter.writeStartElement ("sql");
xmlWriter.writeCData (dados.getSql ());
xmlWriter.writeEndElement ();
xmlWriter.writeStartElement ("cabecalho");
for (int c = 0;
c < dados.getCabecalho ().size (); c ++) {
xmlWriter.writeStartElement ("nome");
xmlWriter.writeAttribute ("tipo", dados.getTipos ().get (c));
xmlWriter.writeCharacters (dados.getCabecalho ().get (c));
xmlWriter.writeEndElement ();
}
xmlWriter.writeEndElement ();
xmlWriter.writeStartElement ("quantidade");
xmlWriter.writeCharacters ("" + dados.getQuantidade ());
xmlWriter.writeEndElement ();
xmlWriter.writeStartElement ("dados");
} catch (XMLStreamException e) {
throw BasicException.errorHandling ("Erro ao escrever dados em arquivo compactado", "msgErroEscreverArquivoDadosXML", e, log);
}
calculadorHash = new CalculaHash ();
}
| 11,514,192 | private void zipDir (File dir, String jarEntry, JarOutputStream jos) throws IOException {
String [] dirList = dir.list ();
for (int i = 0;
i < dirList.length; i ++) {
File f = new File (dir, dirList [i]);
if (f.isDirectory ()) {
zipDir (f, jarEntry + dirList [i] + File.separatorChar, jos);
continue;
}
FileInputStream fis = new FileInputStream (f);
ZipEntry anEntry = new ZipEntry (jarEntry + dirList [i]);
jos.putNextEntry (anEntry);
byte [] readBuffer = new byte [2156];
int bytesIn = 0;
while ((bytesIn = fis.read (readBuffer)) != - 1) {
jos.write (readBuffer, 0, bytesIn);
}
fis.close ();
}
}
| 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 {
}
}
| 9,161,482 | public static void addToJar (JarOutputStream jos, JarFile jf) throws IOException {
Enumeration e = jf.entries ();
while (e.hasMoreElements ()) {
ZipEntry je = (ZipEntry) e.nextElement ();
InputStream io = jf.getInputStream (je);
byte b [] = new byte [4096];
int read = 0;
try {
jos.putNextEntry (je);
while ((read = io.read (b, 0, 4096)) != - 1) {
jos.write (b, 0, read);
}
} catch (ZipException ze) {
throw ze;
}
}
}
| Zip Files | 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 ();
}
}
| 8,703,701 | private byte [] injectModifiedText () {
byte [] buffer = new byte [BUFFER_SIZE];
boolean contentFound = false;
boolean stylesFound = false;
ByteArrayOutputStream out = new ByteArrayOutputStream (2 * fileData.length);
ZipOutputStream zipOutputStream = new ZipOutputStream (out);
ZipInputStream zipInputStream = new ZipInputStream (new ByteArrayInputStream (fileData));
try {
ZipEntry zipEntry = zipInputStream.getNextEntry ();
while (zipEntry != null) {
zipOutputStream.putNextEntry (new ZipEntry (zipEntry.getName ()));
if (content != null && zipEntry.getName ().equals ("content.xml")) {
contentFound = true;
if (log.isTraceEnabled ()) {
log.trace ("Write content.xml to fileData\n" + content);
} else if (log.isDebugEnabled ()) {
log.trace ("Write content.xml to fileData, length = " + content.length ());
}
zipOutputStream.write (content.getBytes ("UTF-8"));
} else if (styles != null && zipEntry.getName ().equals ("styles.xml")) {
stylesFound = true;
if (log.isTraceEnabled ()) {
log.trace ("Write styles.xml to fileData\n" + styles);
} else if (log.isDebugEnabled ()) {
log.debug ("Write styles.xml to fileData, length = " + styles.length ());
}
zipOutputStream.write (styles.getBytes ("UTF-8"));
} else {
int read = zipInputStream.read (buffer);
while (read > - 1) {
zipOutputStream.write (buffer, 0, read);
read = zipInputStream.read (buffer);
}
}
zipEntry = zipInputStream.getNextEntry ();
}
} catch (IOException ex) {
log.error ("Exception while injecting content and styles into odt", ex);
throw new IllegalArgumentException ("fileData is probably not an odt file: " + ex);
} finally {
IOUtils.closeQuietly (zipInputStream);
IOUtils.closeQuietly (zipOutputStream);
}
if (content != null && ! contentFound) {
log.error ("fileData is not an odt file, no content.xml found, throwing exception.");
throw new IllegalArgumentException ("fileData is not an odt file, no content.xml found");
}
if (styles != null && ! stylesFound) {
log.error ("fileData is not an odt file, no styles.xml found, throwing exception.");
throw new IllegalArgumentException ("fileData is not an odt file, no styles.xml found");
}
byte [] result = out.toByteArray ();
if (log.isDebugEnabled ()) {
log.debug ("Injected content. File data changed from " + fileData.length + " bytes to " + result.length + " bytes.");
}
return result;
}
| Zip Files | Type-3 (WT3/4) | false |
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 ();
}
| 18,195,007 | private void zipFiles () throws ZipException, IOException {
ZipOutputStream zipOuputStream = new ZipOutputStream (new FileOutputStream (zipFile));
for (File sourceDir : sourceDirs) {
File [] sourceFiles = sourceDir.listFiles (new SourceFileFilter ());
if (sourceFiles != null) {
for (File sourceFile : sourceFiles) {
ZipEntry zipEntry = new ZipEntry (sourceFile.getName ());
zipOuputStream.putNextEntry (zipEntry);
if (logger.isInfoEnabled ()) {
logger.info ("Adding zip entry " + sourceFile.getAbsolutePath () + " to " + zipFile.getAbsolutePath ());
}
if (sourceFile.length () > BYTE_ARRAY_BUFF_SIZE) {
BufferedInputStream bis = new BufferedInputStream (new FileInputStream (sourceFile), BYTE_ARRAY_BUFF_SIZE);
byte [] buf = new byte [BYTE_ARRAY_BUFF_SIZE];
int b;
while ((b = bis.read (buf, 0, BYTE_ARRAY_BUFF_SIZE)) != - 1) {
zipOuputStream.write (buf, 0, b);
}
bis.close ();
} else {
byte [] fileContents = FileUtil.getFileContentsAsByteArray (sourceFile);
zipOuputStream.write (fileContents);
}
zipOuputStream.closeEntry ();
}
}
}
zipOuputStream.close ();
}
| Zip Files | Type-3 (WT3/4) | false |
2,096,403 | static void writeZipEntry (final byte [] data, final ZipOutputStream out, final ZipEntry entry, final boolean isCopy) throws IOException {
if (isCopy) {
out.putNextEntry (entry);
try {
out.write (data);
} finally {
out.closeEntry ();
}
} else {
final ZipEntry entryCopy = new ZipEntry (entry.getName ());
entryCopy.setTime (entry.getTime ());
entryCopy.setMethod (ZipOutputStream.STORED);
entryCopy.setSize (data.length);
entryCopy.setCompressedSize (data.length);
final CRC32 crc = new CRC32 ();
crc.update (data);
entryCopy.setCrc (crc.getValue ());
out.putNextEntry (entryCopy);
try {
out.write (data);
} finally {
out.closeEntry ();
}
}
}
| 6,650,088 | public int calculateCRC () {
CRC32 crc = new CRC32 ();
crc.reset ();
crc.update (getData (), 2, getData ().length - 2);
return (short) (crc.getValue ());
}
| CRC32 File Checksum | Type-3 (WT3/4) | false |
1,177,247 | @Override
public void write (DataOutput dataOutput, byte [] object) throws IOException {
ZipOutputStream zos = new ZipOutputStream (new DataOutputOutputStream (dataOutput));
zos.setMethod (ZipOutputStream.DEFLATED);
zos.putNextEntry (new ZipEntry ("a"));
zos.write (object, 0, object.length);
zos.finish ();
zos.close ();
}
| 15,468,308 | private void archiveDirectory (ZipOutputStream out, File dir, String path) throws IOException {
byte [] buf = new byte [16384];
File [] files = dir.listFiles ();
if (files.length > 0) {
for (int x = 0;
x < files.length; x ++) {
if (files [x].isFile ()) {
FileInputStream in = new FileInputStream (files [x]);
out.putNextEntry (new ZipEntry (path + files [x].getName ()));
int len;
while ((len = in.read (buf)) > 0) {
out.write (buf, 0, len);
}
out.closeEntry ();
in.close ();
} else {
archiveDirectory (out, files [x], path + files [x].getName () + File.separator);
}
}
} else {
out.putNextEntry (new ZipEntry (path));
out.closeEntry ();
}
}
| Zip Files | Type-3 (WT3/4) | true |
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 ();
}
}
| 3,720,682 | @Override
protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ZipOutputStream zipout = new ZipOutputStream (resp.getOutputStream ());
ZipOutputStream zipout2 = new ZipOutputStream (new FileOutputStream (new File ("c:/t.zip")));
for (int i = 0;
i < 200; i ++) {
BufferedImage img = new BufferedImage (800 + i, 600 + i, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) img.getGraphics ();
g.setPaint (new GradientPaint (0, 0, Color.YELLOW, img.getWidth () - 1, img.getHeight () - 1, Color.BLUE, true));
g.fillRect (0, 0, img.getWidth (), img.getHeight ());
for (int t = 0;
t < img.getHeight (); t += 10) {
g.setColor (new Color (t + 1 * 100 + 1 * 10000));
g.drawLine (0, t, img.getWidth (), t);
}
g.dispose ();
ZipEntry entry = new ZipEntry ("hoge" + i + ".bmp");
zipout.putNextEntry (entry);
ImageIO.write (img, "bmp", zipout);
ZipEntry entry2 = new ZipEntry ("hoge" + i + ".bmp");
zipout2.putNextEntry (entry2);
ImageIO.write (img, "bmp", zipout2);
}
zipout.close ();
zipout2.close ();
}
| Zip Files | Type-3 (WT3/4) | false |
6,457,199 | protected boolean doRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = request.getPathInfo ();
if (! path.startsWith (alias)) {
throw new ServletException ("Path '" + path + "' does not start with registered alias '" + alias + "'");
}
String internal;
if (alias.equals ("/")) {
internal = name + path;
} else {
internal = name + path.substring (alias.length (), path.length ());
}
URL resource = httpContext.getResource (internal);
if (resource == null) {
return false;
}
String mimeType = servletContext.getMimeType (internal);
if (mimeType != null) {
response.setContentType (mimeType);
}
InputStream is = resource.openStream ();
OutputStream os = response.getOutputStream ();
IOUtils.copyAndClose (is, os);
return true;
}
| 16,227,459 | public CmsSetupTestResult execute (CmsSetupBean setupBean) {
CmsSetupTestResult testResult = new CmsSetupTestResult (this);
String basePath = setupBean.getWebAppRfsPath ();
if (! basePath.endsWith (File.separator)) {
basePath += File.separator;
}
File file1;
Random rnd = new Random ();
do {
file1 = new File (basePath + "test" + rnd.nextInt (1000));
} while (file1.exists ());
boolean success = false;
try {
file1.createNewFile ();
FileWriter fw = new FileWriter (file1);
fw.write ("aA1");
fw.close ();
success = true;
FileReader fr = new FileReader (file1);
success = success && (fr.read () == 'a');
success = success && (fr.read () == 'A');
success = success && (fr.read () == '1');
success = success && (fr.read () == - 1);
fr.close ();
success = file1.delete ();
success = ! file1.exists ();
} catch (Exception e) {
success = false;
}
if (! success) {
testResult.setRed ();
testResult.setInfo ("OpenCms cannot be installed without read and write privileges for path " + basePath + "! Please check you are running your servlet container with the right user and privileges.");
testResult.setHelp ("Not enough permissions to create/read/write a file");
testResult.setResult (RESULT_FAILED);
} else {
testResult.setGreen ();
testResult.setResult (RESULT_PASSED);
}
return testResult;
}
| Copy File | Type-3 (WT3/4) | true |
1,446,726 | private void backupPageStore (ZipOutputStream out, String fileName, PageStore store) throws SQLException, IOException {
Database db = session.getDatabase ();
fileName = FileUtils.getFileName (fileName);
out.putNextEntry (new ZipEntry (fileName));
int max = store.getPageCount ();
int pos = 0;
while (true) {
pos = store.copyDirect (pos, out);
if (pos < 0) {
break;
}
db.setProgress (DatabaseEventListener.STATE_BACKUP_FILE, fileName, pos, max);
}
out.closeEntry ();
}
| 23,421,923 | void writeRawDataFile (RawDataFileImpl rawDataFile, int number) throws IOException, TransformerConfigurationException, SAXException {
numOfScans = rawDataFile.getNumOfScans ();
dataPointsOffsets = rawDataFile.getDataPointsOffsets ();
dataPointsLengths = rawDataFile.getDataPointsLengths ();
consolidatedDataPointsOffsets = new TreeMap < Integer, Long > ();
logger.info ("Saving data points of: " + rawDataFile.getName ());
String rawDataSavedName = "Raw data file #" + number + " " + rawDataFile.getName ();
zipOutputStream.putNextEntry (new ZipEntry (rawDataSavedName + ".scans"));
long newOffset = 0;
byte buffer [] = new byte [1 << 20];
RandomAccessFile dataPointsFile = rawDataFile.getDataPointsFile ();
for (Integer storageID : dataPointsOffsets.keySet ()) {
if (canceled) return;
final long offset = dataPointsOffsets.get (storageID);
dataPointsFile.seek (offset);
final int bytes = dataPointsLengths.get (storageID) * 4 * 2;
consolidatedDataPointsOffsets.put (storageID, newOffset);
if (buffer.length < bytes) {
buffer = new byte [bytes * 2];
}
dataPointsFile.read (buffer, 0, bytes);
zipOutputStream.write (buffer, 0, bytes);
newOffset += bytes;
progress = 0.9 * ((double) offset / dataPointsFile.length ());
}
if (canceled) return;
logger.info ("Saving raw data description of: " + rawDataFile.getName ());
zipOutputStream.putNextEntry (new ZipEntry (rawDataSavedName + ".xml"));
OutputStream finalStream = zipOutputStream;
StreamResult streamResult = new StreamResult (finalStream);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance ();
TransformerHandler hd = tf.newTransformerHandler ();
Transformer serializer = hd.getTransformer ();
serializer.setOutputProperty (OutputKeys.INDENT, "yes");
serializer.setOutputProperty (OutputKeys.ENCODING, "UTF-8");
hd.setResult (streamResult);
hd.startDocument ();
saveRawDataInformation (rawDataFile, hd);
hd.endDocument ();
}
| Zip Files | Type-3 (WT3/4) | false |
5,271,797 | private void loadMap () {
final String wordList = "vietwordlist.txt";
try {
File dataFile = new File (supportDir, wordList);
if (! dataFile.exists ()) {
final ReadableByteChannel input = Channels.newChannel (ClassLoader.getSystemResourceAsStream ("dict/" + dataFile.getName ()));
final FileChannel output = new FileOutputStream (dataFile).getChannel ();
output.transferFrom (input, 0, 1000000L);
input.close ();
output.close ();
}
long fileLastModified = dataFile.lastModified ();
if (map == null) {
map = new HashMap ();
} else {
if (fileLastModified <= mapLastModified) {
return;
}
map.clear ();
}
mapLastModified = fileLastModified;
BufferedReader bs = new BufferedReader (new InputStreamReader (new FileInputStream (dataFile), "UTF-8"));
String accented;
while ((accented = bs.readLine ()) != null) {
String plain = VietUtilities.stripDiacritics (accented);
map.put (plain.toLowerCase (), accented);
}
bs.close ();
} catch (IOException e) {
map = null;
e.printStackTrace ();
JOptionPane.showMessageDialog (this, myResources.getString ("Cannot_find_\"") + wordList + myResources.getString ("\"_in\n") + supportDir.toString (), VietPad.APP_NAME, JOptionPane.ERROR_MESSAGE);
}
}
| 10,478,671 | private void copyFile (File sourcefile, File targetfile) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream (new FileInputStream (sourcefile));
out = new BufferedOutputStream (new FileOutputStream (targetfile));
byte [] buffer = new byte [4096];
int bytesread = 0;
while ((bytesread = in.read (buffer)) >= 0) {
out.write (buffer, 0, bytesread);
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
try {
if (in != null) {
in.close ();
}
if (out != null) {
out.close ();
}
} catch (IOException e) {
e.printStackTrace ();
}
}
}
| Copy File | Type-3 (WT3/4) | true |
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;
}
| 5,245,205 | private void writeDynData (final 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 |
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;
}
| 14,203,228 | private void writeEntry (byte [] data, String name, ZipOutputStream outStream) throws IOException {
ZipEntry entry = new ZipEntry (name);
entry.setSize (data.length);
entry.setTime (System.currentTimeMillis ());
if (outStream != null) {
outStream.putNextEntry (entry);
outStream.write (data);
outStream.closeEntry ();
}
}
| Zip Files | Type-3 (WT3/4) | false |
1,287,866 | private void cleanupStagingEnvironment (File stagingDir) throws FileUpdateException {
if (stagingDir != null && stagingDir.exists () && stagingDir.isDirectory ()) {
File [] files = stagingDir.listFiles ();
for (int i = 0;
i < files.length; i ++) {
File f = files [i];
if (! f.delete ()) {
logger.error ("Could not delete: " + f.getAbsolutePath ());
throw new SessionEnvironmentException ("Could not delete: " + f.getAbsolutePath ());
}
}
if (stagingDir.exists ()) {
if (stagingDir.delete ()) {
logger.debug (stagingDir + " was successfully deleted");
} else {
logger.error ("Could not clean up staging directory: " + stagingDir.getAbsolutePath ());
throw new SessionEnvironmentException ("Could not remove directory: " + stagingDir.getAbsolutePath ());
}
}
} else {
throw new SessionEnvironmentException ("Staging directory undefined, does not exist, or is not a directory");
}
}
| 2,641,959 | public static boolean deleteDir (File dir) {
if (dir.exists ()) {
File [] files = dir.listFiles ();
for (int i = 0;
i < files.length; i ++) {
if (files [i].isDirectory ()) {
deleteDir (files [i]);
} else {
files [i].delete ();
}
}
}
return (dir.delete ());
}
| Delete Folder and Contents | Type-3 (WT3/4) | false |
112,054 | private void exportAllSettings (HTTPurl urlData, OutputStream outStream) throws Exception {
CaptureDeviceList devList = CaptureDeviceList.getInstance ();
if (devList.getActiveDeviceCount () > 0) {
PageTemplate template = new PageTemplate (store.getProperty ("path.template") + File.separator + "SettingsLoad.html");
StringBuffer buff = new StringBuffer ();
buff.append ("<tr><td><img border=0 src='/images/stop.png' align='absmiddle' width='24' height='24'></td><td>Can not save settings while a capture is in progress.</td></tr>");
template.replaceAll ("$result", buff.toString ());
outStream.write (template.getPageBytes ());
return;
}
boolean matchList = "true".equalsIgnoreCase (urlData.getParameter ("MatchList"));
boolean autoAdd = "true".equalsIgnoreCase (urlData.getParameter ("AutoAdd"));
boolean channelMapping = "true".equalsIgnoreCase (urlData.getParameter ("ChannelMapping"));
boolean deviceSelection = "true".equalsIgnoreCase (urlData.getParameter ("DeviceSelection"));
boolean agentMapping = "true".equalsIgnoreCase (urlData.getParameter ("AgentMapping"));
boolean channels = "true".equalsIgnoreCase (urlData.getParameter ("Channels"));
boolean tasks = "true".equalsIgnoreCase (urlData.getParameter ("Tasks"));
boolean systemProp = "true".equalsIgnoreCase (urlData.getParameter ("SystemProp"));
boolean schedules = "true".equalsIgnoreCase (urlData.getParameter ("Schedules"));
boolean authSettings = "true".equalsIgnoreCase (urlData.getParameter ("AuthSettings"));
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream ();
ZipOutputStream out = new ZipOutputStream (bytesOut);
out.setComment ("TV Scheduler Pro Settings file (Version: 1.0)");
if (channels) {
out.putNextEntry (new ZipEntry ("Channels.xml"));
StringBuffer channelData = new StringBuffer ();
store.saveChannels (channelData);
byte [] channelBytes = channelData.toString ().getBytes ("UTF-8");
out.write (channelBytes);
out.closeEntry ();
}
if (matchList) {
out.putNextEntry (new ZipEntry ("MatchList.xml"));
StringBuffer matchData = new StringBuffer ();
store.saveMatchList (matchData);
byte [] matchBytes = matchData.toString ().getBytes ("UTF-8");
out.write (matchBytes);
out.closeEntry ();
}
if (autoAdd) {
out.putNextEntry (new ZipEntry ("EpgAutoAdd.xml"));
StringBuffer addData = new StringBuffer ();
store.saveEpgAutoList (addData);
byte [] addBytes = addData.toString ().getBytes ("UTF-8");
out.write (addBytes);
out.closeEntry ();
}
if (tasks) {
out.putNextEntry (new ZipEntry ("Tasks.xml"));
StringBuffer taskData = new StringBuffer ();
store.saveTaskList (taskData);
byte [] taskBytes = taskData.toString ().getBytes ("UTF-8");
out.write (taskBytes);
out.closeEntry ();
}
if (channelMapping) {
GuideStore guideStore = GuideStore.getInstance ();
out.putNextEntry (new ZipEntry ("ChannelMap.sof"));
ByteArrayOutputStream chanMapBytes = new ByteArrayOutputStream ();
guideStore.saveChannelMap (chanMapBytes);
out.write (chanMapBytes.toByteArray ());
out.closeEntry ();
}
if (deviceSelection) {
out.putNextEntry (new ZipEntry ("CaptureDevices.sof"));
ByteArrayOutputStream deviceBytes = new ByteArrayOutputStream ();
devList.saveDeviceList (deviceBytes);
out.write (deviceBytes.toByteArray ());
out.closeEntry ();
}
if (agentMapping) {
out.putNextEntry (new ZipEntry ("AgentMap.sof"));
ByteArrayOutputStream agentMapBytes = new ByteArrayOutputStream ();
store.saveAgentToThemeMap (agentMapBytes);
out.write (agentMapBytes.toByteArray ());
out.closeEntry ();
}
if (schedules) {
out.putNextEntry (new ZipEntry ("Times.sof"));
ByteArrayOutputStream timesBytes = new ByteArrayOutputStream ();
store.saveSchedule (timesBytes);
out.write (timesBytes.toByteArray ());
out.closeEntry ();
}
if (systemProp) {
HashMap < String, String > serverProp = new HashMap < String, String > ();
serverProp.put ("epg.showunlinked", store.getProperty ("epg.showunlinked"));
serverProp.put ("path.theme", store.getProperty ("path.theme"));
serverProp.put ("path.theme.epg", store.getProperty ("path.theme.epg"));
serverProp.put ("capture.path", store.getProperty ("capture.path"));
serverProp.put ("capture.averagedatarate", store.getProperty ("capture.averagedatarate"));
serverProp.put ("capture.autoselectmethod", store.getProperty ("capture.autoselectmethod"));
serverProp.put ("capture.minspacesoft", store.getProperty ("capture.minspacesoft"));
serverProp.put ("capture.includecalculatedusage", store.getProperty ("capture.includecalculatedusage"));
serverProp.put ("capture.deftype", store.getProperty ("capture.deftype"));
serverProp.put ("capture.filename.patterns", store.getProperty ("capture.filename.patterns"));
serverProp.put ("capture.path.details", store.getProperty ("capture.path.details"));
serverProp.put ("capture.capturefailedtimeout", store.getProperty ("capture.capturefailedtimeout"));
serverProp.put ("schedule.buffer.start", store.getProperty ("schedule.buffer.start"));
serverProp.put ("schedule.buffer.end", store.getProperty ("schedule.buffer.end"));
serverProp.put ("schedule.buffer.end.epg", store.getProperty ("schedule.buffer.end.epg"));
serverProp.put ("schedule.wake.system", store.getProperty ("schedule.wake.system"));
serverProp.put ("schedule.overlap", store.getProperty ("schedule.overlap"));
serverProp.put ("sch.autodel.action", store.getProperty ("sch.autodel.action"));
serverProp.put ("sch.autodel.time", store.getProperty ("sch.autodel.time"));
serverProp.put ("guide.source.http.pwd", store.getProperty ("guide.source.http.pwd"));
serverProp.put ("guide.source.xml.channelList", store.getProperty ("guide.source.xml.channelList"));
serverProp.put ("guide.source.type", store.getProperty ("guide.source.type"));
serverProp.put ("guide.source.http", store.getProperty ("guide.source.http"));
serverProp.put ("guide.source.file", store.getProperty ("guide.source.file"));
serverProp.put ("guide.action.name", store.getProperty ("guide.action.name"));
serverProp.put ("guide.source.http.usr", store.getProperty ("guide.source.http.usr"));
serverProp.put ("guide.source.schedule", store.getProperty ("guide.source.schedule"));
serverProp.put ("guide.warn.overlap", store.getProperty ("guide.warn.overlap"));
serverProp.put ("proxy.server", store.getProperty ("proxy.server"));
serverProp.put ("proxy.port", store.getProperty ("proxy.port"));
serverProp.put ("proxy.server.usr", store.getProperty ("proxy.server.usr"));
serverProp.put ("proxy.server.pwd", store.getProperty ("proxy.server.pwd"));
serverProp.put ("email.server", store.getProperty ("email.server"));
serverProp.put ("email.from.name", store.getProperty ("email.from.name"));
serverProp.put ("email.to", store.getProperty ("email.to"));
serverProp.put ("email.from", store.getProperty ("email.from"));
serverProp.put ("email.send.weeklyreport", store.getProperty ("email.send.weeklyreport"));
serverProp.put ("email.send.capfinished", store.getProperty ("email.send.capfinished"));
serverProp.put ("email.send.epgloaded", store.getProperty ("email.send.epgloaded"));
serverProp.put ("email.send.onwarning", store.getProperty ("email.send.onwarning"));
serverProp.put ("email.send.freespacelow", store.getProperty ("email.send.freespacelow"));
serverProp.put ("email.send.serverstarted", store.getProperty ("email.send.serverstarted"));
serverProp.put ("tasks.deftask", store.getProperty ("tasks.deftask"));
serverProp.put ("tasks.pretask", store.getProperty ("tasks.pretask"));
serverProp.put ("tasks.nodataerrortask", store.getProperty ("tasks.nodataerrortask"));
serverProp.put ("tasks.starterrortask", store.getProperty ("tasks.starterrortask"));
serverProp.put ("filebrowser.dirsattop", store.getProperty ("filebrowser.dirsattop"));
serverProp.put ("filebrowser.masks", store.getProperty ("filebrowser.masks"));
serverProp.put ("server.kbled", store.getProperty ("server.kbled"));
ByteArrayOutputStream serverpropBytes = new ByteArrayOutputStream ();
ObjectOutputStream oos = new ObjectOutputStream (serverpropBytes);
oos.writeObject (serverProp);
oos.close ();
out.putNextEntry (new ZipEntry ("ServerProperties.sof"));
out.write (serverpropBytes.toByteArray ());
out.closeEntry ();
}
if (authSettings) {
File authFile = new File (store.getProperty ("path.data") + File.separator + "authentication.prop");
if (authFile.exists ()) {
out.putNextEntry (new ZipEntry ("authentication.prop"));
FileInputStream is = new FileInputStream (authFile);
byte [] buff = new byte [1024];
int read = is.read (buff);
while (read != - 1) {
out.write (buff, 0, read);
read = is.read (buff);
}
out.closeEntry ();
is.close ();
}
}
out.flush ();
out.close ();
StringBuffer header = new StringBuffer ();
header.append ("HTTP/1.1 200 OK\n");
header.append ("Content-Type: application/zip\n");
header.append ("Content-Length: " + bytesOut.size () + "\n");
header.append ("Content-Disposition: attachment; filename=\"TV Scheduler Pro Settings.zip\"\n");
DateFormat df = new SimpleDateFormat ("EEE, dd MMM yyyy hh:mm:ss 'GMT'", new Locale ("En", "Us", "Unix"));
header.append ("Last-Modified: " + df.format (new Date ()) + "\n");
header.append ("\n");
outStream.write (header.toString ().getBytes ());
ByteArrayInputStream zipStream = new ByteArrayInputStream (bytesOut.toByteArray ());
byte [] bytes = new byte [4096];
int read = zipStream.read (bytes);
while (read > - 1) {
outStream.write (bytes, 0, read);
outStream.flush ();
read = zipStream.read (bytes);
}
}
| 21,830,091 | public void testImport () throws Exception {
Init.importEverything ();
String filename = Framework.onlyInstance ().getAppHomeDir () + "sts-sql/example.stz";
ZipOutputStream zo = new ZipOutputStream (new FileOutputStream (filename));
StringWriter swt;
byte [] data;
swt = new StringWriter ();
ExportCSVRegattaWizard erw = new ExportCSVRegattaWizard (new JFrame ());
erw.doExport (swt);
data = swt.toString ().getBytes ();
zo.putNextEntry (new ZipEntry ("regatta.csv"));
zo.write (data);
swt = new StringWriter ();
ExportCSVEntriesWizard eew = new ExportCSVEntriesWizard (new JFrame ());
eew.doExport (swt);
data = swt.toString ().getBytes ();
zo.putNextEntry (new ZipEntry ("entries.csv"));
zo.write (data);
swt = new StringWriter ();
ExportCSVRaceDataWizard edw = new ExportCSVRaceDataWizard (new JFrame ());
edw.doExport (swt);
data = swt.toString ().getBytes ();
zo.putNextEntry (new ZipEntry ("race-data.csv"));
zo.write (data);
zo.close ();
}
| Zip Files | Type-3 (WT3/4) | true |
233,637 | public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext ();
String forw = null;
try {
int maxUploadSize = 50000000;
MultipartRequest multi = new MultipartRequest (request, ".", maxUploadSize);
String descrizione = multi.getParameter ("text");
File myFile = multi.getFile ("uploadfile");
String filePath = multi.getOriginalFileName ("uploadfile");
String path = "C:\\files\\";
try {
FileInputStream inStream = new FileInputStream (myFile);
FileOutputStream outStream = new FileOutputStream (path + myFile.getName ());
while (inStream.available () > 0) {
outStream.write (inStream.read ());
}
inStream.close ();
outStream.close ();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace ();
} catch (IOException ioe) {
ioe.printStackTrace ();
}
forw = "../sendDoc.jsp";
request.setAttribute ("contentType", context.getMimeType (path + myFile.getName ()));
request.setAttribute ("text", descrizione);
request.setAttribute ("path", path + myFile.getName ());
request.setAttribute ("size", Long.toString (myFile.length ()) + " Bytes");
RequestDispatcher rd = request.getRequestDispatcher (forw);
rd.forward (request, response);
} catch (Exception e) {
e.printStackTrace ();
}
}
| 21,931,071 | public static void writeToPetrify (TransitionSystem ts, Writer bw) throws IOException {
File temp = new File ("_temp");
BufferedWriter tw = new BufferedWriter (new FileWriter (temp));
BufferedReader tr = new BufferedReader (new FileReader (temp));
HashSet < ModelGraphVertex > sources = new HashSet < ModelGraphVertex > ();
HashSet < ModelGraphVertex > dests = new HashSet < ModelGraphVertex > ();
ArrayList transitions = ts.getEdges ();
HashSet < String > events = new HashSet < String > ();
for (int i = 0;
i < transitions.size (); i ++) {
TransitionSystemEdge transition = (TransitionSystemEdge) transitions.get (i);
events.add (replaceBadSymbols (transition.getIdentifier ()));
sources.add (transition.getSource ());
dests.add (transition.getDest ());
if (ts.getStateNameFlag () == TransitionSystem.ID) {
tw.write ("s" + transition.getSource ().getId () + " ");
tw.write (replaceBadSymbols (transition.getIdentifier ()) + " ");
tw.write ("s" + transition.getDest ().getId () + "\n");
} else {
tw.write (replaceBadSymbols (transition.getSource ().getIdentifier ()) + " ");
tw.write (replaceBadSymbols (transition.getIdentifier ()) + " ");
tw.write (replaceBadSymbols (transition.getDest ().getIdentifier ()) + "\n");
}
}
tw.close ();
bw.write (".model " + ts.getName ().replaceAll (" ", "_") + "\n");
bw.write (".dummy ");
Iterator it = events.iterator ();
while (it.hasNext ()) bw.write (it.next () + " ");
bw.write ("\n");
bw.write (".state graph" + "\n");
int c;
while ((c = tr.read ()) != - 1) bw.write (c);
tr.close ();
temp.delete ();
for (ModelGraphVertex dest : dests) {
if (sources.contains (dest)) {
sources.remove (dest);
}
}
ModelGraphVertex source = sources.isEmpty () ? null : sources.iterator ().next ();
if (ts.getStateNameFlag () == TransitionSystem.ID) {
if (! ts.hasExplicitEnd ()) bw.write (".marking {s0}" + "\n");
else bw.write (".marking {s" + source.getId () + "}\n");
} else if (source != null) {
bw.write (".marking {" + replaceBadSymbols (source.getIdentifier ()) + "}\n");
}
bw.write (".end");
}
| 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 ();
}
| 20,339,695 | private void addToZip (String path, String srcFile, ZipOutputStream zip) {
File folder = new File (srcFile);
if (folder.isDirectory ()) {
this.addFolderToZip (path, srcFile, zip);
} else {
try {
boolean includeFile = false;
if (this.excludePattern == null) {
includeFile = true;
} else {
if (srcFile.contains (this.excludePattern)) {
includeFile = false;
} else {
includeFile = true;
}
}
if (includeFile == true) {
this.zipMonitor.setNumberNextFile ();
this.zipMonitor.setCurrentJobFile (srcFile);
if (zipMonitor.isCanceled ()) {
return;
}
FileInputStream in = new FileInputStream (srcFile);
zip.putNextEntry (new ZipEntry (path + File.separator + folder.getName ()));
byte [] buf = new byte [1024];
int len;
while ((len = in.read (buf)) > 0) {
zip.write (buf, 0, len);
}
}
} catch (Exception ex) {
ex.printStackTrace ();
}
}
}
| Zip Files | Type-3 (WT3/4) | false |
1,803,586 | private Service getServiceInstance (String className) {
try {
Class clazz = Class.forName (className);
return (Service) clazz.getConstructor (new Class [] {}).newInstance (new Object [] {});
} catch (ClassNotFoundException e) {
this.logger.error (className, e);
return null;
} catch (SecurityException e) {
this.logger.error (className, e);
return null;
} catch (NoSuchMethodException e) {
this.logger.error (className, e);
return null;
} catch (IllegalArgumentException e) {
this.logger.error (className, e);
return null;
} catch (InstantiationException e) {
this.logger.error (className, e);
return null;
} catch (IllegalAccessException e) {
this.logger.error (className, e);
return null;
} catch (InvocationTargetException e) {
this.logger.error (className, e);
return null;
}
}
| 1,849,134 | private void setCommandInput () {
mCommandInput = null;
try {
Class < ? > consoleReaderClass = Class.forName ("jline.ConsoleReader");
if (consoleReaderClass != null) {
Class < ? > consoleInputClass = Class.forName ("jline.ConsoleReaderInputStream");
if (consoleInputClass != null) {
Object jline = consoleReaderClass.newInstance ();
Constructor < ? > constructor = consoleInputClass.getConstructor (consoleReaderClass);
if (constructor != null) {
mCommandInput = (InputStream) constructor.newInstance (jline);
}
}
}
} catch (Exception e1) {
mLogger.info ("Exception loading jline");
}
if (mCommandInput == null) mCommandInput = System.in;
}
| Instantiate Using Reflection | Type-3 (WT3/4) | true |
7,885,446 | public static String CreateZip (String [] filesToZip, String zipFileName) {
byte [] buffer = new byte [18024];
try {
ZipOutputStream out = new ZipOutputStream (new FileOutputStream (zipFileName));
out.setLevel (Deflater.BEST_COMPRESSION);
for (int i = 0;
i < filesToZip.length; i ++) {
FileInputStream in = new FileInputStream (filesToZip [i]);
String fileName = null;
for (int X = filesToZip [i].length () - 1;
X >= 0; X --) {
if (filesToZip [i].charAt (X) == '\\' || filesToZip [i].charAt (X) == '/') {
fileName = filesToZip [i].substring (X + 1);
break;
} else if (X == 0) fileName = filesToZip [i];
}
out.putNextEntry (new ZipEntry (fileName));
int len;
while ((len = in.read (buffer)) > 0) out.write (buffer, 0, len);
out.closeEntry ();
in.close ();
}
out.close ();
} catch (IllegalArgumentException e) {
return "Failed to create zip: " + e.toString ();
} catch (FileNotFoundException e) {
return "Failed to create zip: " + e.toString ();
} catch (IOException e) {
return "Failed to create zip: " + e.toString ();
}
return "Success";
}
| 17,792,212 | private void createButtonCopyToClipboard () {
buttonCopyToClipboard = new Button (shell, SWT.PUSH);
buttonCopyToClipboard.setText ("Co&py to Clipboard");
buttonCopyToClipboard.setLayoutData (SharedStyle.relativeToBottomRight (buttonClose));
buttonCopyToClipboard.addSelectionListener (new SelectionAdapter () {
@Override
public void widgetSelected (final SelectionEvent event) {
IOUtils.copyToClipboard (Version.getEnvironmentReport ());
}}
);
}
| Copy File | Type-3 (WT3/4) | true |
16,166,059 | public void transform (File inputMatrixFile, MatrixIO.Format inputFormat, File outputMatrixFile) throws IOException {
FileChannel original = new FileInputStream (inputMatrixFile).getChannel ();
FileChannel copy = new FileOutputStream (outputMatrixFile).getChannel ();
copy.transferFrom (original, 0, original.size ());
original.close ();
copy.close ();
}
| 22,224,116 | public static void main (String [] args) throws IOException {
if (args.length == 0) {
System.out.println ("Usage: \nGZIPcompress file\n" + "\tUses GZIP compression to compress " + "the file to test.gz");
System.exit (1);
}
BufferedReader in = new BufferedReader (new FileReader (args [0]));
BufferedOutputStream out = new BufferedOutputStream (new GZIPOutputStream (new FileOutputStream ("test.gz")));
System.out.println ("Writing file");
int c;
while ((c = in.read ()) != - 1) out.write (c);
in.close ();
out.close ();
System.out.println ("Reading file");
BufferedReader in2 = new BufferedReader (new InputStreamReader (new GZIPInputStream (new FileInputStream ("test.gz"))));
String s;
while ((s = in2.readLine ()) != null) System.out.println (s);
}
| Copy File | Type-3 (WT3/4) | true |