label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
| Code Sample 1:
public Program updateProgramPath(int id, String sourcePath) throws AdaptationException { Program program = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "UPDATE Programs SET " + "sourcePath = '" + sourcePath + "' " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from Programs WHERE id = " + id; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to update program failed."; log.error(msg); throw new AdaptationException(msg); } program = getProgram(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in updateProgramPath"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return program; }
Code Sample 2:
public String GetMemberName(String id) { String name = null; try { String line; URL url = new URL(intvasmemberDeatails + "?CID=" + id); URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { name = line; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String[] parts = name.split(" "); rating = parts[2]; return parts[0] + " " + parts[1]; } |
11
| Code Sample 1:
public static final String enctrypt(String password) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); throw new RuntimeException("NoSuchAlgorithmException SHA1"); } md.reset(); md.update(password.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); }
Code Sample 2:
private static String getMD5(String phrase) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(phrase.getBytes()); return asHexString(md.digest()); } catch (Exception e) { } return ""; } |
11
| Code Sample 1:
public synchronized String encrypt(String p_plainText) throws ServiceUnavailableException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new ServiceUnavailableException(e.getMessage()); } try { md.update(p_plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new ServiceUnavailableException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static String MD5Encode(String password) { MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } return buf.toString(); } catch (NoSuchAlgorithmException e) { return password; } } |
11
| Code Sample 1:
private synchronized boolean createOrganization(String organizationName, HttpServletRequest req) { if ((organizationName == null) || (organizationName.equals(""))) { message = "invalid new_organization_name."; return false; } String tmpxml = TextUtil.xmlEscape(organizationName); String tmpdb = DBAccess.SQLEscape(organizationName); if ((!organizationName.equals(tmpxml)) || (!organizationName.equals(tmpdb)) || (!TextUtil.isValidFilename(organizationName))) { message = "invalid new_organization_name."; return false; } if ((organizationName.indexOf('-') > -1) || (organizationName.indexOf(' ') > -1)) { message = "invalid new_organization_name."; return false; } String[] orgnames = ServerConsoleServlet.getOrganizationNames(); for (int i = 0; i < orgnames.length; i++) { if (orgnames.equals(organizationName)) { message = "already exists."; return false; } } message = "create new organization: " + organizationName; File newOrganizationDirectory = new File(ServerConsoleServlet.RepositoryLocalDirectory.getAbsolutePath() + File.separator + organizationName); if (!newOrganizationDirectory.mkdir()) { message = "cannot create directory."; return false; } File cacheDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("CacheDirName")); cacheDir.mkdir(); File confDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ConfDirName")); confDir.mkdir(); File rdfDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("RDFDirName")); rdfDir.mkdir(); File resourceDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ResourceDirName")); resourceDir.mkdir(); File obsoleteDir = new File(resourceDir.getAbsolutePath() + File.separator + "obsolete"); obsoleteDir.mkdir(); File schemaDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("SchemaDirName")); schemaDir.mkdir(); String organization_temp_dir = ServerConsoleServlet.convertToAbsolutePath(ServerConsoleServlet.getConfigByTagName("OrganizationTemplate")); File templ = new File(organization_temp_dir); File[] confFiles = templ.listFiles(); for (int i = 0; i < confFiles.length; i++) { try { FileReader fr = new FileReader(confFiles[i]); FileWriter fw = new FileWriter(confDir.getAbsolutePath() + File.separator + confFiles[i].getName()); int c = -1; while ((c = fr.read()) != -1) fw.write(c); fw.flush(); fw.close(); fr.close(); } catch (IOException e) { } } SchemaModelHolder.reloadSchemaModel(organizationName); ResourceModelHolder.reloadResourceModel(organizationName); UserLogServlet.initializeUserLogDB(organizationName); MetaEditServlet.createNewProject(organizationName, "standard", MetaEditServlet.convertProjectIdToProjectUri(organizationName, "standard", req), this.username); ResourceModelHolder.reloadResourceModel(organizationName); message = organizationName + " is created. Restart Tomcat to activate this organization."; return true; }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { 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(); } } } |
11
| Code Sample 1:
public int add(WebService ws) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { String sql = "insert into WebServices (MethodName, ServiceURI) " + "values ('" + ws.getMethodName() + "', '" + ws.getServiceURI() + "')"; conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate(sql); int id; sql = "select currval('webservices_webserviceid_seq')"; rs = stmt.executeQuery(sql); if (rs.next() == false) throw new SQLException("No rows returned from select currval() query"); else id = rs.getInt(1); PreparedStatement pstmt = conn.prepareStatement("insert into WebServiceParams " + "(WebServiceId, Position, ParameterName, Type) " + "values (?, ?, ?, ?)"); pstmt.setInt(1, id); pstmt.setInt(2, 0); pstmt.setString(3, null); pstmt.setInt(4, ws.getReturnType()); pstmt.executeUpdate(); for (Iterator it = ws.parametersIterator(); it.hasNext(); ) { WebServiceParameter param = (WebServiceParameter) it.next(); pstmt.setInt(2, param.getPosition()); pstmt.setString(3, param.getName()); pstmt.setInt(4, param.getType()); pstmt.executeUpdate(); } 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) { e.printStackTrace(); throw new FidoDatabaseException(e); } }
Code Sample 2:
private void removeCollection(long oid, Connection conn) throws XMLDBException { try { String sql = "DELETE FROM X_DOCUMENT WHERE X_DOCUMENT.XDB_COLLECTION_OID = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setLong(1, oid); pstmt.executeUpdate(); pstmt.close(); sql = "DELETE FROM XDB_COLLECTION WHERE XDB_COLLECTION.XDB_COLLECTION_OID = ?"; pstmt = conn.prepareStatement(sql); pstmt.setLong(1, oid); pstmt.executeUpdate(); pstmt.close(); removeChildCollection(oid, conn); } catch (java.sql.SQLException se) { try { conn.rollback(); } catch (java.sql.SQLException se2) { se2.printStackTrace(); } se.printStackTrace(); } } |
11
| Code Sample 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(); }
Code Sample 2:
public void addEntry(InputStream jis, JarEntry entry) throws IOException, URISyntaxException { File target = new File(this.target.getPath() + entry.getName()).getAbsoluteFile(); if (!target.exists()) { target.createNewFile(); } if ((new File(this.source.toURI())).isDirectory()) { File sourceEntry = new File(this.source.getPath() + entry.getName()); FileInputStream fis = new FileInputStream(sourceEntry); byte[] classBytes = new byte[fis.available()]; fis.read(classBytes); (new FileOutputStream(target)).write(classBytes); } else { readwriteStreams(jis, (new FileOutputStream(target))); } } |
11
| Code Sample 1:
private void unpackBundle() throws IOException { File useJarPath = null; if (DownloadManager.isWindowsVista()) { useJarPath = lowJarPath; File jarDir = useJarPath.getParentFile(); if (jarDir != null) { jarDir.mkdirs(); } } else { useJarPath = jarPath; } DownloadManager.log("Unpacking " + this + " to " + useJarPath); InputStream rawStream = new FileInputStream(localPath); JarInputStream in = new JarInputStream(rawStream) { public void close() throws IOException { } }; try { File jarTmp = null; JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.equals("classes.pack")) { File packTmp = new File(useJarPath + ".pack"); packTmp.getParentFile().mkdirs(); DownloadManager.log("Writing temporary .pack file " + packTmp); OutputStream tmpOut = new FileOutputStream(packTmp); try { DownloadManager.send(in, tmpOut); } finally { tmpOut.close(); } jarTmp = new File(useJarPath + ".tmp"); DownloadManager.log("Writing temporary .jar file " + jarTmp); unpack(packTmp, jarTmp); packTmp.delete(); } else if (!entryName.startsWith("META-INF")) { File dest; if (DownloadManager.isWindowsVista()) { dest = new File(lowJavaPath, entryName.replace('/', File.separatorChar)); } else { dest = new File(DownloadManager.JAVA_HOME, entryName.replace('/', File.separatorChar)); } if (entryName.equals(BUNDLE_JAR_ENTRY_NAME)) dest = useJarPath; File destTmp = new File(dest + ".tmp"); boolean exists = dest.exists(); if (!exists) { DownloadManager.log(dest + ".mkdirs()"); dest.getParentFile().mkdirs(); } try { DownloadManager.log("Using temporary file " + destTmp); FileOutputStream out = new FileOutputStream(destTmp); try { byte[] buffer = new byte[2048]; int c; while ((c = in.read(buffer)) > 0) out.write(buffer, 0, c); } finally { out.close(); } if (exists) dest.delete(); DownloadManager.log("Renaming from " + destTmp + " to " + dest); if (!destTmp.renameTo(dest)) { throw new IOException("unable to rename " + destTmp + " to " + dest); } } catch (IOException e) { if (!exists) throw e; } } } if (jarTmp != null) { if (useJarPath.exists()) jarTmp.delete(); else if (!jarTmp.renameTo(useJarPath)) { throw new IOException("unable to rename " + jarTmp + " to " + useJarPath); } } if (DownloadManager.isWindowsVista()) { DownloadManager.log("Using broker to move " + name); if (!DownloadManager.moveDirWithBroker(DownloadManager.getKernelJREDir() + name)) { throw new IOException("unable to create " + name); } DownloadManager.log("Broker finished " + name); } DownloadManager.log("Finished unpacking " + this); } finally { rawStream.close(); } if (deleteOnInstall) { localPath.delete(); } }
Code Sample 2:
private void transform(CommandLine commandLine) throws IOException { Reader reader; if (commandLine.hasOption('i')) { reader = createFileReader(commandLine.getOptionValue('i')); } else { reader = createStandardInputReader(); } Writer writer; if (commandLine.hasOption('o')) { writer = createFileWriter(commandLine.getOptionValue('o')); } else { writer = createStandardOutputWriter(); } String mapRule = commandLine.getOptionValue("m"); try { SrxTransformer transformer = new SrxAnyTransformer(); Map<String, Object> parameterMap = new HashMap<String, Object>(); if (mapRule != null) { parameterMap.put(Srx1Transformer.MAP_RULE_NAME, mapRule); } transformer.transform(reader, writer, parameterMap); } finally { cleanupReader(reader); cleanupWriter(writer); } } |
00
| Code Sample 1:
private String copyAndHash(InputStream input, File into) throws IOException { MessageDigest digest = createMessageDigest(); DigestInputStream dis = new DigestInputStream(input, digest); IOException ex; FileOutputStream fos = null; try { fos = new FileOutputStream(into); IOUtils.copyLarge(dis, fos); byte[] hash = digest.digest(); Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } return formatter.toString(); } catch (IOException e) { ex = e; } finally { IOUtils.closeQuietly(dis); IOUtils.closeQuietly(fos); } if (logger.isWarnEnabled()) logger.warn("Couldn't retrieve data from input!", ex); deleteTempFile(into); throw ex; }
Code Sample 2:
public void update(String target, String cfgVersion) throws MalformedURLException, FileNotFoundException, IOException { Debug.log("Config Updater", "Checking for newer configuration..."); URL url = new URL(target); String[] urlSplit = target.split("/"); this.fileName = urlSplit[urlSplit.length - 1]; BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(Main.getHomeDir() + "tmp-" + this.fileName)); URLConnection urlConnection = url.openConnection(); InputStream in = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int numRead; int fileSize = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); fileSize += numRead; } Debug.log("Config Updater", "Read latest configuration: " + fileSize + " bytes"); in.close(); out.close(); XMLController xmlC = new XMLController(); String newFileVersion = xmlC.readCfgVersion(Main.getHomeDir() + "tmp-" + this.fileName); if (new File(Main.getHomeDir() + this.fileName).exists()) { Debug.log("Config Updater", "Local configfile '" + Main.getHomeDir() + this.fileName + "' exists (version " + cfgVersion + ")"); if (Double.parseDouble(newFileVersion) > Double.parseDouble(cfgVersion)) { Debug.log("Config Updater", "Removing old config and replacing it with version " + newFileVersion); new File(Main.getHomeDir() + this.fileName).delete(); new File(Main.getHomeDir() + "tmp-" + this.fileName).renameTo(new File(Main.getHomeDir() + this.fileName)); this.result = "ConfigFile upgraded to version " + newFileVersion; } else { new File(Main.getHomeDir() + "tmp-" + this.fileName).delete(); Debug.log("Config Updater", "I already have the latest version " + cfgVersion); } } else { Debug.log("Config Updater", "Local config doesn't exist. Loading the new one, version " + newFileVersion); new File(Main.getHomeDir() + "tmp-" + this.fileName).renameTo(new File(Main.getHomeDir() + this.fileName)); this.result = "ConfigFile upgraded to version " + newFileVersion; } Debug.log("Config Updater", "Update of configuration done"); } |
00
| Code Sample 1:
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; }
Code Sample 2:
public void execute() throws InstallerException { try { SQLCommand sqlCommand = new SQLCommand(connectionInfo); connection = sqlCommand.getConnection(); connection.setAutoCommit(false); sqlStatement = connection.createStatement(); double size = (double) statements.size(); for (String statement : statements) { sqlStatement.executeUpdate(statement); setCompletedPercentage(getCompletedPercentage() + (1 / size)); } connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { throw new InstallerException(InstallerException.TRANSACTION_ROLLBACK_ERROR, new Object[] { e.getMessage() }, e); } throw new InstallerException(InstallerException.SQL_EXEC_EXCEPTION, new Object[] { e.getMessage() }, e); } catch (ClassNotFoundException e) { throw new InstallerException(InstallerException.DB_DRIVER_LOAD_ERROR, e); } finally { if (connection != null) { try { sqlStatement.close(); connection.close(); } catch (SQLException e) { } } } } |
11
| Code Sample 1:
public ActionForward dbExecute(ActionMapping pMapping, ActionForm pForm, HttpServletRequest pRequest, HttpServletResponse pResponse) throws DatabaseException { String email = pRequest.getParameter("email"); MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new DatabaseException("Could not hash password for storage: no such algorithm"); } md.update(pRequest.getParameter("password").getBytes()); String password = (new BASE64Encoder()).encode(md.digest()); String remember = pRequest.getParameter("rememberLogin"); User user = database.acquireUserByEmail(email); if (user == null || user.equals(User.anonymous()) || !user.getActive()) { return pMapping.findForward("invalid"); } else if (user.getPassword().equals(password)) { pRequest.getSession().setAttribute("login", user); if (remember != null) { Cookie usercookie = new Cookie("bib.username", email); Cookie passcookie = new Cookie("bib.password", password.toString()); usercookie.setPath("/"); passcookie.setPath("/"); usercookie.setMaxAge(60 * 60 * 24 * 365); passcookie.setMaxAge(60 * 60 * 24 * 365); pResponse.addCookie(usercookie); pResponse.addCookie(passcookie); } return pMapping.findForward("success"); } else { return pMapping.findForward("invalid"); } }
Code Sample 2:
public static String getHash(String userName, String pass) { String hash = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(userName.getBytes()); hash = ISOUtil.hexString(md.digest(pass.getBytes())).toLowerCase(); } catch (NoSuchAlgorithmException e) { } return hash; } |
11
| Code Sample 1:
public Atividade insertAtividade(Atividade atividade) throws SQLException { Connection conn = null; String insert = "insert into Atividade (idatividade, requerente_idrequerente, datacriacao, datatermino, valor, tipoatividade, descricao, fase_idfase, estado) " + "values " + "(nextval('seq_atividade'), " + atividade.getRequerente().getIdRequerente() + ", " + "'" + atividade.getDataCriacao() + "', '" + atividade.getDataTermino() + "', '" + atividade.getValor() + "', '" + atividade.getTipoAtividade().getIdTipoAtividade() + "', '" + atividade.getDescricao() + "', " + atividade.getFaseIdFase() + ", " + atividade.getEstado() + ")"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); if (result == 1) { String sqlSelect = "select last_value from seq_atividade"; ResultSet rs = stmt.executeQuery(sqlSelect); while (rs.next()) { atividade.setIdAtividade(rs.getInt("last_value")); } } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } return null; }
Code Sample 2:
private Vendor createVendor() throws SQLException, IOException { Connection conn = null; Statement st = null; String query = null; ResultSet rs = null; try { conn = dataSource.getConnection(); st = conn.createStatement(); query = "insert into " + DB.Tbl.vend + "(" + col.title + "," + col.addDate + "," + col.authorId + ") values('" + title + "',now()," + user.getId() + ")"; st.executeUpdate(query, new String[] { col.id }); rs = st.getGeneratedKeys(); if (!rs.next()) { throw new SQLException("Не удается получить generated key 'id' в таблице vendors."); } int genId = rs.getInt(1); rs.close(); saveDescr(genId); conn.commit(); Vendor v = new Vendor(); v.setId(genId); v.setTitle(title); v.setDescr(descr); VendorViewer.getInstance().vendorListChanged(); return v; } catch (SQLException e) { try { conn.rollback(); } catch (Exception e1) { } throw e; } finally { try { rs.close(); } catch (Exception e) { } try { st.close(); } catch (Exception e) { } try { conn.close(); } catch (Exception e) { } } } |
11
| Code Sample 1:
@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()); } }
Code Sample 2:
public static void copyFile(String source, String destination, boolean overwrite) { File sourceFile = new File(source); try { File destinationFile = new File(destination); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destinationFile)); int temp = 0; while ((temp = bis.read()) != -1) bos.write(temp); bis.close(); bos.close(); } catch (Exception e) { } return; } |
11
| Code Sample 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(); } }
Code Sample 2:
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; } |
11
| Code Sample 1:
public static String digest(String algorithm, String text) { MessageDigest mDigest = null; try { mDigest = MessageDigest.getInstance(algorithm); mDigest.update(text.getBytes(ENCODING)); } catch (NoSuchAlgorithmException nsae) { Logger.error(Encryptor.class, nsae.getMessage(), nsae); } catch (UnsupportedEncodingException uee) { Logger.error(Encryptor.class, uee.getMessage(), uee); } byte raw[] = mDigest.digest(); return (new BASE64Encoder()).encode(raw); }
Code Sample 2:
public static String md5(String plainText) { String ret = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } ret = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ret; } |
00
| Code Sample 1:
private void setManagedContent(Entry entry, Datastream vds) throws StreamIOException { if (m_transContext == DOTranslationUtility.SERIALIZE_EXPORT_ARCHIVE && !m_format.equals(ATOM_ZIP1_1)) { String mimeType = vds.DSMIME; if (MimeTypeHelper.isText(mimeType) || MimeTypeHelper.isXml(mimeType)) { try { entry.setContent(IOUtils.toString(vds.getContentStream(), m_encoding), mimeType); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { entry.setContent(vds.getContentStream(), mimeType); } } else { String dsLocation; IRI iri; if (m_format.equals(ATOM_ZIP1_1) && m_transContext != DOTranslationUtility.AS_IS) { dsLocation = vds.DSVersionID + "." + MimeTypeUtils.fileExtensionForMIMEType(vds.DSMIME); try { m_zout.putNextEntry(new ZipEntry(dsLocation)); InputStream is = vds.getContentStream(); IOUtils.copy(is, m_zout); is.close(); m_zout.closeEntry(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { dsLocation = StreamUtility.enc(DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), vds, m_transContext).DSLocation); } iri = new IRI(dsLocation); entry.setSummary(vds.DSVersionID); entry.setContent(iri, vds.DSMIME); } }
Code Sample 2:
public Project deleteProject(int projectID) throws AdaptationException { Project project = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM Projects WHERE id = " + projectID; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete project failed."; log.error(msg); throw new AdaptationException(msg); } project = getProject(resultSet); query = "DELETE FROM Projects WHERE id = " + projectID; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProject"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return project; } |
00
| Code Sample 1:
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; }
Code Sample 2:
static void reopen(MJIEnv env, int objref) throws IOException { int fd = env.getIntField(objref, "fd"); long off = env.getLongField(objref, "off"); if (content.get(fd) == null) { int mode = env.getIntField(objref, "mode"); int fnRef = env.getReferenceField(objref, "fileName"); String fname = env.getStringObject(fnRef); if (mode == FD_READ) { FileInputStream fis = new FileInputStream(fname); FileChannel fc = fis.getChannel(); fc.position(off); content.set(fd, fis); } else if (mode == FD_WRITE) { FileOutputStream fos = new FileOutputStream(fname); FileChannel fc = fos.getChannel(); fc.position(off); content.set(fd, fos); } else { env.throwException("java.io.IOException", "illegal mode: " + mode); } } } |
00
| Code Sample 1:
private Collection<URL> doSearch(final URL url) throws IOException { final Collection<URL> result = new ArrayList<URL>(); final InputStream is = url.openStream(); final ReadHTML parse = new ReadHTML(is); final StringBuilder buffer = new StringBuilder(); boolean capture = false; int ch; while ((ch = parse.read()) != -1) { if (ch == 0) { final Tag tag = parse.getTag(); if (tag.getName().equalsIgnoreCase("url")) { buffer.setLength(0); capture = true; } else if (tag.getName().equalsIgnoreCase("/url")) { result.add(new URL(buffer.toString())); buffer.setLength(0); capture = false; } } else { if (capture) { buffer.append((char) ch); } } } return result; }
Code Sample 2:
public void testRedirectWithCookie() throws Exception { String host = "localhost"; int port = this.localServer.getServicePort(); this.localServer.register("*", new BasicRedirectService(host, port)); DefaultHttpClient client = new DefaultHttpClient(); CookieStore cookieStore = new BasicCookieStore(); client.setCookieStore(cookieStore); BasicClientCookie cookie = new BasicClientCookie("name", "value"); cookie.setDomain("localhost"); cookie.setPath("/"); cookieStore.addCookie(cookie); HttpContext context = new BasicHttpContext(); HttpGet httpget = new HttpGet("/oldlocation/"); HttpResponse response = client.execute(getServerHttp(), httpget, context); HttpEntity e = response.getEntity(); if (e != null) { e.consumeContent(); } HttpRequest reqWrapper = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri()); Header[] headers = reqWrapper.getHeaders(SM.COOKIE); assertEquals("There can only be one (cookie)", 1, headers.length); } |
11
| Code Sample 1:
public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
Code Sample 2:
public boolean ponerRivalxRonda(int idJugadorDiv, int idRonda, int dato) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPareoRival = " + 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); } |
00
| Code Sample 1:
public static void registerProviders(ResteasyProviderFactory factory) throws Exception { Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources("META-INF/services/" + Providers.class.getName()); LinkedHashSet<String> set = new LinkedHashSet<String>(); while (en.hasMoreElements()) { URL url = en.nextElement(); InputStream is = url.openStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.equals("")) continue; set.add(line); } } finally { is.close(); } } for (String line : set) { try { Class clazz = Thread.currentThread().getContextClassLoader().loadClass(line); factory.registerProvider(clazz, true); } catch (NoClassDefFoundError e) { logger.warn("NoClassDefFoundError: Unable to load builtin provider: " + line); } catch (ClassNotFoundException e) { logger.warn("ClassNotFoundException: Unable to load builtin provider: " + line); } } }
Code Sample 2:
public RobotList<Resource> sort_decr_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; } |
11
| Code Sample 1:
@Override public boolean update(String consulta, boolean autocommit, int transactionIsolation, Connection cx) throws SQLException { filasUpdate = 0; if (!consulta.contains(";")) { this.tipoConsulta = new Scanner(consulta); if (this.tipoConsulta.hasNext()) { execConsulta = this.tipoConsulta.next(); if (execConsulta.equalsIgnoreCase("update")) { Connection conexion = cx; Statement st = null; try { conexion.setAutoCommit(autocommit); if (transactionIsolation == 1 || transactionIsolation == 2 || transactionIsolation == 4 || transactionIsolation == 8) { conexion.setTransactionIsolation(transactionIsolation); } else { throw new IllegalArgumentException("Valor invalido sobre TransactionIsolation,\n TRANSACTION_NONE no es soportado por MySQL"); } st = (Statement) conexion.createStatement(ResultSetImpl.TYPE_SCROLL_SENSITIVE, ResultSetImpl.CONCUR_UPDATABLE); conexion.setReadOnly(false); filasUpdate = st.executeUpdate(consulta.trim(), Statement.RETURN_GENERATED_KEYS); if (filasUpdate > -1) { if (autocommit == false) { conexion.commit(); } return true; } else { return false; } } catch (MySQLIntegrityConstraintViolationException e) { System.out.println("Posible duplicacion de DATOS"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLNonTransientConnectionException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLDataException e) { System.out.println("Datos incorrectos"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (MySQLSyntaxErrorException e) { System.out.println("Error en la sintaxis de la Consulta en MySQL"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (SQLException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } finally { try { if (st != null) { if (!st.isClosed()) { st.close(); } } if (!conexion.isClosed()) { conexion.close(); } } catch (NullPointerException ne) { ne.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } else { throw new IllegalArgumentException("No es una instruccion Update"); } } else { try { throw new JMySQLException("Error Grave , notifique al departamento de Soporte Tecnico \n" + email); } catch (JMySQLException ex) { Logger.getLogger(JMySQL.class.getName()).log(Level.SEVERE, null, ex); return false; } } } else { throw new IllegalArgumentException("No estan permitidas las MultiConsultas en este metodo"); } }
Code Sample 2:
public Project deleteProject(int projectID) throws AdaptationException { Project project = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM Projects WHERE id = " + projectID; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete project failed."; log.error(msg); throw new AdaptationException(msg); } project = getProject(resultSet); query = "DELETE FROM Projects WHERE id = " + projectID; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProject"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return project; } |
00
| Code Sample 1:
public RTUser getUserInfo(final String username) { getSession(); Map<String, String> attributes = Collections.emptyMap(); final HttpGet get = new HttpGet(m_baseURL + "/REST/1.0/user/" + username); try { final HttpResponse response = getClient().execute(get); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != HttpStatus.SC_OK) { throw new RequestTrackerException("Received a non-200 response code from the server: " + responseCode); } else { if (response.getEntity() != null) { attributes = parseResponseStream(response.getEntity().getContent()); } } } catch (final Exception e) { LogUtils.errorf(this, e, "An exception occurred while getting user info for " + username); return null; } final String id = attributes.get("id"); final String realname = attributes.get("realname"); final String email = attributes.get("emailaddress"); if (id == null || "".equals(id)) { LogUtils.errorf(this, "Unable to retrieve ID from user info."); return null; } return new RTUser(Long.parseLong(id.replace("user/", "")), username, realname, email); }
Code Sample 2:
@Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final String url = req.getParameter("url"); if (!isAllowed(url)) { resp.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } final HttpClient client = new HttpClient(); client.getParams().setVersion(HttpVersion.HTTP_1_0); final PostMethod method = new PostMethod(url); method.getParams().setVersion(HttpVersion.HTTP_1_0); method.setFollowRedirects(false); final RequestEntity entity = new InputStreamRequestEntity(req.getInputStream()); method.setRequestEntity(entity); try { final int statusCode = client.executeMethod(method); if (statusCode != -1) { InputStream is = null; ServletOutputStream os = null; try { is = method.getResponseBodyAsStream(); try { os = resp.getOutputStream(); IOUtils.copy(is, os); } finally { if (os != null) { try { os.flush(); } catch (IOException ignored) { } } } } catch (IOException ioex) { final String message = ioex.getMessage(); if (!"chunked stream ended unexpectedly".equals(message)) { throw ioex; } } finally { IOUtils.closeQuietly(is); } } } finally { method.releaseConnection(); } } |
11
| Code Sample 1:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); String pluginPathInfo = pathInfo.substring(prefix.length()); String gwtPathInfo = pluginPathInfo.substring(pluginKey.length() + 1); String clPath = CLASSPATH_PREFIX + gwtPathInfo; InputStream input = cl.getResourceAsStream(clPath); if (input != null) { try { OutputStream output = resp.getOutputStream(); IOUtils.copy(input, output); } finally { input.close(); } } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
Code Sample 2:
public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); } |
00
| Code Sample 1:
public Object mapRow(ResultSet rs, int i) throws SQLException { Blob blob = rs.getBlob(1); if (rs.wasNull()) return null; try { InputStream inputStream = blob.getBinaryStream(); if (length > 0) IOUtils.copy(inputStream, outputStream, offset, length); else IOUtils.copy(inputStream, outputStream); inputStream.close(); } catch (IOException e) { } return null; }
Code Sample 2:
public static String sha1(String src) { MessageDigest md1 = null; try { md1 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } try { md1.update(src.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return hex(md1.digest()); } |
11
| Code Sample 1:
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; }
Code Sample 2:
public void doRender() throws IOException { File file = new File(fileName); if (!file.exists()) { logger.error("Static resource not found: " + fileName); isNotFound = true; return; } if (fileName.endsWith("xml") || fileName.endsWith("asp")) servletResponse.setContentType("text/xml"); else if (fileName.endsWith("css")) servletResponse.setContentType("text/css"); else if (fileName.endsWith("js")) servletResponse.setContentType("text/javascript"); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, servletResponse.getOutputStream()); logger.debug("Static resource rendered: ".concat(fileName)); } catch (FileNotFoundException e) { logger.error("Static resource not found: " + fileName); isNotFound = true; } finally { IOUtils.closeQuietly(in); } } |
11
| Code Sample 1:
public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
Code Sample 2:
public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); } |
11
| Code Sample 1:
private void fileMaker() { try { long allData = 0; double a = 10; int range = 0; int blockLength = 0; File newFile = new File(mfr.getFilename() + ".part"); if (newFile.exists()) { newFile.delete(); } ArrayList<DataRange> rangeList = null; byte[] data = null; newFile.createNewFile(); ByteBuffer buffer = ByteBuffer.allocate(mfr.getBlocksize()); FileChannel rChannel = new FileInputStream(inputFileName).getChannel(); FileChannel wChannel = new FileOutputStream(newFile, true).getChannel(); System.out.println(); System.out.print("File completion: "); System.out.print("|----------|"); openConnection(); http.getResponseHeader(); for (int i = 0; i < fileMap.length; i++) { fileOffset = fileMap[i]; if (fileOffset != -1) { rChannel.read(buffer, fileOffset); buffer.flip(); wChannel.write(buffer); buffer.clear(); } else { if (!rangeQueue) { rangeList = rangeLookUp(i); range = rangeList.size(); openConnection(); http.setRangesRequest(rangeList); http.sendRequest(); http.getResponseHeader(); data = http.getResponseBody(mfr.getBlocksize()); allData += http.getAllTransferedDataLength(); } if ((i * mfr.getBlocksize() + mfr.getBlocksize()) < mfr.getLength()) { blockLength = mfr.getBlocksize(); } else { blockLength = (int) ((int) (mfr.getBlocksize()) + (mfr.getLength() - (i * mfr.getBlocksize() + mfr.getBlocksize()))); } buffer.put(data, (range - rangeList.size()) * mfr.getBlocksize(), blockLength); buffer.flip(); wChannel.write(buffer); buffer.clear(); rangeList.remove(0); if (rangeList.isEmpty()) { rangeQueue = false; } } if ((((double) i / ((double) fileMap.length - 1)) * 100) >= a) { progressBar(((double) i / ((double) fileMap.length - 1)) * 100); a += 10; } } newFile.setLastModified(getMTime()); sha = new SHA1(newFile); if (sha.SHA1sum().equals(mfr.getSha1())) { System.out.println("\nverifying download...checksum matches OK"); System.out.println("used " + (mfr.getLength() - (mfr.getBlocksize() * missing)) + " " + "local, fetched " + (mfr.getBlocksize() * missing)); new File(mfr.getFilename()).renameTo(new File(mfr.getFilename() + ".zs-old")); newFile.renameTo(new File(mfr.getFilename())); allData += mfr.getLengthOfMetafile(); System.out.println("really downloaded " + allData); double overhead = ((double) (allData - (mfr.getBlocksize() * missing)) / ((double) (mfr.getBlocksize() * missing))) * 100; System.out.println("overhead: " + df.format(overhead) + "%"); } else { System.out.println("\nverifying download...checksum don't match"); System.out.println("Deleting temporary file"); newFile.delete(); System.exit(1); } } catch (IOException ex) { System.out.println("Can't read or write, check your permissions."); System.exit(1); } }
Code Sample 2:
private static void writeBinaryFile(String filename, String target) throws IOException { File outputFile = new File(target); AgentFilesystem.forceDir(outputFile.getParent()); FileOutputStream output = new FileOutputStream(new File(target)); FileInputStream inputStream = new FileInputStream(filename); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) > -1) output.write(buffer, 0, bytesRead); inputStream.close(); output.close(); } |
00
| Code Sample 1:
public static final void parse(String infile, String outfile) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(infile)); DataOutputStream output = new DataOutputStream(new FileOutputStream(outfile)); int w = Integer.parseInt(reader.readLine()); int h = Integer.parseInt(reader.readLine()); output.writeByte(w); output.writeByte(h); int lineCount = 2; try { do { for (int i = 0; i < h; i++) { lineCount++; String line = reader.readLine(); if (line == null) { throw new RuntimeException("Unexpected end of file at line " + lineCount); } for (int j = 0; j < w; j++) { char c = line.charAt(j); System.out.print(c); output.writeByte(c); } System.out.println(""); } lineCount++; output.writeShort(Short.parseShort(reader.readLine())); } while (reader.readLine() != null); } finally { reader.close(); output.close(); } }
Code Sample 2:
public int doEndTag() throws JspException { HttpSession session = pageContext.getSession(); try { IntactUserI user = (IntactUserI) session.getAttribute(Constants.USER_KEY); String urlStr = user.getSourceURL(); if (urlStr == null) { return EVAL_PAGE; } URL url = null; try { url = new URL(urlStr); } catch (MalformedURLException me) { String decodedUrl = URLDecoder.decode(urlStr, "UTF-8"); pageContext.getOut().write("The source is malformed : <a href=\"" + decodedUrl + "\" target=\"_blank\">" + decodedUrl + "</a>"); return EVAL_PAGE; } StringBuffer httpContent = new StringBuffer(); httpContent.append("<!-- URL : " + urlStr + "-->"); String tmpLine; try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((tmpLine = reader.readLine()) != null) { httpContent.append(tmpLine); } reader.close(); } catch (IOException ioe) { user.resetSourceURL(); String decodedUrl = URLDecoder.decode(urlStr, "UTF-8"); pageContext.getOut().write("Unable to display the source at : <a href=\"" + decodedUrl + "\" target=\"_blank\">" + decodedUrl + "</a>"); return EVAL_PAGE; } pageContext.getOut().write(httpContent.toString()); } catch (Exception e) { e.printStackTrace(); throw new JspException("Error when trying to get HTTP content"); } return EVAL_PAGE; } |
00
| Code Sample 1:
public static IProject createEMFProject(IPath javaSource, URI projectLocationURI, List<IProject> referencedProjects, Monitor monitor, int style, List<?> pluginVariables) { IProgressMonitor progressMonitor = BasicMonitor.toIProgressMonitor(monitor); String projectName = javaSource.segment(0); IProject project = null; try { List<IClasspathEntry> classpathEntries = new UniqueEList<IClasspathEntry>(); progressMonitor.beginTask("", 10); progressMonitor.subTask(CodeGenEcorePlugin.INSTANCE.getString("_UI_CreatingEMFProject_message", new Object[] { projectName, projectLocationURI != null ? projectLocationURI.toString() : projectName })); IWorkspace workspace = ResourcesPlugin.getWorkspace(); project = workspace.getRoot().getProject(projectName); if (!project.exists()) { URI location = projectLocationURI; if (location == null) { location = URI.createFileURI(workspace.getRoot().getLocation().append(projectName).toOSString()); } location = location.appendSegment(".project"); File projectFile = new File(location.toString()); if (projectFile.exists()) { projectFile.renameTo(new File(location.toString() + ".old")); } } IJavaProject javaProject = JavaCore.create(project); IProjectDescription projectDescription = null; if (!project.exists()) { projectDescription = ResourcesPlugin.getWorkspace().newProjectDescription(projectName); if (projectLocationURI != null) { projectDescription.setLocationURI(new java.net.URI(projectLocationURI.toString())); } project.create(projectDescription, new SubProgressMonitor(progressMonitor, 1)); project.open(new SubProgressMonitor(progressMonitor, 1)); } else { projectDescription = project.getDescription(); project.open(new SubProgressMonitor(progressMonitor, 1)); if (project.hasNature(JavaCore.NATURE_ID)) { classpathEntries.addAll(Arrays.asList(javaProject.getRawClasspath())); } } boolean isInitiallyEmpty = classpathEntries.isEmpty(); { if (referencedProjects.size() != 0 && (style & (EMF_PLUGIN_PROJECT_STYLE | EMF_EMPTY_PROJECT_STYLE)) == 0) { projectDescription.setReferencedProjects(referencedProjects.toArray(new IProject[referencedProjects.size()])); for (IProject referencedProject : referencedProjects) { IClasspathEntry referencedProjectClasspathEntry = JavaCore.newProjectEntry(referencedProject.getFullPath()); classpathEntries.add(referencedProjectClasspathEntry); } } String[] natureIds = projectDescription.getNatureIds(); if (natureIds == null) { natureIds = new String[] { JavaCore.NATURE_ID, "org.eclipse.pde.PluginNature" }; } else { if (!project.hasNature(JavaCore.NATURE_ID)) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = JavaCore.NATURE_ID; } if (!project.hasNature("org.eclipse.pde.PluginNature")) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = "org.eclipse.pde.PluginNature"; } } projectDescription.setNatureIds(natureIds); ICommand[] builders = projectDescription.getBuildSpec(); if (builders == null) { builders = new ICommand[0]; } boolean hasManifestBuilder = false; boolean hasSchemaBuilder = false; for (int i = 0; i < builders.length; ++i) { if ("org.eclipse.pde.ManifestBuilder".equals(builders[i].getBuilderName())) { hasManifestBuilder = true; } if ("org.eclipse.pde.SchemaBuilder".equals(builders[i].getBuilderName())) { hasSchemaBuilder = true; } } if (!hasManifestBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.ManifestBuilder"); } if (!hasSchemaBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.SchemaBuilder"); } projectDescription.setBuildSpec(builders); project.setDescription(projectDescription, new SubProgressMonitor(progressMonitor, 1)); IContainer sourceContainer = project; if (javaSource.segmentCount() > 1) { IPath sourceContainerPath = javaSource.removeFirstSegments(1).makeAbsolute(); sourceContainer = project.getFolder(sourceContainerPath); if (!sourceContainer.exists()) { for (int i = sourceContainerPath.segmentCount() - 1; i >= 0; i--) { sourceContainer = project.getFolder(sourceContainerPath.removeLastSegments(i)); if (!sourceContainer.exists()) { ((IFolder) sourceContainer).create(false, true, new SubProgressMonitor(progressMonitor, 1)); } } } IClasspathEntry sourceClasspathEntry = JavaCore.newSourceEntry(javaSource); for (Iterator<IClasspathEntry> i = classpathEntries.iterator(); i.hasNext(); ) { IClasspathEntry classpathEntry = i.next(); if (classpathEntry.getPath().isPrefixOf(javaSource)) { i.remove(); } } classpathEntries.add(0, sourceClasspathEntry); } if (isInitiallyEmpty) { IClasspathEntry jreClasspathEntry = JavaCore.newVariableEntry(new Path(JavaRuntime.JRELIB_VARIABLE), new Path(JavaRuntime.JRESRC_VARIABLE), new Path(JavaRuntime.JRESRCROOT_VARIABLE)); for (Iterator<IClasspathEntry> i = classpathEntries.iterator(); i.hasNext(); ) { IClasspathEntry classpathEntry = i.next(); if (classpathEntry.getPath().isPrefixOf(jreClasspathEntry.getPath())) { i.remove(); } } String jreContainer = JavaRuntime.JRE_CONTAINER; String complianceLevel = CodeGenUtil.EclipseUtil.getJavaComplianceLevel(project); if ("1.5".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"; } else if ("1.6".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"; } classpathEntries.add(JavaCore.newContainerEntry(new Path(jreContainer))); } if ((style & EMF_EMPTY_PROJECT_STYLE) == 0) { if ((style & EMF_PLUGIN_PROJECT_STYLE) != 0) { classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins"))); for (Iterator<IClasspathEntry> i = classpathEntries.iterator(); i.hasNext(); ) { IClasspathEntry classpathEntry = i.next(); if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE && !JavaRuntime.JRELIB_VARIABLE.equals(classpathEntry.getPath().toString()) || classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { i.remove(); } } } else { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_CORE_RUNTIME", "org.eclipse.core.runtime"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_CORE_RESOURCES", "org.eclipse.core.resources"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_COMMON", "org.eclipse.emf.common"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_ECORE", "org.eclipse.emf.ecore"); if ((style & EMF_XML_PROJECT_STYLE) != 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_ECORE_XMI", "org.eclipse.emf.ecore.xmi"); } if ((style & EMF_MODEL_PROJECT_STYLE) == 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_EDIT", "org.eclipse.emf.edit"); if ((style & EMF_EDIT_PROJECT_STYLE) == 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_SWT", "org.eclipse.swt"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_JFACE", "org.eclipse.jface"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_VIEWS", "org.eclipse.ui.views"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_EDITORS", "org.eclipse.ui.editors"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_IDE", "org.eclipse.ui.ide"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_WORKBENCH", "org.eclipse.ui.workbench"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_COMMON_UI", "org.eclipse.emf.common.ui"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_EDIT_UI", "org.eclipse.emf.edit.ui"); if ((style & EMF_XML_PROJECT_STYLE) == 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_ECORE_XMI", "org.eclipse.emf.ecore.xmi"); } } } if ((style & EMF_TESTS_PROJECT_STYLE) != 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "JUNIT", "org.junit"); } if (pluginVariables != null) { for (Iterator<?> i = pluginVariables.iterator(); i.hasNext(); ) { Object variable = i.next(); if (variable instanceof IClasspathEntry) { classpathEntries.add((IClasspathEntry) variable); } else if (variable instanceof String) { String pluginVariable = (String) variable; String name; String id; int index = pluginVariable.indexOf("="); if (index == -1) { name = pluginVariable.replace('.', '_').toUpperCase(); id = pluginVariable; } else { name = pluginVariable.substring(0, index); id = pluginVariable.substring(index + 1); } CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, name, id); } } } } } javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]), new SubProgressMonitor(progressMonitor, 1)); } if (isInitiallyEmpty) { javaProject.setOutputLocation(new Path("/" + javaSource.segment(0) + "/bin"), new SubProgressMonitor(progressMonitor, 1)); } } catch (Exception exception) { exception.printStackTrace(); CodeGenEcorePlugin.INSTANCE.log(exception); } finally { progressMonitor.done(); } return project; }
Code Sample 2:
public void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } |
00
| Code Sample 1:
protected void logout() { Session session = getConnection().getSession(); session.removeAttribute("usercookie.object"); String urlIn = GeoNetworkContext.url + "/" + GeoNetworkContext.logoutService; Element results = null; String cookie = (String) session.getAttribute("usercookie.object"); if (cookie != null) { try { URL url = new URL(urlIn); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); conn.setRequestProperty("Cookie", cookie); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); try { results = Xml.loadStream(in); log.debug("CheckLogout to GeoNetwork returned " + Xml.getString(results)); } finally { in.close(); } } catch (Exception e) { throw new RuntimeException("User logout to GeoNetwork failed: ", e); } } log.debug("GeoNetwork logout done"); }
Code Sample 2:
@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(); } |
00
| Code Sample 1:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
Code Sample 2:
public HttpResponse executeWithoutRewriting(HttpUriRequest request, HttpContext context) throws IOException { int code = -1; long start = SystemClock.elapsedRealtime(); try { HttpResponse response; mConnectionAllocated.set(null); if (NetworkStatsEntity.shouldLogNetworkStats()) { int uid = android.os.Process.myUid(); long startTx = NetStat.getUidTxBytes(uid); long startRx = NetStat.getUidRxBytes(uid); response = mClient.execute(request, context); HttpEntity origEntity = response == null ? null : response.getEntity(); if (origEntity != null) { long now = SystemClock.elapsedRealtime(); long elapsed = now - start; NetworkStatsEntity entity = new NetworkStatsEntity(origEntity, mAppName, uid, startTx, startRx, elapsed, now); response.setEntity(entity); } } else { response = mClient.execute(request, context); } code = response.getStatusLine().getStatusCode(); return response; } finally { try { long elapsed = SystemClock.elapsedRealtime() - start; ContentValues values = new ContentValues(); values.put(Checkin.Stats.COUNT, 1); values.put(Checkin.Stats.SUM, elapsed / 1000.0); values.put(Checkin.Stats.TAG, Checkin.Stats.Tag.HTTP_REQUEST + ":" + mAppName); mResolver.insert(Checkin.Stats.CONTENT_URI, values); if (mConnectionAllocated.get() == null && code >= 0) { values.put(Checkin.Stats.TAG, Checkin.Stats.Tag.HTTP_REUSED + ":" + mAppName); mResolver.insert(Checkin.Stats.CONTENT_URI, values); } String status = code < 0 ? "IOException" : Integer.toString(code); values.put(Checkin.Stats.TAG, Checkin.Stats.Tag.HTTP_STATUS + ":" + mAppName + ":" + status); mResolver.insert(Checkin.Stats.CONTENT_URI, values); } catch (Exception e) { Log.e(TAG, "Error recording stats", e); } } } |
00
| Code Sample 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(); } }
Code Sample 2:
public void actionPerformed(ActionEvent e) { if (mode == ADD_URL) { String url = JOptionPane.showInputDialog(null, "Enter URL", "Enter URL", JOptionPane.OK_CANCEL_OPTION); if (url == null) return; try { is = new URL(url).openStream(); } catch (Exception ex) { ex.printStackTrace(); } } else if (mode == ADD_FILE) { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.showDialog(null, "Add tab"); File file = chooser.getSelectedFile(); if (file == null) return; try { is = new FileInputStream(file); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } if (repository == null) repository = PersistenceService.getInstance(); List artists = repository.getAllArtists(); EventList artistList = new BasicEventList(); artistList.addAll(artists); addDialog = new AddSongDialog(artistList, JOptionPane.getRootFrame(), true); Song s = addDialog.getSong(); if (is != null) { String tab; try { tab = readTab(is); s.setTablature(tab); addDialog.setSong(s); } catch (Exception ex) { ex.printStackTrace(); } } addDialog.setVisible(true); addDialog.addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { int ok = addDialog.getReturnStatus(); if (ok == AddSongDialog.RET_CANCEL) return; addSong(); } }); } |
11
| Code Sample 1:
private String getCoded(String pass) { String passSecret = ""; try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(pass.getBytes("UTF8")); byte s[] = m.digest(); for (int i = 0; i < s.length; i++) { passSecret += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6); } } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return passSecret; }
Code Sample 2:
public static User authenticate(final String username, final String password) throws LoginException { Object result = doPriviledgedAction(new PrivilegedAction() { public Object run() { List correctUsers = (List) JsonPath.query("select * from ? where name=?", usersTable(), username); if (correctUsers.size() == 0) { return new LoginException("user " + username + " not found"); } Persistable userObject = (Persistable) correctUsers.get(0); boolean alreadyHashed = false; boolean passwordMatch = password.equals(userObject.get(PASSWORD_FIELD)); if (!passwordMatch) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(((String) userObject.get(PASSWORD_FIELD)).getBytes()); passwordMatch = password.equals(new String(new Base64().encode(md.digest()))); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } alreadyHashed = true; } if (passwordMatch) { Logger.getLogger(User.class.toString()).info("User " + username + " has been authenticated"); User user = (User) userObject; try { if (alreadyHashed) user.currentTicket = password; else { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); user.currentTicket = new String(new Base64().encode(md.digest())); } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return user; } else { Logger.getLogger(User.class.toString()).info("The password was incorrect for " + username); return new LoginException("The password was incorrect for user " + username + ". "); } } }); if (result instanceof LoginException) throw (LoginException) result; return (User) result; } |
00
| Code Sample 1:
private void fetchTree() throws IOException { String urlString = BASE_URL + TREE_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String toParse = in.readLine(); while (in.ready()) { String add = in.readLine(); if (add == null) break; toParse += add; } if (toParse != null && !toParse.startsWith("No tree available")) mProteinTree = new PTree(this, toParse); }
Code Sample 2:
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); } |
11
| Code Sample 1:
public static void copyFile(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(); } } }
Code Sample 2:
public static void main(String[] args) throws IOException { String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); FSDataInputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); System.out.println("\n"); in.seek(0); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } } |
00
| Code Sample 1:
public void actionPerformed(ActionEvent ae) { String actionCommand = ae.getActionCommand(); if (actionCommand == null) { return; } if (DataManager.SHOW_DEBUG) { System.out.println("Action command : " + actionCommand); } DataManager dataManager = ClientDirector.getDataManager(); PlayerImpl myPlayer = dataManager.getMyPlayer(); if (!myPlayer.getLocation().isRoom() && actionCommand.equals("createChatRoom")) { JOptionPane.showMessageDialog(null, "Sorry, but you can not create/leave chat channels\n" + "on World/Town Maps.", "INFORMATION", JOptionPane.INFORMATION_MESSAGE); return; } if (actionCommand.equals("createChatRoom")) { WotlasLocation chatRoomLocation = myPlayer.getLocation(); String chatRoomName = JOptionPane.showInputDialog("Please enter a Name:"); if (chatRoomName == null || chatRoomName.length() == 0) { return; } if (this.tabbedPane.getTabCount() >= ChatRoom.MAXIMUM_CHATROOMS_PER_ROOM - 1) { this.b_createChatRoom.setEnabled(false); } else { this.b_createChatRoom.setEnabled(true); } myPlayer.sendMessage(new ChatRoomCreationMessage(chatRoomName, myPlayer.getPrimaryKey())); } else if (actionCommand.equals("leaveChatRoom")) { if (!this.currentPrimaryKey.equals(ChatRoom.DEFAULT_CHAT)) { myPlayer.sendMessage(new RemPlayerFromChatRoomMessage(myPlayer.getPrimaryKey(), this.currentPrimaryKey)); } } else if (actionCommand.equals("helpChat")) { DataManager dManager = ClientDirector.getDataManager(); dManager.sendMessage(new SendTextMessage(dManager.getMyPlayer().getPrimaryKey(), dManager.getMyPlayer().getPlayerName(), getMyCurrentChatPrimaryKey(), "/help", ChatRoom.NORMAL_VOICE_LEVEL)); } else if (actionCommand.equals("imageChat")) { String imageURL = JOptionPane.showInputDialog("Please enter your image's URL:\nExample: http://wotlas.sf.net/images/wotlas.gif"); if (imageURL == null || imageURL.length() == 0) { return; } try { URL url = new URL(imageURL); URLConnection urlC = url.openConnection(); urlC.connect(); String ctype = urlC.getContentType(); if (!ctype.startsWith("image/")) { JOptionPane.showMessageDialog(null, "The specified URL does not refer to an image !", "Information", JOptionPane.INFORMATION_MESSAGE); return; } if (urlC.getContentLength() > 50 * 1024) { JOptionPane.showMessageDialog(null, "The specified image is too big (above 50kB).", "Information", JOptionPane.INFORMATION_MESSAGE); return; } } catch (Exception ex) { Debug.signal(Debug.ERROR, this, "Failed to get image: " + ex); JOptionPane.showMessageDialog(null, "Failed to get the specified image...\nCheck your URL.", "Error", JOptionPane.ERROR_MESSAGE); return; } DataManager dManager = ClientDirector.getDataManager(); dManager.sendMessage(new SendTextMessage(dManager.getMyPlayer().getPrimaryKey(), dManager.getMyPlayer().getPlayerName(), getMyCurrentChatPrimaryKey(), "<img src='" + imageURL + "'>", ChatRoom.NORMAL_VOICE_LEVEL)); } else { if (DataManager.SHOW_DEBUG) { System.out.println("Err : unknown actionCommand"); System.out.println("No action command found!"); } } }
Code Sample 2:
public final Matrix3D<E> read(final URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("url must not be null"); } InputStream inputStream = null; try { inputStream = url.openStream(); return read(inputStream); } catch (IOException e) { throw e; } finally { MatrixIOUtils.closeQuietly(inputStream); } } |
11
| Code Sample 1:
public byte[] getResponseContent() throws IOException { if (responseContent == null) { InputStream is = getResponseStream(); if (is == null) { responseContent = new byte[0]; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); IOUtils.copy(is, baos); responseContent = baos.toByteArray(); } } return responseContent; }
Code Sample 2:
public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest.getName()); } } byte[] buffer = new byte[bufSize]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } } |
00
| Code Sample 1:
public static void copyFile(File sourceFile, File destFile) { FileChannel source = null; FileChannel destination = null; try { if (!destFile.exists()) { destFile.createNewFile(); } source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } catch (Exception e) { e.printStackTrace(); } } }
Code Sample 2:
protected String calcAuthResponse(String challenge) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(securityPolicy); md.update(challenge.getBytes()); for (int i = 0, n = password.length; i < n; i++) { md.update((byte) password[i]); } byte[] digest = md.digest(); StringBuffer digestText = new StringBuffer(); for (int i = 0; i < digest.length; i++) { int v = (digest[i] < 0) ? digest[i] + 256 : digest[i]; String hex = Integer.toHexString(v); if (hex.length() == 1) { digestText.append("0"); } digestText.append(hex); } return digestText.toString(); } |
11
| Code Sample 1:
public static User authenticate(final String username, final String password) throws LoginException { Object result = doPriviledgedAction(new PrivilegedAction() { public Object run() { List correctUsers = (List) JsonPath.query("select * from ? where name=?", usersTable(), username); if (correctUsers.size() == 0) { return new LoginException("user " + username + " not found"); } Persistable userObject = (Persistable) correctUsers.get(0); boolean alreadyHashed = false; boolean passwordMatch = password.equals(userObject.get(PASSWORD_FIELD)); if (!passwordMatch) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(((String) userObject.get(PASSWORD_FIELD)).getBytes()); passwordMatch = password.equals(new String(new Base64().encode(md.digest()))); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } alreadyHashed = true; } if (passwordMatch) { Logger.getLogger(User.class.toString()).info("User " + username + " has been authenticated"); User user = (User) userObject; try { if (alreadyHashed) user.currentTicket = password; else { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); user.currentTicket = new String(new Base64().encode(md.digest())); } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return user; } else { Logger.getLogger(User.class.toString()).info("The password was incorrect for " + username); return new LoginException("The password was incorrect for user " + username + ". "); } } }); if (result instanceof LoginException) throw (LoginException) result; return (User) result; }
Code Sample 2:
public synchronized String getEncryptedPassword(String plaintext, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance(algorithm); md.update(plaintext.getBytes("UTF-8")); return bytesToHexString(md.digest()); } |
11
| Code Sample 1:
public static String getMD5Hash(String in) { StringBuffer result = new StringBuffer(32); try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(in.getBytes()); Formatter f = new Formatter(result); for (byte b : md5.digest()) { f.format("%02x", b); } } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return result.toString(); }
Code Sample 2:
public String getMd5CodeOf16(String str) { StringBuffer buf = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte b[] = md.digest(); int i; buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { return buf.toString().substring(8, 24); } } |
11
| Code Sample 1:
private static boolean computeCustomerAverages(String completePath, String CustomerAveragesOutputFileName, String CustIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TIntObjectHashMap CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int startIndex, endIndex; TIntArrayList a; int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustomerAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalCusts = CustomerLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "MovieRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); int[] itr = CustomerLimitsTHash.keys(); startIndex = 0; endIndex = 0; a = null; ByteBuffer buf; for (int i = 0; i < totalCusts; i++) { int currentCust = itr[i]; a = (TIntArrayList) CustomerLimitsTHash.get(currentCust); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 3); inC.read(buf, (startIndex - 1) * 3); } else { buf = ByteBuffer.allocate(3); inC.read(buf, (startIndex - 1) * 3); } buf.flip(); int bufsize = buf.capacity() / 3; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getShort(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(8); outbuf.putInt(currentCust); outbuf.putFloat(sum / bufsize); outbuf.flip(); outC.write(outbuf); buf.clear(); buf = null; a.clear(); a = null; } inC.close(); outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
Code Sample 2:
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(); } } |
11
| Code Sample 1:
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version_" + datastream + ".xml\""); } String xmlContent = URLDecoder.decode(req.getParameterValues(Constants.PARAM_CONTENT)[0], "UTF-8"); InputStream is = new ByteArrayInputStream(xmlContent.getBytes("UTF-8")); ServletOutputStream os = resp.getOutputStream(); IOUtils.copyStreams(is, os); os.flush(); }
Code Sample 2:
@Override public void handle(HttpExchange http) throws IOException { Headers reqHeaders = http.getRequestHeaders(); Headers respHeader = http.getResponseHeaders(); respHeader.add("Content-Type", "text/plain"); http.sendResponseHeaders(200, 0); PrintWriter console = new PrintWriter(System.err); PrintWriter web = new PrintWriter(http.getResponseBody()); PrintWriter out = new PrintWriter(new YWriter(web, console)); out.println("### " + new Date() + " ###"); out.println("Method: " + http.getRequestMethod()); out.println("Protocol: " + http.getProtocol()); out.println("RemoteAddress.HostName: " + http.getRemoteAddress().getHostName()); for (String key : reqHeaders.keySet()) { out.println("* \"" + key + "\""); for (String v : reqHeaders.get(key)) { out.println("\t" + v); } } InputStream in = http.getRequestBody(); if (in != null) { out.println(); IOUtils.copyTo(new InputStreamReader(in), out); in.close(); } out.flush(); out.close(); } |
11
| Code Sample 1:
@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()); } }
Code Sample 2:
private static void addFile(File file, TarArchiveOutputStream taos) throws IOException { String filename = null; filename = file.getName(); TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); } |
11
| Code Sample 1:
public void xtest2() throws Exception { InputStream input1 = new FileInputStream("C:/Documentos/j931_01.pdf"); InputStream input2 = new FileInputStream("C:/Documentos/j931_02.pdf"); InputStream tmp = new ITextManager().merge(new InputStream[] { input1, input2 }); FileOutputStream output = new FileOutputStream("C:/temp/split.pdf"); IOUtils.copy(tmp, output); input1.close(); input2.close(); tmp.close(); output.close(); }
Code Sample 2:
public void render(ServiceContext serviceContext) throws Exception { if (serviceContext.getTemplateName() == null) throw new Exception("no Template defined for service: " + serviceContext.getServiceInfo().getRefName()); File f = new File(serviceContext.getTemplateName()); serviceContext.getResponse().setContentLength((int) f.length()); InputStream in = new FileInputStream(f); IOUtils.copy(in, serviceContext.getResponse().getOutputStream(), 0, (int) f.length()); in.close(); } |
00
| Code Sample 1:
public void importarHistoricoDeProventos(File pArquivoXLS, boolean pFiltrarPelaDataDeCorteDoCabecalho, Andamento pAndamento) throws IOException, SQLException, InvalidFormatException { int iLinha = -1; String nomeDaColuna = ""; Statement stmtLimpezaInicialDestino = null; OraclePreparedStatement stmtDestino = null; try { Workbook arquivo = WorkbookFactory.create(new FileInputStream(pArquivoXLS)); Sheet plan1 = arquivo.getSheetAt(0); int QUANTIDADE_DE_REGISTROS_DE_METADADOS = 2; int quantidadeDeRegistrosEstimada = plan1.getPhysicalNumberOfRows() - QUANTIDADE_DE_REGISTROS_DE_METADADOS; String vNomeDePregao, vTipoDaAcao, vDataDaAprovacao, vTipoDoProvento, vDataDoUltimoPrecoCom; BigDecimal vValorDoProvento, vUltimoPrecoCom, vProventoPorPreco; int vProventoPor1Ou1000Acoes, vPrecoPor1Ou1000Acoes; java.sql.Date vUltimoDiaCom; DateFormat formatadorData = new SimpleDateFormat("yyyyMMdd"); DateFormat formatadorPadraoData = DateFormat.getDateInstance(); Row registro; Cell celula; java.util.Date dataLimite = plan1.getRow(0).getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getDateCellValue(); Cell celulaUltimoDiaCom; java.util.Date tmpUltimoDiaCom; stmtLimpezaInicialDestino = conDestino.createStatement(); String sql = "TRUNCATE TABLE TMP_TB_PROVENTO_EM_DINHEIRO"; stmtLimpezaInicialDestino.executeUpdate(sql); sql = "INSERT INTO TMP_TB_PROVENTO_EM_DINHEIRO(NOME_DE_PREGAO, TIPO_DA_ACAO, DATA_DA_APROVACAO, VALOR_DO_PROVENTO, PROVENTO_POR_1_OU_1000_ACOES, TIPO_DO_PROVENTO, ULTIMO_DIA_COM, DATA_DO_ULTIMO_PRECO_COM, ULTIMO_PRECO_COM, PRECO_POR_1_OU_1000_ACOES, PERC_PROVENTO_POR_PRECO) VALUES(:NOME_DE_PREGAO, :TIPO_DA_ACAO, :DATA_DA_APROVACAO, :VALOR_DO_PROVENTO, :PROVENTO_POR_1_OU_1000_ACOES, :TIPO_DO_PROVENTO, :ULTIMO_DIA_COM, :DATA_DO_ULTIMO_PRECO_COM, :ULTIMO_PRECO_COM, :PRECO_POR_1_OU_1000_ACOES, :PERC_PROVENTO_POR_PRECO)"; stmtDestino = (OraclePreparedStatement) conDestino.prepareStatement(sql); stmtDestino.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosImportados = 0; final int NUMERO_DA_LINHA_INICIAL = 1; for (iLinha = NUMERO_DA_LINHA_INICIAL; true; iLinha++) { registro = plan1.getRow(iLinha); if (registro != null) { nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.toString(); celulaUltimoDiaCom = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.ordinal()); if (celulaUltimoDiaCom != null) { if (celulaUltimoDiaCom.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpUltimoDiaCom = celulaUltimoDiaCom.getDateCellValue(); if (tmpUltimoDiaCom.compareTo(dataLimite) <= 0 || !pFiltrarPelaDataDeCorteDoCabecalho) { vUltimoDiaCom = new java.sql.Date(celulaUltimoDiaCom.getDateCellValue().getTime()); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.toString(); vNomeDePregao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.toString(); vTipoDaAcao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.ordinal()); try { java.util.Date tmpDataDaAprovacao; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDaAprovacao = celula.getDateCellValue(); } else { tmpDataDaAprovacao = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDaAprovacao = formatadorData.format(tmpDataDaAprovacao); } catch (ParseException ex) { vDataDaAprovacao = celula.getStringCellValue(); } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.toString(); vValorDoProvento = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.toString(); vProventoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.toString(); vTipoDoProvento = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.ordinal()); if (celula != null) { try { java.util.Date tmpDataDoUltimoPrecoCom; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDoUltimoPrecoCom = celula.getDateCellValue(); } else { tmpDataDoUltimoPrecoCom = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDoUltimoPrecoCom = formatadorData.format(tmpDataDoUltimoPrecoCom); } catch (ParseException ex) { vDataDoUltimoPrecoCom = celula.getStringCellValue().trim(); } } else { vDataDoUltimoPrecoCom = ""; } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.toString(); vUltimoPrecoCom = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.toString(); vPrecoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.ordinal()); if (celula != null && celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { vProventoPorPreco = new BigDecimal(String.valueOf(celula.getNumericCellValue())); } else { vProventoPorPreco = null; } stmtDestino.clearParameters(); stmtDestino.setStringAtName("NOME_DE_PREGAO", vNomeDePregao); stmtDestino.setStringAtName("TIPO_DA_ACAO", vTipoDaAcao); stmtDestino.setStringAtName("DATA_DA_APROVACAO", vDataDaAprovacao); stmtDestino.setBigDecimalAtName("VALOR_DO_PROVENTO", vValorDoProvento); stmtDestino.setIntAtName("PROVENTO_POR_1_OU_1000_ACOES", vProventoPor1Ou1000Acoes); stmtDestino.setStringAtName("TIPO_DO_PROVENTO", vTipoDoProvento); stmtDestino.setDateAtName("ULTIMO_DIA_COM", vUltimoDiaCom); stmtDestino.setStringAtName("DATA_DO_ULTIMO_PRECO_COM", vDataDoUltimoPrecoCom); stmtDestino.setBigDecimalAtName("ULTIMO_PRECO_COM", vUltimoPrecoCom); stmtDestino.setIntAtName("PRECO_POR_1_OU_1000_ACOES", vPrecoPor1Ou1000Acoes); stmtDestino.setBigDecimalAtName("PERC_PROVENTO_POR_PRECO", vProventoPorPreco); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; } } } else { break; } double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosEstimada * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } else { break; } } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); ProblemaNaImportacaoDeArquivo problemaDetalhado = new ProblemaNaImportacaoDeArquivo(); problemaDetalhado.nomeDoArquivo = pArquivoXLS.getName(); problemaDetalhado.linhaProblematicaDoArquivo = iLinha + 1; problemaDetalhado.colunaProblematicaDoArquivo = nomeDaColuna; problemaDetalhado.detalhesSobreOProblema = ex; throw problemaDetalhado; } finally { pAndamento.setPercentualCompleto(100); if (stmtLimpezaInicialDestino != null && (!stmtLimpezaInicialDestino.isClosed())) { stmtLimpezaInicialDestino.close(); } if (stmtDestino != null && (!stmtDestino.isClosed())) { stmtDestino.close(); } } }
Code Sample 2:
@Override public Result sendSMS(String number, String text, Proxy proxy) { try { DefaultHttpClient client = new DefaultHttpClient(); if (proxy != null) { HttpHost prox = new HttpHost(proxy.host, proxy.port); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, prox); } String target = "http://www.smsbilliger.de/free-sms.html"; HttpGet get = new HttpGet(target); HttpResponse response = client.execute(get); HttpEntity e = response.getEntity(); Document doc = ref.getDocumentFromInputStream(e.getContent()); List<Element> forms = ref.selectByXPathOnDocument(doc, "//<ns>FORM", doc.getRootElement().getNamespaceURI()); if (forms.size() == 0) return new Result(Result.SMS_LIMIT_REACHED); Element form = forms.get(0); List<NameValuePair> formparas = new ArrayList<NameValuePair>(); List<Element> inputs = ref.selectByXPathOnElement(form, "//<ns>INPUT|//<ns>TEXTAREA|//<ns>SELECT", form.getNamespaceURI()); Iterator<Element> it = inputs.iterator(); while (it.hasNext()) { Element input = it.next(); String type = input.getAttributeValue("type"); String name = input.getAttributeValue("name"); String value = input.getAttributeValue("value"); if (type != null && type.equals("hidden")) { formparas.add(new BasicNameValuePair(name, value)); } else if (name != null && name.equals(FORM_NUMBER)) { formparas.add(new BasicNameValuePair(name, this.getNumberPart(number))); } else if (name != null && name.equals(FORM_TEXT)) { formparas.add(new BasicNameValuePair(name, text)); } else if (name != null && name.equals(FORM_AGB)) { formparas.add(new BasicNameValuePair(name, "true")); } } formparas.add(new BasicNameValuePair("dialing_code", this.getPrefixPart(number))); formparas.add(new BasicNameValuePair("no_schedule", "yes")); List<Element> captchas = ref.selectByXPathOnDocument(doc, "//<ns>IMG[@id='code_img']", doc.getRootElement().getNamespaceURI()); Element captcha = captchas.get(0); String url = "http://www.smsbilliger.de/" + captcha.getAttributeValue("src"); HttpGet imgcall = new HttpGet(url); HttpResponse imgres = client.execute(imgcall); HttpEntity imge = imgres.getEntity(); BufferedImage img = ImageIO.read(imge.getContent()); imge.getContent().close(); Icon icon = new ImageIcon(img); String result = (String) JOptionPane.showInputDialog(null, "Bitte Captcha eingeben:", "Captcha", JOptionPane.INFORMATION_MESSAGE, icon, null, ""); formparas.add(new BasicNameValuePair(FORM_CAPTCHA, result)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparas, "UTF-8"); HttpPost post = new HttpPost(target); post.setEntity(entity); response = client.execute(post); e = response.getEntity(); doc = ref.getDocumentFromInputStream(e.getContent()); List<Element> fonts = ref.selectByXPathOnDocument(doc, "//<ns>H3", doc.getRootElement().getNamespaceURI()); Iterator<Element> it2 = fonts.iterator(); while (it2.hasNext()) { Element font = it2.next(); String txt = font.getText(); if (txt.contains("Die SMS wurde erfolgreich versendet.")) { return new Result(Result.SMS_SEND); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } return new Result(Result.UNKNOWN_ERROR); } |
00
| Code Sample 1:
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()); } }
Code Sample 2:
public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { InputStream inputStream = url.openStream(); try { return getAudioInputStream(inputStream); } catch (UnsupportedAudioFileException e) { inputStream.close(); throw e; } catch (IOException e) { inputStream.close(); throw e; } } |
00
| Code Sample 1:
@Override public String fetchElectronicEdition(Publication pub) { final String url = pub.getEe(); HttpMethod method = null; String responseBody = ""; method = new GetMethod(url); method.setFollowRedirects(true); try { if (StringUtils.isNotBlank(method.getURI().getScheme())) { InputStream is = null; StringWriter writer = new StringWriter(); try { client.executeMethod(method); Header contentType = method.getResponseHeader("Content-Type"); if (contentType != null && StringUtils.isNotBlank(contentType.getValue()) && contentType.getValue().indexOf("text/html") >= 0) { is = method.getResponseBodyAsStream(); IOUtils.copy(is, writer); responseBody = writer.toString(); } else { logger.info("ignoring non-text/html response from page: " + url + " content-type:" + contentType); } } catch (HttpException he) { logger.error("Http error connecting to '" + url + "'"); logger.error(he.getMessage()); } catch (IOException ioe) { logger.error("Unable to connect to '" + url + "'"); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(writer); } } } catch (URIException e) { logger.error(e); } finally { method.releaseConnection(); } return responseBody; }
Code Sample 2:
@Override public void handlePeerEvent(PeerEvent event) { if (event.geteventInfo() instanceof EventServiceInfo) { EventServiceInfo info = (EventServiceInfo) event.geteventInfo(); if (info.getServiceState() != ServiceState.Deployed) return; long bid = info.getBundleId(); Bundle bundle = context.getBundle(bid); Enumeration entries = bundle.findEntries("OSGI-INF/PrivacyPolicy/", "*.xml", true); if (entries != null) { if (entries.hasMoreElements()) { try { URL url = (URL) entries.nextElement(); BufferedInputStream in = new BufferedInputStream(url.openStream()); XMLPolicyReader reader = new XMLPolicyReader(this.context); RequestPolicy policy = reader.readPolicyFromFile(in); if (policy != null) { this.policyMgr.addPrivacyPolicyForService(info.getServiceID(), policy); } } catch (IOException ioe) { } } } } } |
00
| Code Sample 1:
public static GCalendar getNewestCalendar(Calendar startDate) throws IOException { GCalendar hoge = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpClient http = new DefaultHttpClient(); HttpGet method = new HttpGet("http://localhost:8080/GoogleCalendar/select"); HttpResponse response = http.execute(method); String jsonstr = response.getEntity().toString(); System.out.println("jsonstr = " + jsonstr); hoge = JSON.decode(jsonstr, GCalendar.class); } catch (Exception ex) { ex.printStackTrace(); } return hoge; }
Code Sample 2:
public Document parse(InputSource is) throws SAXException, IOException { LSInput input = ls.createLSInput(); String systemId = is.getSystemId(); InputStream in = is.getByteStream(); if (in != null) { input.setByteStream(in); } else { Reader reader = is.getCharacterStream(); if (reader != null) { input.setCharacterStream(reader); } else { URL url = new URL(systemId); input.setByteStream(url.openStream()); } } input.setPublicId(is.getPublicId()); input.setSystemId(systemId); input.setEncoding(is.getEncoding()); return parser.parse(input); } |
11
| Code Sample 1:
private String encryptPassword(String password) { String result = password; if (password != null) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); result = hash.toString(16); if ((result.length() % 2) != 0) { result = "0" + result; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); getLogger().error("Cannot generate MD5", e); } } return result; }
Code Sample 2:
public static String getDigest(String seed, byte[] code) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed.getBytes("UTF-8")); byte[] passwordMD5Byte = md.digest(code); StringBuffer sb = new StringBuffer(); for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.error(e); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e); return null; } } |
00
| Code Sample 1:
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; }
Code Sample 2:
private void auth() throws IOException { authorized = false; seqNumber = 0; DatagramSocket ds = new DatagramSocket(); ds.setSoTimeout(UDPHID_DEFAULT_TIMEOUT); ds.connect(addr, port); DatagramPacket p = new DatagramPacket(buffer.array(), buffer.capacity()); for (int i = 0; i < UDPHID_DEFAULT_ATTEMPTS; i++) { buffer.clear(); buffer.put((byte) REQ_CHALLENGE); buffer.put(htons((short) UDPHID_PROTO)); buffer.put(name.getBytes()); ds.send(new DatagramPacket(buffer.array(), buffer.position())); buffer.clear(); try { ds.receive(p); } catch (SocketTimeoutException e) { continue; } switch(buffer.get()) { case ANS_CHALLENGE: break; case ANS_FAILURE: throw new IOException("REQ_FAILURE"); default: throw new IOException("invalid packet"); } byte challenge_id = buffer.get(); int challenge_len = (int) buffer.get(); byte[] challenge = new byte[challenge_len]; buffer.get(challenge, 0, p.getLength() - buffer.position()); byte[] response; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(challenge_id); md.update(password.getBytes(), 0, password.length()); md.update(challenge, 0, challenge.length); response = md.digest(); } catch (NoSuchAlgorithmException e) { throw new IOException("NoSuchAlgorithmException: " + e.toString()); } buffer.clear(); buffer.put((byte) REQ_RESPONSE); buffer.put(challenge_id); buffer.put((byte) response.length); buffer.put(response); buffer.put(login.getBytes()); ds.send(new DatagramPacket(buffer.array(), buffer.position())); buffer.clear(); try { ds.receive(p); } catch (SocketTimeoutException e) { continue; } switch(buffer.get()) { case ANS_SUCCESS: int sidLength = buffer.get(); sid = new byte[sidLength]; buffer.get(sid, 0, sidLength); authorized = true; return; case ANS_FAILURE: throw new IOException("access deny"); default: throw new IOException("invalid packet"); } } throw new IOException("operation time out"); } |
11
| Code Sample 1:
private void execute(String file, String[] ebms, String[] eems, String[] ims, String[] efms) throws BuildException { if (verbose) { System.out.println("Preprocessing file " + file + " (type: " + type + ")"); } try { File targetFile = new File(file); FileReader fr = new FileReader(targetFile); BufferedReader reader = new BufferedReader(fr); File preprocFile = File.createTempFile(targetFile.getName(), "tmp", targetFile.getParentFile()); FileWriter fw = new FileWriter(preprocFile); BufferedWriter writer = new BufferedWriter(fw); int result = preprocess(reader, writer, ebms, eems, ims, efms); reader.close(); writer.close(); switch(result) { case OVERWRITE: if (!targetFile.delete()) { System.out.println("Can't overwrite target file with preprocessed file"); throw new BuildException("Can't overwrite target file " + target + " with preprocessed file"); } preprocFile.renameTo(targetFile); if (verbose) { System.out.println("File " + preprocFile.getName() + " modified."); } modifiedCnt++; break; case REMOVE: if (!targetFile.delete()) { System.out.println("Can't delete target file"); throw new BuildException("Can't delete target file " + target); } if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } if (verbose) { System.out.println("File " + preprocFile.getName() + " removed."); } removedCnt++; break; case KEEP: if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } break; default: throw new BuildException("Unexpected preprocessing result for file " + preprocFile.getName()); } } catch (Exception e) { e.printStackTrace(); throw new BuildException(e.getMessage()); } }
Code Sample 2:
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(); } } |
11
| Code Sample 1:
public static String getTextFromPart(Part part) { try { if (part != null && part.getBody() != null) { InputStream in = part.getBody().getInputStream(); String mimeType = part.getMimeType(); if (mimeType != null && MimeUtility.mimeTypeMatches(mimeType, "text/*")) { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); in = null; String charset = getHeaderParameter(part.getContentType(), "charset"); if (charset != null) { charset = CharsetUtil.toJavaCharset(charset); } if (charset == null) { charset = "ASCII"; } String result = out.toString(charset); out.close(); return result; } } } catch (OutOfMemoryError oom) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + oom.toString()); } catch (Exception e) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + e.toString()); } return null; }
Code Sample 2:
private byte[] digestFile(File file, MessageDigest digest) throws IOException { DigestInputStream in = new DigestInputStream(new FileInputStream(file), digest); IOUtils.copy(in, new NullOutputStream()); in.close(); return in.getMessageDigest().digest(); } |
00
| Code Sample 1:
protected static JXStatusBar getStatusBar(final JXPanel jxPanel, final JTabbedPane mainTabbedPane) { JXStatusBar statusBar = new JXStatusBar(); try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Enumeration<URL> urls = cl.getResources("META-INF/MANIFEST.MF"); String substanceVer = null; String substanceBuildStamp = null; while (urls.hasMoreElements()) { InputStream is = urls.nextElement().openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); while (true) { String line = br.readLine(); if (line == null) break; int firstColonIndex = line.indexOf(":"); if (firstColonIndex < 0) continue; String name = line.substring(0, firstColonIndex).trim(); String val = line.substring(firstColonIndex + 1).trim(); if (name.compareTo("Substance-Version") == 0) substanceVer = val; if (name.compareTo("Substance-BuildStamp") == 0) substanceBuildStamp = val; } try { br.close(); } catch (IOException ioe) { } } if (substanceVer != null) { JLabel statusLabel = new JLabel(substanceVer + " [built on " + substanceBuildStamp + "]"); JXStatusBar.Constraint cStatusLabel = new JXStatusBar.Constraint(); cStatusLabel.setFixedWidth(300); statusBar.add(statusLabel, cStatusLabel); } } catch (IOException ioe) { } JXStatusBar.Constraint c2 = new JXStatusBar.Constraint(JXStatusBar.Constraint.ResizeBehavior.FILL); final JLabel tabLabel = new JLabel(""); statusBar.add(tabLabel, c2); mainTabbedPane.getModel().addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { int selectedIndex = mainTabbedPane.getSelectedIndex(); if (selectedIndex < 0) tabLabel.setText("No selected tab"); else tabLabel.setText("Tab " + mainTabbedPane.getTitleAt(selectedIndex) + " selected"); } }); JPanel fontSizePanel = FontSizePanel.getPanel(); JXStatusBar.Constraint fontSizePanelConstraints = new JXStatusBar.Constraint(); fontSizePanelConstraints.setFixedWidth(270); statusBar.add(fontSizePanel, fontSizePanelConstraints); JPanel alphaPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0)); final JLabel alphaLabel = new JLabel("100%"); final JSlider alphaSlider = new JSlider(0, 100, 100); alphaSlider.setFocusable(false); alphaSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { int currValue = alphaSlider.getValue(); alphaLabel.setText(currValue + "%"); jxPanel.setAlpha(currValue / 100.0f); } }); alphaSlider.setToolTipText("Changes the global opacity. Is not Substance-specific"); alphaSlider.setPreferredSize(new Dimension(120, alphaSlider.getPreferredSize().height)); alphaPanel.add(alphaLabel); alphaPanel.add(alphaSlider); JXStatusBar.Constraint alphaPanelConstraints = new JXStatusBar.Constraint(); alphaPanelConstraints.setFixedWidth(160); statusBar.add(alphaPanel, alphaPanelConstraints); return statusBar; }
Code Sample 2:
public String[] getFile() { List<String> records = new ArrayList<String>(); FTPClient ftp = new FTPClient(); try { int reply; FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); ftp.configure(conf); ftp.connect(host, port); System.out.println("Connected to " + host + "."); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); } ftp.login(user, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused login."); } InputStream is = ftp.retrieveFileStream(remotedir + "/" + remotefile); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { if (!line.equals("")) { records.add(line); } } br.close(); isr.close(); is.close(); ftp.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); } } } return records.toArray(new String[0]); } |
00
| Code Sample 1:
@Test public void testPersistor() throws Exception { PreparedStatement ps; ps = connection.prepareStatement("delete from privatadresse"); ps.executeUpdate(); ps.close(); ps = connection.prepareStatement("delete from adresse"); ps.executeUpdate(); ps.close(); ps = connection.prepareStatement("delete from person"); ps.executeUpdate(); ps.close(); Persistor p; Adresse csd = new LieferAdresse(); csd.setStrasse("Amalienstrasse 68"); modificationTracker.addNewParticipant(csd); Person markus = new Person(); markus.setName("markus"); modificationTracker.addNewParticipant(markus); markus.getPrivatAdressen().add(csd); Person martin = new Person(); martin.setName("martin"); modificationTracker.addNewParticipant(martin); p = new Persistor(getSchemaMapping(), idGenerator, modificationTracker); p.persist(); Adresse bia = new LieferAdresse(); modificationTracker.addNewParticipant(bia); bia.setStrasse("dr. boehringer gasse"); markus.getAdressen().add(bia); bia.setPerson(martin); markus.setContactPerson(martin); p = new Persistor(getSchemaMapping(), idGenerator, modificationTracker); try { p.persist(); connection.commit(); } catch (Exception e) { connection.rollback(); throw e; } }
Code Sample 2:
private boolean canReadSource(String fileURL) { URL url; try { url = new URL(fileURL); } catch (MalformedURLException e) { log.error("Error accessing URL " + fileURL + "."); return false; } InputStream is; try { is = url.openStream(); } catch (IOException e) { log.error("Error creating Input Stream from URL '" + fileURL + "'."); return false; } return true; } |
00
| Code Sample 1:
public static InputStream getInputStream(URL url) throws IOException { if (url.getProtocol().equals("file")) { String path = decode(url.getPath(), "UTF-8"); return new BufferedInputStream(new FileInputStream(path)); } else { return new BufferedInputStream(url.openStream()); } }
Code Sample 2:
private static String GetSHA1(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 LoginHttpPostProcessor.ConvertToHex(sha1hash); } |
11
| Code Sample 1:
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String fileName = request.getParameter("tegsoftFileName"); if (fileName.startsWith("Tegsoft_BACKUP_")) { fileName = fileName.substring("Tegsoft_BACKUP_".length()); String targetFileName = "/home/customer/" + fileName; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (fileName.equals("Tegsoft_ASTMODULES")) { String targetFileName = tobeHome + "/setup/Tegsoft_ASTMODULES.tgz"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (fileName.equals("Tegsoft_ASTSBIN")) { String targetFileName = tobeHome + "/setup/Tegsoft_ASTSBIN.tgz"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (!fileName.startsWith("Tegsoft_")) { return; } if (!fileName.endsWith(".zip")) { return; } if (fileName.indexOf("_") < 0) { return; } fileName = fileName.substring(fileName.indexOf("_") + 1); if (fileName.indexOf("_") < 0) { return; } String fileType = fileName.substring(0, fileName.indexOf("_")); String destinationFileName = tobeHome + "/setup/Tegsoft_" + fileName; if (!new File(destinationFileName).exists()) { if ("FORMS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/forms", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("IMAGES".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/image", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("VIDEOS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/videos", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("TEGSOFTJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName, "Tegsoft", "jar"); } else if ("TOBEJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName, "Tobe", "jar"); } else if ("ALLJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("DB".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/sql", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("CONFIGSERVICE".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/init.d/", tobeHome + "/setup/Tegsoft_" + fileName, "tegsoft", null); } else if ("CONFIGSCRIPTS".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/root/", tobeHome + "/setup/Tegsoft_" + fileName, "tegsoft", null); } else if ("CONFIGFOP".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/fop/", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("CONFIGASTERISK".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/asterisk/", tobeHome + "/setup/Tegsoft_" + fileName); } } response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(destinationFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); } catch (Exception ex) { ex.printStackTrace(); } }
Code Sample 2:
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; } |
11
| Code Sample 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(); } }
Code Sample 2:
protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { LOG.debug("copying file"); String tTempFileName = this.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tTempFileName)); Datastream tDatastream = new LocalDatastream(this.getGenericFileName(pDeposit), this.getContentType(), tTempFileName); List<Datastream> tDatastreams = new ArrayList<Datastream>(); tDatastreams.add(tDatastream); return tDatastreams; } |
00
| Code Sample 1:
@Override protected String doInBackground(Location... params) { if (params == null || params.length == 0 || params[0] == null) { return null; } Location location = params[0]; String address = ""; String cachedAddress = DataService.GetInstance(mContext).getAddressFormLocationCache(location.getLatitude(), location.getLongitude()); if (!TextUtils.isEmpty(cachedAddress)) { address = cachedAddress; } else { StringBuilder jsonText = new StringBuilder(); HttpClient client = new DefaultHttpClient(); String url = String.format(GoogleMapAPITemplate, location.getLatitude(), location.getLongitude()); HttpGet httpGet = new HttpGet(url); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { jsonText.append(line); } JSONObject result = new JSONObject(jsonText.toString()); String status = result.getString(GoogleMapStatusSchema.status); if (GoogleMapStatusCodes.OK.equals(status)) { JSONArray addresses = result.getJSONArray(GoogleMapStatusSchema.results); if (addresses.length() > 0) { address = addresses.getJSONObject(0).getString(GoogleMapStatusSchema.formatted_address); if (!TextUtils.isEmpty(currentBestLocationAddress)) { DataService.GetInstance(mContext).updateAddressToLocationCache(location.getLatitude(), location.getLongitude(), currentBestLocationAddress); } } } } else { Log.e("Error", "Failed to get address via google map API."); } } catch (ClientProtocolException e) { e.printStackTrace(); Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } catch (JSONException e) { Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } } return address; }
Code Sample 2:
private void readHomePage(ITestThread testThread) throws IOException { if (null == testThread) { throw new IllegalArgumentException("Test thread may not be null."); } final InputStream urlIn = new URL(testUrl).openStream(); final int availableBytes = urlIn.available(); if (0 == availableBytes) { throw new IllegalStateException("Zero bytes on target host."); } in = new BufferedReader(new InputStreamReader(urlIn)); String line; while (null != in && null != (line = in.readLine())) { page.append(line); page.append('\n'); if (0 != lineDelay) { OS.sleep(lineDelay); } if (testThread.isActionStopped()) { break; } } } |
11
| Code Sample 1:
public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String CFDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = movieAverages.get(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else { finalPrediction = movieAverages.get(movieToProcess); System.out.println("NaN Prediction"); } buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
Code Sample 2:
public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException { int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte(); if (startByte >= 0) { FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(startByte); fc.read(bb); FileOutputStream out = new FileOutputStream(outputFile); out.write(bb.array()); out.close(); fc.close(); fis.close(); return outputFile; } throw new TagNotFoundException("There is no ID3v2Tag data in this file"); } |
11
| Code Sample 1:
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(); }
Code Sample 2:
@Override public void download(String remoteFilePath, String localFilePath) { InputStream remoteStream = null; try { remoteStream = client.get(remoteFilePath); } catch (IOException e) { e.printStackTrace(); } OutputStream localStream = null; try { localStream = new FileOutputStream(new File(localFilePath)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { IOUtils.copy(remoteStream, localStream); } catch (IOException e) { e.printStackTrace(); } } |
11
| Code Sample 1:
private static long saveAndClosePDFDocument(PDDocument document, OutputStreamProvider outProvider) throws IOException, COSVisitorException { File tempFile = null; InputStream in = null; OutputStream out = null; try { tempFile = File.createTempFile("temp", "pdf"); OutputStream tempFileOut = new FileOutputStream(tempFile); tempFileOut = new BufferedOutputStream(tempFileOut); document.save(tempFileOut); document.close(); tempFileOut.close(); long length = tempFile.length(); in = new BufferedInputStream(new FileInputStream(tempFile)); out = new BufferedOutputStream(outProvider.getOutputStream()); IOUtils.copy(in, out); return length; } finally { if (in != null) { IOUtils.closeQuietly(in); } if (out != null) { IOUtils.closeQuietly(out); } if (tempFile != null && !FileUtils.deleteQuietly(tempFile)) { tempFile.deleteOnExit(); } } }
Code Sample 2:
private void writeJar() { try { File outJar = new File(currentProjectDir + DEPLOYDIR + fileSeparator + currentProjectName + ".jar"); jarSize = (int) outJar.length(); File tempJar = File.createTempFile("hipergps" + currentProjectName, ".jar"); tempJar.deleteOnExit(); File preJar = new File(currentProjectDir + "/res/wtj2me.jar"); JarInputStream preJarInStream = new JarInputStream(new FileInputStream(preJar)); Manifest mFest = preJarInStream.getManifest(); java.util.jar.Attributes atts = mFest.getMainAttributes(); if (hiperGeoId != null) { atts.putValue("hiperGeoId", hiperGeoId); } jad.updateAttributes(atts); JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(tempJar), mFest); byte[] buffer = new byte[WalkingtoolsInformation.BUFFERSIZE]; JarEntry jarEntry = null; while ((jarEntry = preJarInStream.getNextJarEntry()) != null) { if (jarEntry.getName().contains("net/") || jarEntry.getName().contains("org/")) { try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } int read; while ((read = preJarInStream.read(buffer)) != -1) { jarOutStream.write(buffer, 0, read); } jarOutStream.closeEntry(); } } File[] icons = { new File(currentProjectDir + WalkingtoolsInformation.IMAGEDIR + fileSeparator + "icon_" + WalkingtoolsInformation.MEDIAUUID + ".png"), new File(currentProjectDir + WalkingtoolsInformation.IMAGEDIR + fileSeparator + "loaderIcon_" + WalkingtoolsInformation.MEDIAUUID + ".png"), new File(currentProjectDir + WalkingtoolsInformation.IMAGEDIR + fileSeparator + "mygps_" + WalkingtoolsInformation.MEDIAUUID + ".png") }; for (int i = 0; i < icons.length; i++) { jarEntry = new JarEntry("img/" + icons[i].getName()); try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } FileInputStream in = new FileInputStream(icons[i]); while (true) { int read = in.read(buffer, 0, buffer.length); if (read <= 0) { break; } jarOutStream.write(buffer, 0, read); } in.close(); } for (int i = 0; i < imageFiles.size(); i++) { jarEntry = new JarEntry("img/" + imageFiles.get(i).getName()); try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } FileInputStream in = new FileInputStream(imageFiles.get(i)); while (true) { int read = in.read(buffer, 0, buffer.length); if (read <= 0) { break; } jarOutStream.write(buffer, 0, read); } in.close(); } for (int i = 0; i < audioFiles.size(); i++) { jarEntry = new JarEntry("audio/" + audioFiles.get(i).getName()); try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } FileInputStream in = new FileInputStream(audioFiles.get(i)); while (true) { int read = in.read(buffer, 0, buffer.length); if (read <= 0) { break; } jarOutStream.write(buffer, 0, read); } in.close(); } File gpx = new File(currentProjectDir + WalkingtoolsInformation.GPXDIR + "/hipergps.gpx"); jarEntry = new JarEntry("gpx/" + gpx.getName()); jarOutStream.putNextEntry(jarEntry); FileInputStream in = new FileInputStream(gpx); while (true) { int read = in.read(buffer, 0, buffer.length); if (read <= 0) { break; } jarOutStream.write(buffer, 0, read); } in.close(); jarOutStream.flush(); jarOutStream.close(); jarSize = (int) tempJar.length(); preJarInStream = new JarInputStream(new FileInputStream(tempJar)); mFest = preJarInStream.getManifest(); atts = mFest.getMainAttributes(); atts.putValue("MIDlet-Jar-Size", "" + jarSize + 1); jarOutStream = new JarOutputStream(new FileOutputStream(outJar), mFest); while ((jarEntry = preJarInStream.getNextJarEntry()) != null) { try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } int read; while ((read = preJarInStream.read(buffer)) != -1) { jarOutStream.write(buffer, 0, read); } jarOutStream.closeEntry(); } jarOutStream.flush(); preJarInStream.close(); jarOutStream.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } |
11
| Code Sample 1:
public static int fileCopy(String strSourceFilePath, String strDestinationFilePath, String strFileName) throws IOException { String SEPARATOR = System.getProperty("file.separator"); File dir = new File(strSourceFilePath); if (!dir.exists()) dir.mkdirs(); File realDir = new File(strDestinationFilePath); if (!realDir.exists()) realDir.mkdirs(); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(new File(strSourceFilePath + SEPARATOR + strFileName)); fos = new FileOutputStream(new File(strDestinationFilePath + SEPARATOR + strFileName)); IOUtils.copy(fis, fos); } catch (Exception ex) { return -1; } finally { try { fos.close(); fis.close(); } catch (Exception ex2) { } } return 0; }
Code Sample 2:
private void zip(String object, TupleOutput output) { byte array[] = object.getBytes(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream out = new GZIPOutputStream(baos); ByteArrayInputStream in = new ByteArrayInputStream(array); IOUtils.copyTo(in, out); in.close(); out.close(); byte array2[] = baos.toByteArray(); if (array2.length + 4 < array.length) { output.writeBoolean(true); output.writeInt(array2.length); output.write(array2); } else { output.writeBoolean(false); output.writeString(object); } } catch (IOException err) { throw new RuntimeException(err); } } |
11
| Code Sample 1:
private void copyResources(File oggDecDir, String[] resources, String resPrefix) throws FileNotFoundException, IOException { for (int i = 0; i < resources.length; i++) { String res = resPrefix + resources[i]; InputStream is = this.getClass().getResourceAsStream(res); if (is == null) throw new IllegalArgumentException("cannot find resource '" + res + "'"); File file = new File(oggDecDir, resources[i]); if (!file.exists() || file.length() == 0) { FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copyStreams(is, fos); } finally { fos.close(); } } } }
Code Sample 2:
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; } |
00
| Code Sample 1:
public static void doHttpPost(String urlName, byte[] data, String contentType, String cookieData) throws InteropException { URL url = getAccessURL(urlName); try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Cookie", cookieData); connection.setRequestProperty("Content-type", contentType); connection.setRequestProperty("Content-length", "" + data.length); OutputStream stream = connection.getOutputStream(); stream.write(data); stream.flush(); stream.close(); connection.connect(); InputStream inputStream = connection.getInputStream(); inputStream.close(); } catch (IOException ex) { throw new InteropException("Error POSTing to " + urlName, ex); } }
Code Sample 2:
public ActionForward dbExecute(ActionMapping pMapping, ActionForm pForm, HttpServletRequest pRequest, HttpServletResponse pResponse) throws DatabaseException { SubmitRegistrationForm newUserData = (SubmitRegistrationForm) pForm; if (!newUserData.getAcceptsEULA()) { pRequest.setAttribute("acceptsEULA", new Boolean(true)); pRequest.setAttribute("noEula", new Boolean(true)); return (pMapping.findForward("noeula")); } if (newUserData.getAction().equals("none")) { newUserData.setAction("submit"); pRequest.setAttribute("UserdataBad", new Boolean(true)); return (pMapping.findForward("success")); } boolean userDataIsOk = true; if (newUserData == null) { return (pMapping.findForward("failure")); } if (newUserData.getLastName().length() < 2) { userDataIsOk = false; pRequest.setAttribute("LastNameBad", new Boolean(true)); } if (newUserData.getFirstName().length() < 2) { userDataIsOk = false; pRequest.setAttribute("FirstNameBad", new Boolean(true)); } EmailValidator emailValidator = EmailValidator.getInstance(); if (!emailValidator.isValid(newUserData.getEmailAddress())) { pRequest.setAttribute("EmailBad", new Boolean(true)); userDataIsOk = false; } else { if (database.acquireUserByEmail(newUserData.getEmailAddress()) != null) { pRequest.setAttribute("EmailDouble", new Boolean(true)); userDataIsOk = false; } } if (newUserData.getFirstPassword().length() < 5) { userDataIsOk = false; pRequest.setAttribute("FirstPasswordBad", new Boolean(true)); } if (newUserData.getSecondPassword().length() < 5) { userDataIsOk = false; pRequest.setAttribute("SecondPasswordBad", new Boolean(true)); } if (!newUserData.getSecondPassword().equals(newUserData.getFirstPassword())) { userDataIsOk = false; pRequest.setAttribute("PasswordsNotEqual", new Boolean(true)); } if (userDataIsOk) { User newUser = new User(); newUser.setFirstName(newUserData.getFirstName()); newUser.setLastName(newUserData.getLastName()); if (!newUserData.getFirstPassword().equals("")) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new DatabaseException("Could not hash password for storage: no such algorithm"); } try { md.update(newUserData.getFirstPassword().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new DatabaseException("Could not hash password for storage: no such encoding"); } newUser.setPassword((new BASE64Encoder()).encode(md.digest())); } newUser.setEmailAddress(newUserData.getEmailAddress()); newUser.setHomepage(newUserData.getHomepage()); newUser.setAddress(newUserData.getAddress()); newUser.setInstitution(newUserData.getInstitution()); newUser.setLanguages(newUserData.getLanguages()); newUser.setDegree(newUserData.getDegree()); newUser.setNationality(newUserData.getNationality()); newUser.setTitle(newUserData.getTitle()); newUser.setActive(true); try { database.updateUser(newUser); } catch (DatabaseException e) { pRequest.setAttribute("UserstoreBad", new Boolean(true)); return (pMapping.findForward("success")); } pRequest.setAttribute("UserdataFine", new Boolean(true)); } else { pRequest.setAttribute("UserdataBad", new Boolean(true)); } return (pMapping.findForward("success")); } |
00
| Code Sample 1:
public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Usage: java SOAPClient4XG " + "http://soapURL soapEnvelopefile.xml" + " [SOAPAction]"); System.err.println("SOAPAction is optional."); System.exit(1); } String SOAPUrl = args[0]; String xmlFile2Send = args[1]; String SOAPAction = ""; if (args.length > 2) SOAPAction = args[2]; URL url = new URL(SOAPUrl); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; FileInputStream fin = new FileInputStream(xmlFile2Send); ByteArrayOutputStream bout = new ByteArrayOutputStream(); copy(fin, bout); fin.close(); byte[] b = bout.toByteArray(); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); httpConn.setRequestProperty("SOAPAction", SOAPAction); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); }
Code Sample 2:
public void testJDBCSavepoints() throws Exception { String sql; String msg; int i; PreparedStatement ps; ResultSet rs; Savepoint sp1; Savepoint sp2; Savepoint sp3; Savepoint sp4; Savepoint sp5; Savepoint sp6; Savepoint sp7; int rowcount = 0; sql = "drop table t if exists"; stmt.executeUpdate(sql); sql = "create table t(id int, fn varchar, ln varchar, zip int)"; stmt.executeUpdate(sql); conn1.setAutoCommit(true); conn1.setAutoCommit(false); sql = "insert into t values(?,?,?,?)"; ps = conn1.prepareStatement(sql); ps.setString(2, "Mary"); ps.setString(3, "Peterson-Clancy"); i = 0; for (; i < 10; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp1 = conn1.setSavepoint("savepoint1"); for (; i < 20; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp2 = conn1.setSavepoint("savepoint2"); for (; i < 30; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp3 = conn1.setSavepoint("savepoint3"); for (; i < 40; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp4 = conn1.setSavepoint("savepoint4"); for (; i < 50; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp5 = conn1.setSavepoint("savepoint5"); sp6 = conn1.setSavepoint("savepoint6"); sp7 = conn1.setSavepoint("savepoint7"); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select count(*) from t value"; try { assertEquals(msg, 50, rowcount); } catch (Exception e) { } conn2.setAutoCommit(false); conn2.setSavepoint("savepoint1"); conn2.setSavepoint("savepoint2"); msg = "savepoint released succesfully on non-originating connection"; try { conn2.releaseSavepoint(sp2); assertTrue(msg, false); } catch (Exception e) { } try { conn2.rollback(sp1); msg = "succesful rollback to savepoint on " + "non-originating connection"; assertTrue(msg, false); } catch (Exception e) { } msg = "direct execution of <release savepoint> statement failed to " + "release JDBC-created SQL-savepoint with identical savepoint name"; try { conn2.createStatement().executeUpdate("release savepoint \"savepoint2\""); } catch (Exception e) { try { assertTrue(msg, false); } catch (Exception e2) { } } msg = "direct execution of <rollback to savepoint> statement failed to " + "roll back to existing JDBC-created SQL-savepoint with identical " + "savepoint name"; try { conn2.createStatement().executeUpdate("rollback to savepoint \"savepoint1\""); } catch (Exception e) { e.printStackTrace(); try { assertTrue(msg, false); } catch (Exception e2) { } } conn1.releaseSavepoint(sp6); msg = "savepoint released succesfully > 1 times"; try { conn1.releaseSavepoint(sp6); assertTrue(msg, false); } catch (Exception e) { } msg = "savepoint released successfully after preceding savepoint released"; try { conn1.releaseSavepoint(sp7); assertTrue(msg, false); } catch (Exception e) { } msg = "preceding same-point savepoint destroyed by following savepoint release"; try { conn1.releaseSavepoint(sp5); } catch (Exception e) { try { assertTrue(msg, false); } catch (Exception e2) { } } conn1.rollback(sp4); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select * rowcount after 50 inserts - 10 rolled back:"; try { assertEquals(msg, 40, rowcount); } catch (Exception e) { } msg = "savepoint rolled back succesfully > 1 times"; try { conn1.rollback(sp4); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(sp3); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select count(*) after 50 inserts - 20 rolled back:"; try { assertEquals(msg, 30, rowcount); } catch (Exception e) { } msg = "savepoint released succesfully after use in rollback"; try { conn1.releaseSavepoint(sp3); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(sp1); msg = "savepoint rolled back without raising an exception after " + "rollback to a preceeding savepoint"; try { conn1.rollback(sp2); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(); msg = "savepoint released succesfully when it should have been " + "destroyed by a full rollback"; try { conn1.releaseSavepoint(sp1); assertTrue(msg, false); } catch (Exception e) { } conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.rollback(); conn1.setAutoCommit(false); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); } |
11
| Code Sample 1:
private static void extract(ZipFile zipFile) throws Exception { FileUtils.deleteQuietly(WEBKIT_DIR); WEBKIT_DIR.mkdirs(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { new File(WEBKIT_DIR, entry.getName()).mkdirs(); continue; } InputStream inputStream = zipFile.getInputStream(entry); File outputFile = new File(WEBKIT_DIR, entry.getName()); FileOutputStream outputStream = new FileOutputStream(outputFile); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } }
Code Sample 2:
public void readPersistentProperties() { try { String file = System.getProperty("user.home") + System.getProperty("file.separator") + ".das2rc"; File f = new File(file); if (f.canRead()) { try { InputStream in = new FileInputStream(f); load(in); in.close(); } catch (IOException e) { e.printStackTrace(); org.das2.util.DasExceptionHandler.handle(e); } } else { if (!f.exists() && f.canWrite()) { try { OutputStream out = new FileOutputStream(f); store(out, ""); out.close(); } catch (IOException e) { e.printStackTrace(); org.das2.util.DasExceptionHandler.handle(e); } } else { System.err.println("Unable to read or write " + file + ". Using defaults."); } } } catch (SecurityException ex) { ex.printStackTrace(); } } |
00
| Code Sample 1:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { if ((this.jTree2.getSelectionPath() == null) || !(this.jTree2.getSelectionPath().getLastPathComponent() instanceof StyleTreeNode)) { Msg.showMsg("Devi selezionare lo stile sotto il quale caricare la ricetta!", this); return; } if ((this.txtUser.getText() == null) || (this.txtUser.getText().length() == 0)) { Msg.showMsg("Il nome utente è obbligatorio!", this); return; } if ((this.txtPwd.getPassword() == null) || (this.txtPwd.getPassword().length == 0)) { Msg.showMsg("La password è obbligatoria!", this); return; } this.nomeRicetta = this.txtNome.getText(); if ((this.nomeRicetta == null) || (this.nomeRicetta.length() == 0)) { Msg.showMsg("Il nome della ricetta è obbligatorio!", this); return; } StyleTreeNode node = null; if (this.jTree2.getSelectionPath().getLastPathComponent() instanceof StyleTreeNode) { node = (StyleTreeNode) this.jTree2.getSelectionPath().getLastPathComponent(); } try { String data = URLEncoder.encode("nick", "UTF-8") + "=" + URLEncoder.encode(this.txtUser.getText(), "UTF-8"); data += "&" + URLEncoder.encode("pwd", "UTF-8") + "=" + URLEncoder.encode(new String(this.txtPwd.getPassword()), "UTF-8"); data += "&" + URLEncoder.encode("id_stile", "UTF-8") + "=" + URLEncoder.encode(node.getIdStile(), "UTF-8"); data += "&" + URLEncoder.encode("nome_ricetta", "UTF-8") + "=" + URLEncoder.encode(this.nomeRicetta, "UTF-8"); data += "&" + URLEncoder.encode("xml_ricetta", "UTF-8") + "=" + URLEncoder.encode(this.xml, "UTF-8"); URL url = new URL("http://" + Main.config.getRemoteServer() + "/upload_ricetta.asp?" + data); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; String str = ""; while ((line = rd.readLine()) != null) { str += line; } rd.close(); Msg.showMsg(str, this); doDefaultCloseAction(); } catch (Exception e) { Utils.showException(e, "Errore in upload", this); } reloadTree(); }
Code Sample 2:
@Test public void testWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } } |
00
| Code Sample 1:
private static boolean initLOG4JProperties(String homeDir) { String Log4jURL = homeDir + LOG4J_URL; try { URL log4jurl = getURL(Log4jURL); InputStream inStreamLog4j = log4jurl.openStream(); Properties propertiesLog4j = new Properties(); try { propertiesLog4j.load(inStreamLog4j); PropertyConfigurator.configure(propertiesLog4j); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { logger.info("Failed to initialize LOG4J with properties file."); return false; } return true; }
Code Sample 2:
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(); } |
11
| Code Sample 1:
public static String md5(String s) { try { MessageDigest digester = MessageDigest.getInstance("MD5"); digester.update(s.getBytes()); return new BigInteger(1, digester.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
Code Sample 2:
private boolean verifyPassword(String password, byte[] hash) { boolean returnValue = false; try { MessageDigest msgDigest = MessageDigest.getInstance("SHA-1"); msgDigest.update(password.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); returnValue = Arrays.equals(hash, digest); } catch (UnsupportedEncodingException ex) { Logger.getLogger(AuthentificationState.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AuthentificationState.class.getName()).log(Level.SEVERE, null, ex); } return returnValue; } |
11
| Code Sample 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); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
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(); } } |
11
| Code Sample 1:
public static void main(String[] args) { paraProc(args); CanonicalGFF cgff = new CanonicalGFF(gffFilename); CanonicalGFF geneModel = new CanonicalGFF(modelFilename); CanonicalGFF transcriptGff = new CanonicalGFF(transcriptFilename); TreeMap ksTable1 = getKsTable(ksTable1Filename); TreeMap ksTable2 = getKsTable(ksTable2Filename); Map intronReadCntMap = new TreeMap(); Map intronSplicingPosMap = new TreeMap(); try { BufferedReader fr = new BufferedReader(new FileReader(inFilename)); while (fr.ready()) { String line = fr.readLine(); if (line.startsWith("#")) continue; String tokens[] = line.split("\t"); String chr = tokens[0]; int start = Integer.parseInt(tokens[1]); int stop = Integer.parseInt(tokens[2]); GenomeInterval intron = new GenomeInterval(chr, start, stop); int readCnt = Integer.parseInt(tokens[3]); intronReadCntMap.put(intron, readCnt); String splicingMapStr = tokens[4]; Map splicingMap = getSplicingMap(splicingMapStr); intronSplicingPosMap.put(intron, splicingMap); } fr.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } double[] hdCDF = getHdCdf(readLength, minimumOverlap); try { FileWriter fw = new FileWriter(outFilename); for (Iterator intronIterator = intronReadCntMap.keySet().iterator(); intronIterator.hasNext(); ) { GenomeInterval intron = (GenomeInterval) intronIterator.next(); int readCnt = ((Integer) intronReadCntMap.get(intron)).intValue(); TreeMap splicingMap = (TreeMap) intronSplicingPosMap.get(intron); Object ksInfoArray[] = distributionAccepter((TreeMap) splicingMap.clone(), readCnt, hdCDF, ksTable1, ksTable2); boolean ksAccepted = (Boolean) ksInfoArray[0]; double testK = (Double) ksInfoArray[1]; double standardK1 = (Double) ksInfoArray[2]; double standardK2 = (Double) ksInfoArray[3]; int positionCnt = splicingMap.size(); Object modelInfoArray[] = getModelAgreedSiteCnt(intron, cgff, geneModel, transcriptGff); int modelAgreedSiteCnt = (Integer) modelInfoArray[0]; int maxAgreedTransSiteCnt = (Integer) modelInfoArray[1]; boolean containedBySomeGene = (Boolean) modelInfoArray[2]; int numIntersectingGenes = (Integer) modelInfoArray[3]; int distance = intron.getStop() - intron.getStart(); fw.write(intron.getChr() + ":" + intron.getStart() + ".." + intron.getStop() + "\t" + distance + "\t" + readCnt + "\t" + splicingMap + "\t" + probabilityEvaluation(readLength, distance, readCnt, splicingMap, positionCnt) + "\t" + ksAccepted + "\t" + testK + "\t" + standardK1 + "\t" + standardK2 + "\t" + positionCnt + "\t" + modelAgreedSiteCnt + "\t" + maxAgreedTransSiteCnt + "\t" + containedBySomeGene + "\t" + numIntersectingGenes + "\n"); } fw.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } }
Code Sample 2:
@Override protected final void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (beforeServingFile(req, resp)) { String pathInfo = req.getPathInfo(); Validate.notNull(pathInfo, "the path info is null -> the sevlet should be mapped with /<mapping>/*"); String resurouce = pathInfo.substring(1); if (log.isDebugEnabled()) { log.debug("resource to expose: " + resurouce); } String extension = resurouce.substring(resurouce.lastIndexOf('.') + 1); MimeType mimeType = MimeTypeRegistry.getByExtension(extension); Validate.notNull(mimeType, "no mimetype found for extension: " + extension); if (log.isDebugEnabled()) { log.debug("the mime type to set: " + mimeType.getMimeType()); } File f = new File(mappedFolder, resurouce); Validate.isTrue(f.exists(), "file: " + f + " does not exist"); Validate.isTrue(f.canRead(), "can not read the file: " + f); if (log.isDebugEnabled()) { log.debug("exposing the file: " + f); } resp.setContentType(mimeType.getMimeType()); FileInputStream fis = new FileInputStream(f); ServletOutputStream os = resp.getOutputStream(); IOUtils.copy(fis, os); os.flush(); IOUtils.closeQuietly(fis); IOUtils.closeQuietly(os); } } |
11
| Code Sample 1:
public int create(BusinessObject o) throws DAOException { int insert = 0; int id = 0; Bill bill = (Bill) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_BILL")); pst.setDate(1, new java.sql.Date(bill.getDate().getTime())); pst.setInt(2, bill.getIdAccount()); insert = pst.executeUpdate(); if (insert <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (insert > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select max(id) from bill"); rs.next(); id = rs.getInt(1); connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return id; }
Code Sample 2:
public ProgramProfilingMessageSymbol deleteProfilingMessageSymbol(int id) throws AdaptationException { ProgramProfilingMessageSymbol profilingMessageSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramProfilingMessageSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete program profiling message " + "symbol failed."; log.error(msg); throw new AdaptationException(msg); } profilingMessageSymbol = getProfilingMessageSymbol(resultSet); query = "DELETE FROM ProgramProfilingMessageSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProfilingMessageSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return profilingMessageSymbol; } |
11
| Code Sample 1:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
Code Sample 2:
public static void main(String[] args) throws IOException { String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } } |
00
| Code Sample 1:
public synchronized AbstractBaseObject update(AbstractBaseObject obj) throws ApplicationException { PreparedStatement preStat = null; StringBuffer sqlStat = new StringBuffer(); MailSetting tmpMailSetting = (MailSetting) ((MailSetting) obj).clone(); synchronized (dbConn) { try { int updateCnt = 0; Timestamp currTime = Utility.getCurrentTimestamp(); sqlStat.append("UPDATE MAIL_SETTING "); sqlStat.append("SET USER_RECORD_ID=?, PROFILE_NAME=?, MAIL_SERVER_TYPE=?, DISPLAY_NAME=?, EMAIL_ADDRESS=?, REMEMBER_PWD_FLAG=?, SPA_LOGIN_FLAG=?, INCOMING_SERVER_HOST=?, INCOMING_SERVER_PORT=?, INCOMING_SERVER_LOGIN_NAME=?, INCOMING_SERVER_LOGIN_PWD=?, OUTGOING_SERVER_HOST=?, OUTGOING_SERVER_PORT=?, OUTGOING_SERVER_LOGIN_NAME=?, OUTGOING_SERVER_LOGIN_PWD=?, PARAMETER_1=?, PARAMETER_2=?, PARAMETER_3=?, PARAMETER_4=?, PARAMETER_5=?, UPDATE_COUNT=?, UPDATER_ID=?, UPDATE_DATE=? "); sqlStat.append("WHERE ID=? AND UPDATE_COUNT=? "); preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); setPrepareStatement(preStat, 1, tmpMailSetting.getUserRecordID()); setPrepareStatement(preStat, 2, tmpMailSetting.getProfileName()); setPrepareStatement(preStat, 3, tmpMailSetting.getMailServerType()); setPrepareStatement(preStat, 4, tmpMailSetting.getDisplayName()); setPrepareStatement(preStat, 5, tmpMailSetting.getEmailAddress()); setPrepareStatement(preStat, 6, tmpMailSetting.getRememberPwdFlag()); setPrepareStatement(preStat, 7, tmpMailSetting.getSpaLoginFlag()); setPrepareStatement(preStat, 8, tmpMailSetting.getIncomingServerHost()); setPrepareStatement(preStat, 9, tmpMailSetting.getIncomingServerPort()); setPrepareStatement(preStat, 10, tmpMailSetting.getIncomingServerLoginName()); setPrepareStatement(preStat, 11, tmpMailSetting.getIncomingServerLoginPwd()); setPrepareStatement(preStat, 12, tmpMailSetting.getOutgoingServerHost()); setPrepareStatement(preStat, 13, tmpMailSetting.getOutgoingServerPort()); setPrepareStatement(preStat, 14, tmpMailSetting.getOutgoingServerLoginName()); setPrepareStatement(preStat, 15, tmpMailSetting.getOutgoingServerLoginPwd()); setPrepareStatement(preStat, 16, tmpMailSetting.getParameter1()); setPrepareStatement(preStat, 17, tmpMailSetting.getParameter2()); setPrepareStatement(preStat, 18, tmpMailSetting.getParameter3()); setPrepareStatement(preStat, 19, tmpMailSetting.getParameter4()); setPrepareStatement(preStat, 20, tmpMailSetting.getParameter5()); setPrepareStatement(preStat, 21, new Integer(tmpMailSetting.getUpdateCount().intValue() + 1)); setPrepareStatement(preStat, 22, sessionContainer.getUserRecordID()); setPrepareStatement(preStat, 23, currTime); setPrepareStatement(preStat, 24, tmpMailSetting.getID()); setPrepareStatement(preStat, 25, tmpMailSetting.getUpdateCount()); updateCnt = preStat.executeUpdate(); dbConn.commit(); if (updateCnt == 0) { throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR); } else { tmpMailSetting.setUpdaterID(sessionContainer.getUserRecordID()); tmpMailSetting.setUpdateDate(currTime); tmpMailSetting.setUpdateCount(new Integer(tmpMailSetting.getUpdateCount().intValue() + 1)); tmpMailSetting.setCreatorName(UserInfoFactory.getUserFullName(tmpMailSetting.getCreatorID())); tmpMailSetting.setUpdaterName(UserInfoFactory.getUserFullName(tmpMailSetting.getUpdaterID())); return (tmpMailSetting); } } catch (Exception e) { try { dbConn.rollback(); } catch (Exception ex) { } log.error(e, e); throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } } }
Code Sample 2:
private static MyCookieData parseCookie(Cookie cookie) throws CookieException { String value = cookie.getValue(); System.out.println("original cookie: " + value); value = value.replace("%3A", ":"); value = value.replace("%40", "@"); System.out.println("cookie after replacement: " + value); String[] parts = value.split(":"); if (parts.length < 4) throw new CookieException("only " + parts.length + " parts in the cookie! " + value); String email = parts[0]; String nickname = parts[1]; boolean admin = Boolean.getBoolean(parts[2].toLowerCase()); String hsh = parts[3]; boolean valid_cookie = true; String cookie_secret = System.getProperty("COOKIE_SECRET"); if (cookie_secret == "") throw new CookieException("cookie secret is not set"); if (email.equals("")) { System.out.println("email is empty!"); nickname = ""; admin = false; } else { try { MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update((email + nickname + admin + cookie_secret).getBytes()); StringBuilder builder = new StringBuilder(); for (byte b : sha.digest()) { byte tmphigh = (byte) (b >> 4); tmphigh = (byte) (tmphigh & 0xf); builder.append(hextab.charAt(tmphigh)); byte tmplow = (byte) (b & 0xf); builder.append(hextab.charAt(tmplow)); } System.out.println(); String vhsh = builder.toString(); if (!vhsh.equals(hsh)) { System.out.println("hash not same!"); System.out.println("hash passed in: " + hsh); System.out.println("hash generated: " + vhsh); valid_cookie = false; } else System.out.println("cookie match!"); } catch (NoSuchAlgorithmException ex) { } } return new MyCookieData(email, admin, nickname, valid_cookie); } |
00
| Code Sample 1:
public static void printResponseHeaders(String address) { logger.info("Address: " + address); try { URL url = new URL(address); URLConnection conn = url.openConnection(); for (int i = 0; ; i++) { String headerName = conn.getHeaderFieldKey(i); String headerValue = conn.getHeaderField(i); if (headerName == null && headerValue == null) { break; } if (headerName == null) { logger.info(headerValue); continue; } logger.info(headerName + " " + headerValue); } } catch (Exception e) { logger.error("Exception Message: " + e.getMessage()); } }
Code Sample 2:
@Override public String decryptString(String passphrase, String crypted) throws Exception { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes("UTF-8")); byte digest[] = md.digest(); String digestString = base64encode(digest); System.out.println(digestString); SecureRandom sr = new SecureRandom(digestString.getBytes()); KeyGenerator kGen = KeyGenerator.getInstance("AES"); kGen.init(128, sr); Key key = kGen.generateKey(); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] cryptString = base64decode(crypted); byte[] bOut = cipher.doFinal(cryptString); String outString = new String(bOut, "UTF-8"); return outString; } |
00
| Code Sample 1:
static ConversionMap create(String file) { ConversionMap out = new ConversionMap(); URL url = ConversionMap.class.getResource("data/" + file); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); while (line != null) { if (line.length() > 0) { String[] arr = line.split("\t"); try { double value = Double.parseDouble(arr[1]); out.put(translate(lowercase(arr[0].getBytes())), value); out.defaultValue += value; out.length = arr[0].length(); } catch (NumberFormatException e) { throw new RuntimeException("Something is wrong with in conversion file: " + e); } } line = in.readLine(); } in.close(); out.defaultValue /= Math.pow(4, out.length); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Their was an error while reading the conversion map: " + e); } return out; }
Code Sample 2:
public ClientDTO changePassword(String pMail, String pMdp) { Client vClientBean = null; ClientDTO vClientDTO = null; vClientBean = mClientDao.getClient(pMail); if (vClientBean != null) { MessageDigest vMd5Instance; try { vMd5Instance = MessageDigest.getInstance("MD5"); vMd5Instance.reset(); vMd5Instance.update(pMdp.getBytes()); byte[] vDigest = vMd5Instance.digest(); BigInteger vBigInt = new BigInteger(1, vDigest); String vHashPassword = vBigInt.toString(16); vClientBean.setMdp(vHashPassword); vClientDTO = BeanToDTO.getInstance().createClientDTO(vClientBean); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return vClientDTO; } |
11
| Code Sample 1:
public static void decompressFile(File orig) throws IOException { File file = new File(INPUT + orig.toString()); File target = new File(OUTPUT + orig.toString().replaceAll(".xml.gz", ".xml")); System.out.println(" Decompressing \"" + file.getName() + "\" into \"" + target + "\""); long l = file.length(); GZIPInputStream gzipinputstream = new GZIPInputStream(new FileInputStream(file)); FileOutputStream fileoutputstream = new FileOutputStream(target); byte abyte0[] = new byte[1024]; int i; while ((i = gzipinputstream.read(abyte0)) != -1) fileoutputstream.write(abyte0, 0, i); fileoutputstream.close(); gzipinputstream.close(); long l1 = target.length(); System.out.println(" Initial size: " + l + "; Decompressed size: " + l1 + "."); System.out.println(" Done."); System.out.println(); }
Code Sample 2:
private void loadMap() { final String wordList = "vietwordlist.txt"; try { File dataFile = new File(supportDir, wordList); if (!dataFile.exists()) { final ReadableByteChannel input = Channels.newChannel(ClassLoader.getSystemResourceAsStream("dict/" + dataFile.getName())); final FileChannel output = new FileOutputStream(dataFile).getChannel(); output.transferFrom(input, 0, 1000000L); input.close(); output.close(); } long fileLastModified = dataFile.lastModified(); if (map == null) { map = new HashMap<String, String>(); } else { if (fileLastModified <= mapLastModified) { return; } map.clear(); } mapLastModified = fileLastModified; BufferedReader bs = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), "UTF-8")); String accented; while ((accented = bs.readLine()) != null) { String plain = VietUtilities.stripDiacritics(accented); map.put(plain.toLowerCase(), accented); } bs.close(); } catch (IOException e) { map = null; e.printStackTrace(); JOptionPane.showMessageDialog(this, myResources.getString("Cannot_find_\"") + wordList + myResources.getString("\"_in\n") + supportDir.toString(), VietPad.APP_NAME, JOptionPane.ERROR_MESSAGE); } } |
00
| Code Sample 1:
@Override public void run() { File dir = new File(loggingDir); if (!dir.isDirectory()) { logger.error("Logging directory \"" + dir.getAbsolutePath() + "\" does not exist."); return; } File file = new File(dir, new Date().toString().replaceAll("[ ,:]", "") + "LoadBalancerLog.txt"); FileWriter writer; try { writer = new FileWriter(file); } catch (IOException e) { e.printStackTrace(); return; } int counter = 0; while (!isInterrupted() && counter < numProbes) { try { writer.write(System.currentTimeMillis() + "," + currentPending + "," + currentThreads + "," + droppedTasks + "," + executionExceptions + "," + currentWeight + "," + averageWaitTime + "," + averageExecutionTime + "#"); writer.flush(); } catch (IOException e) { e.printStackTrace(); break; } counter++; try { sleep(probeTime); } catch (InterruptedException e) { e.printStackTrace(); break; } } try { writer.close(); } catch (IOException e) { e.printStackTrace(); return; } FileReader reader; try { reader = new FileReader(file); } catch (FileNotFoundException e2) { e2.printStackTrace(); return; } Vector<StatStorage> dataV = new Vector<StatStorage>(); int c; try { c = reader.read(); } catch (IOException e1) { e1.printStackTrace(); c = -1; } String entry = ""; Date startTime = null; Date stopTime = null; while (c != -1) { if (c == 35) { String parts[] = entry.split(","); if (startTime == null) startTime = new Date(Long.parseLong(parts[0])); if (parts.length > 0) dataV.add(parse(parts)); stopTime = new Date(Long.parseLong(parts[0])); entry = ""; } else { entry += (char) c; } try { c = reader.read(); } catch (IOException e) { e.printStackTrace(); } } try { reader.close(); } catch (IOException e) { e.printStackTrace(); } if (dataV.size() > 0) { int[] dataPending = new int[dataV.size()]; int[] dataOccupied = new int[dataV.size()]; long[] dataDropped = new long[dataV.size()]; long[] dataException = new long[dataV.size()]; int[] dataWeight = new int[dataV.size()]; long[] dataExecution = new long[dataV.size()]; long[] dataWait = new long[dataV.size()]; for (int i = 0; i < dataV.size(); i++) { dataPending[i] = dataV.get(i).pending; dataOccupied[i] = dataV.get(i).occupied; dataDropped[i] = dataV.get(i).dropped; dataException[i] = dataV.get(i).exceptions; dataWeight[i] = dataV.get(i).currentWeight; dataExecution[i] = (long) dataV.get(i).executionTime; dataWait[i] = (long) dataV.get(i).waitTime; } String startName = startTime.toString(); startName = startName.replaceAll("[ ,:]", ""); file = new File(dir, startName + "pending.gif"); SimpleChart.drawChart(file, 640, 480, dataPending, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "occupied.gif"); SimpleChart.drawChart(file, 640, 480, dataOccupied, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "dropped.gif"); SimpleChart.drawChart(file, 640, 480, dataDropped, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "exceptions.gif"); SimpleChart.drawChart(file, 640, 480, dataException, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "weight.gif"); SimpleChart.drawChart(file, 640, 480, dataWeight, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "execution.gif"); SimpleChart.drawChart(file, 640, 480, dataExecution, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "wait.gif"); SimpleChart.drawChart(file, 640, 480, dataWait, startTime, stopTime, new Color(0, 0, 0)); } recordedExecutionThreads = 0; recordedWaitingThreads = 0; averageExecutionTime = 0; averageWaitTime = 0; if (!isLocked) { debugThread = new DebugThread(); debugThread.start(); } }
Code Sample 2:
public InstanceMonitor(String awsAccessId, String awsSecretKey, String bucketName, boolean first) throws IOException { this.awsAccessId = awsAccessId; this.awsSecretKey = awsSecretKey; props = new Properties(); while (true) { try { s3 = new RestS3Service(new AWSCredentials(awsAccessId, awsSecretKey)); bucket = new S3Bucket(bucketName); S3Object obj = s3.getObject(bucket, EW_PROPERTIES); props.load(obj.getDataInputStream()); break; } catch (S3ServiceException ex) { logger.error("problem fetching props from bucket, retrying", ex); try { Thread.sleep(1000); } catch (InterruptedException iex) { } } } URL url = new URL("http://169.254.169.254/latest/meta-data/hostname"); hostname = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/instance-id"); instanceId = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/public-ipv4"); externalIP = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); this.dns = new NetticaAPI(props.getProperty(NETTICA_USER), props.getProperty(NETTICA_PASS)); this.userData = awsAccessId + " " + awsSecretKey + " " + bucketName; this.first = first; logger.info("InstanceMonitor initialized, first=" + first); } |
00
| Code Sample 1:
public APIResponse delete(String id) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/application/delete/" + id).openConnection(); connection.setRequestMethod("DELETE"); connection.setConnectTimeout(TIMEOUT); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { response.setDone(true); response.setMessage("Application Deleted!"); } else { response.setDone(false); response.setMessage("Delete Application Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
Code Sample 2:
protected void downloadJar(URL downloadURL, File jarFile, IProgressListener pl) { BufferedOutputStream out = null; InputStream in = null; URLConnection urlConnection = null; try { urlConnection = downloadURL.openConnection(); out = new BufferedOutputStream(new FileOutputStream(jarFile)); in = urlConnection.getInputStream(); int len = in.available(); Log.log("downloading jar with size: " + urlConnection.getContentLength()); if (len < 1) len = 1024; byte[] buffer = new byte[len]; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.close(); in.close(); } catch (Exception e) { } finally { if (out != null) { try { out.close(); } catch (IOException ignore) { } } if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } |
00
| Code Sample 1:
private void loadMap() { final String wordList = "vietwordlist.txt"; try { File dataFile = new File(supportDir, wordList); if (!dataFile.exists()) { final ReadableByteChannel input = Channels.newChannel(ClassLoader.getSystemResourceAsStream("dict/" + dataFile.getName())); final FileChannel output = new FileOutputStream(dataFile).getChannel(); output.transferFrom(input, 0, 1000000L); input.close(); output.close(); } long fileLastModified = dataFile.lastModified(); if (map == null) { map = new HashMap(); } else { if (fileLastModified <= mapLastModified) { return; } map.clear(); } mapLastModified = fileLastModified; BufferedReader bs = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), "UTF-8")); String accented; while ((accented = bs.readLine()) != null) { String plain = VietUtilities.stripDiacritics(accented); map.put(plain.toLowerCase(), accented); } bs.close(); } catch (IOException e) { map = null; e.printStackTrace(); JOptionPane.showMessageDialog(this, myResources.getString("Cannot_find_\"") + wordList + myResources.getString("\"_in\n") + supportDir.toString(), VietPad.APP_NAME, JOptionPane.ERROR_MESSAGE); } }
Code Sample 2:
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(); } |
11
| Code Sample 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(); } } }
Code Sample 2:
private void copy(final File src, final File dstDir) { dstDir.mkdirs(); final File dst = new File(dstDir, src.getName()); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(src), "ISO-8859-1")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "ISO-8859-1")); String read; while ((read = reader.readLine()) != null) { Line line = new Line(read); if (line.isComment()) continue; writer.write(read); writer.newLine(); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } if (writer != null) { try { writer.flush(); } catch (IOException e) { } try { writer.close(); } catch (IOException e) { } } } } |
11
| Code Sample 1:
@Override public String fetchElectronicEdition(Publication pub) { final String url = baseURL + pub.getKey() + ".html"; logger.info("fetching pub ee from local cache at: " + url); HttpMethod method = null; String responseBody = ""; method = new GetMethod(url); method.setFollowRedirects(true); try { if (StringUtils.isNotBlank(method.getURI().getScheme())) { InputStream is = null; StringWriter writer = new StringWriter(); try { client.executeMethod(method); Header contentType = method.getResponseHeader("Content-Type"); if (contentType != null && StringUtils.isNotBlank(contentType.getValue()) && contentType.getValue().indexOf("text/html") >= 0) { is = method.getResponseBodyAsStream(); IOUtils.copy(is, writer); responseBody = writer.toString(); } else { logger.info("ignoring non-text/html response from page: " + url + " content-type:" + contentType); } } catch (HttpException he) { logger.error("Http error connecting to '" + url + "'"); logger.error(he.getMessage()); } catch (IOException ioe) { logger.error("Unable to connect to '" + url + "'"); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(writer); } } } catch (URIException e) { logger.error(e); } finally { method.releaseConnection(); } return responseBody; }
Code Sample 2:
private void appendArchive(File instClass) throws IOException { FileOutputStream out = new FileOutputStream(instClass.getName(), true); FileInputStream zipStream = new FileInputStream("install.jar"); byte[] buf = new byte[2048]; int read = zipStream.read(buf); while (read > 0) { out.write(buf, 0, read); read = zipStream.read(buf); } zipStream.close(); out.close(); } |
11
| Code Sample 1:
public void migrateTo(String newExt) throws IOException { DigitalObject input = new DigitalObject.Builder(Content.byReference(new File(AllJavaSEServiceTestsuite.TEST_FILE_LOCATION + "PlanetsLogo.png").toURI().toURL())).build(); System.out.println("Input: " + input); FormatRegistry format = FormatRegistryFactory.getFormatRegistry(); MigrateResult mr = dom.migrate(input, format.createExtensionUri("png"), format.createExtensionUri(newExt), null); ServiceReport sr = mr.getReport(); System.out.println("Got Report: " + sr); DigitalObject doOut = mr.getDigitalObject(); assertTrue("Resulting digital object is null.", doOut != null); System.out.println("Output: " + doOut); System.out.println("Output.content: " + doOut.getContent()); File out = new File("services/java-se/test/results/test." + newExt); FileOutputStream fo = new FileOutputStream(out); IOUtils.copyLarge(doOut.getContent().getInputStream(), fo); fo.close(); System.out.println("Recieved service report: " + mr.getReport()); System.out.println("Recieved service properties: "); ServiceProperties.printProperties(System.out, mr.getReport().getProperties()); }
Code Sample 2:
public void transform(File inputMatrixFile, MatrixIO.Format inputFormat, File outputMatrixFile) throws IOException { FileChannel original = new FileInputStream(inputMatrixFile).getChannel(); FileChannel copy = new FileOutputStream(outputMatrixFile).getChannel(); copy.transferFrom(original, 0, original.size()); original.close(); copy.close(); } |
00
| Code Sample 1:
public String contentType() { if (_contentType != null) { return (String) _contentType; } String uti = null; URL url = url(); System.out.println("OKIOSIDManagedObject.contentType(): url = " + url + "\n"); if (url != null) { String contentType = null; try { contentType = url.openConnection().getContentType(); } catch (java.io.IOException e) { System.out.println("OKIOSIDManagedObject.contentType(): couldn't open URL connection!\n"); return UTType.Item; } if (contentType != null) { System.out.println("OKIOSIDManagedObject.contentType(): contentType = " + contentType + "\n"); uti = UTType.preferredIdentifierForTag(UTType.MIMETypeTagClass, contentType, null); } if (uti == null) { uti = UTType.Item; } } else { uti = UTType.Item; } _contentType = uti; System.out.println("OKIOSIDManagedObject.contentType(): uti = " + uti + "\n"); return uti; }
Code Sample 2:
public BufferedWriter createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); return new BufferedWriter(new OutputStreamWriter(zos, "UTF-8")); } |
11
| Code Sample 1:
void copyFileOnPeer(String path, RServerInfo peerserver, boolean allowoverwrite) throws IOException { RFile file = new RFile(path); OutputStream out = null; FileInputStream in = null; try { in = fileManager.openFileRead(path); out = localClient.openWrite(file, false, WriteMode.TRANSACTED, 1, peerserver, !allowoverwrite); IOUtils.copyLarge(in, out); out.close(); out = null; } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (out != null) { try { out.close(); } catch (Throwable t) { } } } }
Code Sample 2:
public void executaAlteracoes() { Album album = Album.getAlbum(); Photo[] fotos = album.getFotos(); Photo f; int ultimoFotoID = -1; int albumID = album.getAlbumID(); sucesso = true; PainelWebFotos.setCursorWait(true); albumID = recordAlbumData(album, albumID); sucesso = recordFotoData(fotos, ultimoFotoID, albumID); String caminhoAlbum = Util.getFolder("albunsRoot").getPath() + File.separator + albumID; File diretorioAlbum = new File(caminhoAlbum); if (!diretorioAlbum.isDirectory()) { if (!diretorioAlbum.mkdir()) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.7]/ERRO: diretorio " + caminhoAlbum + " n�o pode ser criado. abortando"); return; } } for (int i = 0; i < fotos.length; i++) { f = fotos[i]; if (f.getCaminhoArquivo().length() > 0) { try { FileChannel canalOrigem = new FileInputStream(f.getCaminhoArquivo()).getChannel(); FileChannel canalDestino = new FileOutputStream(caminhoAlbum + File.separator + f.getFotoID() + ".jpg").getChannel(); canalDestino.transferFrom(canalOrigem, 0, canalOrigem.size()); canalOrigem = null; canalDestino = null; } catch (Exception e) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.8]/ERRO: " + e); sucesso = false; } } } prepareThumbsAndFTP(fotos, albumID, caminhoAlbum); prepareExtraFiles(album, caminhoAlbum); fireChangesToGUI(fotos); dispatchAlbum(); PainelWebFotos.setCursorWait(false); } |
11
| Code Sample 1:
public MemoryTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); }
Code Sample 2:
public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("复制文件失败,源文件" + srcFileName + "不存在!"); return false; } else if (!srcFile.isFile()) { System.out.println("复制文件失败," + srcFileName + "不是一个文件!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("目标文件已存在,准备删除!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("删除目标文件" + descFileName + "失败!"); return false; } } else { System.out.println("复制文件失败,目标文件" + descFileName + "已存在!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("目标文件所在的目录不存在,创建目录!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("创建目标文件所在的目录失败!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("复制单个文件" + srcFileName + "到" + descFileName + "成功!"); return true; } catch (Exception e) { System.out.println("复制文件失败:" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } } |
00
| Code Sample 1:
private FTPClient getFTPConnection(String strUser, String strPassword, String strServer, boolean binaryTransfer, String connectionNote, boolean passiveMode) { FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(strServer); ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Connected to " + strServer + ", " + connectionNote); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP server refused connection."); return null; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { return null; } } ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP Could not connect to server."); ResourcePool.LogException(e, this); return null; } try { if (!ftp.login(strUser, strPassword)) { ftp.logout(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP login failed."); return null; } ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Remote system is " + ftp.getSystemName() + ", " + connectionNote); if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } else { ftp.setFileType(FTP.ASCII_FILE_TYPE); } if (passiveMode) { ftp.enterLocalPassiveMode(); } else { ftp.enterLocalActiveMode(); } } catch (FTPConnectionClosedException e) { ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "Server closed connection."); ResourcePool.LogException(e, this); return null; } catch (IOException e) { ResourcePool.LogException(e, this); return null; } return ftp; }
Code Sample 2:
public static String submitURLRequest(String url) throws HttpException, IOException, URISyntaxException { HttpClient httpclient = new DefaultHttpClient(); InputStream stream = null; user_agents = new LinkedList<String>(); user_agents.add("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); String response_text = ""; URI uri = new URI(url); HttpGet post = new HttpGet(uri); int MAX = user_agents.size() - 1; int index = (int) Math.round(((double) Math.random() * (MAX))); String agent = user_agents.get(index); httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, agent); httpclient.getParams().setParameter("User-Agent", agent); httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.ACCEPT_NONE); HttpResponse response = httpclient.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { stream = entity.getContent(); response_text = convertStreamToString(stream); } httpclient.getConnectionManager().shutdown(); if (stream != null) { stream.close(); } return response_text; } |
11
| Code Sample 1:
public static String Sha1(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] hash = new byte[40]; md.update(s.getBytes("iso-8859-1"), 0, s.length()); hash = md.digest(); return toHex(hash); } catch (Exception e) { e.printStackTrace(); return null; } }
Code Sample 2:
public static String hashMD5(String passw) { String passwHash = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(passw.getBytes()); byte[] result = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < result.length; i++) { String tmpStr = "0" + Integer.toHexString((0xff & result[i])); sb.append(tmpStr.substring(tmpStr.length() - 2)); } passwHash = sb.toString(); } catch (NoSuchAlgorithmException ecc) { log.error("Errore algoritmo " + ecc); } return passwHash; } |
11
| Code Sample 1:
public String md5(String phrase) { MessageDigest m; String coded = new String(); try { m = MessageDigest.getInstance("MD5"); m.update(phrase.getBytes(), 0, phrase.length()); coded = (new BigInteger(1, m.digest()).toString(16)).toString(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } if (coded.length() < 32) { coded = "0" + coded; } return coded; }
Code Sample 2:
public Blowfish(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA1"); digest.update(password.getBytes()); } catch (Exception e) { Log.error(e.getMessage(), e); } m_bfish = new BlowfishCBC(digest.digest(), 0); digest.reset(); } |
11
| Code Sample 1:
public static void copyFile(File sourceFile, File destinationFile) throws IOException { if (!destinationFile.exists()) { destinationFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } |
00
| Code Sample 1:
public void xtest12() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/090237098008f637.pdf"); InputStream page1 = manager.cut(pdf, 36, 36); OutputStream outputStream = new FileOutputStream("/tmp/090237098008f637-1.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); }
Code Sample 2:
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; } |
11
| Code Sample 1:
void shutdown(final boolean unexpected) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } log.error("check if we need the controler listener infrastructure"); if (this.dumpDataAtEnd) { new PopulationWriter(this.population, this.network).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); }
Code Sample 2:
private static void serveHTML() throws Exception { Bus bus = BusFactory.getDefaultBus(); DestinationFactoryManager dfm = bus.getExtension(DestinationFactoryManager.class); DestinationFactory df = dfm.getDestinationFactory("http://cxf.apache.org/transports/http/configuration"); EndpointInfo ei = new EndpointInfo(); ei.setAddress("http://localhost:8080/test.html"); Destination d = df.getDestination(ei); d.setMessageObserver(new MessageObserver() { public void onMessage(Message message) { try { ExchangeImpl ex = new ExchangeImpl(); ex.setInMessage(message); Conduit backChannel = message.getDestination().getBackChannel(message, null, null); MessageImpl res = new MessageImpl(); res.put(Message.CONTENT_TYPE, "text/html"); backChannel.prepare(res); OutputStream out = res.getContent(OutputStream.class); FileInputStream is = new FileInputStream("test.html"); IOUtils.copy(is, out, 2048); out.flush(); out.close(); is.close(); backChannel.close(res); } catch (Exception e) { e.printStackTrace(); } } }); } |
11
| Code Sample 1:
void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
Code Sample 2:
public ManageUsers() { if (System.getProperty("user.home") != null) { dataFile = new File(System.getProperty("user.home") + File.separator + "MyRx" + File.separator + "MyRx.dat"); File dataFileDir = new File(System.getProperty("user.home") + File.separator + "MyRx"); dataFileDir.mkdirs(); } else { dataFile = new File("MyRx.dat"); } try { dataFile.createNewFile(); } catch (IOException e1) { logger.error(e1); JOptionPane.showMessageDialog(Menu.getMainMenu(), e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } File oldDataFile = new File("MyRx.dat"); if (oldDataFile.exists()) { FileChannel src = null, dst = null; try { src = new FileInputStream(oldDataFile.getAbsolutePath()).getChannel(); dst = new FileOutputStream(dataFile.getAbsolutePath()).getChannel(); dst.transferFrom(src, 0, src.size()); if (!oldDataFile.delete()) { oldDataFile.deleteOnExit(); } } catch (FileNotFoundException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } finally { try { src.close(); dst.close(); } catch (IOException e) { logger.error(e); } } } } |
00
| Code Sample 1:
public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[8192]; int bytes_read; while (true) { bytes_read = in.read(buffer); if (bytes_read == -1) break; out.write(buffer, 0, bytes_read); } out.flush(); out.close(); in.close(); }
Code Sample 2:
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; } } } |
00
| Code Sample 1:
public static void bubbleSort(int[] a) { for (int i = a.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (a[j] > a[j + 1]) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } }
Code Sample 2:
private void process(String zipFileName, String directory, String db) throws SQLException { InputStream in = null; try { if (!FileUtils.exists(zipFileName)) { throw new IOException("File not found: " + zipFileName); } String originalDbName = null; int originalDbLen = 0; if (db != null) { originalDbName = getOriginalDbName(zipFileName, db); if (originalDbName == null) { throw new IOException("No database named " + db + " found"); } if (originalDbName.startsWith(File.separator)) { originalDbName = originalDbName.substring(1); } originalDbLen = originalDbName.length(); } in = FileUtils.openFileInputStream(zipFileName); ZipInputStream zipIn = new ZipInputStream(in); while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String fileName = entry.getName(); fileName = fileName.replace('\\', File.separatorChar); fileName = fileName.replace('/', File.separatorChar); if (fileName.startsWith(File.separator)) { fileName = fileName.substring(1); } boolean copy = false; if (db == null) { copy = true; } else if (fileName.startsWith(originalDbName + ".")) { fileName = db + fileName.substring(originalDbLen); copy = true; } if (copy) { OutputStream out = null; try { out = FileUtils.openFileOutputStream(directory + File.separator + fileName, false); IOUtils.copy(zipIn, out); out.close(); } finally { IOUtils.closeSilently(out); } } zipIn.closeEntry(); } zipIn.closeEntry(); zipIn.close(); } catch (IOException e) { throw Message.convertIOException(e, zipFileName); } finally { IOUtils.closeSilently(in); } } |
11
| Code Sample 1:
private ChangeCapsule fetchServer(OWLOntology ontologyURI, Long sequenceNumber) throws IOException { String requestString = "http://" + InetAddress.getLocalHost().getHostName() + ":8080/ChangeServer"; requestString += "?fetch=" + URLEncoder.encode(ontologyURI.getURI().toString(), "UTF-8"); requestString += "&number" + sequenceNumber; URL url = new URL(requestString); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer returned = new StringBuffer(); String str; while (null != ((str = input.readLine()))) { returned.append(str); } input.close(); ChangeCapsule cp = new ChangeCapsule(returned.toString()); return cp; }
Code Sample 2:
public static String[] retrieveFasta(String id) throws Exception { URL url = new URL("http://www.uniprot.org/uniprot/" + id + ".fasta"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String header = reader.readLine(); StringBuffer seq = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { seq.append(line); } reader.close(); String[] first = header.split("OS="); return new String[] { id, first[0].split("\\s")[1], first[1].split("GN=")[0], seq.toString() }; } |
00
| Code Sample 1:
private String getMAC(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { } try { md.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static boolean dumpFile(String from, File to, String lineBreak) { try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(from))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(to))); String line = null; while ((line = in.readLine()) != null) out.write(Main.getInstance().resolve(line) + lineBreak); in.close(); out.close(); } catch (Exception e) { Installer.getInstance().getLogger().log(StringUtils.getStackTrace(e)); return false; } return true; } |
00
| Code Sample 1:
@Override public InputStream openStream(long off, long len) throws IOException { URLConnection con = url.openConnection(); if (!(con instanceof HttpURLConnection)) { return null; } long t0 = System.currentTimeMillis(); HttpURLConnection urlcon = (HttpURLConnection) con; urlcon.setRequestProperty("Connection", "Keep-Alive"); String rangeS = ""; if (off > 0) rangeS += "bytes=" + off + "-"; if (len > 0 && off + len < length) rangeS += (len - 1); if (rangeS.length() > 0) { urlcon.setRequestProperty("Range", rangeS); } urlcon.setRequestProperty("Content-Type", "application/octet-stream"); InputStream in = urlcon.getInputStream(); rangeS = urlcon.getHeaderField("Content-Range"); long responseOff = 0; long responseEnd = -1; if (rangeS != null) { int start = rangeS.indexOf(' ') + 1; int end = rangeS.indexOf('-', start); String offS = rangeS.substring(start, end).trim(); responseOff = Long.parseLong(offS); start = end + 1; end = rangeS.indexOf('/', start); String lenS = rangeS.substring(start, end).trim(); responseEnd = 1 + Long.parseLong(lenS); } while (responseOff < off && responseOff <= responseEnd) { long s = in.skip(off - responseOff); if (s <= 0) { break; } responseOff += s; } length = urlcon.getHeaderFieldInt("Content-Length", -1); long respTime = System.currentTimeMillis() - t0; if (responseTime < 0) { responseTime = respTime; } else { responseTime = Math.round(0.5 * responseTime + 0.5 * respTime); } return in; }
Code Sample 2:
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()); } |
00
| Code Sample 1:
public static String digestMd5(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("文字列がNull、または空です。"); } MessageDigest md5; byte[] enclyptedHash; try { md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); enclyptedHash = md5.digest(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ""; } return bytesToHexString(enclyptedHash); }
Code Sample 2:
public byte[] loadResource(String name) throws IOException { ClassPathResource cpr = new ClassPathResource(name); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(cpr.getInputStream(), baos); return baos.toByteArray(); } |
11
| Code Sample 1:
public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); System.out.print("Overwrite existing file " + to_name + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("FileCopy: existing file was not overwritten."); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } |
11
| Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } else { inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public void dispatch(com.sun.star.util.URL aURL, com.sun.star.beans.PropertyValue[] aArguments) { if (aURL.Protocol.compareTo("org.openoffice.oosvn.oosvn:") == 0) { OoDocProperty docProperty = getProperty(); settings.setCancelFired(false); if (aURL.Path.compareTo("svnUpdate") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (NullPointerException ex) { new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; new DialogFileChooser(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = -1; if (logs.length == 0) { error("Sorry, the specified repository is empty."); return; } new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); if (settings.getCancelFired()) return; File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File[] tempFiles = tempDir.listFiles(); File anyOdt = null; File thisOdt = null; for (int j = 0; j < tempFiles.length; j++) { if (tempFiles[j].toString().endsWith(".odt")) anyOdt = tempFiles[j]; if (tempFiles[j].toString().equals(settings.getCheckoutDoc()) && settings.getCheckoutDoc() != null) thisOdt = tempFiles[j]; } if (thisOdt != null) anyOdt = thisOdt; String url; if (settings.getCheckoutDoc() == null || !settings.getCheckoutDoc().equals(anyOdt.getName())) { File newOdt = new File(settings.getCheckoutPath() + "/" + anyOdt.getName()); if (newOdt.exists()) newOdt.delete(); anyOdt.renameTo(newOdt); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } url = "file:///" + newOdt.getPath().replace("\\", "/"); svnInfo.renameTo(newSvnInfo); anyOdt = newOdt; loadDocumentFromUrl(url); settings.setCheckoutDoc(anyOdt.getName()); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } else { try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } url = "file:///" + anyOdt.getPath().replace("\\", "/"); XDispatchProvider xDispatchProvider = (XDispatchProvider) UnoRuntime.queryInterface(XDispatchProvider.class, m_xFrame); PropertyValue property[] = new PropertyValue[1]; property[0] = new PropertyValue(); property[0].Name = "URL"; property[0].Value = url; XMultiServiceFactory xMSF = createProvider(); Object objDispatchHelper = m_xServiceManager.createInstanceWithContext("com.sun.star.frame.DispatchHelper", m_xContext); XDispatchHelper xDispatchHelper = (XDispatchHelper) UnoRuntime.queryInterface(XDispatchHelper.class, objDispatchHelper); xDispatchHelper.executeDispatch(xDispatchProvider, ".uno:CompareDocuments", "", 0, property); } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnCommit") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Collection logs = svnWorker.getLogs(settings); long headRevision = svnWorker.getHeadRevisionNumber(logs); long committedRevision = -1; new DialogCommitMessage(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } if (headRevision == 0) { File impDir = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import"); if (impDir.exists()) if (deleteFileDir(impDir) == false) { error("Error while creating temporary import directory."); return; } if (!impDir.mkdirs()) { error("Error while creating temporary import directory."); return; } File impFile = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import/" + settings.getCheckoutDoc()); try { FileChannel srcChannel = new FileInputStream(settings.getCheckoutPath() + "/" + settings.getCheckoutDoc()).getChannel(); FileChannel dstChannel = new FileOutputStream(impFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception ex) { error("Error while importing file", ex); return; } final String checkoutPath = settings.getCheckoutPath(); try { settings.setCheckoutPath(impDir.toString()); committedRevision = svnWorker.importDirectory(settings, false).getNewRevision(); } catch (Exception ex) { settings.setCheckoutPath(checkoutPath); error("Error while importing file", ex); return; } settings.setCheckoutPath(checkoutPath); if (impDir.exists()) if (deleteFileDir(impDir) == false) error("Error while creating temporary import directory."); try { File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); svnInfo.renameTo(newSvnInfo); if (deleteFileDir(tempDir) == false) { error("Error while managing working copy"); } try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } catch (Exception ex) { error("Error while checking out a working copy for the location", ex); } showMessageBox("Import succesful", "Succesfully imported as revision no. " + committedRevision); return; } else { try { committedRevision = svnWorker.commit(settings, false).getNewRevision(); } catch (Exception ex) { error("Error while committing changes. If the file is not working copy, you must use 'Checkout / Update' first.", ex); } if (committedRevision == -1) { showMessageBox("Update - no changes", "No changes was made. Maybe you must just save the changes."); } else { showMessageBox("Commit succesfull", "Commited as revision no. " + committedRevision); } } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnHistory") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = settings.getCheckoutVersion(); settings.setCheckoutVersion(-99); new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); settings.setCheckoutVersion(checkVersion); } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("settings") == 0) { try { settings = getSerializedSettings(docProperty); } catch (NoSerializedSettingsException ex) { try { settings.setCheckout(docProperty.getDocURL()); } catch (Exception exx) { } } catch (Exception ex) { error("Error getting settings; maybe you" + " need to save your document." + " If this is your first" + " checkout of the document, use Checkout" + " function directly."); return; } new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when saving settings.", ex); } return; } if (aURL.Path.compareTo("about") == 0) { showMessageBox("OoSvn :: About", "Autor: �t�p�n Cenek ([email protected])"); return; } } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.