label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
private InputStream callService(String text) { InputStream in = null; try { URL url = new URL(SERVLET_URL); URLConnection conn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("POST"); httpConn.setDoInput(true); httpConn.setDoOutput(true); httpConn.connect(); DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream()); dataStream.writeBytes(text); dataStream.flush(); dataStream.close(); int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { ex.printStackTrace(); } return in; }
Code Sample 2:
public static void main(String argv[]) { Matrix A, B, C, Z, O, I, R, S, X, SUB, M, T, SQ, DEF, SOL; int errorCount = 0; int warningCount = 0; double tmp, s; double[] columnwise = { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12. }; double[] rowwise = { 1., 4., 7., 10., 2., 5., 8., 11., 3., 6., 9., 12. }; double[][] avals = { { 1., 4., 7., 10. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] rankdef = avals; double[][] tvals = { { 1., 2., 3. }, { 4., 5., 6. }, { 7., 8., 9. }, { 10., 11., 12. } }; double[][] subavals = { { 5., 8., 11. }, { 6., 9., 12. } }; double[][] rvals = { { 1., 4., 7. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] pvals = { { 4., 1., 1. }, { 1., 2., 3. }, { 1., 3., 6. } }; double[][] ivals = { { 1., 0., 0., 0. }, { 0., 1., 0., 0. }, { 0., 0., 1., 0. } }; double[][] evals = { { 0., 1., 0., 0. }, { 1., 0., 2.e-7, 0. }, { 0., -2.e-7, 0., 1. }, { 0., 0., 1., 0. } }; double[][] square = { { 166., 188., 210. }, { 188., 214., 240. }, { 210., 240., 270. } }; double[][] sqSolution = { { 13. }, { 15. } }; double[][] condmat = { { 1., 3. }, { 7., 9. } }; int rows = 3, cols = 4; int invalidld = 5; int raggedr = 0; int raggedc = 4; int validld = 3; int nonconformld = 4; int ib = 1, ie = 2, jb = 1, je = 3; int[] rowindexset = { 1, 2 }; int[] badrowindexset = { 1, 3 }; int[] columnindexset = { 1, 2, 3 }; int[] badcolumnindexset = { 1, 2, 4 }; double columnsummax = 33.; double rowsummax = 30.; double sumofdiagonals = 15; double sumofsquares = 650; print("\nTesting constructors and constructor-like methods...\n"); try { A = new Matrix(columnwise, invalidld); errorCount = try_failure(errorCount, "Catch invalid length in packed constructor... ", "exception not thrown for invalid input"); } catch (IllegalArgumentException e) { try_success("Catch invalid length in packed constructor... ", e.getMessage()); } try { A = new Matrix(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to default constructor... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructor... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } try { A = Matrix.constructWithCopy(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to constructWithCopy... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructWithCopy... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } A = new Matrix(columnwise, validld); B = new Matrix(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; C = B.minus(A); avals[0][0] = tmp; B = Matrix.constructWithCopy(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; if ((tmp - B.get(0, 0)) != 0.0) { errorCount = try_failure(errorCount, "constructWithCopy... ", "copy not effected... data visible outside"); } else { try_success("constructWithCopy... ", ""); } avals[0][0] = columnwise[0]; I = new Matrix(ivals); try { check(I, Matrix.identity(3, 4)); try_success("identity... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "identity... ", "identity Matrix not successfully created"); } print("\nTesting access methods...\n"); B = new Matrix(avals); if (B.getRowDimension() != rows) { errorCount = try_failure(errorCount, "getRowDimension... ", ""); } else { try_success("getRowDimension... ", ""); } if (B.getColumnDimension() != cols) { errorCount = try_failure(errorCount, "getColumnDimension... ", ""); } else { try_success("getColumnDimension... ", ""); } B = new Matrix(avals); double[][] barray = B.getArray(); if (barray != avals) { errorCount = try_failure(errorCount, "getArray... ", ""); } else { try_success("getArray... ", ""); } barray = B.getArrayCopy(); if (barray == avals) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not (deep) copied"); } try { check(barray, avals); try_success("getArrayCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not successfully (deep) copied"); } double[] bpacked = B.getColumnPackedCopy(); try { check(bpacked, columnwise); try_success("getColumnPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getColumnPackedCopy... ", "data not successfully (deep) copied by columns"); } bpacked = B.getRowPackedCopy(); try { check(bpacked, rowwise); try_success("getRowPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getRowPackedCopy... ", "data not successfully (deep) copied by rows"); } try { tmp = B.get(B.getRowDimension(), B.getColumnDimension() - 1); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { tmp = B.get(B.getRowDimension() - 1, B.getColumnDimension()); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("get(int,int)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } try { if (B.get(B.getRowDimension() - 1, B.getColumnDimension() - 1) != avals[B.getRowDimension() - 1][B.getColumnDimension() - 1]) { errorCount = try_failure(errorCount, "get(int,int)... ", "Matrix entry (i,j) not successfully retreived"); } else { try_success("get(int,int)... ", ""); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "get(int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } SUB = new Matrix(subavals); try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, jb, je); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, jb, je); try { check(SUB, M); try_success("getMatrix(int,int,int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(ib, ie, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, columnindexset); try { check(SUB, M); try_success("getMatrix(int,int,int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, jb, je); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, jb, je); try { check(SUB, M); try_success("getMatrix(int[],int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, columnindexset); try { check(SUB, M); try_success("getMatrix(int[],int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.set(B.getRowDimension(), B.getColumnDimension() - 1, 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.set(B.getRowDimension() - 1, B.getColumnDimension(), 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("set(int,int,double)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } try { B.set(ib, jb, 0.); tmp = B.get(ib, jb); try { check(tmp, 0.); try_success("set(int,int,double)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Matrix element not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Unexpected ArrayIndexOutOfBoundsException"); } M = new Matrix(2, 3, 0.); try { B.setMatrix(ib, ie + B.getRowDimension() + 1, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, jb, je, M); try { check(M.minus(B.getMatrix(ib, ie, jb, je)), M); try_success("setMatrix(int,int,int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(ib, ie + B.getRowDimension() + 1, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, columnindexset, M); try { check(M.minus(B.getMatrix(ib, ie, columnindexset)), M); try_success("setMatrix(int,int,int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, jb, je, M); try { check(M.minus(B.getMatrix(rowindexset, jb, je)), M); try_success("setMatrix(int[],int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, columnindexset, M); try { check(M.minus(B.getMatrix(rowindexset, columnindexset)), M); try_success("setMatrix(int[],int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "submatrix not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } print("\nTesting array-like methods...\n"); S = new Matrix(columnwise, nonconformld); R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); A = R; try { S = A.minus(S); errorCount = try_failure(errorCount, "minus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minus conformance check... ", ""); } if (A.minus(R).norm1() != 0.) { errorCount = try_failure(errorCount, "minus... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minus... ", ""); } A = R.copy(); A.minusEquals(R); Z = new Matrix(A.getRowDimension(), A.getColumnDimension()); try { A.minusEquals(S); errorCount = try_failure(errorCount, "minusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minusEquals conformance check... ", ""); } if (A.minus(Z).norm1() != 0.) { errorCount = try_failure(errorCount, "minusEquals... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minusEquals... ", ""); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); C = A.minus(B); try { S = A.plus(S); errorCount = try_failure(errorCount, "plus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plus conformance check... ", ""); } try { check(C.plus(B), A); try_success("plus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plus... ", "(C = A - B, but C + B != A)"); } C = A.minus(B); C.plusEquals(B); try { A.plusEquals(S); errorCount = try_failure(errorCount, "plusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plusEquals conformance check... ", ""); } try { check(C, A); try_success("plusEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plusEquals... ", "(C = A - B, but C = C + B != A)"); } A = R.uminus(); try { check(A.plus(R), Z); try_success("uminus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "uminus... ", "(-A + A != zeros)"); } A = R.copy(); O = new Matrix(A.getRowDimension(), A.getColumnDimension(), 1.0); C = A.arrayLeftDivide(R); try { S = A.arrayLeftDivide(S); errorCount = try_failure(errorCount, "arrayLeftDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivide conformance check... ", ""); } try { check(C, O); try_success("arrayLeftDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivide... ", "(M.\\M != ones)"); } try { A.arrayLeftDivideEquals(S); errorCount = try_failure(errorCount, "arrayLeftDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivideEquals conformance check... ", ""); } A.arrayLeftDivideEquals(R); try { check(A, O); try_success("arrayLeftDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivideEquals... ", "(M.\\M != ones)"); } A = R.copy(); try { A.arrayRightDivide(S); errorCount = try_failure(errorCount, "arrayRightDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivide conformance check... ", ""); } C = A.arrayRightDivide(R); try { check(C, O); try_success("arrayRightDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivide... ", "(M./M != ones)"); } try { A.arrayRightDivideEquals(S); errorCount = try_failure(errorCount, "arrayRightDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivideEquals conformance check... ", ""); } A.arrayRightDivideEquals(R); try { check(A, O); try_success("arrayRightDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivideEquals... ", "(M./M != ones)"); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); try { S = A.arrayTimes(S); errorCount = try_failure(errorCount, "arrayTimes conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimes conformance check... ", ""); } C = A.arrayTimes(B); try { check(C.arrayRightDivideEquals(B), A); try_success("arrayTimes... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimes... ", "(A = R, C = A.*B, but C./B != A)"); } try { A.arrayTimesEquals(S); errorCount = try_failure(errorCount, "arrayTimesEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimesEquals conformance check... ", ""); } A.arrayTimesEquals(B); try { check(A.arrayRightDivideEquals(B), R); try_success("arrayTimesEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimesEquals... ", "(A = R, A = A.*B, but A./B != R)"); } print("\nTesting I/O methods...\n"); try { DecimalFormat fmt = new DecimalFormat("0.0000E00"); fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read()...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } catch (Exception e) { try { e.printStackTrace(System.out); warningCount = try_warning(warningCount, "print()/read()...", "Formatting error... will try JDK1.1 reformulation..."); DecimalFormat fmt = new DecimalFormat("0.0000"); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read() (2nd attempt) ...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } } R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); String tmpname = "TMPMATRIX.serial"; try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tmpname)); out.writeObject(R); ObjectInputStream sin = new ObjectInputStream(new FileInputStream(tmpname)); A = (Matrix) sin.readObject(); try { check(A, R); try_success("writeObject(Matrix)/readObject(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "Matrix not serialized correctly"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "writeObject()/readObject()...", "unexpected I/O error, unable to run serialization test; check write permission in current directory and retry"); } catch (Exception e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "unexpected error in serialization test"); } print("\nTesting linear algebra methods...\n"); A = new Matrix(columnwise, 3); T = new Matrix(tvals); T = A.transpose(); try { check(A.transpose(), T); try_success("transpose...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "transpose()...", "transpose unsuccessful"); } A.transpose(); try { check(A.norm1(), columnsummax); try_success("norm1...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "norm1()...", "incorrect norm calculation"); } try { check(A.normInf(), rowsummax); try_success("normInf()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normInf()...", "incorrect norm calculation"); } try { check(A.normF(), Math.sqrt(sumofsquares)); try_success("normF...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normF()...", "incorrect norm calculation"); } try { check(A.trace(), sumofdiagonals); try_success("trace()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "trace()...", "incorrect trace calculation"); } try { check(A.getMatrix(0, A.getRowDimension() - 1, 0, A.getRowDimension() - 1).det(), 0.); try_success("det()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "det()...", "incorrect determinant calculation"); } SQ = new Matrix(square); try { check(A.times(A.transpose()), SQ); try_success("times(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(Matrix)...", "incorrect Matrix-Matrix product calculation"); } try { check(A.times(0.), Z); try_success("times(double)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(double)...", "incorrect Matrix-scalar product calculation"); } A = new Matrix(columnwise, 4); QRDecomposition QR = A.qr(); R = QR.getR(); try { check(A, QR.getQ().times(R)); try_success("QRDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "QRDecomposition...", "incorrect QR decomposition calculation"); } SingularValueDecomposition SVD = A.svd(); try { check(A, SVD.getU().times(SVD.getS().times(SVD.getV().transpose()))); try_success("SingularValueDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "SingularValueDecomposition...", "incorrect singular value decomposition calculation"); } DEF = new Matrix(rankdef); try { check(DEF.rank(), Math.min(DEF.getRowDimension(), DEF.getColumnDimension()) - 1); try_success("rank()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "rank()...", "incorrect rank calculation"); } B = new Matrix(condmat); SVD = B.svd(); double[] singularvalues = SVD.getSingularValues(); try { check(B.cond(), singularvalues[0] / singularvalues[Math.min(B.getRowDimension(), B.getColumnDimension()) - 1]); try_success("cond()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "cond()...", "incorrect condition number calculation"); } int n = A.getColumnDimension(); A = A.getMatrix(0, n - 1, 0, n - 1); A.set(0, 0, 0.); LUDecomposition LU = A.lu(); try { check(A.getMatrix(LU.getPivot(), 0, n - 1), LU.getL().times(LU.getU())); try_success("LUDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "LUDecomposition...", "incorrect LU decomposition calculation"); } X = A.inverse(); try { check(A.times(X), Matrix.identity(3, 3)); try_success("inverse()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "inverse()...", "incorrect inverse calculation"); } O = new Matrix(SUB.getRowDimension(), 1, 1.0); SOL = new Matrix(sqSolution); SQ = SUB.getMatrix(0, SUB.getRowDimension() - 1, 0, SUB.getRowDimension() - 1); try { check(SQ.solve(SOL), O); try_success("solve()...", ""); } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "solve()...", e1.getMessage()); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "solve()...", e.getMessage()); } A = new Matrix(pvals); CholeskyDecomposition Chol = A.chol(); Matrix L = Chol.getL(); try { check(A, L.times(L.transpose())); try_success("CholeskyDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition...", "incorrect Cholesky decomposition calculation"); } X = Chol.solve(Matrix.identity(3, 3)); try { check(A.times(X), Matrix.identity(3, 3)); try_success("CholeskyDecomposition solve()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition solve()...", "incorrect Choleskydecomposition solve calculation"); } EigenvalueDecomposition Eig = A.eig(); Matrix D = Eig.getD(); Matrix V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (symmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (symmetric)...", "incorrect symmetric Eigenvalue decomposition calculation"); } A = new Matrix(evals); Eig = A.eig(); D = Eig.getD(); V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (nonsymmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (nonsymmetric)...", "incorrect nonsymmetric Eigenvalue decomposition calculation"); } print("\nTestMatrix completed.\n"); print("Total errors reported: " + Integer.toString(errorCount) + "\n"); print("Total warnings reported: " + Integer.toString(warningCount) + "\n"); }
|
00
|
Code Sample 1:
private OSD downloadList() throws IOException, IllegalStateException, ParseException, URISyntaxException { OSD osd = null; HttpClient client = new DefaultHttpClient(); HttpGet getMethod = new HttpGet(new URI(listUri)); try { HttpResponse response = client.execute(getMethod); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } HttpEntity entity = response.getEntity(); if (entity != null) { InputStream stream = entity.getContent(); String charset = null; if (entity.getContentType() != null) { HeaderElement values[] = entity.getContentType().getElements(); if (values.length > 0) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } osd = OSD.parse(stream, charset); } } finally { getMethod.abort(); } return osd; }
Code Sample 2:
public void criarQuestaoDiscursiva(QuestaoDiscursiva q) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO discursiva (id_questao,gabarito) VALUES (?,?)"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setString(2, q.getGabarito()); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } }
|
11
|
Code Sample 1:
protected void copyFile(File src, File dest) throws Exception { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); long transferred = destChannel.transferFrom(srcChannel, 0, srcChannel.size()); if (transferred != srcChannel.size()) throw new Exception("Could not transfer entire file"); srcChannel.close(); destChannel.close(); }
Code Sample 2:
public static List<String> unTar(File tarFile, File directory) throws IOException { List<String> result = new ArrayList<String>(); InputStream inputStream = new FileInputStream(tarFile); TarArchiveInputStream in = new TarArchiveInputStream(inputStream); TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { OutputStream out = new FileOutputStream(new File(directory, entry.getName())); IOUtils.copy(in, out); out.close(); result.add(entry.getName()); entry = in.getNextTarEntry(); } in.close(); return result; }
|
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 FileReader(String filePath, Configuration aConfiguration) throws IOException { file = new File(URLDecoder.decode(filePath, "UTF-8")).getCanonicalFile(); readerConf = aConfiguration; if (file.isDirectory()) { File indexFile = new File(file, "index.php"); File indexFile_1 = new File(file, "index.html"); if (indexFile.exists() && !indexFile.isDirectory()) { file = indexFile; } else if (indexFile_1.exists() && !indexFile_1.isDirectory()) { file = indexFile_1; } else { if (!readerConf.getOption("showFolders").equals("Yes")) { makeErrorPage(503, "Permision denied"); } else { FileOutputStream out = new FileOutputStream(readerConf.getOption("wwwPath") + "/temp/temp.php"); File[] files = file.listFiles(); makeHeader(200, -1, new Date(System.currentTimeMillis()).toString(), "text/html"); String title = "Index of " + file; out.write(("<html><head><title>" + title + "</title></head><body><h3>Index of " + file + "</h3><p>\n").getBytes()); for (int i = 0; i < files.length; i++) { file = files[i]; String filename = file.getName(); String description = ""; if (file.isDirectory()) { description = "<DIR>"; } out.write(("<a href=\"" + file.getPath().substring(readerConf.getOption("wwwPath").length()) + "\">" + filename + "</a> " + description + "<br>\n").getBytes()); } out.write(("</p><hr><p>yawwwserwer</p></body><html>").getBytes()); file = new File(URLDecoder.decode(readerConf.getOption("wwwPath") + "/temp/temp.php", "UTF-8")).getCanonicalFile(); } } } else if (!file.exists()) { makeErrorPage(404, "File Not Found."); } else if (getExtension() == ".exe" || getExtension().contains(".py")) { FileOutputStream out = new FileOutputStream(readerConf.getOption("wwwPath") + "/temp/temp.php"); out.write((runCommand(filePath)).getBytes()); file = new File(URLDecoder.decode(readerConf.getOption("wwwPath") + "/temp/temp.php", "UTF-8")).getCanonicalFile(); } else { System.out.println(getExtension()); makeHeader(200, file.length(), new Date(file.lastModified()).toString(), TYPES.get(getExtension()).toString()); } System.out.println(file); }
|
00
|
Code Sample 1:
public void downloadClicked() { String s_url; try { double minlat = Double.parseDouble(minLat.text()); double maxlat = Double.parseDouble(maxLat.text()); double minlong = Double.parseDouble(minLong.text()); double maxlong = Double.parseDouble(maxLong.text()); s_url = "http://www.openstreetmap.org/api/0.5/map?bbox=" + minlong + "," + minlat + "," + maxlong + "," + maxlat; } catch (Exception e) { QMessageBox.critical(this, "Coordinates Error", "Please check the coordinates entered. Make sure to use proper float values."); return; } try { mylayout.removeWidget(dataWidget); dataWidget.hide(); mylayout.addWidget(downloadWidget, 0, 0, 1, 4); downloadWidget.show(); repaint(); update(); URL url = new URL(s_url); HttpURLConnection con = (HttpURLConnection) url.openConnection(); new Osm2Model(con.getInputStream()); mainapp.setStatusbarText("OSM data successful imported", 1000); mainapp.activateMapDisplay(); hide(); } catch (MalformedURLException e) { QMessageBox.critical(this, "OSM import failed", "Data could not be retrieved as download URL is erroneos."); } catch (IOException e) { QMessageBox.critical(this, "OSM import failed", "I/O error, aborting."); } mylayout.removeWidget(downloadWidget); downloadWidget.hide(); mylayout.addWidget(dataWidget, 0, 0, 1, 4); dataWidget.show(); }
Code Sample 2:
private static String md5(String text) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes("UTF-8")); byte[] messageDigest = digest.digest(); StringBuilder hexString = new StringBuilder(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
|
11
|
Code Sample 1:
public String getResource(String resourceName) throws IOException { InputStream resourceStream = resourceClass.getResourceAsStream(resourceName); ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); IOUtils.copyAndClose(resourceStream, baos); String expected = new String(baos.toByteArray()); return expected; }
Code Sample 2:
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(); } } }
|
11
|
Code Sample 1:
public MoteDeploymentConfiguration updateMoteDeploymentConfiguration(int mdConfigID, int programID, int radioPowerLevel) throws AdaptationException { MoteDeploymentConfiguration mdc = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "UPDATE MoteDeploymentConfigurations SET " + "programID = " + programID + ", " + "radioPowerLevel = " + radioPowerLevel + " " + "WHERE id = " + mdConfigID; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from MoteDeploymentConfigurations WHERE " + "id = " + mdConfigID; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Unable to select updated config."; log.error(msg); ; throw new AdaptationException(msg); } mdc = getMoteDeploymentConfiguration(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in updateMoteDeploymentConfiguration"; 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 mdc; }
Code Sample 2:
public void render(RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException { Writer out = null; PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { out = renderResponse.getWriter(); if (log.isDebugEnabled()) log.debug("Start commit new image"); AuthSession auth_ = (AuthSession) renderRequest.getUserPrincipal(); if (auth_ == null || !auth_.isUserInRole("webmill.upload_image")) { throw new PortletSecurityException("You have not enough right"); } dbDyn = DatabaseAdapter.getInstance(); if (log.isDebugEnabled()) log.debug("urlString - " + renderRequest.getParameter("url_download")); String urlString = renderRequest.getParameter("url_download").trim(); if (urlString == null) throw new IllegalArgumentException("id_firm not initialized"); if (log.isDebugEnabled()) log.debug("result url_download " + urlString); String ext[] = { ".jpg", ".jpeg", ".gif", ".png" }; int i; for (i = 0; i < ext.length; i++) { if ((ext[i] != null) && urlString.toLowerCase().endsWith(ext[i].toLowerCase())) break; } if (i == ext.length) throw new UploadFileException("Unsupported file extension. Error #20.03"); if (log.isDebugEnabled()) log.debug("id_main - " + PortletService.getLong(renderRequest, "id_main")); Long id_main = PortletService.getLong(renderRequest, "id_main"); if (id_main == null) throw new IllegalArgumentException("id_firm not initialized"); String desc = RequestTools.getString(renderRequest, "d"); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_image_number_file"); seq.setTableName("MAIN_FORUM_THREADS"); seq.setColumnName("ID_THREAD"); Long currID = dbDyn.getSequenceNextValue(seq); String storage_ = portletConfig.getPortletContext().getRealPath("/") + File.separatorChar + "image"; String fileName = storage_ + File.separatorChar; if (log.isDebugEnabled()) log.debug("filename - " + fileName); URL url = new URL(urlString); File fileUrl = new File(url.getFile()); if (log.isDebugEnabled()) log.debug("fileUrl - " + fileUrl); String newFileName = StringTools.appendString("" + currID, '0', 7, true) + "-" + fileUrl.getName(); if (log.isDebugEnabled()) log.debug("newFileName " + newFileName); fileName += newFileName; if (log.isDebugEnabled()) log.debug("file to write " + fileName); InputStream is = url.openStream(); FileOutputStream fos = new FileOutputStream(new File(fileName)); byte bytes[] = new byte[1000]; int count = 0; while ((count = is.read(bytes)) != -1) { fos.write(bytes, 0, count); } fos.close(); fos = null; is.close(); is = null; url = null; out.write(DateUtils.getCurrentDate("dd-MMMM-yyyy HH:mm:ss:SS", renderRequest.getLocale()) + "<br>"); ps = dbDyn.prepareStatement("insert into WM_IMAGE_DIR " + "( id_image_dir, ID_FIRM, is_group, id, id_main, name_file, description )" + "(select seq_WM_IMAGE_DIR.nextval, ID_FIRM, 0, ?, ?, ?, ? " + " from WM_AUTH_USER where user_login = ? )"); RsetTools.setLong(ps, 1, currID); RsetTools.setLong(ps, 2, id_main); ps.setString(3, "/image/" + newFileName); ps.setString(4, desc); ps.setString(5, auth_.getUserLogin()); ps.executeUpdate(); dbDyn.commit(); out.write("�������� ������ ������ ��� ������<br>" + "�������� ���� " + newFileName + "<br>" + DateUtils.getCurrentDate("dd-MMMM-yyyy HH:mm:ss:SS", renderRequest.getLocale()) + "<br>" + "<br>" + "<p><a href=\"" + PortletService.url("mill.image.index", renderRequest, renderResponse) + "\">��������� ������ ��������</a></p><br>" + "<p><a href=\"" + PortletService.url(ContainerConstants.CTX_TYPE_INDEX, renderRequest, renderResponse) + "\">�� ������� ��������</a></p>"); } catch (Exception e) { try { dbDyn.rollback(); } catch (Exception e1) { } final String es = "Error upload image from url"; log.error(es, e); throw new PortletException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
|
00
|
Code Sample 1:
private static String getData(String myurl) throws Exception { URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); if (login) { uc.setRequestProperty("Cookie", usercookie + ";" + pwdcookie); } br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { k += temp; } br.close(); return k; }
Code Sample 2:
public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) { h = "0" + h; } hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
|
00
|
Code Sample 1:
public static void main(String[] args) { try { boolean readExp = Utils.getFlag('l', args); final boolean writeExp = Utils.getFlag('s', args); final String expFile = Utils.getOption('f', args); if ((readExp || writeExp) && (expFile.length() == 0)) { throw new Exception("A filename must be given with the -f option"); } Experiment exp = null; if (readExp) { FileInputStream fi = new FileInputStream(expFile); ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(fi)); exp = (Experiment) oi.readObject(); oi.close(); } else { exp = new Experiment(); } System.err.println("Initial Experiment:\n" + exp.toString()); final JFrame jf = new JFrame("Weka Experiment Setup"); jf.getContentPane().setLayout(new BorderLayout()); final SetupPanel sp = new SetupPanel(); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.err.println("\nFinal Experiment:\n" + sp.m_Exp.toString()); if (writeExp) { try { FileOutputStream fo = new FileOutputStream(expFile); ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(fo)); oo.writeObject(sp.m_Exp); oo.close(); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Couldn't write experiment to: " + expFile + '\n' + ex.getMessage()); } } jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); System.err.println("Short nap"); Thread.currentThread().sleep(3000); System.err.println("Done"); sp.setExperiment(exp); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } }
Code Sample 2:
public boolean setTraceUrl(String s) { try { url = new URL(s); istream = url.openConnection(); last_contentLenght = 0; reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); } catch (MalformedURLException malformedurlexception) { System.out.println("Trace2Png: MalformedURLException: " + s); return false; } catch (IOException ioexception) { System.out.println("Trace2Png: IOException: " + s); return false; } trace = t2pNewTrace(); return true; }
|
00
|
Code Sample 1:
public static void copia(File nombreFuente, File nombreDestino) throws IOException { FileInputStream fis = new FileInputStream(nombreFuente); FileOutputStream fos = new FileOutputStream(nombreDestino); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); }
Code Sample 2:
public static void main(String args[]) { int i, j, l; short NUMNUMBERS = 256; short numbers[] = new short[NUMNUMBERS]; Darjeeling.print("START"); for (l = 0; l < 100; l++) { for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i); for (i = 0; i < NUMNUMBERS; i++) { for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) { short temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Darjeeling.print("END"); }
|
00
|
Code Sample 1:
public Model read(String uri, String base, String lang) { try { URL url = new URL(uri); return read(url.openStream(), base, lang); } catch (IOException e) { throw new OntologyException("I/O error while reading from uri " + uri); } }
Code Sample 2:
void IconmenuItem5_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (getPath() != null && !getPath().equals("")) { jFileChooser1.setCurrentDirectory(new File(getPath())); jFileChooser1.setSelectedFile(new File(getPath())); } if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getPath().lastIndexOf(separator); String imgName = getPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setPath(newPath); if (getDefaultPath() == null || getDefaultPath().equals("")) { String msgString = "E' stata selezionata un'immagine da associare all'IconShape, ma non e' " + "stata selezionata ancora nessun'immagine di default. Imposto quella scelta anche come " + "immagine di default?"; if (JOptionPane.showConfirmDialog(null, msgString.substring(0, Math.min(msgString.length(), getFatherPanel().MAX_DIALOG_MSG_SZ)), "choose one", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { setDefaultPath(newPath); createDefaultImage(); } } createImage(); } }
|
00
|
Code Sample 1:
protected void updateJava2ScriptProject(String prjFolder, String binRelative) { try { File cpFile = new File(prjFolder, ".classpath"); FileInputStream fis = new FileInputStream(cpFile); String classpath = J2SLaunchingUtil.readAFile(fis); if (classpath != null) { boolean needUpdate = false; if (classpath.indexOf("ECLIPSE_SWT") == -1 && classpath.indexOf("SWT_LIBRARY") == -1 && classpath.indexOf("eclipse.swt") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry kind=\"var\" path=\"ECLIPSE_SWT\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_SWT") == -1 && classpath.indexOf("ajaxswt.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_SWT_SRC\" kind=\"var\" path=\"AJAX_SWT\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_RPC") == -1 && classpath.indexOf("ajaxrpc.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_RPC_SRC\" kind=\"var\" path=\"AJAX_RPC\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_PIPE") == -1 && classpath.indexOf("ajaxpipe.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_PIPE_SRC\" kind=\"var\" path=\"AJAX_PIPE\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (needUpdate) { try { FileOutputStream fos = new FileOutputStream(cpFile); fos.write(classpath.getBytes("utf-8")); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } File webinf = new File(prjFolder, "WEB-INF"); webinf.mkdir(); new File(webinf, "classes").mkdir(); File lib = new File(webinf, "lib"); lib.mkdir(); IPath newPath = null; URL starterURL = AjaxPlugin.getDefault().getBundle().getEntry(File.separator); String root = "."; try { root = Platform.asLocalURL(starterURL).getFile(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root + "/ajaxrpc.jar"); File rpcFile = new File(newPath.toOSString()); try { FileInputStream is = new FileInputStream(rpcFile); FileOutputStream os = new FileOutputStream(new File(lib, "ajaxrpc.jar")); byte[] buf = new byte[1024]; int read = -1; while ((read = is.read(buf)) != -1) { os.write(buf, 0, read); } os.close(); is.close(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root + "/ajaxpipe.jar"); File pipeFile = new File(newPath.toOSString()); try { FileInputStream is = new FileInputStream(pipeFile); FileOutputStream os = new FileOutputStream(new File(lib, "ajaxpipe.jar")); byte[] buf = new byte[1024]; int read = -1; while ((read = is.read(buf)) != -1) { os.write(buf, 0, read); } os.close(); is.close(); } catch (IOException e1) { e1.printStackTrace(); } StringBuffer buildxml = new StringBuffer(); buildxml.append("<?xml version=\"1.0\"?>\r\n"); buildxml.append("<project name=\"java2script.servlet.pack\" default=\"pack.war\" basedir=\".\">\r\n"); buildxml.append(" <description>Pack Java2Script Servlet Application</description>\r\n"); buildxml.append("\r\n"); String name = new File(prjFolder).getName(); buildxml.append(" <property name=\"java2script.app.name\" value=\"" + name + "\"/>\r\n"); buildxml.append(" <property name=\"bin.folder\" value=\"${basedir}/../" + binRelative + "\"/>\r\n"); buildxml.append("\r\n"); buildxml.append(" <target name=\"pack.war\" depends=\"pack.jar\">\r\n"); buildxml.append(" <tstamp>\r\n"); buildxml.append(" <format property=\"now\" pattern=\"yyyy-MM-dd-HH-mm-ss\"/>\r\n"); buildxml.append(" </tstamp>\r\n"); buildxml.append(" <delete file=\"${basedir}/../${java2script.app.name}.war\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/../${java2script.app.name}.${now}.war\">\r\n"); buildxml.append(" <fileset dir=\"${basedir}/../\">\r\n"); buildxml.append(" <exclude name=\"src/**\"/>\r\n"); buildxml.append(" <exclude name=\"META-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.java\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.class\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append(" <exclude name=\".classpath\"/>\r\n"); buildxml.append(" <exclude name=\".project\"/>\r\n"); buildxml.append(" <exclude name=\".j2s\"/>\r\n"); buildxml.append(" <exclude name=\"web.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.properties\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" <fileset dir=\"${basedir}/..\">\r\n"); buildxml.append(" <include name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"WEB-INF/build.xml\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" <copy file=\"${basedir}/../${java2script.app.name}.${now}.war\"\r\n"); buildxml.append(" tofile=\"${basedir}/../${java2script.app.name}.war\"/>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); buildxml.append(" <target name=\"pack.jar\">\r\n"); buildxml.append(" <delete file=\"${basedir}/lib/${java2script.app.name}.jar\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/lib/${java2script.app.name}.jar\">\r\n"); buildxml.append(" <fileset dir=\"${bin.folder}\">\r\n"); buildxml.append(" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.html\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.js\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.css\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.bmp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.gif\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.png\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jpg\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jpeg\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append(" <exclude name=\".classpath\"/>\r\n"); buildxml.append(" <exclude name=\".project\"/>\r\n"); buildxml.append(" <exclude name=\".j2s\"/>\r\n"); buildxml.append(" <exclude name=\"web.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.properties\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); starterURL = AjaxPlugin.getDefault().getBundle().getEntry(File.separator); root = "."; try { root = Platform.asLocalURL(starterURL).getFile(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root); String ajaxPath = newPath.toOSString(); String key = "net.sf.j2s.ajax"; int idx = ajaxPath.lastIndexOf(key); if (idx != -1) { ajaxPath = ajaxPath.substring(0, idx) + "net.sf.j2s.lib" + ajaxPath.substring(idx + key.length()); } File libFile = new File(ajaxPath); String j2sRelativePath = FileUtil.toRelativePath(libFile.getAbsolutePath(), webinf.getAbsolutePath()); if (j2sRelativePath.length() > 0 && !j2sRelativePath.endsWith("/")) { j2sRelativePath += "/"; } int slashIndex = j2sRelativePath.lastIndexOf('/', j2sRelativePath.length() - 2); String pluginPath = j2sRelativePath.substring(0, slashIndex); String libPluginPath = j2sRelativePath.substring(slashIndex + 1, j2sRelativePath.length() - 1); buildxml.append(" <target name=\"pack.plugins.j2slib.war\">\r\n"); buildxml.append(" <delete file=\"${basedir}/../plugins.war\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/../plugins.war\">\r\n"); buildxml.append(" <fileset dir=\"${basedir}/" + pluginPath + "/\">\r\n"); buildxml.append(" <include name=\"" + libPluginPath + "/**\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/library.jar\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/META-INF/**\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); buildxml.append("</project>\r\n"); try { FileOutputStream fos = new FileOutputStream(new File(webinf, "build.xml")); fos.write(buildxml.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } StringBuffer webxml = new StringBuffer(); webxml.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n"); webxml.append("<!DOCTYPE web-app\r\n"); webxml.append(" PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\r\n"); webxml.append(" \"http://java.sun.com/dtd/web-app_2_3.dtd\">\r\n"); webxml.append("<web-app>\r\n"); webxml.append(" <display-name>Java2Script</display-name>\r\n"); webxml.append(" <description>Java2Script application</description>\r\n"); webxml.append(genereateServlet("simplerpc", "net.sf.j2s.ajax.SimpleRPCHttpServlet")); webxml.append(genereateServlet("piperpc", "net.sf.j2s.ajax.CompoundPipeRPCHttpServlet")); webxml.append(" <servlet>\r\n"); webxml.append(" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append(" <servlet-class>net.sf.j2s.ajax.SimplePipeHttpServlet</servlet-class>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.query.timeout</param-name>\r\n"); webxml.append(" <param-value>20000</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.script.breakout</param-name>\r\n"); webxml.append(" <param-value>1200000</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.max.items.per.query</param-name>\r\n"); webxml.append(" <param-value>60</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" </servlet>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>simplerpc</servlet-name>\r\n"); webxml.append(" <url-pattern>/simplerpc</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>piperpc</servlet-name>\r\n"); webxml.append(" <url-pattern>/piperpc</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append(" <url-pattern>/simplepipe</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append("</web-app>\r\n"); try { FileOutputStream fos = new FileOutputStream(new File(webinf, "web.xml")); fos.write(webxml.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } }
Code Sample 2:
private void jbInit() throws Exception { getContentPane().setLayout(borderLayout1); this.setTitle("�ϥλ���"); jTextPane1.setEditable(false); this.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); jScrollPane1.getViewport().add(jTextPane1); this.setSize(400, 600); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); URL url = ReadmeFrame.class.getResource("readme.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder strBuilder = new StringBuilder(); while (reader.ready()) { strBuilder.append(reader.readLine()); strBuilder.append('\n'); } reader.close(); jTextPane1.setText(strBuilder.toString()); }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
@Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException, NotAuthorizedException, BadRequestException, NotFoundException { try { resolveFileAttachment(); } catch (NoFileByTheIdException e) { throw new NotFoundException(e.getLocalizedMessage()); } DefinableEntity owningEntity = fa.getOwner().getEntity(); InputStream in = getFileModule().readFile(owningEntity.getParentBinder(), owningEntity, fa); try { if (range != null) { if (logger.isDebugEnabled()) logger.debug("sendContent: ranged content: " + toString(fa)); PartialGetHelper.writeRange(in, range, out); } else { if (logger.isDebugEnabled()) logger.debug("sendContent: send whole file " + toString(fa)); IOUtils.copy(in, out); } out.flush(); } catch (ReadingException e) { throw new IOException(e); } catch (WritingException e) { throw new IOException(e); } finally { IOUtils.closeQuietly(in); } }
|
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); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
protected void setUp() throws Exception { this.testOutputDirectory = new File(getClass().getResource("/").getPath()); this.pluginFile = new File(this.testOutputDirectory, "/plugin.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(pluginFile)); zos.putNextEntry(new ZipEntry("WEB-INF/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/lib/")); zos.putNextEntry(new ZipEntry("WEB-INF/lib/plugin.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/plugin.jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); jos.putNextEntry(new ZipEntry("vqwiki/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/system.properties")); System.getProperties().store(jos, null); jos.closeEntry(); jos.close(); IOUtils.copy(new FileInputStream(jarFile), zos); zos.closeEntry(); zos.close(); jarFile.delete(); pcl = new PluginClassLoader(new File(testOutputDirectory, "/work")); pcl.addPlugin(pluginFile); }
|
11
|
Code Sample 1:
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = getServletContext(); String forw = null; try { int maxUploadSize = 50000000; MultipartRequest multi = new MultipartRequest(request, ".", maxUploadSize); String descrizione = multi.getParameter("text"); File myFile = multi.getFile("uploadfile"); String filePath = multi.getOriginalFileName("uploadfile"); String path = "C:\\files\\"; try { FileInputStream inStream = new FileInputStream(myFile); FileOutputStream outStream = new FileOutputStream(path + myFile.getName()); while (inStream.available() > 0) { outStream.write(inStream.read()); } inStream.close(); outStream.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } forw = "../sendDoc.jsp"; request.setAttribute("contentType", context.getMimeType(path + myFile.getName())); request.setAttribute("text", descrizione); request.setAttribute("path", path + myFile.getName()); request.setAttribute("size", Long.toString(myFile.length()) + " Bytes"); RequestDispatcher rd = request.getRequestDispatcher(forw); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } }
|
00
|
Code Sample 1:
public void close() throws IOException { output.flush(); output.close(); FTPClient client = new FTPClient(); if (server == null) { throw new IOException("FTP_SERVER property is missing"); } else { if (port != null) { client.connect(server, Integer.parseInt(port)); } else { client.connect(server); } } if (username != null) { logger.debug("log in as specified user"); client.login(username, password); } else { logger.debug("log in as anonymous"); client.login("anonymous", this.getClass().getName()); } if (binaery) { logger.debug("use binaery mode"); client.setFileType(FTP.BINARY_FILE_TYPE); } else { logger.debug("use ascii mode"); client.setFileType(FTP.ASCII_FILE_TYPE); } client.enterLocalPassiveMode(); logger.debug("store file on server: " + tempFile + " under name: " + file); InputStream stream = new FileInputStream(tempFile); String dir = file.substring(0, file.lastIndexOf("/")) + "/"; String split[] = dir.split("/"); String last = ""; logger.debug("creating dir: " + dir); for (int i = 0; i < split.length; i++) { last = last + "/" + split[i]; logger.debug(last + " --> " + client.makeDirectory(last)); } logger.debug("storing file: " + file); client.deleteFile(file); client.storeFile(file, stream); client.disconnect(); tempFile.delete(); try { FTPSource source = new FTPSource(); source.configure(properties); source.setIdentifier(file); if (source.exist()) { logger.debug("done"); } else { throw new IOException("can't find file I just wrote, something went wrong!"); } } catch (ConfigurationException e) { throw new IOException(e.getMessage()); } }
Code Sample 2:
public static void main(String[] argv) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (Exception e) { e.printStackTrace(); } md.update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".getBytes(), 0, 56); String exp = "84983E441C3BD26EBAAE4AA1F95129E5E54670F1"; String result = toString(md.digest()); System.out.println(exp); System.out.println(result); if (!exp.equals(result)) System.out.println("NOT EQUAL!"); }
|
11
|
Code Sample 1:
@Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException { String context = request.getContextPath(); String resource = request.getRequestURI().replace(context, ""); resource = resource.replaceAll("^/\\w*/", ""); if ((StringUtils.isEmpty(resource)) || (resource.endsWith("/"))) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } URL url = ClassLoaderUtils.getResource(resource); if (url == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if ((this.deny != null) && (this.deny.length > 0)) { for (String s : this.deny) { s = s.trim(); if (s.indexOf('*') != -1) { s = s.replaceAll("\\*", ".*"); } if (Pattern.matches(s, resource)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } } } InputStream input = url.openStream(); OutputStream output = response.getOutputStream(); URLConnection connection = url.openConnection(); String contentEncoding = connection.getContentEncoding(); int contentLength = connection.getContentLength(); String contentType = connection.getContentType(); if (contentEncoding != null) { response.setCharacterEncoding(contentEncoding); } response.setContentLength(contentLength); response.setContentType(contentType); IOUtils.copy(input, output, true); }
Code Sample 2:
public void command() { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(dir)); int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { filename = chooser.getSelectedFile().getAbsolutePath(); String f2 = ""; for (int i = 0; i < filename.length(); ++i) { if (filename.charAt(i) != '\\') { f2 = f2 + filename.charAt(i); } else f2 = f2 + '/'; } filename = f2; if (filename.contains(dir)) { filename = filename.substring(dir.length()); } else { try { FileChannel srcFile = new FileInputStream(filename).getChannel(); FileChannel dstFile; filename = "ueditor_files/" + chooser.getSelectedFile().getName(); File newFile; if (!(newFile = new File(dir + filename)).createNewFile()) { dstFile = new FileInputStream(dir + filename).getChannel(); newFile = null; } else { dstFile = new FileOutputStream(newFile).getChannel(); } dstFile.transferFrom(srcFile, 0, srcFile.size()); srcFile.close(); dstFile.close(); System.out.println("file copyed to: " + dir + filename); } catch (Exception e) { e.printStackTrace(); label.setIcon(InputText.iconX); filename = null; for (Group g : groups) { g.updateValidity(true); } return; } } label.setIcon(InputText.iconV); for (Group g : groups) { g.updateValidity(true); } } }
|
11
|
Code Sample 1:
private static void unzipEntry(final ZipFile zipfile, final ZipEntry entry, final File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } }
Code Sample 2:
@Test public void testWrite() throws Exception { MrstkXmlFileReader reader = new MrstkXmlFileReader(); reader.setFileName("..//data//MrstkXML//prototype3.xml"); reader.read(); SpectrumArray sp = reader.getOutput(); File tmp = File.createTempFile("mrstktest", ".xml"); System.out.println("Writing temp file: " + tmp.getAbsolutePath()); MrstkXmlFileWriter writer = new MrstkXmlFileWriter(sp); writer.setFile(tmp); writer.write(); MrstkXmlFileReader reader2 = new MrstkXmlFileReader(); reader2.setFileName(writer.getFile().getAbsolutePath()); reader2.read(); SpectrumArray sp2 = reader2.getOutput(); assertTrue(sp.equals(sp2)); }
|
00
|
Code Sample 1:
public static void main(String[] args) { String logConfiguration = args[2]; DOMConfigurator.configure(logConfiguration); String urlToRun = args[0]; String outputFile = args[1]; InputStream conInput = null; BufferedReader reader = null; BufferedWriter writer = null; if (logger.isDebugEnabled()) { logger.debug("output file is " + outputFile); } try { URL url = new URL(urlToRun); URLConnection urlCon = url.openConnection(); urlCon.connect(); conInput = urlCon.getInputStream(); reader = new BufferedReader(new InputStreamReader(conInput)); File output = new File(outputFile); writer = new BufferedWriter(new FileWriter(output)); String line = null; while ((line = reader.readLine()) != null) { logger.debug(line); writer.write(line); } writer.flush(); } catch (MalformedURLException murle) { logger.error(urlToRun + " is not a valid URL", murle); } catch (IOException ioe) { logger.error("IO Error ocured while opening connection to " + urlToRun, ioe); } finally { try { reader.close(); conInput.close(); writer.close(); } catch (IOException ioe) { throw new RuntimeException("Cannot close readers or streams", ioe); } } }
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) { } } }
|
00
|
Code Sample 1:
public static Properties addAttributes(Node node, String[] names, Properties props, LogEvent evt) throws ConfigurationException { if (props == null) props = new Properties(); try { MessageDigest md = MessageDigest.getInstance("MD5"); for (int i = 0; i < names.length; i++) { String value = addProperty(names[i], props, node, evt); if (value != null) { md.update(names[i].getBytes()); md.update(value.getBytes()); } } byte[] digest = md.digest(); evt.addMessage("digest " + ISOUtil.hexString(digest)); props.put(DIGEST_PROPERTY, digest); } catch (NoSuchAlgorithmException e) { throw new ConfigurationException(e); } return props; }
Code Sample 2:
public static void copyFile(IPath fromFileName, IPath toFileName) throws IOException { File fromFile = fromFileName.toFile(); File toFile = toFileName.toFile(); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } InputStream from = null; OutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(fromFile)); to = new BufferedOutputStream(new FileOutputStream(toFile)); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { } if (to != null) try { to.close(); } catch (IOException e) { } } }
|
11
|
Code Sample 1:
public static String encrypt(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw new WebDocRuntimeException(ex); } md.update(text.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); return hash.toString(HEX); }
Code Sample 2:
public static String encryptePassword(String md5key, String passwordAccount, String encryptedPassword, int passwdenc) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(Constants.ALGORITHM); switch(passwdenc) { case 1: md.update((md5key + encryptedPassword).getBytes("8859_1")); break; case 2: md.update((encryptedPassword + md5key).getBytes("8859_1")); break; default: return null; } return new String(md.digest()); }
|
00
|
Code Sample 1:
public void testCodingFromFileSmaller() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff;"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); }
Code Sample 2:
List HttpPost(URL url, List requestList) throws IOException { List responseList = new ArrayList(); URLConnection con; BufferedReader in; OutputStreamWriter out; StringBuffer req; String line; logInfo("HTTP POST: " + url); con = url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); out = new OutputStreamWriter(con.getOutputStream()); req = new StringBuffer(); for (int i = 0, n = requestList.size(); i < n; i++) { if (i != 0) req.append("&"); req.append(((HttpHeader) requestList.get(i)).key); req.append("="); if (((HttpHeader) requestList.get(i)).unicode) { StringBuffer tmp = new StringBuffer(200); byte[] uniBytes = ((HttpHeader) requestList.get(i)).value.getBytes("UnicodeBigUnmarked"); for (int j = 0; j < uniBytes.length; j++) tmp.append(Integer.toHexString(uniBytes[j]).length() == 1 ? "0" + Integer.toHexString(uniBytes[j]) : Integer.toHexString(uniBytes[j])); req.append(tmp.toString().replaceAll("ff", "")); } else req.append(((HttpHeader) requestList.get(i)).value); } out.write(req.toString()); out.flush(); out.close(); in = new BufferedReader(new InputStreamReader((con.getInputStream()))); while ((line = in.readLine()) != null) responseList.add(line); in.close(); return responseList; }
|
11
|
Code Sample 1:
private boolean saveDocumentXml(String repository, String tempRepo) { boolean result = true; try { XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "documents/document"; InputSource insource = new InputSource(new FileInputStream(tempRepo + File.separator + AppConstants.DMS_XML)); NodeList nodeList = (NodeList) xpath.evaluate(expression, insource, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); System.out.println(node.getNodeName()); DocumentModel document = new DocumentModel(); NodeList childs = node.getChildNodes(); for (int j = 0; j < childs.getLength(); j++) { Node child = childs.item(j); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName() != null && child.getFirstChild() != null && child.getFirstChild().getNodeValue() != null) { System.out.println(child.getNodeName() + "::" + child.getFirstChild().getNodeValue()); } if (Document.FLD_ID.equals(child.getNodeName())) { if (child.getFirstChild() != null) { String szId = child.getFirstChild().getNodeValue(); if (szId != null && szId.length() > 0) { try { document.setId(new Long(szId)); } catch (Exception e) { e.printStackTrace(); } } } } else if (document.FLD_NAME.equals(child.getNodeName())) { document.setName(child.getFirstChild().getNodeValue()); document.setTitle(document.getName()); document.setDescr(document.getName()); document.setExt(getExtension(document.getName())); } else if (document.FLD_LOCATION.equals(child.getNodeName())) { document.setLocation(child.getFirstChild().getNodeValue()); } else if (document.FLD_OWNER.equals(child.getNodeName())) { Long id = new Long(child.getFirstChild().getNodeValue()); User user = new UserModel(); user.setId(id); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setOwner(user); } } } } boolean isSave = docService.save(document); if (isSave) { String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File fileFolder = new File(sbRepo.append(sbFolder).toString()); if (!fileFolder.exists()) { fileFolder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(fileFolder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(tempRepo + File.separator + document.getName()).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); document.setSize(fcSource.size()); log.info("Batch upload file " + document.getName() + " into [" + document.getLocation() + "] as " + document.getName() + "." + document.getExt()); folder.setId(DEFAULT_FOLDER); folder = (Folder) folderService.find(folder); if (folder != null && folder.getId() != null) { document.setFolder(folder); } workspace.setId(DEFAULT_WORKSPACE); workspace = (Workspace) workspaceService.find(workspace); if (workspace != null && workspace.getId() != null) { document.setWorkspace(workspace); } user.setId(DEFAULT_USER); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setCrtby(user.getId()); } document.setCrtdate(new Date()); document = (DocumentModel) docService.resetDuplicateDocName(document); docService.save(document); DocumentIndexer.indexDocument(preference, document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } } } catch (Exception e) { result = false; e.printStackTrace(); } return result; }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
public void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), 1024 * 1024 * 32, true, true); fileInputStream.close(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void add(String user, String pass, boolean admin, boolean developer) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String sql; if (contains(stmt, user) == true) { sql = "update Principals set Password = '" + pass + "' " + " where PrincipalId = '" + user + "'"; } else { sql = "insert into Principals (PrincipalId, Password) " + " values ('" + user + "', '" + pass + "')"; } stmt.executeUpdate(sql); updateRoles(stmt, user, admin, developer); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
|
11
|
Code Sample 1:
private static void copySmallFile(File sourceFile, File targetFile) throws BusinessException { LOG.debug("Copying SMALL file '" + sourceFile.getAbsolutePath() + "' to '" + targetFile.getAbsolutePath() + "'."); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(sourceFile).getChannel(); outChannel = new FileOutputStream(targetFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new BusinessException("Could not copy file from '" + sourceFile.getAbsolutePath() + "' to '" + targetFile.getAbsolutePath() + "'!", e); } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { LOG.error("Could not close input stream!", e); } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { LOG.error("Could not close output stream!", e); } } }
Code Sample 2:
private String transferWSDL(String wsdlURL, String userPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (userPassword != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDeployDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
|
00
|
Code Sample 1:
private void copyTemplates(ProjectPath pPath) { String sourceAntPath = pPath.sourceAntPath(); final String moduleName = projectOperations.getFocusedTopLevelPackage().toString(); logger.info("Module Name: " + moduleName); String targetDirectory = pPath.canonicalFileSystemPath(projectOperations); logger.info("Moving into target Directory: " + targetDirectory); if (!targetDirectory.endsWith("/")) { targetDirectory += "/"; } if (!fileManager.exists(targetDirectory)) { fileManager.createDirectory(targetDirectory); } System.out.println("Target Directory: " + pPath.sourceAntPath()); String path = TemplateUtils.getTemplatePath(getClass(), sourceAntPath); Set<URL> urls = UrlFindingUtils.findMatchingClasspathResources(context.getBundleContext(), path); Assert.notNull(urls, "Could not search bundles for resources for Ant Path '" + path + "'"); if (urls.isEmpty()) { logger.info("URLS are empty stopping..."); } for (URL url : urls) { logger.info("Stepping into " + url.toExternalForm()); String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1); fileName = fileName.replace("-template", ""); String targetFilename = targetDirectory + fileName; logger.info("Handling " + targetFilename); if (!fileManager.exists(targetFilename)) { try { logger.info("Copied file"); String input = FileCopyUtils.copyToString(new InputStreamReader(url.openStream())); logger.info("TopLevelPackage: " + projectOperations.getFocusedTopLevelPackage()); logger.info("SegmentPackage: " + pPath.canonicalFileSystemPath(projectOperations)); String topLevelPackage = projectOperations.getFocusedTopLevelPackage().toString(); input = input.replace("__TOP_LEVEL_PACKAGE__", topLevelPackage); input = input.replace("__SEGMENT_PACKAGE__", pPath.segmentPackage()); input = input.replace("__PROJECT_NAME__", projectOperations.getFocusedProjectName()); input = input.replace("__ENTITY_NAME__", entityName); MutableFile mutableFile = fileManager.createFile(targetFilename); FileCopyUtils.copy(input.getBytes(), mutableFile.getOutputStream()); } catch (IOException ioe) { throw new IllegalStateException("Unable to create '" + targetFilename + "'", ioe); } } } }
Code Sample 2:
public void test_digest() throws UnsupportedEncodingException { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA"); assertNotNull(sha); } catch (NoSuchAlgorithmException e) { fail("getInstance did not find algorithm"); } sha.update(MESSAGE.getBytes("UTF-8")); byte[] digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST)); sha.reset(); for (int i = 0; i < 63; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_63_As)); sha.reset(); for (int i = 0; i < 64; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_64_As)); sha.reset(); for (int i = 0; i < 65; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_65_As)); testSerializationSHA_DATA_1(sha); testSerializationSHA_DATA_2(sha); }
|
11
|
Code Sample 1:
public static void copyFile(FileInputStream source, FileOutputStream target) throws Exception { FileChannel inChannel = source.getChannel(); FileChannel outChannel = target.getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
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()); } }
|
11
|
Code Sample 1:
public static void main(String[] args) { try { boolean readExp = Utils.getFlag('l', args); final boolean writeExp = Utils.getFlag('s', args); final String expFile = Utils.getOption('f', args); if ((readExp || writeExp) && (expFile.length() == 0)) { throw new Exception("A filename must be given with the -f option"); } Experiment exp = null; if (readExp) { FileInputStream fi = new FileInputStream(expFile); ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(fi)); exp = (Experiment) oi.readObject(); oi.close(); } else { exp = new Experiment(); } System.err.println("Initial Experiment:\n" + exp.toString()); final JFrame jf = new JFrame("Weka Experiment Setup"); jf.getContentPane().setLayout(new BorderLayout()); final SetupPanel sp = new SetupPanel(); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.err.println("\nFinal Experiment:\n" + sp.m_Exp.toString()); if (writeExp) { try { FileOutputStream fo = new FileOutputStream(expFile); ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(fo)); oo.writeObject(sp.m_Exp); oo.close(); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Couldn't write experiment to: " + expFile + '\n' + ex.getMessage()); } } jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); System.err.println("Short nap"); Thread.currentThread().sleep(3000); System.err.println("Done"); sp.setExperiment(exp); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } }
Code Sample 2:
public static boolean copyFile(File src, File dest) throws IOException { if (src == null) { throw new IllegalArgumentException("src == null"); } if (dest == null) { throw new IllegalArgumentException("dest == null"); } if (!src.isFile()) { return false; } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); try { in.transferTo(0, in.size(), out); return true; } catch (IOException e) { throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws IOException { System.out.println("start"); URL url = new URL("https://spreadsheets.google.com/feeds/list/" + "0AnoMCh3_x82sdERLR3FvVDBIWXpjT1JlcENmOFdERVE/" + "od7/public/basic"); InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { String[] mass = line.split("<entry>"); for (String m : mass) { System.out.println(m); } } }
Code Sample 2:
@Test public void testCopy_inputStreamToWriter_Encoding_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer, "UTF8"); fail(); } catch (NullPointerException ex) { } }
|
00
|
Code Sample 1:
private String callPage(String urlStr) throws IOException { URL url = new URL(urlStr); BufferedReader reader = null; StringBuilder result = new StringBuilder(); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { result.append(line); } } finally { if (reader != null) reader.close(); } return result.toString(); }
Code Sample 2:
public void run() { try { if (FileDenAccount.loginsuccessful) { host = FileDenAccount.username + " | FileDen.com"; } else { host = "FileDen.com"; uploadFailed(); return; } if (file.length() > 1073741824) { JOptionPane.showMessageDialog(neembuuuploader.NeembuuUploader.getInstance(), "<html><b>" + getClass().getSimpleName() + "</b> " + TranslationProvider.get("neembuuuploader.uploaders.maxfilesize") + ": <b>1GB</b></html>", getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE); uploadFailed(); return; } file_ext = file.getName().substring(file.getName().lastIndexOf(".") + 1); String[] unsupported = new String[] { "html", "htm", "php", "php3", "phtml", "htaccess", "htpasswd", "cgi", "pl", "asp", "aspx", "cfm", "exe", "ade", "adp", "bas", "bat", "chm", "cmd", "com", "cpl", "crt", "hlp", "hta", "inf", "ins", "isp", "jse", "lnk", "mdb", "mde", "msc", "msi", "msp", "mst", "pcd", "pif", "reg", "scr", "sct", "shs", "url", "vbe", "vbs", "wsc", "wsf", "wsh", "shb", "js", "vb", "ws", "mdt", "mdw", "mdz", "shb", "scf", "pl", "pm", "dll" }; for (int i = 0; i < unsupported.length; i++) { if (file_ext.equalsIgnoreCase(unsupported[i])) { file_extension_not_supported = true; break; } } if (file_extension_not_supported) { JOptionPane.showMessageDialog(neembuuuploader.NeembuuUploader.getInstance(), "<html><b>" + getClass().getSimpleName() + "</b> " + TranslationProvider.get("neembuuuploader.uploaders.filetypenotsupported") + ": <b>" + file_ext + "</b></html>", getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE); uploadFailed(); return; } status = UploadStatus.INITIALISING; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.fileden.com/upload_old.php"); httppost.setHeader("Cookie", FileDenAccount.getCookies().toString()); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("action", new StringBody("upload")); mpEntity.addPart("upload_to", new StringBody("")); mpEntity.addPart("overwrite_option", new StringBody("overwrite")); mpEntity.addPart("thumbnail_size", new StringBody("small")); mpEntity.addPart("create_img_tags", new StringBody("1")); mpEntity.addPart("file0", new MonitoredFileBody(file, uploadProgress)); httppost.setEntity(mpEntity); NULogger.getLogger().log(Level.INFO, "executing request {0}", httppost.getRequestLine()); NULogger.getLogger().info("Now uploading your file into fileden"); status = UploadStatus.UPLOADING; HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); NULogger.getLogger().info(response.getStatusLine().toString()); status = UploadStatus.GETTINGLINK; if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } NULogger.getLogger().info(uploadresponse); downloadlink = CommonUploaderTasks.parseResponse(uploadresponse, "'link':'", "'"); NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink); downURL = downloadlink; httpclient.getConnectionManager().shutdown(); uploadFinished(); } catch (Exception e) { Logger.getLogger(RapidShare.class.getName()).log(Level.SEVERE, null, e); uploadFailed(); } }
|
00
|
Code Sample 1:
public static final String getUniqueKey() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; ; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { println("Warn: getUniqueKey(), Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { println("Warn: getUniqueKey() " + e); } return digest; }
Code Sample 2:
public void testStorageString() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); r.addText("This is an example"); r.addText(" and another one."); assertEquals("This is an example and another one.", r.getText()); InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); try { r.getOutputStream(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } try { r.getWriter(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); }
|
00
|
Code Sample 1:
@Override public byte[] read(String path) throws PersistenceException { path = fmtPath(path); try { S3Object fileObj = s3Service.getObject(bucketObj, path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(fileObj.getDataInputStream(), out); return out.toByteArray(); } catch (Exception e) { throw new PersistenceException("fail to read s3 file - " + path, e); } }
Code Sample 2:
private Image2D resolvePNG(URI uri) { Image2D image2D = null; if (uri.getScheme() != null) { try { URL url = new URL(uri.toString()); InputStream is = url.openStream(); BufferedImage image = PNGDecoder.decode(is); int imageType = Image2D.RGB; if (image.getType() == BufferedImage.TYPE_INT_RGB) imageType = Image2D.RGB; else if (image.getType() == BufferedImage.TYPE_INT_ARGB) imageType = Image2D.RGBA; image2D = new Image2D(imageType, image); } catch (IOException ex) { } } else { String path = uri.getPath(); File file = new File(path); if (file.getAbsoluteFile().exists()) { try { FileInputStream is = new FileInputStream(file); BufferedImage image = PNGDecoder.decode(is); int imageType = Image2D.RGB; if (image.getType() == BufferedImage.TYPE_INT_RGB) imageType = Image2D.RGB; else if (image.getType() == BufferedImage.TYPE_INT_ARGB) imageType = Image2D.RGBA; image2D = new Image2D(imageType, image); } catch (FileNotFoundException ex) { } catch (IOException ex) { } } } return image2D; }
|
11
|
Code Sample 1:
@Test public void testTrainingDefault() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
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 in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public int download(String fileName) { OutputStream out = null; URLConnection conn = null; InputStream in = null; int numRead = 0; int totalRead = 0; try { URL url = new URL(URL); out = new BufferedOutputStream(new FileOutputStream(fileName)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); totalRead += numRead; } } catch (IOException exception) { totalRead = 0; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } return totalRead; } }
|
11
|
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:
@Override public User login(String username, String password) { User user = null; try { user = (User) em.createQuery("Select o from User o where o.username = :username").setParameter("username", username).getSingleResult(); } catch (NoResultException e) { throw new NestedException(e.getMessage(), e); } try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(password.getBytes("UTF-8")); byte[] hash = digest.digest(); BigInteger bigInt = new BigInteger(1, hash); String hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } if (hashtext.equals(user.getPassword())) return user; } catch (Exception e) { throw new NestedException(e.getMessage(), e); } return null; }
|
00
|
Code Sample 1:
public void get(File fileToGet) throws IOException { String fileName = fileToGet.getName(); URL url = new URL(this.endpointURL + fileName); URLConnection connection = url.openConnection(); InputStream input = connection.getInputStream(); log.debug("get: " + fileName); try { FileOutputStream fileStream = new FileOutputStream(fileToGet); byte[] bt = new byte[10000]; int cnt = input.read(bt); log.debug("Read bytes: " + cnt); while (cnt != -1) { fileStream.write(bt, 0, cnt); cnt = input.read(bt); } input.close(); fileStream.close(); } catch (IOException e) { new File(fileName).delete(); throw e; } }
Code Sample 2:
public static void main(String[] args) { String logConfiguration = args[2]; DOMConfigurator.configure(logConfiguration); String urlToRun = args[0]; String outputFile = args[1]; InputStream conInput = null; BufferedReader reader = null; BufferedWriter writer = null; if (logger.isDebugEnabled()) { logger.debug("output file is " + outputFile); } try { URL url = new URL(urlToRun); URLConnection urlCon = url.openConnection(); urlCon.connect(); conInput = urlCon.getInputStream(); reader = new BufferedReader(new InputStreamReader(conInput)); File output = new File(outputFile); writer = new BufferedWriter(new FileWriter(output)); String line = null; while ((line = reader.readLine()) != null) { logger.debug(line); writer.write(line); } writer.flush(); } catch (MalformedURLException murle) { logger.error(urlToRun + " is not a valid URL", murle); } catch (IOException ioe) { logger.error("IO Error ocured while opening connection to " + urlToRun, ioe); } finally { try { reader.close(); conInput.close(); writer.close(); } catch (IOException ioe) { throw new RuntimeException("Cannot close readers or streams", ioe); } } }
|
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); } catch (IOException e) { throw e; } 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(); } }
|
00
|
Code Sample 1:
public static String hash(String text) throws Exception { StringBuffer hexString; MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(text.getBytes()); byte[] digest = mdAlgorithm.digest(); hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { text = Integer.toHexString(0xFF & digest[i]); if (text.length() < 2) { text = "0" + text; } hexString.append(text); } return hexString.toString(); }
Code Sample 2:
public static void call(String host, String port, String method, String[] params) { cat.debug("call (host:" + host + " port:" + port + " method:" + method); try { String message = null; StringBuffer bufMessage = new StringBuffer(); bufMessage.append("<?xml version='1.0' encoding='ISO-8859-1'?>"); bufMessage.append("<methodCall>"); bufMessage.append("<methodName>"); bufMessage.append(method); bufMessage.append("</methodName>"); bufMessage.append("<params>"); if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { bufMessage.append("<param><value><![CDATA[" + params[i] + "]]></value></param>"); } } bufMessage.append("</params></methodCall>"); message = bufMessage.toString(); bufMessage = null; String stringUrl = "http://" + host + ":" + port + "/RPC2"; cat.debug("Sending message to: " + stringUrl + "\n" + message); URL url = new URL(stringUrl); URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); urlConnection.getOutputStream().write(message.getBytes()); urlConnection.getOutputStream().flush(); urlConnection.getOutputStream().close(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { cat.debug("#server# " + line); } bufferedReader.close(); } catch (Exception e) { cat.debug("Unable to send link to Gnowsis!", e); } }
|
00
|
Code Sample 1:
public void storeModule(OWLModuleManager manager, Module module, URI physicalURI, OWLModuleFormat moduleFormat) throws ModuleStorageException, UnknownModuleException { try { OutputStream os; if (!physicalURI.isAbsolute()) { throw new ModuleStorageException("Physical URI must be absolute: " + physicalURI); } if (physicalURI.getScheme().equals("file")) { File file = new File(physicalURI); file.getParentFile().mkdirs(); os = new FileOutputStream(file); } else { URL url = physicalURI.toURL(); URLConnection conn = url.openConnection(); os = conn.getOutputStream(); } Writer w = new BufferedWriter(new OutputStreamWriter(os)); storeModule(manager, module, w, moduleFormat); } catch (IOException e) { throw new ModuleStorageException(e); } }
Code Sample 2:
public InputSource resolveEntity(String pPublicId, String pSystemId) throws SAXException, IOException { getCisUtils().debug("Resolving entity publicId=" + pPublicId + ", systemId=" + pSystemId); final String res; if ("-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN".equals(pPublicId)) { res = "resources/web-app_2_3.dtd"; } else { return null; } URL url = getClass().getResource(res); if (url == null) { throw new SAXException("Failed to locate resource: " + res); } InputSource isource = new InputSource(url.openStream()); isource.setSystemId(url.toExternalForm()); return isource; }
|
11
|
Code Sample 1:
@Override public void run() { try { IOUtils.copy(getSource(), processStdIn); System.err.println("Copy done."); close(); } catch (IOException e) { e.printStackTrace(); IOUtils.closeQuietly(ExternalDecoder.this); } }
Code Sample 2:
public void generate(FileObject outputDirectory, FileObject generatedOutputDirectory, List<Library> libraryModels, String tapdocXml) throws FileSystemException { if (!generatedOutputDirectory.exists()) { generatedOutputDirectory.createFolder(); } if (outputDirectory.exists()) { outputDirectory.createFolder(); } ZipUtils.extractZip(new ClasspathResource(classResolver, "/com/erinors/tapestry/tapdoc/service/xdoc/resources.zip"), outputDirectory); for (Library library : libraryModels) { String libraryName = library.getName(); String libraryLocation = library.getLocation(); generatedOutputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).createFolder(); try { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Library.xsl"), "libraryName", libraryName); FileObject index = generatedOutputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).resolveFile("index.xml"); Writer out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } catch (Exception e) { throw new RuntimeException(e); } for (Component component : library.getComponents()) { String componentName = component.getName(); System.out.println("Generating " + libraryName + ":" + componentName + "..."); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("libraryName", libraryName); parameters.put("componentName", componentName); String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Component.xsl"), parameters); Writer out = null; try { FileObject index = generatedOutputDirectory.resolveFile(fileNameGenerator.getComponentIndexFile(libraryLocation, componentName, true)); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); Resource specificationLocation = component.getSpecificationLocation(); if (specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL() != null) { File srcResourcesDirectory = new File(specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL().toURI()); FileObject dstResourcesFileObject = outputDirectory.resolveFile(fileNameGenerator.getComponentDirectory(libraryLocation, componentName)).resolveFile("resource"); if (srcResourcesDirectory.exists() && srcResourcesDirectory.isDirectory()) { File[] files = srcResourcesDirectory.listFiles(); if (files != null) { for (File resource : files) { if (resource.isFile() && !resource.isHidden()) { FileObject resourceFileObject = dstResourcesFileObject.resolveFile(resource.getName()); resourceFileObject.createFile(); InputStream inResource = null; OutputStream outResource = null; try { inResource = new FileInputStream(resource); outResource = resourceFileObject.getContent().getOutputStream(); IOUtils.copy(inResource, outResource); } finally { IOUtils.closeQuietly(inResource); IOUtils.closeQuietly(outResource); } } } } } } } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); } } } { Writer out = null; try { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Overview.xsl")); FileObject index = generatedOutputDirectory.resolveFile("index.xml"); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); } } }
|
00
|
Code Sample 1:
public static OutputStream getOutputStream(String path) throws ResourceException { URL url = getURL(path); if (url != null) { try { return url.openConnection().getOutputStream(); } catch (IOException e) { throw new ResourceException(e); } } else { throw new ResourceException("Error obtaining resource, invalid path: " + path); } }
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 String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; FormFile file = vo.getFile(); String inforId = request.getParameter("inforId"); System.out.println("inforId=" + inforId); if (file != null) { String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); if (file.getFileSize() != 0) { file.getInputStream(); String name = file.getFileName(); String fullPath = realpath + "attach/" + strAppend + name; t_attach attach = new t_attach(); attach.setAttach_fullname(fullPath); attach.setAttach_name(name); attach.setInfor_id(Integer.parseInt(inforId)); attach.setInsert_day(new Date()); attach.setUpdate_day(new Date()); t_attach_EditMap attachEdit = new t_attach_EditMap(); attachEdit.add(attach); File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(file.getInputStream(), out); out.close(); System.out.println("file name is :" + name); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); System.out.println("in the end...."); return "aftersave"; }
Code Sample 2:
public static void zipDirectory(String dir, String zipfile) throws IOException, IllegalArgumentException { File d = new File(dir); if (!d.isDirectory()) throw new IllegalArgumentException("Not a directory: " + dir); String[] entries = d.list(); byte[] buffer = new byte[4096]; int bytesRead; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); for (int i = 0; i < entries.length; i++) { File f = new File(d, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getPath()); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); }
|
00
|
Code Sample 1:
List<String> options(String path) throws TwinException { try { BasicHttpRequest request = new BasicHttpRequest("OPTIONS", url + path); HttpClient client = getClient(); HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request); Header hdr = response.getFirstHeader("Allow"); if (hdr == null || hdr.getValue().isEmpty()) return Collections.emptyList(); return Arrays.asList(hdr.getValue().split("\\s*,\\s*")); } catch (IOException e) { throw TwinError.UnknownError.create("IOException when accessing RC", e); } }
Code Sample 2:
public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
00
|
Code Sample 1:
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(); }
Code Sample 2:
private List<Document> storeDocuments(List<Document> documents) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); List<Document> newDocuments = new ArrayList<Document>(); try { session.beginTransaction(); Preference preference = new PreferenceModel(); preference = (Preference) preference.doList(preference).get(0); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); if (documents != null && !documents.isEmpty()) { for (Iterator<Document> iter = documents.iterator(); iter.hasNext(); ) { Document document = iter.next(); if (AppConstants.STATUS_ACTIVE.equals(document.getStatus())) { try { document = (Document) preAdd(document, getParams()); File fileIn = new File(preference.getScanLocation() + File.separator + document.getName()); File fileOut = new File(preference.getStoreLocation() + File.separator + document.getName()); FileInputStream in = new FileInputStream(fileIn); FileOutputStream out = new FileOutputStream(fileOut); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); document.doAdd(document); boolean isDeleted = fileIn.delete(); System.out.println("Deleted scan folder file: " + document.getName() + ":" + isDeleted); if (isDeleted) { document.setStatus(AppConstants.STATUS_PROCESSING); int uploadCount = 0; if (document.getUploadCount() != null) { uploadCount = document.getUploadCount(); } uploadCount++; document.setUploadCount(uploadCount); newDocuments.add(document); } } catch (Exception add_ex) { add_ex.printStackTrace(); } } else if (AppConstants.STATUS_PROCESSING.equals(document.getStatus())) { int uploadCount = document.getUploadCount(); if (uploadCount < 5) { uploadCount++; document.setUploadCount(uploadCount); System.out.println("increase upload count: " + document.getName() + ":" + uploadCount); newDocuments.add(document); } else { System.out.println("delete from documents list: " + document.getName()); } } else if (AppConstants.STATUS_INACTIVE.equals(document.getStatus())) { document.setFixFlag(AppConstants.FLAG_NO); newDocuments.add(document); } } } } catch (Exception ex) { ex.printStackTrace(); } return newDocuments; }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private String getHash(String string) { Monitor hashTime = JamonMonitorLogger.getTimeMonitor(Cache.class, "HashTime").start(); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.reset(); md5.update(string.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } String str = hexString.toString(); hashTime.stop(); return str; }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
private void fillTemplate(String resource, OutputStream outputStream, Map<String, String> replacements) throws IOException { URL url = Tools.getResource(resource); if (url == null) { throw new IOException("could not find resource"); } BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8"))); String line = null; do { line = reader.readLine(); if (line != null) { for (String key : replacements.keySet()) { String value = replacements.get(key); if (key != null) { line = line.replace(key, value); } } writer.write(line); writer.newLine(); } } while (line != null); reader.close(); writer.close(); }
|
00
|
Code Sample 1:
public Object invoke(Invocation invocation) throws Throwable { SmartRef smartRef = (SmartRef) invocation.getValue(Invocation.SMARTREF); HttpURLConnection connection = null; ObjectOutputStream out = null; URL url = null; try { url = new URL(smartRef.getProperties().getProperty("org.smartcc.connector.url")); url = new URL(url, smartRef.getLookup()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Content-Type", "application/octet-stream"); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); out = new ObjectOutputStream(connection.getOutputStream()); out.writeObject(invocation); out.flush(); } catch (ObjectStreamException e) { System.err.println("error: during serialization"); throw new EJBException("error: during serialization", e); } catch (IOException e) { System.err.println("error: could not connect to " + url); throw new ConnectIOException("could not connect to " + url, e); } finally { try { out.close(); } catch (Exception e) { } } boolean isThrowable = false; Object result = null; ObjectInputStream in = null; try { in = new ObjectInputStream(connection.getInputStream()); isThrowable = in.readBoolean(); if (isThrowable || !invocation.getMethod().getReturnType().equals(void.class)) result = in.readObject(); } catch (ObjectStreamException e) { System.err.println("error: during deserialization"); throw new EJBException("error: during deserialization", e); } catch (IOException e) { System.err.println("error: could not connect to " + url); throw new ConnectIOException("could not connect to " + url, e); } finally { try { in.close(); } catch (Exception e) { } } if (isThrowable) throw (Throwable) result; return result; }
Code Sample 2:
private static void copyFile(File f) { try { String baseName = baseDir.getCanonicalPath(); String fullPath = f.getCanonicalPath(); String nameSufix = fullPath.substring(baseName.length() + 1); File destFile = new File(FileDestDir, nameSufix); destFile.getParentFile().mkdirs(); destFile.createNewFile(); FileChannel fromChannel = new FileInputStream(f).getChannel(); FileChannel toChannel = new FileOutputStream(destFile).getChannel(); fromChannel.transferTo(0, fromChannel.size(), toChannel); fromChannel.close(); toChannel.close(); destFile.setLastModified(f.lastModified()); } catch (Exception e) { System.err.println(e.getMessage()); } }
|
00
|
Code Sample 1:
public static InputStream call(String serviceUrl, Map parameters) throws IOException, RestException { StringBuffer urlString = new StringBuffer(serviceUrl); String query = RestClient.buildQueryString(parameters); HttpURLConnection conn; if ((urlString.length() + query.length() + 1) > MAX_URI_LENGTH_FOR_GET) { URL url = new URL(urlString.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_STRING); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); conn.getOutputStream().write(query.getBytes()); } else { if (query.length() > 0) { urlString.append("?").append(query); } URL url = new URL(urlString.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_STRING); conn.setRequestMethod("GET"); } int responseCode = conn.getResponseCode(); if (HttpURLConnection.HTTP_OK != responseCode) { ByteArrayOutputStream errorBuffer = new ByteArrayOutputStream(); int read; byte[] readBuffer = new byte[ERROR_READ_BUFFER_SIZE]; InputStream errorStream = conn.getErrorStream(); while (-1 != (read = errorStream.read(readBuffer))) { errorBuffer.write(readBuffer, 0, read); } throw new RestException("Request failed, HTTP " + responseCode + ": " + conn.getResponseMessage(), errorBuffer.toByteArray()); } return conn.getInputStream(); }
Code Sample 2:
public static String getMdPsw(String passwd) throws Exception { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(passwd.getBytes("iso-8859-1"), 0, passwd.length()); md5hash = md.digest(); return convertToHex(md5hash); }
|
00
|
Code Sample 1:
public void importarHistoricoDeCotacoesDosPapeis(File[] pArquivosTXT, boolean pApagarDadosImportadosAnteriormente, Andamento pAndamento) throws FileNotFoundException, SQLException { if (pApagarDadosImportadosAnteriormente) { Statement stmtLimpezaInicialDestino = conDestino.createStatement(); String sql = "TRUNCATE TABLE TMP_TB_COTACAO_AVISTA_LOTE_PDR"; stmtLimpezaInicialDestino.executeUpdate(sql); sql = "TRUNCATE TABLE TMP_TB_COTACAO_OUTROS_MERCADOS"; stmtLimpezaInicialDestino.executeUpdate(sql); } final int TAMANHO_DO_REGISTRO = 245; long TAMANHO_DOS_METADADOS_DO_ARQUIVO = 2 * TAMANHO_DO_REGISTRO; long tamanhoDosArquivos = 0; for (File arquivoTXT : pArquivosTXT) { long tamanhoDoArquivo = arquivoTXT.length(); tamanhoDosArquivos += tamanhoDoArquivo; } int quantidadeEstimadaDeRegistros = (int) ((tamanhoDosArquivos - (pArquivosTXT.length * TAMANHO_DOS_METADADOS_DO_ARQUIVO)) / TAMANHO_DO_REGISTRO); String sqlMercadoAVistaLotePadrao = "INSERT INTO TMP_TB_COTACAO_AVISTA_LOTE_PDR(DATA_PREGAO, CODBDI, CODNEG, TPMERC, NOMRES, ESPECI, PRAZOT, MODREF, PREABE, PREMAX, PREMIN, PREMED, PREULT, PREOFC, PREOFV, TOTNEG, QUATOT, VOLTOT, PREEXE, INDOPC, DATVEN, FATCOT, PTOEXE, CODISI, DISMES) VALUES(:DATA_PREGAO, :CODBDI, :CODNEG, :TPMERC, :NOMRES, :ESPECI, :PRAZOT, :MODREF, :PREABE, :PREMAX, :PREMIN, :PREMED, :PREULT, :PREOFC, :PREOFV, :TOTNEG, :QUATOT, :VOLTOT, :PREEXE, :INDOPC, :DATVEN, :FATCOT, :PTOEXE, :CODISI, :DISMES)"; OraclePreparedStatement stmtDestinoMercadoAVistaLotePadrao = (OraclePreparedStatement) conDestino.prepareStatement(sqlMercadoAVistaLotePadrao); stmtDestinoMercadoAVistaLotePadrao.setExecuteBatch(COMANDOS_POR_LOTE); String sqlOutrosMercados = "INSERT INTO TMP_TB_COTACAO_OUTROS_MERCADOS(DATA_PREGAO, CODBDI, CODNEG, TPMERC, NOMRES, ESPECI, PRAZOT, MODREF, PREABE, PREMAX, PREMIN, PREMED, PREULT, PREOFC, PREOFV, TOTNEG, QUATOT, VOLTOT, PREEXE, INDOPC, DATVEN, FATCOT, PTOEXE, CODISI, DISMES) VALUES(:DATA_PREGAO, :CODBDI, :CODNEG, :TPMERC, :NOMRES, :ESPECI, :PRAZOT, :MODREF, :PREABE, :PREMAX, :PREMIN, :PREMED, :PREULT, :PREOFC, :PREOFV, :TOTNEG, :QUATOT, :VOLTOT, :PREEXE, :INDOPC, :DATVEN, :FATCOT, :PTOEXE, :CODISI, :DISMES)"; OraclePreparedStatement stmtDestinoOutrosMercados = (OraclePreparedStatement) conDestino.prepareStatement(sqlOutrosMercados); stmtDestinoOutrosMercados.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosImportadosDosArquivos = 0; Scanner in = null; int numeroDoRegistro = -1; try { for (File arquivoTXT : pArquivosTXT) { int quantidadeDeRegistrosImportadosDoArquivoAtual = 0; int vDATA_PREGAO; try { in = new Scanner(new FileInputStream(arquivoTXT), Constantes.CONJUNTO_DE_CARACTERES_DOS_ARQUIVOS_TEXTO_DA_BOVESPA.name()); String registro; numeroDoRegistro = 0; while (in.hasNextLine()) { ++numeroDoRegistro; registro = in.nextLine(); if (registro.length() != TAMANHO_DO_REGISTRO) throw new ProblemaNaImportacaoDeArquivo(); if (registro.startsWith("01")) { stmtDestinoMercadoAVistaLotePadrao.clearParameters(); stmtDestinoOutrosMercados.clearParameters(); vDATA_PREGAO = Integer.parseInt(registro.substring(2, 10).trim()); int vCODBDI = Integer.parseInt(registro.substring(10, 12).trim()); String vCODNEG = registro.substring(12, 24).trim(); int vTPMERC = Integer.parseInt(registro.substring(24, 27).trim()); String vNOMRES = registro.substring(27, 39).trim(); String vESPECI = registro.substring(39, 49).trim(); String vPRAZOT = registro.substring(49, 52).trim(); String vMODREF = registro.substring(52, 56).trim(); BigDecimal vPREABE = obterBigDecimal(registro.substring(56, 69).trim(), 13, 2); BigDecimal vPREMAX = obterBigDecimal(registro.substring(69, 82).trim(), 13, 2); BigDecimal vPREMIN = obterBigDecimal(registro.substring(82, 95).trim(), 13, 2); BigDecimal vPREMED = obterBigDecimal(registro.substring(95, 108).trim(), 13, 2); BigDecimal vPREULT = obterBigDecimal(registro.substring(108, 121).trim(), 13, 2); BigDecimal vPREOFC = obterBigDecimal(registro.substring(121, 134).trim(), 13, 2); BigDecimal vPREOFV = obterBigDecimal(registro.substring(134, 147).trim(), 13, 2); int vTOTNEG = Integer.parseInt(registro.substring(147, 152).trim()); BigDecimal vQUATOT = new BigDecimal(registro.substring(152, 170).trim()); BigDecimal vVOLTOT = obterBigDecimal(registro.substring(170, 188).trim(), 18, 2); BigDecimal vPREEXE = obterBigDecimal(registro.substring(188, 201).trim(), 13, 2); int vINDOPC = Integer.parseInt(registro.substring(201, 202).trim()); int vDATVEN = Integer.parseInt(registro.substring(202, 210).trim()); int vFATCOT = Integer.parseInt(registro.substring(210, 217).trim()); BigDecimal vPTOEXE = obterBigDecimal(registro.substring(217, 230).trim(), 13, 6); String vCODISI = registro.substring(230, 242).trim(); int vDISMES = Integer.parseInt(registro.substring(242, 245).trim()); boolean mercadoAVistaLotePadrao = (vTPMERC == 10 && vCODBDI == 2); OraclePreparedStatement stmtDestino; if (mercadoAVistaLotePadrao) { stmtDestino = stmtDestinoMercadoAVistaLotePadrao; } else { stmtDestino = stmtDestinoOutrosMercados; } stmtDestino.setIntAtName("DATA_PREGAO", vDATA_PREGAO); stmtDestino.setIntAtName("CODBDI", vCODBDI); stmtDestino.setStringAtName("CODNEG", vCODNEG); stmtDestino.setIntAtName("TPMERC", vTPMERC); stmtDestino.setStringAtName("NOMRES", vNOMRES); stmtDestino.setStringAtName("ESPECI", vESPECI); stmtDestino.setStringAtName("PRAZOT", vPRAZOT); stmtDestino.setStringAtName("MODREF", vMODREF); stmtDestino.setBigDecimalAtName("PREABE", vPREABE); stmtDestino.setBigDecimalAtName("PREMAX", vPREMAX); stmtDestino.setBigDecimalAtName("PREMIN", vPREMIN); stmtDestino.setBigDecimalAtName("PREMED", vPREMED); stmtDestino.setBigDecimalAtName("PREULT", vPREULT); stmtDestino.setBigDecimalAtName("PREOFC", vPREOFC); stmtDestino.setBigDecimalAtName("PREOFV", vPREOFV); stmtDestino.setIntAtName("TOTNEG", vTOTNEG); stmtDestino.setBigDecimalAtName("QUATOT", vQUATOT); stmtDestino.setBigDecimalAtName("VOLTOT", vVOLTOT); stmtDestino.setBigDecimalAtName("PREEXE", vPREEXE); stmtDestino.setIntAtName("INDOPC", vINDOPC); stmtDestino.setIntAtName("DATVEN", vDATVEN); stmtDestino.setIntAtName("FATCOT", vFATCOT); stmtDestino.setBigDecimalAtName("PTOEXE", vPTOEXE); stmtDestino.setStringAtName("CODISI", vCODISI); stmtDestino.setIntAtName("DISMES", vDISMES); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportadosDoArquivoAtual++; quantidadeDeRegistrosImportadosDosArquivos++; } else if (registro.startsWith("99")) { BigDecimal totalDeRegistros = obterBigDecimal(registro.substring(31, 42).trim(), 11, 0); assert (totalDeRegistros.intValue() - 2) == quantidadeDeRegistrosImportadosDoArquivoAtual : "Quantidade de registros divergente"; break; } double percentualCompleto = (double) quantidadeDeRegistrosImportadosDosArquivos / quantidadeEstimadaDeRegistros * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); ProblemaNaImportacaoDeArquivo problemaDetalhado = new ProblemaNaImportacaoDeArquivo(); problemaDetalhado.nomeDoArquivo = arquivoTXT.getName(); problemaDetalhado.linhaProblematicaDoArquivo = numeroDoRegistro; problemaDetalhado.detalhesSobreOProblema = ex; throw problemaDetalhado; } finally { in.close(); } } } finally { pAndamento.setPercentualCompleto(100); stmtDestinoMercadoAVistaLotePadrao.close(); stmtDestinoOutrosMercados.close(); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static void copyTo(File src, File dest) throws IOException { if (src.equals(dest)) throw new IOException("copyTo src==dest file"); FileOutputStream fout = new FileOutputStream(dest); InputStream in = new FileInputStream(src); IOUtils.copyTo(in, fout); fout.flush(); fout.close(); in.close(); }
|
00
|
Code Sample 1:
private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); String response = new String(baos.toByteArray(), "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + response); return response; }
Code Sample 2:
public static String encrypt(String password) throws NoSuchAlgorithmException { java.security.MessageDigest d = null; d = java.security.MessageDigest.getInstance("MD5"); d.reset(); d.update(password.getBytes()); byte[] cr = d.digest(); return getString(cr).toLowerCase(); }
|
11
|
Code Sample 1:
public static void copy(File toCopy, File dest) throws IOException { FileInputStream src = new FileInputStream(toCopy); FileOutputStream out = new FileOutputStream(dest); try { while (src.available() > 0) { out.write(src.read()); } } finally { src.close(); out.close(); } }
Code Sample 2:
public void generate(FileObject outputDirectory, FileObject generatedOutputDirectory, List<Library> libraryModels, String tapdocXml) throws FileSystemException { if (!outputDirectory.exists()) { outputDirectory.createFolder(); } ZipUtils.extractZip(new ClasspathResource(classResolver, "/com/erinors/tapestry/tapdoc/standalone/resources.zip"), outputDirectory); for (Library library : libraryModels) { String libraryName = library.getName(); String libraryLocation = library.getLocation(); outputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).createFolder(); try { { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Library.xsl"), "libraryName", libraryName); FileObject index = outputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).resolveFile("index.html"); Writer out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("ComponentIndex.xsl"), "libraryName", libraryName); FileObject index = outputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).resolveFile("components.html"); Writer out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } } catch (Exception e) { throw new RuntimeException(e); } for (Component component : library.getComponents()) { String componentName = component.getName(); System.out.println("Generating " + libraryName + ":" + componentName + "..."); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("libraryName", libraryName); parameters.put("componentName", componentName); String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Component.xsl"), parameters); Writer out = null; try { FileObject index = outputDirectory.resolveFile(fileNameGenerator.getComponentIndexFile(libraryLocation, componentName, true)); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); Resource specificationLocation = component.getSpecificationLocation(); if (specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL() != null) { File srcResourcesDirectory = new File(specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL().toURI()); FileObject dstResourcesFileObject = outputDirectory.resolveFile(fileNameGenerator.getComponentDirectory(libraryLocation, componentName)).resolveFile("resource"); if (srcResourcesDirectory.exists() && srcResourcesDirectory.isDirectory()) { File[] files = srcResourcesDirectory.listFiles(); if (files != null) { for (File resource : files) { if (resource.isFile() && !resource.isHidden()) { FileObject resourceFileObject = dstResourcesFileObject.resolveFile(resource.getName()); resourceFileObject.createFile(); InputStream inResource = null; OutputStream outResource = null; try { inResource = new FileInputStream(resource); outResource = resourceFileObject.getContent().getOutputStream(); IOUtils.copy(inResource, outResource); } finally { IOUtils.closeQuietly(inResource); IOUtils.closeQuietly(outResource); } } } } } } } catch (Exception e) { throw new RuntimeException(e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } } { Writer out = null; try { { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("LibraryIndex.xsl")); FileObject index = outputDirectory.resolveFile("libraries.html"); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Overview.xsl")); FileObject index = outputDirectory.resolveFile("overview.html"); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("AllComponents.xsl")); FileObject index = outputDirectory.resolveFile("allcomponents.html"); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); } } }
|
11
|
Code Sample 1:
@Test public void testCopy_readerToOutputStream_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null); fail(); } catch (NullPointerException ex) { } }
Code Sample 2:
public static boolean copyFile(final File fileFrom, final File fileTo) { assert fileFrom != null : "fileFrom is null"; assert fileTo != null : "fileTo is null"; LOGGER.info(buildLogString(COPY_FILE_INFO, new Object[] { fileFrom, fileTo })); boolean error = true; FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(fileFrom); outputStream = new FileOutputStream(fileTo); final FileChannel inChannel = inputStream.getChannel(); final FileChannel outChannel = outputStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); error = false; } catch (final IOException e) { LOGGER.log(SEVERE, buildLogString(COPY_FILE_ERROR, new Object[] { fileFrom, fileTo }), e); } finally { closeCloseable(inputStream, fileFrom); closeCloseable(outputStream, fileTo); } return error; }
|
11
|
Code Sample 1:
protected void onSubmit() { super.onSubmit(); if (!this.hasError()) { final FileUpload upload = fileUploadField.getFileUpload(); if (upload != null) { try { StringWriter xmlSourceWriter = new StringWriter(); IOUtils.copy(upload.getInputStream(), xmlSourceWriter); processSubmittedDoap(xmlSourceWriter.toString()); } catch (IOException e) { setResponsePage(new ErrorReportPage(new UserReportableException("Unable to add doap using RDF supplied", DoapFormPage.class, e))); } } } }
Code Sample 2:
private void copyResource(final String resourceName, final File file) throws IOException { assertTrue(resourceName.startsWith("/")); InputStream in = null; boolean suppressExceptionOnClose = true; try { in = this.getClass().getResourceAsStream(resourceName); assertNotNull("Resource '" + resourceName + "' not found.", in); OutputStream out = null; try { out = new FileOutputStream(file); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
|
00
|
Code Sample 1:
private boolean delete() { boolean ret = false; try { Connection conn = ((JdbcRequestCycle) getRequestCycle()).getConnection(); if (conn == null) { throw new RestartResponseException(new OkErrorPage(OkErrorEnum.DATABASE)); } String query = "delete from revisions where entry=?"; PreparedStatement pstmt = conn.prepareStatement(query); pstmt.setInt(1, entry); int revisionsRowsAffected = pstmt.executeUpdate(); query = "delete from entry where id=?"; pstmt = conn.prepareStatement(query); pstmt.setInt(1, entry); int entryRowAffected = pstmt.executeUpdate(); if (entryRowAffected > 0) { ret = true; } else { conn.rollback(); } info(entryRowAffected + " entry with " + revisionsRowsAffected + " revisions was deleted."); } catch (SQLException ex) { ex.printStackTrace(); } return ret; }
Code Sample 2:
public void reademi(Vector<String> descriptions, Vector<String> links, String linkaddress, String idmap) { InputStream is = null; URL url; ArrayList<String> keys = new ArrayList<String>(); ArrayList<String> names = new ArrayList<String>(); try { url = new URL(idmap); is = url.openStream(); Scanner scanner = new Scanner(is); scanner.nextLine(); String line = ""; String id = ""; while (scanner.hasNextLine()) { line = scanner.nextLine(); Scanner linescanner = new Scanner(line); linescanner.useDelimiter("\t"); id = linescanner.next(); id = id.substring(0, id.length() - 2); keys.add(id); linescanner.next(); linescanner.next(); linescanner.next(); linescanner.useDelimiter("\n"); names.add(linescanner.next()); } BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(linkaddress).openStream())); String link = ""; String key = ""; String name = ""; int counter = 0; while ((line = reader.readLine()) != null) { if (line.indexOf("style=raw") != -1) { int linkstart = line.indexOf("http://www.ebi.ac.uk/cgi-bin/dbfetch?db"); int idstart = line.indexOf("id=") + 3; int linkend = line.substring(linkstart).indexOf("\"") + linkstart; link = line.substring(linkstart, linkend); key = line.substring(idstart, linkend); if (keys.indexOf(key) != -1) { name = names.get(keys.indexOf(key)); counter++; descriptions.add(counter + " " + key + " " + name); links.add(link); } } } } catch (MalformedURLException e) { } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
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(); }
Code Sample 2:
private static void copy(File source, File target) throws IOException { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(source); to = new FileOutputStream(target); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { } if (to != null) try { to.close(); } catch (IOException e) { } } }
|
11
|
Code Sample 1:
public String encodePassword(String password, byte[] salt) throws Exception { if (salt == null) { salt = new byte[12]; secureRandom.nextBytes(salt); } MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF8")); byte[] digest = md.digest(); byte[] storedPassword = new byte[digest.length + 12]; System.arraycopy(salt, 0, storedPassword, 0, 12); System.arraycopy(digest, 0, storedPassword, 12, digest.length); return new String(Base64.encode(storedPassword)); }
Code Sample 2:
public static String calculate(String str) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); md.update(str.getBytes()); byte byteData[] = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (NoSuchAlgorithmException ex) { return null; } }
|
11
|
Code Sample 1:
public String getHash(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] toChapter1Digest = md.digest(); return Keystore.hexEncode(toChapter1Digest); } catch (Exception e) { logger.error("Error in creating DN hash: " + e.getMessage()); return null; } }
Code Sample 2:
public static boolean checkEncode(String origin, byte[] mDigest, String algorithm) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(origin.getBytes()); if (MessageDigest.isEqual(mDigest, md.digest())) { return true; } else { return false; } }
|
00
|
Code Sample 1:
private LoadReturnCode loadChild(Map<Key, ValueItem> map, String fileOrUrl, LoadReturnCode defaultResult) throws IOException { try { URL childurl = getAsUrl(fileOrUrl); if (childurl == null) return defaultResult; InputStream childStream = childurl.openStream(); fileOrUrl = childurl.toString(); LinkedProperties child = new LinkedProperties(); child.initFromParent(this); child.setFilename(fileOrUrl); int p = fileOrUrl.lastIndexOf('/'); setLoadPath((p < 0) ? null : fileOrUrl.substring(0, p)); Map<Key, ValueItem> childMap = new HashMap<Key, ValueItem>(map); removeLocalKeys(childMap); @SuppressWarnings("unused") LoadReturnCode childresult = child.onLoad(childMap, childStream); try { if (childStream != null) childStream.close(); } catch (IOException ioex) { } childStream = null; map.putAll(childMap); return resolveMap(map); } catch (IOException ioe) { System.out.println(getFilename() + ": error loading childfile " + fileOrUrl); throw ioe; } }
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) { ; } } }
|
00
|
Code Sample 1:
private Document saveFile(Document document, File file) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { Preference preference = preferences.get(0); String repo = preference.getRepository(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(document.getLocation()); File folder = new File(sbRepo.append(sbFolder).toString()); log.info("Check in file ID [" + document.getId() + "] to " + folder.getAbsolutePath()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null, fcVersionDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append(".").append(document.getExt()); StringBuffer sbVersionFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append("_").append(document.getVersion().toString()).append(".").append(document.getExt()); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcVersionDest = new FileOutputStream(sbVersionFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); fcSource = new FileInputStream(file).getChannel(); fcVersionDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } if (fcVersionDest != null) { fcVersionDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } return document; }
Code Sample 2:
public void run() { try { if (netLoadAccount.loginsuccessful) { host = netLoadAccount.username + " | Netload.in"; } else { host = "Netload.in"; } status = UploadStatus.INITIALISING; initialize(); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); if (netLoadAccount.loginsuccessful) { httppost.setHeader("Cookie", usercookie); } MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); if (netLoadAccount.loginsuccessful) { mpEntity.addPart("upload_hash", new StringBody(upload_hash)); } mpEntity.addPart("file", new MonitoredFileBody(file, uploadProgress)); httppost.setEntity(mpEntity); NULogger.getLogger().log(Level.INFO, "executing request {0}", httppost.getRequestLine()); NULogger.getLogger().info("Now uploading your file into netload"); status = UploadStatus.UPLOADING; HttpResponse response = httpclient.execute(httppost); status = UploadStatus.GETTINGLINK; HttpEntity resEntity = response.getEntity(); NULogger.getLogger().info(response.getStatusLine().toString()); httpclient.getConnectionManager().shutdown(); if (response.containsHeader("Location")) { Header firstHeader = response.getFirstHeader("Location"); NULogger.getLogger().info(firstHeader.getValue()); uploadresponse = getData(firstHeader.getValue()); downloadlink = CommonUploaderTasks.parseResponse(uploadresponse, "The download link is: <br/>", "\" target=\"_blank\">"); downloadlink = downloadlink.substring(downloadlink.indexOf("href=\"")); downloadlink = downloadlink.replace("href=\"", ""); NULogger.getLogger().log(Level.INFO, "download link : {0}", downloadlink); deletelink = CommonUploaderTasks.parseResponse(uploadresponse, "The deletion link is: <br/>", "\" target=\"_blank\">"); deletelink = deletelink.substring(deletelink.indexOf("href=\"")); deletelink = deletelink.replace("href=\"", ""); NULogger.getLogger().log(Level.INFO, "delete link : {0}", deletelink); downURL = downloadlink; delURL = deletelink; uploadFinished(); } else { throw new Exception("There might be a problem with your internet connection or server error. Please try after some time :("); } } catch (Exception e) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e); uploadFailed(); } }
|
11
|
Code Sample 1:
protected void writePage(final CacheItem entry, final TranslationResponse response, ModifyTimes times) throws IOException { if (entry == null) { return; } Set<ResponseHeader> headers = new TreeSet<ResponseHeader>(); for (ResponseHeader h : entry.getHeaders()) { if (TranslationResponse.ETAG.equals(h.getName())) { if (!times.isFileLastModifiedKnown()) { headers.add(new ResponseHeaderImpl(h.getName(), doETagStripWeakMarker(h.getValues()))); } } else { headers.add(h); } } response.addHeaders(headers); if (!times.isFileLastModifiedKnown()) { response.setLastModified(entry.getLastModified()); } response.setTranslationCount(entry.getTranslationCount()); response.setFailCount(entry.getFailCount()); OutputStream output = response.getOutputStream(); try { InputStream input = entry.getContentAsStream(); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { response.setEndState(ResponseStateOk.getInstance()); } }
Code Sample 2:
@Override public void dispatchContent(InputStream is) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Sending content message over JMS"); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(is, bos); this.send(new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { BytesMessage message = session.createBytesMessage(); message.writeBytes(bos.toByteArray()); return message; } }); }
|
00
|
Code Sample 1:
public static void main(String[] args) { File directory = new File(args[0]); File[] files = directory.listFiles(); try { PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(args[1]))); for (int i = 0; i < files.length; i++) { BufferedReader reader = new BufferedReader(new FileReader(files[i])); while (reader.ready()) writer.println(reader.readLine()); reader.close(); } writer.flush(); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException { log.debug("Start MemberPortletActionMethod.processAction()"); MemberProcessingActionRequest mp = null; try { ModuleManager moduleManager = ModuleManager.getInstance(PropertiesProvider.getConfigPath()); mp = new MemberProcessingActionRequest(actionRequest, moduleManager); String moduleName = RequestTools.getString(actionRequest, MemberConstants.MEMBER_MODULE_PARAM); String actionName = RequestTools.getString(actionRequest, MemberConstants.MEMBER_ACTION_PARAM); String subActionName = RequestTools.getString(actionRequest, MemberConstants.MEMBER_SUBACTION_PARAM).trim(); if (log.isDebugEnabled()) { Map parameterMap = actionRequest.getParameterMap(); if (!parameterMap.entrySet().isEmpty()) { log.debug("Action request parameter"); for (Object o : parameterMap.entrySet()) { Map.Entry entry = (Map.Entry) o; log.debug(" key: " + entry.getKey() + ", value: " + entry.getValue()); } } else { log.debug("Action request map is empty"); } log.debug(" Point #4.1 module '" + moduleName + "'"); log.debug(" Point #4.2 action '" + actionName + "'"); log.debug(" Point #4.3 subAction '" + subActionName + "'"); } if (mp.mod == null) { actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Point #4.2. Module '" + moduleName + "' not found"); return; } if (mp.mod.getType() != null && mp.mod.getType().getType() == ModuleTypeTypeType.LOOKUP_TYPE && (mp.getFromParam() == null || mp.getFromParam().length() == 0)) { actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Point #4.4. Module " + moduleName + " is lookup module"); return; } int actionType = ContentTypeActionType.valueOf(actionName).getType(); if (log.isDebugEnabled()) { log.debug("action name " + actionName); log.debug("ContentTypeActionType " + ContentTypeActionType.valueOf(actionName).toString()); log.debug("action type " + actionType); } mp.content = MemberServiceClass.getContent(mp.mod, actionType); if (mp.content == null) { actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Module: '" + moduleName + "', action '" + actionName + "', not found"); return; } if (log.isDebugEnabled()) { log.debug("Debug. Unmarshal sqlCache object"); synchronized (syncFile) { XmlTools.writeToFile(mp.content.getQueryArea().getSqlCache(), SiteUtils.getTempDir() + File.separatorChar + "member-content-site-start-0.xml", "windows-1251"); } } if (!MemberServiceClass.checkRole(actionRequest, mp.content)) { actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Access denied"); return; } if (log.isDebugEnabled()) { log.debug("Unmarshal sqlCache object"); synchronized (syncFile) { XmlTools.writeToFile(mp.content.getQueryArea().getSqlCache(), SiteUtils.getTempDir() + File.separatorChar + "member-content-site-start-2.xml", "windows-1251"); } } initRenderParameters(actionRequest.getParameterMap(), actionResponse); if ("commit".equalsIgnoreCase(subActionName)) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = mp.getDatabaseAdapter(); int i1; switch(actionType) { case ContentTypeActionType.INSERT_TYPE: if (log.isDebugEnabled()) log.debug("Start prepare data for inserting."); String validateStatus = mp.validateFields(dbDyn); if (log.isDebugEnabled()) log.debug("Validating status - " + validateStatus); if (validateStatus != null) { WebmillErrorPage.setErrorInfo(actionResponse, validateStatus, MemberConstants.ERROR_TEXT, null, "Continue", MemberConstants.ERROR_URL_NAME); return; } if (log.isDebugEnabled()) { log.debug("Unmarshal sqlCache object"); synchronized (syncFile) { XmlTools.writeToFile(mp.content.getQueryArea().getSqlCache(), SiteUtils.getTempDir() + File.separatorChar + "member-content-before-yesno.xml", "windows-1251"); } } if (log.isDebugEnabled()) log.debug("Start looking for field with type " + FieldsTypeJspTypeType.YES_1_NO_N.toString()); if (MemberServiceClass.hasYesNoField(actionRequest.getParameterMap(), mp.mod, mp.content)) { if (log.isDebugEnabled()) log.debug("Found field with type " + FieldsTypeJspTypeType.YES_1_NO_N.toString()); mp.process_Yes_1_No_N_Fields(dbDyn); } else { if (log.isDebugEnabled()) log.debug("Field with type " + FieldsTypeJspTypeType.YES_1_NO_N.toString() + " not found"); } String sql_ = MemberServiceClass.buildInsertSQL(mp.content, mp.getFromParam(), mp.mod, dbDyn, actionRequest.getServerName(), mp.getModuleManager(), mp.authSession); if (log.isDebugEnabled()) { log.debug("insert SQL:\n" + sql_ + "\n"); log.debug("Unmarshal sqlCache object"); synchronized (syncFile) { XmlTools.writeToFile(mp.content.getQueryArea().getSqlCache(), SiteUtils.getTempDir() + File.separatorChar + "member-content.xml", "windows-1251"); } } boolean checkStatus = false; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: checkStatus = mp.checkRestrict(); if (!checkStatus) throw new ServletException("check status of restrict failed"); break; } if (log.isDebugEnabled()) log.debug("check status - " + checkStatus); ps = dbDyn.prepareStatement(sql_); Object idNewRec = mp.bindInsert(dbDyn, ps); i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Number of inserter record - " + i1); DatabaseManager.close(ps); ps = null; if (log.isDebugEnabled()) { outputDebugOfInsertStatus(mp, dbDyn, idNewRec); } mp.prepareBigtextData(dbDyn, idNewRec, false); for (int i = 0; i < mp.mod.getRelateClassCount(); i++) { RelateClassType rc = mp.mod.getRelateClass(i); if (log.isDebugEnabled()) log.debug("#7.003.003 terminate class " + rc.getClassName()); CacheFactory.terminate(rc.getClassName(), null, Boolean.TRUE.equals(rc.getIsFullReinitCache())); } break; case ContentTypeActionType.CHANGE_TYPE: if (log.isDebugEnabled()) log.debug("Commit change page"); validateStatus = mp.validateFields(dbDyn); if (validateStatus != null) { WebmillErrorPage.setErrorInfo(actionResponse, validateStatus, MemberConstants.ERROR_TEXT, null, "Continue", MemberConstants.ERROR_URL_NAME); return; } if (MemberServiceClass.hasYesNoField(actionRequest.getParameterMap(), mp.mod, mp.content)) { if (log.isDebugEnabled()) log.debug("Found field with type " + FieldsTypeJspTypeType.YES_1_NO_N); mp.process_Yes_1_No_N_Fields(dbDyn); } Object idCurrRec; if (log.isDebugEnabled()) log.debug("PrimaryKeyType " + mp.content.getQueryArea().getPrimaryKeyType()); switch(mp.content.getQueryArea().getPrimaryKeyType().getType()) { case PrimaryKeyTypeType.NUMBER_TYPE: log.debug("PrimaryKeyType - 'number'"); idCurrRec = PortletService.getLong(actionRequest, mp.mod.getName() + '.' + mp.content.getQueryArea().getPrimaryKey()); break; case PrimaryKeyTypeType.STRING_TYPE: log.debug("PrimaryKeyType - 'string'"); idCurrRec = RequestTools.getString(actionRequest, mp.mod.getName() + '.' + mp.content.getQueryArea().getPrimaryKey()); break; default: throw new Exception("Change. Wrong type of primary key - " + mp.content.getQueryArea().getPrimaryKeyType()); } if (log.isDebugEnabled()) log.debug("mp.isSimpleField(): " + mp.isSimpleField()); if (mp.isSimpleField()) { log.debug("start build SQL"); sql_ = MemberServiceClass.buildUpdateSQL(dbDyn, mp.content, mp.getFromParam(), mp.mod, true, actionRequest.getParameterMap(), actionRequest.getRemoteUser(), actionRequest.getServerName(), mp.getModuleManager(), mp.authSession); if (log.isDebugEnabled()) log.debug("update SQL:" + sql_); ps = dbDyn.prepareStatement(sql_); mp.bindUpdate(dbDyn, ps, idCurrRec, true); i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Number of updated record - " + i1); } log.debug("prepare big text"); mp.prepareBigtextData(dbDyn, idCurrRec, true); if (mp.content.getQueryArea().getPrimaryKeyType().getType() != PrimaryKeyTypeType.NUMBER_TYPE) throw new Exception("PK of 'Bigtext' table must be a 'number' type"); log.debug("start sync cache data"); for (int i = 0; i < mp.mod.getRelateClassCount(); i++) { RelateClassType rc = mp.mod.getRelateClass(i); if (log.isDebugEnabled()) log.debug("#7.003.002 terminate class " + rc.getClassName() + ", id_rec " + idCurrRec); if (mp.content.getQueryArea().getPrimaryKeyType().getType() == PrimaryKeyTypeType.NUMBER_TYPE) { CacheFactory.terminate(rc.getClassName(), (Long) idCurrRec, Boolean.TRUE.equals(rc.getIsFullReinitCache())); } else { actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Change. Wrong type of primary key - " + mp.content.getQueryArea().getPrimaryKeyType()); return; } } break; case ContentTypeActionType.DELETE_TYPE: log.debug("Commit delete page<br>"); Object idRec; if (mp.content.getQueryArea().getPrimaryKeyType().getType() == PrimaryKeyTypeType.NUMBER_TYPE) { idRec = PortletService.getLong(actionRequest, mp.mod.getName() + '.' + mp.content.getQueryArea().getPrimaryKey()); } else if (mp.content.getQueryArea().getPrimaryKeyType().getType() == PrimaryKeyTypeType.STRING_TYPE) { idRec = RequestTools.getString(actionRequest, mp.mod.getName() + '.' + mp.content.getQueryArea().getPrimaryKey()); } else { actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Delete. Wrong type of primary key - " + mp.content.getQueryArea().getPrimaryKeyType()); return; } if (dbDyn.getFamaly() == DatabaseManager.MYSQL_FAMALY) mp.deleteBigtextData(dbDyn, idRec); sql_ = MemberServiceClass.buildDeleteSQL(dbDyn, mp.mod, mp.content, mp.getFromParam(), actionRequest.getParameterMap(), actionRequest.getRemoteUser(), actionRequest.getServerName(), moduleManager, mp.authSession); if (log.isDebugEnabled()) log.debug("delete SQL: " + sql_ + "<br>\n"); ps = dbDyn.prepareStatement(sql_); mp.bindDelete(ps); i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Number of deleted record - " + i1); if (idRec != null && (idRec instanceof Long)) { for (int i = 0; i < mp.mod.getRelateClassCount(); i++) { RelateClassType rc = mp.mod.getRelateClass(i); if (log.isDebugEnabled()) log.debug("#7.003.001 terminate class " + rc.getClassName() + ", id_rec " + idRec.toString()); CacheFactory.terminate(rc.getClassName(), (Long) idRec, Boolean.TRUE.equals(rc.getIsFullReinitCache())); } } break; default: actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Unknown type of action - " + actionName); return; } log.debug("do commit"); dbDyn.commit(); } catch (Exception e1) { try { dbDyn.rollback(); } catch (Exception e001) { log.info("error in rolback()"); } log.error("Error while processing this page", e1); if (dbDyn.testExceptionIndexUniqueKey(e1)) { WebmillErrorPage.setErrorInfo(actionResponse, "You input value already exists in DB. Try again with other value", MemberConstants.ERROR_TEXT, null, "Continue", MemberConstants.ERROR_URL_NAME); } else { WebmillErrorPage.setErrorInfo(actionResponse, "Error while processing request", MemberConstants.ERROR_TEXT, e1, "Continue", MemberConstants.ERROR_URL_NAME); } } finally { DatabaseManager.close(dbDyn, ps); } } } catch (Exception e) { final String es = "General processing error "; log.error(es, e); throw new PortletException(es, e); } finally { if (mp != null) { mp.destroy(); } } }
|
00
|
Code Sample 1:
@Override protected URLConnection openConnection(URL url) throws IOException { try { final HttpServlet servlet; String path = url.getPath(); if (path.matches("reg:.+")) { String registerName = path.replaceAll("reg:([^/]*)/.*", "$1"); servlet = register.get(registerName); if (servlet == null) throw new RuntimeException("No servlet registered with name " + registerName); } else { String servletClassName = path.replaceAll("([^/]*)/.*", "$1"); servlet = (HttpServlet) Class.forName(servletClassName).newInstance(); } final MockHttpServletRequest req = new MockHttpServletRequest().setMethod("GET"); final MockHttpServletResponse resp = new MockHttpServletResponse(); return new HttpURLConnection(url) { @Override public int getResponseCode() throws IOException { serviceIfNeeded(); return resp.status; } @Override public InputStream getInputStream() throws IOException { serviceIfNeeded(); if (resp.status == 500) throw new IOException("Server responded with error 500"); byte[] array = resp.out.toByteArray(); return new ByteArrayInputStream(array); } @Override public InputStream getErrorStream() { try { serviceIfNeeded(); } catch (IOException e) { throw new RuntimeException(e); } if (resp.status != 500) return null; return new ByteArrayInputStream(resp.out.toByteArray()); } @Override public OutputStream getOutputStream() throws IOException { return req.tmp; } @Override public void addRequestProperty(String key, String value) { req.addHeader(key, value); } @Override public void connect() throws IOException { } @Override public boolean usingProxy() { return false; } @Override public void disconnect() { } private boolean called; private void serviceIfNeeded() throws IOException { try { if (!called) { called = true; req.setMethod(getRequestMethod()); servlet.service(req, resp); } } catch (ServletException e) { throw new RuntimeException(e); } } }; } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }
Code Sample 2:
private void saveAttachment(long messageId, Part attachment, boolean saveAsNew) throws IOException, MessagingException { long attachmentId = -1; Uri contentUri = null; int size = -1; File tempAttachmentFile = null; if ((!saveAsNew) && (attachment instanceof LocalAttachmentBodyPart)) { attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId(); } if (attachment.getBody() != null) { Body body = attachment.getBody(); if (body instanceof LocalAttachmentBody) { contentUri = ((LocalAttachmentBody) body).getContentUri(); } else { InputStream in = attachment.getBody().getInputStream(); tempAttachmentFile = File.createTempFile("att", null, mAttachmentsDir); FileOutputStream out = new FileOutputStream(tempAttachmentFile); size = IOUtils.copy(in, out); in.close(); out.close(); } } if (size == -1) { String disposition = attachment.getDisposition(); if (disposition != null) { String s = MimeUtility.getHeaderParameter(disposition, "size"); if (s != null) { size = Integer.parseInt(s); } } } if (size == -1) { size = 0; } String storeData = Utility.combine(attachment.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA), ','); String name = MimeUtility.getHeaderParameter(attachment.getContentType(), "name"); String contentId = attachment.getContentId(); if (attachmentId == -1) { ContentValues cv = new ContentValues(); cv.put("message_id", messageId); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("store_data", storeData); cv.put("size", size); cv.put("name", name); cv.put("mime_type", attachment.getMimeType()); cv.put("content_id", contentId); attachmentId = mDb.insert("attachments", "message_id", cv); } else { ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("size", size); cv.put("content_id", contentId); cv.put("message_id", messageId); mDb.update("attachments", cv, "id = ?", new String[] { Long.toString(attachmentId) }); } if (tempAttachmentFile != null) { File attachmentFile = new File(mAttachmentsDir, Long.toString(attachmentId)); tempAttachmentFile.renameTo(attachmentFile); attachment.setBody(new LocalAttachmentBody(contentUri, mContext)); ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); mDb.update("attachments", cv, "id = ?", new String[] { Long.toString(attachmentId) }); } if (attachment instanceof LocalAttachmentBodyPart) { ((LocalAttachmentBodyPart) attachment).setAttachmentId(attachmentId); } }
|
11
|
Code Sample 1:
public void xtestGetThread() throws Exception { GMSearchOptions options = new GMSearchOptions(); options.setFrom(loginInfo.getUsername() + "*"); options.setSubject("message*"); GMSearchResponse mail = client.getMail(options); for (Iterator it = mail.getThreadSnapshots().iterator(); it.hasNext(); ) { GMThreadSnapshot threadSnapshot = (GMThreadSnapshot) it.next(); GMThread thread = client.getThread(threadSnapshot.getThreadID()); log.info("Most Recent Thread: " + thread); for (Iterator iter = thread.getMessages().iterator(); iter.hasNext(); ) { GMMessage message = (GMMessage) iter.next(); log.info("Message: " + message); Iterable<GMAttachment> attachments = message.getAttachments(); for (Iterator iterator = attachments.iterator(); iterator.hasNext(); ) { GMAttachment attachment = (GMAttachment) iterator.next(); String ext = FilenameUtils.getExtension(attachment.getFilename()); if (ext.trim().length() > 0) ext = "." + ext; String base = FilenameUtils.getBaseName(attachment.getFilename()); File file = File.createTempFile(base, ext, new File(System.getProperty("user.home"))); log.info("Saving attachment: " + file.getPath()); InputStream attStream = client.getAttachmentAsStream(attachment.getId(), message.getMessageID()); IOUtils.copy(attStream, new FileOutputStream(file)); attStream.close(); assertEquals(file.length(), attachment.getSize()); log.info("Done. Successfully saved: " + file.getPath()); file.delete(); } } } }
Code Sample 2:
public void run() { try { Socket socket = getSocket(); System.out.println("opening socket to " + address + " on " + port); InputStream in = socket.getInputStream(); for (; ; ) { FileTransferHeader header = FileTransferHeader.readHeader(in); if (header == null) break; System.out.println("header: " + header); String[] parts = header.getFilename().getSegments(); String filename; if (parts.length > 0) filename = "dl-" + parts[parts.length - 1]; else filename = "dl-" + session.getScreenname(); System.out.println("writing to file " + filename); long sum = 0; if (new File(filename).exists()) { FileInputStream fis = new FileInputStream(filename); byte[] block = new byte[10]; for (int i = 0; i < block.length; ) { int count = fis.read(block); if (count == -1) break; i += count; } FileTransferChecksum summer = new FileTransferChecksum(); summer.update(block, 0, 10); sum = summer.getValue(); } FileChannel fileChannel = new FileOutputStream(filename).getChannel(); FileTransferHeader outHeader = new FileTransferHeader(header); outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK); outHeader.setIcbmMessageId(cookie); outHeader.setBytesReceived(0); outHeader.setReceivedChecksum(sum); OutputStream socketOut = socket.getOutputStream(); System.out.println("sending header: " + outHeader); outHeader.write(socketOut); for (int i = 0; i < header.getFileSize(); ) { long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i); System.out.println("transferred " + transferred); if (transferred == -1) return; i += transferred; } System.out.println("finished transfer!"); fileChannel.close(); FileTransferHeader doneHeader = new FileTransferHeader(header); doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED); doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE); doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1); doneHeader.setIcbmMessageId(cookie); doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1); doneHeader.write(socketOut); if (doneHeader.getFilesLeft() - 1 <= 0) { socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); return; } }
|
00
|
Code Sample 1:
private synchronized Document executeHttpMethod(final HttpUriRequest httpRequest) throws UnauthorizedException, ThrottledException, ApiException { if (!isNextRequestAllowed()) { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Wait " + WAITING_TIME + "ms for request."); } wait(WAITING_TIME); } catch (InterruptedException ie) { throw new ApiException("Waiting for request interrupted.", ie); } } try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Perform request."); } HttpResponse httpResponse = httpClient.execute(httpRequest); switch(httpResponse.getStatusLine().getStatusCode()) { case HTTP_OK: HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { InputStream responseStream = httpEntity.getContent(); if (responseStream == null) { throw new ApiException("TODO"); } else { String response = null; try { response = IOUtils.toString(responseStream, RESPONSE_ENCODING); } catch (IOException ioe) { throw new ApiException("Problem reading response", ioe); } catch (RuntimeException re) { httpRequest.abort(); throw new ApiException("Problem reading response", re); } finally { responseStream.close(); } StringReader responseReader = new StringReader(response); Document document = documentBuilder.parse(new InputSource(responseReader)); return document; } } case HTTP_UNAVAILABLE: throw new ThrottledException("TODO"); case HTTP_UNAUTHORIZED: throw new UnauthorizedException("TODO"); default: throw new ApiException("Unexpected HTTP status code: " + httpResponse.getStatusLine().getStatusCode()); } } catch (SAXException se) { throw new ApiException("TODO", se); } catch (IOException ioe) { throw new ApiException("TODO", ioe); } finally { updateLastRequestTimestamp(); } }
Code Sample 2:
@Override public void vote(String urlString, Map<String, String> headData, Map<String, String> paramData) { HttpURLConnection httpConn = null; try { URL url = new URL(urlString); httpConn = (HttpURLConnection) url.openConnection(); String cookies = getCookies(httpConn); System.out.println(cookies); BufferedReader post = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "GB2312")); String text = null; while ((text = post.readLine()) != null) { System.out.println(text); } } catch (MalformedURLException e) { e.printStackTrace(); throw new VoteBeanException("网址不正确", e); } catch (IOException e) { e.printStackTrace(); throw new VoteBeanException("不能打开网址", e); } }
|
00
|
Code Sample 1:
public void checkAndDownload(String statsUrl, RDFStatsUpdatableModelExt stats, Date lastDownload, boolean onlyIfNewer) throws DataSourceMonitorException { if (log.isInfoEnabled()) log.info("Checking if update required for statistics of " + ds + "..."); HttpURLConnection urlConnection; try { URL url = new URL(statsUrl); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(CONNECT_TIMEOUT); urlConnection.setReadTimeout(READ_TIMEOUT); int statusCode = urlConnection.getResponseCode(); if (statusCode / 100 != 2) { String msg = urlConnection.getResponseMessage(); throw new DataSourceMonitorException(statsUrl + " returned HTTP " + statusCode + (msg != null ? msg : "") + "."); } } catch (Exception e) { throw new DataSourceMonitorException("Failed to connect to " + statsUrl + ".", e); } long lastModified = urlConnection.getLastModified(); boolean newer = lastDownload == null || lastModified == 0 || lastModified - TIMING_GAP > lastDownload.getTime(); if (newer || !onlyIfNewer) { Model newStats = retrieveModelData(urlConnection, ds); Date retrievedTimestamp = Calendar.getInstance().getTime(); Date modifiedTimestamp = (urlConnection.getLastModified() > 0) ? new Date(urlConnection.getLastModified()) : null; if (log.isInfoEnabled()) log.info("Attempt to import up-to-date " + ((modifiedTimestamp != null) ? "(from " + modifiedTimestamp + ") " : "") + "statistics for " + ds + "."); try { if (stats.updateFrom(RDFStatsModelFactory.create(newStats), onlyIfNewer)) stats.setLastDownload(ds.getSPARQLEndpointURL(), retrievedTimestamp); } catch (Exception e) { throw new DataSourceMonitorException("Failed to import statistics and set last download for " + ds + ".", e); } } else { if (log.isInfoEnabled()) log.info("Statistics for " + ds + " are up-to-date" + ((lastDownload != null) ? " (" + lastDownload + ")" : "")); } }
Code Sample 2:
public static void fileCopy(String from_name, String to_name) throws IOException { File fromFile = new File(from_name); File toFile = new File(to_name); if (fromFile.equals(toFile)) abort("cannot copy on itself: " + from_name); if (!fromFile.exists()) abort("no such currentSourcepartName file: " + from_name); if (!fromFile.isFile()) abort("can't copy directory: " + from_name); if (!fromFile.canRead()) abort("currentSourcepartName file is unreadable: " + from_name); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) abort("destination file is unwriteable: " + to_name); } else { String parent = toFile.getParent(); if (parent == null) abort("destination directory doesn't exist: " + parent); File dir = new File(parent); if (!dir.exists()) abort("destination directory doesn't exist: " + parent); if (dir.isFile()) abort("destination is not a directory: " + parent); if (!dir.canWrite()) abort("destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int 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:
private File downloadPDB(String pdbId) { File tempFile = new File(path + "/" + pdbId + ".pdb.gz"); File pdbHome = new File(path); if (!pdbHome.canWrite()) { System.err.println("can not write to " + pdbHome); return null; } String ftp = String.format("ftp://ftp.ebi.ac.uk/pub/databases/msd/pdb_uncompressed/pdb%s.ent", pdbId.toLowerCase()); System.out.println("Fetching " + ftp); try { URL url = new URL(ftp); InputStream conn = url.openStream(); System.out.println("writing to " + tempFile); FileOutputStream outPut = new FileOutputStream(tempFile); GZIPOutputStream gzOutPut = new GZIPOutputStream(outPut); PrintWriter pw = new PrintWriter(gzOutPut); BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(conn)); String line; while ((line = fileBuffer.readLine()) != null) { pw.println(line); } pw.flush(); pw.close(); outPut.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); return null; } return tempFile; }
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 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:
void execute(HttpClient client, MonitoredService svc) { try { URI uri = getURI(svc); PageSequenceHttpMethod method = getMethod(); method.setURI(uri); if (getVirtualHost() != null) { method.getParams().setVirtualHost(getVirtualHost()); } if (getUserAgent() != null) { method.addRequestHeader("User-Agent", getUserAgent()); } if (m_parms.length > 0) { method.setParameters(m_parms); } if (m_page.getUserInfo() != null) { String userInfo = m_page.getUserInfo(); String[] streetCred = userInfo.split(":", 2); if (streetCred.length == 2) { client.getState().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(streetCred[0], streetCred[1])); method.setDoAuthentication(true); } } int code = client.executeMethod(method); if (!getRange().contains(code)) { throw new PageSequenceMonitorException("response code out of range for uri:" + uri + ". Expected " + getRange() + " but received " + code); } InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } String responseString = outputStream.toString(); if (getFailurePattern() != null) { Matcher matcher = getFailurePattern().matcher(responseString); if (matcher.find()) { throw new PageSequenceMonitorException(getResolvedFailureMessage(matcher)); } } if (getSuccessPattern() != null) { Matcher matcher = getSuccessPattern().matcher(responseString); if (!matcher.find()) { throw new PageSequenceMonitorException("failed to find '" + getSuccessPattern() + "' in page content at " + uri); } } } catch (URIException e) { throw new IllegalArgumentException("unable to construct URL for page: " + e, e); } catch (HttpException e) { throw new PageSequenceMonitorException("HTTP Error " + e, e); } catch (IOException e) { throw new PageSequenceMonitorException("I/O Error " + e, e); } }
|
11
|
Code Sample 1:
public static boolean writeFileB2C(InputStream pIs, File pFile, boolean pAppend) { boolean flag = false; try { FileWriter fw = new FileWriter(pFile, pAppend); IOUtils.copy(pIs, fw); fw.flush(); fw.close(); pIs.close(); flag = true; } catch (Exception e) { LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; }
Code Sample 2:
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(); } } }
|
00
|
Code Sample 1:
private String grabInformationFromWeb(String query, String infoName) throws Exception { String result = ""; URL url = new URL(query); HttpURLConnection request = null; request = (HttpURLConnection) url.openConnection(); if (request != null) { InputStream in = url.openStream(); int c = 0; StringBuilder sb = new StringBuilder(); while ((c = in.read()) != -1) { sb = sb.append((char) c); } String s = sb.toString(); result = Utils.getTagValue(s, "<" + infoName + ">", "</" + infoName + ">"); in.close(); } return result; }
Code Sample 2:
public void assign() throws Exception { if (proposalIds.equals("") || usrIds.equals("")) throw new Exception("No proposal or peer-viewer selected."); String[] pids = proposalIds.split(","); String[] uids = usrIds.split(","); int pnum = pids.length; int unum = uids.length; if (pnum == 0 || unum == 0) throw new Exception("No proposal or peer-viewer selected."); int i, j; String pStr = "update proposal set current_status='assigned' where "; for (i = 0; i < pnum; i++) { if (i > 0) pStr += " OR "; pStr += "PROPOSAL_ID=" + pids[i]; } Calendar date = Calendar.getInstance(); int day = date.get(Calendar.DATE); int month = date.get(Calendar.MONTH); int year = date.get(Calendar.YEAR); String dt = String.valueOf(year) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(day); PreparedStatement prepStmt = null; try { con = database.getConnection(); con.setAutoCommit(false); prepStmt = con.prepareStatement(pStr); prepStmt.executeUpdate(); pStr = "insert into event (summary,document1,document2,document3,publicComments,privateComments,ACTION_ID,eventDate,ROLE_ID,reviewText,USR_ID,PROPOSAL_ID,SUBJECTUSR_ID) values " + "('','','','','','','assigned','" + dt + "',2,'new'," + userId + ",?,?)"; prepStmt = con.prepareStatement(pStr); for (i = 0; i < pnum; i++) { for (j = 0; j < unum; j++) { prepStmt.setString(1, pids[i]); prepStmt.setString(2, uids[j]); prepStmt.executeUpdate(); } } con.commit(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } event_Form fr = new event_Form(); for (j = 0; j < unum; j++) { fr.setUSR_ID(userId); fr.setSUBJECTUSR_ID(uids[j]); systemManager.handleEvent(SystemManager.EVENT_PROPOSAL_ASSIGNED, fr, null, null); } }
|
00
|
Code Sample 1:
public static final String encryptMD5(String decrypted) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(decrypted.getBytes()); byte hash[] = md5.digest(); md5.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } }
Code Sample 2:
public static void main(String[] a) throws Exception { HashMap<String, Integer> numberOfOccurencesOfThisComboe = new HashMap<String, Integer>(); HashMap<String, String> fileToCATHMapping = new HashMap<String, String>(); ArrayList<String> allFilesToBeCopied = new ArrayList<String>(); new File(outputDir).mkdirs(); FileReader fis = new FileReader(completeFileWithDirToCathFileList); BufferedReader bis = new BufferedReader(fis); String line = ""; String currentCombo = ""; while ((line = bis.readLine()) != null) { String[] allEntries = line.split("\\s+"); String fileName = allEntries[0]; String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4]; String reducedComboForFilteringOut = allEntries[1] + allEntries[2] + allEntries[3]; fileToCATHMapping.put(fileName, reducedComboForFilteringOut); if (currentCombo.equals(thisCombo)) { } else { System.out.println("merke: " + fileName); allFilesToBeCopied.add(fileName); currentCombo = thisCombo; } } for (String fileName : allFilesToBeCopied) { String reducedComboForFilteringOut = fileToCATHMapping.get(fileName); if (!numberOfOccurencesOfThisComboe.containsKey(reducedComboForFilteringOut)) { numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, 1); } else { Integer thisCounter = numberOfOccurencesOfThisComboe.get(reducedComboForFilteringOut); thisCounter = thisCounter + 1; numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, thisCounter); } } HashSet<String> isSingleElement = new HashSet<String>(); for (Entry<String, Integer> thisEntry : numberOfOccurencesOfThisComboe.entrySet()) { if (thisEntry.getValue() == 1) { System.out.println("single: " + thisEntry.getKey()); isSingleElement.add(thisEntry.getKey()); } else { System.out.println("not single: " + thisEntry.getKey()); } } System.out.println(allFilesToBeCopied.size()); for (String file : allFilesToBeCopied) { if (!isSingleElement.contains(fileToCATHMapping.get(file))) { try { FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel(); FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } }
|
11
|
Code Sample 1:
public void execute(File tsvFile, File xmlFile) { BufferedReader reader = null; Writer writer = null; Boolean isFileSuccessfullyConverted = Boolean.TRUE; TableConfiguration tableConfig = null; try { xmlFile.getParentFile().mkdirs(); reader = new BufferedReader(new InputStreamReader(new FileInputStream(tsvFile), INPUT_ENCODING)); writer = new OutputStreamWriter(new FileOutputStream(xmlFile), OUTPUT_ENCODING); tableConfig = Tsv2DocbookConverter.convert2(tableConfigManager, idScanner.extractIdentification(tsvFile), reader, writer, inputPolisher); isFileSuccessfullyConverted = (tableConfig != null); } catch (UnsupportedEncodingException e) { logger.error("Failed to create reader with UTF-8 encoding: " + e.getMessage(), e); } catch (FileNotFoundException fnfe) { logger.error("Failed to open tsv input file '" + tsvFile + "'. " + fnfe.getMessage()); } catch (Throwable cause) { logger.error("Failed to convert input tsv file '" + tsvFile + "'.", cause); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { logger.warn("Unable to close input file.", ioe); } } if (writer != null) { try { writer.close(); } catch (IOException ioe) { logger.warn("Unable to close output file.", ioe); } } } if (isFileSuccessfullyConverted) { String newOutputFileName = tableConfig.getFileName(idScanner.extractIdentification(tsvFile)); if (newOutputFileName != null) { File newOutputFile = new File(xmlFile.getParentFile(), newOutputFileName); if (!xmlFile.renameTo(newOutputFile)) { logger.warn("Unable to rename '" + xmlFile + "' to '" + newOutputFile + "'."); logger.info("Created successfully '" + xmlFile + "'."); } else { logger.info("Created successfully '" + newOutputFileName + "'."); } } else { logger.info("Created successfully '" + xmlFile + "'."); } } else { logger.warn("Unable to convert input tsv file '" + Tsv2DocBookApplication.trimPath(sourceDir, tsvFile) + "' to docbook."); if (xmlFile.exists() && !xmlFile.delete()) { logger.warn("Unable to remove (empty) output file '" + xmlFile + "', which was created as target for the docbook table."); } } }
Code Sample 2:
public void copy(String original, String copy) throws SQLException { try { OutputStream out = openFileOutputStream(copy, false); InputStream in = openFileInputStream(original); IOUtils.copyAndClose(in, out); } catch (IOException e) { throw Message.convertIOException(e, "Can not copy " + original + " to " + copy); } }
|
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:
@Override protected String getRawPage(String url) throws IOException { HttpClient httpClient = new HttpClient(); String proxyHost = config.getString("proxy.host"), proxyPortString = config.getString("proxy.port"); if (proxyHost != null && proxyPortString != null) { int proxyPort = -1; try { proxyPort = Integer.parseInt(proxyPortString); } catch (NumberFormatException e) { } if (proxyPort != -1) { httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); } } GetMethod urlGet = new GetMethod(url); urlGet.setRequestHeader("Accept-Encoding", ""); urlGet.setRequestHeader("User-Agent", "Mozilla/5.0"); int retCode; if ((retCode = httpClient.executeMethod(urlGet)) != HttpStatus.SC_OK) { throw new RuntimeException("Unexpected HTTP code: " + retCode); } String encoding = null; Header contentType = urlGet.getResponseHeader("Content-Type"); if (contentType != null) { String contentTypeString = contentType.toString(); int i = contentTypeString.indexOf("charset="); if (i != -1) { encoding = contentTypeString.substring(i + "charset=".length()).trim(); } } boolean gzipped = false; Header contentEncoding = urlGet.getResponseHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { gzipped = true; } byte[] htmlData; try { InputStream in = gzipped ? new GZIPInputStream(urlGet.getResponseBodyAsStream()) : urlGet.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); htmlData = out.toByteArray(); in.close(); } finally { urlGet.releaseConnection(); } if (encoding == null) { Matcher m = Pattern.compile("(?i)<meta[^>]*charset=(([^\"]+\")|(\"[^\"]+\"))").matcher(new String(htmlData)); if (m.find()) { encoding = m.group(1).trim().replace("\"", ""); } } if (encoding == null) { encoding = "UTF-8"; } return new String(htmlData, encoding); }
|
11
|
Code Sample 1:
public static void main(String[] args) { String fe = null, fk = null, f1 = null, f2 = null; DecimalFormat df = new DecimalFormat("000"); int key = 0; int i = 1; for (; ; ) { System.out.println("==================================================="); System.out.println("\n2009 BME\tTeam ESC's Compare\n"); System.out.println("===================================================\n"); System.out.println(" *** Menu ***\n"); System.out.println("1. Fajlok osszehasonlitasa"); System.out.println("2. Hasznalati utasitas"); System.out.println("3. Kilepes"); System.out.print("\nKivalasztott menu szama: "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { key = reader.read(); switch(key) { case '3': System.exit(0); break; case '2': System.out.println("\n @author Bedo Zotlan - F3VFDE"); System.out.println("Team ESC's Compare"); System.out.println("2009."); System.out.println(); System.out.println("(1) A program ket fajl osszahesonlitasat vegzi. A fajloknak a program gyokerkonyvtaraban kell lenniuk!"); System.out.println("(2) A menubol ertelem szeruen valasztunk az opciok kozul, majd a program keresere megadjuk a ket osszehasonlitando " + "fajl nevet kiterjesztessel egyutt, kulonben hibat kapunk!"); System.out.println("(3) Miutan elvegeztuk az osszehasonlitasokat a program mindegyiket kimenti a compare_xxx.txt fajlba, azonban ha kilepunk a programbol, " + "majd utana ismet elinditjuk es elkezdunk osszehasonlitasokat vegezni, akkor felulirhatja " + "az elozo futtatasbol kapott fajlainkat, erre kulonosen figyelni kell!"); System.out.println("(4) A kimeneti compare_xxx.txt fajlon kivul minden egyes osszehasonlitott fajlrol csinal egy <fajl neve>.<fajl kiterjesztese>.numbered " + "nevu fajlt, ami annyiban ter el az eredeti fajloktol, hogy soronkent sorszamozva vannak!"); System.out.println("(5) Egy nem ures es egy ures fajl osszehasonlitasa utan azt az eredmenyt kapjuk, hogy \"OK, megyezenek!\". Ez termeszetesen hibas" + " es a kimeneti fajlunk is ures lesz. Ezt szinten keruljuk el, ne hasonlitsunk ures fajlokhoz mas fajlokat!"); System.out.println("(6) A fajlok megtekintesehez Notepad++ 5.0.0 verzioja ajanlott legalabb!\n"); break; case '1': { System.out.print("\nAz etalon adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fe = (inFileName + ".numbered"); f1 = inFileName; String aLine; while ((aLine = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } System.out.print("A kapott adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fk = (inFileName + ".numbered"); f2 = inFileName; String aLine_k; while ((aLine_k = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine_k + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } try { int lnNo_c = 1; int mstk = 0; BufferedReader bin_e = new BufferedReader(new FileReader(fe)); BufferedReader bin_k = new BufferedReader(new FileReader(fk)); BufferedWriter bout = new BufferedWriter(new FileWriter("compare_" + i++ + ".txt")); Calendar actDate = Calendar.getInstance(); bout.write("==================================================\n"); bout.write("\n2009 BME\tTeam ESC's Compare"); bout.write("\n" + actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n\n"); bout.write("==================================================\n"); bout.write("Az etalon ertekekkel teli fajl neve: " + f1 + "\n"); bout.write("A kapott ertekekkel teli fajl neve: " + f2 + "\n\n"); System.out.println("==================================================\n"); System.out.println("\n2009 BME\tTeam ESC's Compare"); System.out.println(actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n"); System.out.println("==================================================\n"); System.out.println("\nAz etalon ertekekkel teli fajl neve: " + f1); System.out.println("A kapott ertekekkel teli fajl neve: " + f2 + "\n"); String aLine_c1 = null, aLine_c2 = null; File fa = new File(fe); File fb = new File(fk); if (fa.length() != fb.length()) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); } else { while (((aLine_c1 = bin_e.readLine()) != null) && ((aLine_c2 = bin_k.readLine()) != null)) if (aLine_c1.equals(aLine_c2)) { } else { mstk++; bout.write("#" + df.format(lnNo_c) + ": HIBA --> \t" + f1 + " : " + aLine_c1 + " \n\t\t\t\t\t" + f2 + " : " + aLine_c2 + "\n"); System.out.println("#" + df.format(lnNo_c) + ": HIBA -->\t " + f1 + " : " + aLine_c1 + " \n\t\t\t" + f2 + " : " + aLine_c2 + "\n"); lnNo_c++; } if (mstk != 0) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); bout.write("\nHibas sorok szama: " + mstk); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); System.out.println("Hibas sorok szama: " + mstk); } else { bout.write("\nOsszehasonlitas eredmenye: OK, megegyeznek!"); System.out.println("\nOsszehasonlitas eredm�nye: OK, megegyeznek!\n"); } } bin_e.close(); bin_k.close(); fa.delete(); fb.delete(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajl"); } break; } } } catch (Exception e) { System.out.println("A fut�s sor�n hiba t�rt�nt!"); } } }
Code Sample 2:
public static boolean copyFile(File src, File dest) throws IOException { if (src == null) { throw new IllegalArgumentException("src == null"); } if (dest == null) { throw new IllegalArgumentException("dest == null"); } if (!src.isFile()) { return false; } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); try { in.transferTo(0, in.size(), out); return true; } catch (IOException e) { throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void unzip2(String strZipFile, String folder) throws IOException, ArchiveException { FileUtil.fileExists(strZipFile, true); final InputStream is = new FileInputStream(strZipFile); ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; OutputStream out = null; while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) { File zipPath = new File(folder); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { out = new FileOutputStream(new File(folder, entry.getName())); IOUtils.copy(in, out); out.close(); } } in.close(); }
|
11
|
Code Sample 1:
public static void main(String args[]) throws Exception { File file = new File("D:/work/love.txt"); @SuppressWarnings("unused") ZipFile zipFile = new ZipFile("D:/work/test1.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("D:/work/test1.zip")); zos.setEncoding("GBK"); ZipEntry entry = null; if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); int readLen = 0; byte[] buf = new byte[2048]; if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 2048)) != -1) { zos.write(buf, 0, readLen); } in.close(); } zos.close(); }
Code Sample 2:
public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { size = outputFile.length(); if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } }
|
00
|
Code Sample 1:
public static String convetToSignature(Map<String, String> keyVal, String apiSecret) { if (keyVal == null || apiSecret == null || keyVal.size() <= 0 || apiSecret.trim().equals("")) { throw new IllegalArgumentException("keyVal or api secret is not valid. Please Check it again."); } Iterator<Entry<String, String>> iterator = keyVal.entrySet().iterator(); StringBuffer rslt = new StringBuffer(); byte[] signature = null; while (iterator.hasNext()) { Entry<String, String> entry = iterator.next(); rslt.append(entry.getKey()); rslt.append("="); rslt.append(entry.getValue()); } rslt.append(apiSecret); try { MessageDigest md5 = MessageDigest.getInstance(HASHING_METHOD); md5.reset(); md5.update(rslt.toString().getBytes()); rslt.delete(0, rslt.length()); signature = md5.digest(); for (int i = 0; i < signature.length; i++) { String hex = Integer.toHexString(0xff & signature[i]); if (hex.length() == 1) { rslt.append('0'); } rslt.append(hex); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return rslt.toString(); }
Code Sample 2:
private void postObject(Object obj, String strURL) throws Exception { print("entering post object"); URL url = new URL(strURL); URLConnection urlConn = url.openConnection(); print("HttpNetworkMessageConnection.postObject:returned from url.openConnection()"); urlConn.setUseCaches(false); urlConn.setDoOutput(true); ObjectOutputStream oos = new ObjectOutputStream(urlConn.getOutputStream()); print("HttpNetworkMessageConnection.postObject:returned from urlConn.getOutputStream()"); oos.writeObject(obj); print("HttpNetworkMessageConnection.postObject:returned from writeObject()"); oos.flush(); oos.close(); InputStream is = urlConn.getInputStream(); print("HttpNetworkMessageConnection.postObject:returned from getInputStream()"); while (is.read() != -1) { } is.close(); print("exiting postObject"); }
|
00
|
Code Sample 1:
@Override public void convert() throws Exception { URL url = new URL("http://qsardb.jrc.it/qmrf/download.jsp?filetype=xml&id=" + Integer.parseInt(this.id)); InputStream is = url.openStream(); try { QMRF qmrf = QmrfUtil.loadQmrf(is); Qmrf2Qdb.convert(getQdb(), qmrf); } finally { is.close(); } }
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(); }
|
00
|
Code Sample 1:
private String read(URL url) throws IOException { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer text = new StringBuffer(); String line; while ((line = in.readLine()) != null) { text.append(line); } return text.toString(); } finally { in.close(); } }
Code Sample 2:
public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
|
11
|
Code Sample 1:
public String getHash(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] toChapter1Digest = md.digest(); return Keystore.hexEncode(toChapter1Digest); } catch (Exception e) { logger.error("Error in creating DN hash: " + e.getMessage()); return null; } }
Code Sample 2:
public static String getSHA1Digest(String inputStr) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; byte[] sha1hash = null; md = MessageDigest.getInstance("SHA"); sha1hash = new byte[40]; md.update(inputStr.getBytes("iso-8859-1"), 0, inputStr.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
|
00
|
Code Sample 1:
public static byte[] wrapBMP(Image image) throws IOException { if (image.getOriginalType() != Image.ORIGINAL_BMP) throw new IOException("Only BMP can be wrapped in WMF."); InputStream imgIn; byte data[] = null; if (image.getOriginalData() == null) { imgIn = image.url().openStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int b = 0; while ((b = imgIn.read()) != -1) out.write(b); imgIn.close(); data = out.toByteArray(); } else data = image.getOriginalData(); int sizeBmpWords = (data.length - 14 + 1) >>> 1; ByteArrayOutputStream os = new ByteArrayOutputStream(); writeWord(os, 1); writeWord(os, 9); writeWord(os, 0x0300); writeDWord(os, 9 + 4 + 5 + 5 + (13 + sizeBmpWords) + 3); writeWord(os, 1); writeDWord(os, 14 + sizeBmpWords); writeWord(os, 0); writeDWord(os, 4); writeWord(os, META_SETMAPMODE); writeWord(os, 8); writeDWord(os, 5); writeWord(os, META_SETWINDOWORG); writeWord(os, 0); writeWord(os, 0); writeDWord(os, 5); writeWord(os, META_SETWINDOWEXT); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeDWord(os, 13 + sizeBmpWords); writeWord(os, META_DIBSTRETCHBLT); writeDWord(os, 0x00cc0020); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeWord(os, 0); writeWord(os, 0); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeWord(os, 0); writeWord(os, 0); os.write(data, 14, data.length - 14); if ((data.length & 1) == 1) os.write(0); writeDWord(os, 3); writeWord(os, 0); os.close(); return os.toByteArray(); }
Code Sample 2:
public void onUpload$btnFileUpload(UploadEvent ue) { BufferedInputStream in = null; BufferedOutputStream out = null; if (ue == null) { System.out.println("unable to upload file"); return; } else { System.out.println("fileUploaded()"); } try { Media m = ue.getMedia(); System.out.println("m.getContentType(): " + m.getContentType()); System.out.println("m.getFormat(): " + m.getFormat()); try { InputStream is = m.getStreamData(); in = new BufferedInputStream(is); File baseDir = new File(UPLOAD_PATH); if (!baseDir.exists()) { baseDir.mkdirs(); } final File file = new File(UPLOAD_PATH + m.getName()); OutputStream fout = new FileOutputStream(file); out = new BufferedOutputStream(fout); IOUtils.copy(in, out); if (m.getFormat().equals("zip") || m.getFormat().equals("x-gzip")) { final String filename = m.getName(); Messagebox.show("Archive file detected. Would you like to unzip this file?", "ALA Spatial Portal", Messagebox.YES + Messagebox.NO, Messagebox.QUESTION, new EventListener() { @Override public void onEvent(Event event) throws Exception { try { int response = ((Integer) event.getData()).intValue(); if (response == Messagebox.YES) { System.out.println("unzipping file to: " + UPLOAD_PATH); boolean success = Zipper.unzipFile(filename, new FileInputStream(file), UPLOAD_PATH, false); if (success) { Messagebox.show("File unzipped: '" + filename + "'"); } else { Messagebox.show("Unable to unzip '" + filename + "' "); } } else { System.out.println("leaving archive file alone"); } } catch (NumberFormatException nfe) { System.out.println("Not a valid response"); } } }); } else { Messagebox.show("File '" + m.getName() + "' successfully uploaded"); } } catch (IOException e) { System.out.println("IO Exception while saving file: "); e.printStackTrace(System.out); } catch (Exception e) { System.out.println("General Exception: "); e.printStackTrace(System.out); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException e) { System.out.println("IO Exception while closing stream: "); e.printStackTrace(System.out); } } } catch (Exception e) { System.out.println("Error uploading file."); e.printStackTrace(System.out); } }
|
00
|
Code Sample 1:
private static String fetchUrl(String url, boolean keepLineEnds) throws IOException, MalformedURLException { URLConnection destConnection = (new URL(url)).openConnection(); BufferedReader br; String inputLine; StringBuffer doc = new StringBuffer(); String contentEncoding; destConnection.setRequestProperty("Accept-Encoding", "gzip"); if (proxyAuth != null) destConnection.setRequestProperty("Proxy-Authorization", proxyAuth); destConnection.connect(); contentEncoding = destConnection.getContentEncoding(); if ((contentEncoding != null) && contentEncoding.equals("gzip")) { br = new BufferedReader(new InputStreamReader(new GZIPInputStream(destConnection.getInputStream()))); } else { br = new BufferedReader(new InputStreamReader(destConnection.getInputStream())); } while ((inputLine = br.readLine()) != null) { if (keepLineEnds) doc.append(inputLine + "\n"); else doc.append(inputLine); } br.close(); return doc.toString(); }
Code Sample 2:
@Override public void delArtista(Integer numeroInscricao) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "delete from artista where numeroinscricao = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, numeroInscricao); ps.executeUpdate(); delEndereco(conn, ps, numeroInscricao); delObras(conn, ps, numeroInscricao); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } }
|
11
|
Code Sample 1:
private static Vector<String> getIgnoreList() { try { URL url = DeclarationTranslation.class.getClassLoader().getResource("ignorelist"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); Vector<String> ret = new Vector<String>(); String line = null; while ((line = bufferedReader.readLine()) != null) { ret.add(line); } return ret; } catch (Exception e) { return null; } }
Code Sample 2:
String openUrlAsString(String address, int maxLines) { StringBuffer sb; try { URL url = new URL(address); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); sb = new StringBuffer(); int count = 0; String line; while ((line = br.readLine()) != null && count++ < maxLines) sb.append(line + "\n"); in.close(); } catch (IOException e) { sb = null; } return sb != null ? new String(sb) : null; }
|
00
|
Code Sample 1:
public static void retrieveAttachments(RemoteAttachment[] attachments, String id, String projectName, String key, SimpleDateFormat formatter, java.sql.Connection connect) { if (attachments.length != 0) { for (RemoteAttachment attachment : attachments) { attachmentAuthor = attachment.getAuthor(); if (attachment.getCreated() != null) { attachmentCreated = formatter.format(attachment.getCreated().getTime()); } attachmentFileName = attachment.getFilename(); attachmentFileSize = attachment.getFilesize(); attachmentId = attachment.getId(); attachmentMimeType = attachment.getMimetype(); if (attachmentMimeType.startsWith("text")) { URL attachmentUrl; try { attachmentUrl = new URL("https://issues.apache.org/jira/secure/attachment/" + attachmentId + "/" + attachmentFileName); urlConnection = (HttpURLConnection) attachmentUrl.openConnection(); urlConnection.connect(); serverCode = urlConnection.getResponseCode(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (serverCode == 200) { actual = new File("../attachments/" + projectName + "/" + key); if (!actual.exists()) { actual.mkdirs(); } attachmentPath = "../attachments/" + projectName + "/" + key + "/" + attachmentFileName; BufferedInputStream bis; try { bis = new BufferedInputStream(urlConnection.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(attachmentPath)); byte[] b = new byte[1024]; int len = -1; while ((len = bis.read(b)) != -1) { if (len == 1024) { bos.write(b); } else { bos.write(b, 0, len); } } bos.close(); bis.close(); insertAttachment(connect, id); } catch (IOException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } } } }
Code Sample 2:
public static byte[] excutePostRaw(String targetURL, byte[] postdata) { URL url; HttpURLConnection connection = null; try { url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(postdata.length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.write(postdata); wr.flush(); wr.close(); int amt = connection.getContentLength(); InputStream in = connection.getInputStream(); MojasiWriter writer = new MojasiWriter(); byte[] buff = new byte[256]; while (writer.size() < amt) { int got = in.read(buff); if (got < 0) break; writer.pushBytes(buff, got); if (writer.size() > 1) System.out.println(); } in.close(); connection.disconnect(); return writer.getBytes(); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (connection != null) { connection.disconnect(); } } }
|
00
|
Code Sample 1:
public String execute(HttpServletRequest request, HttpServletResponse response, User user, String parameter) throws Exception { long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L); BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, parameter, user); response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"'); String contentType = binaryAttribute.getContentType(); if (contentType != null) { if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) { response.setContentType("application/octet-stream"); } else { response.setContentType(contentType); } } else { response.setContentType("application/octet-stream"); } IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream()); return null; }
Code Sample 2:
public static TikaInputStream get(URL url, Metadata metadata) throws IOException { if ("file".equalsIgnoreCase(url.getProtocol())) { try { File file = new File(url.toURI()); if (file.isFile()) { return get(file, metadata); } } catch (URISyntaxException e) { } } URLConnection connection = url.openConnection(); String path = url.getPath(); int slash = path.lastIndexOf('/'); if (slash + 1 < path.length()) { metadata.set(Metadata.RESOURCE_NAME_KEY, path.substring(slash + 1)); } String type = connection.getContentType(); if (type != null) { metadata.set(Metadata.CONTENT_TYPE, type); } String encoding = connection.getContentEncoding(); if (encoding != null) { metadata.set(Metadata.CONTENT_ENCODING, encoding); } int length = connection.getContentLength(); if (length >= 0) { metadata.set(Metadata.CONTENT_LENGTH, Integer.toString(length)); } return new TikaInputStream(new BufferedInputStream(connection.getInputStream()), new TemporaryResources(), length); }
|
00
|
Code Sample 1:
public void retrieveChallenge() throws MalformedURLException, IOException, FBConnectionException, FBErrorException { URL url = new URL(getHost() + getPath()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("X-FB-User", getUser()); conn.setRequestProperty("X-FB-Mode", "GetChallenge"); conn.connect(); Element fbresponse; try { fbresponse = readXML(conn); } catch (FBConnectionException fbce) { error = true; throw fbce; } catch (FBErrorException fbee) { error = true; throw fbee; } catch (Exception e) { error = true; FBConnectionException fbce = new FBConnectionException("XML parsing failed"); fbce.attachSubException(e); throw fbce; } NodeList nl = fbresponse.getElementsByTagName("GetChallengeResponse"); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof Element && hasError((Element) nl.item(i))) { error = true; FBErrorException e = new FBErrorException(); e.setErrorCode(errorcode); e.setErrorText(errortext); throw e; } } NodeList challenge = fbresponse.getElementsByTagName("Challenge"); for (int i = 0; i < challenge.getLength(); i++) { NodeList children = challenge.item(i).getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (children.item(j) instanceof Text) { challenges.offer(children.item(j).getNodeValue()); } } } }
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(); } }
|
00
|
Code Sample 1:
private JButton getButtonSonido() { if (buttonSonido == null) { buttonSonido = new JButton(); buttonSonido.setText(Messages.getString("gui.AdministracionResorces.15")); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetree.png")); buttonSonido.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetreeOK.png")); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonSonido; }
Code Sample 2:
private void fetch() throws IOException { if (getAttachmentUrl() != null && (!getAttachmentUrl().isEmpty())) { InputStream input = null; ByteArrayOutputStream output = null; try { URL url = new URL(getAttachmentUrl()); input = url.openStream(); output = new ByteArrayOutputStream(); int i; while ((i = input.read()) != -1) { output.write(i); } this.data = output.toByteArray(); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } } } }
|
11
|
Code Sample 1:
protected void migrateOnDemand() { try { if (fso.fileExists(prefix + ".fat") && !fso.fileExists(prefix + EXTENSIONS[UBM_FILE])) { RandomAccessFile ubm, meta, ctr, rbm; InputStream inputStream; OutputStream outputStream; fso.renameFile(prefix + ".fat", prefix + EXTENSIONS[UBM_FILE]); ubm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); meta = fso.openFile(prefix + EXTENSIONS[MTD_FILE], "rw"); ctr = fso.openFile(prefix + EXTENSIONS[CTR_FILE], "rw"); ubm.seek(ubm.length() - 16); meta.writeInt(blockSize = ubm.readInt()); meta.writeInt(size = ubm.readInt()); ctr.setLength(ubm.readLong() + blockSize); ctr.close(); meta.close(); ubm.setLength(ubm.length() - 16); ubm.seek(0); rbm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); inputStream = new BufferedInputStream(new RandomAccessFileInputStream(ubm)); outputStream = new BufferedOutputStream(new RandomAccessFileOutputStream(rbm)); for (int b; (b = inputStream.read()) != -1; ) outputStream.write(b); outputStream.close(); inputStream.close(); rbm.close(); ubm.close(); } } catch (IOException ie) { throw new WrappingRuntimeException(ie); } }
Code Sample 2:
@Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + httpServletRequest.getQueryString()); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + baos.toString()); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); }
|
00
|
Code Sample 1:
public InputStream getDaoConfig(String connectionType) throws IOException { URL url = null; InputStream inStream = null; if (connectionType.equals(SQL.ORACLE)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("oracle.xml"); } else if (connectionType.equals(SQL.SQL2K)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("sql2k.xml"); } else if (connectionType.equals(SQL.CACHE)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("cache.xml"); } else if (connectionType.equals(SQL.DB2)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("db2.xml"); } else { Categories.dataXml().error("* Problem: Unknown connection type: " + connectionType); } try { inStream = url.openStream(); } catch (NullPointerException npe) { Categories.dataXml().error("* Problem: Undefined resource URL: " + npe.getMessage()); throw npe; } return inStream; }
Code Sample 2:
public static String encripta(String senha) throws GCIException { LOGGER.debug(INICIANDO_METODO + "encripta(String)"); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException e) { LOGGER.fatal(e.getMessage(), e); throw new GCIException(e); } finally { LOGGER.debug(FINALIZANDO_METODO + "encripta(String)"); } }
|
11
|
Code Sample 1:
public static void copy(File from_file, File to_file) throws IOException { if (!from_file.exists()) abort("FileCopy: no such source file: " + from_file.getName()); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_file.getName()); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_file.getName()); 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_file.getName()); } 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) { e.printStackTrace(); } } if (to != null) { try { to.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
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:
private DataFileType[] getDataFiles(Collection<ContentToSend> contentsToSend) { DataFileType[] files = new DataFileType[contentsToSend.size()]; int fileIndex = 0; for (ContentToSend contentToSend : contentsToSend) { DataFileType dataFile = DataFileType.Factory.newInstance(); dataFile.setFilename(contentToSend.getFileName()); dataFile.setId("D" + fileIndex); dataFile.setMimeType(contentToSend.getMimeType()); dataFile.setContentType(DataFileType.ContentType.EMBEDDED_BASE_64); final StringWriter stringWriter = new StringWriter(); final OutputStream encodeStream = Base64.newEncoder(stringWriter, 0, null); final InputStream is = contentToSend.getInputStream(); try { long sizeCopied = IOUtils.copyLarge(is, encodeStream); dataFile.setSize(BigDecimal.valueOf(sizeCopied)); } catch (IOException e) { throw new RuntimeException("Failed to get input to the file to be sent", e); } finally { IOUtils.closeQuietly(encodeStream); IOUtils.closeQuietly(is); } dataFile.setStringValue(stringWriter.toString()); files[fileIndex++] = dataFile; } return files; }
|
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 static IBiopaxModel read(URL url) throws ReactionException, IOException { IBiopaxModel model = null; InputStream in = null; try { in = url.openStream(); model = read(in); } catch (IOException e) { LOGGER.error("Unable to read from URL " + url, e); } finally { if (in != null) in.close(); } return model; }
|
00
|
Code Sample 1:
public static InputStream sendReq(String url, String content, ConnectData data) { try { URLConnection con = new URL(url).openConnection(); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); con.setUseCaches(false); setUA(con); con.setRequestProperty("Accept-Charset", "utf-8"); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (data.cookie != null) con.setRequestProperty("Cookie", data.cookie); HttpURLConnection httpurl = (HttpURLConnection) con; httpurl.setRequestMethod("POST"); Writer wr = new OutputStreamWriter(con.getOutputStream()); wr.write(content); wr.flush(); con.connect(); InputStream is = con.getInputStream(); is = new BufferedInputStream(is); wr.close(); parseCookie(con, data); return is; } catch (IOException ioe) { Log.except("failed to send request " + url, ioe); } return null; }
Code Sample 2:
public static void copyCompletely(InputStream input, OutputStream output) throws IOException { if ((output instanceof FileOutputStream) && (input instanceof FileInputStream)) { try { FileChannel target = ((FileOutputStream) output).getChannel(); FileChannel source = ((FileInputStream) input).getChannel(); source.transferTo(0, Integer.MAX_VALUE, target); source.close(); target.close(); return; } catch (Exception e) { } } byte[] buf = new byte[8192]; while (true) { int length = input.read(buf); if (length < 0) break; output.write(buf, 0, length); } try { input.close(); } catch (IOException ignore) { } try { output.close(); } catch (IOException ignore) { } }
|
00
|
Code Sample 1:
@Override public void onClick(View v) { username = textusername.getText().toString(); password = textpassword.getText().toString(); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new name_value("uname", username)); nameValuePairs.add(new name_value("upass", password)); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.gotrackit.net/server/check_user.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection" + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line = "0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } if (result.contains("reject")) { Context context = getApplicationContext(); int duration = Toast.LENGTH_SHORT; String wrong = "Invalid Username or Password"; Toast toast = Toast.makeText(context, wrong, duration); toast.show(); } else { MyApp uid = (MyApp) getApplicationContext(); uid.setStringValue(result); Intent myintent = new Intent(v.getContext(), UserMap.class); startActivityForResult(myintent, 0); } }
Code Sample 2:
public static boolean compress(File source, File target, Manifest manifest) { try { if (!(source.exists() & source.isDirectory())) return false; if (target.exists()) target.delete(); ZipOutputStream output = null; boolean isJar = target.getName().toLowerCase().endsWith(".jar"); if (isJar) { File manifestDir = new File(source, "META-INF"); remove(manifestDir); if (manifest != null) output = new JarOutputStream(new FileOutputStream(target), manifest); else output = new JarOutputStream(new FileOutputStream(target)); } else output = new ZipOutputStream(new FileOutputStream(target)); ArrayList list = getContents(source); String baseDir = source.getAbsolutePath().replace('\\', '/'); if (!baseDir.endsWith("/")) baseDir = baseDir + "/"; int baseDirLength = baseDir.length(); byte[] buffer = new byte[1024]; int bytesRead; for (int i = 0, n = list.size(); i < n; i++) { File file = (File) list.get(i); FileInputStream f_in = new FileInputStream(file); String filename = file.getAbsolutePath().replace('\\', '/'); if (filename.startsWith(baseDir)) filename = filename.substring(baseDirLength); if (isJar) output.putNextEntry(new JarEntry(filename)); else output.putNextEntry(new ZipEntry(filename)); while ((bytesRead = f_in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); f_in.close(); output.closeEntry(); } output.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; }
|
11
|
Code Sample 1:
public void xtest11() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/UML2.pdf"); InputStream page1 = manager.cut(pdf, 1, 1); OutputStream outputStream = new FileOutputStream("/tmp/page.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
public static void copyFile(final File fromFile, File toFile) throws IOException { try { if (!fromFile.exists()) { throw new IOException("FileCopy: " + "no such source file: " + fromFile.getAbsoluteFile()); } if (!fromFile.isFile()) { throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getAbsoluteFile()); } if (!fromFile.canRead()) { throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getAbsoluteFile()); } if (toFile.isDirectory()) { toFile = new File(toFile, fromFile.getName()); } if (toFile.exists() && !toFile.canWrite()) { throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getAbsoluteFile()); } final FileChannel inChannel = new FileInputStream(fromFile).getChannel(); final FileChannel outChannel = new FileOutputStream(toFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (final IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("CopyFile went wrong!", e); } } }
Code Sample 2:
@Override protected void writeFile() { super.writeFile(); try { String tagListFilePath = file.toURI().toASCIIString(); tagListFilePath = tagListFilePath.substring(0, tagListFilePath.lastIndexOf(FileManager.GLIPS_VIEW_EXTENSION)) + FileManager.TAG_LIST_FILE_EXTENSION; File tagListFile = new File(new URI(tagListFilePath)); StringBuffer buffer = new StringBuffer(""); for (String tagName : tags) { buffer.append(tagName + "\n"); } ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.toString().getBytes("UTF-8")); FileOutputStream out = new FileOutputStream(tagListFile); FileChannel channel = out.getChannel(); channel.write(byteBuffer); channel.close(); } catch (Exception ex) { } try { String parentPath = file.getParentFile().toURI().toASCIIString(); if (!parentPath.endsWith("/")) { parentPath += "/"; } File srcFile = null, destFile = null; byte[] tab = new byte[1000]; int nb = 0; InputStream in = null; OutputStream out = null; for (String destinationName : dataBaseFiles.keySet()) { srcFile = dataBaseFiles.get(destinationName); if (srcFile != null) { destFile = new File(new URI(parentPath + destinationName)); in = new BufferedInputStream(new FileInputStream(srcFile)); out = new BufferedOutputStream(new FileOutputStream(destFile)); while (in.available() > 0) { nb = in.read(tab); if (nb > 0) { out.write(tab, 0, nb); } } in.close(); out.flush(); out.close(); } } } catch (Exception ex) { ex.printStackTrace(); } }
|
00
|
Code Sample 1:
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnClear) { passwordField.setText(""); } for (int i = 0; i < 10; i++) { if (e.getSource() == btnNumber[i]) { String password = new String((passwordField.getPassword())); passwordField.setText(password + i); } } if (e.getSource() == btnOK) { String password = new String((passwordField.getPassword())); ResultSet rs; Statement stmt; String sql; String result = ""; boolean checkPassword = false; sql = "select password from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("password"); } rs.close(); stmt.close(); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) checkPassword = true; else checkPassword = false; } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (checkPassword == true) { JOptionPane.showMessageDialog(null, "senha correta!"); sql = "delete from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } setVisible(false); setTries(0); Error.log(4003, "Senha de uso �nico verificada positivamente."); Error.log(4002, "Autentica��o etapa 3 encerrada."); ManagerWindow mw = new ManagerWindow(login); mw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { JOptionPane.showMessageDialog(null, "senha incorreta!"); int tries = getTries(); if (tries == 0) { Error.log(4004, "Primeiro erro da senha de uso �nico contabilizado."); } else if (tries == 1) { Error.log(4005, "Segundo erro da senha de uso �nico contabilizado."); } else if (tries == 2) { Error.log(4006, "Terceiro erro da senha de uso �nico contabilizado."); Error.log(4007, "Acesso do usuario " + login + " bloqueado pela autentica��o etapa 3."); Error.log(4002, "Autentica��o etapa 3 encerrada."); Error.log(1002, "Sistema encerrado."); setTries(++tries); System.exit(1); } setTries(++tries); } } }
Code Sample 2:
public boolean loadURL(URL url) { try { _properties.load(url.openStream()); Argo.log.info("Configuration loaded from " + url + "\n"); return true; } catch (Exception e) { if (_canComplain) Argo.log.warn("Unable to load configuration " + url + "\n"); _canComplain = false; return false; } }
|
00
|
Code Sample 1:
public void reademi(Vector<String> descriptions, Vector<String> links, String linkaddress, String idmap) { InputStream is = null; URL url; ArrayList<String> keys = new ArrayList<String>(); ArrayList<String> names = new ArrayList<String>(); try { url = new URL(idmap); is = url.openStream(); Scanner scanner = new Scanner(is); scanner.nextLine(); String line = ""; String id = ""; while (scanner.hasNextLine()) { line = scanner.nextLine(); Scanner linescanner = new Scanner(line); linescanner.useDelimiter("\t"); id = linescanner.next(); id = id.substring(0, id.length() - 2); keys.add(id); linescanner.next(); linescanner.next(); linescanner.next(); linescanner.useDelimiter("\n"); names.add(linescanner.next()); } BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(linkaddress).openStream())); String link = ""; String key = ""; String name = ""; int counter = 0; while ((line = reader.readLine()) != null) { if (line.indexOf("style=raw") != -1) { int linkstart = line.indexOf("http://www.ebi.ac.uk/cgi-bin/dbfetch?db"); int idstart = line.indexOf("id=") + 3; int linkend = line.substring(linkstart).indexOf("\"") + linkstart; link = line.substring(linkstart, linkend); key = line.substring(idstart, linkend); if (keys.indexOf(key) != -1) { name = names.get(keys.indexOf(key)); counter++; descriptions.add(counter + " " + key + " " + name); links.add(link); } } } } catch (MalformedURLException e) { } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private void modifyEntry(ModifyInterceptorChain chain, DistinguishedName dn, ArrayList<LDAPModification> mods, Connection con) throws LDAPException { try { con.setAutoCommit(false); HashMap<String, String> ldap2db = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_LDAP2DB + this.dbInsertName); Iterator<LDAPModification> it = mods.iterator(); String sql = "UPDATE " + this.tableName + " SET "; while (it.hasNext()) { LDAPModification mod = it.next(); if (mod.getOp() != LDAPModification.REPLACE) { throw new LDAPException("Only modify replace allowed", LDAPException.OBJECT_CLASS_VIOLATION, ""); } sql += ldap2db.get(mod.getAttribute().getName()) + "=? "; } sql += " WHERE " + this.rdnField + "=?"; PreparedStatement ps = con.prepareStatement(sql); it = mods.iterator(); int i = 1; while (it.hasNext()) { LDAPModification mod = it.next(); ps.setString(i, mod.getAttribute().getStringValue()); i++; } String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); ps.setString(i, uid); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } }
|
00
|
Code Sample 1:
public static String getDigestResponse(String user, String password, String method, String requri, String authstr) { String realm = ""; String nonce = ""; String opaque = ""; String algorithm = ""; String qop = ""; StringBuffer digest = new StringBuffer(); String cnonce; String noncecount; String pAuthStr = authstr; int ptr = 0; String response = ""; int i = 0; StringTokenizer st = new StringTokenizer(pAuthStr, ","); StringTokenizer stprob = null; String str = null; String key = null; String value = null; Properties probs = new Properties(); while (st.hasMoreTokens()) { String nextToken = st.nextToken(); stprob = new StringTokenizer(nextToken, "="); key = stprob.nextToken(); value = stprob.nextToken(); if (value.charAt(0) == '"' || value.charAt(0) == '\'') { value = value.substring(1, value.length() - 1); } probs.put(key, value); } digest.append("Digest username=\"" + user + "\", "); digest.append("realm=\""); digest.append(probs.getProperty("realm")); digest.append("\", "); digest.append("nonce=\""); digest.append(probs.getProperty("nonce")); digest.append("\", "); digest.append("uri=\"" + requri + "\", "); cnonce = "abcdefghi"; noncecount = "00000001"; String toDigest = user + ":" + realm + ":" + password; byte[] digestbuffer = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toDigest.getBytes()); digestbuffer = md.digest(); } catch (Exception e) { System.err.println("Error creating digest request: " + e); return null; } digest.append("qop=\"auth\", "); digest.append("cnonce=\"" + cnonce + "\", "); digest.append("nc=" + noncecount + ", "); digest.append("response=\"" + response + "\""); if (probs.getProperty("opaque") != null) { digest.append(", opaque=\"" + probs.getProperty("opaque") + "\""); } System.out.println("SipProtocol: Digest calculated."); return digest.toString(); }
Code Sample 2:
public boolean checkTypeChange(Class<?> clazz, File buildDir, File refFile) throws MojoExecutionException { if (!clazz.isPrimitive()) { ClassLoader cl = clazz.getClassLoader(); if (cl == loader) { if (clazz.isArray()) return checkTypeChange(getArrayType(clazz), buildDir, refFile); String path = clazz.getName().replace('.', File.separatorChar) + ".class"; File file = new File(buildDir, path); long lastMod = Long.MAX_VALUE; if (!file.exists()) { URL url = cl.getResource(path); if (url == null) throw new MojoExecutionException("Can't get URL for webservice class '" + clazz.getName() + "' from jar file."); else { try { JarURLConnection con = (JarURLConnection) url.openConnection(); lastMod = con.getJarEntry().getTime(); } catch (IOException x) { throw new MojoExecutionException("Can't get modification time for webservice class '" + clazz.getName() + "' from jar file."); } } } else { lastMod = file.lastModified(); } if (refFile.lastModified() < lastMod) return true; if (clazz.isInterface()) { Class<?>[] itfs = clazz.getInterfaces(); for (int i = 0; i < itfs.length; i++) { boolean changed = checkTypeChange(itfs[i], buildDir, refFile); if (changed) return true; } } else { Class<?> sup = clazz.getSuperclass(); boolean changed = checkTypeChange(sup, buildDir, refFile); if (changed) return true; } } } return false; }
|
00
|
Code Sample 1:
public void executeAction(JobContext context) throws Exception { HttpClient httpClient = (HttpClient) context.resolve("httpClient"); List<NameValuePair> qparams = new ArrayList<NameValuePair>(); Iterator<String> keySet = params.keySet().iterator(); while (keySet.hasNext()) { String key = keySet.next(); String value = params.get(key); qparams.add(new BasicNameValuePair(key, value)); } String paramString = URLEncodedUtils.format(qparams, "UTF-8"); if (this.url.endsWith("/")) { this.url = this.url.substring(0, this.url.length() - 1); } String url = this.url + paramString; URI uri = URI.create(url); HttpGet httpget = new HttpGet(uri); if (!(this.referer == null || this.referer.equals(""))) httpget.setHeader(this.referer, url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); String content = ""; if (entity != null) { content = EntityUtils.toString(entity, "UTF-8"); } }
Code Sample 2:
private static boolean unzipWithWarning(File source, File targetDirectory, OverwriteValue policy) { try { if (!source.exists()) return false; ZipInputStream input = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry = null; byte[] buffer = new byte[1024]; while ((zipEntry = input.getNextEntry()) != null) { if (zipEntry.isDirectory()) continue; File newFile = new File(targetDirectory, zipEntry.getName()); if (newFile.exists()) { switch(policy.value) { case NO_TO_ALL: continue; case YES_TO_ALL: break; default: switch(policy.value = confirmOverwrite(zipEntry.getName())) { case NO_TO_ALL: case NO: continue; default: } } } newFile.getParentFile().mkdirs(); int bytesRead; FileOutputStream output = new FileOutputStream(newFile); while ((bytesRead = input.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); input.closeEntry(); } input.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.