label
int64 0
1
| func1
stringlengths 173
53.1k
| func2
stringlengths 173
53.1k
| id
int64 0
901k
|
---|---|---|---|
0 | public final void copyFile(final File fromFile, final File toFile) throws IOException { this.createParentPathIfNeeded(toFile); final FileChannel sourceChannel = new FileInputStream(fromFile).getChannel(); final FileChannel targetChannel = new FileOutputStream(toFile).getChannel(); final long sourceFileSize = sourceChannel.size(); sourceChannel.transferTo(0, sourceFileSize, targetChannel); } | public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; } | 900,100 |
0 | private String getMd5(String base64image) { String token = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(base64image.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); token = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return token; } | private boolean copyFile(File inFile, File outFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(inFile)); writer = new BufferedWriter(new FileWriter(outFile)); while (reader.ready()) { writer.write(reader.read()); } writer.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { ex.printStackTrace(); return false; } } if (writer != null) { try { writer.close(); } catch (IOException ex) { return false; } } } return true; } | 900,101 |
0 | 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!"); } | public static String hashClientPassword(String algorithm, String password, String salt) throws IllegalArgumentException, DruidSafeRuntimeException { if (algorithm == null) { throw new IllegalArgumentException("THE ALGORITHM MUST NOT BE NULL"); } if (password == null) { throw new IllegalArgumentException("THE PASSWORD MUST NOT BE NULL"); } if (salt == null) { salt = ""; } String result = null; try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(password.getBytes()); md.update(salt.getBytes()); result = SecurityHelper.byteArrayToHexString(md.digest()); } catch (NoSuchAlgorithmException e) { throw new DruidSafeRuntimeException(e); } return result; } | 900,102 |
1 | public String read(String url) throws IOException { URL myurl = new URL(url); BufferedReader in = new BufferedReader(new InputStreamReader(myurl.openStream())); StringBuffer sb = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) sb.append(inputLine); in.close(); return sb.toString(); } | public static void addClasses(URL url) { BufferedReader reader = null; String line; ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { line = line.trim(); if ((line.length() == 0) || line.startsWith(";")) { continue; } try { classes.add(Class.forName(line, true, cl)); } catch (Throwable t) { } } } catch (Throwable t) { } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { } } } } | 900,103 |
0 | private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException { FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(srcFile); FileChannel iChannel = is.getChannel(); os = new FileOutputStream(destFile, false); FileChannel oChannel = os.getChannel(); long doneBytes = 0L; long todoBytes = srcFile.length(); while (todoBytes != 0L) { long iterationBytes = Math.min(todoBytes, chunkSize); long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes); if (iterationBytes != transferredLength) { throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied."); } doneBytes += transferredLength; todoBytes -= transferredLength; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified()); if (!successTimestampOp) { log.warn("Could not change timestamp for {}. Index synchronization may be slow.", destFile); } } | public Document getWsdlDomResource(String aResourceName) throws SdlException { logger.debug("getWsdlDomResource() " + aResourceName); InputStream in = null; try { URL url = getDeploymentContext().getResourceURL(aResourceName); if (url == null) { logger.error("url is null"); return null; } else { logger.debug("loading wsdl document " + aResourceName); in = url.openStream(); return getSdlParser().loadWsdlDocument(in, null); } } catch (Throwable t) { logger.error("Error: " + t + " for " + aResourceName); throw new SdlDeploymentException(MessageFormat.format("unable to load: {0} from {1}", new Object[] { aResourceName, getDeploymentContext().getDeploymentLocation() }), t); } finally { SdlCloser.close(in); } } | 900,104 |
0 | @Override public String addUserIdentity(OpenIDItem identity, long userId) throws DatabaseException { if (identity == null) throw new NullPointerException("identity"); if (identity.getIdentity() == null || "".equals(identity.getIdentity())) throw new NullPointerException("identity.getIdentity()"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } String retID = "exist"; PreparedStatement insSt = null, seqSt = null; try { int modified = 0; insSt = getConnection().prepareStatement(INSERT_IDENTITY_STATEMENT); insSt.setLong(1, userId); insSt.setString(2, identity.getIdentity()); modified = insSt.executeUpdate(); seqSt = getConnection().prepareStatement(USER_IDENTITY_VALUE); ResultSet rs = seqSt.executeQuery(); while (rs.next()) { retID = rs.getString(1); } if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + seqSt + "\" and \"" + insSt + "\""); } else { getConnection().rollback(); LOGGER.debug("DB has not been updated -> rollback! Queries: \"" + seqSt + "\" and \"" + insSt + "\""); retID = "error"; } } catch (SQLException e) { LOGGER.error(e); retID = "error"; } finally { closeConnection(); } return retID; } | public static SubstanceSkin.ColorSchemes getColorSchemes(URL url) { List<SubstanceColorScheme> schemes = new ArrayList<SubstanceColorScheme>(); BufferedReader reader = null; Color ultraLight = null; Color extraLight = null; Color light = null; Color mid = null; Color dark = null; Color ultraDark = null; Color foreground = null; String name = null; ColorSchemeKind kind = null; boolean inColorSchemeBlock = false; try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while (true) { String line = reader.readLine(); if (line == null) break; line = line.trim(); if (line.length() == 0) continue; if (line.startsWith("#")) { continue; } if (line.indexOf("{") >= 0) { if (inColorSchemeBlock) { throw new IllegalArgumentException("Already in color scheme definition"); } inColorSchemeBlock = true; name = line.substring(0, line.indexOf("{")).trim(); continue; } if (line.indexOf("}") >= 0) { if (!inColorSchemeBlock) { throw new IllegalArgumentException("Not in color scheme definition"); } inColorSchemeBlock = false; if ((name == null) || (kind == null) || (ultraLight == null) || (extraLight == null) || (light == null) || (mid == null) || (dark == null) || (ultraDark == null) || (foreground == null)) { throw new IllegalArgumentException("Incomplete specification"); } Color[] colors = new Color[] { ultraLight, extraLight, light, mid, dark, ultraDark, foreground }; if (kind == ColorSchemeKind.LIGHT) { schemes.add(getLightColorScheme(name, colors)); } else { schemes.add(getDarkColorScheme(name, colors)); } name = null; kind = null; ultraLight = null; extraLight = null; light = null; mid = null; dark = null; ultraDark = null; foreground = null; continue; } String[] split = line.split("="); if (split.length != 2) { throw new IllegalArgumentException("Unsupported format in line " + line); } String key = split[0].trim(); String value = split[1].trim(); if ("kind".equals(key)) { if (kind == null) { if ("Light".equals(value)) { kind = ColorSchemeKind.LIGHT; continue; } if ("Dark".equals(value)) { kind = ColorSchemeKind.DARK; continue; } throw new IllegalArgumentException("Unsupported format in line " + line); } throw new IllegalArgumentException("'kind' should only be defined once"); } if ("colorUltraLight".equals(key)) { if (ultraLight == null) { ultraLight = Color.decode(value); continue; } throw new IllegalArgumentException("'ultraLight' should only be defined once"); } if ("colorExtraLight".equals(key)) { if (extraLight == null) { extraLight = Color.decode(value); continue; } throw new IllegalArgumentException("'extraLight' should only be defined once"); } if ("colorLight".equals(key)) { if (light == null) { light = Color.decode(value); continue; } throw new IllegalArgumentException("'light' should only be defined once"); } if ("colorMid".equals(key)) { if (mid == null) { mid = Color.decode(value); continue; } throw new IllegalArgumentException("'mid' should only be defined once"); } if ("colorDark".equals(key)) { if (dark == null) { dark = Color.decode(value); continue; } throw new IllegalArgumentException("'dark' should only be defined once"); } if ("colorUltraDark".equals(key)) { if (ultraDark == null) { ultraDark = Color.decode(value); continue; } throw new IllegalArgumentException("'ultraDark' should only be defined once"); } if ("colorForeground".equals(key)) { if (foreground == null) { foreground = Color.decode(value); continue; } throw new IllegalArgumentException("'foreground' should only be defined once"); } throw new IllegalArgumentException("Unsupported format in line " + line); } ; } catch (IOException ioe) { throw new IllegalArgumentException(ioe); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { } } } return new SubstanceSkin.ColorSchemes(schemes); } | 900,105 |
0 | public static String getHashedPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); BigInteger hashedInt = new BigInteger(1, digest.digest()); return String.format("%1$032X", hashedInt); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae.getMessage()); } return ""; } | @Override void execute(Connection conn, Component parent, String context, ProgressMonitor progressBar, ProgressWrapper progressWrapper) throws Exception { Statement statement = null; try { conn.setAutoCommit(false); statement = conn.createStatement(); String deleteSql = getDeleteSql(m_compositionId); statement.executeUpdate(deleteSql); conn.commit(); s_compostionCache.delete(new Integer(m_compositionId)); } catch (SQLException ex) { try { conn.rollback(); } catch (SQLException e) { e.printStackTrace(); } throw ex; } finally { if (statement != null) { statement.close(); } } } | 900,106 |
0 | public static String encryptMd5(String plaintext) { String hashtext = ""; try { MessageDigest m; m = MessageDigest.getInstance("MD5"); m.reset(); m.update(plaintext.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; } | protected static String readUrl(URL url) throws IOException { BufferedReader in = null; StringBuffer buf = new StringBuffer(); try { in = new BufferedReader(new InputStreamReader(url.openStream())); final char[] charBuf = new char[1024]; int len = 0; while ((len = in.read(charBuf)) != -1) buf.append(charBuf, 0, len); } finally { if (in != null) in.close(); } return buf.toString(); } | 900,107 |
1 | public static final boolean copy(File source, File target, boolean overwrite) { if (!overwrite && target.exists()) { LOGGER.error("Target file exist and it not permitted to overwrite it !"); return false; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } finally { try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } } return true; } | 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(); } } | 900,108 |
0 | public void init() { System.out.println("Init applet..."); int port = Integer.parseInt(getParameter("port")); int useUDP = Integer.parseInt(getParameter("udp")); boolean bUseUDP = false; if (useUDP > 0) bUseUDP = true; m_strWorld = getParameter("world"); m_strHost = this.getCodeBase().getHost(); try { new EnvironmentMap(getParameter("vrwmap")); } catch (Throwable t) { System.out.println(t.getMessage()); } URL urlExperiment = null; InputStream expStream = null; try { String strPathExperiment = getParameter("experiment"); if (strPathExperiment.length() > 0) { urlExperiment = new URL(getCodeBase(), strPathExperiment); expStream = urlExperiment.openStream(); } } catch (java.net.MalformedURLException e) { System.out.println("Couldn't open url experiment: badly specified URL " + e.getMessage()); } catch (Throwable t) { System.out.println("Couldn't open url experiment: " + t.getMessage()); } try { System.out.println("Creating client, logging to " + m_strWorld); m_VRWClient = new VRWClient(m_strHost, port, true, bUseUDP); m_VRWClient.setInApplet(true); m_VRWClient.login(m_strWorld); } catch (java.io.IOException e) { System.out.println("IOException creating the VRWClient"); } try { jsobj = JSObject.getWindow(this); } catch (Throwable t) { System.out.println("Exception getting Java Script Interface: " + t.getMessage()); } refApplet = this; m_frmVRWConsole = new VRWConsoleFrame(); m_frmVRWConsole.setTitle("VRW Client Console"); m_frmVRWConsole.pack(); m_frmVRWConsole.setSize(Math.max(300, m_frmVRWConsole.getSize().width), Math.max(200, m_frmVRWConsole.getSize().height)); if (expStream != null) { System.out.println("Passing experiment stream to VRWConsoleFrame"); m_frmVRWConsole.loadExperiment(expStream); } m_frmVRWConsole.setVisible(true); } | public void copyJarContent(File jarPath, File targetDir) throws IOException { log.info("Copying natives from " + jarPath.getName()); JarFile jar = new JarFile(jarPath); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry file = entries.nextElement(); File f = new File(targetDir, file.getName()); log.info("Copying native - " + file.getName()); File parentFile = f.getParentFile(); parentFile.mkdirs(); if (file.isDirectory()) { f.mkdir(); continue; } InputStream is = null; FileOutputStream fos = null; try { is = jar.getInputStream(file); fos = new FileOutputStream(f); IOUtils.copy(is, fos); } finally { if (fos != null) fos.close(); if (is != null) is.close(); } } } | 900,109 |
1 | public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } } | private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { } } catch (FileNotFoundException e) { } } | 900,110 |
1 | public void process() throws Exception { String searchXML = FileUtils.readFileToString(new File(getSearchRequestRelativeFilePath())); Map<String, String> parametersMap = new HashMap<String, String>(); parametersMap.put("searchXML", searchXML); String proxyHost = null; int proxyPort = -1; String serverUserName = null; String serverUserPassword = null; FileOutputStream fos = null; if (getUseProxy()) { serverUserName = getServerUserName(); serverUserPassword = getServerUserPassword(); } if (getUseProxy()) { proxyHost = getProxyHost(); proxyPort = getProxyPort(); } try { InputStream responseInputStream = URLUtils.getHttpResponse(getSearchBaseURL(), serverUserName, serverUserPassword, URLUtils.HTTP_POST_METHOD, proxyHost, proxyPort, parametersMap, -1); fos = new FileOutputStream(getSearchResponseRelativeFilePath()); IOUtils.copyLarge(responseInputStream, fos); } finally { if (null != fos) { fos.flush(); fos.close(); } } } | public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.FileOutputStream;"); importList.add("java.io.FileInputStream;"); importList.add("java.io.DataInputStream;"); importList.add("java.io.DataOutputStream;"); importList.add("java.io.IOException;"); importList.add("java.sql.Date;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + "\n"); sb.append("{" + "\n public static final int PROTO_VERSION=" + proto_version + ";"); sb.append("\n\n"); StringBuffer f_writer = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); while (it.hasNext()) { Member member = (Member) it.next(); String nm = member.getName(); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToBinaryCode(pad, "dos", getter + "()")); f_reader.append(gen_type.getFromBinaryCode(pad, "din", setter)); } String reader_vars = ""; sb.append("\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n DataOutputStream dos = new DataOutputStream(fos);" + "\n writeStream(dos, obj);" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n readStream(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeStream(DataOutputStream dos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n dos.writeByte(PROTO_VERSION);" + "\n " + f_writer + "\n } // end of writeStream" + "\n" + "\n public static void readStream(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + "\n int proto_version = din.readByte();" + "\n if (proto_version==" + proto_version + ") readStreamV1(din,obj);" + "\n } // end of readStream" + "\n" + "\n public static void readStreamV1(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + reader_vars + f_reader + "\n } // end of readStreamV1" + "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"); return sb.toString(); } | 900,111 |
0 | public static void copyFile(File source, File destination) throws IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[4096]; int read = -1; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } out.flush(); out.close(); in.close(); } | public void initFromXml(final String xmlFileName) throws java.net.MalformedURLException, ConfigurationException, IOException { if (xmlInitialized) { return; } templates = null; MergeTemplateWriter.setTokenList(getTokenProvider().getKnownTokens()); java.net.URL url = new FileFinder().getUrl(getTokenProvider().getClass(), xmlFileName); InputStreamReader xmlFileReader = new InputStreamReader(url.openStream()); KnownTemplates temps = MergeTemplateWriter.importFromXML(xmlFileReader); xmlFileReader.close(); KnownTemplates.setDefaultInstance(temps); setTemplates(temps); setInitialized(true); } | 900,112 |
1 | protected int executeUpdates(List<UpdateStatement> statements, OlVersionCheck olVersionCheck) throws DaoException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("start executeUpdates"); } PreparedStatement stmt = null; Connection conn = null; int rowsAffected = 0; try { conn = ds.getConnection(); conn.setAutoCommit(false); conn.rollback(); conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); if (olVersionCheck != null) { stmt = conn.prepareStatement(olVersionCheck.getQuery()); stmt.setObject(1, olVersionCheck.getId()); ResultSet rs = stmt.executeQuery(); rs.next(); Number olVersion = (Number) rs.getObject("olVersion"); stmt.close(); stmt = null; if (olVersion.intValue() != olVersionCheck.getOlVersionToCheck().intValue()) { rowsAffected = -1; } } if (rowsAffected >= 0) { for (UpdateStatement query : statements) { stmt = conn.prepareStatement(query.getQuery()); if (query.getParams() != null) { for (int parameterIndex = 1; parameterIndex <= query.getParams().length; parameterIndex++) { Object object = query.getParams()[parameterIndex - 1]; stmt.setObject(parameterIndex, object); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug(" **** Sending statement:\n" + query.getQuery()); } rowsAffected += stmt.executeUpdate(); stmt.close(); stmt = null; } } conn.commit(); conn.close(); conn = null; } catch (SQLException e) { if ("23000".equals(e.getSQLState())) { LOGGER.info("Integrity constraint violation", e); throw new UniqueConstaintException(); } throw new DaoException("error.databaseError", e); } finally { try { if (stmt != null) { LOGGER.debug("closing open statement!"); stmt.close(); } } catch (SQLException e) { throw new DaoException("error.databaseError", e); } finally { stmt = null; } try { if (conn != null) { LOGGER.debug("rolling back open connection!"); conn.rollback(); conn.setAutoCommit(true); conn.close(); } } catch (SQLException e) { throw new DaoException("error.databaseError", e); } finally { conn = null; } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("finish executeUpdates"); } return rowsAffected; } | public void addUserToRealm(final NewUser user) { try { connection.setAutoCommit(false); final String pass, salt; final List<RealmWithEncryptedPass> realmPass = new ArrayList<RealmWithEncryptedPass>(); Realm realm; String username; username = user.username.toLowerCase(locale); PasswordHasher ph = PasswordFactory.getInstance().getPasswordHasher(); pass = ph.hashPassword(user.password); salt = ph.getSalt(); realmPass.add(new RealmWithEncryptedPass(cm.getRealm("null"), PasswordFactory.getInstance().getPasswordHasher().hashRealmPassword(username, "", user.password))); if (user.realms != null) { for (String realmName : user.realms) { realm = cm.getRealm(realmName); realmPass.add(new RealmWithEncryptedPass(realm, PasswordFactory.getInstance().getPasswordHasher().hashRealmPassword(username, realm.getFullRealmName(), user.password))); } user.realms = null; } new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("user.updatePassword")); psImpl.setString(1, pass); psImpl.setString(2, salt); psImpl.setInt(3, user.userId); psImpl.executeUpdate(); } }); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realm.addUser")); RealmWithEncryptedPass rwep; RealmDb realm; Iterator<RealmWithEncryptedPass> iter1 = realmPass.iterator(); while (iter1.hasNext()) { rwep = iter1.next(); realm = (RealmDb) rwep.realm; psImpl.setInt(1, realm.getRealmId()); psImpl.setInt(2, user.userId); psImpl.setInt(3, user.domainId); psImpl.setString(4, rwep.password); psImpl.executeUpdate(); } } }); connection.commit(); cmDB.removeUser(user.userId); } catch (GeneralSecurityException e) { log.error(e); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } throw new RuntimeException("Error updating Realms. Unable to continue Operation."); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } } | 900,113 |
0 | @Override public void run() { try { File[] inputFiles = new File[this.previousFiles != null ? this.previousFiles.length + 1 : 1]; File copiedInput = new File(this.randomFolder, this.inputFile.getName()); IOUtils.copyFile(this.inputFile, copiedInput); inputFiles[inputFiles.length - 1] = copiedInput; if (previousFiles != null) { for (int i = 0; i < this.previousFiles.length; i++) { File prev = this.previousFiles[i]; File copiedPrev = new File(this.randomFolder, prev.getName()); IOUtils.copyFile(prev, copiedPrev); inputFiles[i] = copiedPrev; } } org.happycomp.radiog.Activator activator = org.happycomp.radiog.Activator.getDefault(); if (this.exportedMP3File != null) { EncodingUtils.encodeToWavAndThenMP3(inputFiles, this.exportedWavFile, this.exportedMP3File, this.deleteOnExit, this.randomFolder, activator.getCommandsMap()); } else { EncodingUtils.encodeToWav(inputFiles, this.exportedWavFile, randomFolder, activator.getCommandsMap()); } if (encodeMonitor != null) { encodeMonitor.setEncodingFinished(true); } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } | public String translate(String before, int translateType) throws CoreException { if (before == null) throw new IllegalArgumentException("before is null."); if ((translateType != ENGLISH_TO_JAPANESE) && (translateType != JAPANESE_TO_ENGLISH)) { throw new IllegalArgumentException("Invalid translateType. value=" + translateType); } try { URL url = new URL(config.getTranslatorSiteUrl()); URLConnection connection = url.openConnection(); sendTranslateRequest(before, translateType, connection); String afterContents = receiveTranslatedResponse(connection); String afterStartKey = config.getTranslationResultStart(); String afterEndKey = config.getTranslationResultEnd(); int startLength = afterStartKey.length(); int startPos = afterContents.indexOf(afterStartKey); if (startPos != -1) { int endPos = afterContents.indexOf(afterEndKey, startPos); if (endPos != -1) { String after = afterContents.substring(startPos + startLength, endPos); after = replaceEntities(after); return after; } else { throwCoreException(ERROR_END_KEYWORD_NOT_FOUND, "End keyword not found.", null); } } else { throwCoreException(ERROR_START_KEYWORD_NOT_FOUND, "Start keyword not found.", null); } } catch (IOException e) { throwCoreException(ERROR_IO, e.getMessage(), e); } throw new IllegalStateException("CoreException not occurd."); } | 900,114 |
0 | public static String doPost(String http_url, String post_data) { if (post_data == null) { post_data = ""; } try { URLConnection conn = new URL(http_url).openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(post_data); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuffer buffer = new StringBuffer(); while ((line = in.readLine()) != null) { buffer.append(line); buffer.append("\n"); } return buffer.toString(); } catch (IOException e) { ; } catch (ClassCastException e) { e.printStackTrace(); } return null; } | public static String loadURLToString(String url, String EOL) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); String result = ""; String str; while ((str = in.readLine()) != null) { result += str + EOL; } in.close(); return result; } | 900,115 |
0 | public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, Vector images) { int i; lengthOfTask = images.size(); Element dataBaseXML = new Element("dataBase"); for (i = 0; ((i < images.size()) && !stop && !cancel); i++) { Vector imagen = new Vector(2); imagen = (Vector) images.elementAt(i); String element = (String) imagen.elementAt(0); current = i; String pathSrc = System.getProperty("user.dir") + File.separator + "images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(File.separator) + 1, pathSrc.length()); String pathDst = directoryPath + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector<String> keyWords = new Vector<String>(); keyWords = TIGDataBase.asociatedConceptSearch(element); Element image = new Element("image"); image.setAttribute("name", name); if (keyWords.size() != 0) { for (int k = 0; k < keyWords.size(); k++) { Element category = new Element("category"); category.setText(keyWords.get(k).trim()); image.addContent(category); } } dataBaseXML.addContent(image); } Document doc = new Document(dataBaseXML); try { XMLOutputter out = new XMLOutputter(); FileOutputStream f = new FileOutputStream(directoryPath + "images.xml"); out.output(doc, f); f.flush(); f.close(); } catch (Exception e) { e.printStackTrace(); } current = lengthOfTask; } | public void addUrl(URL url) throws IOException, SAXException { InputStream inStream = url.openStream(); String path = url.getPath(); int slashInx = path.lastIndexOf('/'); String name = path.substring(slashInx + 1); Document doc = docBuild.parse(inStream); Element root = doc.getDocumentElement(); String rootTag = root.getTagName(); if (rootTag.equals("graphml")) { NodeList graphNodes = root.getElementsByTagName("graph"); for (int i = 0; i < graphNodes.getLength(); i++) { Element elem = (Element) graphNodes.item(i); String graphName = elem.getAttribute("id"); if (graphName == null) { graphName = name; } addStructure(new GraphSpec(graphName)); urlRefs.put(graphName, url); } } else if (rootTag.equals("tree")) { addStructure(new TreeSpec(name)); urlRefs.put(name, url); } else { throw new IllegalArgumentException("Format of " + url + " not understood."); } inStream.close(); } | 900,116 |
1 | public DialogueSymbole(final JFrame jframe, final Element el, final String srcAttr) { super(jframe, JaxeResourceBundle.getRB().getString("symbole.Insertion"), true); this.jframe = jframe; this.el = el; final String nomf = el.getAttribute(srcAttr); boolean applet = false; try { final File dossierSymboles = new File("symboles"); if (!dossierSymboles.exists()) { JOptionPane.showMessageDialog(jframe, JaxeResourceBundle.getRB().getString("erreur.SymbolesNonTrouve"), JaxeResourceBundle.getRB().getString("erreur.Erreur"), JOptionPane.ERROR_MESSAGE); return; } liste = chercherImages(dossierSymboles); } catch (AccessControlException ex) { applet = true; try { final URL urlListe = DialogueSymbole.class.getClassLoader().getResource("symboles/liste.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(urlListe.openStream())); final ArrayList<File> listeImages = new ArrayList<File>(); String ligne = null; while ((ligne = in.readLine()) != null) { if (!"".equals(ligne.trim())) listeImages.add(new File("symboles/" + ligne.trim())); } liste = listeImages.toArray(new File[listeImages.size()]); } catch (IOException ex2) { LOG.error(ex2); } } final JPanel cpane = new JPanel(new BorderLayout()); setContentPane(cpane); final GridLayout grille = new GridLayout((int) Math.ceil(liste.length / 13.0), 13, 10, 10); final JPanel spane = new JPanel(grille); cpane.add(spane, BorderLayout.CENTER); ichoix = 0; final MyMouseListener ecouteur = new MyMouseListener(); labels = new JLabel[liste.length]; for (int i = 0; i < liste.length; i++) { if (nomf != null && !"".equals(nomf) && nomf.equals(liste[i].getPath())) ichoix = i; URL urlIcone; try { if (applet) { final URL urlListe = DialogueSymbole.class.getClassLoader().getResource("symboles/liste.txt"); final String baseURL = urlListe.toString().substring(0, urlListe.toString().indexOf("symboles/liste.txt")); urlIcone = new URL(baseURL + liste[i].getPath()); } else urlIcone = liste[i].toURL(); } catch (MalformedURLException ex) { LOG.error(ex); break; } final Icon ic = new ImageIcon(urlIcone); final JLabel label = new JLabel(ic); label.addMouseListener(ecouteur); labels[i] = label; spane.add(label); } final JPanel bpane = new JPanel(new FlowLayout(FlowLayout.RIGHT)); final JButton boutonAnnuler = new JButton(JaxeResourceBundle.getRB().getString("bouton.Annuler")); boutonAnnuler.addActionListener(this); boutonAnnuler.setActionCommand("Annuler"); bpane.add(boutonAnnuler); final JButton boutonOK = new JButton(JaxeResourceBundle.getRB().getString("bouton.OK")); boutonOK.addActionListener(this); boutonOK.setActionCommand("OK"); bpane.add(boutonOK); cpane.add(bpane, BorderLayout.SOUTH); getRootPane().setDefaultButton(boutonOK); choix(ichoix); pack(); if (jframe != null) { final Rectangle r = jframe.getBounds(); setLocation(r.x + r.width / 4, r.y + r.height / 4); } else { final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screen.width - getSize().width) / 3, (screen.height - getSize().height) / 3); } } | public static ArrayList<Credential> importCredentials(String urlString) { ArrayList<Credential> results = new ArrayList<Credential>(); try { URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buff = new StringBuffer(); String line; while ((line = in.readLine()) != null) { buff.append(line); if (line.equals("-----END PGP SIGNATURE-----")) { Credential credential = ProfileParser.parseCredential(buff.toString(), true); results.add(credential); buff = new StringBuffer(); } else { buff.append(NL); } } } catch (MalformedURLException e) { } catch (IOException e) { } catch (ParsingException e) { System.err.println(e); } return results; } | 900,117 |
0 | public static void write(File file, InputStream source) throws IOException { OutputStream outputStream = null; assert file != null : "file must not be null."; assert file.isFile() : "file must be a file."; assert file.canWrite() : "file must be writable."; assert source != null : "source must not be null."; try { outputStream = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(source, outputStream); outputStream.flush(); } finally { IOUtils.closeQuietly(outputStream); } } | public static String getMD5(String s) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(), 0, s.length()); String result = new BigInteger(1, m.digest()).toString(16); while (result.length() < 32) { result = '0' + result; } return result; } catch (NoSuchAlgorithmException ex) { return null; } } | 900,118 |
0 | public TreeMap getStrainMap() { TreeMap strainMap = new TreeMap(); String server = ""; try { Datasource[] ds = DatasourceManager.getDatasouce(alias, version, DatasourceManager.ALL_CONTAINS_GROUP); for (int i = 0; i < ds.length; i++) { if (ds[i].getDescription().startsWith(MOUSE_DBSNP)) { if (ds[i].getServer().length() == 0) { Connection con = ds[i].getConnection(); strainMap = Action.lineMode.regularSQL.GenotypeDataSearchAction.getStrainMap(con); break; } else { server = ds[i].getServer(); HashMap serverUrlMap = InitXml.getInstance().getServerMap(); String serverUrl = (String) serverUrlMap.get(server); URL url = new URL(serverUrl + servletName); URLConnection uc = url.openConnection(); uc.setDoOutput(true); OutputStream os = uc.getOutputStream(); StringBuffer buf = new StringBuffer(); buf.append("viewType=getstrains"); buf.append("&hHead=" + hHead); buf.append("&hCheck=" + version); PrintStream ps = new PrintStream(os); ps.print(buf.toString()); ps.close(); ObjectInputStream ois = new ObjectInputStream(uc.getInputStream()); strainMap = (TreeMap) ois.readObject(); ois.close(); } } } } catch (Exception e) { log.error("strain map", e); } return strainMap; } | public void loadSourceCode() { if (getResourceName() != null) { String filename = getResourceName() + ".java"; sourceCode = new String("<html><body bgcolor=\"#ffffff\"><pre>"); InputStream is; InputStreamReader isr; CodeViewer cv = new CodeViewer(); URL url; try { url = getClass().getResource(filename); is = url.openStream(); isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr); String line = reader.readLine(); while (line != null) { sourceCode += cv.syntaxHighlight(line) + " \n "; line = reader.readLine(); } sourceCode += new String("</pre></body></html>"); } catch (Exception ex) { sourceCode = "Could not load file: " + filename; } } } | 900,119 |
1 | public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } } | public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } } | 900,120 |
0 | private boolean sendMsg(TACMessage msg) { try { String msgStr = msg.getMessageString(); URLConnection conn = url.openConnection(); conn.setRequestProperty("Content-Length", "" + msgStr.length()); conn.setDoOutput(true); OutputStream output = conn.getOutputStream(); output.write(msgStr.getBytes()); output.flush(); InputStream input = conn.getInputStream(); int len = conn.getContentLength(); int totalRead = 0; int read; byte[] content = new byte[len]; while ((len > totalRead) && (read = input.read(content, totalRead, len - totalRead)) > 0) { totalRead += read; } output.close(); input.close(); if (len < totalRead) { log.severe("truncated message response for " + msg.getType()); return false; } else { msgStr = new String(content); msg.setReceivedMessage(msgStr); msg.deliverMessage(); } return true; } catch (Exception e) { log.log(Level.SEVERE, "could not send message", e); return false; } } | public void filter(File source, File destination, MNamespace mNamespace) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(source)); BufferedWriter writer = new BufferedWriter(new FileWriter(destination)); int line = 0; int column = 0; Stack parseStateStack = new Stack(); parseStateStack.push(new ParseState(mNamespace)); for (Iterator i = codePieces.iterator(); i.hasNext(); ) { NamedCodePiece cp = (NamedCodePiece) i.next(); while (line < cp.getStartLine()) { line++; column = 0; writer.write(reader.readLine()); writer.newLine(); } while (column < cp.getStartPosition()) { writer.write(reader.read()); column++; } cp.write(writer, parseStateStack, column); while (line < cp.getEndLine()) { line++; column = 0; reader.readLine(); } while (column < cp.getEndPosition()) { column++; reader.read(); } } String data; while ((data = reader.readLine()) != null) { writer.write(data); writer.newLine(); } reader.close(); writer.close(); } | 900,121 |
1 | private List<File> ungzipFile(File directory, File compressedFile) throws IOException { List<File> files = new ArrayList<File>(); TarArchiveInputStream in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(compressedFile))); try { TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { if (entry.isDirectory()) { log.warn("TAR archive contains directories which are being ignored"); entry = in.getNextTarEntry(); continue; } String fn = new File(entry.getName()).getName(); if (fn.startsWith(".")) { log.warn("TAR archive contains a hidden file which is being ignored"); entry = in.getNextTarEntry(); continue; } File targetFile = new File(directory, fn); if (targetFile.exists()) { log.warn("TAR archive contains duplicate filenames, only the first is being extracted"); entry = in.getNextTarEntry(); continue; } files.add(targetFile); log.debug("Extracting file: " + entry.getName() + " to: " + targetFile.getAbsolutePath()); OutputStream fout = new BufferedOutputStream(new FileOutputStream(targetFile)); InputStream entryIn = new FileInputStream(entry.getFile()); IOUtils.copy(entryIn, fout); fout.close(); entryIn.close(); } } finally { in.close(); } return files; } | public static boolean copy(String source, String dest) { int bytes; byte array[] = new byte[BUFFER_LEN]; try { InputStream is = new FileInputStream(source); OutputStream os = new FileOutputStream(dest); while ((bytes = is.read(array, 0, BUFFER_LEN)) > 0) os.write(array, 0, bytes); is.close(); os.close(); return true; } catch (IOException e) { return false; } } | 900,122 |
1 | private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; } | public static String getMD5(String in) { if (in == null) { return null; } try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(in.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xFF & hash[i]); if (hex.length() == 1) { hex = "0" + hex; } hexString.append(hex); } return hexString.toString(); } catch (Exception e) { Debug.logException(e); } return null; } | 900,123 |
1 | public static boolean writeFileByBinary(InputStream pIs, File pFile, boolean pAppend) { boolean flag = false; try { FileOutputStream fos = new FileOutputStream(pFile, pAppend); IOUtils.copy(pIs, fos); fos.flush(); fos.close(); pIs.close(); flag = true; } catch (Exception e) { LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; } | 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(); } | 900,124 |
1 | public RobotList<Resource> sort_incr_Resource(RobotList<Resource> list, String field) { int length = list.size(); Index_value[] resource_dist = new Index_value[length]; if (field.equals("") || field.equals("location")) { Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, distance(cur_loc, list.get(i).location)); } } else if (field.equals("energy")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).energy); } } else if (field.equals("ammostash")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).ammostash); } } else if (field.equals("speed")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).speed); } } else if (field.equals("health")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).health); } } else { say("impossible to sort list - nothing modified"); return list; } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (resource_dist[i].value > resource_dist[i + 1].value) { Index_value a = resource_dist[i]; resource_dist[i] = resource_dist[i + 1]; resource_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Resource> new_resource_list = new RobotList<Resource>(Resource.class); for (int i = 0; i < length; i++) { new_resource_list.addLast(list.get(resource_dist[i].index)); } return new_resource_list; } | public static void shakeSort(int[] a) { if (a == null) { throw new IllegalArgumentException("Null-pointed array"); } int k = 0; int left = 0; int right = a.length - 1; while (right - left > 0) { k = 0; for (int i = 0; i <= right - 1; i++) { if (a[i] > a[i + 1]) { k = i; int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } right = k; k = a.length - 1; for (int i = left; i <= right - 1; i++) { if (a[i] > a[i + 1]) { k = i; int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } left = k; } } | 900,125 |
0 | private File sendQuery(String query) throws MusicBrainzException { File xmlServerResponse = null; try { xmlServerResponse = new File(SERVER_RESPONSE_FILE); long start = Calendar.getInstance().getTimeInMillis(); System.out.println("\n\n++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(" consulta de busqueda -> " + query); URL url = new URL(query); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String response = ""; String line = ""; System.out.println(" Respuesta del servidor: \n"); while ((line = in.readLine()) != null) { response += line; } xmlServerResponse = new File(SERVER_RESPONSE_FILE); System.out.println(" Ruta del archivo XML -> " + xmlServerResponse.getAbsolutePath()); BufferedWriter out = new BufferedWriter(new FileWriter(xmlServerResponse)); out.write(response); out.close(); System.out.println("Tamanho del xmlFile -> " + xmlServerResponse.length()); long ahora = (Calendar.getInstance().getTimeInMillis() - start); System.out.println(" Tiempo transcurrido en la consulta (en milesimas) -> " + ahora); System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); } catch (IOException e) { e.printStackTrace(); String msg = e.getMessage(); if (e instanceof FileNotFoundException) { msg = "ERROR: MusicBrainz URL used is not found:\n" + msg; } else { } throw new MusicBrainzException(msg); } return xmlServerResponse; } | private void copyLocalFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } | 900,126 |
1 | private void copyFile(String inputPath, String basis, String filename) throws GLMRessourceFileException { try { FileChannel inChannel = new FileInputStream(new File(inputPath)).getChannel(); File target = new File(basis, filename); FileChannel outChannel = new FileOutputStream(target).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (Exception e) { throw new GLMRessourceFileException(7); } } | public String openFileAsText(String resource) throws IOException { StringWriter wtr = new StringWriter(); InputStreamReader rdr = new InputStreamReader(openFile(resource)); try { IOUtils.copy(rdr, wtr); } finally { IOUtils.closeQuietly(rdr); } return wtr.toString(); } | 900,127 |
1 | public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); 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) { ; } } } | public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } | 900,128 |
1 | public static Document validateXml(File messageFile, URL inputUrl, String[] catalogs) throws IOException, ParserConfigurationException, Exception, SAXException, FileNotFoundException { InputSource source = new InputSource(inputUrl.openStream()); Document logDoc = DomUtil.getNewDom(); XMLReader reader = SaxUtil.getXMLFormatLoggingXMLReader(log, logDoc, true, catalogs); reader.parse(source); InputStream logStream = DomUtil.serializeToInputStream(logDoc, "utf-8"); System.out.println("Creating message file \"" + messageFile.getAbsolutePath() + "\"..."); OutputStream fos = new FileOutputStream(messageFile); IOUtils.copy(logStream, fos); return logDoc; } | public static void compress(File srcFile, File destFile) throws IOException { InputStream input = null; OutputStream output = null; try { input = new BufferedInputStream(new FileInputStream(srcFile)); output = new GZIPOutputStream(new FileOutputStream(destFile)); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } } | 900,129 |
1 | @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String contentId = req.getParameter(CONTENT_ID); String contentType = req.getParameter(CONTENT_TYPE); if (contentId == null || contentType == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Content id or content type not specified"); return; } try { switch(ContentType.valueOf(contentType)) { case IMAGE: resp.setContentType("image/jpeg"); break; case AUDIO: resp.setContentType("audio/mp3"); break; case VIDEO: resp.setContentType("video/mpeg"); break; default: throw new IllegalStateException("Invalid content type specified"); } } catch (IllegalArgumentException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid content type specified"); return; } String baseUrl = this.getServletContext().getInitParameter(BASE_URL); URL url = new URL(baseUrl + "/" + contentType.toLowerCase() + "/" + contentId); URLConnection conn = url.openConnection(); resp.setContentLength(conn.getContentLength()); IOUtils.copy(conn.getInputStream(), resp.getOutputStream()); } | 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; } | 900,130 |
0 | protected void writeSnapshot(final String message, final String details) { try { URL url = proxyAddress == null ? new URL(url_spec) : new URL("http", proxyAddress, proxyPort, url_spec); LOG.info("connect to " + url); URLConnection connection = url.openConnection(); connection.setDoOutput(true); HttpQueryWriter out = new HttpQueryWriter(connection.getOutputStream()); out.addParameter("error", message); out.addParameter("trace", details); out.close(); InputStream in = connection.getInputStream(); int c; StringBuffer result = new StringBuffer(); while ((c = in.read()) != -1) { result.append((char) c); } LOG.info(result); in.close(); } catch (UnknownHostException e) { LOG.info("could not find host (unknown host) to submit log to"); } catch (IOException e) { LOG.debug("i/o problem submitting log", e); } } | private void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); if (zShareAccount.loginsuccessful) { httppost.setHeader("Cookie", zShareAccount.getSidcookie() + ";" + zShareAccount.getMysessioncookie()); } else { httppost.setHeader("Cookie", sidcookie + ";" + mysessioncookie); } generateZShareID(); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("", new MonitoredFileBody(file, uploadProgress)); mpEntity.addPart("TOS", new StringBody("1")); httppost.setEntity(mpEntity); NULogger.getLogger().log(Level.INFO, "executing request {0}", httppost.getRequestLine()); status = UploadStatus.UPLOADING; NULogger.getLogger().info("Now uploading your file into zshare.net"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); NULogger.getLogger().info(response.getStatusLine().toString()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } uploadresponse = uploadresponse.replaceAll("\n", ""); uploadresponse = uploadresponse.substring(uploadresponse.indexOf("index2.php")); uploadresponse = uploadresponse.substring(0, uploadresponse.indexOf("\">here")); uploadresponse = uploadresponse.replaceAll("amp;", ""); if (zShareAccount.loginsuccessful) { uploadresponse = zShareAccount.getZsharelink() + uploadresponse; } else { uploadresponse = zsharelink + uploadresponse; } uploadresponse = uploadresponse.replaceAll(" ", "%20"); NULogger.getLogger().log(Level.INFO, "resp : {0}", uploadresponse); httpclient.getConnectionManager().shutdown(); } | 900,131 |
0 | private void criarQuestaoMultiplaEscolha(QuestaoMultiplaEscolha q) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO multipla_escolha (id_questao, texto, gabarito) VALUES (?,?,?)"; try { for (Alternativa alternativa : q.getAlternativa()) { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setString(2, alternativa.getTexto()); stmt.setBoolean(3, alternativa.getGabarito()); stmt.executeUpdate(); conexao.commit(); } } catch (SQLException e) { conexao.rollback(); throw e; } } | private String getEncryptedPassword() { String encrypted; char[] pwd = password.getPassword(); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(new String(pwd).getBytes("UTF-8")); byte[] digested = md.digest(); encrypted = new String(Base64Coder.encode(digested)); } catch (Exception e) { encrypted = new String(pwd); } for (int i = 0; i < pwd.length; i++) pwd[i] = 0; return encrypted; } | 900,132 |
0 | public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) throw new IOException("Source and destination cannot be the same file path"); FileChannel srcChannel = new FileInputStream(source).getChannel(); if (!dest.exists()) dest.createNewFile(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } | public void delUser(User user) throws SQLException, IOException, ClassNotFoundException { String dbUserID; String stockSymbol; Statement stmt = con.createStatement(); try { con.setAutoCommit(false); dbUserID = user.getUserID(); if (getUser(dbUserID) != null) { ResultSet rs1 = stmt.executeQuery("SELECT userID, symbol " + "FROM UserStocks WHERE userID = '" + dbUserID + "'"); while (rs1.next()) { try { stockSymbol = rs1.getString("symbol"); delUserStocks(dbUserID, stockSymbol); } catch (SQLException ex) { throw new SQLException("Deletion of user stock holding failed: " + ex.getMessage()); } } try { stmt.executeUpdate("DELETE FROM Users WHERE " + "userID = '" + dbUserID + "'"); } catch (SQLException ex) { throw new SQLException("User deletion failed: " + ex.getMessage()); } } else throw new IOException("User not found in database - cannot delete."); try { con.commit(); } catch (SQLException ex) { throw new SQLException("Transaction commit failed: " + ex.getMessage()); } } catch (SQLException ex) { try { con.rollback(); } catch (SQLException sqx) { throw new SQLException("Transaction failed then rollback failed: " + sqx.getMessage()); } throw new SQLException("Transaction failed; was rolled back: " + ex.getMessage()); } stmt.close(); } | 900,133 |
1 | public static boolean writeFileB2C(InputStream pIs, File pFile, boolean pAppend) { boolean flag = false; try { FileWriter fw = new FileWriter(pFile, pAppend); IOUtils.copy(pIs, fw); fw.flush(); fw.close(); pIs.close(); flag = true; } catch (Exception e) { LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; } | public ServiceAdapterIfc deploy(String session, String name, byte jarBytes[], String jarName, String serviceClass, String serviceInterface) throws RemoteException, MalformedURLException, StartServiceException, SessionException { try { File jarFile = new File(jarName); jarName = jarFile.getName(); String jarName2 = jarName; jarFile = new File(jarName2); int n = 0; while (jarFile.exists()) { jarName2 = jarName + n++; jarFile = new File(jarName2); } FileOutputStream fos = new FileOutputStream(jarName2); IOUtils.copy(new ByteArrayInputStream(jarBytes), fos); SCClassLoader cl = new SCClassLoader(new URL[] { new URL("file://" + jarFile.getAbsolutePath()) }, getMasterNode().getSCClassLoaderCounter()); return startService(session, name, serviceClass, serviceInterface, cl); } catch (SessionException e) { throw e; } catch (Exception e) { throw new StartServiceException("Could not deploy service: " + e.getMessage(), e); } } | 900,134 |
0 | private void downloadFile(String directory, String fileName) { URL url = null; String urlstr = updateURL + directory + fileName; int position = 0; try { Logger.msg(threadName + "Download new file from " + urlstr); url = new URL(urlstr); URLConnection conn = url.openConnection(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(updateDirectory + System.getProperty("file.separator") + fileName)); int i = in.read(); while (i != -1) { if (isInterrupted()) { setWasInterrupted(); in.close(); out.flush(); out.close(); interrupt(); return; } out.write(i); i = in.read(); position += 1; if (position % 1000 == 0) { Enumeration<DownloadFilesListener> en = listener.elements(); while (en.hasMoreElements()) { DownloadFilesListener currentListener = en.nextElement(); currentListener.progress(1000); } } } Enumeration<DownloadFilesListener> en = listener.elements(); while (en.hasMoreElements()) { DownloadFilesListener currentListener = en.nextElement(); currentListener.progress(1000); } in.close(); out.flush(); out.close(); Logger.msg(threadName + "Saved file " + fileName + " to " + updateDirectory + System.getProperty("file.separator") + fileName); } catch (Exception e) { Logger.err(threadName + "Error (" + e.toString() + ")"); } } | private ImageReader findImageReader(URL url) { ImageInputStream input = null; try { input = ImageIO.createImageInputStream(url.openStream()); } catch (IOException e) { logger.log(Level.WARNING, "zly adres URL obrazka " + url, e); } ImageReader reader = null; if (input != null) { Iterator readers = ImageIO.getImageReaders(input); while ((reader == null) && (readers != null) && readers.hasNext()) { reader = (ImageReader) readers.next(); } reader.setInput(input); } return reader; } | 900,135 |
1 | public void delete(int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); int max = findMaxRank(stmt); if ((row < 1) || (row > max)) throw new IllegalArgumentException("Row number not between 1 and " + max); stmt.executeUpdate("delete from WordClassifications where Rank = " + row); for (int i = row; i < max; ++i) stmt.executeUpdate("update WordClassifications set Rank = " + i + " where Rank = " + (i + 1)); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } | private void saveCampaign() throws HeadlessException { try { dbConnection.setAutoCommit(false); dbConnection.setSavepoint(); String sql = "UPDATE campaigns SET " + "queue = ? ," + "adjustRatioPeriod = ?, " + "asterisk = ?, " + "context = ?," + "extension = ?, " + "dialContext = ?, " + "dialPrefix = ?," + "dialTimeout = ?, " + "dialingMethod = ?," + "dialsPerFreeResourceRatio = ?, " + "maxIVRChannels = ?, " + "maxDialingThreads = ?," + "maxDialsPerFreeResourceRatio = ?," + "minDialsPerFreeResourceRatio = ?, " + "maxTries = ?, " + "firstRetryAfterMinutes = ?," + "secondRetryAfterMinutes = ?, " + "furtherRetryAfterMinutes = ?, " + "startDate = ?, " + "endDate = ?," + "popUpURL = ?, " + "contactBatchSize = ?, " + "retriesBatchPct = ?, " + "reschedulesBatchPct = ?, " + "allowReschedule = ?, " + "rescheduleToOnself = ?, " + "script = ?," + "agentsCanUpdateContacts = ?, " + "hideContactFields = ?, " + "afterCallWork = ?, " + "reserveAvailableAgents = ?, " + "useDNCList = ?, " + "enableAgentDNC = ?, " + "contactsFilter = ?, " + "DNCTo = ?," + "callRecordingPolicy = ?, " + "callRecordingPercent = ?, " + "callRecordingMaxAge = ?, " + "WHERE name = ?"; PreparedStatement statement = dbConnection.prepareStatement(sql); int i = 1; statement.setString(i++, txtQueue.getText()); statement.setInt(i++, Integer.valueOf(txtAdjustRatio.getText())); statement.setString(i++, ""); statement.setString(i++, txtContext.getText()); statement.setString(i++, txtExtension.getText()); statement.setString(i++, txtDialContext.getText()); statement.setString(i++, txtDialPrefix.getText()); statement.setInt(i++, 30000); statement.setInt(i++, cboDialingMethod.getSelectedIndex()); statement.setFloat(i++, Float.valueOf(txtInitialDialingRatio.getText())); statement.setInt(i++, Integer.valueOf(txtMaxIVRChannels.getText())); statement.setInt(i++, Integer.valueOf(txtDialLimit.getText())); statement.setFloat(i++, Float.valueOf(txtMaxDialingRatio.getText())); statement.setFloat(i++, Float.valueOf(txtMinDialingRatio.getText())); statement.setInt(i++, Integer.valueOf(txtMaxRetries.getText())); statement.setInt(i++, Integer.valueOf(txtFirstRetry.getText())); statement.setInt(i++, Integer.valueOf(txtSecondRetry.getText())); statement.setInt(i++, Integer.valueOf(txtFurtherRetries.getText())); statement.setDate(i++, Date.valueOf(txtStartDate.getText())); statement.setDate(i++, Date.valueOf(txtEndDate.getText())); statement.setString(i++, txtURL.getText()); statement.setInt(i++, Integer.valueOf(txtContactBatchSize.getText())); statement.setInt(i++, Integer.valueOf(txtRetryBatchPct.getText())); statement.setInt(i++, Integer.valueOf(txtRescheduleBatchPct.getText())); statement.setInt(i++, chkAgentCanReschedule.isSelected() ? 1 : 0); statement.setInt(i++, chkAgentCanRescheduleSelf.isSelected() ? 1 : 0); statement.setString(i++, txtScript.getText()); statement.setInt(i++, chkAgentCanUpdateContacts.isSelected() ? 1 : 0); statement.setString(i++, ""); statement.setInt(i++, Integer.valueOf(txtACW.getText())); statement.setInt(i++, Integer.valueOf(txtReserveAgents.getText())); statement.setInt(i++, cboDNCListPreference.getSelectedIndex()); statement.setInt(i++, 1); statement.setString(i++, ""); statement.setInt(i++, 0); statement.setInt(i++, cboRecordingPolicy.getSelectedIndex()); statement.setInt(i++, Integer.valueOf(txtRecordingPct.getText())); statement.setInt(i++, Integer.valueOf(txtRecordingMaxAge.getText())); statement.setString(i++, campaign); statement.executeUpdate(); dbConnection.commit(); } catch (SQLException ex) { try { dbConnection.rollback(); } catch (SQLException ex1) { Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex1); } JOptionPane.showMessageDialog(this.getRootPane(), ex.getLocalizedMessage(), "Error", JOptionPane.ERROR_MESSAGE); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex); } } | 900,136 |
0 | private FileLog(LOG_LEVEL displayLogLevel, LOG_LEVEL logLevel, String logPath) { this.logLevel = logLevel; this.displayLogLevel = displayLogLevel; if (null != logPath) { logFile = new File(logPath, "current.log"); log(LOG_LEVEL.DEBUG, "FileLog", "Initialising logfile " + logFile.getAbsolutePath() + " ."); try { if (logFile.exists()) { if (!logFile.renameTo(new File(logPath, System.currentTimeMillis() + ".log"))) { File newFile = new File(logPath, System.currentTimeMillis() + ".log"); if (newFile.exists()) { log(LOG_LEVEL.WARN, "FileLog", "The file (" + newFile.getAbsolutePath() + newFile.getName() + ") already exists, will overwrite it."); newFile.delete(); } newFile.createNewFile(); FileInputStream inStream = new FileInputStream(logFile); FileOutputStream outStream = new FileOutputStream(newFile); byte buffer[] = null; int offSet = 0; while (inStream.read(buffer, offSet, 2048) != -1) { outStream.write(buffer); offSet += 2048; } inStream.close(); outStream.close(); logFile.delete(); logFile = new File(logPath, "current.log"); } } logFile.createNewFile(); } catch (IOException e) { logFile = null; } } else { logFile = null; } } | public void addURL(String urlSpec) throws IOException { URL url = new URL(urlSpec); for (int i = 0; i < urls.size(); i++) { if (((URL) urls.elementAt(i)).equals(url)) { Logger.logWarning("Attempt to add an URL twice: " + url); return; } } InputStream stream = url.openStream(); stream.close(); urls.addElement(urlSpec); Logger.logDebug("Added " + url); } | 900,137 |
0 | private InputStream urlToInputStream(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setRequestProperty("User-Agent", IE); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.connect(); String encoding = conn.getContentEncoding(); if ((encoding != null) && encoding.equalsIgnoreCase("gzip")) return new GZIPInputStream(conn.getInputStream()); else if ((encoding != null) && encoding.equalsIgnoreCase("deflate")) return new InflaterInputStream(conn.getInputStream(), new Inflater(true)); else return conn.getInputStream(); } | public boolean openConnection(String url, Properties props) throws SQLException { try { Class.forName(RunConfig.getInstance().getDriverNameJDBC()); if (url == null) url = RunConfig.getInstance().getConnectionUrlJDBC(); connection = DriverManager.getConnection(url, props); if (statementTable == null) statementTable = new Hashtable<String, PreparedStatement>(); if (resultTable == null) resultTable = new Hashtable<String, ResultSet>(); clearStatus(); return true; } catch (Exception e) { setStatus(e); return false; } } | 900,138 |
0 | public Set<Plugin<?>> loadPluginImplementationMetaData() throws PluginRegistryException { try { final Enumeration<URL> urls = JavaSystemHelper.getResources(pluginImplementationMetaInfPath); pluginImplsSet.clear(); if (urls != null) { while (urls.hasMoreElements()) { final URL url = urls.nextElement(); echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.found", "classes", url.getPath())); InputStream resourceInput = null; Reader reader = null; BufferedReader buffReader = null; String line; try { resourceInput = url.openStream(); reader = new InputStreamReader(resourceInput); buffReader = new BufferedReader(reader); line = buffReader.readLine(); while (line != null) { try { pluginImplsSet.add(inspectPluginImpl(Class.forName(line.trim()))); echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.processing", "class", line)); line = buffReader.readLine(); } catch (final ClassNotFoundException cnfe) { throw new PluginRegistryException("plugin.error.load.classnotfound", cnfe, pluginImplementationMetaInfPath, line); } catch (final LinkageError ncfe) { if (LOGGER.isDebugEnabled()) { echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.linkageError", "class", line, ncfe.getMessage())); } line = buffReader.readLine(); } } } catch (final IOException ioe) { throw new PluginRegistryException("plugin.error.load.ioe", ioe, url.getFile(), ioe.getMessage()); } finally { if (buffReader != null) { buffReader.close(); } if (reader != null) { reader.close(); } if (resourceInput != null) { resourceInput.close(); } } } } return Collections.unmodifiableSet(pluginImplsSet); } catch (final IOException ioe) { throw new PluginRegistryException("plugin.error.load.ioe", ioe, pluginImplementationMetaInfPath, ioe.getMessage()); } } | private void processBasicContent() { String[] packageNames = sourceCollector.getPackageNames(); for (int i = 0; i < packageNames.length; i++) { XdcSource[] sources = sourceCollector.getXdcSources(packageNames[i]); File dir = new File(outputDir, packageNames[i]); dir.mkdirs(); Set pkgDirs = new HashSet(); for (int j = 0; j < sources.length; j++) { XdcSource source = sources[j]; Properties patterns = source.getPatterns(); if (patterns != null) { tables.put("patterns", patterns); } pkgDirs.add(source.getFile().getParentFile()); DialectHandler dialectHandler = source.getDialectHandler(); Writer out = null; try { String sourceFilePath = source.getFile().getAbsolutePath(); source.setProcessingProperties(baseProperties, j > 0 ? sources[j - 1].getFileName() : null, j < sources.length - 1 ? sources[j + 1].getFileName() : null); String rootComment = XslUtils.transformToString(sourceFilePath, XSL_PKG + "/source-header.xsl", tables); source.setRootComment(rootComment); Document htmlDoc = XslUtils.transform(sourceFilePath, encoding, dialectHandler.getXslResourcePath(), tables); if (LOG.isInfoEnabled()) { LOG.info("Processing source file " + sourceFilePath); } out = IOUtils.getWriter(new File(dir, source.getFile().getName() + ".html"), docencoding); XmlUtils.printHtml(out, htmlDoc); if (sourceProcessor != null) { sourceProcessor.processSource(source, encoding, docencoding); } XdcSource.clearProcessingProperties(baseProperties); } catch (XmlException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } for (Iterator iter = pkgDirs.iterator(); iter.hasNext(); ) { File docFilesDir = new File((File) iter.next(), "xdc-doc-files"); if (docFilesDir.exists() && docFilesDir.isDirectory()) { File targetDir = new File(dir, "xdc-doc-files"); targetDir.mkdirs(); try { IOUtils.copyTree(docFilesDir, targetDir); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } } | 900,139 |
0 | private void load() throws SQLException { Connection conn = null; Statement stmt = null; try { conn = FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); ClearData.clearTables(stmt); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (100, 'Person')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (101, 'john')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (200, 'Dog')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (201, 'johns dog')"); stmt.executeQuery("select setval('objects_objectid_seq', 1000)"); stmt.executeUpdate("insert into ClassLinkTypes (LinkName, LinkType) values ('hasa', 2)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (100, 'isa', 1)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (101, 'instance', 100)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (200, 'isa', 1)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (201, 'instance', 200)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (101, 'hasa', 201)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('LEFT-WALL', '1', 'QV+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('does', '1', 'HV+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('john', '1', 'S+ | DO-', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('a', '1', 'D+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('dog', '1', '[D-] & (S+ | DO-)', 200)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('have', '1', 'S- & HV- & QV- & DO+', 1)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('S', 1)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('DO', 3)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('QV', 8)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('D', 10)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('HV', 16)"); stmt.executeUpdate("insert into Articles (ArticleName, Dereference) values ('a', 2)"); stmt.executeUpdate("insert into FrameSlots (SlotName) values ('actor')"); stmt.executeUpdate("insert into FrameSlots (SlotName) values ('object')"); stmt.executeUpdate("insert into Verbs (VerbName, Type, SubjectSlot, IndirectObjectSlot, PredicateNounSlot) values ('have', 1, 'actor', '', 'object')"); stmt.executeUpdate("insert into ProperNouns (Noun, SenseNumber, ObjectId) values ('john', 1, 101)"); stmt.executeQuery("select setval('instructions_instructionid_seq', 1)"); stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (3, 'set_return_status true', null, 0, null, null, null)"); stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (3, 'set_return_status false', null, 0, null, null, null)"); stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (2, '', 'actor', 1, 'hasa', 200, null)"); stmt.executeUpdate("insert into InstructionGroups (InstructionId, Rank, GroupInstruction) " + "values (4, 1, 2)"); stmt.executeUpdate("insert into InstructionGroups (InstructionId, Rank, GroupInstruction) " + "values (4, 2, 3)"); stmt.executeQuery("select setval('transactions_transactionid_seq', 1)"); stmt.executeUpdate("insert into Transactions (InstructionId, Description) values (4, 'have - question')"); stmt.executeQuery("select setval('verbtransactions_verbid_seq', 1)"); stmt.executeUpdate("insert into VerbTransactions (VerbString, MoodType, TransactionId) values ('have', 3, 2)"); stmt.executeUpdate("insert into VerbConstraints (VerbId, FrameSlot, ObjectId) values (2, 'actor', 100)"); stmt.executeUpdate("insert into VerbConstraints (VerbId, FrameSlot, ObjectId) values (2, 'object', 200)"); stmt.executeUpdate("update SystemProperties set value = 'Tutorial 2 Data' where name = 'DB Data Version'"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } | InputStream createInputStream(FileInfo fi) throws IOException, MalformedURLException { if (fi.inputStream != null) return fi.inputStream; else if (fi.url != null && !fi.url.equals("")) return new URL(fi.url + fi.fileName).openStream(); else { File f = new File(fi.directory + fi.fileName); if (f == null || f.isDirectory()) return null; else { InputStream is = new FileInputStream(f); if (fi.compression >= FileInfo.LZW) is = new RandomAccessStream(is); return is; } } } | 900,140 |
0 | private static synchronized InputStream tryFailoverServer(String url, String currentlyActiveServer, int status, IOException e) throws MalformedURLException, IOException { logger.log(Level.WARNING, "problems connecting to geonames server " + currentlyActiveServer, e); if (geoNamesServerFailover == null || currentlyActiveServer.equals(geoNamesServerFailover)) { if (currentlyActiveServer.equals(geoNamesServerFailover)) { timeOfLastFailureMainServer = 0; } throw e; } timeOfLastFailureMainServer = System.currentTimeMillis(); logger.info("trying to connect to failover server " + geoNamesServerFailover); URLConnection conn = new URL(geoNamesServerFailover + url).openConnection(); String userAgent = USER_AGENT + " failover from " + geoNamesServer; if (status != 0) { userAgent += " " + status; } conn.setRequestProperty("User-Agent", userAgent); InputStream in = conn.getInputStream(); return in; } | 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(); } } | 900,141 |
1 | @Test public void testCopy_readerToOutputStream_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null); fail(); } catch (NullPointerException ex) { } } | public static void unZip(String unZipfileName, String outputDirectory) throws IOException, FileNotFoundException { FileOutputStream fileOut; File file; ZipEntry zipEntry; ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName)), encoder); while ((zipEntry = zipIn.getNextEntry()) != null) { file = new File(outputDirectory + File.separator + zipEntry.getName()); if (zipEntry.isDirectory()) { createDirectory(file.getPath(), ""); } else { File parent = file.getParentFile(); if (!parent.exists()) { createDirectory(parent.getPath(), ""); } fileOut = new FileOutputStream(file); int readedBytes; while ((readedBytes = zipIn.read(buf)) > 0) { fileOut.write(buf, 0, readedBytes); } fileOut.close(); } zipIn.closeEntry(); } } | 900,142 |
0 | private static String getHash(char[] passwd, String algorithm) throws NoSuchAlgorithmException { MessageDigest alg = MessageDigest.getInstance(algorithm); alg.reset(); alg.update(new String(passwd).getBytes()); byte[] digest = alg.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(0xff & digest[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } | public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } | 900,143 |
1 | public static void copyFile(File dst, File src, boolean append) throws FileNotFoundException, IOException { dst.createNewFile(); FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dst).getChannel(); long startAt = 0; if (append) startAt = out.size(); in.transferTo(startAt, in.size(), out); out.close(); in.close(); } | 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; } | 900,144 |
0 | public static String getFileContents(String path) { BufferedReader buffReader = null; if (path.indexOf("://") != -1) { URL url = null; try { url = new URL(path); } catch (MalformedURLException e) { logger.warn("Malformed URL: \"" + path + "\""); } try { String encoding = XMLKit.getDeclaredXMLEncoding(url.openStream()); buffReader = new BufferedReader(new InputStreamReader(url.openStream(), encoding)); } catch (IOException e) { logger.warn("I/O error trying to read \"" + path + "\""); } } else { File toRead = null; try { toRead = getExistingFile(path); } catch (FileNotFoundException e) { throw new UserError(new FileNotFoundException(path)); } if (toRead.isAbsolute()) { String parent = toRead.getParent(); try { workingDirectory.push(URLTools.createValidURL(parent)); } catch (FileNotFoundException e) { throw new DeveloperError("Created an invalid parent file: \"" + parent + "\".", e); } } if (toRead.exists() && !toRead.isDirectory()) { path = toRead.getAbsolutePath(); try { String encoding = XMLKit.getDeclaredXMLEncoding(new FileInputStream(path)); buffReader = new BufferedReader(new InputStreamReader(new FileInputStream(path), encoding)); } catch (IOException e) { logger.warn("I/O error trying to read \"" + path + "\""); return null; } } else { assert toRead.exists() : "getExistingFile() returned a non-existent file"; if (toRead.isDirectory()) { throw new UserError(new FileAlreadyExistsAsDirectoryException(toRead)); } } } StringBuilder result = new StringBuilder(); String line; try { while ((line = buffReader.readLine()) != null) { result.append(line); } buffReader.close(); } catch (IOException e) { logger.warn("I/O error trying to read \"" + path + "\""); return null; } return result.toString(); } | protected void setOuterIP() { try { URL url = new URL("http://elm-ve.sf.net/ipCheck/ipCheck.cgi"); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String ip = br.readLine(); ip = ip.trim(); bridgeOutIPTF.setText(ip); } catch (Exception e) { e.printStackTrace(); } } | 900,145 |
1 | public static void joinFiles(FileValidator validator, File target, File[] sources) { FileOutputStream fos = null; try { if (!validator.verifyFile(target)) return; fos = new FileOutputStream(target); FileInputStream fis = null; byte[] bytes = new byte[512]; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); int nbread = 0; try { while ((nbread = fis.read(bytes)) > -1) { fos.write(bytes, 0, nbread); } } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { fis.close(); } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } } | @RequestMapping(value = "/privatefiles/{file_name}") public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) { try { Boolean validUser = false; final String currentUser = principal.getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!auth.getPrincipal().equals(new String("anonymousUser"))) { MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal(); if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true; } if (currentUser != null) { Study study = studyService.getBiiStudy(fileName, true); Collection<User> users = study.getUsers(); Iterator<User> iter = users.iterator(); while (iter.hasNext()) { User user = iter.next(); if (user.getUserName().equals(currentUser)) { validUser = true; break; } } } if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised")); try { InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip"); response.setContentType("application/zip"); IOUtils.copy(is, response.getOutputStream()); } catch (Exception e) { throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing")); } response.flushBuffer(); } catch (IOException ex) { logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); throw new RuntimeException("IOError writing file to output stream"); } } | 900,146 |
0 | public void saveUserUpFile(UserInfo userInfo, String distFileName, InputStream instream) throws IOException { String fullPicFile = BBSCSUtil.getUserWebFilePath(userInfo.getId()) + distFileName; String fullPicFileSmall = BBSCSUtil.getUserWebFilePath(userInfo.getId()) + distFileName + Constant.IMG_SMALL_FILEPREFIX; OutputStream bos = new FileOutputStream(fullPicFile); IOUtils.copy(instream, bos); ImgUtil.reduceImg(fullPicFile, fullPicFileSmall, this.getSysConfig().getFaceWidth(), this.getSysConfig().getFaceHigh(), 0); } | public String getWebcontent(final String link, final String postdata) { final StringBuffer response = new StringBuffer(); try { DisableSSLCertificateCheckUtil.disableChecks(); final URL url = new URL(link); final URLConnection conn = url.openConnection(); conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(postdata); wr.flush(); final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String content = ""; while ((content = rd.readLine()) != null) { response.append(content); response.append('\n'); } wr.close(); rd.close(); } catch (final Exception e) { LOG.error("getWebcontent(String link, String postdata): " + e.toString() + "\012" + link + "\012" + postdata); } return response.toString(); } | 900,147 |
1 | public static void main(String[] argv) { if (1 < argv.length) { File[] sources = Source(argv[0]); if (null != sources) { for (File src : sources) { File[] targets = Target(src, argv); if (null != targets) { final long srclen = src.length(); try { FileChannel source = new FileInputStream(src).getChannel(); try { for (File tgt : targets) { FileChannel target = new FileOutputStream(tgt).getChannel(); try { source.transferTo(0L, srclen, target); } finally { target.close(); } System.out.printf("Updated %s\n", tgt.getPath()); File[] deletes = Delete(src, tgt); if (null != deletes) { for (File del : deletes) { if (SVN) { if (SvnDelete(del)) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } else if (del.delete()) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } } if (SVN) SvnAdd(tgt); } } finally { source.close(); } } catch (Exception exc) { exc.printStackTrace(); System.exit(1); } } } System.exit(0); } else { System.err.printf("Source file(s) not found in '%s'\n", argv[0]); System.exit(1); } } else { usage(); System.exit(1); } } | 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; } | 900,148 |
1 | public static java.io.ByteArrayOutputStream getFileByteStream(URL _url) { java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); try { InputStream input = _url.openStream(); IOUtils.copy(input, buffer); IOUtils.closeQuietly(input); } catch (Exception err) { throw new RuntimeException(err); } return buffer; } | public static final void zip(final ZipOutputStream out, final File f, String base) throws Exception { if (f.isDirectory()) { final File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (final File element : fl) { zip(out, element, base + element.getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); final FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); } | 900,149 |
0 | public void runTask(HashMap pjobParms) throws Exception { FTPClient lftpClient = null; FileInputStream lfisSourceFile = null; JBJFPluginDefinition lpluginCipher = null; IJBJFPluginCipher theCipher = null; try { JBJFFTPDefinition lxmlFTP = null; if (getFTPDefinition() != null) { lxmlFTP = getFTPDefinition(); this.mstrSourceDirectory = lxmlFTP.getSourceDirectory(); this.mstrTargetDirectory = lxmlFTP.getTargetDirectory(); this.mstrFilename = lxmlFTP.getFilename(); this.mstrRemoteServer = lxmlFTP.getServer(); if (getResources().containsKey("plugin-cipher")) { lpluginCipher = (JBJFPluginDefinition) getResources().get("plugin-cipher"); } if (lpluginCipher != null) { theCipher = getTaskPlugins().getCipherPlugin(lpluginCipher.getPluginId()); } if (theCipher != null) { this.mstrServerUsr = theCipher.decryptString(lxmlFTP.getUser()); this.mstrServerPwd = theCipher.decryptString(lxmlFTP.getPass()); } else { this.mstrServerUsr = lxmlFTP.getUser(); this.mstrServerPwd = lxmlFTP.getPass(); } } else { throw new Exception("Work unit [ " + SHORT_NAME + " ] is missing an FTP Definition. Please check" + " your JBJF Batch Definition file an make sure" + " this work unit has a <resource> element added" + " within the <task> element."); } lfisSourceFile = new FileInputStream(mstrSourceDirectory + File.separator + mstrFilename); lftpClient = new FTPClient(); lftpClient.connect(mstrRemoteServer); lftpClient.setFileType(lxmlFTP.getFileTransferType()); if (!FTPReply.isPositiveCompletion(lftpClient.getReplyCode())) { throw new Exception("FTP server [ " + mstrRemoteServer + " ] refused connection."); } if (!lftpClient.login(mstrServerUsr, mstrServerPwd)) { throw new Exception("Unable to login to server [ " + mstrTargetDirectory + " ]."); } if (!lftpClient.changeWorkingDirectory(mstrTargetDirectory)) { throw new Exception("Unable to change to remote directory [ " + mstrTargetDirectory + "]"); } lftpClient.enterLocalPassiveMode(); if (!lftpClient.storeFile(mstrFilename, lfisSourceFile)) { throw new Exception("Unable to upload [ " + mstrSourceDirectory + "/" + mstrFilename + " ]" + " to " + mstrTargetDirectory + File.separator + mstrFilename + " to " + mstrRemoteServer); } lfisSourceFile.close(); lftpClient.logout(); } catch (Exception e) { throw e; } finally { if (lftpClient != null && lftpClient.isConnected()) { try { lftpClient.disconnect(); } catch (IOException ioe) { } } if (lfisSourceFile != null) { try { lfisSourceFile.close(); } catch (Exception e) { } } } } | public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } | 900,150 |
1 | public static java.io.ByteArrayOutputStream getFileByteStream(URL _url) { java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); try { InputStream input = _url.openStream(); IOUtils.copy(input, buffer); IOUtils.closeQuietly(input); } catch (Exception err) { throw new RuntimeException(err); } return buffer; } | private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir, BackUpInfoFileGroup fileGroup, LinkedList<String> restoreList) { LinkedList<BackUpInfoFile> fileList = fileGroup.getFileList(); if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } for (int i = 0; i < fileList.size(); i++) { if (fileList.get(i).getId().equals(entry.getName())) { for (int j = 0; j < restoreList.size(); j++) { if ((fileList.get(i).getName() + "." + fileList.get(i).getType()).equals(restoreList.get(j))) { counter += 1; File outputFile = new File(outputDir, fileList.get(i).getName() + "." + fileList.get(i).getType()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream; BufferedOutputStream outputStream; try { inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException ex) { throw new BackupException(ex.getMessage()); } } } } } } | 900,151 |
1 | 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(); } } | protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } } | 900,152 |
0 | public static String sendGetRequest(String endpoint, String requestParameters) { if (endpoint == null) return null; String result = null; if (endpoint.startsWith("http://")) { try { StringBuffer data = new StringBuffer(); String urlStr = endpoint; if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); result = sb.toString(); } catch (Exception e) { Logger.getLogger(HTTPClient.class.getClass().getName()).log(Level.FINE, "Could not connect to URL, is the service online?"); } } return result; } | @SuppressWarnings("finally") private void compress(File src) throws IOException { if (this.switches.contains(Switch.test)) return; checkSourceFile(src); if (src.getPath().endsWith(".bz2")) { this.log.println("WARNING: skipping file because it already has .bz2 suffix:").println(src); return; } final File dst = new File(src.getPath() + ".bz2").getAbsoluteFile(); if (!checkDestFile(dst)) return; FileChannel inChannel = null; FileChannel outChannel = null; FileOutputStream fileOut = null; BZip2OutputStream bzOut = null; FileLock inLock = null; FileLock outLock = null; try { inChannel = new FileInputStream(src).getChannel(); final long inSize = inChannel.size(); inLock = inChannel.tryLock(0, inSize, true); if (inLock == null) throw error("source file locked by another process: " + src); fileOut = new FileOutputStream(dst); outChannel = fileOut.getChannel(); bzOut = new BZip2OutputStream( new BufferedXOutputStream(fileOut, 8192), Math.min( (this.blockSize == -1) ? BZip2OutputStream.MAX_BLOCK_SIZE : this.blockSize, BZip2OutputStream.chooseBlockSize(inSize) ) ); outLock = outChannel.tryLock(); if (outLock == null) throw error("destination file locked by another process: " + dst); final boolean showProgress = this.switches.contains(Switch.showProgress); long pos = 0; int progress = 0; if (showProgress || this.verbose) { this.log.print("source: " + src).print(": size=").println(inSize); this.log.println("target: " + dst); } while (true) { final long maxStep = showProgress ? Math.max(8192, (inSize - pos) / MAX_PROGRESS) : (inSize - pos); if (maxStep <= 0) { if (showProgress) { for (int i = progress; i < MAX_PROGRESS; i++) this.log.print('#'); this.log.println(" done"); } break; } else { final long step = inChannel.transferTo(pos, maxStep, bzOut); if ((step == 0) && (inChannel.size() != inSize)) throw error("file " + src + " has been modified concurrently by another process"); pos += step; if (showProgress) { final double p = (double) pos / (double) inSize; final int newProgress = (int) (MAX_PROGRESS * p); for (int i = progress; i < newProgress; i++) this.log.print('#'); progress = newProgress; } } } inLock.release(); inChannel.close(); bzOut.closeInstance(); final long outSize = outChannel.position(); outChannel.truncate(outSize); outLock.release(); fileOut.close(); if (this.verbose) { final double ratio = (inSize == 0) ? (outSize * 100) : ((double) outSize / (double) inSize); this.log.print("raw size: ").print(inSize) .print("; compressed size: ").print(outSize) .print("; compression ratio: ").print(ratio).println('%'); } if (!this.switches.contains(Switch.keep)) { if (!src.delete()) throw error("unable to delete sourcefile: " + src); } } catch (final IOException ex) { IO.tryClose(inChannel); IO.tryClose(bzOut); IO.tryClose(fileOut); IO.tryRelease(inLock); IO.tryRelease(outLock); try { this.log.println(); } finally { throw ex; } } } | 900,153 |
1 | public void testAddFiles() throws Exception { File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip")); File copy = new File(original.getParentFile(), "1test.zip"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(original); out = new FileOutputStream(copy); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath())); archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor()); IArchive[] children = archive.getChildren(); boolean found = false; for (IArchive child : children) { if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true; } assertTrue(found); copy.delete(); } | @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(targetPath + filename)); IOUtils.copy(is, fos); response.setStatus(HttpServletResponse.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); } | 900,154 |
1 | public static void copy(String a, String b) throws IOException { File inputFile = new File(a); File outputFile = new File(b); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } | 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(); } | 900,155 |
0 | protected String readFileUsingHttp(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Type", "text/html"); httpConn.setRequestProperty("Content-Length", "0"); httpConn.setRequestMethod("GET"); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setAllowUserInteraction(false); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; } | public void testReplicateAfterWrite2Slave() throws Exception { int nDocs = 50; for (int i = 0; i < nDocs; i++) { index(masterClient, "id", i, "name", "name = " + i); } String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=disableReplication"; URL url = new URL(masterUrl); InputStream stream = url.openStream(); try { stream.close(); } catch (IOException e) { } masterClient.commit(); NamedList masterQueryRsp = query("*:*", masterClient); SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response"); assertEquals(nDocs, masterQueryResult.getNumFound()); Thread.sleep(100); index(slaveClient, "id", 551, "name", "name = " + 551); slaveClient.commit(true, true); index(slaveClient, "id", 552, "name", "name = " + 552); slaveClient.commit(true, true); index(slaveClient, "id", 553, "name", "name = " + 553); slaveClient.commit(true, true); index(slaveClient, "id", 554, "name", "name = " + 554); slaveClient.commit(true, true); index(slaveClient, "id", 555, "name", "name = " + 555); slaveClient.commit(true, true); NamedList slaveQueryRsp = query("id:555", slaveClient); SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(1, slaveQueryResult.getNumFound()); masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=enableReplication"; url = new URL(masterUrl); stream = url.openStream(); try { stream.close(); } catch (IOException e) { } Thread.sleep(3000); slaveQueryRsp = query("id:555", slaveClient); slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(0, slaveQueryResult.getNumFound()); } | 900,156 |
0 | private boolean saveDocumentXml(String repository, String tempRepo) { boolean result = true; try { XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "documents/document"; InputSource insource = new InputSource(new FileInputStream(tempRepo + File.separator + AppConstants.DMS_XML)); NodeList nodeList = (NodeList) xpath.evaluate(expression, insource, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); System.out.println(node.getNodeName()); DocumentModel document = new DocumentModel(); NodeList childs = node.getChildNodes(); for (int j = 0; j < childs.getLength(); j++) { Node child = childs.item(j); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName() != null && child.getFirstChild() != null && child.getFirstChild().getNodeValue() != null) { System.out.println(child.getNodeName() + "::" + child.getFirstChild().getNodeValue()); } if (Document.FLD_ID.equals(child.getNodeName())) { if (child.getFirstChild() != null) { String szId = child.getFirstChild().getNodeValue(); if (szId != null && szId.length() > 0) { try { document.setId(new Long(szId)); } catch (Exception e) { e.printStackTrace(); } } } } else if (document.FLD_NAME.equals(child.getNodeName())) { document.setName(child.getFirstChild().getNodeValue()); document.setTitle(document.getName()); document.setDescr(document.getName()); document.setExt(getExtension(document.getName())); } else if (document.FLD_LOCATION.equals(child.getNodeName())) { document.setLocation(child.getFirstChild().getNodeValue()); } else if (document.FLD_OWNER.equals(child.getNodeName())) { Long id = new Long(child.getFirstChild().getNodeValue()); User user = new UserModel(); user.setId(id); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setOwner(user); } } } } boolean isSave = docService.save(document); if (isSave) { String repo = preference.getRepository(); 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 fileFolder = new File(sbRepo.append(sbFolder).toString()); if (!fileFolder.exists()) { fileFolder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(fileFolder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(tempRepo + File.separator + document.getName()).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); document.setSize(fcSource.size()); log.info("Batch upload file " + document.getName() + " into [" + document.getLocation() + "] as " + document.getName() + "." + document.getExt()); folder.setId(DEFAULT_FOLDER); folder = (Folder) folderService.find(folder); if (folder != null && folder.getId() != null) { document.setFolder(folder); } workspace.setId(DEFAULT_WORKSPACE); workspace = (Workspace) workspaceService.find(workspace); if (workspace != null && workspace.getId() != null) { document.setWorkspace(workspace); } user.setId(DEFAULT_USER); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setCrtby(user.getId()); } document.setCrtdate(new Date()); document = (DocumentModel) docService.resetDuplicateDocName(document); docService.save(document); DocumentIndexer.indexDocument(preference, document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } } } catch (Exception e) { result = false; e.printStackTrace(); } return result; } | public static final String getUniqueKey() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; ; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { println("Warn: getUniqueKey(), Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { println("Warn: getUniqueKey() " + e); } return digest; } | 900,157 |
0 | public TextureData newTextureData(GLProfile glp, URL url, int internalFormat, int pixelFormat, boolean mipmap, String fileSuffix) throws IOException { InputStream stream = new BufferedInputStream(url.openStream()); try { return newTextureData(glp, stream, internalFormat, pixelFormat, mipmap, fileSuffix); } finally { stream.close(); } } | public static String calcCRC(String phrase) { StringBuffer crcCalc = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(phrase.getBytes()); byte[] tabDigest = md.digest(); for (int i = 0; i < tabDigest.length; i++) { String octet = "0" + Integer.toHexString(tabDigest[i]); crcCalc.append(octet.substring(octet.length() - 2)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return crcCalc.toString(); } | 900,158 |
0 | public TreeMap getStrainMap() { TreeMap strainMap = new TreeMap(); String server = ""; try { Datasource[] ds = DatasourceManager.getDatasouce(alias, version, DatasourceManager.ALL_CONTAINS_GROUP); for (int i = 0; i < ds.length; i++) { if (ds[i].getDescription().startsWith(MOUSE_DBSNP)) { if (ds[i].getServer().length() == 0) { Connection con = ds[i].getConnection(); strainMap = Action.lineMode.regularSQL.GenotypeDataSearchAction.getStrainMap(con); break; } else { server = ds[i].getServer(); HashMap serverUrlMap = InitXml.getInstance().getServerMap(); String serverUrl = (String) serverUrlMap.get(server); URL url = new URL(serverUrl + servletName); URLConnection uc = url.openConnection(); uc.setDoOutput(true); OutputStream os = uc.getOutputStream(); StringBuffer buf = new StringBuffer(); buf.append("viewType=getstrains"); buf.append("&hHead=" + hHead); buf.append("&hCheck=" + version); PrintStream ps = new PrintStream(os); ps.print(buf.toString()); ps.close(); ObjectInputStream ois = new ObjectInputStream(uc.getInputStream()); strainMap = (TreeMap) ois.readObject(); ois.close(); } } } } catch (Exception e) { log.error("strain map", e); } return strainMap; } | public GGPhotoInfo getPhotoInfo(String photoId, String language) throws IllegalStateException, GGException, Exception { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("method", "gg.photos.getInfo")); qparams.add(new BasicNameValuePair("key", this.key)); qparams.add(new BasicNameValuePair("photo_id", photoId)); if (null != language) { qparams.add(new BasicNameValuePair("language", language)); } String url = REST_URL + "?" + URLEncodedUtils.format(qparams, "UTF-8"); URI uri = new URI(url); HttpGet httpget = new HttpGet(uri); HttpResponse response = httpClient.execute(httpget); int status = response.getStatusLine().getStatusCode(); errorCheck(response, status); InputStream content = response.getEntity().getContent(); GGPhotoInfo photo = JAXB.unmarshal(content, GGPhotoInfo.class); return photo; } | 900,159 |
0 | public In(URL url) { try { URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(is, charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println("Could not open " + url); } } | public static final String convertPassword(final String srcPwd) { StringBuilder out; MessageDigest md; byte[] byteValues; byte singleChar = 0; try { md = MessageDigest.getInstance("MD5"); md.update(srcPwd.getBytes()); byteValues = md.digest(); if ((byteValues == null) || (byteValues.length <= 0)) { return null; } out = new StringBuilder(byteValues.length * 2); for (byte element : byteValues) { singleChar = (byte) (element & 0xF0); singleChar = (byte) (singleChar >>> 4); singleChar = (byte) (singleChar & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); singleChar = (byte) (element & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); } return out.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } | 900,160 |
0 | public void testCopyFolderContents() throws IOException { log.info("Running: testCopyFolderContents()"); IOUtils.copyFolderContents(srcFolderName, destFolderName); Assert.assertTrue(destFile1.exists() && destFile1.isFile()); Assert.assertTrue(destFile2.exists() && destFile2.isFile()); Assert.assertTrue(destFile3.exists() && destFile3.isFile()); } | public String getImageURL(String text) { String imgURL = ""; try { URL url = new URL("http://images.search.yahoo.com/search/images?p=" + URLEncoder.encode(text)); URLConnection connection = url.openConnection(); DataInputStream in = new DataInputStream(connection.getInputStream()); String line; Pattern imgPattern = Pattern.compile("isrc=\"([^\"]*)\""); while ((line = in.readLine()) != null) { Matcher match = imgPattern.matcher(line); if (match.find()) { imgURL = match.group(1); break; } } in.close(); } catch (Exception e) { } return imgURL; } | 900,161 |
0 | private String getData(String myurl) throws Exception { URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); uc.setRequestProperty("Cookie", NetLoadAccount.getPhpsessioncookie()); br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { k += temp; } br.close(); return k; } | private void bubbleSort(int[] mas) { boolean t = true; int temp = 0; while (t) { t = false; for (int i = 0; i < mas.length - 1; i++) { if (mas[i] > mas[i + 1]) { temp = mas[i]; mas[i] = mas[i + 1]; mas[i + 1] = temp; t = true; } } } } | 900,162 |
1 | public static void copyFile5(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copyLarge(in, out); in.close(); out.close(); } | public void run() { saveWLHome(); for (final TabControl control : tabControls) { control.performOk(WLPropertyPage.this.getProject(), WLPropertyPage.this); } if (isEnabledJCLCopy()) { final File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File log4jLibrary = new File(lib, "log4j-1.2.13.jar"); if (!log4jLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jcl/log4j-1.2.13.jar")); fos = new FileOutputStream(log4jLibrary); IOUtils.copy(srcFile, fos); srcFile.close(); fos.flush(); fos.close(); srcFile = toInputStream(new Path("/jcl/commons-logging-1.0.4.jar")); File jcl = new File(lib, "commons-logging-1.0.4.jar"); fos = new FileOutputStream(jcl); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy JCL jars file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } } if (isEnabledJSTLCopy()) { File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File jstlLibrary = new File(lib, "jstl.jar"); if (!jstlLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jstl/jstl.jar")); fos = new FileOutputStream(jstlLibrary); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the JSTL 1.1 jar file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (final IOException e) { Logger.getLog().debug("I/O exception closing resources", e); } } } } } | 900,163 |
0 | void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); } | public static String encode(String str) { String md5Str = null; try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(str.getBytes("UTF8")); byte[] hash = digest.digest(); md5Str = ""; for (int i = 0; i < hash.length; i++) { md5Str += Integer.toHexString((0x000000ff & hash[i]) | 0xffffff00).substring(6); } } catch (Exception e) { e.printStackTrace(); } return md5Str; } | 900,164 |
0 | public String getFeatureInfoHTML(Point3d GKposition, String[] layerIds, int featureCount) { String html = ""; try { String request = null; if (version == VERSION_030) { org.gdi3d.xnavi.services.w3ds.x030.GetFeatureInfo getFeatureInfo = new org.gdi3d.xnavi.services.w3ds.x030.GetFeatureInfo(this.serviceEndPoint); request = getFeatureInfo.createRequest(GKposition, layerIds, featureCount); } else if (version == VERSION_040) { org.gdi3d.xnavi.services.w3ds.x040.GetFeatureInfo getFeatureInfo = new org.gdi3d.xnavi.services.w3ds.x040.GetFeatureInfo(this.serviceEndPoint); request = getFeatureInfo.createRequest(GKposition, layerIds, featureCount); } else if (version == VERSION_041) { org.gdi3d.xnavi.services.w3ds.x041.GetFeatureInfo getFeatureInfo = new org.gdi3d.xnavi.services.w3ds.x041.GetFeatureInfo(this.serviceEndPoint); request = getFeatureInfo.createRequest(GKposition, layerIds, featureCount); } if (Navigator.isVerbose()) System.out.println(request); URL url = new URL(request); int contentLength = -1; URLConnection urlc; urlc = url.openConnection(); urlc.setReadTimeout(Navigator.TIME_OUT); if (getEncoding() != null) { urlc.setRequestProperty("Authorization", "Basic " + getEncoding()); } urlc.connect(); String content_type = urlc.getContentType(); if (content_type.equalsIgnoreCase("text/html") || content_type.equalsIgnoreCase("text/html;charset=UTF-8")) { InputStream is = urlc.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); StringBuffer sb = new StringBuffer(); InputStreamReader isr = new InputStreamReader(bis); char chars[] = new char[10240]; int len = 0; contentLength = 0; while ((len = isr.read(chars, 0, chars.length)) >= 0) { sb.append(chars, 0, len); contentLength += len; } chars = null; isr.close(); bis.close(); is.close(); html = sb.toString(); } } catch (Exception e) { e.printStackTrace(); } return html; } | public static Image getImage(URL url) throws IOException { InputStream is = null; try { is = url.openStream(); Image img = getImage(is); img.setUrl(url); return img; } finally { if (is != null) { is.close(); } } } | 900,165 |
1 | private String getStoreName() { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(protectionDomain.getBytes()); final byte[] bs = digest.digest(); final StringBuffer sb = new StringBuffer(bs.length * 2); for (int i = 0; i < bs.length; i++) { final String s = Integer.toHexString(bs[i] & 0xff); if (s.length() < 2) sb.append('0'); sb.append(s); } return sb.toString(); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Can't save credentials: digest method MD5 unavailable."); } } | public static String encrypt(String unencryptedString) { if (StringUtils.isBlank(unencryptedString)) { throw new IllegalArgumentException("Cannot encrypt a null or empty string"); } MessageDigest md = null; String encryptionAlgorithm = Environment.getValue(Environment.PROP_ENCRYPTION_ALGORITHM); try { md = MessageDigest.getInstance(encryptionAlgorithm); } catch (NoSuchAlgorithmException e) { logger.warn("JDK does not support the " + encryptionAlgorithm + " encryption algorithm. Weaker encryption will be attempted."); } if (md == null) { try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException("JDK does not support the SHA-1 or SHA-512 encryption algorithms"); } Environment.setValue(Environment.PROP_ENCRYPTION_ALGORITHM, "SHA-1"); try { Environment.saveConfiguration(); } catch (WikiException e) { logger.info("Failure while saving encryption algorithm property", e); } } try { md.update(unencryptedString.getBytes("UTF-8")); byte raw[] = md.digest(); return encrypt64(raw); } catch (GeneralSecurityException e) { logger.error("Encryption failure", e); throw new IllegalStateException("Failure while encrypting value"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Unsupporting encoding UTF-8"); } } | 900,166 |
0 | @Override public synchronized void deleteHttpSessionStatistics(String contextName, String project, Date dateFrom, Date dateTo) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getHttpSessionInvocationsSchemaAndTableName() + " FROM " + this.getHttpSessionInvocationsSchemaAndTableName() + " INNER JOIN " + this.getHttpSessionElementsSchemaAndTableName() + " ON " + this.getHttpSessionElementsSchemaAndTableName() + ".element_id = " + this.getHttpSessionInvocationsSchemaAndTableName() + ".element_id WHERE "; if (contextName != null) { queryString = queryString + " context_name LIKE ? AND "; } if (project != null) { queryString = queryString + " project LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + " start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + " start_timestamp <= ? AND "; } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if (project != null) { preparedStatement.setString(indexCounter, project); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting HTTP session statistics.", e); } finally { this.releaseConnection(connection); } } | private void runUpdateAppListing() { DataStorage.clearListedAppListing(); GenericUrl url = new GoogleUrl(EnterpriseMarketplaceUrl.generateAppListingUrl() + DataStorage.getVendorProfile().vendorId); AppListing appListingBody = buildAppListing(appsMarketplaceProject); JsonHttpContent content = new JsonHttpContent(); content.jsonFactory = jsonFactory; if (appListingBody != null) { content.data = appListingBody; } AppListing appListing; try { HttpRequest request = requestFactory.buildPutRequest(url, content); request.addParser(jsonHttpParser); request.readTimeout = readTimeout; HttpResponse response = request.execute(); appListing = response.parseAs(AppListing.class); operationStatus = validateAppListing(appListing, appListingBody); if (operationStatus) { DataStorage.setListedAppListing(appListing); } response.getContent().close(); } catch (IOException e) { AppsMarketplacePluginLog.logError(e); } } | 900,167 |
1 | @Override public void excluir(Disciplina t) throws Exception { PreparedStatement stmt = null; String sql = "DELETE from disciplina where id_disciplina = ?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, t.getIdDisciplina()); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } finally { try { stmt.close(); conexao.close(); } catch (SQLException e) { throw e; } } } | public static void main(String[] args) { try { Class.forName("org.hsqldb.jdbcDriver"); } catch (ClassNotFoundException e) { System.out.println("HSQL Driver not found."); System.exit(1); } Connection con = null; try { con = DriverManager.getConnection("jdbc:hsqldb:.", "sa", ""); con.setAutoCommit(false); } catch (SQLException e) { System.out.println("Connection error: " + e.getMessage()); System.exit(e.getErrorCode()); } String createTable = "CREATE TABLE NAMES (NAME VARCHAR(100))"; Statement stmt = null; try { stmt = con.createStatement(); con.commit(); stmt.executeUpdate(createTable); con.commit(); } catch (SQLException e) { System.out.println("Create table error: " + e.getMessage()); try { con.rollback(); con.close(); System.exit(e.getErrorCode()); } catch (SQLException ex) { } } Vector names = new Vector(4); names.addElement("FRANK"); names.addElement("FRED"); names.addElement("JACK"); names.addElement("JIM"); String ins = "INSERT INTO NAMES VALUES (?)"; PreparedStatement pstmt = null; try { con.commit(); pstmt = con.prepareStatement(ins); for (int i = 0; i < names.size(); i++) { pstmt.setString(1, (String) names.elementAt(i)); pstmt.executeUpdate(); } con.commit(); } catch (SQLException e) { System.out.println("Insert error: " + e.getMessage()); try { con.rollback(); con.close(); System.exit(e.getErrorCode()); } catch (SQLException ex) { } } String selAll = "SELECT * FROM NAMES"; ResultSet rs = null; stmt = null; try { stmt = con.createStatement(); rs = stmt.executeQuery(selAll); System.out.println("SELECT * FROM NAMES"); while (rs.next()) { String name = rs.getString(1); System.out.println("\t" + name); } stmt.close(); } catch (SQLException e) { System.out.println("Select All error: " + e.getMessage()); try { con.close(); System.exit(e.getErrorCode()); } catch (SQLException ex) { } } String selectLike = "SELECT * FROM NAMES WHERE NAME LIKE 'F%'"; rs = null; stmt = null; try { stmt = con.createStatement(); rs = stmt.executeQuery(selectLike); System.out.println("SELECT * FROM NAMES WHERE NAME LIKE 'F%'"); while (rs.next()) { String name = rs.getString(1); System.out.println("\t" + name); } stmt.close(); } catch (SQLException e) { System.out.println("Select Like error: " + e.getMessage()); try { con.close(); System.exit(e.getErrorCode()); } catch (SQLException ex) { } } try { con.close(); } catch (SQLException e) { } } | 900,168 |
1 | public Stopper(String stopWordsFile) { try { BufferedReader br = null; FileReader fr = null; if (stopWordsFile.startsWith("http")) { URL url = new URL(stopWordsFile); br = new BufferedReader(new InputStreamReader(url.openStream())); } else { fr = new FileReader(new File(stopWordsFile)); br = new BufferedReader(fr); } String line = null; while ((line = br.readLine()) != null) { line = line.trim(); stopWords.put(line, ""); } fr.close(); } catch (Exception e) { System.out.println("Stopwords not Found"); return; } } | public static void main(String arg[]) { try { URL url = new URL(tempurl); HttpURLConnection connect = (HttpURLConnection) url.openConnection(); connect.setDoInput(true); connect.setDoOutput(true); BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream(), "gb2312")); String line = null; StringBuffer content = new StringBuffer(); while ((line = in.readLine()) != null) { content.append(line); } in.close(); url = null; String msg = content.toString(); Matcher m = p.matcher(msg); while (m.find()) { System.out.println(m.group(1) + "---" + m.group(2) + "---" + m.group(3) + "---" + m.group(4) + "---" + m.group(5) + "---"); } } catch (Exception e) { System.out.println("Error:"); System.out.println(e.getStackTrace()); } } | 900,169 |
1 | public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new OutputStream() { @Override public void write(byte[] b, int off, int len) { } @Override public void write(int b) { } @Override public void write(byte[] b) throws IOException { } }); } finally { IOUtils.closeQuietly(in); } return checksum; } | private static FileEntry writeEntry(Zip64File zip64File, FileEntry targetPath, File toWrite, boolean compress) { InputStream in = null; EntryOutputStream out = null; processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath.getName(), toWrite), compress); try { if (!compress) { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_STORED, getFileDate(toWrite)); } else { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_DEFLATED, getFileDate(toWrite)); } if (!targetPath.isDirectory()) { in = new FileInputStream(toWrite); IOUtils.copyLarge(in, out); in.close(); } out.flush(); out.close(); if (targetPath.isDirectory()) { log.info("[createZip] Written folder entry to zip: " + targetPath.getName()); } else { log.info("[createZip] Written file entry to zip: " + targetPath.getName()); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (ZipException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return targetPath; } | 900,170 |
1 | public static void copyFile(String input, String output) { try { FileChannel srcChannel = new FileInputStream("srcFilename").getChannel(); FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } | 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; } | 900,171 |
1 | public static Drawable fetchCachedDrawable(String url) throws MalformedURLException, IOException { Log.d(LOG_TAG, "Fetching cached : " + url); String cacheName = md5(url); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); if (!r.exists()) { InputStream is = (InputStream) fetch(url); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); Drawable d = Drawable.createFromStream(fis, "src"); return d; } | public String readFile(String filename) throws UnsupportedEncodingException, FileNotFoundException, IOException { File f = new File(baseDir); f = new File(f, filename); StringWriter w = new StringWriter(); Reader fr = new InputStreamReader(new FileInputStream(f), "UTF-8"); IOUtils.copy(fr, w); fr.close(); w.close(); String contents = w.toString(); return contents; } | 900,172 |
0 | public void copyFile2(String src, String dest) throws IOException { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(src); fw = new FileWriter(dest); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(src); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { throw new FileCopyException(src + " " + MM.PHRASES.getPhrase("35")); } catch (IOException ioe) { throw new FileCopyException(MM.PHRASES.getPhrase("36")); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } } | public Document parse(Document document) { CSSCompilerBuilder compilerBuilder = new CSSCompilerBuilder(); StyleSheetCompilerFactory compilerFactory = getStyleSheetCompilerFactory(); compilerBuilder.setStyleSheetCompilerFactory(compilerFactory); CSSCompiler cssCompiler = compilerBuilder.getCSSCompiler(); CompiledStyleSheet defaultCompiledStyleSheet; try { URL url = getClass().getResource("/com/volantis/mcs/runtime/default.css"); InputStream stream = url.openStream(); defaultCompiledStyleSheet = cssCompiler.compile(new InputStreamReader(stream), null); } catch (IOException e) { throw new ExtendedRuntimeException(e); } StylingFactory stylingFactory = StylingFactory.getDefaultInstance(); StylingEngine stylingEngine = stylingFactory.createStylingEngine(new InlineStyleSheetCompilerFactory(StylingFunctions.getResolver())); stylingEngine.pushStyleSheet(defaultCompiledStyleSheet); DocumentStyler styler = new DocumentStyler(stylingEngine, XDIMESchemata.CDM_NAMESPACE); styler.style(document); DOMWalker walker = new DOMWalker(new WalkingDOMVisitorStub() { public void visit(Element element) { if (element.getStyles() == null) { throw new IllegalArgumentException("element " + element.getName() + " has no styles"); } } }); walker.walk(document); DOMTransformer transformer = new DeferredInheritTransformer(); document = transformer.transform(null, document); return document; } | 900,173 |
0 | private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException { Datastream ds = new DatastreamManagedContent(); setDSCommonProperties(ds, entry); ds.DSLocationType = "INTERNAL_ID"; ds.DSMIME = getDSMimeType(entry); IRI contentLocation = entry.getContentSrc(); if (contentLocation != null) { if (m_obj.isNew()) { ValidationUtility.validateURL(contentLocation.toString(), ds.DSControlGrp); } if (m_format.equals(ATOM_ZIP1_1)) { if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) { File f = getContentSrcAsFile(contentLocation); contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath()); } } ds.DSLocation = contentLocation.toString(); ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation; return ds; } try { File temp = File.createTempFile("binary-datastream", null); OutputStream out = new FileOutputStream(temp); if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) { IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding); } else { IOUtils.copy(entry.getContentStream(), out); } ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } return ds; } | public static String postRequest(String url, String content) throws IOException { InputStream is = null; ByteArrayOutputStream buf = new ByteArrayOutputStream(); String result = null; try { Object obj = openConnection(url, content, "POST", "text/xml"); if (obj instanceof InputStream) { is = (InputStream) obj; } else { return "Cannot open a connection with " + url + " : " + obj.toString(); } int c = is.read(); while (c != -1) { buf.write(c); c = is.read(); } result = new String(buf.toByteArray()); } finally { if (is != null) { is.close(); } if (buf != null) { buf.close(); } } return result; } | 900,174 |
0 | public String getHtml(String path) throws Exception { URL url = new URL(path); URLConnection conn = url.openConnection(); conn.setDoOutput(true); InputStream inputStream = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8"); StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(isr); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } String result = sb.toString(); return result; } | public static boolean isSameHttpContent(final String url, final File localFile, UsernamePasswordCredentials creds) throws IOException { if (localFile.isFile()) { long localContentLength = localFile.length(); long localLastModified = localFile.lastModified() / 1000; long contentLength = -1; long lastModified = -1; HttpClient httpclient = createHttpClient(creds); try { HttpHead httphead = new HttpHead(url); HttpResponse response = httpclient.execute(httphead); if (response != null) { StatusLine statusLine = response.getStatusLine(); int status = statusLine.getStatusCode() / 100; if (status == 2) { Header lastModifiedHeader = response.getFirstHeader("Last-Modified"); Header contentLengthHeader = response.getFirstHeader("Content-Length"); if (contentLengthHeader != null) { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (lastModifiedHeader != null) { SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); formatter.setDateFormatSymbols(new DateFormatSymbols(Locale.US)); try { lastModified = formatter.parse(lastModifiedHeader.getValue()).getTime() / 1000; } catch (ParseException e) { logger.error(e); } } } else { return true; } } } finally { httpclient.getConnectionManager().shutdown(); } if (logger.isDebugEnabled()) { logger.debug("local:" + localContentLength + " " + localLastModified); logger.debug("remote:" + contentLength + " " + lastModified); } if (contentLength != -1 && localContentLength != contentLength) return false; if (lastModified != -1 && lastModified != localLastModified) return false; if (contentLength == -1 && lastModified == -1) return false; return true; } return false; } | 900,175 |
1 | public static void concatenateToDestFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { if (!destFile.createNewFile()) { throw new IllegalArgumentException("Could not create destination file:" + destFile.getName()); } } BufferedOutputStream bufferedOutputStream = null; BufferedInputStream bufferedInputStream = null; byte[] buffer = new byte[1024]; try { bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFile, true)); bufferedInputStream = new BufferedInputStream(new FileInputStream(sourceFile)); while (true) { int readByte = bufferedInputStream.read(buffer, 0, buffer.length); if (readByte == -1) { break; } bufferedOutputStream.write(buffer, 0, readByte); } } finally { if (bufferedOutputStream != null) { bufferedOutputStream.close(); } if (bufferedInputStream != null) { bufferedInputStream.close(); } } } | private static void createCompoundData(String dir, String type) { try { Set s = new HashSet(); File nouns = new File(dir + "index." + type); FileInputStream fis = new FileInputStream(nouns); InputStreamReader reader = new InputStreamReader(fis); StringBuffer sb = new StringBuffer(); int chr = reader.read(); while (chr >= 0) { if (chr == '\n' || chr == '\r') { String line = sb.toString(); if (line.length() > 0) { String[] spaceSplit = PerlHelp.split(line); for (int i = 0; i < spaceSplit.length; i++) { if (spaceSplit[i].indexOf('_') >= 0) { s.add(spaceSplit[i].replace('_', ' ')); } } } sb.setLength(0); } else { sb.append((char) chr); } chr = reader.read(); } System.out.println(type + " size=" + s.size()); File output = new File(dir + "compound." + type + "s.gz"); FileOutputStream fos = new FileOutputStream(output); GZIPOutputStream gzos = new GZIPOutputStream(new BufferedOutputStream(fos)); PrintWriter writer = new PrintWriter(gzos); writer.println("# This file was extracted from WordNet data, the following copyright notice"); writer.println("# from WordNet is attached."); writer.println("#"); writer.println("# This software and database is being provided to you, the LICENSEE, by "); writer.println("# Princeton University under the following license. By obtaining, using "); writer.println("# and/or copying this software and database, you agree that you have "); writer.println("# read, understood, and will comply with these terms and conditions.: "); writer.println("# "); writer.println("# Permission to use, copy, modify and distribute this software and "); writer.println("# database and its documentation for any purpose and without fee or "); writer.println("# royalty is hereby granted, provided that you agree to comply with "); writer.println("# the following copyright notice and statements, including the disclaimer, "); writer.println("# and that the same appear on ALL copies of the software, database and "); writer.println("# documentation, including modifications that you make for internal "); writer.println("# use or for distribution. "); writer.println("# "); writer.println("# WordNet 1.7 Copyright 2001 by Princeton University. All rights reserved. "); writer.println("# "); writer.println("# THIS SOFTWARE AND DATABASE IS PROVIDED \"AS IS\" AND PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR "); writer.println("# IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- "); writer.println("# ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE "); writer.println("# OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT "); writer.println("# INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR "); writer.println("# OTHER RIGHTS. "); writer.println("# "); writer.println("# The name of Princeton University or Princeton may not be used in"); writer.println("# advertising or publicity pertaining to distribution of the software"); writer.println("# and/or database. Title to copyright in this software, database and"); writer.println("# any associated documentation shall at all times remain with"); writer.println("# Princeton University and LICENSEE agrees to preserve same. "); for (Iterator i = s.iterator(); i.hasNext(); ) { String mwe = (String) i.next(); writer.println(mwe); } writer.close(); } catch (Exception e) { e.printStackTrace(); } } | 900,176 |
1 | public void updateDb(int scriptNumber) throws SQLException, IOException { String pathName = updatesPackage.replace(".", "/"); InputStream in = getClass().getClassLoader().getResourceAsStream(pathName + "/" + scriptNumber + ".sql"); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); String script = out.toString("UTF-8"); String[] statements = script.split(";"); for (String statement : statements) { getJdbcTemplate().execute(statement); } } | public void copyFile(File source, File destination, boolean lazy) { if (!source.exists()) { return; } if (lazy) { String oldContent = null; try { oldContent = read(source); } catch (Exception e) { return; } String newContent = null; try { newContent = read(destination); } catch (Exception e) { } if ((oldContent == null) || !oldContent.equals(newContent)) { copyFile(source, destination, false); } } else { if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { _log.error(ioe.getMessage()); } } } | 900,177 |
1 | public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } | public void generateReport(AllTestsResult atr, AllConvsResult acr, File nwbConvGraph) { ConvResult[] convs = acr.getConvResults(); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(nwbConvGraph)); writer = new BufferedWriter(new FileWriter(this.annotatedNWBGraph)); String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("id*int")) { writer.write(line + " isTrusted*int chanceCorrect*float isConverter*int \r\n"); } else if (line.matches(NODE_LINE)) { String[] parts = line.split(" "); String rawConvName = parts[1]; String convName = rawConvName.replaceAll("\"", ""); boolean wroteAttributes = false; for (int ii = 0; ii < convs.length; ii++) { ConvResult cr = convs[ii]; if (cr.getShortName().equals(convName)) { int trusted; if (cr.isTrusted()) { trusted = 1; } else { trusted = 0; } writer.write(line + " " + trusted + " " + FormatUtil.formatToPercent(cr.getChanceCorrect()) + " 1 " + "\r\n"); wroteAttributes = true; break; } } if (!wroteAttributes) { writer.write(line + " 1 100.0 0" + "\r\n"); } } else { writer.write(line + "\r\n"); } } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to generate Graph Report.", e); try { if (reader != null) reader.close(); } catch (IOException e2) { this.log.log(LogService.LOG_ERROR, "Unable to close graph report stream", e); } } finally { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to close either graph report reader or " + "writer.", e); e.printStackTrace(); } } } | 900,178 |
1 | public static void main(String[] args) { String WTKdir = null; String sourceFile = null; String instrFile = null; String outFile = null; String jadFile = null; Manifest mnf; if (args.length == 0) { usage(); return; } int i = 0; while (i < args.length && args[i].startsWith("-")) { if (("-WTK".equals(args[i])) && (i < args.length - 1)) { i++; WTKdir = args[i]; } else if (("-source".equals(args[i])) && (i < args.length - 1)) { i++; sourceFile = args[i]; } else if (("-instr".equals(args[i])) && (i < args.length - 1)) { i++; instrFile = args[i]; } else if (("-o".equals(args[i])) && (i < args.length - 1)) { i++; outFile = args[i]; } else if (("-jad".equals(args[i])) && (i < args.length - 1)) { i++; jadFile = args[i]; } else { System.out.println("Error: Unrecognized option: " + args[i]); System.exit(0); } i++; } if (WTKdir == null || sourceFile == null || instrFile == null) { System.out.println("Error: Missing parameter!!!"); usage(); return; } if (outFile == null) outFile = sourceFile; FileInputStream fisJar; try { fisJar = new FileInputStream(sourceFile); } catch (FileNotFoundException e1) { System.out.println("Cannot find source jar file: " + sourceFile); e1.printStackTrace(); return; } FileOutputStream fosJar; File aux = null; try { aux = File.createTempFile("predef", "aux"); fosJar = new FileOutputStream(aux); } catch (IOException e1) { System.out.println("Cannot find temporary jar file: " + aux); e1.printStackTrace(); return; } JarFile instrJar = null; Enumeration en = null; File tempDir = null; try { instrJar = new JarFile(instrFile); en = instrJar.entries(); tempDir = File.createTempFile("jbtp", ""); tempDir.delete(); System.out.println("Create directory: " + tempDir.mkdirs()); tempDir.deleteOnExit(); } catch (IOException e) { System.out.println("Cannot open instrumented file: " + instrFile); e.printStackTrace(); return; } String[] wtklib = new java.io.File(WTKdir + File.separator + "lib").list(new OnlyJar()); String preverifyCmd = WTKdir + File.separator + "bin" + File.separator + "preverify -classpath " + WTKdir + File.separator + "lib" + File.separator + CLDC_JAR + File.pathSeparator + WTKdir + File.separator + "lib" + File.separator + MIDP_JAR + File.pathSeparator + WTKdir + File.separator + "lib" + File.separator + WMA_JAR + File.pathSeparator + instrFile; for (int k = 0; k < wtklib.length; k++) { preverifyCmd += File.pathSeparator + WTKdir + File.separator + "lib" + wtklib[k]; } preverifyCmd += " " + "-d " + tempDir.getAbsolutePath() + " "; while (en.hasMoreElements()) { JarEntry je = (JarEntry) en.nextElement(); String jeName = je.getName(); if (jeName.endsWith(".class")) jeName = jeName.substring(0, jeName.length() - 6); preverifyCmd += jeName + " "; } try { Process p = Runtime.getRuntime().exec(preverifyCmd); if (p.waitFor() != 0) { BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream())); System.out.println("Error calling the preverify command."); while (in.ready()) { System.out.print("" + in.readLine()); } System.out.println(); in.close(); return; } } catch (Exception e) { System.out.println("Cannot execute preverify command"); e.printStackTrace(); return; } File[] listOfFiles = computeFiles(tempDir); System.out.println("-------------------------------\n" + "Files to insert: "); String[] strFiles = new String[listOfFiles.length]; int l = tempDir.toString().length() + 1; for (int j = 0; j < listOfFiles.length; j++) { strFiles[j] = listOfFiles[j].toString().substring(l); strFiles[j] = strFiles[j].replace(File.separatorChar, '/'); System.out.println(strFiles[j]); } System.out.println("-------------------------------"); try { JarInputStream jis = new JarInputStream(fisJar); mnf = jis.getManifest(); JarOutputStream jos = new JarOutputStream(fosJar, mnf); nextJar: for (JarEntry je = jis.getNextJarEntry(); je != null; je = jis.getNextJarEntry()) { String s = je.getName(); for (int k = 0; k < strFiles.length; k++) { if (strFiles[k].equals(s)) continue nextJar; } jos.putNextEntry(je); byte[] b = new byte[512]; for (int k = jis.read(b, 0, 512); k >= 0; k = jis.read(b, 0, 512)) { jos.write(b, 0, k); } } jis.close(); for (int j = 0; j < strFiles.length; j++) { FileInputStream fis = new FileInputStream(listOfFiles[j]); JarEntry je = new JarEntry(strFiles[j]); jos.putNextEntry(je); byte[] b = new byte[512]; while (fis.available() > 0) { int k = fis.read(b, 0, 512); jos.write(b, 0, k); } fis.close(); } jos.close(); fisJar.close(); fosJar.close(); } catch (IOException e) { System.out.println("Cannot read/write jar file."); e.printStackTrace(); return; } try { FileOutputStream fos = new FileOutputStream(outFile); FileInputStream fis = new FileInputStream(aux); byte[] b = new byte[512]; while (fis.available() > 0) { int k = fis.read(b, 0, 512); fos.write(b, 0, k); } fis.close(); fos.close(); } catch (IOException e) { System.out.println("Cannot write output jar file: " + outFile); e.printStackTrace(); } Iterator it; Attributes atr; atr = mnf.getMainAttributes(); it = atr.keySet().iterator(); if (jadFile != null) { FileOutputStream fos; try { File outJarFile = new File(outFile); fos = new FileOutputStream(jadFile); PrintStream psjad = new PrintStream(fos); while (it.hasNext()) { Object ats = it.next(); psjad.println(ats + ": " + atr.get(ats)); } psjad.println("MIDlet-Jar-URL: " + outFile); psjad.println("MIDlet-Jar-Size: " + outJarFile.length()); fos.close(); } catch (IOException eio) { System.out.println("Cannot create jad file."); eio.printStackTrace(); } } } | public void visit(BosMember member) throws BosException { String relative = AddressingUtil.getRelativePath(member.getDataSourceUri(), baseUri); URL resultUrl; try { resultUrl = new URL(outputUrl, relative); File resultFile = new File(resultUrl.toURI()); resultFile.getParentFile().mkdirs(); log.info("Creating result file \"" + resultFile.getAbsolutePath() + "\"..."); IOUtils.copy(member.getInputStream(), new FileOutputStream(resultFile)); } catch (Exception e) { throw new BosException(e); } } | 900,179 |
0 | public static int deleteHedgeCustTrade() { Connection conn = null; PreparedStatement psmt = null; StringBuffer SQL = new StringBuffer(200); int deleted = 0; SQL.append(" DELETE FROM JHF_HEDGE_CUSTTRADE "); try { conn = JdbcConnectionPool.mainConnection(); conn.setAutoCommit(false); conn.setReadOnly(false); psmt = conn.prepareStatement(SQL.toString()); deleted = psmt.executeUpdate(); conn.commit(); } catch (SQLException e) { if (null != conn) { try { conn.rollback(); } catch (SQLException e1) { System.out.println(" error when roll back !"); } } } finally { try { if (null != psmt) { psmt.close(); psmt = null; } if (null != conn) { conn.close(); conn = null; } } catch (SQLException e) { System.out.println(" error when psmt close or conn close ."); } } return deleted; } | public static void copy(String pstrFileFrom, String pstrFileTo) { try { FileChannel srcChannel = new FileInputStream(pstrFileFrom).getChannel(); FileChannel dstChannel = new FileOutputStream(pstrFileTo).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { throw new RuntimeException(e); } } | 900,180 |
1 | public File copyFile(File f) throws IOException { File t = createNewFile("fm", "cpy"); FileOutputStream fos = new FileOutputStream(t); FileChannel foc = fos.getChannel(); FileInputStream fis = new FileInputStream(f); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return t; } | private void copy(File in, File out) { log.info("Copying yam file from: " + in.getName() + " to: " + out.getName()); try { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (IOException ioe) { fail("Failed testing while copying modified file: " + ioe.getMessage()); } } | 900,181 |
1 | static String getMD5Hash(String str) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { int v = (int) b[i]; v = v < 0 ? 0x100 + v : v; String cc = Integer.toHexString(v); if (cc.length() == 1) sb.append('0'); sb.append(cc); } return sb.toString(); } | @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); String format = req.getParameter("format"); EntityManager em = EMF.get().createEntityManager(); String uname = (req.getParameter("uname") == null) ? "" : req.getParameter("uname"); String passwd = (req.getParameter("passwd") == null) ? "" : req.getParameter("passwd"); String name = (req.getParameter("name") == null) ? "" : req.getParameter("name"); String email = (req.getParameter("email") == null) ? "" : req.getParameter("email"); if (uname == null || uname.equals("") || uname.length() < 4) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.unameTooShort(uname).toXML(em)); else resp.getWriter().print(Error.unameTooShort(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (User.fromUserName(em, uname) != null) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.userExists(uname).toXML(em)); else resp.getWriter().print(Error.userExists(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_CONFLICT); em.close(); return; } if (passwd.equals("") || passwd.length() < 6) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (format != null && format.equals("xml")) resp.getWriter().print(Error.passwdTooShort(uname).toXML(em)); else resp.getWriter().print(Error.passwdTooShort(uname).toJSON(em)); em.close(); return; } User u = new User(); u.setUsername(uname); u.setPasswd(passwd); u.setName(name); u.setEmail(email); u.setPaid(false); StringBuffer apikey = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); String api = System.nanoTime() + "" + System.identityHashCode(this) + "" + uname; algorithm.update(api.getBytes()); byte[] digest = algorithm.digest(); for (int i = 0; i < digest.length; i++) { apikey.append(Integer.toHexString(0xFF & digest[i])); } } catch (NoSuchAlgorithmException e) { resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); log.severe(e.toString()); em.close(); return; } u.setApiKey(apikey.toString()); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(u); tx.commit(); } catch (Throwable t) { log.severe("Error adding user " + uname + " Reason:" + t.getMessage()); tx.rollback(); resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); return; } log.info("User " + u.getName() + " was created successfully"); resp.setStatus(HttpServletResponse.SC_CREATED); if (format != null && format.equals("xml")) resp.getWriter().print(u.toXML(em)); else resp.getWriter().print(u.toJSON(em)); em.close(); } | 900,182 |
1 | public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException("Expected arguments: fileName log"); String fileName = args[0]; String logFile = args[1]; LineNumberReader reader = null; PrintWriter writer = null; try { Reader reader0 = new FileReader(fileName); reader = new LineNumberReader(reader0); Writer writer0 = new FileWriter(logFile); BufferedWriter writer1 = new BufferedWriter(writer0); writer = new PrintWriter(writer1); String line = reader.readLine(); while (line != null) { line = line.trim(); if (line.length() >= 81) { writer.println("Analyzing Sudoku #" + reader.getLineNumber()); System.out.println("Analyzing Sudoku #" + reader.getLineNumber()); Grid grid = new Grid(); for (int i = 0; i < 81; i++) { char ch = line.charAt(i); if (ch >= '1' && ch <= '9') { int value = (ch - '0'); grid.setCellValue(i % 9, i / 9, value); } } Solver solver = new Solver(grid); solver.rebuildPotentialValues(); try { Map<Rule, Integer> rules = solver.solve(null); Map<String, Integer> ruleNames = solver.toNamedList(rules); double difficulty = 0; String hardestRule = ""; for (Rule rule : rules.keySet()) { if (rule.getDifficulty() > difficulty) { difficulty = rule.getDifficulty(); hardestRule = rule.getName(); } } for (String rule : ruleNames.keySet()) { int count = ruleNames.get(rule); writer.println(Integer.toString(count) + " " + rule); System.out.println(Integer.toString(count) + " " + rule); } writer.println("Hardest technique: " + hardestRule); System.out.println("Hardest technique: " + hardestRule); writer.println("Difficulty: " + difficulty); System.out.println("Difficulty: " + difficulty); } catch (UnsupportedOperationException ex) { writer.println("Failed !"); System.out.println("Failed !"); } writer.println(); System.out.println(); writer.flush(); } else System.out.println("Skipping incomplete line: " + line); line = reader.readLine(); } writer.close(); reader.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException ex) { ex.printStackTrace(); } } System.out.print("Finished."); } | protected void writeGZippedBytes(byte array[], TupleOutput out) { if (array == null || array.length == 0) { out.writeBoolean(false); writeBytes(array, out); return; } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length); GZIPOutputStream gzout = new GZIPOutputStream(baos); ByteArrayInputStream bais = new ByteArrayInputStream(array); IOUtils.copyTo(bais, gzout); gzout.finish(); gzout.close(); bais.close(); byte compressed[] = baos.toByteArray(); if (compressed.length < array.length) { out.writeBoolean(true); writeBytes(compressed, out); } else { out.writeBoolean(false); writeBytes(array, out); } } catch (IOException err) { throw new RuntimeException(err); } } | 900,183 |
1 | public static String sha1Hash(String input) { try { MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1"); sha1Digest.update(input.getBytes()); return byteArrayToString(sha1Digest.digest()); } catch (Exception e) { logger.error(e.getMessage(), e); } return ""; } | ServiceDescription getServiceDescription() throws ConfigurationException { final XPath pathsXPath = this.xPathFactory.newXPath(); try { final Node serviceDescriptionNode = (Node) pathsXPath.evaluate(ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration, XPathConstants.NODE); final String title = getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.TITLE_ELEMENT); ServiceDescription.Builder builder = new ServiceDescription.Builder(title, Migrate.class.getCanonicalName()); Property[] serviceProperties = getServiceProperties(serviceDescriptionNode); builder.author(getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.CREATOR_ELEMENT)); builder.classname(this.canonicalServiceName); builder.description(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.DESCRIPTION_ELEMENT)); final String serviceVersion = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.VERSION_ELEMENT); final Tool toolDescription = getToolDescriptionElement(serviceDescriptionNode); String identifier = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.IDENTIFIER_ELEMENT); if (identifier == null || "".equals(identifier)) { try { final MessageDigest identDigest = MessageDigest.getInstance("MD5"); identDigest.update(this.canonicalServiceName.getBytes()); final String versionInfo = (serviceVersion != null) ? serviceVersion : ""; identDigest.update(versionInfo.getBytes()); final URI toolIDURI = toolDescription.getIdentifier(); final String toolIdentifier = toolIDURI == null ? "" : toolIDURI.toString(); identDigest.update(toolIdentifier.getBytes()); final BigInteger md5hash = new BigInteger(identDigest.digest()); identifier = md5hash.toString(16); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException(nsae); } } builder.identifier(identifier); builder.version(serviceVersion); builder.tool(toolDescription); builder.instructions(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.INSTRUCTIONS_ELEMENT)); builder.furtherInfo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.FURTHER_INFO_ELEMENT)); builder.logo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.LOGO_ELEMENT)); builder.serviceProvider(this.serviceProvider); final DBMigrationPathFactory migrationPathFactory = new DBMigrationPathFactory(this.configuration); final MigrationPaths migrationPaths = migrationPathFactory.getAllMigrationPaths(); builder.paths(MigrationPathConverter.toPlanetsPaths(migrationPaths)); builder.inputFormats(migrationPaths.getInputFormatURIs().toArray(new URI[0])); builder.parameters(getUniqueParameters(migrationPaths)); builder.properties(serviceProperties); return builder.build(); } catch (XPathExpressionException xPathExpressionException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), xPathExpressionException); } catch (NullPointerException nullPointerException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), nullPointerException); } } | 900,184 |
0 | @SuppressWarnings("unchecked") protected void processTransformAction(HttpServletRequest request, HttpServletResponse response, String action) throws Exception { File transformationFile = null; String tr = request.getParameter(Definitions.REQUEST_PARAMNAME_XSLT); if (StringUtils.isNotBlank(tr)) { transformationFile = new File(xslBase, tr); if (!transformationFile.isFile()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"" + Definitions.REQUEST_PARAMNAME_XSLT + "\" " + "with value \"" + tr + "\" refers to non existing file"); return; } } StreamResult result; ByteArrayOutputStream baos = null; if (isDevelopmentMode) { baos = new ByteArrayOutputStream(); if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(baos, Base64.DECODE)); } else { result = new StreamResult(baos); } } else { if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(response.getOutputStream(), Base64.DECODE)); } else { result = new StreamResult(response.getOutputStream()); } } HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); String method = transformer.getOutputProperties().getProperty(OutputKeys.METHOD, "xml"); String contentType; if (method.endsWith("html")) { contentType = Definitions.MIMETYPE_HTML; } else if (method.equals("xml")) { contentType = Definitions.MIMETYPE_XML; } else { contentType = Definitions.MIMETYPE_TEXTPLAIN; } String encoding = transformer.getOutputProperties().getProperty(OutputKeys.ENCODING, "UTF-8"); response.setContentType(contentType + ";charset=" + encoding); DataSourceIf dataSource = new NullSource(); transformer.transform((Source) dataSource, result); if (isDevelopmentMode) { IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream()); } } | public boolean ponerFlotantexRonda(int idJugadorDiv, int idRonda, int dato) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET flotante = " + dato + " 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); } | 900,185 |
0 | @Test public void test_lookupType_FullSearch_CaseSensivity() throws Exception { URL url = new URL(baseUrl + "/lookupType/moRO"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("[{\"itemTypeID\":19724,\"itemCategoryID\":6,\"name\":\"Moros\"},{\"itemTypeID\":19725,\"itemCategoryID\":9,\"name\":\"Moros Blueprint\"}]")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); } | public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } | 900,186 |
1 | public Object read(InputStream inputStream, Map metadata) throws IOException, ClassNotFoundException { if (log.isTraceEnabled()) log.trace("Read input stream with metadata=" + metadata); Integer resCode = (Integer) metadata.get(HTTPMetadataConstants.RESPONSE_CODE); String resMessage = (String) metadata.get(HTTPMetadataConstants.RESPONSE_CODE_MESSAGE); if (resCode != null && validResponseCodes.contains(resCode) == false) throw new RuntimeException("Invalid HTTP server response [" + resCode + "] - " + resMessage); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); String soapMessage = new String(baos.toByteArray(), charsetEncoding); if (isTraceEnabled) { String prettySoapMessage = DOMWriter.printNode(DOMUtils.parse(soapMessage), true); log.trace("Incoming Response SOAPMessage\n" + prettySoapMessage); } return soapMessage; } | public static void copyFile(File from, File to) { try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[1024 * 16]; int read = 0; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } in.close(); } catch (IOException e) { e.printStackTrace(); } } | 900,187 |
1 | private List<File> ungzipFile(File directory, File compressedFile) throws IOException { List<File> files = new ArrayList<File>(); TarArchiveInputStream in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(compressedFile))); try { TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { if (entry.isDirectory()) { log.warn("TAR archive contains directories which are being ignored"); entry = in.getNextTarEntry(); continue; } String fn = new File(entry.getName()).getName(); if (fn.startsWith(".")) { log.warn("TAR archive contains a hidden file which is being ignored"); entry = in.getNextTarEntry(); continue; } File targetFile = new File(directory, fn); if (targetFile.exists()) { log.warn("TAR archive contains duplicate filenames, only the first is being extracted"); entry = in.getNextTarEntry(); continue; } files.add(targetFile); log.debug("Extracting file: " + entry.getName() + " to: " + targetFile.getAbsolutePath()); OutputStream fout = new BufferedOutputStream(new FileOutputStream(targetFile)); InputStream entryIn = new FileInputStream(entry.getFile()); IOUtils.copy(entryIn, fout); fout.close(); entryIn.close(); } } finally { in.close(); } return files; } | public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } | 900,188 |
0 | public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { BufferedReader reader; if (baseUrl == null) setBaseUrlFromUrl(url); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } fromUrl = true; return load(reader); } | public void insertRealm(final List<NewRealms> newRealms) { try { connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realm.add")); Iterator<NewRealms> iter = newRealms.iterator(); NewRealms newRealm; String realm; Iterator<String> iter2; while (iter.hasNext()) { newRealm = iter.next(); psImpl.setInt(3, newRealm.domainId); iter2 = newRealm.realms.iterator(); while (iter2.hasNext()) { realm = iter2.next(); psImpl.setString(1, realm); psImpl.setString(2, realm.toLowerCase(locale)); psImpl.executeUpdate(); } } } }); connection.commit(); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } } | 900,189 |
1 | public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException(MM.PHRASES.getPhrase("25") + " " + source_name); if (!source_file.canRead()) throw new FileCopyException(MM.PHRASES.getPhrase("26") + " " + MM.PHRASES.getPhrase("27") + ": " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("29") + ": " + dest_name); System.out.print(MM.PHRASES.getPhrase("19") + dest_name + MM.PHRASES.getPhrase("30") + ": "); System.out.flush(); response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new FileCopyException(MM.PHRASES.getPhrase("31")); } else throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("32") + ": " + dest_name); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("33") + ": " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("34") + ": " + dest_name); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) try { source.close(); } catch (IOException e) { ; } if (destination != null) try { destination.close(); } catch (IOException e) { ; } } } | public void verRecordatorio() { try { cantidadArchivos = obtenerCantidad() + 1; boolean existe = false; String filenametxt = ""; String filenamezip = ""; String hora = ""; String lugar = ""; String actividad = ""; String linea = ""; int dia = 0; int mes = 0; int ano = 0; for (int i = 1; i < cantidadArchivos; i++) { filenamezip = "recordatorio" + i + ".zip"; filenametxt = "recordatorio" + i + ".txt"; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(filenamezip); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, buffer); while ((count = is.read(data, 0, buffer)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); is.close(); } DataInputStream input = new DataInputStream(new FileInputStream(filenametxt)); dia = Integer.parseInt(input.readLine()); mes = Integer.parseInt(input.readLine()); ano = Integer.parseInt(input.readLine()); if (dia == Integer.parseInt(identificarDato(datoSeleccionado))) { existe = true; hora = input.readLine(); lugar = input.readLine(); while ((linea = input.readLine()) != null) actividad += linea + "\n"; verRecordatorioInterfaz(hora, lugar, actividad); hora = ""; lugar = ""; actividad = ""; } input.close(); } if (!existe) JOptionPane.showMessageDialog(null, "No existe un recordatorio guardado\n" + "para el " + identificarDato(datoSeleccionado) + " de " + meses[mesTemporal].toLowerCase() + " del a�o " + anoTemporal, "No existe", JOptionPane.INFORMATION_MESSAGE); table.clearSelection(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } } | 900,190 |
0 | protected InputStream callApiMethod(String apiUrl, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.connect(); if (request.getResponseCode() != expected) { Error error = readResponse(Error.class, getWrappedInputStream(request.getErrorStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()))); throw createBingSearchApiClientException(error); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingSearchException(e); } } | 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"; } | 900,191 |
1 | 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(); } | private void writeFile(File file, String fileName) { try { FileInputStream fin = new FileInputStream(file); FileOutputStream fout = new FileOutputStream(dirTableModel.getDirectory().getAbsolutePath() + File.separator + fileName); int val; while ((val = fin.read()) != -1) fout.write(val); fin.close(); fout.close(); dirTableModel.reset(); } catch (Exception e) { e.printStackTrace(); } } | 900,192 |
1 | protected String getHashCode(String value) { if (log.isDebugEnabled()) log.debug("getHashCode(...) -> begin"); String retVal = null; try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(value.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < digest.length; i++) { sb.append(this.toHexString(digest[i])); } retVal = sb.toString(); if (log.isDebugEnabled()) log.debug("getHashCode(...) -> hashcode = " + retVal); } catch (Exception e) { log.error("getHashCode(...) -> error occured generating hashcode ", e); } if (log.isDebugEnabled()) log.debug("getHashCode(...) -> end"); return retVal; } | private String getBytes(String in) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(in.getBytes()); byte[] passWordBytes = md5.digest(); String s = "["; for (int i = 0; i < passWordBytes.length; i++) s += passWordBytes[i] + ", "; s = s.substring(0, s.length() - 2); s += "]"; return s; } | 900,193 |
1 | public void removeUser(final User user) throws IOException { try { Connection conn = null; boolean autoCommit = false; try { conn = pool.getConnection(); autoCommit = conn.getAutoCommit(); conn.setAutoCommit(false); final PreparedStatement removeUser = conn.prepareStatement("delete from users where userId = ?"); removeUser.setString(1, user.getUserId()); removeUser.executeUpdate(); final PreparedStatement deleteRoles = conn.prepareStatement("delete from userRoles where userId=?"); deleteRoles.setString(1, user.getUserId()); deleteRoles.executeUpdate(); conn.commit(); } catch (Throwable t) { if (conn != null) conn.rollback(); throw new SQLException(t.toString()); } finally { if (conn != null) { conn.setAutoCommit(autoCommit); conn.close(); } } } catch (final SQLException sqle) { log.log(Level.SEVERE, sqle.toString(), sqle); throw new IOException(sqle.toString()); } } | @Override public void excluir(Disciplina t) throws Exception { PreparedStatement stmt = null; String sql = "DELETE from disciplina where id_disciplina = ?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, t.getIdDisciplina()); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } finally { try { stmt.close(); conexao.close(); } catch (SQLException e) { throw e; } } } | 900,194 |
0 | public int subclass(int objectId, String description) throws FidoDatabaseException, ObjectNotFoundException { try { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { String sql = "insert into Objects (Description) " + "values ('" + description + "')"; conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, objectId) == false) throw new ObjectNotFoundException(objectId); stmt.executeUpdate(sql); int id; sql = "select currval('objects_objectid_seq')"; rs = stmt.executeQuery(sql); if (rs.next() == false) throw new SQLException("No rows returned from select currval() query"); else id = rs.getInt(1); ObjectLinkTable objectLinkList = new ObjectLinkTable(); objectLinkList.linkObjects(stmt, id, "isa", objectId); conn.commit(); return id; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } | @Override public ImageData getImageData(URL url) { InputStream in = null; try { URLConnection conn = url.openConnection(); conn.setRequestProperty("user-agent", "Tahiti/Alpha5x"); conn.setRequestProperty("agent-system", "aglets"); conn.setAllowUserInteraction(true); conn.connect(); in = conn.getInputStream(); String type = conn.getContentType(); int len = conn.getContentLength(); if (len < 0) { len = in.available(); } byte[] b = new byte[len]; int off = 0; int n = 0; while (n < len) { int count = in.read(b, off + n, len - n); if (count < 0) { throw new java.io.EOFException(); } n += count; } in.close(); return new AgletImageData(url, b, type); } catch (Exception ex) { ex.printStackTrace(); return null; } } | 900,195 |
1 | public static void main(String[] args) throws IOException { File inputFile = new File("D:/farrago.txt"); File outputFile = new File("D:/outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } | public void create(File target) { if ("dir".equals(type)) { File dir = new File(target, name); dir.mkdirs(); for (Resource c : children) { c.create(dir); } } else if ("package".equals(type)) { String[] dirs = name.split("\\."); File parent = target; for (String d : dirs) { parent = new File(parent, d); } parent.mkdirs(); for (Resource c : children) { c.create(parent); } } else if ("file".equals(type)) { InputStream is = getInputStream(); File file = new File(target, name); try { if (is != null) { FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(is, fos); fos.flush(); fos.close(); } else { PrintStream ps = new PrintStream(file); ps.print(content); ps.flush(); ps.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if ("zip".equals(type)) { try { unzip(target); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { throw new RuntimeException("unknown resource type: " + type); } } | 900,196 |
0 | private static HttpURLConnection _getConnection(HttpPrincipal httpPrincipal) throws IOException { if (httpPrincipal == null || httpPrincipal.getUrl() == null) { return null; } URL url = null; if ((httpPrincipal.getUserId() <= 0) || (httpPrincipal.getPassword() == null)) { url = new URL(httpPrincipal.getUrl() + "/tunnel-web/liferay/do"); } else { url = new URL(httpPrincipal.getUrl() + "/tunnel-web/secure/liferay/do"); } HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setDoInput(true); urlc.setDoOutput(true); urlc.setUseCaches(false); urlc.setRequestMethod("POST"); if ((httpPrincipal.getUserId() > 0) && (httpPrincipal.getPassword() != null)) { String userNameAndPassword = httpPrincipal.getUserId() + ":" + httpPrincipal.getPassword(); urlc.setRequestProperty("Authorization", "Basic " + Base64.encode(userNameAndPassword.getBytes())); } return urlc; } | public void savaUserPerm(String userid, Collection user_perm_collect) throws DAOException, SQLException { ConnectionProvider cp = null; Connection conn = null; ResultSet rs = null; PreparedStatement pstmt = null; PrivilegeFactory factory = PrivilegeFactory.getInstance(); Operation op = factory.createOperation(); try { cp = ConnectionProviderFactory.getConnectionProvider(Constants.DATA_SOURCE); conn = cp.getConnection(); pstmt = conn.prepareStatement(DEL_USER_PERM); pstmt.setString(1, userid); pstmt.executeUpdate(); if ((user_perm_collect == null) || (user_perm_collect.size() <= 0)) { return; } else { conn.setAutoCommit(false); pstmt = conn.prepareStatement(ADD_USER_PERM); Iterator user_perm_ir = user_perm_collect.iterator(); while (user_perm_ir.hasNext()) { UserPermission userPerm = (UserPermission) user_perm_ir.next(); pstmt.setString(1, String.valueOf(userPerm.getUser_id())); pstmt.setString(2, String.valueOf(userPerm.getResource_id())); pstmt.setString(3, String.valueOf(userPerm.getResop_id())); pstmt.executeUpdate(); } conn.commit(); conn.setAutoCommit(true); } } catch (Exception e) { e.printStackTrace(); conn.rollback(); throw new DAOException(); } finally { try { if (conn != null) { conn.close(); } if (pstmt != null) { pstmt.close(); } } catch (Exception e) { } } } | 900,197 |
1 | public static Boolean decompress(File source, File destination) { FileOutputStream outputStream; ZipInputStream inputStream; try { outputStream = null; inputStream = new ZipInputStream(new FileInputStream(source)); int read; byte buffer[] = new byte[BUFFER_SIZE]; ZipEntry zipEntry; while ((zipEntry = inputStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) new File(destination, zipEntry.getName()).mkdirs(); else { File fileEntry = new File(destination, zipEntry.getName()); fileEntry.getParentFile().mkdirs(); outputStream = new FileOutputStream(fileEntry); while ((read = inputStream.read(buffer, 0, BUFFER_SIZE)) != -1) { outputStream.write(buffer, 0, read); } outputStream.flush(); outputStream.close(); } } inputStream.close(); } catch (Exception oException) { return false; } return true; } | private long generateUnixInstallShell(File unixShellFile, String instTemplate, File instClassFile) throws IOException { FileOutputStream byteWriter = new FileOutputStream(unixShellFile); InputStream is = getClass().getResourceAsStream("/" + instTemplate); InputStreamReader isr = new InputStreamReader(is); LineNumberReader reader = new LineNumberReader(isr); String content = ""; String installClassStartStr = "000000000000"; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassStartStr.length()); int installClassStartPos = 0; long installClassOffset = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallShell")); String line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassStart"))) { content += line + "\n"; line = reader.readLine(); } content += "InstallClassStart=" + installClassStartStr + "\n"; installClassStartPos = content.length() - 1 - 1 - installClassStartStr.length(); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassSize"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassSize=" + instClassFile.length() + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassName"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassName=" + instClassName_ + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# Install class"))) { content += line + "\n"; line = reader.readLine(); } if (line != null) content += line + "\n"; byteWriter.write(content.substring(0, installClassStartPos + 1).getBytes()); byteWriter.write(nf.format(content.length()).getBytes()); byteWriter.write(content.substring(installClassStartPos + 1 + installClassStartStr.length()).getBytes()); installClassOffset = content.length(); content = null; FileInputStream classStream = new FileInputStream(instClassFile); byte[] buf = new byte[2048]; int read = classStream.read(buf); while (read > 0) { byteWriter.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); reader.close(); byteWriter.close(); return installClassOffset; } | 900,198 |
1 | 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()); } | public static void copy(FileInputStream in, File destination) throws IOException { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = in.getChannel(); dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (dstChannel != null) { dstChannel.close(); } } } | 900,199 |