repo
stringlengths
1
191
βŒ€
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
FOADA
FOADA-master/src/utility/Impact.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package utility; import java.util.List; import java.util.Set; import exception.FOADAException; import structure.FOADAConfiguration; public abstract class Impact { public enum Mode { UniversallyQuantifyArguments, FindOccurrences }; /** add all the leaves successors of a given node into the work list if it is not covered * @param givenNode the given node * @param workList the work list of IMPACT */ public static void reEnable(FOADAConfiguration givenNode, List<FOADAConfiguration> workList) throws FOADAException { boolean givenNodeIsCovered = givenNode.isCovered(); if(givenNode.successors.isEmpty() && !givenNodeIsCovered && !workList.contains(givenNode) && !givenNode.expression.toString().equals("false")) { workList.add(0, givenNode); } if(!givenNodeIsCovered) { for(FOADAConfiguration successor : givenNode.successors) { reEnable(successor, workList); } } } public static boolean close(FOADAConfiguration node, List<FOADAConfiguration> workList, Set<FOADAConfiguration> allValidNodes) throws FOADAException { for(FOADAConfiguration targetNode : allValidNodes) { // pick a target node (which is not covered) from all nodes according to a certain order if(targetNode.number < node.number && !targetNode.isCovered()) { // if the current node along path is covered by the target node if(JavaSMTConfig.checkImplication(node.expression, targetNode.expression)) { // remove all the coverage where the node or any of its successors covers another node.removeRecursivelyCoveredRelations(workList); node.coveringNodes.add(targetNode); targetNode.coveredNodes.add(node); return true; } } } return false; } }
2,548
31.265823
127
java
FOADA
FOADA-master/src/utility/JavaSMTConfig.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package utility; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.java_smt.SolverContextFactory; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.BooleanFormulaManager; import org.sosy_lab.java_smt.api.FormulaManager; import org.sosy_lab.java_smt.api.ProverEnvironment; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager; import org.sosy_lab.java_smt.api.SolverContext; import org.sosy_lab.java_smt.api.SolverException; import org.sosy_lab.java_smt.api.UFManager; import exception.FOADAException; import exception.ImplicationProverEnvironmentException; import exception.JavaSMTInvalidConfigurationException; public class JavaSMTConfig { public static SolverContext solverContext; public static FormulaManager fmgr; public static BooleanFormulaManager bmgr; public static QuantifiedFormulaManager qmgr; public static UFManager ufmgr; public static void initJavaSMT() throws FOADAException { try { solverContext = SolverContextFactory.createSolverContext(Solvers.Z3); fmgr = solverContext.getFormulaManager(); bmgr = fmgr.getBooleanFormulaManager(); qmgr = fmgr.getQuantifiedFormulaManager(); ufmgr = fmgr.getUFManager(); } catch(InvalidConfigurationException e) { throw new JavaSMTInvalidConfigurationException(e); } } public static BooleanFormula removeTimeStamp(BooleanFormula expression) { BooleanFormula result = expression; String resultToString = fmgr.dumpFormula(result).toString(); for(String s : fmgr.extractVariablesAndUFs(result).keySet()) { if(s.contains("_") && s.charAt(0) != 'v') { resultToString = resultToString.replace(s, s.substring(0, s.indexOf("_"))); } } result = fmgr.parse(resultToString); return result; } public static boolean checkImplication(BooleanFormula f1, BooleanFormula f2) throws FOADAException { BooleanFormula implication = bmgr.implication(f1, f2); ProverEnvironment prover = solverContext.newProverEnvironment(); BooleanFormula notImplication = bmgr.not(implication); prover.addConstraint(notImplication); boolean isUnsat; boolean implicationIsValid = false; try { isUnsat = prover.isUnsat(); if(isUnsat) { implicationIsValid = true; } else { implicationIsValid = false; } } catch (SolverException e) { throw new ImplicationProverEnvironmentException(e); } catch (InterruptedException e) { throw new ImplicationProverEnvironmentException(e); } prover.close(); return implicationIsValid; } }
3,441
30.290909
82
java
FOADA
FOADA-master/src/utility/Solver.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package utility; import org.sosy_lab.java_smt.SolverContextFactory; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; import utility.Console.ConsoleType; public abstract class Solver { public static void checkZ3() { try { SolverContextFactory.createSolverContext(Solvers.Z3); } catch(Exception e) { Console.printError(ConsoleType.JavaSMT, "The solver Z3 failed."); Console.printError(ConsoleType.JavaSMT, e.getMessage()); return; } Console.printInfo(ConsoleType.JavaSMT, "The solver " + Console.GREEN_BRIGHT + "Z3 succeeded" + Console.RESET + "."); } public static void checkMATHSAT5() { try { SolverContextFactory.createSolverContext(Solvers.MATHSAT5); } catch(Exception e) { Console.printError(ConsoleType.JavaSMT, "The solver MATHSAT5 failed."); Console.printError(ConsoleType.JavaSMT, e.getMessage()); return; } Console.printInfo(ConsoleType.JavaSMT, "The solver " + Console.GREEN_BRIGHT + "MATHSAT5 succeeded" + Console.RESET + "."); } public static void checkSMTINTERPOL() { try { SolverContextFactory.createSolverContext(Solvers.SMTINTERPOL); } catch(Exception e) { Console.printError(ConsoleType.JavaSMT, "The solver SMTINTERPOL failed."); Console.printError(ConsoleType.JavaSMT, e.getMessage()); return; } Console.printInfo(ConsoleType.JavaSMT, "The solver " + Console.GREEN_BRIGHT + "SMTINTERPOL succeeded" + Console.RESET + "."); } public static void checkPRINCESS() { try { SolverContextFactory.createSolverContext(Solvers.PRINCESS); } catch(Exception e) { Console.printError(ConsoleType.JavaSMT, "The solver PRINCESS failed."); Console.printError(ConsoleType.JavaSMT, e.getMessage()); return; } Console.printInfo(ConsoleType.JavaSMT, "The solver " + Console.GREEN_BRIGHT + "PRINCESS succeeded" + Console.RESET + "."); } }
2,770
31.988095
127
java
FOADA
FOADA-master/src/utility/TreeSearch.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package utility; public abstract class TreeSearch { public enum Mode { BFS, DFS }; }
919
26.878788
82
java
go-ethereum
go-ethereum-master/crypto/secp256k1/libsecp256k1/src/java/org/bitcoin/NativeSecp256k1.java
/* * Copyright 2013 Google Inc. * Copyright 2014-2016 the libsecp256k1 contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoin; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.math.BigInteger; import com.google.common.base.Preconditions; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import static org.bitcoin.NativeSecp256k1Util.*; /** * <p>This class holds native methods to handle ECDSA verification.</p> * * <p>You can find an example library that can be used for this at https://github.com/bitcoin/secp256k1</p> * * <p>To build secp256k1 for use with bitcoinj, run * `./configure --enable-jni --enable-experimental --enable-module-ecdh` * and `make` then copy `.libs/libsecp256k1.so` to your system library path * or point the JVM to the folder containing it with -Djava.library.path * </p> */ public class NativeSecp256k1 { private static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); private static final Lock r = rwl.readLock(); private static final Lock w = rwl.writeLock(); private static ThreadLocal<ByteBuffer> nativeECDSABuffer = new ThreadLocal<ByteBuffer>(); /** * Verifies the given secp256k1 signature in native code. * Calling when enabled == false is undefined (probably library not loaded) * * @param data The data which was signed, must be exactly 32 bytes * @param signature The signature * @param pub The public key which did the signing */ public static boolean verify(byte[] data, byte[] signature, byte[] pub) throws AssertFailException{ Preconditions.checkArgument(data.length == 32 && signature.length <= 520 && pub.length <= 520); ByteBuffer byteBuff = nativeECDSABuffer.get(); if (byteBuff == null || byteBuff.capacity() < 520) { byteBuff = ByteBuffer.allocateDirect(520); byteBuff.order(ByteOrder.nativeOrder()); nativeECDSABuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(data); byteBuff.put(signature); byteBuff.put(pub); byte[][] retByteArray; r.lock(); try { return secp256k1_ecdsa_verify(byteBuff, Secp256k1Context.getContext(), signature.length, pub.length) == 1; } finally { r.unlock(); } } /** * libsecp256k1 Create an ECDSA signature. * * @param data Message hash, 32 bytes * @param key Secret key, 32 bytes * * Return values * @param sig byte array of signature */ public static byte[] sign(byte[] data, byte[] sec) throws AssertFailException{ Preconditions.checkArgument(data.length == 32 && sec.length <= 32); ByteBuffer byteBuff = nativeECDSABuffer.get(); if (byteBuff == null || byteBuff.capacity() < 32 + 32) { byteBuff = ByteBuffer.allocateDirect(32 + 32); byteBuff.order(ByteOrder.nativeOrder()); nativeECDSABuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(data); byteBuff.put(sec); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_ecdsa_sign(byteBuff, Secp256k1Context.getContext()); } finally { r.unlock(); } byte[] sigArr = retByteArray[0]; int sigLen = new BigInteger(new byte[] { retByteArray[1][0] }).intValue(); int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue(); assertEquals(sigArr.length, sigLen, "Got bad signature length."); return retVal == 0 ? new byte[0] : sigArr; } /** * libsecp256k1 Seckey Verify - returns 1 if valid, 0 if invalid * * @param seckey ECDSA Secret key, 32 bytes */ public static boolean secKeyVerify(byte[] seckey) { Preconditions.checkArgument(seckey.length == 32); ByteBuffer byteBuff = nativeECDSABuffer.get(); if (byteBuff == null || byteBuff.capacity() < seckey.length) { byteBuff = ByteBuffer.allocateDirect(seckey.length); byteBuff.order(ByteOrder.nativeOrder()); nativeECDSABuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(seckey); r.lock(); try { return secp256k1_ec_seckey_verify(byteBuff,Secp256k1Context.getContext()) == 1; } finally { r.unlock(); } } /** * libsecp256k1 Compute Pubkey - computes public key from secret key * * @param seckey ECDSA Secret key, 32 bytes * * Return values * @param pubkey ECDSA Public key, 33 or 65 bytes */ //TODO add a 'compressed' arg public static byte[] computePubkey(byte[] seckey) throws AssertFailException{ Preconditions.checkArgument(seckey.length == 32); ByteBuffer byteBuff = nativeECDSABuffer.get(); if (byteBuff == null || byteBuff.capacity() < seckey.length) { byteBuff = ByteBuffer.allocateDirect(seckey.length); byteBuff.order(ByteOrder.nativeOrder()); nativeECDSABuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(seckey); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_ec_pubkey_create(byteBuff, Secp256k1Context.getContext()); } finally { r.unlock(); } byte[] pubArr = retByteArray[0]; int pubLen = new BigInteger(new byte[] { retByteArray[1][0] }).intValue(); int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue(); assertEquals(pubArr.length, pubLen, "Got bad pubkey length."); return retVal == 0 ? new byte[0]: pubArr; } /** * libsecp256k1 Cleanup - This destroys the secp256k1 context object * This should be called at the end of the program for proper cleanup of the context. */ public static synchronized void cleanup() { w.lock(); try { secp256k1_destroy_context(Secp256k1Context.getContext()); } finally { w.unlock(); } } public static long cloneContext() { r.lock(); try { return secp256k1_ctx_clone(Secp256k1Context.getContext()); } finally { r.unlock(); } } /** * libsecp256k1 PrivKey Tweak-Mul - Tweak privkey by multiplying to it * * @param tweak some bytes to tweak with * @param seckey 32-byte seckey */ public static byte[] privKeyTweakMul(byte[] privkey, byte[] tweak) throws AssertFailException{ Preconditions.checkArgument(privkey.length == 32); ByteBuffer byteBuff = nativeECDSABuffer.get(); if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) { byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length); byteBuff.order(ByteOrder.nativeOrder()); nativeECDSABuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(privkey); byteBuff.put(tweak); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_privkey_tweak_mul(byteBuff,Secp256k1Context.getContext()); } finally { r.unlock(); } byte[] privArr = retByteArray[0]; int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF; int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue(); assertEquals(privArr.length, privLen, "Got bad pubkey length."); assertEquals(retVal, 1, "Failed return value check."); return privArr; } /** * libsecp256k1 PrivKey Tweak-Add - Tweak privkey by adding to it * * @param tweak some bytes to tweak with * @param seckey 32-byte seckey */ public static byte[] privKeyTweakAdd(byte[] privkey, byte[] tweak) throws AssertFailException{ Preconditions.checkArgument(privkey.length == 32); ByteBuffer byteBuff = nativeECDSABuffer.get(); if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) { byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length); byteBuff.order(ByteOrder.nativeOrder()); nativeECDSABuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(privkey); byteBuff.put(tweak); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_privkey_tweak_add(byteBuff,Secp256k1Context.getContext()); } finally { r.unlock(); } byte[] privArr = retByteArray[0]; int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF; int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue(); assertEquals(privArr.length, privLen, "Got bad pubkey length."); assertEquals(retVal, 1, "Failed return value check."); return privArr; } /** * libsecp256k1 PubKey Tweak-Add - Tweak pubkey by adding to it * * @param tweak some bytes to tweak with * @param pubkey 32-byte seckey */ public static byte[] pubKeyTweakAdd(byte[] pubkey, byte[] tweak) throws AssertFailException{ Preconditions.checkArgument(pubkey.length == 33 || pubkey.length == 65); ByteBuffer byteBuff = nativeECDSABuffer.get(); if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) { byteBuff = ByteBuffer.allocateDirect(pubkey.length + tweak.length); byteBuff.order(ByteOrder.nativeOrder()); nativeECDSABuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(pubkey); byteBuff.put(tweak); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_pubkey_tweak_add(byteBuff,Secp256k1Context.getContext(), pubkey.length); } finally { r.unlock(); } byte[] pubArr = retByteArray[0]; int pubLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF; int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue(); assertEquals(pubArr.length, pubLen, "Got bad pubkey length."); assertEquals(retVal, 1, "Failed return value check."); return pubArr; } /** * libsecp256k1 PubKey Tweak-Mul - Tweak pubkey by multiplying to it * * @param tweak some bytes to tweak with * @param pubkey 32-byte seckey */ public static byte[] pubKeyTweakMul(byte[] pubkey, byte[] tweak) throws AssertFailException{ Preconditions.checkArgument(pubkey.length == 33 || pubkey.length == 65); ByteBuffer byteBuff = nativeECDSABuffer.get(); if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) { byteBuff = ByteBuffer.allocateDirect(pubkey.length + tweak.length); byteBuff.order(ByteOrder.nativeOrder()); nativeECDSABuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(pubkey); byteBuff.put(tweak); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_pubkey_tweak_mul(byteBuff,Secp256k1Context.getContext(), pubkey.length); } finally { r.unlock(); } byte[] pubArr = retByteArray[0]; int pubLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF; int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue(); assertEquals(pubArr.length, pubLen, "Got bad pubkey length."); assertEquals(retVal, 1, "Failed return value check."); return pubArr; } /** * libsecp256k1 create ECDH secret - constant time ECDH calculation * * @param seckey byte array of secret key used in exponentiaion * @param pubkey byte array of public key used in exponentiaion */ public static byte[] createECDHSecret(byte[] seckey, byte[] pubkey) throws AssertFailException{ Preconditions.checkArgument(seckey.length <= 32 && pubkey.length <= 65); ByteBuffer byteBuff = nativeECDSABuffer.get(); if (byteBuff == null || byteBuff.capacity() < 32 + pubkey.length) { byteBuff = ByteBuffer.allocateDirect(32 + pubkey.length); byteBuff.order(ByteOrder.nativeOrder()); nativeECDSABuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(seckey); byteBuff.put(pubkey); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_ecdh(byteBuff, Secp256k1Context.getContext(), pubkey.length); } finally { r.unlock(); } byte[] resArr = retByteArray[0]; int retVal = new BigInteger(new byte[] { retByteArray[1][0] }).intValue(); assertEquals(resArr.length, 32, "Got bad result length."); assertEquals(retVal, 1, "Failed return value check."); return resArr; } /** * libsecp256k1 randomize - updates the context randomization * * @param seed 32-byte random seed */ public static synchronized boolean randomize(byte[] seed) throws AssertFailException{ Preconditions.checkArgument(seed.length == 32 || seed == null); ByteBuffer byteBuff = nativeECDSABuffer.get(); if (byteBuff == null || byteBuff.capacity() < seed.length) { byteBuff = ByteBuffer.allocateDirect(seed.length); byteBuff.order(ByteOrder.nativeOrder()); nativeECDSABuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(seed); w.lock(); try { return secp256k1_context_randomize(byteBuff, Secp256k1Context.getContext()) == 1; } finally { w.unlock(); } } private static native long secp256k1_ctx_clone(long context); private static native int secp256k1_context_randomize(ByteBuffer byteBuff, long context); private static native byte[][] secp256k1_privkey_tweak_add(ByteBuffer byteBuff, long context); private static native byte[][] secp256k1_privkey_tweak_mul(ByteBuffer byteBuff, long context); private static native byte[][] secp256k1_pubkey_tweak_add(ByteBuffer byteBuff, long context, int pubLen); private static native byte[][] secp256k1_pubkey_tweak_mul(ByteBuffer byteBuff, long context, int pubLen); private static native void secp256k1_destroy_context(long context); private static native int secp256k1_ecdsa_verify(ByteBuffer byteBuff, long context, int sigLen, int pubLen); private static native byte[][] secp256k1_ecdsa_sign(ByteBuffer byteBuff, long context); private static native int secp256k1_ec_seckey_verify(ByteBuffer byteBuff, long context); private static native byte[][] secp256k1_ec_pubkey_create(ByteBuffer byteBuff, long context); private static native byte[][] secp256k1_ec_pubkey_parse(ByteBuffer byteBuff, long context, int inputLen); private static native byte[][] secp256k1_ecdh(ByteBuffer byteBuff, long context, int inputLen); }
15,756
34.250559
116
java
go-ethereum
go-ethereum-master/crypto/secp256k1/libsecp256k1/src/java/org/bitcoin/NativeSecp256k1Test.java
package org.bitcoin; import com.google.common.io.BaseEncoding; import java.util.Arrays; import java.math.BigInteger; import javax.xml.bind.DatatypeConverter; import static org.bitcoin.NativeSecp256k1Util.*; /** * This class holds test cases defined for testing this library. */ public class NativeSecp256k1Test { //TODO improve comments/add more tests /** * This tests verify() for a valid signature */ public static void testVerifyPos() throws AssertFailException{ boolean result = false; byte[] data = BaseEncoding.base16().lowerCase().decode("CF80CD8AED482D5D1527D7DC72FCEFF84E6326592848447D2DC0B0E87DFC9A90".toLowerCase()); //sha256hash of "testing" byte[] sig = BaseEncoding.base16().lowerCase().decode("3044022079BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F817980220294F14E883B3F525B5367756C2A11EF6CF84B730B36C17CB0C56F0AAB2C98589".toLowerCase()); byte[] pub = BaseEncoding.base16().lowerCase().decode("040A629506E1B65CD9D2E0BA9C75DF9C4FED0DB16DC9625ED14397F0AFC836FAE595DC53F8B0EFE61E703075BD9B143BAC75EC0E19F82A2208CAEB32BE53414C40".toLowerCase()); result = NativeSecp256k1.verify( data, sig, pub); assertEquals( result, true , "testVerifyPos"); } /** * This tests verify() for a non-valid signature */ public static void testVerifyNeg() throws AssertFailException{ boolean result = false; byte[] data = BaseEncoding.base16().lowerCase().decode("CF80CD8AED482D5D1527D7DC72FCEFF84E6326592848447D2DC0B0E87DFC9A91".toLowerCase()); //sha256hash of "testing" byte[] sig = BaseEncoding.base16().lowerCase().decode("3044022079BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F817980220294F14E883B3F525B5367756C2A11EF6CF84B730B36C17CB0C56F0AAB2C98589".toLowerCase()); byte[] pub = BaseEncoding.base16().lowerCase().decode("040A629506E1B65CD9D2E0BA9C75DF9C4FED0DB16DC9625ED14397F0AFC836FAE595DC53F8B0EFE61E703075BD9B143BAC75EC0E19F82A2208CAEB32BE53414C40".toLowerCase()); result = NativeSecp256k1.verify( data, sig, pub); //System.out.println(" TEST " + new BigInteger(1, resultbytes).toString(16)); assertEquals( result, false , "testVerifyNeg"); } /** * This tests secret key verify() for a valid secretkey */ public static void testSecKeyVerifyPos() throws AssertFailException{ boolean result = false; byte[] sec = BaseEncoding.base16().lowerCase().decode("67E56582298859DDAE725F972992A07C6C4FB9F62A8FFF58CE3CA926A1063530".toLowerCase()); result = NativeSecp256k1.secKeyVerify( sec ); //System.out.println(" TEST " + new BigInteger(1, resultbytes).toString(16)); assertEquals( result, true , "testSecKeyVerifyPos"); } /** * This tests secret key verify() for a invalid secretkey */ public static void testSecKeyVerifyNeg() throws AssertFailException{ boolean result = false; byte[] sec = BaseEncoding.base16().lowerCase().decode("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF".toLowerCase()); result = NativeSecp256k1.secKeyVerify( sec ); //System.out.println(" TEST " + new BigInteger(1, resultbytes).toString(16)); assertEquals( result, false , "testSecKeyVerifyNeg"); } /** * This tests public key create() for a valid secretkey */ public static void testPubKeyCreatePos() throws AssertFailException{ byte[] sec = BaseEncoding.base16().lowerCase().decode("67E56582298859DDAE725F972992A07C6C4FB9F62A8FFF58CE3CA926A1063530".toLowerCase()); byte[] resultArr = NativeSecp256k1.computePubkey( sec); String pubkeyString = javax.xml.bind.DatatypeConverter.printHexBinary(resultArr); assertEquals( pubkeyString , "04C591A8FF19AC9C4E4E5793673B83123437E975285E7B442F4EE2654DFFCA5E2D2103ED494718C697AC9AEBCFD19612E224DB46661011863ED2FC54E71861E2A6" , "testPubKeyCreatePos"); } /** * This tests public key create() for a invalid secretkey */ public static void testPubKeyCreateNeg() throws AssertFailException{ byte[] sec = BaseEncoding.base16().lowerCase().decode("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF".toLowerCase()); byte[] resultArr = NativeSecp256k1.computePubkey( sec); String pubkeyString = javax.xml.bind.DatatypeConverter.printHexBinary(resultArr); assertEquals( pubkeyString, "" , "testPubKeyCreateNeg"); } /** * This tests sign() for a valid secretkey */ public static void testSignPos() throws AssertFailException{ byte[] data = BaseEncoding.base16().lowerCase().decode("CF80CD8AED482D5D1527D7DC72FCEFF84E6326592848447D2DC0B0E87DFC9A90".toLowerCase()); //sha256hash of "testing" byte[] sec = BaseEncoding.base16().lowerCase().decode("67E56582298859DDAE725F972992A07C6C4FB9F62A8FFF58CE3CA926A1063530".toLowerCase()); byte[] resultArr = NativeSecp256k1.sign(data, sec); String sigString = javax.xml.bind.DatatypeConverter.printHexBinary(resultArr); assertEquals( sigString, "30440220182A108E1448DC8F1FB467D06A0F3BB8EA0533584CB954EF8DA112F1D60E39A202201C66F36DA211C087F3AF88B50EDF4F9BDAA6CF5FD6817E74DCA34DB12390C6E9" , "testSignPos"); } /** * This tests sign() for a invalid secretkey */ public static void testSignNeg() throws AssertFailException{ byte[] data = BaseEncoding.base16().lowerCase().decode("CF80CD8AED482D5D1527D7DC72FCEFF84E6326592848447D2DC0B0E87DFC9A90".toLowerCase()); //sha256hash of "testing" byte[] sec = BaseEncoding.base16().lowerCase().decode("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF".toLowerCase()); byte[] resultArr = NativeSecp256k1.sign(data, sec); String sigString = javax.xml.bind.DatatypeConverter.printHexBinary(resultArr); assertEquals( sigString, "" , "testSignNeg"); } /** * This tests private key tweak-add */ public static void testPrivKeyTweakAdd_1() throws AssertFailException { byte[] sec = BaseEncoding.base16().lowerCase().decode("67E56582298859DDAE725F972992A07C6C4FB9F62A8FFF58CE3CA926A1063530".toLowerCase()); byte[] data = BaseEncoding.base16().lowerCase().decode("3982F19BEF1615BCCFBB05E321C10E1D4CBA3DF0E841C2E41EEB6016347653C3".toLowerCase()); //sha256hash of "tweak" byte[] resultArr = NativeSecp256k1.privKeyTweakAdd( sec , data ); String sigString = javax.xml.bind.DatatypeConverter.printHexBinary(resultArr); assertEquals( sigString , "A168571E189E6F9A7E2D657A4B53AE99B909F7E712D1C23CED28093CD57C88F3" , "testPrivKeyAdd_1"); } /** * This tests private key tweak-mul */ public static void testPrivKeyTweakMul_1() throws AssertFailException { byte[] sec = BaseEncoding.base16().lowerCase().decode("67E56582298859DDAE725F972992A07C6C4FB9F62A8FFF58CE3CA926A1063530".toLowerCase()); byte[] data = BaseEncoding.base16().lowerCase().decode("3982F19BEF1615BCCFBB05E321C10E1D4CBA3DF0E841C2E41EEB6016347653C3".toLowerCase()); //sha256hash of "tweak" byte[] resultArr = NativeSecp256k1.privKeyTweakMul( sec , data ); String sigString = javax.xml.bind.DatatypeConverter.printHexBinary(resultArr); assertEquals( sigString , "97F8184235F101550F3C71C927507651BD3F1CDB4A5A33B8986ACF0DEE20FFFC" , "testPrivKeyMul_1"); } /** * This tests private key tweak-add uncompressed */ public static void testPrivKeyTweakAdd_2() throws AssertFailException { byte[] pub = BaseEncoding.base16().lowerCase().decode("040A629506E1B65CD9D2E0BA9C75DF9C4FED0DB16DC9625ED14397F0AFC836FAE595DC53F8B0EFE61E703075BD9B143BAC75EC0E19F82A2208CAEB32BE53414C40".toLowerCase()); byte[] data = BaseEncoding.base16().lowerCase().decode("3982F19BEF1615BCCFBB05E321C10E1D4CBA3DF0E841C2E41EEB6016347653C3".toLowerCase()); //sha256hash of "tweak" byte[] resultArr = NativeSecp256k1.pubKeyTweakAdd( pub , data ); String sigString = javax.xml.bind.DatatypeConverter.printHexBinary(resultArr); assertEquals( sigString , "0411C6790F4B663CCE607BAAE08C43557EDC1A4D11D88DFCB3D841D0C6A941AF525A268E2A863C148555C48FB5FBA368E88718A46E205FABC3DBA2CCFFAB0796EF" , "testPrivKeyAdd_2"); } /** * This tests private key tweak-mul uncompressed */ public static void testPrivKeyTweakMul_2() throws AssertFailException { byte[] pub = BaseEncoding.base16().lowerCase().decode("040A629506E1B65CD9D2E0BA9C75DF9C4FED0DB16DC9625ED14397F0AFC836FAE595DC53F8B0EFE61E703075BD9B143BAC75EC0E19F82A2208CAEB32BE53414C40".toLowerCase()); byte[] data = BaseEncoding.base16().lowerCase().decode("3982F19BEF1615BCCFBB05E321C10E1D4CBA3DF0E841C2E41EEB6016347653C3".toLowerCase()); //sha256hash of "tweak" byte[] resultArr = NativeSecp256k1.pubKeyTweakMul( pub , data ); String sigString = javax.xml.bind.DatatypeConverter.printHexBinary(resultArr); assertEquals( sigString , "04E0FE6FE55EBCA626B98A807F6CAF654139E14E5E3698F01A9A658E21DC1D2791EC060D4F412A794D5370F672BC94B722640B5F76914151CFCA6E712CA48CC589" , "testPrivKeyMul_2"); } /** * This tests seed randomization */ public static void testRandomize() throws AssertFailException { byte[] seed = BaseEncoding.base16().lowerCase().decode("A441B15FE9A3CF56661190A0B93B9DEC7D04127288CC87250967CF3B52894D11".toLowerCase()); //sha256hash of "random" boolean result = NativeSecp256k1.randomize(seed); assertEquals( result, true, "testRandomize"); } public static void testCreateECDHSecret() throws AssertFailException{ byte[] sec = BaseEncoding.base16().lowerCase().decode("67E56582298859DDAE725F972992A07C6C4FB9F62A8FFF58CE3CA926A1063530".toLowerCase()); byte[] pub = BaseEncoding.base16().lowerCase().decode("040A629506E1B65CD9D2E0BA9C75DF9C4FED0DB16DC9625ED14397F0AFC836FAE595DC53F8B0EFE61E703075BD9B143BAC75EC0E19F82A2208CAEB32BE53414C40".toLowerCase()); byte[] resultArr = NativeSecp256k1.createECDHSecret(sec, pub); String ecdhString = javax.xml.bind.DatatypeConverter.printHexBinary(resultArr); assertEquals( ecdhString, "2A2A67007A926E6594AF3EB564FC74005B37A9C8AEF2033C4552051B5C87F043" , "testCreateECDHSecret"); } public static void main(String[] args) throws AssertFailException{ System.out.println("\n libsecp256k1 enabled: " + Secp256k1Context.isEnabled() + "\n"); assertEquals( Secp256k1Context.isEnabled(), true, "isEnabled" ); //Test verify() success/fail testVerifyPos(); testVerifyNeg(); //Test secKeyVerify() success/fail testSecKeyVerifyPos(); testSecKeyVerifyNeg(); //Test computePubkey() success/fail testPubKeyCreatePos(); testPubKeyCreateNeg(); //Test sign() success/fail testSignPos(); testSignNeg(); //Test privKeyTweakAdd() 1 testPrivKeyTweakAdd_1(); //Test privKeyTweakMul() 2 testPrivKeyTweakMul_1(); //Test privKeyTweakAdd() 3 testPrivKeyTweakAdd_2(); //Test privKeyTweakMul() 4 testPrivKeyTweakMul_2(); //Test randomize() testRandomize(); //Test ECDH testCreateECDHSecret(); NativeSecp256k1.cleanup(); System.out.println(" All tests passed." ); } }
11,440
49.400881
220
java
go-ethereum
go-ethereum-master/crypto/secp256k1/libsecp256k1/src/java/org/bitcoin/NativeSecp256k1Util.java
/* * Copyright 2014-2016 the libsecp256k1 contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoin; public class NativeSecp256k1Util{ public static void assertEquals( int val, int val2, String message ) throws AssertFailException{ if( val != val2 ) throw new AssertFailException("FAIL: " + message); } public static void assertEquals( boolean val, boolean val2, String message ) throws AssertFailException{ if( val != val2 ) throw new AssertFailException("FAIL: " + message); else System.out.println("PASS: " + message); } public static void assertEquals( String val, String val2, String message ) throws AssertFailException{ if( !val.equals(val2) ) throw new AssertFailException("FAIL: " + message); else System.out.println("PASS: " + message); } public static class AssertFailException extends Exception { public AssertFailException(String message) { super( message ); } } }
1,543
32.565217
108
java
go-ethereum
go-ethereum-master/crypto/secp256k1/libsecp256k1/src/java/org/bitcoin/Secp256k1Context.java
/* * Copyright 2014-2016 the libsecp256k1 contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoin; /** * This class holds the context reference used in native methods * to handle ECDSA operations. */ public class Secp256k1Context { private static final boolean enabled; //true if the library is loaded private static final long context; //ref to pointer to context obj static { //static initializer boolean isEnabled = true; long contextRef = -1; try { System.loadLibrary("secp256k1"); contextRef = secp256k1_init_context(); } catch (UnsatisfiedLinkError e) { System.out.println("UnsatisfiedLinkError: " + e.toString()); isEnabled = false; } enabled = isEnabled; context = contextRef; } public static boolean isEnabled() { return enabled; } public static long getContext() { if(!enabled) return -1; //sanity check return context; } private static native long secp256k1_init_context(); }
1,551
28.846154
75
java
null
wasm3-main/platforms/android/app/src/main/java/com/example/wasm3/MainActivity.java
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.wasm3; import androidx.annotation.Keep; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView)findViewById(R.id.console); runMain(); } @Keep private void outputText(final String s) { runOnUiThread(new Runnable() { @Override public void run() { MainActivity.this.tv.append(s); } }); } static { System.loadLibrary("wasm3-jni"); } public native void runMain(); }
1,431
26.018868
75
java
dlib
dlib-master/dlib/java/swig_test.java
/* This file tests all the ways of using jvector and jvector_crit. */ import net.dlib.*; public class swig_test { public static int sum(long[] arr) { int s = 0; for (int i = 0; i < arr.length; ++i) s += arr[i]; return s; } public static void zero(long[] arr) { for (int i = 0; i < arr.length; ++i) arr[i] = 0; } public static int sum(byte[] arr) { int s = 0; for (int i = 0; i < arr.length; ++i) s += arr[i]; return s; } public static void zero(byte[] arr) { for (int i = 0; i < arr.length; ++i) arr[i] = 0; } public static int sum(short[] arr) { int s = 0; for (int i = 0; i < arr.length; ++i) s += arr[i]; return s; } public static void zero(short[] arr) { for (int i = 0; i < arr.length; ++i) arr[i] = 0; } public static int sum(int[] arr) { int s = 0; for (int i = 0; i < arr.length; ++i) s += arr[i]; return s; } public static void zero(int[] arr) { for (int i = 0; i < arr.length; ++i) arr[i] = 0; } public static void assertIs28(int val) { if (val != 28) { throw new RuntimeException("Test failed " + val); } } public static void assertIsEqual(int val1, int val2) { if (val1 != val2) { throw new RuntimeException("Test failed " + val1 + " should be equal to " + val2); } } public static double sum(double[] arr) { double s = 0; for (int i = 0; i < arr.length; ++i) s += arr[i]; return s; } public static void zero(double[] arr) { for (int i = 0; i < arr.length; ++i) arr[i] = 0; } public static void assertIs28(double val) { if (val != 28) { throw new RuntimeException("Test failed " + val); } } public static float sum(float[] arr) { float s = 0; for (int i = 0; i < arr.length; ++i) s += arr[i]; return s; } public static void zero(float[] arr) { for (int i = 0; i < arr.length; ++i) arr[i] = 0; } public static void assertIs28(float val) { if (val != 28) { throw new RuntimeException("Test failed " + val); } } public static void main(String[] args) { { float[] arr = new float[8]; for (int round = 0; round < 100; ++round) { zero(arr); global.assign(arr); assertIs28(sum(arr)); zero(arr); global.assign_crit(arr); assertIs28(sum(arr)); } for (int round = 0; round < 100; ++round) { zero(arr); global.assign(arr); assertIs28(sum(arr)); assertIs28(global.sum(arr)); zero(arr); global.assign_crit(arr); assertIs28(sum(arr)); assertIs28(global.sum_crit(arr)); } } { double[] arr = new double[8]; for (int round = 0; round < 100; ++round) { zero(arr); global.assign(arr); assertIs28(sum(arr)); zero(arr); global.assign_crit(arr); assertIs28(sum(arr)); } for (int round = 0; round < 100; ++round) { zero(arr); global.assign(arr); assertIs28(sum(arr)); assertIs28(global.sum(arr)); zero(arr); global.assign_crit(arr); assertIs28(sum(arr)); assertIs28(global.sum_crit(arr)); } } { byte[] arr = new byte[8]; for (int round = 0; round < 100; ++round) { zero(arr); global.assign(arr); assertIs28(sum(arr)); zero(arr); global.assign_crit(arr); assertIs28(sum(arr)); } for (int round = 0; round < 100; ++round) { zero(arr); global.assign(arr); assertIs28(sum(arr)); assertIs28(global.sum(arr)); zero(arr); global.assign_crit(arr); assertIs28(sum(arr)); assertIs28(global.sum_crit(arr)); } } { long[] arr = new long[8]; for (int round = 0; round < 100; ++round) { zero(arr); global.assign(arr); assertIs28(sum(arr)); zero(arr); global.assign_crit(arr); assertIs28(sum(arr)); } for (int round = 0; round < 100; ++round) { zero(arr); global.assign(arr); assertIs28(sum(arr)); assertIs28(global.sum(arr)); zero(arr); global.assign_crit(arr); assertIs28(sum(arr)); assertIs28(global.sum_crit(arr)); } } { short[] arr = new short[8]; for (int round = 0; round < 100; ++round) { zero(arr); global.assign(arr); assertIs28(sum(arr)); zero(arr); global.assign_crit(arr); assertIs28(sum(arr)); } for (int round = 0; round < 100; ++round) { zero(arr); global.assign(arr); assertIs28(sum(arr)); assertIs28(global.sum(arr)); zero(arr); global.assign_crit(arr); assertIs28(sum(arr)); assertIs28(global.sum_crit(arr)); } } { int[] arr = new int[8]; for (int round = 0; round < 100; ++round) { zero(arr); global.assign(arr); assertIs28(sum(arr)); zero(arr); global.assign_crit(arr); assertIs28(sum(arr)); } for (int round = 0; round < 100; ++round) { zero(arr); global.assign(arr); assertIs28(sum(arr)); assertIs28(global.sum(arr)); zero(arr); global.assign_crit(arr); assertIs28(sum(arr)); assertIs28(global.sum_crit(arr)); } } { int[] a = global.make_an_array(4); for (int i = 0; i < a.length; ++i) { assertIsEqual(a[i], i); } } System.out.println("\n\n ALL TESTS COMPLETED SUCCESSFULLY\n"); } }
6,840
25.827451
94
java
jdepend
jdepend-master/sample/epayment/adapters/ABCGatewayAdapter.java
package epayment.adapters; import epayment.adapters.*; import epayment.framework.IGatewayAdapter; import epayment.framework.IPaymentRequest; import epayment.framework.IPaymentResponse; import epayment.framework.PaymentException; import epayment.response.PaymentResponse; /** * The <code>ABCGatewayAdapter</code> class is an * <code>IGatewayAdapter</code> which adapts * to a vendor-specific epayment package. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public class ABCGatewayAdapter implements IGatewayAdapter { // // Vendor-specific proxy class. // //private ABCProxy _proxy; /** * Constructs an <code>ABCGatewayAdapter</code> instance. */ public ABCGatewayAdapter() { //_proxy = new ABCProxy(); } /** * Sets the payment gateway host. * * @param host Gateway host. */ public void setHost(String host) { //_proxy.setGatewayHostName(host); } /** * Performs an authorize for the specified payment request * information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse authorize(IPaymentRequest request) throws PaymentException { PaymentResponse response = new PaymentResponse(); // // Adapt the request information to the // vendor-specific proxy API. // /* _proxy.setAction("authorize"); _proxy.setUserId(request.getUserId()); _proxy.setPassword(request.getUserPassword()); _proxy.setAccountHolderName(request.getAccountName()); _proxy.setAccountHolderNumber(request.getAccountNumber()); _proxy.setUserDefinedField1(request.getComment()); _proxy.setTransactionAmount(request.getAmount()); */ // // Perform the transaction against // the vendor-specific API. // /* boolean success = false; try { success = _proxy.performTransaction(); } catch (Exception e) { throw new PaymentException(e.getMessage()); } */ // // Adapt the vendor-specific response information // to the generic response API. // /* if (success) { response.setResponseMessage(_proxy.getResult()); response.setProcessedDate(_proxy.getDate()); } else { throw new PaymentException(_proxy.getResult()); } */ return response; } /** * Performs a capture for the specified payment * request information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse capture(IPaymentRequest request) throws PaymentException { // similar to authorize() return new PaymentResponse(); } /** * Performs a sale (authorize and capture) for the specified * payment request information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse sale(IPaymentRequest request) throws PaymentException { // similar to authorize() return new PaymentResponse(); } /** * Performs a credit for the specified payment request * information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse credit(IPaymentRequest request) throws PaymentException { // similar to authorize() return new PaymentResponse(); } /** * Performs a void for the specified payment request * information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse voidSale(IPaymentRequest request) throws PaymentException { // similar to authorize() return new PaymentResponse(); } }
4,016
22.769231
70
java
jdepend
jdepend-master/sample/epayment/adapters/XYZGatewayAdapter.java
package epayment.adapters; import epayment.framework.IGatewayAdapter; import epayment.framework.IPaymentRequest; import epayment.framework.IPaymentResponse; import epayment.framework.PaymentException; import epayment.response.PaymentResponse; /** * The <code>XYZGatewayAdapter</code> class is an * <code>IGatewayAdapter</code> which adapts * to a vendor-specific epayment package. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public class XYZGatewayAdapter implements IGatewayAdapter { // // Vendor-specific proxy class. // //private XYZProxy _proxy; /** * Constructs an <code>XYZGatewayAdapter</code> instance. */ public XYZGatewayAdapter() { //_proxy = new XYZProxy(); } /** * Sets the payment gateway host. * * @param host Gateway host. */ public void setHost(String host) { //_proxy.setHostName(host); } /** * Performs an authorize for the specified payment request * information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse authorize(IPaymentRequest request) throws PaymentException { PaymentResponse response = new PaymentResponse(); // // Adapt the request information to the // vendor-specific proxy API. // /* _proxy.setAction("1"); _proxy.setUser(request.getUserId()); _proxy.setPass(request.getUserPassword()); _proxy.setName(request.getAccountName()); _proxy.setNumber(request.getAccountNumber()); _proxy.setComment(request.getComment()); _proxy.setAmount(request.getAmount()); */ // // Perform the transaction against // the vendor-specific API. // /* boolean success = false; try { success = _proxy.execute(); } catch (Exception e) { throw new PaymentException(e.getMessage()); } */ // // Adapt the vendor-specific response information // to the generic response API. // /* if (success) { response.setResponseMessage(_proxy.getExecutionResult()); response.setProcessedDate(_proxy.getDateTime()); } else { throw new PaymentException(_proxy.getResult()); } */ return response; } /** * Performs a capture for the specified payment * request information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse capture(IPaymentRequest request) throws PaymentException { // similar to authorize() return new PaymentResponse(); } /** * Performs a sale (authorize and capture) for the specified * payment request information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse sale(IPaymentRequest request) throws PaymentException { // similar to authorize() return new PaymentResponse(); } /** * Performs a credit for the specified payment request * information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse credit(IPaymentRequest request) throws PaymentException { // similar to authorize() return new PaymentResponse(); } /** * Performs a void for the specified payment request * information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse voidSale(IPaymentRequest request) throws PaymentException { // similar to authorize() return new PaymentResponse(); } }
3,921
22.48503
70
java
jdepend
jdepend-master/sample/epayment/commands/AuthorizeCommand.java
package epayment.commands; import epayment.framework.*; /** * The <code>AuthorizeCommand</code> class is an * <code>AbstractPaymentCommand</code> for authorizing * a purchase. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public class AuthorizeCommand extends AbstractPaymentCommand { /** * Constructs an <code>AuthorizeCommand</code> with * the specified payment request. * * @param request Payment request. */ public AuthorizeCommand(IPaymentRequest request) { super(request); } /** * Executes this command using the specified payment * adapter and returns a payment response. * * @param adapter Payment adapter. * @return response Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse execute(IGatewayAdapter adapter) throws PaymentException { return adapter.authorize(getPaymentRequest()); } }
1,024
23.404762
70
java
jdepend
jdepend-master/sample/epayment/commands/CaptureCommand.java
package epayment.commands; import epayment.framework.*; /** * The <code>CaptureCommand</code> class is an * <code>AbstractPaymentCommand</code> for capturing * a previously authorized amount. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public class CaptureCommand extends AbstractPaymentCommand { /** * Constructs an <code>CaptureCommand</code> with * the specified payment request. * * @param request Payment request. */ public CaptureCommand(IPaymentRequest request) { super(request); } /** * Executes this command using the specified payment * adapter and returns a payment response. * * @param adapter Payment adapter. * @return response Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse execute(IGatewayAdapter adapter) throws PaymentException { return adapter.capture(getPaymentRequest()); } }
1,032
23.595238
70
java
jdepend
jdepend-master/sample/epayment/commands/CreditCommand.java
package epayment.commands; import epayment.framework.*; /** * The <code>CreditCommand</code> class is an * <code>AbstractPaymentCommand</code> for crediting * a previous capture. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public class CreditCommand extends AbstractPaymentCommand { /** * Constructs an <code>CreditCommand</code> with * the specified payment request. * * @param request Payment request. */ public CreditCommand(IPaymentRequest request) { super(request); } /** * Executes this command using the specified payment * adapter and returns a payment response. * * @param adapter Payment adapter. * @return response Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse execute(IGatewayAdapter adapter) throws PaymentException { return adapter.credit(getPaymentRequest()); } }
1,015
23.190476
70
java
jdepend
jdepend-master/sample/epayment/commands/SaleCommand.java
package epayment.commands; import epayment.framework.*; /** * The <code>SaleCommand</code> class is an * <code>AbstractPaymentCommand</code> for authorizing * and capturing a purchase in an * atomic operation. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public class SaleCommand extends AbstractPaymentCommand { /** * Constructs an <code>SaleCommand</code> with * the specified payment request. * * @param request Payment request. */ public SaleCommand(IPaymentRequest request) { super(request); } /** * Executes this command using the specified payment * adapter and returns a payment response. * * @param adapter Payment adapter. * @return response Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse execute(IGatewayAdapter adapter) throws PaymentException { return adapter.sale(getPaymentRequest()); } }
1,039
23.186047
70
java
jdepend
jdepend-master/sample/epayment/commands/VoidSaleCommand.java
package epayment.commands; import epayment.framework.*; /** * The <code>VoidSaleCommand</code> class is an * <code>AbstractPaymentCommand</code> for voiding * a previous sale. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public class VoidSaleCommand extends AbstractPaymentCommand { /** * Constructs an <code>VoidSaleCommand</code> with * the specified payment request. * * @param request Payment request. */ public VoidSaleCommand(IPaymentRequest request) { super(request); } /** * Executes this command using the specified payment * adapter and returns a payment response. * * @param adapter Payment adapter. * @return response Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse execute(IGatewayAdapter adapter) throws PaymentException { return adapter.voidSale(getPaymentRequest()); } }
1,020
23.309524
70
java
jdepend
jdepend-master/sample/epayment/framework/AbstractPaymentCommand.java
package epayment.framework; /** * The <code>AbstractPaymentCommand</code> class provides * the default behavior for the <code>IPaymentCommand</code> * interface. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public abstract class AbstractPaymentCommand implements IPaymentCommand { private IPaymentRequest _request; /** * Constructs an <code>AbstractPaymentCommand</code> * instance. */ public AbstractPaymentCommand(IPaymentRequest request) { _request = request; } /** * Executes this command using the specified payment * adapter and returns a payment response. * * @param adapter Payment adapter. * @return response Payment response. * @throws PaymentException If an error occurs. */ public abstract IPaymentResponse execute(IGatewayAdapter adapter) throws PaymentException; /** * Returns the payment request. * * @return Payment request. */ protected IPaymentRequest getPaymentRequest() { return _request; } }
1,113
23.217391
73
java
jdepend
jdepend-master/sample/epayment/framework/IGatewayAdapter.java
package epayment.framework; /** * The <code>IGatewayAdapter</code> interface defines * the common interface for all electronic payment * gateways. * <p> * Implementors of this interface serve as interface * adapters to vendor-specific payment gateways. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public interface IGatewayAdapter { /** * Sets the payment gateway host. * * @param host Gateway host. */ public void setHost(String host); /** * Performs an authorizes for the specified payment request * information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse authorize(IPaymentRequest request) throws PaymentException; /** * Performs a capture for the specified payment request * information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse capture(IPaymentRequest request) throws PaymentException; /** * Performs a sale (authorize and capture) for the specified * payment request information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse sale(IPaymentRequest request) throws PaymentException; /** * Performs a credit for the specified payment request * information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse credit(IPaymentRequest request) throws PaymentException; /** * Performs a void for the specified payment request * information and returns a payment response. * * @param request Payment request. * @return Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse voidSale(IPaymentRequest request) throws PaymentException; }
2,242
26.691358
70
java
jdepend
jdepend-master/sample/epayment/framework/IPaymentCommand.java
package epayment.framework; /** * The <code>IPaymentCommand</code> interface defines * the common interface for all electronic payment * actions. * <p> * Implementors of this interface encapsulate a payment * request as an object which can be generically * processed by the <code>PaymentProcessor</code>. * The <code>PaymentProcessor</code> is responsible * for installing an appropriate implementation of * an <code>IGatewayAdapter</code>. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public interface IPaymentCommand { /** * Executes this command using the specified payment * adapter and returns a payment response. * * @param adapter Payment adapter. * @return response Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse execute(IGatewayAdapter adapter) throws PaymentException; }
1,004
28.558824
70
java
jdepend
jdepend-master/sample/epayment/framework/IPaymentRequest.java
package epayment.framework; import java.io.Serializable; /** * The <code>IPaymentRequest</code> interface defines * the interface for payment request information. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public interface IPaymentRequest extends Serializable { /** * Sets the user id. * * @param id User id. */ public void setUserId(String id); /** * Sets the user password. * * @param password User password. */ public void setUserPassword(String password); /** * Sets the cardholder name. * * @param name Cardholder name. */ public void setAccountName(String name); /** * Sets the cardholder's account number. * <p> * This number will be stripped of all spaces, * non-numeric characters, and dashes. * * @param number Card account number. */ public void setAccountNumber(String number); /** * Sets the amount of the transaction. * <p> * The format is xxx.yy. * * @param amount Amount in dollars. */ public void setAmount(double amount); /** * Sets the reporting comment. * * @param comment Reporting comment. */ public void setComment(String comment); }
1,285
19.09375
70
java
jdepend
jdepend-master/sample/epayment/framework/IPaymentResponse.java
package epayment.framework; import java.io.Serializable; /** * The <code>IPaymentResponse</code> interface defines * the interface for payment response information. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public interface IPaymentResponse extends Serializable { /** * Returns the processed date. * * @return Processed date. */ public String getProcessedDate(); /** * Returns the response message. * * @return Response message. */ public String getResponseMessage(); }
643
19.774194
70
java
jdepend
jdepend-master/sample/epayment/framework/PaymentException.java
package epayment.framework; /** * The <code>PaymentException</code> class is an * <code>Exception</code> thrown when a payment * processing error occurs. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public class PaymentException extends Exception { /** * Constructs a <code>PaymentException</code> with * the specified message. * * @param message Message. */ public PaymentException(String message) { super (message); } }
586
21.576923
70
java
jdepend
jdepend-master/sample/epayment/processor/PaymentProcessor.java
package epayment.processor; import epayment.framework.IGatewayAdapter; import epayment.framework.IPaymentCommand; import epayment.framework.IPaymentResponse; import epayment.framework.PaymentException; /** * The <code>PaymentProcessor</code> class is a bridge * for an <code>IGatewayAdapter</code>. This class is * responsible for processing <code>IPaymentCommand</code> * instances, while decoupling them from specific * payment processing implementations. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public class PaymentProcessor { private IGatewayAdapter _adapter; private static PaymentProcessor _processor; /** * Constructs a <code>PaymentProcessor</code> * instance using the default configurator. */ public PaymentProcessor() { try { PaymentProcessorConfigurator configurator = new PaymentProcessorConfigurator(); configurator.configure(this); } catch(Exception e) { System.err.println("Payment processor configuration error: " + e.getMessage()); // default to consistent state } } /** * Constructs a <code>PaymentProcessor</code> * instance with the specified gateway adapter. * * @param adapter Gateway adapter. */ public PaymentProcessor(IGatewayAdapter adapter) { setGatewayAdapter(adapter); } /** * Returns the sole instance of this class. * * @return Payment processor. */ public static PaymentProcessor getProcessor() { if (_processor == null) { _processor = new PaymentProcessor(); } return _processor; } /** * Sets the gateway adapter. * * @param adapter Gateway adapter. */ protected void setGatewayAdapter(IGatewayAdapter adapter) { _adapter = adapter; } /** * Processes the specified payment command using * the specified payment request and returns a * payment response. * * @param command Payment command. * @return response Payment response. * @throws PaymentException If an error occurs. */ public IPaymentResponse process(IPaymentCommand command) throws PaymentException { return command.execute(_adapter); } }
2,223
23.43956
70
java
jdepend
jdepend-master/sample/epayment/processor/PaymentProcessorConfigurator.java
package epayment.processor; import epayment.framework.IGatewayAdapter; /** * The <code>PaymentProcessorConfigurator</code> class * is responsible for configuring the run-time * environment of the <code>PaymentProcessor</code>. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public class PaymentProcessorConfigurator { /** * Constructs a <code>PaymentProcessorConfigurator</code>. */ public PaymentProcessorConfigurator() { } /** * Configures the specified payment processor. * * @param processor Payment processor to configure. * @throws IOException If a configuration error occurred. */ public void configure(PaymentProcessor processor) { // // Production applications should use a dynamic // configuration mechanism with an adapter factory // to construct the appropriate adapter. // IGatewayAdapter adapter = null; /* adapter = makeAdapter("XYZGatewayAdapter"); adapter.setHost(someHostName); */ processor.setGatewayAdapter(adapter); } }
1,142
23.319149
70
java
jdepend
jdepend-master/sample/epayment/request/PaymentRequest.java
package epayment.request; import epayment.framework.IPaymentRequest; /** * The <code>PaymentRequest</code> class is an * <code>IPaymentRequest</code> that encapsulates * the basic payment request information. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public class PaymentRequest implements IPaymentRequest { private String _userId; private String _userPassword; private String _name; private String _accountNumber; private double _amount; private String _comment; /** * Constructs a <code>PaymentRequest</code>. * with default values. */ public PaymentRequest() { _userId = ""; _userPassword = ""; _name = ""; _accountNumber = ""; _amount = 0.0; _comment = ""; } /** * Sets the user id. * * @param id User id. */ public void setUserId(String id) { _userId = id; } /** * Returns the user id. * * @return User id. */ protected String getUserId() { return _userId; } /** * Sets the user password. * * @param password User password. */ public void setUserPassword(String password) { _userPassword = password; } /** * Returns the user password. * * @return User password. */ protected String getUserPassword() { return _userPassword; } /** * Sets the name. * * @param name Name. */ public void setAccountName(String name) { _name = name; } /** * Returns the name. * * @return Name. */ protected String getAccountName() { return _name; } /** * Sets the account number. * * @param number Account number. */ public void setAccountNumber(String number) { _accountNumber = number; } /** * Returns the account number. * * @return Account number. */ protected String getAccountNumber() { return _accountNumber; } /** * Sets the amount of the transaction. * * @param amount Amount in dollars. */ public void setAmount(double amount) { _amount = amount; } /** * Returns the amount of the transaction. * * @return Amount in dollars. */ protected double getAmount() { return _amount; } /** * Sets the reporting comment. * * @param comment Reporting comment. */ public void setComment(String comment) { _comment = comment; } /** * Returns the reporting comment. * * @return Reporting comment. */ protected String getComment() { return _comment; } /** * Returns the string representation of this object. * * @return String representation. */ public String toString() { StringBuffer contents = new StringBuffer(); contents.append("User ID = " + _userId + "\n"); contents.append("User Password = " + _userPassword + "\n"); contents.append("Name = " + _name + "\n"); contents.append("Account Number = " + _accountNumber + "\n"); contents.append("Amount = " + _amount + "\n"); return contents.toString(); } }
2,991
16.6
70
java
jdepend
jdepend-master/sample/epayment/response/PaymentResponse.java
package epayment.response; import epayment.framework.IPaymentResponse; /** * The <code>PaymentResponse</code> class is an * <code>IPaymentResponse</code> that encapsulates * the basic payment response information. * <p> * This class is strictly an example. * * @author <a href="mailto:[email protected]">Mike Clark</a> * @author <a href="http://www.clarkware.com">Clarkware Consulting</a> */ public class PaymentResponse implements IPaymentResponse { private String _processedDate; private String _responseMessage; /** * Constructs a <code>PaymentResponse</code> * with default values. */ public PaymentResponse() { _processedDate = ""; _responseMessage = ""; } /** * Returns the processed date. * * @return Processed date. */ public String getProcessedDate() { return _processedDate; } /** * Sets the processed date. * * @param date Processed date. */ protected void setProcessedDate(String date) { _processedDate = date; } /** * Returns the response message. * * @return Response message. */ public String getResponseMessage() { return _responseMessage; } /** * Sets the response message. * * @param message Response message. */ protected void setResponseMessage(String message) { _responseMessage = message; } /** * Returns the string representation of this object. * * @return String representation. */ public String toString() { StringBuffer contents = new StringBuffer(); contents.append("Response Message = " + _responseMessage + "\n"); contents.append("Processed Date = " + _processedDate + "\n"); return contents.toString(); } }
1,655
19.7
70
java
jdepend
jdepend-master/src/jdepend/framework/AbstractParser.java
package jdepend.framework; import java.io.*; import java.util.*; /** * The <code>AbstractParser</code> class is the base class * for classes capable of parsing files to create a * <code>JavaClass</code> instance. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public abstract class AbstractParser { private ArrayList parseListeners; private PackageFilter filter; public static boolean DEBUG = false; public AbstractParser() { this(new PackageFilter()); } public AbstractParser(PackageFilter filter) { setFilter(filter); parseListeners = new ArrayList(); } public void addParseListener(ParserListener listener) { parseListeners.add(listener); } /** * Registered parser listeners are informed that the resulting * <code>JavaClass</code> was parsed. */ public abstract JavaClass parse(InputStream is) throws IOException; /** * Informs registered parser listeners that the specified * <code>JavaClass</code> was parsed. * * @param jClass Parsed Java class. */ protected void onParsedJavaClass(JavaClass jClass) { for (Iterator i = parseListeners.iterator(); i.hasNext();) { ((ParserListener) i.next()).onParsedJavaClass(jClass); } } protected PackageFilter getFilter() { if (filter == null) { setFilter(new PackageFilter()); } return filter; } protected void setFilter(PackageFilter filter) { this.filter = filter; } protected void debug(String message) { if (DEBUG) { System.err.println(message); } } }
1,698
23.623188
71
java
jdepend
jdepend-master/src/jdepend/framework/ClassFileParser.java
package jdepend.framework; import java.io.*; import java.util.*; /** * The <code>ClassFileParser</code> class is responsible for * parsing a Java class file to create a <code>JavaClass</code> * instance. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class ClassFileParser extends AbstractParser { public static final int JAVA_MAGIC = 0xCAFEBABE; public static final int CONSTANT_UTF8 = 1; public static final int CONSTANT_UNICODE = 2; public static final int CONSTANT_INTEGER = 3; public static final int CONSTANT_FLOAT = 4; public static final int CONSTANT_LONG = 5; public static final int CONSTANT_DOUBLE = 6; public static final int CONSTANT_CLASS = 7; public static final int CONSTANT_STRING = 8; public static final int CONSTANT_FIELD = 9; public static final int CONSTANT_METHOD = 10; public static final int CONSTANT_INTERFACEMETHOD = 11; public static final int CONSTANT_NAMEANDTYPE = 12; public static final int CONSTANT_METHOD_HANDLE = 15; public static final int CONSTANT_METHOD_TYPE = 16; public static final int CONSTANT_INVOKEDYNAMIC = 18; public static final char CLASS_DESCRIPTOR = 'L'; public static final int ACC_INTERFACE = 0x200; public static final int ACC_ABSTRACT = 0x400; private String fileName; private String className; private String superClassName; private String interfaceNames[]; private boolean isAbstract; private JavaClass jClass; private Constant[] constantPool; private FieldOrMethodInfo[] fields; private FieldOrMethodInfo[] methods; private AttributeInfo[] attributes; private DataInputStream in; public ClassFileParser() { this(new PackageFilter()); } public ClassFileParser(PackageFilter filter) { super(filter); reset(); } private void reset() { className = null; superClassName = null; interfaceNames = new String[0]; isAbstract = false; jClass = null; constantPool = new Constant[1]; fields = new FieldOrMethodInfo[0]; methods = new FieldOrMethodInfo[0]; attributes = new AttributeInfo[0]; } /** * Registered parser listeners are informed that the resulting * <code>JavaClass</code> was parsed. */ public JavaClass parse(File classFile) throws IOException { this.fileName = classFile.getCanonicalPath(); debug("\nParsing " + fileName + "..."); InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(classFile)); return parse(in); } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } } public JavaClass parse(InputStream is) throws IOException { reset(); jClass = new JavaClass("Unknown"); in = new DataInputStream(is); int magic = parseMagic(); int minorVersion = parseMinorVersion(); int majorVersion = parseMajorVersion(); constantPool = parseConstantPool(); parseAccessFlags(); className = parseClassName(); superClassName = parseSuperClassName(); interfaceNames = parseInterfaces(); fields = parseFields(); methods = parseMethods(); parseAttributes(); addClassConstantReferences(); addAnnotationsReferences(); onParsedJavaClass(jClass); return jClass; } private int parseMagic() throws IOException { int magic = in.readInt(); if (magic != JAVA_MAGIC) { throw new IOException("Invalid class file: " + fileName); } return magic; } private int parseMinorVersion() throws IOException { return in.readUnsignedShort(); } private int parseMajorVersion() throws IOException { return in.readUnsignedShort(); } private Constant[] parseConstantPool() throws IOException { int constantPoolSize = in.readUnsignedShort(); Constant[] pool = new Constant[constantPoolSize]; for (int i = 1; i < constantPoolSize; i++) { Constant constant = parseNextConstant(); pool[i] = constant; // // 8-byte constants use two constant pool entries // if (constant.getTag() == CONSTANT_DOUBLE || constant.getTag() == CONSTANT_LONG) { i++; } } return pool; } private void parseAccessFlags() throws IOException { int accessFlags = in.readUnsignedShort(); boolean isAbstract = ((accessFlags & ACC_ABSTRACT) != 0); boolean isInterface = ((accessFlags & ACC_INTERFACE) != 0); this.isAbstract = isAbstract || isInterface; jClass.isAbstract(this.isAbstract); debug("Parser: abstract = " + this.isAbstract); } private String parseClassName() throws IOException { int entryIndex = in.readUnsignedShort(); String className = getClassConstantName(entryIndex); jClass.setName(className); jClass.setPackageName(getPackageName(className)); debug("Parser: class name = " + className); debug("Parser: package name = " + getPackageName(className)); return className; } private String parseSuperClassName() throws IOException { int entryIndex = in.readUnsignedShort(); String superClassName = getClassConstantName(entryIndex); addImport(getPackageName(superClassName)); debug("Parser: super class name = " + superClassName); return superClassName; } private String[] parseInterfaces() throws IOException { int interfacesCount = in.readUnsignedShort(); String[] interfaceNames = new String[interfacesCount]; for (int i = 0; i < interfacesCount; i++) { int entryIndex = in.readUnsignedShort(); interfaceNames[i] = getClassConstantName(entryIndex); addImport(getPackageName(interfaceNames[i])); debug("Parser: interface = " + interfaceNames[i]); } return interfaceNames; } private FieldOrMethodInfo[] parseFields() throws IOException { int fieldsCount = in.readUnsignedShort(); FieldOrMethodInfo[] fields = new FieldOrMethodInfo[fieldsCount]; for (int i = 0; i < fieldsCount; i++) { fields[i] = parseFieldOrMethodInfo(); String descriptor = toUTF8(fields[i].getDescriptorIndex()); debug("Parser: field descriptor = " + descriptor); String[] types = descriptorToTypes(descriptor); for (int t = 0; t < types.length; t++) { addImport(getPackageName(types[t])); debug("Parser: field type = " + types[t]); } } return fields; } private FieldOrMethodInfo[] parseMethods() throws IOException { int methodsCount = in.readUnsignedShort(); FieldOrMethodInfo[] methods = new FieldOrMethodInfo[methodsCount]; for (int i = 0; i < methodsCount; i++) { methods[i] = parseFieldOrMethodInfo(); String descriptor = toUTF8(methods[i].getDescriptorIndex()); debug("Parser: method descriptor = " + descriptor); String[] types = descriptorToTypes(descriptor); for (int t = 0; t < types.length; t++) { if (types[t].length() > 0) { addImport(getPackageName(types[t])); debug("Parser: method type = " + types[t]); } } } return methods; } private Constant parseNextConstant() throws IOException { Constant result; byte tag = in.readByte(); switch (tag) { case (ClassFileParser.CONSTANT_CLASS): case (ClassFileParser.CONSTANT_STRING): case (ClassFileParser.CONSTANT_METHOD_TYPE): result = new Constant(tag, in.readUnsignedShort()); break; case (ClassFileParser.CONSTANT_FIELD): case (ClassFileParser.CONSTANT_METHOD): case (ClassFileParser.CONSTANT_INTERFACEMETHOD): case (ClassFileParser.CONSTANT_NAMEANDTYPE): case (ClassFileParser.CONSTANT_INVOKEDYNAMIC): result = new Constant(tag, in.readUnsignedShort(), in .readUnsignedShort()); break; case (ClassFileParser.CONSTANT_INTEGER): result = new Constant(tag, new Integer(in.readInt())); break; case (ClassFileParser.CONSTANT_FLOAT): result = new Constant(tag, new Float(in.readFloat())); break; case (ClassFileParser.CONSTANT_LONG): result = new Constant(tag, new Long(in.readLong())); break; case (ClassFileParser.CONSTANT_DOUBLE): result = new Constant(tag, new Double(in.readDouble())); break; case (ClassFileParser.CONSTANT_UTF8): result = new Constant(tag, in.readUTF()); break; case (ClassFileParser.CONSTANT_METHOD_HANDLE): result = new Constant(tag, in.readByte(), in.readUnsignedShort()); break; default: throw new IOException("Unknown constant: " + tag); } return result; } private FieldOrMethodInfo parseFieldOrMethodInfo() throws IOException { FieldOrMethodInfo result = new FieldOrMethodInfo( in.readUnsignedShort(), in.readUnsignedShort(), in .readUnsignedShort()); int attributesCount = in.readUnsignedShort(); for (int a = 0; a < attributesCount; a++) { AttributeInfo attribute = parseAttribute(); if ("RuntimeVisibleAnnotations".equals(attribute.name)) { result._runtimeVisibleAnnotations = attribute; } } return result; } private void parseAttributes() throws IOException { int attributesCount = in.readUnsignedShort(); attributes = new AttributeInfo[attributesCount]; for (int i = 0; i < attributesCount; i++) { attributes[i] = parseAttribute(); // Section 4.7.7 of VM Spec - Class File Format if (attributes[i].getName() != null) { if (attributes[i].getName().equals("SourceFile")) { byte[] b = attributes[i].getValue(); int b0 = b[0] < 0 ? b[0] + 256 : b[0]; int b1 = b[1] < 0 ? b[1] + 256 : b[1]; int pe = b0 * 256 + b1; String descriptor = toUTF8(pe); jClass.setSourceFile(descriptor); } } } } private AttributeInfo parseAttribute() throws IOException { AttributeInfo result = new AttributeInfo(); int nameIndex = in.readUnsignedShort(); if (nameIndex != -1) { result.setName(toUTF8(nameIndex)); } int attributeLength = in.readInt(); byte[] value = new byte[attributeLength]; for (int b = 0; b < attributeLength; b++) { value[b] = in.readByte(); } result.setValue(value); return result; } private Constant getConstantPoolEntry(int entryIndex) throws IOException { if (entryIndex < 0 || entryIndex >= constantPool.length) { throw new IOException("Illegal constant pool index : " + entryIndex); } return constantPool[entryIndex]; } private void addClassConstantReferences() throws IOException { for (int j = 1; j < constantPool.length; j++) { if (constantPool[j].getTag() == CONSTANT_CLASS) { String name = toUTF8(constantPool[j].getNameIndex()); addImport(getPackageName(name)); debug("Parser: class type = " + slashesToDots(name)); } if (constantPool[j].getTag() == CONSTANT_DOUBLE || constantPool[j].getTag() == CONSTANT_LONG) { j++; } } } private void addAnnotationsReferences() throws IOException { for (int j = 1; j < attributes.length; j++) { if ("RuntimeVisibleAnnotations".equals(attributes[j].name)) { addAnnotationReferences(attributes[j]); } } for (int j = 1; j < fields.length; j++) { if (fields[j]._runtimeVisibleAnnotations != null) { addAnnotationReferences(fields[j]._runtimeVisibleAnnotations); } } for (int j = 1; j < methods.length; j++) { if (methods[j]._runtimeVisibleAnnotations != null) { addAnnotationReferences(methods[j]._runtimeVisibleAnnotations); } } } private void addAnnotationReferences(AttributeInfo annotation) throws IOException { // JVM Spec 4.8.15 byte[] data = annotation.value; int numAnnotations = u2(data, 0); int annotationIndex = 2; addAnnotationReferences(data, annotationIndex, numAnnotations); } private int addAnnotationReferences(byte[] data, int index, int numAnnotations) throws IOException { int visitedAnnotations = 0; while (visitedAnnotations < numAnnotations) { int typeIndex = u2(data, index); int numElementValuePairs = u2(data, index = index + 2); addImport(getPackageName(toUTF8(typeIndex).substring(1))); int visitedElementValuePairs = 0; index += 2; while (visitedElementValuePairs < numElementValuePairs) { index = addAnnotationElementValueReferences(data, index = index + 2); visitedElementValuePairs++; } visitedAnnotations++; } return index; } private int addAnnotationElementValueReferences(byte[] data, int index) throws IOException { byte tag = data[index]; index += 1; switch (tag) { case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': case 's': index += 2; break; case 'e': int enumTypeIndex = u2(data, index); addImport(getPackageName(toUTF8(enumTypeIndex).substring(1))); index += 4; break; case 'c': int classInfoIndex = u2(data, index); addImport(getPackageName(toUTF8(classInfoIndex).substring(1))); index += 2; break; case '@': index = addAnnotationReferences(data, index, 1); break; case '[': int numValues = u2(data, index); index = index + 2; for (int i = 0; i < numValues; i++) { index = addAnnotationElementValueReferences(data, index); } break; } return index; } private int u2(byte[] data, int index) { return (data[index] << 8 & 0xFF00) | (data[index+1] & 0xFF); } private String getClassConstantName(int entryIndex) throws IOException { Constant entry = getConstantPoolEntry(entryIndex); if (entry == null) { return ""; } return slashesToDots(toUTF8(entry.getNameIndex())); } private String toUTF8(int entryIndex) throws IOException { Constant entry = getConstantPoolEntry(entryIndex); if (entry.getTag() == CONSTANT_UTF8) { return (String) entry.getValue(); } throw new IOException("Constant pool entry is not a UTF8 type: " + entryIndex); } private void addImport(String importPackage) { if ((importPackage != null) && (getFilter().accept(importPackage))) { jClass.addImportedPackage(new JavaPackage(importPackage)); } } private String slashesToDots(String s) { return s.replace('/', '.'); } private String getPackageName(String s) { if ((s.length() > 0) && (s.charAt(0) == '[')) { String types[] = descriptorToTypes(s); if (types.length == 0) { return null; // primitives } s = types[0]; } s = slashesToDots(s); int index = s.lastIndexOf("."); if (index > 0) { return s.substring(0, index); } return "Default"; } private String[] descriptorToTypes(String descriptor) { int typesCount = 0; for (int index = 0; index < descriptor.length(); index++) { if (descriptor.charAt(index) == ';') { typesCount++; } } String types[] = new String[typesCount]; int typeIndex = 0; for (int index = 0; index < descriptor.length(); index++) { int startIndex = descriptor.indexOf(CLASS_DESCRIPTOR, index); if (startIndex < 0) { break; } index = descriptor.indexOf(';', startIndex + 1); types[typeIndex++] = descriptor.substring(startIndex + 1, index); } return types; } class Constant { private byte _tag; private int _nameIndex; private int _typeIndex; private Object _value; Constant(byte tag, int nameIndex) { this(tag, nameIndex, -1); } Constant(byte tag, Object value) { this(tag, -1, -1); _value = value; } Constant(byte tag, int nameIndex, int typeIndex) { _tag = tag; _nameIndex = nameIndex; _typeIndex = typeIndex; _value = null; } byte getTag() { return _tag; } int getNameIndex() { return _nameIndex; } int getTypeIndex() { return _typeIndex; } Object getValue() { return _value; } public String toString() { StringBuffer s = new StringBuffer(""); s.append("tag: " + getTag()); if (getNameIndex() > -1) { s.append(" nameIndex: " + getNameIndex()); } if (getTypeIndex() > -1) { s.append(" typeIndex: " + getTypeIndex()); } if (getValue() != null) { s.append(" value: " + getValue()); } return s.toString(); } } class FieldOrMethodInfo { private int _accessFlags; private int _nameIndex; private int _descriptorIndex; private AttributeInfo _runtimeVisibleAnnotations; FieldOrMethodInfo(int accessFlags, int nameIndex, int descriptorIndex) { _accessFlags = accessFlags; _nameIndex = nameIndex; _descriptorIndex = descriptorIndex; } int accessFlags() { return _accessFlags; } int getNameIndex() { return _nameIndex; } int getDescriptorIndex() { return _descriptorIndex; } public String toString() { StringBuffer s = new StringBuffer(""); try { s.append("\n name (#" + getNameIndex() + ") = " + toUTF8(getNameIndex())); s.append("\n signature (#" + getDescriptorIndex() + ") = " + toUTF8(getDescriptorIndex())); String[] types = descriptorToTypes(toUTF8(getDescriptorIndex())); for (int t = 0; t < types.length; t++) { s.append("\n type = " + types[t]); } } catch (Exception e) { e.printStackTrace(); } return s.toString(); } } class AttributeInfo { private String name; private byte[] value; public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setValue(byte[] value) { this.value = value; } public byte[] getValue() { return this.value; } } /** * Returns a string representation of this object. * * @return String representation. */ public String toString() { StringBuffer s = new StringBuffer(); try { s.append("\n" + className + ":\n"); s.append("\nConstants:\n"); for (int i = 1; i < constantPool.length; i++) { Constant entry = getConstantPoolEntry(i); s.append(" " + i + ". " + entry.toString() + "\n"); if (entry.getTag() == CONSTANT_DOUBLE || entry.getTag() == CONSTANT_LONG) { i++; } } s.append("\nClass Name: " + className + "\n"); s.append("Super Name: " + superClassName + "\n\n"); s.append(interfaceNames.length + " interfaces\n"); for (int i = 0; i < interfaceNames.length; i++) { s.append(" " + interfaceNames[i] + "\n"); } s.append("\n" + fields.length + " fields\n"); for (int i = 0; i < fields.length; i++) { s.append(fields[i].toString() + "\n"); } s.append("\n" + methods.length + " methods\n"); for (int i = 0; i < methods.length; i++) { s.append(methods[i].toString() + "\n"); } s.append("\nDependencies:\n"); Iterator imports = jClass.getImportedPackages().iterator(); while (imports.hasNext()) { JavaPackage jPackage = (JavaPackage) imports.next(); s.append(" " + jPackage.getName() + "\n"); } } catch (Exception e) { e.printStackTrace(); } return s.toString(); } /** * Test main. */ public static void main(String args[]) { try { ClassFileParser.DEBUG = true; if (args.length <= 0) { System.err.println("usage: ClassFileParser <class-file>"); System.exit(0); } ClassFileParser parser = new ClassFileParser(); parser.parse(new File(args[0])); System.err.println(parser.toString()); } catch (Exception e) { System.err.println(e.getMessage()); } } }
22,723
28.32129
104
java
jdepend
jdepend-master/src/jdepend/framework/DependencyConstraint.java
package jdepend.framework; import java.util.*; import jdepend.framework.JavaPackage; /** * The <code>DependencyConstraint</code> class is a constraint that tests * whether two package-dependency graphs are equivalent. * <p> * This class is useful for writing package dependency assertions (e.g. JUnit). * For example, the following JUnit test will ensure that the 'ejb' and 'web' * packages only depend upon the 'util' package, and no others: * <p> * <blockquote> * * <pre> * * public void testDependencyConstraint() { * * JDepend jdepend = new JDepend(); * jdepend.addDirectory(&quot;/path/to/classes&quot;); * Collection analyzedPackages = jdepend.analyze(); * * DependencyConstraint constraint = new DependencyConstraint(); * * JavaPackage ejb = constraint.addPackage(&quot;com.xyz.ejb&quot;); * JavaPackage web = constraint.addPackage(&quot;com.xyz.web&quot;); * JavaPackage util = constraint.addPackage(&quot;com.xyz.util&quot;); * * ejb.dependsUpon(util); * web.dependsUpon(util); * * assertEquals(&quot;Dependency mismatch&quot;, true, constraint * .match(analyzedPackages)); * } * </pre> * * </blockquote> * </p> * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class DependencyConstraint { private HashMap packages; public DependencyConstraint() { packages = new HashMap(); } public JavaPackage addPackage(String packageName) { JavaPackage jPackage = (JavaPackage) packages.get(packageName); if (jPackage == null) { jPackage = new JavaPackage(packageName); addPackage(jPackage); } return jPackage; } public void addPackage(JavaPackage jPackage) { if (!packages.containsValue(jPackage)) { packages.put(jPackage.getName(), jPackage); } } public Collection getPackages() { return packages.values(); } /** * Indicates whether the specified packages match the * packages in this constraint. * * @return <code>true</code> if the packages match this constraint */ public boolean match(Collection expectedPackages) { if (packages.size() == expectedPackages.size()) { for (Iterator i = expectedPackages.iterator(); i.hasNext();) { Object next = i.next(); if (next instanceof JavaPackage) { JavaPackage nextPackage = (JavaPackage) next; if (!matchPackage(nextPackage)) { return false; } } else { break; } return true; } } return false; } private boolean matchPackage(JavaPackage expectedPackage) { JavaPackage actualPackage = (JavaPackage) packages.get(expectedPackage .getName()); if (actualPackage != null) { if (equalsDependencies(actualPackage, expectedPackage)) { return true; } } return false; } private boolean equalsDependencies(JavaPackage a, JavaPackage b) { return equalsAfferents(a, b) && equalsEfferents(a, b); } private boolean equalsAfferents(JavaPackage a, JavaPackage b) { if (a.equals(b)) { Collection otherAfferents = b.getAfferents(); if (a.getAfferents().size() == otherAfferents.size()) { for (Iterator i = a.getAfferents().iterator(); i.hasNext();) { JavaPackage afferent = (JavaPackage)i.next(); if (!otherAfferents.contains(afferent)) { return false; } } return true; } } return false; } private boolean equalsEfferents(JavaPackage a, JavaPackage b) { if (a.equals(b)) { Collection otherEfferents = b.getEfferents(); if (a.getEfferents().size() == otherEfferents.size()) { for (Iterator i = a.getEfferents().iterator(); i.hasNext();) { JavaPackage efferent = (JavaPackage)i.next(); if (!otherEfferents.contains(efferent)) { return false; } } return true; } } return false; } }
4,489
27.0625
79
java
jdepend
jdepend-master/src/jdepend/framework/FileManager.java
package jdepend.framework; import java.io.*; import java.util.*; /** * The <code>FileManager</code> class is responsible for extracting * Java class files (<code>.class</code> files) from a collection of * registered directories. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class FileManager { private ArrayList directories; private boolean acceptInnerClasses; public FileManager() { directories = new ArrayList(); acceptInnerClasses = true; } /** * Determines whether inner classes should be collected. * * @param b <code>true</code> to collect inner classes; * <code>false</code> otherwise. */ public void acceptInnerClasses(boolean b) { acceptInnerClasses = b; } public void addDirectory(String name) throws IOException { File directory = new File(name); if (directory.isDirectory() || acceptJarFile(directory)) { directories.add(directory); } else { throw new IOException("Invalid directory or JAR file: " + name); } } public boolean acceptFile(File file) { return acceptClassFile(file) || acceptJarFile(file); } public boolean acceptClassFile(File file) { if (!file.isFile()) { return false; } return acceptClassFileName(file.getName()); } public boolean acceptClassFileName(String name) { if (!acceptInnerClasses) { if (name.toLowerCase().indexOf("$") > 0) { return false; } } if (!name.toLowerCase().endsWith(".class")) { return false; } return true; } public boolean acceptJarFile(File file) { return isJar(file) || isZip(file) || isWar(file); } public Collection extractFiles() { Collection files = new TreeSet(); for (Iterator i = directories.iterator(); i.hasNext();) { File directory = (File)i.next(); collectFiles(directory, files); } return files; } private void collectFiles(File directory, Collection files) { if (directory.isFile()) { addFile(directory, files); } else { String[] directoryFiles = directory.list(); for (int i = 0; i < directoryFiles.length; i++) { File file = new File(directory, directoryFiles[i]); if (acceptFile(file)) { addFile(file, files); } else if (file.isDirectory()) { collectFiles(file, files); } } } } private void addFile(File f, Collection files) { if (!files.contains(f)) { files.add(f); } } private boolean isWar(File file) { return existsWithExtension(file, ".war"); } private boolean isZip(File file) { return existsWithExtension(file, ".zip"); } private boolean isJar(File file) { return existsWithExtension(file, ".jar"); } private boolean existsWithExtension(File file, String extension) { return file.isFile() && file.getName().toLowerCase().endsWith(extension); } }
3,288
23.544776
76
java
jdepend
jdepend-master/src/jdepend/framework/JDepend.java
package jdepend.framework; import java.io.IOException; import java.util.*; /** * The <code>JDepend</code> class analyzes directories of Java class files * and generates the following metrics for each Java package. * <p> * <ul> * <li>Afferent Coupling (Ca) * <p> * The number of packages that depend upon the classes within the analyzed * package. * </p> * </li> * <li>Efferent Coupling (Ce) * <p> * The number of packages that the classes in the analyzed package depend upon. * </p> * </li> * <li>Abstractness (A) * <p> * The ratio of the number of abstract classes (and interfaces) in the analyzed * package to the total number of classes in the analyzed package. * </p> * <p> * The range for this metric is 0 to 1, with A=0 indicating a completely * concrete package and A=1 indicating a completely abstract package. * </p> * </li> * <li>Instability (I) * <p> * The ratio of efferent coupling (Ce) to total coupling (Ce + Ca) such that I = * Ce / (Ce + Ca). * </p> * <p> * The range for this metric is 0 to 1, with I=0 indicating a completely stable * package and I=1 indicating a completely instable package. * </p> * </li> * <li>Distance from the Main Sequence (D) * <p> * The perpendicular distance of a package from the idealized line A + I = 1. A * package coincident with the main sequence is optimally balanced with respect * to its abstractness and stability. Ideal packages are either completely * abstract and stable (x=0, y=1) or completely concrete and instable (x=1, * y=0). * </p> * <p> * The range for this metric is 0 to 1, with D=0 indicating a package that is * coincident with the main sequence and D=1 indicating a package that is as far * from the main sequence as possible. * </p> * </li> * <li>Package Dependency Cycle * <p> * Package dependency cycles are reported along with the paths of packages * participating in package dependency cycles. * </p> * </li> * </ul> * <p> * These metrics are hereafter referred to as the "Martin Metrics", as they are * credited to Robert Martin (Object Mentor Inc.) and referenced in the book * "Designing Object Oriented C++ Applications using the Booch Method", by * Robert C. Martin, Prentice Hall, 1995. * </p> * <p> * Example API use: * <p> * <blockquote> * * <pre> * JDepend jdepend = new JDepend(); * jdepend.addDirectory(&quot;/path/to/classes&quot;); * Collection packages = jdepend.analyze(); * * Iterator i = packages.iterator(); * while (i.hasNext()) { * JavaPackage jPackage = (JavaPackage) i.next(); * String name = jPackage.getName(); * int Ca = jPackage.afferentCoupling(); * int Ce = jPackage.efferentCoupling(); * float A = jPackage.abstractness(); * float I = jPackage.instability(); * float D = jPackage.distance(); * boolean b = jPackage.containsCycle(); * } * </pre> * * </blockquote> * </p> * <p> * This class is the data model used by the <code>jdepend.textui.JDepend</code> * and <code>jdepend.swingui.JDepend</code> views. * </p> * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class JDepend { private HashMap packages; private FileManager fileManager; private PackageFilter filter; private ClassFileParser parser; private JavaClassBuilder builder; private Collection components; public JDepend() { this(new PackageFilter()); } public JDepend(PackageFilter filter) { setFilter(filter); this.packages = new HashMap(); this.fileManager = new FileManager(); this.parser = new ClassFileParser(filter); this.builder = new JavaClassBuilder(parser, fileManager); PropertyConfigurator config = new PropertyConfigurator(); addPackages(config.getConfiguredPackages()); analyzeInnerClasses(config.getAnalyzeInnerClasses()); } /** * Analyzes the registered directories and returns the collection of * analyzed packages. * * @return Collection of analyzed packages. */ public Collection analyze() { Collection classes = builder.build(); for (Iterator i = classes.iterator(); i.hasNext();) { analyzeClass((JavaClass)i.next()); } return getPackages(); } /** * Adds the specified directory name to the collection of directories to be * analyzed. * * @param name Directory name. * @throws IOException If the directory is invalid. */ public void addDirectory(String name) throws IOException { fileManager.addDirectory(name); } /** * Sets the list of components. * * @param components Comma-separated list of components. */ public void setComponents(String components) { this.components = new ArrayList(); StringTokenizer st = new StringTokenizer(components, ","); while (st.hasMoreTokens()) { String component = st.nextToken(); this.components.add(component); } } /** * Determines whether inner classes are analyzed. * * @param b <code>true</code> to analyze inner classes; * <code>false</code> otherwise. */ public void analyzeInnerClasses(boolean b) { fileManager.acceptInnerClasses(b); } /** * Returns the collection of analyzed packages. * * @return Collection of analyzed packages. */ public Collection getPackages() { return packages.values(); } /** * Returns the analyzed package of the specified name. * * @param name Package name. * @return Package, or <code>null</code> if the package was not analyzed. */ public JavaPackage getPackage(String name) { return (JavaPackage)packages.get(name); } /** * Returns the number of analyzed Java packages. * * @return Number of Java packages. */ public int countPackages() { return getPackages().size(); } /** * Returns the number of registered Java classes to be analyzed. * * @return Number of classes. */ public int countClasses() { return builder.countClasses(); } /** * Indicates whether the packages contain one or more dependency cycles. * * @return <code>true</code> if one or more dependency cycles exist. */ public boolean containsCycles() { for (Iterator i = getPackages().iterator(); i.hasNext();) { JavaPackage jPackage = (JavaPackage)i.next(); if (jPackage.containsCycle()) { return true; } } return false; } /** * Indicates whether the analyzed packages match the specified * dependency constraint. * * @return <code>true</code> if the packages match the dependency * constraint */ public boolean dependencyMatch(DependencyConstraint constraint) { return constraint.match(getPackages()); } /** * Registers the specified parser listener. * * @param listener Parser listener. */ public void addParseListener(ParserListener listener) { parser.addParseListener(listener); } /** * Adds the specified Java package name to the collection of analyzed * packages. * * @param name Java package name. * @return Added Java package. */ public JavaPackage addPackage(String name) { name = toComponent(name); JavaPackage pkg = (JavaPackage)packages.get(name); if (pkg == null) { pkg = new JavaPackage(name); addPackage(pkg); } return pkg; } private String toComponent(String packageName) { if (components != null) { for (Iterator i = components.iterator(); i.hasNext();) { String component = (String)i.next(); if (packageName.startsWith(component + ".")) { return component; } } } return packageName; } /** * Adds the specified collection of packages to the collection * of analyzed packages. * * @param packages Collection of packages. */ public void addPackages(Collection packages) { for (Iterator i = packages.iterator(); i.hasNext();) { JavaPackage pkg = (JavaPackage)i.next(); addPackage(pkg); } } /** * Adds the specified Java package to the collection of * analyzed packages. * * @param pkg Java package. */ public void addPackage(JavaPackage pkg) { if (!packages.containsValue(pkg)) { packages.put(pkg.getName(), pkg); } } public PackageFilter getFilter() { if (filter == null) { filter = new PackageFilter(); } return filter; } public void setFilter(PackageFilter filter) { if (parser != null) { parser.setFilter(filter); } this.filter = filter; } private void analyzeClass(JavaClass clazz) { String packageName = clazz.getPackageName(); if (!getFilter().accept(packageName)) { return; } JavaPackage clazzPackage = addPackage(packageName); clazzPackage.addClass(clazz); Collection imports = clazz.getImportedPackages(); for (Iterator i = imports.iterator(); i.hasNext();) { JavaPackage importedPackage = (JavaPackage)i.next(); importedPackage = addPackage(importedPackage.getName()); clazzPackage.dependsUpon(importedPackage); } } }
9,730
27.205797
80
java
jdepend
jdepend-master/src/jdepend/framework/JavaClass.java
package jdepend.framework; import java.util.*; /** * The <code>JavaClass</code> class represents a Java * class or interface. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class JavaClass { private String className; private String packageName; private boolean isAbstract; private HashMap imports; private String sourceFile; public JavaClass(String name) { className = name; packageName = "default"; isAbstract = false; imports = new HashMap(); sourceFile = "Unknown"; } public void setName(String name) { className = name; } public String getName() { return className; } public void setPackageName(String name) { packageName = name; } public String getPackageName() { return packageName; } public void setSourceFile(String name) { sourceFile = name; } public String getSourceFile() { return sourceFile; } public Collection getImportedPackages() { return imports.values(); } public void addImportedPackage(JavaPackage jPackage) { if (!jPackage.getName().equals(getPackageName())) { imports.put(jPackage.getName(), jPackage); } } public boolean isAbstract() { return isAbstract; } public void isAbstract(boolean isAbstract) { this.isAbstract = isAbstract; } public boolean equals(Object other) { if (other instanceof JavaClass) { JavaClass otherClass = (JavaClass) other; return otherClass.getName().equals(getName()); } return false; } public int hashCode() { return getName().hashCode(); } public static class ClassComparator implements Comparator { public int compare(Object a, Object b) { JavaClass c1 = (JavaClass) a; JavaClass c2 = (JavaClass) b; return c1.getName().compareTo(c2.getName()); } } }
2,044
20.302083
63
java
jdepend
jdepend-master/src/jdepend/framework/JavaClassBuilder.java
package jdepend.framework; import java.io.*; import java.util.*; import java.util.jar.*; import java.util.zip.*; /** * The <code>JavaClassBuilder</code> builds <code>JavaClass</code> * instances from .class, .jar, .war, or .zip files. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class JavaClassBuilder { private AbstractParser parser; private FileManager fileManager; public JavaClassBuilder() { this(new ClassFileParser(), new FileManager()); } public JavaClassBuilder(FileManager fm) { this(new ClassFileParser(), fm); } public JavaClassBuilder(AbstractParser parser, FileManager fm) { this.parser = parser; this.fileManager = fm; } public int countClasses() { AbstractParser counter = new AbstractParser() { public JavaClass parse(InputStream is) { return new JavaClass(""); } }; JavaClassBuilder builder = new JavaClassBuilder(counter, fileManager); Collection classes = builder.build(); return classes.size(); } /** * Builds the <code>JavaClass</code> instances. * * @return Collection of <code>JavaClass</code> instances. */ public Collection build() { Collection classes = new ArrayList(); for (Iterator i = fileManager.extractFiles().iterator(); i.hasNext();) { File nextFile = (File)i.next(); try { classes.addAll(buildClasses(nextFile)); } catch (IOException ioe) { System.err.println("\n" + ioe.getMessage()); } } return classes; } /** * Builds the <code>JavaClass</code> instances from the * specified file. * * @param file Class or Jar file. * @return Collection of <code>JavaClass</code> instances. */ public Collection buildClasses(File file) throws IOException { if (fileManager.acceptClassFile(file)) { InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); JavaClass parsedClass = parser.parse(is); Collection javaClasses = new ArrayList(); javaClasses.add(parsedClass); return javaClasses; } finally { if (is != null) { is.close(); } } } else if (fileManager.acceptJarFile(file)) { JarFile jarFile = new JarFile(file); Collection result = buildClasses(jarFile); jarFile.close(); return result; } else { throw new IOException("File is not a valid " + ".class, .jar, .war, or .zip file: " + file.getPath()); } } /** * Builds the <code>JavaClass</code> instances from the specified * jar, war, or zip file. * * @param file Jar, war, or zip file. * @return Collection of <code>JavaClass</code> instances. */ public Collection buildClasses(JarFile file) throws IOException { Collection javaClasses = new ArrayList(); Enumeration entries = file.entries(); while (entries.hasMoreElements()) { ZipEntry e = (ZipEntry) entries.nextElement(); if (fileManager.acceptClassFileName(e.getName())) { InputStream is = null; try { is = new BufferedInputStream(file.getInputStream(e)); JavaClass jc = parser.parse(is); javaClasses.add(jc); } finally { is.close(); } } } return javaClasses; } }
3,806
26.586957
80
java
jdepend
jdepend-master/src/jdepend/framework/JavaPackage.java
package jdepend.framework; import java.util.*; /** * The <code>JavaPackage</code> class represents a Java package. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class JavaPackage { private String name; private int volatility; private HashSet classes; private List afferents; private List efferents; public JavaPackage(String name) { this(name, 1); } public JavaPackage(String name, int volatility) { this.name = name; setVolatility(volatility); classes = new HashSet(); afferents = new ArrayList(); efferents = new ArrayList(); } public String getName() { return name; } /** * @return The package's volatility (0-1). */ public int getVolatility() { return volatility; } /** * @param v Volatility (0-1). */ public void setVolatility(int v) { volatility = v; } public boolean containsCycle() { return collectCycle(new ArrayList()); } /** * Collects the packages participating in the first package dependency cycle * detected which originates from this package. * * @param list Collecting object to be populated with the list of * JavaPackage instances in a cycle. * @return <code>true</code> if a cycle exist; <code>false</code> * otherwise. */ public boolean collectCycle(List list) { if (list.contains(this)) { list.add(this); return true; } list.add(this); for (Iterator i = getEfferents().iterator(); i.hasNext();) { JavaPackage efferent = (JavaPackage)i.next(); if (efferent.collectCycle(list)) { return true; } } list.remove(this); return false; } /** * Collects all the packages participating in a package dependency cycle * which originates from this package. * <p> * This is a more exhaustive search than that employed by * <code>collectCycle</code>. * * @param list Collecting object to be populated with the list of * JavaPackage instances in a cycle. * @return <code>true</code> if a cycle exist; <code>false</code> * otherwise. */ public boolean collectAllCycles(List list) { if (list.contains(this)) { list.add(this); return true; } list.add(this); boolean containsCycle = false; for (Iterator i = getEfferents().iterator(); i.hasNext();) { JavaPackage efferent = (JavaPackage)i.next(); if (efferent.collectAllCycles(list)) { containsCycle = true; } } if (containsCycle) { return true; } list.remove(this); return false; } public void addClass(JavaClass clazz) { classes.add(clazz); } public Collection getClasses() { return classes; } public int getClassCount() { return classes.size(); } public int getAbstractClassCount() { int count = 0; for (Iterator i = classes.iterator(); i.hasNext();) { JavaClass clazz = (JavaClass)i.next(); if (clazz.isAbstract()) { count++; } } return count; } public int getConcreteClassCount() { int count = 0; for (Iterator i = classes.iterator(); i.hasNext();) { JavaClass clazz = (JavaClass)i.next(); if (!clazz.isAbstract()) { count++; } } return count; } /** * Adds the specified Java package as an efferent of this package * and adds this package as an afferent of it. * * @param imported Java package. */ public void dependsUpon(JavaPackage imported) { addEfferent(imported); imported.addAfferent(this); } /** * Adds the specified Java package as an afferent of this package. * * @param jPackage Java package. */ public void addAfferent(JavaPackage jPackage) { if (!jPackage.getName().equals(getName())) { if (!afferents.contains(jPackage)) { afferents.add(jPackage); } } } public Collection getAfferents() { return afferents; } public void setAfferents(Collection afferents) { this.afferents = new ArrayList(afferents); } public void addEfferent(JavaPackage jPackage) { if (!jPackage.getName().equals(getName())) { if (!efferents.contains(jPackage)) { efferents.add(jPackage); } } } public Collection getEfferents() { return efferents; } public void setEfferents(Collection efferents) { this.efferents = new ArrayList(efferents); } /** * @return The afferent coupling (Ca) of this package. */ public int afferentCoupling() { return afferents.size(); } /** * @return The efferent coupling (Ce) of this package. */ public int efferentCoupling() { return efferents.size(); } /** * @return Instability (0-1). */ public float instability() { float totalCoupling = (float) efferentCoupling() + (float) afferentCoupling(); if (totalCoupling > 0) { return efferentCoupling()/totalCoupling; } return 0; } /** * @return The package's abstractness (0-1). */ public float abstractness() { if (getClassCount() > 0) { return (float) getAbstractClassCount() / (float) getClassCount(); } return 0; } /** * @return The package's distance from the main sequence (D). */ public float distance() { float d = Math.abs(abstractness() + instability() - 1); return d * volatility; } public boolean equals(Object other) { if (other instanceof JavaPackage) { JavaPackage otherPackage = (JavaPackage) other; return otherPackage.getName().equals(getName()); } return false; } public int hashCode() { return getName().hashCode(); } public String toString() { return name; } }
6,461
22.67033
80
java
jdepend
jdepend-master/src/jdepend/framework/PackageComparator.java
package jdepend.framework; import java.util.Comparator; /** * The <code>PackageComparator</code> class is a <code>Comparator</code> * used to compare two <code>JavaPackage</code> instances for order using a * sorting strategy. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class PackageComparator implements Comparator { private PackageComparator byWhat; private static PackageComparator byName; static { byName = new PackageComparator(); } public static PackageComparator byName() { return byName; } private PackageComparator() { } public PackageComparator(PackageComparator byWhat) { this.byWhat = byWhat; } public PackageComparator byWhat() { return byWhat; } public int compare(Object p1, Object p2) { JavaPackage a = (JavaPackage) p1; JavaPackage b = (JavaPackage) p2; if (byWhat() == byName()) { return a.getName().compareTo(b.getName()); } return 0; } }
1,052
20.489796
75
java
jdepend
jdepend-master/src/jdepend/framework/PackageFilter.java
package jdepend.framework; import java.io.*; import java.util.*; /** * The <code>PackageFilter</code> class is used to filter imported * package names. * <p> * The default filter contains any packages declared in the * <code>jdepend.properties</code> file, if such a file exists * either in the user's home directory or somewhere in the classpath. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class PackageFilter { private Collection filtered; /** * Constructs a <code>PackageFilter</code> instance containing * the filters specified in the <code>jdepend.properties</code> file, * if it exists. */ public PackageFilter() { this(new ArrayList()); PropertyConfigurator config = new PropertyConfigurator(); addPackages(config.getFilteredPackages()); } /** * Constructs a <code>PackageFilter</code> instance containing * the filters contained in the specified file. * * @param f Property file. */ public PackageFilter(File f) { this(new ArrayList()); PropertyConfigurator config = new PropertyConfigurator(f); addPackages(config.getFilteredPackages()); } /** * Constructs a <code>PackageFilter</code> instance with the * specified collection of package names to filter. * * @param packageNames Package names to filter. */ public PackageFilter(Collection packageNames) { filtered = new ArrayList(); addPackages(packageNames); } /** * Returns the collection of filtered package names. * * @return Filtered package names. */ public Collection getFilters() { return filtered; } /** * Indicates whether the specified package name passes this package filter. * * @param packageName Package name. * @return <code>true</code> if the package name should be included; * <code>false</code> otherwise. */ public boolean accept(String packageName) { for (Iterator i = getFilters().iterator(); i.hasNext();) { String nameToFilter = (String)i.next(); if (packageName.startsWith(nameToFilter)) { return false; } } return true; } public void addPackages(Collection packageNames) { for (Iterator i = packageNames.iterator(); i.hasNext();) { addPackage((String)i.next()); } } public void addPackage(String packageName) { if (packageName.endsWith("*")) { packageName = packageName.substring(0, packageName.length() - 1); } if (packageName.length() > 0) { getFilters().add(packageName); } } }
2,774
27.030303
79
java
jdepend
jdepend-master/src/jdepend/framework/ParserListener.java
package jdepend.framework; /** * The <code>ParserListener</code> interface defines a listener * notified upon the completion of parsing events. * <p> * Implementers of this interface register for notification using * the <code>JDepend.addParseListener()</code> method. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public interface ParserListener { /** * Called whenever a Java class file is parsed into the specified * <code>JavaClass</code> instance. * * @param parsedClass Parsed Java class. */ public void onParsedJavaClass(JavaClass parsedClass); }
627
25.166667
69
java
jdepend
jdepend-master/src/jdepend/framework/PropertyConfigurator.java
package jdepend.framework; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Properties; import java.util.StringTokenizer; /** * The <code>PropertyConfigurator</code> class contains configuration * information contained in the <code>jdepend.properties</code> file, * if such a file exists either in the user's home directory or somewhere * in the classpath. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class PropertyConfigurator { private Properties properties; public static final String DEFAULT_PROPERTY_FILE = "jdepend.properties"; /** * Constructs a <code>PropertyConfigurator</code> instance * containing the properties specified in the file * <code>jdepend.properties</code>, if it exists. */ public PropertyConfigurator() { this(getDefaultPropertyFile()); } /** * Constructs a <code>PropertyConfigurator</code> instance * with the specified property set. * * @param p Property set. */ public PropertyConfigurator(Properties p) { this.properties = p; } /** * Constructs a <code>PropertyConfigurator</code> instance * with the specified property file. * * @param f Property file. */ public PropertyConfigurator(File f) { this(loadProperties(f)); } public Collection getFilteredPackages() { Collection packages = new ArrayList(); Enumeration e = properties.propertyNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); if (key.startsWith("ignore")) { String path = properties.getProperty(key); StringTokenizer st = new StringTokenizer(path, ","); while (st.hasMoreTokens()) { String name = (String) st.nextToken(); name = name.trim(); packages.add(name); } } } return packages; } public Collection getConfiguredPackages() { Collection packages = new ArrayList(); Enumeration e = properties.propertyNames(); while (e.hasMoreElements()) { String key = (String)e.nextElement(); if (!key.startsWith("ignore") && (!key.equals("analyzeInnerClasses"))) { String v = properties.getProperty(key); packages.add(new JavaPackage(key, new Integer(v).intValue())); } } return packages; } public boolean getAnalyzeInnerClasses() { String key = "analyzeInnerClasses"; if (properties.containsKey(key)) { String value = properties.getProperty(key); return new Boolean(value).booleanValue(); } return true; } public static File getDefaultPropertyFile() { String home = System.getProperty("user.home"); return new File(home, DEFAULT_PROPERTY_FILE); } public static Properties loadProperties(File file) { Properties p = new Properties(); InputStream is = null; try { is = new FileInputStream(file); } catch (Exception e) { is = PropertyConfigurator.class.getResourceAsStream("/" + DEFAULT_PROPERTY_FILE); } try { if (is != null) { p.load(is); } } catch (IOException ignore) { } finally { try { if (is != null) { is.close(); } } catch (IOException ignore) { } } return p; } }
3,851
25.937063
78
java
jdepend
jdepend-master/src/jdepend/swingui/AboutDialog.java
package jdepend.swingui; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * The <code>AboutDialog</code> displays the about information. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ class AboutDialog extends JDialog { /** * Constructs an <code>AboutDialog</code> with the specified parent frame. * * @param parent Parent frame. */ public AboutDialog(JFrame parent) { super(parent); setTitle("About"); setResizable(false); getContentPane().setLayout(new BorderLayout()); setSize(300, 200); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); } }); JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); JLabel titleLabel = new JLabel("JDepend"); titleLabel.setFont(new Font("dialog", Font.BOLD, 18)); JLabel nameLabel = new JLabel("Mike Clark"); nameLabel.setFont(new Font("dialog", Font.PLAIN, 12)); JLabel companyLabel = new JLabel("Clarkware Consulting, Inc."); companyLabel.setFont(new Font("dialog", Font.PLAIN, 12)); JLabel httpLabel = new JLabel("www.clarkware.com"); httpLabel.setFont(new Font("dialog", Font.PLAIN, 12)); JLabel blankLabel = new JLabel(" "); JButton closeButton = createButton("Close"); panel.add(titleLabel, createConstraints(1, 1)); panel.add(new JLabel(" "), createConstraints(1, 2)); panel.add(nameLabel, createConstraints(1, 3)); panel.add(companyLabel, createConstraints(1, 4)); panel.add(httpLabel, createConstraints(1, 5)); panel.add(new JLabel(" "), createConstraints(1, 6)); panel.add(new JLabel(" "), createConstraints(1, 7)); panel.add(closeButton, createConstraints(1, 9)); getContentPane().add("Center", panel); } /** * Creates and returns a button with the specified label. * * @param label Button label. * @return Button. */ private JButton createButton(String label) { JButton button = new JButton(label); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); return button; } /** * Creates and returns a grid bag constraint with the specified x and y * values. * * @param x X-coordinate. * @param y Y-coordinate. * @return GridBagConstraints */ private GridBagConstraints createConstraints(int x, int y) { GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = x; constraints.gridy = y; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.CENTER; constraints.weightx = 0.0; constraints.weighty = 0.0; return constraints; } }
3,055
25.119658
78
java
jdepend
jdepend-master/src/jdepend/swingui/AfferentNode.java
package jdepend.swingui; import java.util.*; import jdepend.framework.*; /** * The <code>AfferentNode</code> class is a <code>PackageNode</code> for an * afferent Java package and its afferent packages. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class AfferentNode extends PackageNode { /** * Constructs an <code>AfferentNode</code> with the specified parent node * and afferent Java package. * * @param parent Parent package node. * @param jPackage Afferent Java package. */ public AfferentNode(PackageNode parent, JavaPackage jPackage) { super(parent, jPackage); } /** * Creates and returns a <code>PackageNode</code> with the specified * parent node and Java package. * * @param parent Parent package node. * @param jPackage Java package. * @return A non-null <code>PackageNode</code. */ protected PackageNode makeNode(PackageNode parent, JavaPackage jPackage) { return new AfferentNode(parent, jPackage); } /** * Returns the collection of Java packages coupled to the package * represented in this node. * * @return Collection of coupled packages. */ protected Collection getCoupledPackages() { return getPackage().getAfferents(); } /** * Returns the string representation of this node in it's current tree * context. * * @return Node label. */ public String toString() { if (getParent() == null) { return "Used By - Afferent Dependencies" + " (" + getChildren().size() + " Packages)"; } return super.toString(); } }
1,719
25.060606
78
java
jdepend
jdepend-master/src/jdepend/swingui/DependTree.java
package jdepend.swingui; import java.awt.*; import javax.swing.*; import javax.swing.tree.*; import javax.swing.event.*; import jdepend.framework.JavaPackage; /** * The <code>DependTree</code> class defines the graphical tree for displaying * the packages and their hierarchical dependencies. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class DependTree extends JPanel implements TreeSelectionListener { private JTree tree; private DependTreeModel model; /** * Constructs a <code>DependTree</code> with an empty tree model. */ public DependTree() { this(new DependTreeModel(new AfferentNode(null, new JavaPackage("")))); } /** * Constructs a <code>DependTree</code> with the specified tree model. * * @param model Depend tree model. */ public DependTree(DependTreeModel model) { setBorder(BorderFactory.createTitledBorder(model.getRoot().toString())); setModel(model); setLayout(new BorderLayout()); JScrollPane pane = createScrollPane(); add(pane, "Center"); } /** * Sets the tree model. * * @param model Tree model. */ public void setModel(DependTreeModel model) { this.model = model; setBorder(BorderFactory.createTitledBorder(model.getRoot().toString())); getTree().setModel(this.model); } /** * Returns the tree model. * * @return Tree model. */ public DependTreeModel getModel() { return (DependTreeModel) getTree().getModel(); } /** * Registers the specified listener with this tree. * * @param l Tree selection listener. */ public void addTreeSelectionListener(TreeSelectionListener l) { getTree().addTreeSelectionListener(l); } /** * Callback method triggered whenever the value of the tree selection * changes. * * @param te Event that characterizes the change. */ public void valueChanged(TreeSelectionEvent te) { TreePath path = te.getNewLeadSelectionPath(); if (path != null) { Object o = path.getLastPathComponent(); } } /** * Creates and returns a scroll pane. * * @return Scroll pane. */ private JScrollPane createScrollPane() { JScrollPane pane = new JScrollPane(getTree()); return pane; } /** * Creates and returns a peered tree. * * @return Tree. */ private JTree createTree() { JTree tree = new JTree(); tree.setShowsRootHandles(false); tree.setFont(new Font("Dialog", Font.PLAIN, 12)); tree.addTreeSelectionListener(this); tree.setRootVisible(false); tree.setLargeModel(true); return tree; } /* * Returns the peered tree. @return A non-null tree. */ private JTree getTree() { if (tree == null) { tree = createTree(); } return tree; } }
3,044
21.894737
80
java
jdepend
jdepend-master/src/jdepend/swingui/DependTreeModel.java
package jdepend.swingui; import java.util.*; import javax.swing.tree.*; import javax.swing.event.*; /** * The <code>DependTreeModel</code> class defines the data model being * observed by a <code>DependTree</code> instance. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class DependTreeModel implements TreeModel { private PackageNode root; private Vector listeners; /** * Constructs a <code>DependTreeModel</code> with the specified root * package node. * * @param root Root package node. */ public DependTreeModel(PackageNode root) { this.root = root; listeners = new Vector(); } /** * Returns the root of the tree. * * @return The root of the tree, or <code>null</code> if the tree has no * nodes. */ public Object getRoot() { return root; } /** * Returns the child of the specified parent at the specified index in the * parent's child collection. * <p> * The specified parent must be a node previously obtained from this data * source. * * @param parent A node in the tree, obtained from this data source. * @param index Index of child in the parent's child collection. * @return Child. */ public Object getChild(Object parent, int index) { Object answer = null; ArrayList children; if (parent instanceof PackageNode) { children = ((PackageNode) parent).getChildren(); if (children != null) { if (index < children.size()) { answer = children.get(index); } } } return answer; } /** * Returns the number of children for the specified parent. * <p> * The specified parent must be a node previously obtained from this data * source. * * @param parent A node in the tree, obtained from this data source. * @return The number of children of the specified parent, or 0 if the * parent is a leaf node or if it has no children. */ public int getChildCount(Object parent) { int answer = 0; ArrayList children; if (parent instanceof PackageNode) { children = ((PackageNode) parent).getChildren(); if (children != null) { answer = children.size(); } } return answer; } /** * Determines whether the specified tree node is a leaf node. * * @param o A node in the tree, obtained from this data source. * @return <code>true</code> if the node is a leaf; <code>false</code> * otherwise. */ public boolean isLeaf(Object o) { boolean answer = true; if (o instanceof PackageNode) { PackageNode node = (PackageNode) o; return node.isLeaf(); } return answer; } /** * Callback method triggered when the value for the item specified by * <i>path </i> has changed to <i>newValue </i>. * * @param path Path to the node that has changed. * @param newValue The new value of the node. */ public void valueForPathChanged(TreePath path, Object newValue) { // do nothing } /** * Returns the index of the specified child within the specified parent. * * @param parent Parent node. * @param child Child node. * @return Index of child within parent. */ public int getIndexOfChild(Object parent, Object child) { int answer = -1; ArrayList children = null; if (parent instanceof PackageNode) { children = ((PackageNode) parent).getChildren(); if (children != null) { answer = children.indexOf(child); } } return answer; } /** * Adds a listener for the <code>TreeModelEvent</code> posted after the * tree changes. * * @param l The listener to add. */ public void addTreeModelListener(TreeModelListener l) { if ((l != null) && !listeners.contains(l)) { listeners.addElement(l); } } /** * Removes a listener for <code>TreeModelEvent</code>s. * * @param l The listener to remove. */ public void removeTreeModelListener(TreeModelListener l) { listeners.removeElement(l); } }
4,471
25
78
java
jdepend
jdepend-master/src/jdepend/swingui/EfferentNode.java
package jdepend.swingui; import java.util.*; import jdepend.framework.*; /** * The <code>EfferentNode</code> class is a <code>PackageNode</code> for an * efferent Java package and its efferent packages. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class EfferentNode extends PackageNode { /** * Constructs an <code>EfferentNode</code> with the specified parent node * and efferent Java package. * * @param parent Parent package node. * @param jPackage Efferent Java package. */ public EfferentNode(PackageNode parent, JavaPackage jPackage) { super(parent, jPackage); } /** * Creates and returns a <code>PackageNode</code> with the specified * parent node and Java package. * * @param parent Parent package node. * @param jPackage Java package. * @return A non-null <code>PackageNode</code. */ protected PackageNode makeNode(PackageNode parent, JavaPackage jPackage) { return new EfferentNode(parent, jPackage); } /** * Returns the collection of Java packages coupled to the package * represented in this node. * * @return Collection of coupled packages. */ protected Collection getCoupledPackages() { return getPackage().getEfferents(); } /** * Indicates whether the specified package should be displayed as a child of * this node. * <p> * Efferent packages without classes are never shown at the root level to * exclude non-analyzed packages. * * @param jPackage Package to test. * @return <code>true</code> to display the package; <code>false</code> * otherwise. */ public boolean isChild(JavaPackage jPackage) { if (getParent() != null) { return true; } else if (jPackage.getClassCount() > 0) { return true; } return false; } /** * Returns the string representation of this node in it's current tree * context. * * @return Node label. */ public String toString() { if (getParent() == null) { return "Depends Upon - Efferent Dependencies" + " (" + getChildren().size() + " Packages)"; } return super.toString(); } }
2,343
25.942529
80
java
jdepend
jdepend-master/src/jdepend/swingui/JDepend.java
package jdepend.swingui; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.tree.*; import jdepend.framework.JavaClass; import jdepend.framework.JavaPackage; import jdepend.framework.PackageComparator; import jdepend.framework.PackageFilter; import jdepend.framework.ParserListener; /** * The <code>JDepend</code> class analyzes directories of Java class files, * generates metrics for each Java package, and reports the metrics in a Swing * tree. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class JDepend implements ParserListener { private jdepend.framework.JDepend analyzer; private JFrame frame; private StatusPanel statusPanel; private JTextField statusField; private JProgressBar progressBar; private DependTree afferentTree; private DependTree efferentTree; private Hashtable resourceStrings; private Hashtable actions; private static Font BOLD_FONT = new Font("dialog", Font.BOLD, 12); /** * Constructs a <code>JDepend</code> instance. */ public JDepend() { analyzer = new jdepend.framework.JDepend(); analyzer.addParseListener(this); // // Force the cross platform L&F. // try { UIManager.setLookAndFeel(UIManager .getCrossPlatformLookAndFeelClassName()); //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } // // Install the resource string table. // resourceStrings = new Hashtable(); resourceStrings.put("menubar", "File"); resourceStrings.put("File", "About Exit"); // // Install the action table. // actions = new Hashtable(); actions.put("About", new AboutAction()); actions.put("Exit", new ExitAction()); } /** * Adds the specified directory name to the collection of directories to be * analyzed. * * @param name Directory name. * @throws IOException If the directory does not exist. */ public void addDirectory(String name) throws IOException { analyzer.addDirectory(name); } /** * Sets the package filter. * * @param filter Package filter. */ public void setFilter(PackageFilter filter) { analyzer.setFilter(filter); } /** * Sets the comma-separated list of components. */ public void setComponents(String components) { analyzer.setComponents(components); } /** * Analyzes the registered directories, generates metrics for each Java * package, and reports the metrics in a graphical format. */ public void analyze() { display(); startProgressMonitor(analyzer.countClasses()); ArrayList packages = new ArrayList(analyzer.analyze()); Collections.sort(packages, new PackageComparator(PackageComparator .byName())); stopProgressMonitor(); updateTree(packages); } /** * Called whenever a Java source file is parsed into the specified * <code>JavaClass</code> instance. * * @param jClass Parsed Java class. */ public void onParsedJavaClass(final JavaClass jClass) { SwingUtilities.invokeLater(new Runnable() { public void run() { getProgressBar().setValue(getProgressBar().getValue() + 1); } }); } private void display() { frame = createUI(); frame.setVisible(true); } private void updateTree(ArrayList packages) { JavaPackage jPackage = new JavaPackage("root"); jPackage.setAfferents(packages); jPackage.setEfferents(packages); AfferentNode ah = new AfferentNode(null, jPackage); getAfferentTree().setModel(new DependTreeModel(ah)); EfferentNode eh = new EfferentNode(null, jPackage); getEfferentTree().setModel(new DependTreeModel(eh)); } private void startProgressMonitor(final int maxValue) { SwingUtilities.invokeLater(new Runnable() { public void run() { getProgressBar().setMinimum(0); getProgressBar().setMaximum(maxValue); getStatusPanel().setStatusComponent(getProgressBar()); } }); } private void stopProgressMonitor() { SwingUtilities.invokeLater(new Runnable() { public void run() { getStatusPanel().setStatusComponent(getStatusField()); int classCount = analyzer.countClasses(); int packageCount = analyzer.countPackages(); showStatusMessage("Analyzed " + packageCount + " packages (" + classCount + " classes)."); } }); } private JFrame createUI() { JFrame frame = createFrame("JDepend"); JMenuBar menuBar = createMenubar(); frame.setJMenuBar(menuBar); JPanel treePanel = createTreePanel(); StatusPanel statusPanel = getStatusPanel(); frame.getContentPane().add("Center", treePanel); frame.getContentPane().add("South", statusPanel); frame.pack(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int width = 700; int height = 500; int x = (screenSize.width - width) / 2; int y = (screenSize.height - height) / 2; frame.setBounds(x, y, width, height); frame.setSize(width, height); return frame; } private JFrame createFrame(String title) { JFrame frame = new JFrame(title); frame.getContentPane().setLayout(new BorderLayout()); frame.setBackground(SystemColor.control); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { new ExitAction().actionPerformed(null); } }); return frame; } private JPanel createTreePanel() { JPanel panel = new JPanel(); panel.setLayout(new GridLayout(2, 1)); panel.add(getEfferentTree()); panel.add(getAfferentTree()); /* * panel.setLayout(new GridLayout(1,1)); JSplitPane splitPane = new * JSplitPane(JSplitPane.VERTICAL_SPLIT); * splitPane.setOneTouchExpandable(true); * splitPane.setTopComponent(getEfferentTree()); * splitPane.setBottomComponent(getAfferentTree()); * panel.add(splitPane); */ return panel; } private StatusPanel createStatusPanel() { StatusPanel panel = new StatusPanel(); panel.setStatusComponent(getStatusField()); return panel; } private JProgressBar createProgressBar() { JProgressBar bar = new JProgressBar(); bar.setStringPainted(true); return bar; } private JTextField createStatusField() { JTextField statusField = new JTextField(); statusField.setFont(BOLD_FONT); statusField.setEditable(false); statusField.setForeground(Color.black); statusField.setBorder(BorderFactory .createBevelBorder(BevelBorder.LOWERED)); Insets insets = new Insets(5, 5, 5, 5); statusField.setMargin(insets); return statusField; } private JMenuBar createMenubar() { JMenuBar menuBar = new JMenuBar(); String[] menuKeys = tokenize((String) resourceStrings.get("menubar")); for (int i = 0; i < menuKeys.length; i++) { JMenu m = createMenu(menuKeys[i]); if (m != null) { menuBar.add(m); } } return menuBar; } private JMenu createMenu(String key) { String[] itemKeys = tokenize((String) resourceStrings.get(key)); JMenu menu = new JMenu(key); for (int i = 0; i < itemKeys.length; i++) { if (itemKeys[i].equals("-")) { menu.addSeparator(); } else { JMenuItem mi = createMenuItem(itemKeys[i]); menu.add(mi); } } char mnemonic = key.charAt(0); menu.setMnemonic(mnemonic); return menu; } private JMenuItem createMenuItem(String key) { JMenuItem mi = new JMenuItem(key); char mnemonic = key.charAt(0); mi.setMnemonic(mnemonic); char accelerator = key.charAt(0); mi.setAccelerator(KeyStroke.getKeyStroke(accelerator, java.awt.Event.CTRL_MASK)); String actionString = key; mi.setActionCommand(actionString); Action a = getActionForCommand(actionString); if (a != null) { mi.addActionListener(a); mi.setEnabled(a.isEnabled()); } else { mi.setEnabled(false); } return mi; } private void showStatusMessage(final String message) { getStatusField().setFont(BOLD_FONT); getStatusField().setForeground(Color.black); getStatusField().setText(" " + message); } private void showStatusError(final String message) { getStatusField().setFont(BOLD_FONT); getStatusField().setForeground(Color.red); getStatusField().setText(" " + message); } private DependTree getAfferentTree() { if (afferentTree == null) { afferentTree = new DependTree(); afferentTree.addTreeSelectionListener(new TreeListener()); } return afferentTree; } private DependTree getEfferentTree() { if (efferentTree == null) { efferentTree = new DependTree(); efferentTree.addTreeSelectionListener(new TreeListener()); } return efferentTree; } private StatusPanel getStatusPanel() { if (statusPanel == null) { statusPanel = createStatusPanel(); } return statusPanel; } private JProgressBar getProgressBar() { if (progressBar == null) { progressBar = createProgressBar(); } return progressBar; } private JTextField getStatusField() { if (statusField == null) { statusField = createStatusField(); } return statusField; } private Action getActionForCommand(String command) { return (Action) actions.get(command); } /* * Parses the specified string into an array of strings on whitespace * boundaries. @param input String to tokenize. @return Strings. */ private String[] tokenize(String input) { Vector v = new Vector(); StringTokenizer t = new StringTokenizer(input); while (t.hasMoreTokens()) { v.addElement(t.nextToken()); } String cmd[] = new String[v.size()]; for (int i = 0; i < cmd.length; i++) { cmd[i] = (String) v.elementAt(i); } return cmd; } private void postStatusMessage(final String message) { SwingUtilities.invokeLater(new Runnable() { public void run() { showStatusMessage(message); } }); } private void postStatusError(final String message) { SwingUtilities.invokeLater(new Runnable() { public void run() { showStatusError(message); } }); } // // Tree selection handler. // private class TreeListener implements TreeSelectionListener { /** * Constructs a <code>TreeListener</code> instance. */ TreeListener() { } /** * Callback method triggered whenever the value of the tree selection * changes. * * @param te Event that characterizes the change. */ public void valueChanged(TreeSelectionEvent te) { TreePath path = te.getNewLeadSelectionPath(); if (path != null) { PackageNode node = (PackageNode) path.getLastPathComponent(); showStatusMessage(node.toMetricsString()); } } } // // About action handler. // private class AboutAction extends AbstractAction { /** * Constructs an <code>AboutAction</code> instance. */ AboutAction() { super("About"); } /** * Handles the action. */ public void actionPerformed(ActionEvent e) { AboutDialog d = new AboutDialog(frame); d.setModal(true); d.setLocation(300, 300); d.show(); } } // // Exit action handler. // private class ExitAction extends AbstractAction { /** * Constructs an <code>ExitAction</code> instance. */ ExitAction() { super("Exit"); } /** * Handles the action. */ public void actionPerformed(ActionEvent e) { frame.dispose(); System.exit(0); } } private void usage(String message) { if (message != null) { System.err.println("\n" + message); } String baseUsage = "\nJDepend "; System.err.println(""); System.err.println("usage: "); System.err.println(baseUsage + "-components <components> " + "<directory> [directory2 [directory 3] ...]"); System.exit(1); } private void instanceMain(String[] args) { if (args.length < 1) { usage("Must specify at least one directory."); } int directoryCount = 0; for (int i = 0; i < args.length; i++) { if (args[i].startsWith("-")) { if (args[i].equalsIgnoreCase("-components")) { if (args.length <= i + 1) { usage("Components not specified."); } setComponents(args[++i]); } else { usage("Invalid argument: " + args[i]); } } else { try { addDirectory(args[i]); directoryCount++; } catch (IOException ioe) { usage("Directory does not exist: " + args[i]); } } } if (directoryCount == 0) { usage("Must specify at least one directory."); } analyze(); } public static void main(String[] args) { new JDepend().instanceMain(args); } }
14,845
25.605735
82
java
jdepend
jdepend-master/src/jdepend/swingui/PackageNode.java
package jdepend.swingui; import java.text.NumberFormat; import java.util.*; import jdepend.framework.*; /** * The <code>PackageNode</code> class defines the default behavior for tree * nodes representing Java packages. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public abstract class PackageNode { private PackageNode parent; private JavaPackage jPackage; private ArrayList children; private static NumberFormat formatter; static { formatter = NumberFormat.getInstance(); formatter.setMaximumFractionDigits(2); } /** * Constructs a <code>PackageNode</code> with the specified package and * its collection of dependent packages. * * @param parent Parent package node. * @param jPackage Java package. */ public PackageNode(PackageNode parent, JavaPackage jPackage) { this.parent = parent; this.jPackage = jPackage; children = null; } /** * Returns the Java package represented in this node. * * @return Java package. */ public JavaPackage getPackage() { return jPackage; } /** * Returns the parent of this package node. * * @return Parent package node. */ public PackageNode getParent() { return parent; } /** * Indicates whether this node is a leaf node. * * @return <code>true</code> if this node is a leaf; <code>false</code> * otherwise. */ public boolean isLeaf() { if (getCoupledPackages().size() > 0) { return false; } return true; } /** * Creates and returns a <code>PackageNode</code> with the specified * parent node and Java package. * * @param parent Parent package node. * @param jPackage Java package. * @return A non-null <code>PackageNode</code. */ protected abstract PackageNode makeNode(PackageNode parent, JavaPackage jPackage); /** * Returns the collection of Java packages coupled to the package * represented in this node. * * @return Collection of coupled packages. */ protected abstract Collection getCoupledPackages(); /** * Indicates whether the specified package should be displayed as a child of * this node. * * @param jPackage Package to test. * @return <code>true</code> to display the package; <code>false</code> * otherwise. */ public boolean isChild(JavaPackage jPackage) { return true; } /** * Returns the child package nodes of this node. * * @return Collection of child package nodes. */ public ArrayList getChildren() { if (children == null) { children = new ArrayList(); ArrayList packages = new ArrayList(getCoupledPackages()); Collections.sort(packages, new PackageComparator(PackageComparator .byName())); Iterator i = packages.iterator(); while (i.hasNext()) { JavaPackage jPackage = (JavaPackage) i.next(); if (isChild(jPackage)) { PackageNode childNode = makeNode(this, jPackage); children.add(childNode); } } } return children; } /** * Returns the string representation of this node's metrics. * * @return Metrics string. */ public String toMetricsString() { StringBuffer label = new StringBuffer(); label.append(getPackage().getName()); label.append(" ("); label.append("CC: " + getPackage().getConcreteClassCount() + " "); label.append("AC: " + getPackage().getAbstractClassCount() + " "); label.append("Ca: " + getPackage().afferentCoupling() + " "); label.append("Ce: " + getPackage().efferentCoupling() + " "); label.append("A: " + format(getPackage().abstractness()) + " "); label.append("I: " + format(getPackage().instability()) + " "); label.append("D: " + format(getPackage().distance()) + " "); label.append("V: " + getPackage().getVolatility()); if (getPackage().containsCycle()) { label.append(" Cyclic"); } label.append(")"); return label.toString(); } /** * Returns the string representation of this node in it's current tree * context. * * @return Node label. */ public String toString() { if (getParent().getParent() == null) { return toMetricsString(); } return getPackage().getName(); } /* * Returns the specified number in a displayable format. @param number * Number to format. @return Formatted number. */ private static String format(float f) { return formatter.format(f); } }
4,950
26.203297
80
java
jdepend
jdepend-master/src/jdepend/swingui/StatusPanel.java
package jdepend.swingui; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.BoxLayout; /** * The <code>StatusPanel</code> class defines the status-related UI * components. * <p> * This panel primarily contains either a text field or a progress bar. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class StatusPanel extends JPanel { /** * Constructs a <code>StatusPanel</code>. */ public StatusPanel() { super(); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); } /** * Sets the specified component as the current status component of this * panel. * * @param component Status component. */ public void setStatusComponent(JComponent component) { removeAll(); add(component); repaint(); validate(); } }
877
21.512821
75
java
jdepend
jdepend-master/src/jdepend/textui/JDepend.java
package jdepend.textui; import java.io.*; import java.util.*; import java.text.NumberFormat; import jdepend.framework.JavaClass; import jdepend.framework.JavaPackage; import jdepend.framework.PackageComparator; import jdepend.framework.PackageFilter; /** * The <code>JDepend</code> class analyzes directories of Java class files, * generates metrics for each Java package, and reports the metrics in a textual * format. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class JDepend { private jdepend.framework.JDepend analyzer; private PrintWriter writer; protected NumberFormat formatter; /** * Constructs a <code>JDepend</code> instance using standard output. */ public JDepend() { this(new PrintWriter(System.out)); } /** * Constructs a <code>JDepend</code> instance with the specified writer. * * @param writer Writer. */ public JDepend(PrintWriter writer) { analyzer = new jdepend.framework.JDepend(); formatter = NumberFormat.getInstance(); formatter.setMaximumFractionDigits(2); setWriter(writer); } /** * Sets the output writer. * * @param writer Output writer. */ public void setWriter(PrintWriter writer) { this.writer = writer; } protected PrintWriter getWriter() { return writer; } /** * Sets the package filter. * * @param filter Package filter. */ public void setFilter(PackageFilter filter) { analyzer.setFilter(filter); } /** * Sets the comma-separated list of components. */ public void setComponents(String components) { analyzer.setComponents(components); } /** * Adds the specified directory name to the collection of directories to be * analyzed. * * @param name Directory name. * @throws IOException If the directory does not exist. */ public void addDirectory(String name) throws IOException { analyzer.addDirectory(name); } /** * Determines whether inner classes are analyzed. * * @param b <code>true</code> to analyze inner classes; <code>false</code> * otherwise. */ public void analyzeInnerClasses(boolean b) { analyzer.analyzeInnerClasses(b); } /** * Analyzes the registered directories, generates metrics for each Java * package, and reports the metrics. */ public void analyze() { printHeader(); Collection packages = analyzer.analyze(); ArrayList packageList = new ArrayList(packages); Collections.sort(packageList, new PackageComparator(PackageComparator .byName())); printPackages(packageList); printCycles(packageList); printSummary(packageList); printFooter(); getWriter().flush(); } protected void printPackages(Collection packages) { printPackagesHeader(); Iterator i = packages.iterator(); while (i.hasNext()) { printPackage((JavaPackage) i.next()); } printPackagesFooter(); } protected void printPackage(JavaPackage jPackage) { printPackageHeader(jPackage); if (jPackage.getClasses().size() == 0) { printNoStats(); printPackageFooter(jPackage); return; } printStatistics(jPackage); printSectionBreak(); printAbstractClasses(jPackage); printSectionBreak(); printConcreteClasses(jPackage); printSectionBreak(); printEfferents(jPackage); printSectionBreak(); printAfferents(jPackage); printPackageFooter(jPackage); } protected void printAbstractClasses(JavaPackage jPackage) { printAbstractClassesHeader(); ArrayList members = new ArrayList(jPackage.getClasses()); Collections.sort(members, new JavaClass.ClassComparator()); Iterator memberIter = members.iterator(); while (memberIter.hasNext()) { JavaClass jClass = (JavaClass) memberIter.next(); if (jClass.isAbstract()) { printClassName(jClass); } } printAbstractClassesFooter(); } protected void printConcreteClasses(JavaPackage jPackage) { printConcreteClassesHeader(); ArrayList members = new ArrayList(jPackage.getClasses()); Collections.sort(members, new JavaClass.ClassComparator()); Iterator memberIter = members.iterator(); while (memberIter.hasNext()) { JavaClass concrete = (JavaClass) memberIter.next(); if (!concrete.isAbstract()) { printClassName(concrete); } } printConcreteClassesFooter(); } protected void printEfferents(JavaPackage jPackage) { printEfferentsHeader(); ArrayList efferents = new ArrayList(jPackage.getEfferents()); Collections.sort(efferents, new PackageComparator(PackageComparator .byName())); Iterator efferentIter = efferents.iterator(); while (efferentIter.hasNext()) { JavaPackage efferent = (JavaPackage) efferentIter.next(); printPackageName(efferent); } if (efferents.size() == 0) { printEfferentsError(); } printEfferentsFooter(); } protected void printAfferents(JavaPackage jPackage) { printAfferentsHeader(); ArrayList afferents = new ArrayList(jPackage.getAfferents()); Collections.sort(afferents, new PackageComparator(PackageComparator .byName())); Iterator afferentIter = afferents.iterator(); while (afferentIter.hasNext()) { JavaPackage afferent = (JavaPackage) afferentIter.next(); printPackageName(afferent); } if (afferents.size() == 0) { printAfferentsError(); } printAfferentsFooter(); } protected void printCycles(Collection packages) { printCyclesHeader(); Iterator i = packages.iterator(); while (i.hasNext()) { printCycle((JavaPackage) i.next()); } printCyclesFooter(); } protected void printCycle(JavaPackage jPackage) { List list = new ArrayList(); jPackage.collectCycle(list); if (!jPackage.containsCycle()) { return; } JavaPackage cyclePackage = (JavaPackage) list.get(list.size() - 1); String cyclePackageName = cyclePackage.getName(); int i = 0; Iterator pkgIter = list.iterator(); while (pkgIter.hasNext()) { i++; JavaPackage pkg = (JavaPackage) pkgIter.next(); if (i == 1) { printCycleHeader(pkg); } else { if (pkg.getName().equals(cyclePackageName)) { printCycleTarget(pkg); } else { printCycleContributor(pkg); } } } printCycleFooter(); } protected void printHeader() { // do nothing } protected void printFooter() { // do nothing } protected void printPackagesHeader() { // do nothing } protected void printPackagesFooter() { // do nothing } protected void printNoStats() { getWriter().println( "No stats available: package referenced, but not analyzed."); } protected void printPackageHeader(JavaPackage jPackage) { getWriter().println( "\n--------------------------------------------------"); getWriter().println("- Package: " + jPackage.getName()); getWriter().println( "--------------------------------------------------"); } protected void printPackageFooter(JavaPackage jPackage) { // do nothing } protected void printStatistics(JavaPackage jPackage) { getWriter().println("\nStats:"); getWriter().println( tab() + "Total Classes: " + jPackage.getClassCount()); getWriter() .println( tab() + "Concrete Classes: " + jPackage.getConcreteClassCount()); getWriter() .println( tab() + "Abstract Classes: " + jPackage.getAbstractClassCount()); getWriter().println(""); getWriter().println(tab() + "Ca: " + jPackage.afferentCoupling()); getWriter().println(tab() + "Ce: " + jPackage.efferentCoupling()); getWriter().println(""); getWriter().println( tab() + "A: " + toFormattedString(jPackage.abstractness())); getWriter().println( tab() + "I: " + toFormattedString(jPackage.instability())); getWriter().println( tab() + "D: " + toFormattedString(jPackage.distance())); } protected void printClassName(JavaClass jClass) { getWriter().println(tab() + jClass.getName()); } protected void printPackageName(JavaPackage jPackage) { getWriter().println(tab() + jPackage.getName()); } protected void printAbstractClassesHeader() { getWriter().println("Abstract Classes:"); } protected void printAbstractClassesFooter() { // do nothing } protected void printConcreteClassesHeader() { getWriter().println("Concrete Classes:"); } protected void printConcreteClassesFooter() { // do nothing } protected void printEfferentsHeader() { getWriter().println("Depends Upon:"); } protected void printEfferentsFooter() { // do nothing } protected void printEfferentsError() { getWriter().println(tab() + "Not dependent on any packages."); } protected void printAfferentsHeader() { getWriter().println("Used By:"); } protected void printAfferentsFooter() { // do nothing } protected void printAfferentsError() { getWriter().println(tab() + "Not used by any packages."); } protected void printCyclesHeader() { printSectionBreak(); getWriter().println( "\n--------------------------------------------------"); getWriter().println("- Package Dependency Cycles:"); getWriter().println( "--------------------------------------------------\n"); } protected void printCyclesFooter() { // do nothing } protected void printCycleHeader(JavaPackage jPackage) { getWriter().println(jPackage.getName()); getWriter().println(tab() + "|"); } protected void printCycleTarget(JavaPackage jPackage) { getWriter().println(tab() + "|-> " + jPackage.getName()); } protected void printCycleContributor(JavaPackage jPackage) { getWriter().println(tab() + "| " + jPackage.getName()); } protected void printCycleFooter() { printSectionBreak(); } protected void printSummary(Collection packages) { getWriter().println( "\n--------------------------------------------------"); getWriter().println("- Summary:"); getWriter().println( "--------------------------------------------------\n"); getWriter() .println( "Name, Class Count, Abstract Class Count, Ca, Ce, A, I, D, V:\n"); Iterator i = packages.iterator(); while (i.hasNext()) { JavaPackage jPackage = (JavaPackage) i.next(); getWriter().print(jPackage.getName() + ","); getWriter().print(jPackage.getClassCount() + ","); getWriter().print(jPackage.getAbstractClassCount() + ","); getWriter().print(jPackage.afferentCoupling() + ","); getWriter().print(jPackage.efferentCoupling() + ","); getWriter().print(toFormattedString(jPackage.abstractness()) + ","); getWriter().print(toFormattedString(jPackage.instability()) + ","); getWriter().print(toFormattedString(jPackage.distance()) + ","); getWriter().println(jPackage.getVolatility()); } } protected void printSectionBreak() { getWriter().println(""); } protected String toFormattedString(float f) { return formatter.format(f); } protected String tab() { return " "; } protected String tab(int n) { StringBuffer s = new StringBuffer(); for (int i = 0; i < n; i++) { s.append(tab()); } return s.toString(); } protected void usage(String message) { if (message != null) { System.err.println("\n" + message); } String baseUsage = "\nJDepend "; System.err.println(""); System.err.println("usage: "); System.err.println(baseUsage + "[-components <components>]" + " [-file <output file>] <directory> " + "[directory2 [directory 3] ...]"); System.exit(1); } protected void instanceMain(String[] args) { if (args.length < 1) { usage("Must specify at least one directory."); } int directoryCount = 0; for (int i = 0; i < args.length; i++) { if (args[i].startsWith("-")) { if (args[i].equalsIgnoreCase("-file")) { if (args.length <= i + 1) { usage("Output file name not specified."); } try { setWriter(new PrintWriter(new OutputStreamWriter( new FileOutputStream(args[++i]), "UTF8"))); } catch (IOException ioe) { usage(ioe.getMessage()); } } else if (args[i].equalsIgnoreCase("-components")) { if (args.length <= i + 1) { usage("Components not specified."); } setComponents(args[++i]); } else { usage("Invalid argument: " + args[i]); } } else { try { addDirectory(args[i]); directoryCount++; } catch (IOException ioe) { usage("Directory does not exist: " + args[i]); } } } if (directoryCount == 0) { usage("Must specify at least one directory."); } analyze(); } public static void main(String args[]) { new JDepend().instanceMain(args); } }
14,940
27.297348
90
java
jdepend
jdepend-master/src/jdepend/xmlui/JDepend.java
package jdepend.xmlui; import java.io.*; import java.util.*; import java.text.NumberFormat; import jdepend.framework.JavaClass; import jdepend.framework.JavaPackage; /** * The <code>JDepend</code> class analyzes directories of Java class files, * generates metrics for each Java package, and reports the metrics in an XML * format. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class JDepend extends jdepend.textui.JDepend { /** * Constructs a <code>JDepend</code> instance using standard output. */ public JDepend() { this(new PrintWriter(System.out)); } /** * Constructs a <code>JDepend</code> instance with the specified writer. * * @param writer Writer. */ public JDepend(PrintWriter writer) { super(writer); formatter = NumberFormat.getInstance(Locale.ENGLISH); formatter.setMaximumFractionDigits(2); } protected void printHeader() { getWriter().println("<?xml version=\"1.0\"?>"); getWriter().println("<JDepend>"); } protected void printFooter() { getWriter().println("</JDepend>"); } protected void printPackagesHeader() { getWriter().println(tab() + "<Packages>"); } protected void printPackagesFooter() { getWriter().println(tab() + "</Packages>"); } protected void printPackageHeader(JavaPackage jPackage) { printSectionBreak(); getWriter().println( tab(2) + "<Package name=\"" + jPackage.getName() + "\">"); } protected void printPackageFooter(JavaPackage jPackage) { getWriter().println(tab(2) + "</Package>"); } protected void printNoStats() { getWriter().println( tab(3) + "<error>No stats available: " + "package referenced, but not analyzed.</error>"); } protected void printStatistics(JavaPackage jPackage) { getWriter().println(tab(3) + "<Stats>"); getWriter().println( tab(4) + "<TotalClasses>" + jPackage.getClassCount() + "</TotalClasses>"); getWriter().println( tab(4) + "<ConcreteClasses>" + jPackage.getConcreteClassCount() + "</ConcreteClasses>"); getWriter().println( tab(4) + "<AbstractClasses>" + jPackage.getAbstractClassCount() + "</AbstractClasses>"); getWriter().println( tab(4) + "<Ca>" + jPackage.afferentCoupling() + "</Ca>"); getWriter().println( tab(4) + "<Ce>" + jPackage.efferentCoupling() + "</Ce>"); getWriter().println( tab(4) + "<A>" + toFormattedString(jPackage.abstractness()) + "</A>"); getWriter().println( tab(4) + "<I>" + toFormattedString(jPackage.instability()) + "</I>"); getWriter().println( tab(4) + "<D>" + toFormattedString(jPackage.distance()) + "</D>"); getWriter().println(tab(4) + "<V>" + jPackage.getVolatility() + "</V>"); getWriter().println(tab(3) + "</Stats>"); } protected void printClassName(JavaClass jClass) { getWriter().println( tab(4) + "<Class sourceFile=\"" + jClass.getSourceFile() + "\">"); getWriter().println(tab(5) + jClass.getName()); getWriter().println(tab(4) + "</Class>"); } protected void printPackageName(JavaPackage jPackage) { getWriter().println( tab(4) + "<Package>" + jPackage.getName() + "</Package>"); } protected void printAbstractClassesHeader() { getWriter().println(tab(3) + "<AbstractClasses>"); } protected void printAbstractClassesFooter() { getWriter().println(tab(3) + "</AbstractClasses>"); } protected void printConcreteClassesHeader() { getWriter().println(tab(3) + "<ConcreteClasses>"); } protected void printConcreteClassesFooter() { getWriter().println(tab(3) + "</ConcreteClasses>"); } protected void printEfferentsHeader() { getWriter().println(tab(3) + "<DependsUpon>"); } protected void printEfferentsFooter() { getWriter().println(tab(3) + "</DependsUpon>"); } protected void printEfferentsError() { // do nothing } protected void printAfferentsHeader() { getWriter().println(tab(3) + "<UsedBy>"); } protected void printAfferentsFooter() { getWriter().println(tab(3) + "</UsedBy>"); } protected void printAfferentsError() { // do nothing } protected void printCyclesHeader() { printSectionBreak(); getWriter().println(tab() + "<Cycles>"); } protected void printCyclesFooter() { getWriter().println(tab() + "</Cycles>"); } protected void printCycleHeader(JavaPackage jPackage) { getWriter().println( tab(2) + "<Package Name=\"" + jPackage.getName() + "\">"); } protected void printCycleFooter() { getWriter().println(tab(2) + "</Package>"); printSectionBreak(); } protected void printCycleTarget(JavaPackage jPackage) { printCycleContributor(jPackage); } protected void printCycleContributor(JavaPackage jPackage) { getWriter().println( tab(3) + "<Package>" + jPackage.getName() + "</Package>"); } protected void printSummary(Collection packages) { // do nothing } /** * Main. */ public static void main(String args[]) { new JDepend().instanceMain(args); } }
5,738
28.735751
80
java
jdepend
jdepend-master/test/jdepend/framework/AllTests.java
package jdepend.framework; import junit.framework.Test; import junit.framework.TestSuite; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class AllTests { public static Test suite() { TestSuite suite = new TestSuite("JDepend Tests"); suite.addTestSuite(ClassFileParserTest.class); suite.addTestSuite(ComponentTest.class); suite.addTestSuite(JarFileParserTest.class); suite.addTestSuite(ConstraintTest.class); suite.addTestSuite(CycleTest.class); suite.addTestSuite(CollectAllCyclesTest.class); suite.addTestSuite(FileManagerTest.class); suite.addTestSuite(FilterTest.class); suite.addTestSuite(MetricTest.class); suite.addTestSuite(PropertyConfiguratorTest.class); suite.addTestSuite(ExampleTest.class); return suite; } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }
972
26.8
59
java
jdepend
jdepend-master/test/jdepend/framework/ClassFileParserTest.java
package jdepend.framework; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class ClassFileParserTest extends JDependTestCase { private ClassFileParser parser; public ClassFileParserTest(String name) { super(name); } protected void setUp() { super.setUp(); PackageFilter filter = new PackageFilter(new ArrayList()); parser = new ClassFileParser(filter); } protected void tearDown() { super.tearDown(); } public void testInvalidClassFile() { File f = new File(getTestDir() + getPackageSubDir() + "ExampleTest.java"); try { parser.parse(f); fail("Invalid class file: Should raise IOException"); } catch (IOException expected) { assertTrue(true); } } public void testInterfaceClass() throws IOException { File f = new File(getBuildDir() + getPackageSubDir() + "ExampleInterface.class"); JavaClass clazz = parser.parse(f); assertTrue(clazz.isAbstract()); assertEquals("jdepend.framework.ExampleInterface", clazz.getName()); assertEquals("ExampleInterface.java", clazz.getSourceFile()); Collection imports = clazz.getImportedPackages(); assertEquals(6, imports.size()); assertTrue(imports.contains(new JavaPackage("java.math"))); assertTrue(imports.contains(new JavaPackage("java.text"))); assertTrue(imports.contains(new JavaPackage("java.lang"))); assertTrue(imports.contains(new JavaPackage("java.io"))); assertTrue(imports.contains(new JavaPackage("java.rmi"))); assertTrue(imports.contains(new JavaPackage("java.util"))); } public void testAbstractClass() throws IOException { File f = new File(getBuildDir() + getPackageSubDir() + "ExampleAbstractClass.class"); JavaClass clazz = parser.parse(f); assertTrue(clazz.isAbstract()); assertEquals("jdepend.framework.ExampleAbstractClass", clazz.getName()); assertEquals("ExampleAbstractClass.java", clazz.getSourceFile()); Collection imports = clazz.getImportedPackages(); assertEquals(7, imports.size()); assertTrue(imports.contains(new JavaPackage("java.math"))); assertTrue(imports.contains(new JavaPackage("java.text"))); assertTrue(imports.contains(new JavaPackage("java.lang"))); assertTrue(imports.contains(new JavaPackage("java.lang.reflect"))); assertTrue(imports.contains(new JavaPackage("java.io"))); assertTrue(imports.contains(new JavaPackage("java.rmi"))); assertTrue(imports.contains(new JavaPackage("java.util"))); } public void testConcreteClass() throws IOException { File f = new File(getBuildDir() + getPackageSubDir() + "ExampleConcreteClass.class"); JavaClass clazz = parser.parse(f); assertFalse(clazz.isAbstract()); assertEquals("jdepend.framework.ExampleConcreteClass", clazz.getName()); assertEquals("ExampleConcreteClass.java", clazz.getSourceFile()); Collection imports = clazz.getImportedPackages(); assertEquals(19, imports.size()); assertTrue(imports.contains(new JavaPackage("java.net"))); assertTrue(imports.contains(new JavaPackage("java.text"))); assertTrue(imports.contains(new JavaPackage("java.sql"))); assertTrue(imports.contains(new JavaPackage("java.lang"))); assertTrue(imports.contains(new JavaPackage("java.io"))); assertTrue(imports.contains(new JavaPackage("java.rmi"))); assertTrue(imports.contains(new JavaPackage("java.util"))); assertTrue(imports.contains(new JavaPackage("java.util.jar"))); assertTrue(imports.contains(new JavaPackage("java.math"))); // annotations assertTrue(imports.contains(new JavaPackage("org.junit.runners"))); assertTrue(imports.contains(new JavaPackage("java.applet"))); assertTrue(imports.contains(new JavaPackage("org.junit"))); assertTrue(imports.contains(new JavaPackage("javax.crypto"))); assertTrue(imports.contains(new JavaPackage("java.awt.geom"))); assertTrue(imports.contains(new JavaPackage("java.awt.image.renderable"))); assertTrue(imports.contains(new JavaPackage("jdepend.framework.p1"))); assertTrue(imports.contains(new JavaPackage("jdepend.framework.p2"))); assertTrue(imports.contains(new JavaPackage("java.awt.im"))); assertTrue(imports.contains(new JavaPackage("java.awt.dnd.peer"))); } public void testInnerClass() throws IOException { File f = new File(getBuildDir() + getPackageSubDir() + "ExampleConcreteClass$ExampleInnerClass.class"); JavaClass clazz = parser.parse(f); assertFalse(clazz.isAbstract()); assertEquals("jdepend.framework.ExampleConcreteClass$ExampleInnerClass", clazz.getName()); assertEquals("ExampleConcreteClass.java", clazz.getSourceFile()); Collection imports = clazz.getImportedPackages(); assertEquals(1, imports.size()); assertTrue(imports.contains(new JavaPackage("java.lang"))); } public void testPackageClass() throws IOException { File f = new File(getBuildDir() + getPackageSubDir() + "ExamplePackageClass.class"); JavaClass clazz = parser.parse(f); assertFalse(clazz.isAbstract()); assertEquals("jdepend.framework.ExamplePackageClass", clazz.getName()); assertEquals("ExampleConcreteClass.java", clazz.getSourceFile()); Collection imports = clazz.getImportedPackages(); assertEquals(1, imports.size()); assertTrue(imports.contains(new JavaPackage("java.lang"))); } public void testExampleClassFileFromTimDrury() throws IOException { // see http://github.com/clarkware/jdepend/issues#issue/1 parser.parse(ClassFileParser.class.getResourceAsStream("/data/example_class1.bin")); } public void testExampleClassFile2() throws IOException { parser.parse(ClassFileParser.class.getResourceAsStream("/data/example_class2.bin")); } }
6,505
34.167568
92
java
jdepend
jdepend-master/test/jdepend/framework/CollectAllCyclesTest.java
package jdepend.framework; import java.util.ArrayList; import java.util.List; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class CollectAllCyclesTest extends JDependTestCase { public CollectAllCyclesTest(String name) { super(name); } public void testNoCycles() { JavaPackage a = new JavaPackage("A"); JavaPackage b = new JavaPackage("B"); a.dependsUpon(b); List aCycles = new ArrayList(); assertEquals(false, a.containsCycle()); assertEquals(false, a.collectAllCycles(aCycles)); assertListEquals(aCycles, new String[] {}); List bCycles = new ArrayList(); assertEquals(false, b.containsCycle()); assertEquals(false, b.collectAllCycles(bCycles)); assertListEquals(bCycles, new String[] {}); } public void test2Node1BranchCycle() { JavaPackage a = new JavaPackage("A"); JavaPackage b = new JavaPackage("B"); a.dependsUpon(b); b.dependsUpon(a); List aCycles = new ArrayList(); assertEquals(true, a.containsCycle()); assertEquals(true, a.collectAllCycles(aCycles)); assertListEquals(aCycles, new String[] {"A", "B", "A"}); List bCycles = new ArrayList(); assertEquals(true, b.containsCycle()); assertEquals(true, b.collectAllCycles(bCycles)); assertListEquals(bCycles, new String[] {"B", "A", "B"}); } public void test3Node1BranchCycle() { JavaPackage a = new JavaPackage("A"); JavaPackage b = new JavaPackage("B"); JavaPackage c = new JavaPackage("C"); a.dependsUpon(b); b.dependsUpon(c); c.dependsUpon(a); List aCycles = new ArrayList(); assertEquals(true, a.containsCycle()); assertEquals(true, a.collectAllCycles(aCycles)); assertListEquals(aCycles, new String[] {"A", "B", "C", "A"}); List bCycles = new ArrayList(); assertEquals(true, b.containsCycle()); assertEquals(true, b.collectAllCycles(bCycles)); assertListEquals(bCycles, new String[] {"B", "C", "A", "B"}); List cCycles = new ArrayList(); assertEquals(true, c.containsCycle()); assertEquals(true, c.collectAllCycles(cCycles)); assertListEquals(cCycles, new String[] {"C", "A", "B", "C"}); } public void test3Node1BranchSubCycle() { JavaPackage a = new JavaPackage("A"); JavaPackage b = new JavaPackage("B"); JavaPackage c = new JavaPackage("C"); a.dependsUpon(b); b.dependsUpon(c); c.dependsUpon(b); List aCycles = new ArrayList(); assertEquals(true, a.containsCycle()); assertEquals(true, a.collectAllCycles(aCycles)); assertListEquals(aCycles, new String[] {"A", "B", "C", "B"}); List bCycles = new ArrayList(); assertEquals(true, b.containsCycle()); assertEquals(true, b.collectAllCycles(bCycles)); assertListEquals(bCycles, new String[] {"B", "C", "B"}); List cCycles = new ArrayList(); assertEquals(true, c.containsCycle()); assertEquals(true, c.collectAllCycles(cCycles)); assertListEquals(cCycles, new String[] {"C", "B", "C"}); } public void test3Node2BranchCycle() { JavaPackage a = new JavaPackage("A"); JavaPackage b = new JavaPackage("B"); JavaPackage c = new JavaPackage("C"); a.dependsUpon(b); b.dependsUpon(a); a.dependsUpon(c); c.dependsUpon(a); List aCycles = new ArrayList(); assertEquals(true, a.containsCycle()); assertEquals(true, a.collectAllCycles(aCycles)); assertListEquals(aCycles, new String[] {"A", "B", "A", "C", "A"}); List bCycles = new ArrayList(); assertEquals(true, b.containsCycle()); assertEquals(true, b.collectAllCycles(bCycles)); assertListEquals(bCycles, new String[] {"B", "A", "B", "C", "A"}); List cCycles = new ArrayList(); assertEquals(true, c.containsCycle()); assertEquals(true, c.collectAllCycles(cCycles)); assertListEquals(cCycles, new String[] {"C", "A", "B", "A", "C"}); } public void test5Node2BranchCycle() { JavaPackage a = new JavaPackage("A"); JavaPackage b = new JavaPackage("B"); JavaPackage c = new JavaPackage("C"); JavaPackage d = new JavaPackage("D"); JavaPackage e = new JavaPackage("E"); a.dependsUpon(b); b.dependsUpon(c); c.dependsUpon(a); a.dependsUpon(d); d.dependsUpon(e); e.dependsUpon(a); List aCycles = new ArrayList(); assertEquals(true, a.containsCycle()); assertEquals(true, a.collectAllCycles(aCycles)); assertListEquals(aCycles, new String[] {"A", "B", "C", "A", "D", "E", "A"}); List bCycles = new ArrayList(); assertEquals(true, b.containsCycle()); assertEquals(true, b.collectAllCycles(bCycles)); assertListEquals(bCycles, new String[] {"B", "C", "A", "B", "D", "E", "A"}); List cCycles = new ArrayList(); assertEquals(true, c.containsCycle()); assertEquals(true, c.collectAllCycles(cCycles)); assertListEquals(cCycles, new String[] {"C", "A", "B", "C", "D", "E", "A"}); List dCycles = new ArrayList(); assertEquals(true, d.containsCycle()); assertEquals(true, d.collectAllCycles(dCycles)); assertListEquals(dCycles, new String[] {"D", "E", "A", "B", "C", "A" , "D"}); List eCycles = new ArrayList(); assertEquals(true, e.containsCycle()); assertEquals(true, e.collectAllCycles(eCycles)); assertListEquals(eCycles, new String[] {"E", "A", "B", "C", "A", "D", "E"}); } protected void assertListEquals(List list, String names[]) { assertEquals(names.length, list.size()); for (int i=0; i < names.length; i++) { assertEquals(names[i], ((JavaPackage)list.get(i)).getName()); } } }
5,447
28.290323
79
java
jdepend
jdepend-master/test/jdepend/framework/ComponentTest.java
package jdepend.framework; import java.io.IOException; import java.text.NumberFormat; import java.util.Collection; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class ComponentTest extends JDependTestCase { private JDepend jdepend; private static NumberFormat formatter; static { formatter = NumberFormat.getInstance(); formatter.setMaximumFractionDigits(2); } public ComponentTest(String name) { super(name); } protected void setUp() { super.setUp(); jdepend = new JDepend(); jdepend.analyzeInnerClasses(false); } protected void tearDown() { super.tearDown(); } public void testJDependComponents() throws IOException { jdepend.setComponents("jdepend,junit,java,javax"); jdepend.addDirectory(getBuildDir()); jdepend.analyze(); Collection packages = jdepend.getPackages(); assertEquals(6, packages.size()); assertJDependPackage(); assertJUnitPackage(); assertJavaPackage(); assertJavaxPackage(); } private void assertJDependPackage() { JavaPackage p = jdepend.getPackage("jdepend"); assertEquals("jdepend", p.getName()); assertEquals(36, p.getConcreteClassCount()); assertEquals(7, p.getAbstractClassCount()); assertEquals(0, p.afferentCoupling()); assertEquals(5, p.efferentCoupling()); assertEquals(format(0.16f), format(p.abstractness())); assertEquals("1", format(p.instability())); assertEquals(format(0.16f), format(p.distance())); assertEquals(1, p.getVolatility()); Collection efferents = p.getEfferents(); assertEquals(5, efferents.size()); assertTrue(efferents.contains(new JavaPackage("java"))); assertTrue(efferents.contains(new JavaPackage("javax"))); assertTrue(efferents.contains(new JavaPackage("junit"))); Collection afferents = p.getAfferents(); assertEquals(0, afferents.size()); } private void assertJUnitPackage() { JavaPackage p = jdepend.getPackage("junit"); assertEquals("junit", p.getName()); Collection afferents = p.getAfferents(); assertEquals(1, afferents.size()); assertTrue(afferents.contains(new JavaPackage("jdepend"))); Collection efferents = p.getEfferents(); assertEquals(0, efferents.size()); } private void assertJavaPackage() { JavaPackage p = jdepend.getPackage("java"); assertEquals("java", p.getName()); Collection afferents = p.getAfferents(); assertEquals(1, afferents.size()); assertTrue(afferents.contains(new JavaPackage("jdepend"))); Collection efferents = p.getEfferents(); assertEquals(0, efferents.size()); } private void assertJavaxPackage() { JavaPackage p = jdepend.getPackage("javax"); assertEquals("javax", p.getName()); Collection afferents = p.getAfferents(); assertEquals(1, afferents.size()); assertTrue(afferents.contains(new JavaPackage("jdepend"))); Collection efferents = p.getEfferents(); assertEquals(0, efferents.size()); } private String format(float f) { return formatter.format(f); } }
3,458
29.342105
67
java
jdepend
jdepend-master/test/jdepend/framework/ConstraintTest.java
package jdepend.framework; import java.io.IOException; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class ConstraintTest extends JDependTestCase { private JDepend jdepend; public ConstraintTest(String name) { super(name); } protected void setUp() { super.setUp(); PackageFilter filter = new PackageFilter(); filter.addPackage("java.*"); filter.addPackage("javax.*"); jdepend = new JDepend(filter); } public void testMatchPass() { DependencyConstraint constraint = new DependencyConstraint(); JavaPackage expectedA = constraint.addPackage("A"); JavaPackage expectedB = constraint.addPackage("B"); expectedA.dependsUpon(expectedB); JavaPackage actualA = new JavaPackage("A"); JavaPackage actualB = new JavaPackage("B"); actualA.dependsUpon(actualB); jdepend.addPackage(actualA); jdepend.addPackage(actualB); assertEquals(true, jdepend.dependencyMatch(constraint)); } public void testMatchFail() { DependencyConstraint constraint = new DependencyConstraint(); JavaPackage expectedA = constraint.addPackage("A"); JavaPackage expectedB = constraint.addPackage("B"); JavaPackage expectedC = constraint.addPackage("C"); expectedA.dependsUpon(expectedB); JavaPackage actualA = new JavaPackage("A"); JavaPackage actualB = new JavaPackage("B"); JavaPackage actualC = new JavaPackage("C"); actualA.dependsUpon(actualB); actualA.dependsUpon(actualC); jdepend.addPackage(actualA); jdepend.addPackage(actualB); jdepend.addPackage(actualC); assertEquals(false, jdepend.dependencyMatch(constraint)); } public void testJDependConstraints() throws IOException { jdepend.addDirectory(getBuildDir()); jdepend.analyze(); DependencyConstraint constraint = new DependencyConstraint(); JavaPackage junitframework = constraint.addPackage("junit.framework"); JavaPackage junitui = constraint.addPackage("junit.textui"); JavaPackage framework = constraint.addPackage("jdepend.framework"); JavaPackage text = constraint.addPackage("jdepend.textui"); JavaPackage xml = constraint.addPackage("jdepend.xmlui"); JavaPackage swing = constraint.addPackage("jdepend.swingui"); JavaPackage orgjunitrunners = constraint.addPackage("orgjunitrunners"); JavaPackage jdependframeworkp2 = constraint.addPackage("jdependframeworkp2"); JavaPackage jdependframeworkp3 = constraint.addPackage("jdependframeworkp3"); JavaPackage jdependframeworkp1 = constraint.addPackage("jdependframeworkp1"); JavaPackage orgjunit = constraint.addPackage("orgjunit"); framework.dependsUpon(junitframework); framework.dependsUpon(junitui); text.dependsUpon(framework); xml.dependsUpon(framework); xml.dependsUpon(text); swing.dependsUpon(framework); xml.dependsUpon(framework); framework.dependsUpon(jdependframeworkp2); framework.dependsUpon(jdependframeworkp3); framework.dependsUpon(jdependframeworkp1); framework.dependsUpon(orgjunitrunners); framework.dependsUpon(orgjunit); assertEquals(true, jdepend.dependencyMatch(constraint)); } }
3,451
31.87619
85
java
jdepend
jdepend-master/test/jdepend/framework/CycleTest.java
package jdepend.framework; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class CycleTest extends JDependTestCase { public CycleTest(String name) { super(name); } public void testNoCycles() { JavaPackage a = new JavaPackage("A"); JavaPackage b = new JavaPackage("B"); a.dependsUpon(b); List aCycles = new ArrayList(); assertEquals(false, a.containsCycle()); assertEquals(false, a.collectCycle(aCycles)); assertListEquals(aCycles, new String[] {}); List bCycles = new ArrayList(); assertEquals(false, b.containsCycle()); assertEquals(false, b.collectCycle(bCycles)); assertListEquals(bCycles, new String[] {}); } public void test2Node1BranchCycle() { JavaPackage a = new JavaPackage("A"); JavaPackage b = new JavaPackage("B"); a.dependsUpon(b); b.dependsUpon(a); List aCycles = new ArrayList(); assertEquals(true, a.containsCycle()); assertEquals(true, a.collectCycle(aCycles)); assertListEquals(aCycles, new String[] { "A", "B", "A"}); List bCycles = new ArrayList(); assertEquals(true, b.containsCycle()); assertEquals(true, b.collectCycle(bCycles)); assertListEquals(bCycles, new String[] { "B", "A", "B"}); } public void test3Node1BranchCycle() { JavaPackage a = new JavaPackage("A"); JavaPackage b = new JavaPackage("B"); JavaPackage c = new JavaPackage("C"); a.dependsUpon(b); b.dependsUpon(c); c.dependsUpon(a); List aCycles = new ArrayList(); assertEquals(true, a.containsCycle()); assertEquals(true, a.collectCycle(aCycles)); assertListEquals(aCycles, new String[] { "A", "B", "C", "A"}); List bCycles = new ArrayList(); assertEquals(true, b.containsCycle()); assertEquals(true, b.collectCycle(bCycles)); assertListEquals(bCycles, new String[] { "B", "C", "A", "B"}); List cCycles = new ArrayList(); assertEquals(true, c.containsCycle()); assertEquals(true, c.collectCycle(cCycles)); assertListEquals(cCycles, new String[] { "C", "A", "B", "C"}); } public void test3Node1BranchSubCycle() { JavaPackage a = new JavaPackage("A"); JavaPackage b = new JavaPackage("B"); JavaPackage c = new JavaPackage("C"); a.dependsUpon(b); b.dependsUpon(c); c.dependsUpon(b); List aCycles = new ArrayList(); assertEquals(true, a.containsCycle()); assertEquals(true, a.collectCycle(aCycles)); assertListEquals(aCycles, new String[] { "A", "B", "C", "B"}); List bCycles = new ArrayList(); assertEquals(true, b.containsCycle()); assertEquals(true, b.collectCycle(bCycles)); assertListEquals(bCycles, new String[] { "B", "C", "B"}); List cCycles = new ArrayList(); assertEquals(true, c.containsCycle()); assertEquals(true, c.collectCycle(cCycles)); assertListEquals(cCycles, new String[] { "C", "B", "C"}); } public void test3Node2BranchCycle() { JavaPackage a = new JavaPackage("A"); JavaPackage b = new JavaPackage("B"); JavaPackage c = new JavaPackage("C"); a.dependsUpon(b); b.dependsUpon(a); a.dependsUpon(c); c.dependsUpon(a); List aCycles = new ArrayList(); assertEquals(true, a.containsCycle()); assertEquals(true, a.collectCycle(aCycles)); assertListEquals(aCycles, new String[] { "A", "B", "A"}); List bCycles = new ArrayList(); assertEquals(true, b.containsCycle()); assertEquals(true, b.collectCycle(bCycles)); assertListEquals(bCycles, new String[] { "B", "A", "B"}); List cCycles = new ArrayList(); assertEquals(true, c.containsCycle()); assertEquals(true, c.collectCycle(cCycles)); assertListEquals(cCycles, new String[] { "C", "A", "B", "A"}); } public void test5Node2BranchCycle() { JavaPackage a = new JavaPackage("A"); JavaPackage b = new JavaPackage("B"); JavaPackage c = new JavaPackage("C"); JavaPackage d = new JavaPackage("D"); JavaPackage e = new JavaPackage("E"); a.dependsUpon(b); b.dependsUpon(c); c.dependsUpon(a); a.dependsUpon(d); d.dependsUpon(e); e.dependsUpon(a); List aCycles = new ArrayList(); assertEquals(true, a.containsCycle()); assertEquals(true, a.collectCycle(aCycles)); assertListEquals(aCycles, new String[] { "A", "B", "C", "A"}); List bCycles = new ArrayList(); assertEquals(true, b.containsCycle()); assertEquals(true, b.collectCycle(bCycles)); assertListEquals(bCycles, new String[] { "B", "C", "A", "B"}); List cCycles = new ArrayList(); assertEquals(true, c.containsCycle()); assertEquals(true, c.collectCycle(cCycles)); assertListEquals(cCycles, new String[] { "C", "A", "B", "C"}); List dCycles = new ArrayList(); assertEquals(true, d.containsCycle()); assertEquals(true, d.collectCycle(dCycles)); assertListEquals(dCycles, new String[] { "D", "E", "A", "B", "C", "A"}); List eCycles = new ArrayList(); assertEquals(true, e.containsCycle()); assertEquals(true, e.collectCycle(eCycles)); assertListEquals(eCycles, new String[] { "E", "A", "B", "C", "A"}); } protected void assertListEquals(List list, String names[]) { assertEquals(names.length, list.size()); for (int i = 0; i < names.length; i++) { assertEquals(names[i], ((JavaPackage) list.get(i)).getName()); } } protected void printCycles(List list) { Iterator i = list.iterator(); while (i.hasNext()) { JavaPackage p = (JavaPackage) i.next(); if (i.hasNext()) { System.out.print(p.getName() + "->"); } else { System.out.println(p.getName()); } } } }
6,295
30.959391
80
java
jdepend
jdepend-master/test/jdepend/framework/ExampleAbstractClass.java
package jdepend.framework; import java.math.BigDecimal; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public abstract class ExampleAbstractClass implements ExampleInterface, java.io.Serializable { private java.lang.reflect.Method method; public ExampleAbstractClass() { } public void a() { java.net.URL url; } public java.util.Vector b(String[] s, java.text.NumberFormat nf) { return null; } public void c(BigDecimal bd, byte[] b) throws java.rmi.RemoteException { } public abstract java.io.File[] d() throws java.io.IOException; }
631
19.387097
76
java
jdepend
jdepend-master/test/jdepend/framework/ExampleAnnotation.java
package jdepend.framework; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static jdepend.framework.p3.ExampleSecondEnum.NO_DEPENDENCIES_ON_ME; import java.lang.annotation.Retention; import jdepend.framework.p1.ExampleInnerAnnotation; import jdepend.framework.p2.ExampleEnum; import jdepend.framework.p3.ExampleSecondEnum; @Retention(RUNTIME) public @interface ExampleAnnotation { Class<?> c1() default Object.class; Class<?> c2() default Object.class; ExampleInnerAnnotation c3(); ExampleEnum c4(); ExampleSecondEnum c5() default NO_DEPENDENCIES_ON_ME; }
591
21.769231
75
java
jdepend
jdepend-master/test/jdepend/framework/ExampleConcreteClass.java
package jdepend.framework; import java.math.BigDecimal; import jdepend.framework.p1.ExampleInnerAnnotation; import jdepend.framework.p2.ExampleEnum; import org.junit.Ignore; import org.junit.Test; import org.junit.runners.Suite.SuiteClasses; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ @org.junit.runners.Suite.SuiteClasses(java.applet.AppletStub.class) public class ExampleConcreteClass extends ExampleAbstractClass { private java.sql.Statement[] statements; public ExampleConcreteClass() { } public void a() { try { java.net.URL url = new java.net.URL("http://www.clarkware.com"); } catch (Exception e) { } } public java.util.Vector b(String[] s, java.text.NumberFormat nf) { return null; } public void c(BigDecimal bd, byte[] bytes) throws java.rmi.RemoteException { int[] a = { 1, 2, 3}; int[][] b = { { 1, 2}, { 3, 4}, { 5, 6}}; } public java.io.File[] d() throws java.io.IOException { java.util.jar.JarFile[] files = new java.util.jar.JarFile[1]; return new java.io.File[10]; } public java.lang.String[] e() { java.lang.String[] strings = new java.lang.String[1]; return strings; } @org.junit.Test(expected = javax.crypto.BadPaddingException.class) @ExampleAnnotation( c1 = java.awt.geom.AffineTransform.class, c2 = java.awt.image.renderable.ContextualRenderedImageFactory.class, c3 = @ExampleInnerAnnotation({ java.awt.im.InputContext.class, java.awt.dnd.peer.DragSourceContextPeer.class}), c4 = ExampleEnum.E1) @org.junit.Ignore public void f() { } public class ExampleInnerClass { } } class ExamplePackageClass { }
1,778
25.161765
80
java
jdepend
jdepend-master/test/jdepend/framework/ExampleInterface.java
package jdepend.framework; import java.math.BigDecimal; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public interface ExampleInterface { public void a(); public java.util.Vector b(String[] s, java.text.NumberFormat nf); public void c(BigDecimal bd, byte[] b) throws java.rmi.RemoteException; public java.io.File[] d() throws java.io.IOException; }
401
19.1
75
java
jdepend
jdepend-master/test/jdepend/framework/ExampleTest.java
package jdepend.framework; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import junit.framework.TestCase; /** * The <code>ExampleTest</code> is an example <code>TestCase</code> * that demonstrates tests for measuring the distance from the * main sequence (D), package dependency constraints, and the * existence of cyclic package dependencies. * <p> * This test analyzes the JDepend class files. * * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class ExampleTest extends TestCase { private JDepend jdepend; public String jdependHomeDirectory; public ExampleTest(String name) { super(name); } protected void setUp() throws IOException { jdependHomeDirectory = System.getProperty("jdepend.home"); if (jdependHomeDirectory == null) { fail("Property 'jdepend.home' not defined"); } PackageFilter filter = new PackageFilter(); filter.addPackage("java.*"); filter.addPackage("javax.*"); jdepend = new JDepend(filter); String classesDir = jdependHomeDirectory + File.separator + "build"; jdepend.addDirectory(classesDir); } /** * Tests the conformance of a single package to a distance * from the main sequence (D) within a tolerance. */ public void testOnePackageDistance() { double ideal = 0.0; double tolerance = 0.8; jdepend.analyze(); JavaPackage p = jdepend.getPackage("jdepend.framework"); assertEquals("Distance exceeded: " + p.getName(), ideal, p.distance(), tolerance); } /** * Tests that a single package does not contain any * package dependency cycles. */ public void testOnePackageHasNoCycles() { jdepend.analyze(); JavaPackage p = jdepend.getPackage("jdepend.framework"); assertEquals("Cycles exist: " + p.getName(), false, p.containsCycle()); } /** * Tests the conformance of all analyzed packages to a * distance from the main sequence (D) within a tolerance. */ public void testAllPackagesDistance() { double ideal = 0.0; double tolerance = 1.0; Collection packages = jdepend.analyze(); for (Iterator iter = packages.iterator(); iter.hasNext();) { JavaPackage p = (JavaPackage)iter.next(); assertEquals("Distance exceeded: " + p.getName(), ideal, p.distance(), tolerance); } } /** * Tests that a package dependency cycle does not exist * for any of the analyzed packages. */ public void testAllPackagesHaveNoCycles() { Collection packages = jdepend.analyze(); assertEquals("Cycles exist", false, jdepend.containsCycles()); } /** * Tests that a package dependency constraint is matched * for the analyzed packages. * <p> * Fails if any package dependency other than those declared * in the dependency constraints are detected. */ public void testDependencyConstraint() { DependencyConstraint constraint = new DependencyConstraint(); JavaPackage junitframework = constraint.addPackage("junit.framework"); JavaPackage junitui = constraint.addPackage("junit.textui"); JavaPackage framework = constraint.addPackage("jdepend.framework"); JavaPackage text = constraint.addPackage("jdepend.textui"); JavaPackage xml = constraint.addPackage("jdepend.xmlui"); JavaPackage swing = constraint.addPackage("jdepend.swingui"); JavaPackage orgjunitrunners = constraint.addPackage("orgjunitrunners"); JavaPackage jdependframeworkp2 = constraint.addPackage("jdependframeworkp2"); JavaPackage jdependframeworkp3 = constraint.addPackage("jdependframeworkp3"); JavaPackage jdependframeworkp1 = constraint.addPackage("jdependframeworkp1"); JavaPackage orgjunit = constraint.addPackage("orgjunit"); framework.dependsUpon(junitframework); framework.dependsUpon(junitui); text.dependsUpon(framework); xml.dependsUpon(framework); xml.dependsUpon(text); swing.dependsUpon(framework); framework.dependsUpon(jdependframeworkp2); framework.dependsUpon(jdependframeworkp3); framework.dependsUpon(jdependframeworkp1); framework.dependsUpon(orgjunitrunners); framework.dependsUpon(orgjunit); jdepend.analyze(); assertEquals("Constraint mismatch", true, jdepend.dependencyMatch(constraint)); } public static void main(String[] args) { junit.textui.TestRunner.run(ExampleTest.class); } }
4,836
30.409091
85
java
jdepend
jdepend-master/test/jdepend/framework/FileManagerTest.java
package jdepend.framework; import java.io.File; import java.io.IOException; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class FileManagerTest extends JDependTestCase { private FileManager fileManager; public FileManagerTest(String name) { super(name); } protected void setUp() { super.setUp(); fileManager = new FileManager(); fileManager.acceptInnerClasses(false); } protected void tearDown() { super.tearDown(); } public void testEmptyFileManager() { assertEquals(0, fileManager.extractFiles().size()); } public void testBuildDirectory() throws IOException { fileManager.addDirectory(getBuildDir()); assertEquals(43, fileManager.extractFiles().size()); } public void testNonExistentDirectory() { try { fileManager.addDirectory(getBuildDir() + "junk"); fail("Non-existent directory: Should raise IOException"); } catch (IOException expected) { assertTrue(true); } } public void testInvalidDirectory() { String file = getTestDir() + getPackageSubDir() + "ExampleTest.java"; try { fileManager.addDirectory(file); fail("Invalid directory: Should raise IOException"); } catch (IOException expected) { assertTrue(true); } } public void testClassFile() throws IOException { File f = new File(getBuildDir() + getPackageSubDir() + "JDepend.class"); assertEquals(true, new FileManager().acceptClassFile(f)); } public void testNonExistentClassFile() { File f = new File(getBuildDir() + "JDepend.class"); assertEquals(false, new FileManager().acceptClassFile(f)); } public void testInvalidClassFile() { File f = new File(getHomeDir() + "build.xml"); assertEquals(false, new FileManager().acceptClassFile(f)); } public void testJar() throws IOException { File f = File.createTempFile("bogus", ".jar", new File(getTestDataDir())); fileManager.addDirectory(f.getPath()); f.deleteOnExit(); } public void testZip() throws IOException { File f = File.createTempFile("bogus", ".zip", new File(getTestDataDir())); fileManager.addDirectory(f.getPath()); f.deleteOnExit(); } public void testWar() throws IOException { File f = File.createTempFile("bogus", ".war", new File(getTestDataDir())); fileManager.addDirectory(f.getPath()); f.deleteOnExit(); } }
2,712
25.861386
80
java
jdepend
jdepend-master/test/jdepend/framework/FilterTest.java
package jdepend.framework; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class FilterTest extends JDependTestCase { public FilterTest(String name) { super(name); } protected void setUp() { super.setUp(); System.setProperty("user.home", getTestDataDir()); } protected void tearDown() { super.tearDown(); } public void testDefault() { PackageFilter filter = new PackageFilter(); assertEquals(5, filter.getFilters().size()); assertFiltersExist(filter); } public void testFile() throws IOException { String filterFile = getTestDataDir() + "jdepend.properties"; PackageFilter filter = new PackageFilter(new File(filterFile)); assertEquals(5, filter.getFilters().size()); assertFiltersExist(filter); } public void testCollection() throws IOException { Collection filters = new ArrayList(); filters.add("java.*"); filters.add("javax.*"); filters.add("sun.*"); filters.add("com.sun.*"); filters.add("com.xyz.tests.*"); PackageFilter filter = new PackageFilter(filters); assertEquals(5, filter.getFilters().size()); assertFiltersExist(filter); } public void testCollectionSubset() { Collection filters = new ArrayList(); filters.add("com.xyz"); PackageFilter filter = new PackageFilter(filters); assertEquals(1, filter.getFilters().size()); } private void assertFiltersExist(PackageFilter filter) { assertFalse(filter.accept("java.lang")); assertFalse(filter.accept("javax.ejb")); assertTrue(filter.accept("com.xyz.tests")); assertFalse(filter.accept("com.xyz.tests.a")); assertTrue(filter.accept("com.xyz.ejb")); } }
1,961
26.633803
71
java
jdepend
jdepend-master/test/jdepend/framework/JDependTestCase.java
package jdepend.framework; import java.io.*; import junit.framework.*; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class JDependTestCase extends TestCase { private String homeDir; private String testDir; private String testDataDir; private String buildDir; private String packageSubDir; private String originalUserHome; public JDependTestCase(String name) { super(name); } protected void setUp() { homeDir = System.getProperty("jdepend.home"); if (homeDir == null) { fail("Property 'jdepend.home' not defined"); } homeDir = homeDir + File.separator; testDir = homeDir + File.separator + "test" + File.separator; testDataDir = testDir + "data" + File.separator; buildDir = homeDir + "build" + File.separator; packageSubDir = "jdepend" + File.separator + "framework" + File.separator; originalUserHome = System.getProperty("user.home"); } protected void tearDown() { System.setProperty("user.home", originalUserHome); } public String getHomeDir() { return homeDir; } public String getTestDataDir() { return testDataDir; } public String getTestDir() { return testDir; } public String getBuildDir() { return buildDir; } public String getPackageSubDir() { return packageSubDir; } }
1,494
22.359375
69
java
jdepend
jdepend-master/test/jdepend/framework/JarFileParserTest.java
package jdepend.framework; import java.io.File; import java.io.IOException; import java.util.Collection; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class JarFileParserTest extends JDependTestCase { private File jarFile; private File zipFile; public JarFileParserTest(String name) { super(name); } protected void setUp() { super.setUp(); jarFile = new File(getTestDataDir() + "test.jar"); zipFile = new File(getTestDataDir() + "test.zip"); } protected void tearDown() { super.tearDown(); } public void testInvalidJarFile() throws IOException { JavaClassBuilder builder = new JavaClassBuilder(); File bogusFile = new File(getTestDataDir() + "bogus.jar"); try { builder.buildClasses(bogusFile); fail("Should raise IOException"); } catch (IOException expected) { assertTrue(true); } } public void testInvalidZipFile() throws IOException { JavaClassBuilder builder = new JavaClassBuilder(); File bogusFile = new File(getTestDataDir() + "bogus.zip"); try { builder.buildClasses(bogusFile); fail("Should raise IOException"); } catch (IOException expected) { assertTrue(true); } } public void testJarFile() throws IOException { JavaClassBuilder builder = new JavaClassBuilder(); Collection classes = builder.buildClasses(jarFile); assertEquals(5, classes.size()); assertClassesExist(classes); assertInnerClassesExist(classes); } public void testJarFileWithoutInnerClasses() throws IOException { FileManager fm = new FileManager(); fm.acceptInnerClasses(false); JavaClassBuilder builder = new JavaClassBuilder(fm); Collection classes = builder.buildClasses(jarFile); assertEquals(4, classes.size()); assertClassesExist(classes); } public void testZipFile() throws IOException { JavaClassBuilder builder = new JavaClassBuilder(); Collection classes = builder.buildClasses(zipFile); assertEquals(5, classes.size()); assertClassesExist(classes); assertInnerClassesExist(classes); } public void testZipFileWithoutInnerClasses() throws IOException { FileManager fm = new FileManager(); fm.acceptInnerClasses(false); JavaClassBuilder builder = new JavaClassBuilder(fm); Collection classes = builder.buildClasses(zipFile); assertEquals(4, classes.size()); assertClassesExist(classes); } public void testCountClasses() throws IOException { JDepend jdepend = new JDepend(); jdepend.addDirectory(getTestDataDir()); jdepend.analyzeInnerClasses(true); assertEquals(10, jdepend.countClasses()); jdepend.analyzeInnerClasses(false); assertEquals(8, jdepend.countClasses()); } private void assertClassesExist(Collection classes) { assertTrue(classes.contains(new JavaClass( "jdepend.framework.ExampleAbstractClass"))); assertTrue(classes.contains(new JavaClass( "jdepend.framework.ExampleInterface"))); assertTrue(classes.contains(new JavaClass( "jdepend.framework.ExampleConcreteClass"))); } private void assertInnerClassesExist(Collection classes) { assertTrue(classes.contains(new JavaClass( "jdepend.framework.ExampleConcreteClass$ExampleInnerClass"))); } }
3,641
25.977778
78
java
jdepend
jdepend-master/test/jdepend/framework/MetricTest.java
package jdepend.framework; import java.io.IOException; import java.text.NumberFormat; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class MetricTest extends JDependTestCase { private JDepend jdepend; private static NumberFormat formatter; static { formatter = NumberFormat.getInstance(); formatter.setMaximumFractionDigits(2); } public MetricTest(String name) { super(name); } protected void setUp() { super.setUp(); PackageFilter filter = new PackageFilter(); filter.addPackage("java.*"); filter.addPackage("javax.*"); jdepend = new JDepend(filter); jdepend.analyzeInnerClasses(false); } protected void tearDown() { super.tearDown(); } public void testAnalyzeClassFiles() throws IOException { jdepend.addDirectory(getBuildDir()); assertAnalyzePackages(); } private void assertAnalyzePackages() { assertEquals(43, jdepend.countClasses()); PackageFilter filter = jdepend.getFilter(); filter.addPackage("junit.*"); jdepend.analyze(); assertFrameworkPackage(); assertTextUIPackage(); assertSwingUIPackage(); assertXmlUIPackage(); } private void assertFrameworkPackage() { JavaPackage p = jdepend.getPackage("jdepend.framework"); assertNotNull(p); assertEquals(25, p.getConcreteClassCount()); assertEquals(5, p.getAbstractClassCount()); assertEquals(3, p.afferentCoupling()); assertEquals(5, p.efferentCoupling()); assertEquals(format(0.17f), format(p.abstractness())); assertEquals(format(0.62f), format(p.instability())); assertEquals(format(0.21f), format(p.distance())); assertEquals(1, p.getVolatility()); } private void assertTextUIPackage() { JavaPackage p = jdepend.getPackage("jdepend.textui"); assertNotNull(p); assertEquals(1, p.getConcreteClassCount()); assertEquals(0, p.getAbstractClassCount()); assertEquals(1, p.efferentCoupling()); assertEquals("0", format(p.abstractness())); assertEquals(1, p.afferentCoupling()); assertEquals(format(0.5f), format(p.instability())); assertEquals(format(0.5f), format(p.distance())); assertEquals(1, p.getVolatility()); } private void assertSwingUIPackage() { JavaPackage p = jdepend.getPackage("jdepend.swingui"); assertNotNull(p); assertEquals(7, p.getConcreteClassCount()); assertEquals(1, p.getAbstractClassCount()); assertEquals(0, p.afferentCoupling()); assertEquals(1, p.efferentCoupling()); assertEquals(format(0.12f), format(p.abstractness())); assertEquals("1", format(p.instability())); assertEquals(format(0.12f), format(p.distance())); assertEquals(1, p.getVolatility()); } private void assertXmlUIPackage() { JavaPackage p = jdepend.getPackage("jdepend.xmlui"); assertNotNull(p); assertEquals(1, p.getConcreteClassCount()); assertEquals(0, p.getAbstractClassCount()); assertEquals(0, p.afferentCoupling()); assertEquals(2, p.efferentCoupling()); assertEquals(format(0.0f), format(p.abstractness())); assertEquals("1", format(p.instability())); assertEquals(format(0.0f), format(p.distance())); assertEquals(1, p.getVolatility()); } public void testConfiguredVolatility() throws IOException { jdepend.addDirectory(getBuildDir()); JavaPackage pkg = new JavaPackage("jdepend.swingui"); pkg.setVolatility(0); jdepend.addPackage(pkg); jdepend.analyze(); JavaPackage analyzedPkg = jdepend.getPackage(pkg.getName()); assertEquals(0, analyzedPkg.getVolatility()); assertEquals(format(0.0f), format(analyzedPkg.distance())); assertEquals(7, analyzedPkg.getConcreteClassCount()); } private String format(float f) { return formatter.format(f); } }
4,137
28.557143
68
java
jdepend
jdepend-master/test/jdepend/framework/ProfilingHarness.java
package jdepend.framework; import static java.lang.String.format; public class ProfilingHarness { public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); for (int i = 0; i < 10; i++) { JDepend jDepend = new JDepend(); for (String arg : args) { jDepend.addDirectory(arg); } System.out.println(jDepend.countClasses()); } long end = System.currentTimeMillis(); System.out.println(format("done: %sms", (end - start))); } }
495
22.619048
58
java
jdepend
jdepend-master/test/jdepend/framework/PropertyConfiguratorTest.java
package jdepend.framework; import java.io.File; import java.io.IOException; import java.util.Collection; /** * @author <b>Mike Clark</b> * @author Clarkware Consulting, Inc. */ public class PropertyConfiguratorTest extends JDependTestCase { public PropertyConfiguratorTest(String name) { super(name); } protected void setUp() { super.setUp(); System.setProperty("user.home", getTestDataDir()); } protected void tearDown() { super.tearDown(); } public void testDefaultFilters() { PropertyConfigurator c = new PropertyConfigurator(); assertFiltersExist(c.getFilteredPackages()); assertFalse(c.getAnalyzeInnerClasses()); } public void testFiltersFromFile() throws IOException { String file = getTestDataDir() + "jdepend.properties"; PropertyConfigurator c = new PropertyConfigurator(new File(file)); assertFiltersExist(c.getFilteredPackages()); assertFalse(c.getAnalyzeInnerClasses()); } private void assertFiltersExist(Collection filters) { assertEquals(5, filters.size()); assertTrue(filters.contains("java.*")); assertTrue(filters.contains("javax.*")); assertTrue(filters.contains("sun.*")); assertTrue(filters.contains("com.sun.*")); assertTrue(filters.contains("com.xyz.tests.*")); } public void testDefaultPackages() throws IOException { JDepend j = new JDepend(); JavaPackage pkg = j.getPackage("com.xyz.a.neverchanges"); assertNotNull(pkg); assertEquals(0, pkg.getVolatility()); pkg = j.getPackage("com.xyz.b.neverchanges"); assertNotNull(pkg); assertEquals(0, pkg.getVolatility()); pkg = j.getPackage("com.xyz.c.neverchanges"); assertNull(pkg); } }
1,838
26.447761
74
java
jdepend
jdepend-master/test/jdepend/framework/p1/ExampleInnerAnnotation.java
package jdepend.framework.p1; public @interface ExampleInnerAnnotation { Class<?>[] value() default {}; }
111
13
42
java
jdepend
jdepend-master/test/jdepend/framework/p2/ExampleEnum.java
package jdepend.framework.p2; public enum ExampleEnum { E1, E2 }
68
8.857143
29
java
jdepend
jdepend-master/test/jdepend/framework/p3/ExampleSecondEnum.java
package jdepend.framework.p3; public enum ExampleSecondEnum { NO_DEPENDENCIES_ON_ME }
88
13.833333
31
java
javalang
javalang-master/javalang/test/source/package-info/AnnotationJavadoc.java
@Package /** Test that includes java doc first but no annotation */ package org.javalang.test;
95
18.2
52
java
javalang
javalang-master/javalang/test/source/package-info/AnnotationOnly.java
@Package package org.javalang.test;
35
17
26
java
javalang
javalang-master/javalang/test/source/package-info/JavadocAnnotation.java
/** Test that includes java doc first but no annotation */ @Package package org.javalang.test;
95
18.2
52
java
javalang
javalang-master/javalang/test/source/package-info/JavadocOnly.java
/** Test that includes java doc first but no annotation */ package org.javalang.test;
86
20.75
52
java
javalang
javalang-master/javalang/test/source/package-info/NoAnnotationNoJavadoc.java
package org.javalang.test;
26
26
26
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/BibRecord.java
package org.allenai.scienceparse; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.Calendar; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; @Data @EqualsAndHashCode(exclude={"citeRegEx", "shortCiteRegEx"}) public class BibRecord { public static final int MINYEAR = 1800; public static final int MAXYEAR = Calendar.getInstance().get(Calendar.YEAR) + 10; // Something is wrong with sbt, lombok, and Scala/Java interop, making this unconstructable from // Scala if you don't write this custom constructor. public BibRecord( final String title, final List<String> author, final String venue, final Pattern citeRegEx, final Pattern shortCiteRegEx, final int year ) { this.title = title; this.author = author; this.venue = venue; this.citeRegEx = citeRegEx; this.shortCiteRegEx = shortCiteRegEx; this.year = year; } static private String normalizeInitialsInAuthor(String author) { author = author.trim(); author = author.replaceAll("(\\p{Lu}\\.) (\\p{Lu}\\.)", "$1$2"); author = author.replaceAll("(\\p{Lu}\\.) (\\p{Lu}\\.)", "$1$2"); //twice to catch three-initial seq. return author; } public BibRecord withNormalizedAuthors() { return new BibRecord( title, author.stream(). map(BibRecord::normalizeInitialsInAuthor). filter(s -> !StringUtils.normalize(s.toLowerCase()).equals("et al")). collect(Collectors.toList()), venue, citeRegEx, shortCiteRegEx, year); } public BibRecord withTitle(final String newTitle) { return new BibRecord( newTitle, author, venue, citeRegEx, shortCiteRegEx, year); } private static String stripSuperscriptTags(final String s) { if(s == null) return null; else return s.replaceAll("[⍗⍐]", ""); } public BibRecord withoutSuperscripts() { return new BibRecord( stripSuperscriptTags(title), author.stream().map(BibRecord::stripSuperscriptTags).collect(Collectors.toList()), stripSuperscriptTags(venue), citeRegEx, shortCiteRegEx, year); } public String title; public final List<String> author; public final String venue; public final Pattern citeRegEx; public final Pattern shortCiteRegEx; public final int year; }
2,469
27.068182
104
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/CRFBibRecordParser.java
package org.allenai.scienceparse; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.gs.collections.api.tuple.Pair; import com.gs.collections.impl.tuple.Tuples; import lombok.extern.slf4j.Slf4j; import org.allenai.ml.sequences.crf.CRFModel; import org.allenai.scienceparse.ExtractReferences.BibRecordParser; import org.allenai.scienceparse.ExtractedMetadata.LabelSpan; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; @Slf4j public class CRFBibRecordParser implements BibRecordParser { private CRFModel<String, String, String> model; public static final String DATA_VERSION = "0.1"; public CRFBibRecordParser(CRFModel<String, String, String> inModel) { model = inModel; } public static List<Pair<String, String>> getLabeledLineUMass(String s) { final String [] sourceTags = new String [] {"address", "authors", "booktitle", "editor", "institution", "journal", "pages", "publisher", "tech", "thesis", "title", "volume", "year"}; //MUST BE SORTED final String [] destTags = new String [] {"address", ExtractedMetadata.authorTag, ExtractedMetadata.venueTag, "editor", "institution", ExtractedMetadata.venueTag, "pages", "publisher", "tech", ExtractedMetadata.venueTag, ExtractedMetadata.titleTag, "volume", ExtractedMetadata.yearTag}; //pull the ref marker s.replaceAll("<ref-marker>.*</ref-marker>", ""); return labelAccordingToTags(s, sourceTags, destTags); } public static List<Pair<String, String>> labelAccordingToTags( String s, String[] sourceTags, String[] destTags ) { List<String> toks = tokenize(s); List<Pair<String, String>> out = new ArrayList<>(); out.add(Tuples.pair("<S>", "<S>")); boolean atStart = false; int curTagIndex = -1; //the current source tag that we're in, and labeling for for(int i=0; i<toks.size(); i++) { String sTok = toks.get(i); if(sTok.endsWith(">")) { String t = sTok.replaceAll("<", "").replaceAll("/", "").replaceAll(">", ""); int idx = Arrays.binarySearch(sourceTags, t); if(idx >= 0) { //ignore unescaped XML chars in bib if(sTok.startsWith("</")) curTagIndex = -1; //our tag closed else { curTagIndex = idx; atStart = true; } } } else { //write it out with proper tag String tag = "O"; if(curTagIndex >= 0) { tag = destTags[curTagIndex]; if(i<toks.size()-1) { if(toks.get(i+1).equals("</" + sourceTags[curTagIndex] + ">")) { //our tag ends on next word if(atStart) { //single-word span tag = "W_" + tag; } else { tag = "E_" + tag; } } else if(atStart) { tag = "B_" + tag; } else { tag = "I_" + tag; } } } out.add(Tuples.pair(sTok, tag)); atStart = false; } } out.add(Tuples.pair("</S>", "</S>")); return out; } public static List<Pair<String, String>> getLabeledLineCora(String s) { final String [] sourceTags = new String [] {"author", "booktitle", "date", "editor", "institution", "journal", "location", "note", "pages", "publisher", "tech", "title", "volume"}; //MUST BE SORTED final String [] destTags = new String [] {ExtractedMetadata.authorTag, ExtractedMetadata.venueTag, ExtractedMetadata.yearTag, "editor", "institution", ExtractedMetadata.venueTag, "location", "note", "pages", "publisher", ExtractedMetadata.venueTag, ExtractedMetadata.titleTag, "volume"}; return labelAccordingToTags(s, sourceTags, destTags); } public static List<Pair<String, String>> getLabeledLineKermit(String s) { final String [] sourceTags = new String [] {"author", "booktitle", "date", "editor", "note", "pages", "publisher", "pubPlace", "title", "volume"}; //MUST BE SORTED final String [] destTags = new String [] {ExtractedMetadata.authorTag, ExtractedMetadata.venueTag, ExtractedMetadata.yearTag, "editor", "note", "pages", "publisher", "location", ExtractedMetadata.titleTag, "volume"}; s = s.replaceAll("<title level=\"j\"> ([^<]+) </title>", "<booktitle> $1 </booktitle>"); s = s.replaceAll("<title level=\"m\"> ([^<]+) </title>", "<booktitle> $1 </booktitle>"); s = s.replaceAll("<title level=\"a\"> ([^<]+) </title>", "<title> $1 </title>"); s = s.replaceAll("biblScope type=\"vol\" ([^<]+) </biblScope>", "<vol> $1 </vol>"); s = s.replaceAll("biblScope type=\"pp\" ([^<]+) </biblScope>", "<pages> $1 </pages>"); s = s.replaceAll("biblScope type=\"issue\" ([^<]+) </biblScope>", "<issue> $1 </issue>"); return labelAccordingToTags(s, sourceTags, destTags); } public static List<List<Pair<String, String>>> labelFromCoraFile(File trainFile) throws IOException { return labelFromFile(trainFile, s->getLabeledLineCora(s)); } public static List<List<Pair<String, String>>> labelFromUMassFile(File trainFile) throws IOException { return labelFromFile(trainFile, s-> getLabeledLineUMass(s)); } public static List<List<Pair<String, String>>> labelFromKermitFile(File trainFile) throws IOException { return labelFromFile(trainFile, s-> getLabeledLineKermit(s)); } public static List<List<Pair<String, String>>> labelFromFile(File trainFile, Function<String, List<Pair<String, String>>> gll) throws IOException { List<List<Pair<String, String>>> out = new ArrayList<>(); BufferedReader brIn = new BufferedReader(new InputStreamReader(new FileInputStream(trainFile), "UTF-8")); String sLine; while((sLine = brIn.readLine())!=null) { List<Pair<String,String>> labeledLine = gll.apply(sLine); out.add(labeledLine); } brIn.close(); return out; } private static List<String> tokenize(String line) { //tokenizes string for use in bib parsing //line = line.replaceAll("([a-z0-9])(,|\\.)", "$1 $2"); //break on lowercase alpha or num before . or , String [] toks = line.split(" "); //otherwise not fancy return Arrays.asList(toks); } private final LoadingCache<ArrayList<String>, List<String>> bestGuessCache = CacheBuilder.newBuilder(). maximumSize(10240). expireAfterAccess(10, TimeUnit.MINUTES).build( new CacheLoader<ArrayList<String>, List<String>>() { @Override public List<String> load(ArrayList<String> key) throws Exception { return model.bestGuess(key); } } ); public BibRecord parseRecord(String line) { if(Thread.interrupted()) throw new Parser.ParsingTimeout(); line = line.trim(); if(line.isEmpty() || line.length() > 2000) return null; Matcher m = RegexWithTimeout.matcher(ExtractReferences.pBracket, line); String citeRegEx = null; String shortCiteRegEx = null; if(m.matches()) { citeRegEx = m.group(1); shortCiteRegEx = citeRegEx; line = m.group(2); } else { m = RegexWithTimeout.matcher(ExtractReferences.pDot, line); if(m.matches()) { citeRegEx = m.group(1); shortCiteRegEx = citeRegEx; line = m.group(2); } } line = line.trim(); if(line.isEmpty()) return null; ArrayList<String> toks = new ArrayList<String>(); toks.add("<S>"); toks.addAll(tokenize(line)); toks.add("</S>"); List<String> labels; try{ labels = bestGuessCache.get(toks); } catch(final Exception e) { return null; } labels = PDFToCRFInput.padTagSequence(labels); List<LabelSpan> lss = ExtractedMetadata.getSpans(labels); String title = null; String author = null; String venue = null; String year = null; for (LabelSpan ls : lss) { //TODO: figure out how to make this code less redundant if (title == null && ls.tag.equals(ExtractedMetadata.titleTag)) { //only take the first title = PDFToCRFInput.stringAtForStringList(toks, ls.loc); } else if (author == null && ls.tag.equals(ExtractedMetadata.authorTag)) { author = PDFToCRFInput.stringAtForStringList(toks, ls.loc); } else if (venue == null && ls.tag.equals(ExtractedMetadata.venueTag)) { venue = PDFToCRFInput.stringAtForStringList(toks, ls.loc); } else if (year == null && ls.tag.equals(ExtractedMetadata.yearTag)) { year = PDFToCRFInput.stringAtForStringList(toks, ls.loc); } } List<String> authors = author == null ? null : ExtractReferences.authorStringToList(author); // log.info("authors first extracted: " + ((authors==null)?"":authors.toString())); // log.info("year first extracted: " + year); int iYear = -1; if(year == null && venue != null) { // check venue first, as sometimes year is at end Matcher mY = RegexWithTimeout.matcher(ReferencesPredicateExtractor.yearPattern, venue); while (mY.find()) year = mY.group(1); } if(year == null) { // check whole line Matcher mY = RegexWithTimeout.matcher(ReferencesPredicateExtractor.yearPattern, line); while(mY.find()) year = mY.group(1); } if(year != null) iYear = ExtractReferences.extractRefYear(year); if(citeRegEx == null && year != null) { shortCiteRegEx = ExtractReferences.getCiteAuthorFromAuthors(authors); citeRegEx = shortCiteRegEx + ",? " + ((iYear > 0)?Pattern.quote(iYear + ""):""); } if(citeRegEx == null || shortCiteRegEx == null || title == null || authors == null || year == null) return null; // log.info("cite string " + citeRegEx); BibRecord brOut = null; try { brOut = new BibRecord( CRFBibRecordParser.cleanTitle(title), Parser.trimAuthors(authors), Parser.cleanTitle(venue), Pattern.compile(citeRegEx), Pattern.compile(shortCiteRegEx), iYear); } catch (final NumberFormatException e) { return null; } if(iYear==0) //heuristic -- if we don't find year, almost certainly we didn't extract correctly. return null; // log.info("returning " + brOut.toString()); return brOut; } public static String cleanTitle(String title) { return title.replaceAll("^\\p{Pi}", ""). replaceAll("(\\p{Pe}|,|\\.)$", ""); } }
10,718
38.263736
149
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/CheckReferences.java
package org.allenai.scienceparse; import com.gs.collections.impl.set.mutable.primitive.LongHashSet; import org.allenai.scienceparse.ParserGroundTruth.Paper; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CheckReferences implements Serializable { private LongHashSet paperHashCodes = new LongHashSet(); public CheckReferences(String jsonFile) throws IOException { addPapers(new ParserGroundTruth(jsonFile).papers); } public CheckReferences(final InputStream is) throws IOException { addPapers(new ParserGroundTruth(is).papers); } public int getHashSize() { return paperHashCodes.size(); } public void addPaper(String title, List<String> authors, int year, String venue) { paperHashCodes.add(getHashCode(title, authors, year, venue)); } public boolean hasPaper(String title, List<String> authors, int year, String venue) { return paperHashCodes.contains(getHashCode(title, authors, year, venue)); } public long getHashCode(String title, List<String> authors, int year, String venue) { title = Parser.processTitle(title); authors = Parser.lastNames(authors); if(title==null) title = ""; if(authors==null) authors = new ArrayList<String>(); long hashCode = ((long) authors.hashCode()) * ((long) Integer.MAX_VALUE) + ((long) title.hashCode()) + ((long) Integer.hashCode(year)); return hashCode; } public void addPapers(List<Paper> papers) { for (Paper p : papers) { addPaper(p.title, Arrays.asList(p.authors), p.year, p.venue); } } }
1,672
29.981481
104
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/CitationRecord.java
package org.allenai.scienceparse; import lombok.Data; import lombok.experimental.Wither; @Data public class CitationRecord { public final int referenceID; @Wither public final String context; public final int startOffset; public final int endOffset; CitationRecord( final int referenceID, final String context, final int startOffset, final int endOffset ) { // Looks like we have to have an explicit constructor because otherwise, Scala freaks out when // using this class. this.referenceID = referenceID; this.context = context; this.startOffset = startOffset; this.endOffset = endOffset; } CitationRecord withConvertedSuperscriptTags() { final String newContext = context. replace('⍐', '('). replace('⍗', ')'); return this.withContext(newContext); } }
851
22.666667
98
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/DirectoryPaperSource.java
package org.allenai.scienceparse; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; /** * A paper source that gets papers from a directory in the file system */ public class DirectoryPaperSource extends PaperSource { private final File dir; public DirectoryPaperSource(final File dir) { this.dir = dir; } @Override public InputStream getPdf(final String paperId) throws FileNotFoundException { final File file = new File(dir, paperId + ".pdf"); return new BufferedInputStream(new FileInputStream(file)); } }
667
25.72
82
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/ExtractReferences.java
package org.allenai.scienceparse; import com.gs.collections.api.tuple.Pair; import com.gs.collections.impl.tuple.Tuples; import lombok.val; import lombok.extern.slf4j.Slf4j; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.allenai.ml.linalg.DenseVector; import org.allenai.ml.linalg.Vector; import org.allenai.ml.sequences.StateSpace; import org.allenai.ml.sequences.crf.CRFFeatureEncoder; import org.allenai.ml.sequences.crf.CRFModel; import org.allenai.ml.sequences.crf.CRFWeightsEncoder; import org.allenai.ml.util.IOUtils; import org.allenai.ml.util.Indexer; import org.nustaq.serialization.FSTObjectInput; import org.nustaq.serialization.FSTObjectOutput; @Slf4j public class ExtractReferences { public static final String authUnit = "\\p{Lu}[\\p{L}'`\\-]+"; public static final String authOneName = authUnit + "(?: " + authUnit + ")?"; //space and repetition for things like De Mori public static final String authLastCommaInitial = authOneName + ", (?:\\p{Lu}\\.-? ?)+"; public static final String authConnect = "(?:; |, |, and |; and | and )"; public static final String authInitialsLast = "(?:\\p{Lu}\\.?(?:-| )?)+ " + authOneName; public static final String authInitialsLastList = authInitialsLast + "(?:" + authConnect + authInitialsLast + ")*"; public static final String authPlain = authOneName + "(?:\\p{Lu}\\. )?" + authOneName; public static final String authPlainList = authPlain + "(?:(?:, and|,) (?:" + authPlain + "))*"; //pattern for matching single author name, format as in Jones, C. M. public static final String authGeneral = "\\p{Lu}[\\p{L}\\.'`\\- ]+"; public static final String authGeneralList = authGeneral + "(?:(?:; |, |, and |; and | and )" + authGeneral + ")*"; // patterns for mentions private static final String numberOrRangeRe = "(?:[1-9][0-9]*(?: *- *[1-9][0-9]*)?)"; private static final String separatorRe = "(?: *[,;|] *)"; private static final String citeCharactersRe = numberOrRangeRe + "(?:" + separatorRe + numberOrRangeRe + ")*"; public static final Pattern mentions = Pattern.compile( "(?:" + citeCharactersRe + ")|" + "(?:\\[" + citeCharactersRe + "\\])|" + "(?:\\(" + citeCharactersRe + "\\))" ); private ArrayList<BibStractor> extractors = null; public static Pattern pBracket = Pattern.compile("\\[([0-9]+)\\](.*)"); public static Pattern pDot = Pattern.compile("([0-9]+)\\.(.*)"); CheckReferences cr; final CRFBibRecordParser bibCRFRecordParser; public static final String DATA_VERSION = "0.3-BIB"; // Faster serialization public ExtractReferences(String gazFile) throws IOException { this(new FileInputStream(gazFile)); } public ExtractReferences(String gazFile, String bibModelFile) throws IOException { this(new FileInputStream(gazFile), new DataInputStream(new FileInputStream(bibModelFile))); } public ExtractReferences(final InputStream is) throws IOException { this(is, null); } public ExtractReferences(final InputStream is, final DataInputStream bibCRFModel) throws IOException { this(is, bibCRFModel, null); } public ExtractReferences( final InputStream is, final DataInputStream bibCRFModel, final InputStream gazCacheInputStream ) throws IOException { if(gazCacheInputStream != null) { try(final FSTObjectInput in = new FSTObjectInput(gazCacheInputStream)) { cr = (CheckReferences)in.readObject(); } catch(final Exception e) { log.warn("Could not load gazetteer from cache. Loading it slowly instead.", e); } } if(cr == null) cr = new CheckReferences(is); extractors = new ArrayList<>(); if(bibCRFModel != null) { final CRFModel<String, String, String> bibCRF = loadModel(bibCRFModel); bibCRFRecordParser = new CRFBibRecordParser(bibCRF); extractors.addAll(Arrays.asList( new NumberCloseParen(new Class [] { NumberCloseParenBibRecordParser.class, CRFBibRecordParser.class}), new BracketNumber(new Class [] { BracketNumberInitialsQuotedBibRecordParser.class, CRFBibRecordParser.class}), new NamedYear(new Class [] { NamedYearBibRecordParser.class, CRFBibRecordParser.class}), new NamedYear(new Class [] { NamedYearInParensBibRecordParser.class, CRFBibRecordParser.class}), new NumberDot(new Class [] { NumberDotYearParensBibRecordParser.class, CRFBibRecordParser.class}), new NumberDot(new Class [] { NumberDotAuthorNoTitleBibRecordParser.class, CRFBibRecordParser.class}), new NumberDot(new Class [] { NumberDotYearNoParensBibRecordParser.class, CRFBibRecordParser.class}), new BracketNumber(new Class [] { BracketNumberInitialsYearParensCOMMAS.class, CRFBibRecordParser.class}), new BracketNumber(new Class [] { BracketNumberBibRecordParser.class, CRFBibRecordParser.class}), new BracketName(new Class [] { BracketNameBibRecordParser.class, CRFBibRecordParser.class}) )); extractors.addAll(Arrays.asList( new BracketNumber(new Class [] {CRFBibRecordParser.class}), new NumberDot(new Class [] {CRFBibRecordParser.class}), new NumberDotNaturalLineBreaks(new Class [] {CRFBibRecordParser.class}), new NamedYear(new Class [] {CRFBibRecordParser.class}), new BracketName(new Class [] {CRFBibRecordParser.class}))); } else { bibCRFRecordParser = null; extractors.addAll(Arrays.asList( new BracketNumber(new Class [] {BracketNumberInitialsQuotedBibRecordParser.class}), new NamedYear(new Class [] {NamedYearBibRecordParser.class}), new NamedYear(new Class [] {NamedYearInParensBibRecordParser.class}), new NumberDot(new Class [] {NumberDotYearParensBibRecordParser.class}), new NumberDot(new Class [] {NumberDotAuthorNoTitleBibRecordParser.class}), new NumberDot(new Class [] {NumberDotYearNoParensBibRecordParser.class}), new BracketNumber(new Class [] {BracketNumberInitialsYearParensCOMMAS.class}), new BracketNumber(new Class [] {BracketNumberBibRecordParser.class}), new BracketName(new Class [] {BracketNameBibRecordParser.class}))); } } public static ExtractReferences createAndWriteGazCache( final InputStream is, final DataInputStream bibCRFModel, final OutputStream gazCacheFileOutputStream ) throws IOException { val result = new ExtractReferences(is, bibCRFModel); final FSTObjectOutput out = new FSTObjectOutput(gazCacheFileOutputStream); out.writeObject(result.cr); return result; } public static CRFModel<String, String, String> loadModel( DataInputStream dis ) throws IOException { IOUtils.ensureVersionMatch(dis, ExtractReferences.DATA_VERSION); val stateSpace = StateSpace.load(dis); Indexer<String> nodeFeatures = Indexer.load(dis); Indexer<String> edgeFeatures = Indexer.load(dis); Vector weights = DenseVector.of(IOUtils.loadDoubles(dis)); ParserLMFeatures plf = null; GazetteerFeatures gf = null; try(FSTObjectInput in = new FSTObjectInput(dis)) { try { plf = (ParserLMFeatures)in.readObject(); } catch (final Exception e) { // do nothing // but now plf is NULL. Is that OK? } try { gf = (GazetteerFeatures)in.readObject(); } catch (final Exception e) { log.info("Failed to load kermit gazetteer with this error:", e); } if (gf != null) log.info("kermit gazetteer successfully loaded."); else log.info("could not load kermit gazetter"); } val predExtractor = new ReferencesPredicateExtractor(plf); predExtractor.setGf(gf); val featureEncoder = new CRFFeatureEncoder<String, String, String>(predExtractor, stateSpace, nodeFeatures, edgeFeatures); val weightsEncoder = new CRFWeightsEncoder<String>(stateSpace, nodeFeatures.size(), edgeFeatures.size()); return new CRFModel<String, String, String>(featureEncoder, weightsEncoder, weights); } public static Pattern authStrToPat(String s) { if(s == null || s.length() == 0) s = ""; return Pattern.compile(s, Pattern.CASE_INSENSITIVE); } //returns pattern-ready form of author private static String cleanAuthString(String s) { return s.replaceAll("\\p{P}", ".");//allow anything for any punctuation } private static final Pattern yearPattern = Pattern.compile("[1-2][0-9][0-9][0-9]"); public static int extractRefYear(String sYear) { final Matcher mYear = RegexWithTimeout.matcher(yearPattern, sYear); int a = 0; while (mYear.find()) { try { a = Integer.parseInt(mYear.group().trim()); } catch (final NumberFormatException e) { // do nothing } if (a > BibRecord.MINYEAR && a < BibRecord.MAXYEAR) return a; } return a; } private static final Pattern firstNamesPattern = Pattern.compile( "\\p{javaUpperCase}{1,3}|" + "(\\p{javaUpperCase}\\.){1,3}|" + "(\\p{javaUpperCase}\\s+){0,2}(\\p{javaUpperCase})|" + "(\\p{javaUpperCase}\\.\\s+){0,2}(\\p{javaUpperCase}\\.)"); /** * Takes in a string mentioning several authors, returns normalized list of authors * * @param authString * @return */ public static List<String> authorStringToList(String authString) { authString = authString.trim(); // remove punctuation at the end, all punctuation but . authString = authString.replaceAll("[\\p{Punct}&&[^.]]*$", ""); // remove punctuation at the beginning authString = authString.replaceAll("^\\p{Punct}*", ""); // remove "et al" at the end authString = authString.replaceAll("[\\s\\p{Punct}]*[eE][tT]\\s+[aA][lL].?$", ""); // remove "etc" at the end authString = authString.replaceAll("[\\s\\p{Punct}]*[eE][tT][cC].?$", ""); // find out the top-level separator of names final String mainSplitString; if(authString.contains(";")) mainSplitString = ";"; else mainSplitString = ","; // replace "and" with the top level separator authString = authString.replaceAll("\\b[aA][nN][dD]\\b|&", mainSplitString); // split into names final String[] names = authString.split(mainSplitString); // clean up the names for(int i = 0; i < names.length; ++i) { names[i] = names[i].trim(). // clean up names that start with punctuation replaceAll("^\\p{Punct}\\s+", ""); } // Some look like this: "Divakaran, A., Forlines, C., Lanning, T., Shipman, S., Wittenburg, K." // If we split by comma, we need to make sure to glue these back together. if(mainSplitString.equals(",")) { for(int i = 1; i < names.length; ++i) { if(firstNamesPattern.matcher(names[i]).matches()) { names[i - 1] = names[i] + " " + names[i - 1]; names[i] = ""; // We'll clean up empty strings later. i += 1; } } } // see if we have to reorder first and last names int invertAroundCommaCount = 0; int invertAroundSpaceCount = 0; int doNothingCount = 0; for(final String name : names) { if(name.isEmpty()) continue; if(name.contains(",")) { invertAroundCommaCount += 1; } else { final String[] individualNames = name.split("\\s+"); // If the last individual name looks like not-a-last-name, we assume we have to invert. if(firstNamesPattern.matcher(individualNames[individualNames.length - 1]).matches()) invertAroundSpaceCount += 1; else doNothingCount += 1; } } // invert, if we have to if(invertAroundCommaCount > invertAroundSpaceCount && invertAroundCommaCount > doNothingCount) { // invert around comma for(int i = 0; i < names.length; ++i) { final String[] parts = names[i].split("\\s*,\\s*"); if(parts.length == 2) names[i] = parts[1] + " " + parts[0]; } } else if(invertAroundSpaceCount > invertAroundCommaCount && invertAroundSpaceCount > doNothingCount) { // invert around space, i.e., make Johnson M into M Johnson final StringBuilder b = new StringBuilder(128); for(int i = 0; i < names.length; ++i) { final String[] parts = names[i].split("\\s+"); b.append(parts[parts.length - 1]); b.append(' '); for(int j = 0; j < parts.length - 1; ++j) { b.append(parts[j]); b.append(' '); } names[i] = b.toString().trim(); b.setLength(0); } } // strip out empty strings return Arrays.asList(names).stream().filter(s -> !s.isEmpty()).collect(Collectors.toList()); } private static <T> List<T> removeNulls(List<T> in) { return in.stream().filter(a -> (a != null)).collect(Collectors.toList()); } private static String getAuthorLastName(String authName) { int idx = authName.lastIndexOf(" "); return authName.substring(idx + 1); } private static int refStart(List<String> paper) { for (int i = paper.size() / 3; i < paper.size(); i++) { //heuristic, assume refs start at least 1/3 into doc String s = paper.get(i); if (s.endsWith("References") || s.endsWith("Citations") || s.endsWith("Bibliography") || s.endsWith("Bibliographie") || s.endsWith("REFERENCES") || s.endsWith("CITATIONS") || s.endsWith("BIBLIOGRAPHY") || s.endsWith("BIBLIOGRAPHIE")) return i; else if (s.contains("References<lb>") || s.contains("Citations<lb>") || s.contains("Bibliography<lb>") || s.contains("Bibliographie<lb>") || s.contains("REFERENCES<lb>") || s.contains("CITATIONS<lb>") || s.contains("BIBLIOGRAPHY<lb>") || s.contains("BIBLIOGRAPHIE<lb>")) { return i - 1; } } return -1; } public static int getIdxOf(List<BibRecord> bib, String citeStr) { //note: slow for (int i = 0; i < bib.size(); i++) { if (bib.get(i).citeRegEx.matcher(citeStr).matches()) return i; } return -1; } public static Pair<Integer, Integer> shortCiteSearch(int yearPos, int year, String s, List<BibRecord> bib) { int start = -1; int idx = -1; int ct = 0; for(BibRecord br : bib) { Matcher m = RegexWithTimeout.matcher(br.shortCiteRegEx, s); if(m.find()) { //TODO: handle multiple matches if(m.start() > yearPos) continue; start = m.start(); idx = ct; break; } ct++; } return Tuples.pair(start, idx); } //note, also replaces <lb> with spaces in lines with found references public static List<CitationRecord> findCitations(List<String> paper, List<BibRecord> bib, BibStractor bs) { ArrayList<CitationRecord> out = new ArrayList<>(); Pattern p = Pattern.compile(bs.getCiteRegex()); Pattern pRange = Pattern.compile("([1-9][0-9]*)\\p{Pd}([1-9][0-9]*)"); int stop = refStart(paper); //stop at start of refs if (stop < 0) stop = paper.size(); //start of refs not found (should never happen for non-null bibliography...) for (int i = 0; i < stop; i++) { String s = paper.get(i).replaceAll("-<lb>", "").replaceAll("<lb>", " "); paper.set(i, s); Matcher m = RegexWithTimeout.matcher(p, s); while (m.find()) { String citationMeat = m.group(1); if(citationMeat == null) citationMeat = m.group(2); String[] citations = citationMeat.split(bs.getCiteDelimiter()); for (final String citation : citations) { Matcher mRange = RegexWithTimeout.matcher(pRange, citation); if(mRange.matches()) { //special case for ranges int st = Integer.parseInt(mRange.group(1)); int end = Integer.parseInt(mRange.group(2)); for(int j=st;j<=end;j++) { if(Thread.interrupted()) throw new Parser.ParsingTimeout(); int idx = getIdxOf(bib, j + ""); if (idx >= 0) { out.add(new CitationRecord(idx, paper.get(i), m.start(), m.end())); } } } else { int idx = getIdxOf(bib, citation.trim()); if (idx >= 0) { int start = m.start(); // Some citeRegexes depend on context, specifically, they only work at the end of a // sentence. That means they have to include the preceding period in the citeRegex, // which makes m.start() point to the period. To avoid this, we go to the next // character. if(paper.get(i).charAt(m.start()) == '.') start += 1; out.add(new CitationRecord(idx, paper.get(i), start, m.end())); } } } } //short-cites are assumed to be e.g.: Etzioni et al. (2005) if(bs.getShortCiteRegex() != null) { Pattern p2 = Pattern.compile(bs.getShortCiteRegex()); Matcher m2 = RegexWithTimeout.matcher(p2, s); while(m2.find()) { Pair<Integer, Integer> shct = shortCiteSearch(m2.start(), Integer.parseInt(m2.group(1).substring(0, 4)), s, bib); int start = shct.getOne(); int idx = shct.getTwo(); if(start > 0) { out.add(new CitationRecord(idx, paper.get(i), start, m2.end()+1)); } } } } return out; } public int numFound(List<BibRecord> brs) { int i = 0; for (BibRecord br : brs) { if (cr.hasPaper(br.title, br.author, br.year, br.venue)) i++; } return i; } public int longestIdx(List<BibRecord>[] results) { int maxLen = -1; int idx = -1; for (int i = 0; i < results.length; i++) { int f = 10000 * numFound(results[i]) + results[i].size(); //order by num found, then by size if (f > maxLen) { idx = i; maxLen = f; } } // log.info("chose " + idx + " with " + maxLen); return idx; } //heuristic public boolean refEnd(String s) { if (s.endsWith("Appendix") || s.endsWith("APPENDIX")) return true; else return false; } private static List<BibRecord> clean(final List<BibRecord> brs) { val result = new ArrayList<BibRecord>(brs.size()); // remove punctuation at the beginning and end of the title for(final BibRecord b : brs) { final String newTitle = b.title.trim().replaceAll("^\\p{P}", "").replaceAll("[\\p{P}&&[^)]]$", ""); if( !newTitle.isEmpty() && // delete empty titles newTitle.length() < 512 && // delete absurdly long bib entries (b.venue == null || b.venue.length() < 512) && (b.author == null || b.author.stream().allMatch(a -> a.length() < 512)) ) { result.add(b.withTitle(newTitle)); } } return result; } /** * Returns the list of BibRecords, plus the extractor that produced them (in order to enable * citation parsing) */ public Pair<List<BibRecord>, BibStractor> findReferences(List<String> paper) { int start = refStart(paper) + 1; List<BibRecord>[] results = new ArrayList[extractors.size()]; for (int i = 0; i < results.length; i++) results[i] = new ArrayList<>(); StringBuilder sb = new StringBuilder(); for (int i = start; i < paper.size(); i++) { if(refEnd(paper.get(i))) break; sb.append("<bb>"); sb.append(paper.get(i)); } String text = sb.toString(); for (int i = 0; i < results.length; i++) { results[i] = extractors.get(i).parse(text); results[i] = clean(results[i]); } int idx = longestIdx(results); //log.info("references: " + results[idx].toString()); return Tuples.pair(results[idx], extractors.get(idx)); } public interface BibRecordParser { BibRecord parseRecord(String line); } public abstract class BibStractor { final BibRecordParser [] recParser; BibStractor(Class [] c) { BibRecordParser b = null; recParser = new BibRecordParser[c.length]; for(int i=0; i<c.length; i++) { if(c[i] == CRFBibRecordParser.class) { //special case b = bibCRFRecordParser; } else { try { b = (BibRecordParser) c[i].newInstance(); } catch (final Exception e) { log.warn("Exception while creating BibStractor", e); } } recParser[i] = b; } } BibStractor() { recParser = null; } public abstract List<BibRecord> parse(String source); public abstract String getCiteRegex(); public String getShortCiteRegex() { return null; } //may return null for bibstractors without short cites public abstract String getCiteDelimiter(); } private static class DefaultBibRecordParser implements BibRecordParser { public BibRecord parseRecord(String line) { return new BibRecord(line, null, null, null, null, 0); } } private static class BracketNumberInitialsQuotedBibRecordParser implements BibRecordParser { private static final String regEx = "\\[([0-9]+)\\] (.*)(?:,|\\.|:) [\\p{Pi}\"\']+(.*),[\\p{Pf}\"\']+ (?:(?:I|i)n )?(.*)\\.?"; private static final Pattern pattern = Pattern.compile(regEx); public BracketNumberInitialsQuotedBibRecordParser() { } //example: // "[1] E. Chang and A. Zakhor, β€œScalable video data placement on parallel disk " //+ "arrays," in IS&T/SPIE Int. Symp. Electronic Imaging: Science and Technology, " //+ "Volume 2185: Image and Video Databases II, San Jose, CA, Feb. 1994, pp. 208–221." public BibRecord parseRecord(String line) { Matcher m = RegexWithTimeout.matcher(pattern, line.trim()); if (m.matches()) { return new BibRecord( m.group(3), authorStringToList(m.group(2)), m.group(4), Pattern.compile(m.group(1)), null, extractRefYear(m.group(4))); } else { return null; } } } private static class BracketNumberBibRecordParser implements BibRecordParser { private static final String regEx = "\\[([0-9]+)\\] (" + authInitialsLastList + ")\\. ([^\\.]+)\\. (?:(?:I|i)n )?(.*) ([1-2][0-9]{3})\\.( .*)?"; private static final Pattern pattern = Pattern.compile(regEx); public BracketNumberBibRecordParser() { } //example: //TODO public BibRecord parseRecord(String line) { Matcher m = RegexWithTimeout.matcher(pattern, line.trim()); if (m.matches()) { return new BibRecord( m.group(3), authorStringToList(m.group(2)), m.group(4), Pattern.compile(m.group(1)), null, extractRefYear(m.group(5))); } else { return null; } } } // Example: // 6) Farrell GC, Larter CZ. Nonalcoholic fatty liver disease: from steatosis to cirrhosis. // Hepatology 2006;43(Suppl. 1):S99-S112. private static class NumberCloseParenBibRecordParser implements BibRecordParser { private static final String uppercaseNameUnit = authUnit; private static final String anycaseNameUnit = "[\\p{L}'`\\-]+"; private static final String multipleNameUnits = "(?:" + anycaseNameUnit + " +)*" + uppercaseNameUnit; private static final String initialsLastAuthor = multipleNameUnits + " +\\p{Lu}+"; private static final String multipleInitialsLastAuthors = initialsLastAuthor + "(?:" + authConnect + initialsLastAuthor + ")*"; private static final String regEx = ( "([0-9]+)\\)" + // "6)" " +" + "(" + multipleInitialsLastAuthors + ")(?:, et al)?\\." + // "Farrell GC, Larter CZ." " +" + "([^\\.]+[\\.\\?])" + // "Nonalcoholic fatty liver disease: from steatosis to cirrhosis." " +" + "(.*) +([1-2][0-9]{3});" + // "Hepatology 2006;" ".*"); // "43(Suppl. 1):S99-S112." private static final Pattern pattern = Pattern.compile(regEx); public NumberCloseParenBibRecordParser() { } public BibRecord parseRecord(final String line) { Matcher m = RegexWithTimeout.matcher(pattern, line.trim()); if (m.matches()) { String title = m.group(3); if(title.endsWith(".")) title = title.substring(0, title.length() - 1); return new BibRecord( title, authorStringToList(m.group(2)), m.group(4), Pattern.compile(m.group(1)), null, extractRefYear(m.group(5))); } else { return null; } } } static class NumberDotAuthorNoTitleBibRecordParser implements BibRecordParser { private static final String regEx = "([0-9]+)\\. +(" + authLastCommaInitial + "(?:; " + authLastCommaInitial + ")*)" + " ([^0-9]*) ([1-2][0-9]{3})(?:\\.|,[0-9, ]*)(?:.*)"; private static final Pattern pattern = Pattern.compile(regEx); public NumberDotAuthorNoTitleBibRecordParser() { } //example: //1. Jones, C. M.; Henry, E. R.; Hu, Y.; Chan C. K; Luck S. D.; Bhuyan, A.; Roder, H.; Hofrichter, J.; //Eaton, W. A. Proc Natl Acad Sci USA 1993, 90, 11860. public BibRecord parseRecord(String line) { Matcher m = RegexWithTimeout.matcher(pattern, line.trim()); if (m.matches()) { return new BibRecord( "", authorStringToList(m.group(2)), m.group(3), Pattern.compile(m.group(1)), null, extractRefYear(m.group(4))); } else { return null; } } } private static class NumberDotYearParensBibRecordParser implements BibRecordParser { private static final String regEx = "([0-9]+)\\. ([^:]+): ([^\\.]+)\\. (?:(?:I|i)n: )?(.*) \\([^)]*([0-9]{4})\\)\\.?(?: .*)?"; //last part is for header break private static final Pattern pattern = Pattern.compile(regEx); public NumberDotYearParensBibRecordParser() { } //example: //TODO public BibRecord parseRecord(String line) { Matcher m = RegexWithTimeout.matcher(pattern, line.trim()); if (m.matches()) { return new BibRecord( m.group(3), authorStringToList(m.group(2)), m.group(4), Pattern.compile(m.group(1)), null, extractRefYear(m.group(5))); } else { return null; } } } private static class NumberDotYearNoParensBibRecordParser implements BibRecordParser { private static final String regEx = "([0-9]+)\\. (" + authInitialsLastList + "). ([^\\.]+)\\. (?:(?:I|i)n: )?(.*) ([1-2][0-9]{3}).( .*)?"; //last part for header break private static final Pattern pattern = Pattern.compile(regEx); public NumberDotYearNoParensBibRecordParser() { } //example: //TODO public BibRecord parseRecord(String line) { Matcher m = RegexWithTimeout.matcher(pattern, line.trim()); if (m.matches()) { return new BibRecord( m.group(3), authorStringToList(m.group(2)), m.group(4), Pattern.compile(m.group(1)), null, extractRefYear(m.group(5))); } else { return null; } } } private static class NamedYearBibRecordParser implements BibRecordParser { private static final String regEx = "(" + authGeneralList + ") +([1-2][0-9]{3}[a-z]?)\\. ([^\\.]+)\\. (?:(?:I|i)n )?(.*)\\.?"; private static final Pattern pattern = Pattern.compile(regEx); public NamedYearBibRecordParser() { } //example: //STONEBREAKER, M. 1986. A Case for Shared Nothing. Database Engineering 9, 1, 4–9. public BibRecord parseRecord(String line) { Matcher m = RegexWithTimeout.matcher(pattern, line.trim()); if (m.matches()) { final List<String> authors = authorStringToList(m.group(1)); final int year = Integer.parseInt(m.group(2).substring(0, 4)); final String nameStr = getCiteAuthorFromAuthors(authors); final String citeStr = nameStr + ",? " + m.group(2); return new BibRecord(m.group(3), authors, m.group(4), authStrToPat(citeStr), authStrToPat(nameStr), year); } else { return null; } } } private static class NamedYearInParensBibRecordParser implements BibRecordParser { private static final String regEx = "(" + authGeneralList + ") +\\(([1-2][0-9]{3}[a-z]?)\\)\\. ([^\\.]+)\\. (?:(?:I|i)n )?(.*)\\.?"; private static final Pattern pattern = Pattern.compile(regEx); public NamedYearInParensBibRecordParser() { } //example: //STONEBREAKER, M. 1986. A Case for Shared Nothing. Database Engineering 9, 1, 4–9. public BibRecord parseRecord(String line) { Matcher m = RegexWithTimeout.matcher(pattern, line.trim()); if (m.matches()) { List<String> authors = authorStringToList(m.group(1)); int year = Integer.parseInt(m.group(2).substring(0, 4)); String nameStr = getCiteAuthorFromAuthors(authors); String citeStr = nameStr + ",? " + m.group(2); return new BibRecord(m.group(3), authors, m.group(4), authStrToPat(citeStr), authStrToPat(nameStr), year); } else { return null; } } } private static class BracketNumberInitialsYearParensCOMMAS implements BibRecordParser { private static final String regEx1 = "\\[([0-9]+)\\] (" + authInitialsLastList + ")(?:,|\\.) ([^\\.,]+)(?:,|\\.) (?:(?:I|i)n )?(.*)\\(.*([1-2][0-9]{3}).*\\).*"; private static final Pattern pattern1 = Pattern.compile(regEx1); private static final String regEx2 = "\\[([0-9]+)\\] (" + authInitialsLastList + ")(?:,|\\.) ([^\\.,]+)(?:,|\\.) (?:(?:I|i)n )?(.*), ((?:20|19)[0-9]{2})(?:\\.|,).*"; private static final Pattern pattern2 = Pattern.compile(regEx2); public BracketNumberInitialsYearParensCOMMAS() { } //example: // [1] S. Abiteboul, H. Kaplan, and T. Milo, Compact labeling schemes for ancestor queries. Proc. 12th Ann. ACM-SIAM Symp. // on Discrete Algorithms (SODA 2001), 547-556. public BibRecord parseRecord(String line) { Matcher m = RegexWithTimeout.matcher(pattern1, line.trim()); Matcher m2 = RegexWithTimeout.matcher(pattern2, line.trim()); if (m.matches()) { return new BibRecord( m.group(3), authorStringToList(m.group(2)), m.group(4), Pattern.compile(m.group(1)), null, extractRefYear(m.group(5))); } else if (m2.matches()) { return new BibRecord( m2.group(3), authorStringToList(m2.group(2)), m2.group(4), Pattern.compile(m2.group(1)), null, extractRefYear(m2.group(5))); } else { return null; } } } private static class BracketNameBibRecordParser implements BibRecordParser { private static final String regEx1 = "\\[([^\\]]+)\\] (" + authInitialsLastList + ")(?:,|\\.) ([^\\.,]+)(?:,|\\.) (?:(?:I|i)n )?(.*), ([1-2][0-9]{3})\\."; private static final Pattern pattern1 = Pattern.compile(regEx1); private static final String regEx2 = "\\[([^\\]]+)\\] (" + authGeneralList + ")(?:,|\\.) ([^\\.,]+)(?:,|\\.) (?:(?:I|i)n )?(.*),? ([1-2][0-9]{3})\\..*"; private static final Pattern pattern2 = Pattern.compile(regEx2); public BracketNameBibRecordParser() { } //example: // [Magnini et al., 2002] B. Magnini, M. Negri, R. Prevete, and // H. Tanev. Is it the right answer? exploiting web redundancy // for answer validation. In ACL, 2002. public BibRecord parseRecord(String line) { Matcher m = RegexWithTimeout.matcher(pattern1, line.trim()); Matcher m2 = RegexWithTimeout.matcher(pattern2, line.trim()); if (m.matches()) { if (m.group(1).matches("[0-9]+")) //don't override BracketNumber return null; return new BibRecord( m.group(3), authorStringToList(m.group(2)), m.group(4), authStrToPat(cleanAuthString(m.group(1))), null, extractRefYear(m.group(5))); } else if (m2.matches()) { if (m2.group(1).matches("[0-9]+")) //don't override BracketNumber return null; return new BibRecord( m2.group(3), authorStringToList(m2.group(2)), m2.group(4), authStrToPat(cleanAuthString(m2.group(1))), null, extractRefYear(m2.group(5))); } else { return null; } } } //in regex form public static String getCiteAuthorFromAuthors(List<String> authors) { if(authors == null || authors.size()==0) return null; if (authors.size() > 2) { return cleanAuthString(getAuthorLastName(authors.get(0))) + " et al\\."; } else if (authors.size() == 1) { return cleanAuthString(getAuthorLastName(authors.get(0))); } else if (authors.size() == 2) { return cleanAuthString(getAuthorLastName(authors.get(0))) + " and " + cleanAuthString(getAuthorLastName(authors.get(1))); } return null; } public class NamedYear extends BibStractor { private final static String citeRegex = "(?:\\[|\\()([^\\[\\(\\]\\)]+ [1-2][0-9]{3}[a-z]?)+(?:\\]|\\))"; private final static String shortCiteRegex = "(?:\\[|\\()([1-2][0-9]{3}[a-z]?)(?:\\]|\\))"; private final static String citeDelimiter = "; ?"; NamedYear(Class [] c) { super(c); } public String getCiteRegex() { return citeRegex; } @Override public String getShortCiteRegex() { return shortCiteRegex; } public String getCiteDelimiter() { return citeDelimiter; } public List<BibRecord> parse(String line) { if (line.startsWith("<bb>")) line = line.substring(4); String[] citesa = line.split("<bb>"); List<String> cites = Arrays.asList(citesa); List<BibRecord> out = new ArrayList<BibRecord>(); boolean first = true; for (String s : cites) { s = s.replaceAll("-<lb>", "").replaceAll("<lb>", " ").trim(); if(first) { //don't overwrite number-bracket or number-dot if(s.length() > 0) if(RegexWithTimeout.matcher(pBracket, s).matches() || RegexWithTimeout.matcher(pDot, s).matches()) { return removeNulls(out); } else { first = false; } } for(int i=0; i<recParser.length;i++) { BibRecord br = this.recParser[i].parseRecord(s); if(br!=null) { out.add(br); break; } } } out = removeNulls(out); return out; } } private class NumberDotNaturalLineBreaks extends NumberDot { NumberDotNaturalLineBreaks(Class [] c) { super(c); } @Override public List<BibRecord> parse(String line) { return parseWithGivenBreaks(line, true); } } private class NumberDot extends BracketNumber { NumberDot(Class [] c) { super(c); } protected List<BibRecord> parseWithGivenBreaks(String line, boolean bigBreaks) { if(!bigBreaks) line = line.replaceAll("<bb>", "<lb>"); else line = line.replaceAll("<lb>", " "); int i = 0; String preTag = "<bb>"; if(!bigBreaks) preTag = "<lb>"; String tag = preTag + (++i) + ". "; List<String> cites = new ArrayList<String>(); int st = line.indexOf(tag); while (st >= 0) { tag = preTag + (++i) + ". "; int end = line.indexOf(tag, st); if (end > 0) { cites.add(line.substring(st, end)); } else { cites.add(line.substring(st)); } st = end; } List<BibRecord> out = new ArrayList<BibRecord>(); for (String s : cites) { s = s.replaceAll("-<lb>", "").replaceAll("<lb>", " "); s = s.replaceAll("-<bb>", "").replaceAll("<bb>", " "); for(int j=0; j<recParser.length;j++) { BibRecord br = this.recParser[j].parseRecord(s); if(br!=null) { out.add(br); break; } } } out = removeNulls(out); return out; } public List<BibRecord> parse(String line) { return parseWithGivenBreaks(line, false); } } private class BracketNumber extends BibStractor { protected final String citeRegex = "(?:" + "[\\[\\(]" + // open bracket/paren "(" + citeCharactersRe + ")" + // the meat "[\\]\\)]" + // close bracket/paren ")|(?:" + // or "\\.⍐" + // period, followed by superscript "(" + citeCharactersRe + ")" + // the meat "⍗" + // end of superscript ")"; protected final String citeDelimiter = separatorRe; BracketNumber(Class[] c) { super(c); } public String getCiteRegex() { return citeRegex; } public String getCiteDelimiter() { return citeDelimiter; } public List<BibRecord> parse(String line) { line = line.replaceAll("<bb>", "<lb>"); int i = 0; String tag = "[" + (++i) + "]"; List<String> cites = new ArrayList<String>(); int st = line.indexOf(tag); while (st >= 0) { tag = "<lb>[" + (++i) + "]"; int end = line.indexOf(tag, st); if (end > 0) { cites.add(line.substring(st, end)); } else { cites.add(line.substring(st)); } st = end; } List<BibRecord> out = new ArrayList<BibRecord>(); boolean first = true; for (String s : cites) { s = s.replaceAll("-<lb>(\\p{Ll})", "$1").replaceAll("<lb>", " ").trim(); for(int j=0; j<recParser.length;j++) { BibRecord br = this.recParser[j].parseRecord(s); if(br!=null) { out.add(br); break; } } } out = removeNulls(out); return out; } } private class NumberCloseParen extends BibStractor { NumberCloseParen(Class[] c) { super(c); } private final String citeRegex = "\\(([0-9, \\p{Pd}]+)\\)"; public String getCiteRegex() { return citeRegex; } private final String citeDelimiter = "(,| |;)+"; public String getCiteDelimiter() { return citeDelimiter; } public List<BibRecord> parse(String line) { line = line.replaceAll("<bb>", "<lb>"); int i = 0; String tag = (++i) + ")"; List<String> cites = new ArrayList<String>(); int st = line.indexOf(tag); while (st >= 0) { tag = "<lb>" + (++i) + ")"; int end = line.indexOf(tag, st); if (end > 0) { cites.add(line.substring(st, end)); } else { cites.add(line.substring(st)); } st = end; } List<BibRecord> out = new ArrayList<BibRecord>(); boolean first = true; for (String s : cites) { s = s.replaceAll("-<lb>(\\p{Ll})", "$1").replaceAll("<lb>", " ").trim(); for(int j=0; j<recParser.length;j++) { BibRecord br = this.recParser[j].parseRecord(s); if(br!=null) { out.add(br); break; } } } out = removeNulls(out); return out; } } private class BracketName extends BibStractor { protected final String citeRegex = "\\[([^\\]]+)\\]"; protected final String citeDelimiter = "; ?"; BracketName(Class [] c) { super(c); } public String getCiteRegex() { return citeRegex; } public String getCiteDelimiter() { return citeDelimiter; } public List<BibRecord> parse(String line) { if (line.startsWith("<bb>")) line = line.substring(4); String[] citesa = line.split("<bb>"); List<String> cites = Arrays.asList(citesa); List<BibRecord> out = new ArrayList<BibRecord>(); boolean first = true; for (String s : cites) { s = s.replaceAll("-<lb>", "").replaceAll("<lb>", " ").trim(); if(first) { //don't overwrite number-bracket or number-dot if(s.length() > 0) if(RegexWithTimeout.matcher(pBracket, s).matches() || RegexWithTimeout.matcher(pDot, s).matches()) { return removeNulls(out); } else { first = false; } } for(int i=0; i<recParser.length;i++) { BibRecord br = this.recParser[i].parseRecord(s); if(br!=null) { out.add(br); break; } } } out = removeNulls(out); return out; } } }
41,282
34.375321
146
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/ExtractedMetadata.java
package org.allenai.scienceparse; import com.gs.collections.api.tuple.Pair; import com.gs.collections.impl.tuple.Tuples; import lombok.Data; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.allenai.scienceparse.ParserGroundTruth.Paper; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.regex.Pattern; /** * Simple container for extracted metadata. * * @author dcdowney */ @Data @Slf4j public class ExtractedMetadata { public static final String titleTag = "T"; //label used in labeled data public static final String authorTag = "A"; //label used in labeled data public static final String yearTag = "Y"; //label used in labeled data (bibliography only) public static final String venueTag = "V"; //label used in labeled data (bibliography only) transient private static Pattern emailDelimitersRegex = Pattern.compile(",|\\||;"); public enum Source { INVALID, CRF, META } public Source source; public String title; public List<String> authors; public List<String> emails; //extracted by special (non-CRF) heuristic process public List<Section> sections; public List<BibRecord> references; public List<CitationRecord> referenceMentions; public int year; public String abstractText; public String creator; // program that created the PDF, i.e. LaTeX or PowerPoint or something else /** * Constructs ExtractedMetadata from given text and labels * * @param toks * @param labels */ public ExtractedMetadata(List<PaperToken> toks, List<String> labels) { List<LabelSpan> lss = getSpans(labels); authors = new ArrayList<String>(); for (LabelSpan ls : lss) { if (title == null && ls.tag.equals(titleTag)) { title = PDFToCRFInput.stringAt(toks, ls.loc); } else if (ls.tag.equals(authorTag)) { authors.add(PDFToCRFInput.stringAt(toks, ls.loc)); } } emails = getEmails(toks); } public ExtractedMetadata(String sTitle, List<String> sAuthors, Date cDate) { title = sTitle; authors = sAuthors; if (cDate != null) { Calendar cal = Calendar.getInstance(); cal.setTime(cDate); year = cal.get(Calendar.YEAR); } emails = new ArrayList<String>(); } public ExtractedMetadata(Paper p) { title = p.title; authors = Arrays.asList(p.authors); year = p.year; emails = new ArrayList<String>(); } //assumes token contains @ public static List<String> tokToMail(String tok) { ArrayList<String> out = new ArrayList<>(); if (!tok.contains("@")) { return null; } tok = tok.replaceAll("\\P{Print}", ""); if (tok.contains(":")) { if (tok.split(":").length > 1) tok = tok.split(":")[1]; } String[] parts = tok.split("@"); if (parts.length == 2) { String domain = parts[1]; String emailStrings = parts[0]; String[] emails = new String[1]; if ((emailStrings.startsWith("{") && emailStrings.endsWith("}")) || (emailStrings.startsWith("[") && emailStrings.endsWith ("]")) || emailStrings.contains(",") || emailStrings.contains("|")) { emailStrings = emailStrings.replaceAll("\\{|\\}|\\[|\\]", ""); emails = emailStrings.split(emailDelimitersRegex.pattern()); } else { emails[0] = emailStrings; } for (String email : emails) { out.add(email.trim() + "@" + domain); } } else { log.debug("e-mail parts not 2"); } return out; } public static List<String> getEmails(List<PaperToken> toks) { ArrayList<String> out = new ArrayList<>(); for (PaperToken t : toks) { if (t.getPdfToken() != null) { String stT = t.getPdfToken().token; if (stT != null && stT.contains("@")) out.addAll(tokToMail(stT)); } } return out; } public static List<LabelSpan> getSpans(List<String> labels) { ArrayList<LabelSpan> out = new ArrayList<LabelSpan>(); int st = -1; String curTag = ""; for (int i = 0; i < labels.size(); i++) { String lab = labels.get(i); if (lab.equals("O")) { st = -1; } else if (lab.startsWith("B_")) { st = i; curTag = lab.substring(2); } else if (lab.startsWith("I_")) { String t = lab.substring(2); if (!curTag.equals(t)) { //mis-matched tags, do not extract st = -1; } } else if (lab.startsWith("E_")) { String t = lab.substring(2); if (curTag.equals(t) && st >= 0) { LabelSpan ls = new LabelSpan(curTag, (Pair<Integer, Integer>) Tuples.pair(st, i + 1)); out.add(ls); st = -1; } } else if (lab.startsWith("W_")) { String t = lab.substring(2); LabelSpan ls = new LabelSpan(t, (Pair<Integer, Integer>) Tuples.pair(i, i + 1)); out.add(ls); st = -1; } } return out; } public void setYearFromDate(Date cDate) { Calendar cal = Calendar.getInstance(); cal.setTime(cDate); year = cal.get(Calendar.YEAR); } public String toString() { StringBuffer out = new StringBuffer("T: " + title + "\r\n"); authors.forEach((String a) -> out.append("A: " + a + "\r\n")); emails.forEach((String a) -> out.append("E: " + a + "\r\n")); return out.toString(); } @RequiredArgsConstructor public static class LabelSpan { public final String tag; public final Pair<Integer, Integer> loc; //(inclusive, exclusive) } }
5,571
28.956989
100
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/FallbackPaperSource.java
package org.allenai.scienceparse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; /** * A paper source that uses other paper sources, one after the other, to try to locate a paper. */ public class FallbackPaperSource extends PaperSource { private final static Logger logger = LoggerFactory.getLogger(FallbackPaperSource.class); private final PaperSource[] sources; public FallbackPaperSource(final PaperSource... sources) { this.sources = sources; } @Override public InputStream getPdf(final String paperId) throws IOException { // Try all but the last source. for(int i = 0; i < sources.length - 1; ++i) { final PaperSource source = sources[i]; try { return source.getPdf(paperId); } catch (final Exception e) { logger.info( "Getting paper {} from source {} failed, {} more sources to try", paperId, i, sources.length - i - 1); } } // Try the last source. final PaperSource source = sources[sources.length - 1]; return source.getPdf(paperId); } }
1,157
26.571429
95
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/GazetteerFeatures.java
package org.allenai.scienceparse; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.allenai.scienceparse.ExtractedMetadata.LabelSpan; import com.gs.collections.impl.map.mutable.primitive.ObjectIntHashMap; import com.gs.collections.impl.set.mutable.primitive.LongHashSet; import com.gs.collections.impl.tuple.Tuples; import lombok.extern.slf4j.Slf4j; /** * Holds gazetteers of journal names, person names, countries, etc. * Note: only retains gazetteer entries with length at most MAXLENGTH. * */ @Slf4j public class GazetteerFeatures implements Serializable { private static final long serialVersionUID = 1L; private LongHashSet [] hashSets; //each element represents a gazetteer, the long hashcodes of contained strings private String [] hashNames; private static int MAXLENGTH = 7; //maximum length (in words) of any gazetteer entry /** * Reads in string gazetteers, assumed to be one entry per line, one gazetteer per file in given directory. * @param inDir * @throws Exception */ public GazetteerFeatures(String inDir) throws IOException { File [] files = (new File(inDir)).listFiles(); hashSets = new LongHashSet[files.length]; hashNames = new String[files.length]; for(int i=0; i<files.length; i++) { hashSets[i] = readGazetteer(files[i]); hashNames[i] = files[i].getName(); } } //transform applied to all gazetteer entries private String t(String s) { return s.toLowerCase().replaceAll("\\p{P}+", " ").replaceAll(" +", " ").trim(); } public static boolean withinLength(String s) { int ct = 0; s = s.trim(); int idx = s.indexOf(" "); while(idx >=0) { if(++ct == MAXLENGTH) { return false; } idx = s.indexOf(" ", idx+1); } return true; } private LongHashSet readGazetteer(File f) throws IOException { BufferedReader brIn = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8")); String sLine; LongHashSet out = new LongHashSet(); while((sLine = brIn.readLine())!=null) { if(sLine.startsWith("#")||sLine.trim().length()==0) continue; if(!withinLength(sLine)) continue; out.add(StringLongHash.hash(t(sLine))); } brIn.close(); return out; } public int size() { return hashSets.length; } public int sizeOfSet(int set) { return hashSets[set].size(); } public boolean inSet(String s, int i) { long hc = StringLongHash.hash(t(s)); return hashSets[i].contains(hc); } //returns whether a string is in each gazetteer public boolean [] inSet(String s) { long hc = StringLongHash.hash(t(s)); boolean [] out = new boolean[hashSets.length]; Arrays.fill(out, false); for(int i=0; i<hashSets.length;i++) { if(hashSets[i].contains(hc)) out[i] = true; } return out; } //-1 if not found public int gazetteerNumber(String s) { for(int i=0;i<=hashSets.length;i++) { if(s.equals(hashNames[i])) return i; } return -1; } public String getStringSpan(List<String> ws, int start, int length) { StringBuffer sb = new StringBuffer(); for(int i=start;i<length+start; i++) { sb.append(ws.get(i) + " "); } return sb.toString().trim(); } public List<LabelSpan> getSpansForGaz(List<String> ws, int gn) { ArrayList<LabelSpan> out = new ArrayList<>(); for(int i=0; i<ws.size();i++) { for(int j=0; j<Math.min(MAXLENGTH, ws.size()+1-i); j++) { String query = getStringSpan(ws, i, j); if(inSet(query, gn)) { LabelSpan ls = new LabelSpan(hashNames[gn], Tuples.pair(i, i+j)); out.add(ls); } } } return out; } public List<LabelSpan> getSpans(List<String> ws) { ArrayList<LabelSpan> out = new ArrayList<>(); for(int i=0; i<this.hashSets.length; i++) { out.addAll(getSpansForGaz(ws, i)); } return out; } }
4,177
26.853333
113
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/MarkableFileInputStream.java
package org.allenai.scienceparse; import java.io.FileInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.nio.channels.FileChannel; class MarkableFileInputStream extends FilterInputStream { private FileChannel fileChannel; private static final long NOT_MARKED = -1; private static final long MARK_FAILED = -2; private long mark = NOT_MARKED; public MarkableFileInputStream(final FileInputStream fis) { super(fis); fileChannel = fis.getChannel(); mark(0); } @Override public boolean markSupported() { return true; } @Override public synchronized void mark(int readlimit) { try { mark = fileChannel.position(); } catch (IOException ex) { mark = MARK_FAILED; } } @Override public synchronized void reset() throws IOException { if(mark == NOT_MARKED) throw new IOException("not marked"); else if(mark == MARK_FAILED) throw new IOException("previous mark failed"); else fileChannel.position(mark); } @Override public void close() throws IOException { super.close(); } }
1,116
21.795918
61
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/PDFDocToPartitionedText.java
package org.allenai.scienceparse; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.gs.collections.api.list.ImmutableList; import com.gs.collections.api.map.primitive.DoubleIntMap; import com.gs.collections.api.map.primitive.MutableDoubleIntMap; import com.gs.collections.api.map.primitive.MutableFloatIntMap; import com.gs.collections.api.map.primitive.MutableObjectIntMap; import com.gs.collections.api.set.primitive.DoubleSet; import com.gs.collections.api.set.primitive.MutableDoubleSet; import com.gs.collections.api.tuple.Pair; import com.gs.collections.api.tuple.primitive.DoubleIntPair; import com.gs.collections.api.tuple.primitive.FloatIntPair; import com.gs.collections.impl.factory.primitive.DoubleIntMaps; import com.gs.collections.impl.factory.primitive.DoubleSets; import com.gs.collections.impl.factory.primitive.FloatIntMaps; import com.gs.collections.impl.map.mutable.primitive.ObjectIntHashMap; import com.gs.collections.impl.tuple.Tuples; import org.allenai.scienceparse.pdfapi.PDFDoc; import org.allenai.scienceparse.pdfapi.PDFLine; import org.allenai.scienceparse.pdfapi.PDFPage; import lombok.extern.slf4j.Slf4j; import org.allenai.scienceparse.pdfapi.PDFToken; @Slf4j public class PDFDocToPartitionedText { /** * Returns list of strings representation of this file. Breaks new lines when pdf line break larger than threshold. * All original line breaks indicated by <lb> * * @param pdf * @return */ public static List<String> getRaw(PDFDoc pdf) { ArrayList<String> out = new ArrayList<>(); StringBuilder s = new StringBuilder(); PDFLine prevLine = null; double qLineBreak = getRawBlockLineBreak(pdf); for (PDFPage p : pdf.getPages()) { for (PDFLine l : p.getLines()) { if (breakSize(l, prevLine) > qLineBreak) { String sAdd = s.toString(); if (sAdd.endsWith("<lb>")) sAdd = sAdd.substring(0, sAdd.length() - 4); out.add(sAdd); s = new StringBuilder(); } String sAdd = lineToString(l); if (sAdd.length() > 0) { s.append(sAdd); s.append("<lb>"); } prevLine = l; } //HACK(dcdowney): always break on new page. Should be safe barring "bad breaks" I think if (s.length() > 0) { String sAdd = s.toString(); if (sAdd.endsWith("<lb>")) sAdd = sAdd.substring(0, sAdd.length() - 4); out.add(sAdd); s = new StringBuilder(); } } return out; } public static float breakSize(PDFLine l2, PDFLine l1) { if (l2 == null || l1 == null) return 0.0f; float h1 = PDFToCRFInput.getH(l1); float h2 = PDFToCRFInput.getH(l2); return (PDFToCRFInput.getY(l2, true) - PDFToCRFInput.getY(l1, false)) / Math.min(h1, h2); } private static List<Double> getBreaks(PDFPage p) { PDFLine prevLine = null; ArrayList<Double> breaks = new ArrayList<>(); for (PDFLine l : p.getLines()) { double bs = breakSize(l, prevLine); if (bs > 0) { //<= 0 due to math, tables, new pages, should be ignored breaks.add(bs); } prevLine = l; } breaks.sort(Double::compare); return breaks; } private static List<Double> getBreaks(PDFDoc pdf) { ArrayList<Double> breaks = new ArrayList<>(); for (PDFPage p : pdf.getPages()) { breaks.addAll(getBreaks(p)); } breaks.sort(Double::compare); return breaks; } public static double getReferenceLineBreak(PDFDoc pdf) { List<Double> breaks = getBreaks(pdf); if(breaks.isEmpty()) return 1.0; int idx = (7 * breaks.size()) / 9; //hand-tuned threshold good for breaking references return breaks.get(idx); } public static double getRawBlockLineBreak(PDFDoc pdf) { List<Double> breaks = getBreaks(pdf); if(breaks.isEmpty()) return 1.0; int idx = (7 * breaks.size()) / 9; //hand-tuned threshold good for breaking papers return breaks.get(idx); } public static double getFirstPagePartitionBreak(PDFPage pdf) { List<Double> breaks = getBreaks(pdf); if(breaks.isEmpty()) return 1.0; int idx = (3 * breaks.size()) / 6; //hand-tuned threshold good for breaking first pages (abstracts) return breaks.get(idx) + 0.50; } private static String lineToString(PDFLine l) { StringBuilder sb = new StringBuilder(); for(PDFToken token : l.tokens) { sb.append(token.token); sb.append(' '); } return sb.toString().trim(); } private static String cleanLine(String s) { s = s.replaceAll("\r|\t|\n", " ").trim(); while (s.contains(" ")) s = s.replaceAll(" ", " "); return s; } public static String getFirstTextBlock(PDFDoc pdf) { PDFPage fp = pdf.pages.get(0); double fpp = getFirstPagePartitionBreak(fp); StringBuilder out = new StringBuilder(); PDFLine prevLine = null; boolean first = true; for(PDFLine l : fp.lines) { if(first) { first=false; //skip the first line (heuristic) continue; } if (breakSize(l, prevLine) > fpp) { if(out.length() > 400) { //hand-tuned threshold of min abstract length return out.toString().trim(); } else { out.delete(0, out.length()); out.append(' '); out.append(cleanLine(lineToString(l))); } } else { out.append(' '); out.append(cleanLine(lineToString(l))); } prevLine = l; } return ""; } private final static Pattern inLineAbstractPattern = Pattern.compile("^abstract ?\\p{P}?", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE); private final static Pattern[] generalAbstractCleaners = new Pattern[] { Pattern.compile("Key ?words(:| |\\.).*$", Pattern.UNICODE_CASE), Pattern.compile("KEY ?WORDS(:| |\\.).*$", Pattern.UNICODE_CASE), Pattern.compile("Key ?Words(:| |\\.).*$", Pattern.UNICODE_CASE), Pattern.compile("(1|I)\\.? Introduction.*$", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE), Pattern.compile("Categories and Subject Descriptors.*$", Pattern.UNICODE_CASE), Pattern.compile("0 [1-2][0-9]{3}.*$", Pattern.UNICODE_CASE), Pattern.compile("Contents.*$", Pattern.UNICODE_CASE), Pattern.compile("Index terms\\p{P}.*$", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE), }; private final static Pattern paragraphAbstractCleaner = Pattern.compile("^summary ?\\p{P}?", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE); public static String getAbstract(List<String> raw, PDFDoc pdf) { boolean inAbstract = false; StringBuilder out = new StringBuilder(); for(String s : raw) { if(inAbstract) { if(s.length() < 20) break; else { out.append(' '); out.append(s.trim()); } } if(s.toLowerCase().contains("abstract") && s.length() < 10) { inAbstract = true; } else if(s.toLowerCase().contains("a b s t r a c t")) { inAbstract = true; } else if(RegexWithTimeout.matcher(inLineAbstractPattern, s).find()) { out.append(RegexWithTimeout.matcher(inLineAbstractPattern, s).replaceFirst("")); inAbstract = true; } } String abs = out.toString().trim(); if(abs.length()==0) { //we didn't find an abstract. Pull out the first paragraph-looking thing. abs = getFirstTextBlock(pdf); abs = RegexWithTimeout.matcher(paragraphAbstractCleaner, abs).replaceFirst(""); } // remove keywords, intro from abstract for(Pattern p : generalAbstractCleaners) { abs = RegexWithTimeout.matcher(p, abs).replaceFirst(""); } abs = abs.replaceAll("- ", ""); return abs; } private static boolean lenientRefStart(PDFLine l, PDFLine prevLine, double qLineBreak) { final PDFToken firstToken = l.tokens.get(0); return ( firstToken.token.equals("[1]") || firstToken.token.equals("1.") ) && l.tokens.size() > 1 && ( PDFToCRFInput.getX(l.tokens.get(1), true) > firstToken.fontMetrics.spaceWidth || breakSize(l, prevLine) > qLineBreak ); } public static Set<String> referenceHeaders = new HashSet<String>(Arrays.asList( "references", "citations", "bibliography", "reference", "bibliographie")); private static Pattern referenceStartPattern = Pattern.compile("^\\d{1,2}(\\.|\\s|$)|^\\[.+?\\]"); private static boolean gapAcrossMiddle(PDFToken t1, PDFToken t2, PDFPage p, float lineSpaceWidth) { double gap = PDFToCRFInput.getXGap(t1, t2); double pageCenter = p.getPageWidth() / 2.0; double gapCenter = (PDFToCRFInput.getX(t1, false) + PDFToCRFInput.getX(t2, true))/2.0; return gap > 5*lineSpaceWidth && Math.abs(gapCenter - pageCenter) < 50*lineSpaceWidth; //lenient on center since margins might differ } /** * The lower-level processing sometimes fails to detect column breaks and/or fails to order * to column lines correctly. This function attempts to repair that, returning column-broken lines * ordered left-to-right, top-to-bottom. * @param lines * @return */ public static List<Pair<PDFPage, PDFLine>> repairColumns(List<Pair<PDFPage, PDFLine>> lines) { List<Pair<PDFPage, PDFLine>> out = new ArrayList<>(); List<PDFLine> linesA = new ArrayList<>(); //holds new, broken lines PDFPage prevPage = null; ArrayList<Double> gaps = new ArrayList<>(); double meanSpaceWidth = 0.0; for(final Pair<PDFPage, PDFLine> pageLinePair : lines) { PDFLine line = pageLinePair.getTwo(); PDFPage page = pageLinePair.getOne(); if(page != prevPage && prevPage != null) { final PDFPage comparePage = prevPage; linesA.sort((line1, line2) -> Double.compare(lineSorter(line1, comparePage), lineSorter(line2, comparePage))); for(PDFLine linea : linesA) out.add(Tuples.pair(prevPage, linea)); linesA = new ArrayList<>(); } List<PDFToken> lineAcc = new ArrayList<>(); PDFToken prevToken = null; for(final PDFToken token : line.tokens) { if(prevToken != null) { if(gapAcrossMiddle(prevToken, token, page, prevToken.fontMetrics.spaceWidth)) { gaps.add((PDFToCRFInput.getX(prevToken,false) + PDFToCRFInput.getX(token, true))/2.0); meanSpaceWidth += prevToken.fontMetrics.spaceWidth; linesA.add(PDFLine.builder().tokens(new ArrayList<>(lineAcc)).build()); lineAcc = new ArrayList<>(); } } lineAcc.add(token); prevToken = token; } if(lineAcc.size() > 0) linesA.add(PDFLine.builder().tokens(new ArrayList<>(lineAcc)).build()); prevPage = page; } //if gaps are consistent and there are at least ten of them: boolean useReorderedLines = false; if(gaps.size() > 10) { useReorderedLines = true; double mean = 0.0; meanSpaceWidth /= gaps.size(); for(double d : gaps) { mean += d; } mean /= gaps.size(); for(double d : gaps) { if(Math.abs(d - mean) > 3*meanSpaceWidth) { useReorderedLines = false; break; } } } if(useReorderedLines) { final PDFPage comparePage = prevPage; linesA.sort((line1, line2) -> Double.compare(lineSorter(line1, comparePage), lineSorter(line2, comparePage))); for (PDFLine linea : linesA) out.add(Tuples.pair(prevPage, linea)); log.info("using re-ordered lines: " + out.size()); return out; } else return lines; } private static double lineSorter(PDFLine line, PDFPage p) { return 1E8*(firstCol(line, p)?0.0:1.0) + PDFToCRFInput.getY(line, true); } private static boolean firstCol(PDFLine line, PDFPage p) { double pageThird = p.getPageWidth() / 3.0; return PDFToCRFInput.getX(line, true) < pageThird; } private static boolean referenceIsSplit(String lineOne, String lineTwo) { Matcher lineOneMatcher = RegexWithTimeout.matcher(referenceStartPattern, lineOne); return (lineOneMatcher.find() && lineOneMatcher.end() == lineOne.length() && !RegexWithTimeout.matcher(referenceStartPattern, lineTwo).find()); } /** * Returns best guess of list of strings representation of the references of this file, * intended to be one reference per list element, using spacing and indentation as cues */ public static List<String> getRawReferences(PDFDoc pdf) { PDFLine prevLine = null; boolean inRefs = false; boolean foundRefs = false; double qLineBreak = getReferenceLineBreak(pdf); boolean lenient = false; // Find reference lines in the document List<Pair<PDFPage, PDFLine>> referenceLines = new ArrayList<>(); int totalLines = 0; for(int pass=0;pass<2;pass++) { int passLines = 0; if(pass==1) if(foundRefs) break; else lenient=true; //try harder this time. for (PDFPage p : pdf.getPages()) { double farLeft = Double.MAX_VALUE; //of current column double farRight = -1.0; //of current column for (PDFLine l : p.getLines()) { if (!inRefs && (l != null && l.tokens != null && l.tokens.size() > 0)) { if ( l.tokens.get(l.tokens.size() - 1).token != null && referenceHeaders.contains( l.tokens.get(l.tokens.size() - 1).token.trim().toLowerCase().replaceAll("\\p{Punct}*$", "")) && l.tokens.size() < 5 ) { inRefs = true; foundRefs = true; prevLine = l; continue; //skip this line } else if (lenient && passLines > totalLines / 4) { //used if we don't find refs on first pass; must not be in first 1/4 of doc if (lenientRefStart(l, prevLine, qLineBreak)) { inRefs = true; foundRefs = true; //DON'T skip this line. } } } if (inRefs) referenceLines.add(Tuples.pair(p, l)); prevLine = l; } if(pass==0) totalLines++; passLines++; } } referenceLines = repairColumns(referenceLines); // split reference lines into columns final List<List<PDFLine>> referenceLinesInColumns = new ArrayList<>(); PDFPage lastPage = null; double currentColumnBottom = Double.MAX_VALUE; for(final Pair<PDFPage, PDFLine> pageLinePair : referenceLines) { final PDFPage p = pageLinePair.getOne(); final PDFLine l = pageLinePair.getTwo(); // remove empty lines if(l.tokens.isEmpty()) continue; // Cut into columns. One column is a set of lines with continuously increasing Y coordinates. final double lineTop = PDFToCRFInput.getY(l, true); final double lineBottom = PDFToCRFInput.getY(l, false); if (p != lastPage || lineTop < currentColumnBottom) { final List<PDFLine> newColumn = new ArrayList<>(); newColumn.add(l); referenceLinesInColumns.add(newColumn); currentColumnBottom = lineBottom; } else { referenceLinesInColumns.get(referenceLinesInColumns.size() - 1).add(l); currentColumnBottom = lineBottom; } lastPage = p; } // parse each column into output // We assume that the indentation of the first line of every column marks the start of a // reference (unless that indentation happens only once) final List<String> out = new ArrayList<String>(); for(final List<PDFLine> column : referenceLinesInColumns) { // find indentation levels final MutableFloatIntMap left2count = FloatIntMaps.mutable.empty(); for(final PDFLine l : column) { final float left = PDFToCRFInput.getX(l, true); final float lineSpaceWidth = l.tokens.get(0).fontMetrics.spaceWidth; // find an indentation level that's close to this one // This is not proper clustering, but I don't think we need it. float foundLeft = left; for(final float indentLevel : left2count.keySet().toArray()) { if(Math.abs(indentLevel - left) < lineSpaceWidth) { foundLeft = indentLevel; break; } } final int oldCount = left2count.getIfAbsent(foundLeft, 0); left2count.remove(foundLeft); left2count.put( (foundLeft * oldCount + left) / (oldCount + 1), oldCount + 1); } // find the indentation that starts a reference float startReferenceIndentation = -1000; // default is some number that's definitely more than one space width away from a realistic indent final ImmutableList<FloatIntPair> startReferenceIndentCandidates = left2count.keyValuesView().toSortedListBy(pair -> -pair.getTwo()).take(2).toImmutable(); if(startReferenceIndentCandidates.size() > 1) { final FloatIntPair first = startReferenceIndentCandidates.get(0); final FloatIntPair second = startReferenceIndentCandidates.get(1); // find lines that look like they start references, and use them to determine which indent // starts a reference float firstIndentSeen = -1; for(final PDFLine l : column) { float left = PDFToCRFInput.getX(l, true); final float lineSpaceWidth = l.tokens.get(0).fontMetrics.spaceWidth; // snap to candidate indentations if(Math.abs(first.getOne() - left) < lineSpaceWidth) left = first.getOne(); else if(Math.abs(second.getOne() - left) < lineSpaceWidth) left = second.getOne(); else continue; // only consider candidates if(firstIndentSeen < 0) firstIndentSeen = left; final String lineAsString = lineToString(l); if(referenceStartPattern.matcher(lineAsString).find()) { startReferenceIndentation = left; break; } } if(startReferenceIndentation < 0) { startReferenceIndentation = second.getOne(); // pick the one that's less common } } // find vertical spaces that might separate references final float breakSizeTolerance = 0.1f; MutableFloatIntMap vspace2count = FloatIntMaps.mutable.empty(); for(int i = 1; i < column.size(); ++i) { final PDFLine l1 = column.get(i - 1); final PDFLine l2 = column.get(i); final float thisVspace = breakSize(l2, l1); // vspace is measured in line heights // if it's close to another break size, we should cluster them float foundVspace = thisVspace; for(final float v : vspace2count.keySet().toArray()) { if(Math.abs(v - thisVspace) <= breakSizeTolerance) { foundVspace = v; break; } } final int oldCount = vspace2count.getIfAbsent(foundVspace, 0); vspace2count.remove(foundVspace); vspace2count.put( (foundVspace * oldCount + thisVspace) / (oldCount + 1), oldCount + 1); } // filter down to reasonable vspaces final long numberOfBreaks = vspace2count.sum(); vspace2count = vspace2count.select((vspace, count) -> count >= numberOfBreaks / 5 && // must account for 20% of breaks count > 1 && // must occur at least once vspace < 3 // more than 3 lines of gap is crazy ); float breakReferenceVspace = -1.0f; if(column.size() > 5 && vspace2count.size() >= 2) // only if we have at least 5 lines breakReferenceVspace = vspace2count.keySet().max(); int linesGrouped = 0; // We never group more than six lines together at a time. final StringBuilder builder = new StringBuilder(); prevLine = null; for(final PDFLine l : column) { final float left = PDFToCRFInput.getX(l, true); final String lineAsString = lineToString(l); final float lineSpaceWidth = l.tokens.get(0).fontMetrics.spaceWidth; linesGrouped += 1; final boolean br = linesGrouped >= 6 || ( breakReferenceVspace < 0 && // if we have vspace, we don't use indent startReferenceIndentation > 0 && Math.abs(left-startReferenceIndentation) < lineSpaceWidth ) || referenceStartPattern.matcher(lineAsString).find() || ( prevLine != null && breakReferenceVspace > 0 && breakSize(l, prevLine) >= breakReferenceVspace - breakSizeTolerance ); if(br) { // save old line final String outLine = cleanLine(builder.toString()); if(!outLine.isEmpty()) out.add(outLine); // start new line builder.setLength(0); builder.append(lineAsString); linesGrouped = 1; } else { if (!builder.toString().isEmpty()) builder.append("<lb>"); builder.append(lineAsString); } prevLine = l; } // save last line final String outLine = cleanLine(builder.toString()); if(!outLine.isEmpty()) out.add(outLine); } // If two columns were found incorrectly, the out array may consist of alternating // reference numbers and reference information. In this case, combine numbers with // the content that follows. List<String> mergedRefs = new ArrayList<String>(); int i=0; while (i<out.size()) { String thisRef = out.get(i); String nextRef = i < out.size()-1 ? out.get(i+1) : null; if (nextRef != null && referenceIsSplit(thisRef, nextRef)) { mergedRefs.add(String.join(" ", thisRef, nextRef)); i += 2; } else { mergedRefs.add(thisRef); i += 1; } } return mergedRefs; } }
22,094
35.886477
145
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/PDFPredicateExtractor.java
package org.allenai.scienceparse; import com.gs.collections.api.map.primitive.ObjectDoubleMap; import com.gs.collections.api.tuple.Pair; import com.gs.collections.impl.map.mutable.primitive.ObjectDoubleHashMap; import com.gs.collections.impl.tuple.Tuples; import org.allenai.word2vec.Searcher; import org.allenai.word2vec.Word2VecModel; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.allenai.datastore.Datastore; import org.allenai.ml.sequences.crf.CRFPredicateExtractor; import org.allenai.scienceparse.pdfapi.PDFToken; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; @Slf4j public class PDFPredicateExtractor implements CRFPredicateExtractor<PaperToken, String> { public static final List<String> stopWords = Arrays.asList("a", "an", "the", "in", "of", "for", "from", "and", "as", "but", "to"); public static final HashSet<String> stopHash = new HashSet<String>(stopWords); private final ParserLMFeatures lmFeats; private final Searcher word2vecSearcher; public PDFPredicateExtractor() { this(null); } public PDFPredicateExtractor(ParserLMFeatures plf) { try { final Path word2VecModelPath = Datastore.apply().filePath("org.allenai.scienceparse", "Word2VecModel.bin", 1); word2vecSearcher = WordVectorCache.searcherForPath(word2VecModelPath); } catch(final IOException e) { throw new RuntimeException(e); } lmFeats = plf; } public static List<String> getCaseMasks(String tok) { Pattern Xxx = Pattern.compile("[A-Z][a-z]*"); Pattern xxx = Pattern.compile("[a-z]+"); Pattern letters = Pattern.compile("[a-zA-Z]+"); Pattern dig = Pattern.compile("[0-9]+"); Pattern hasNum = Pattern.compile(".*[0-9]+.*"); Pattern letterDot = Pattern.compile("[A-Z]\\."); Pattern hasNonAscii = Pattern.compile(".*[^\\p{ASCII}]+.*"); Pattern wordColon = Pattern.compile("[a-zA-Z]+:"); Pattern hasAt = Pattern.compile(".*@.*"); List<Pattern> pats = Arrays.asList(Xxx, xxx, letters, dig, hasNum, letterDot, hasNonAscii, wordColon, hasAt); List<String> feats = Arrays.asList("%Xxx", "%xxx", "%letters", "%dig", "%hasNum", "%letDot", "%hasNonAscii", "%capWordColon", "%hasAt"); ArrayList<String> out = new ArrayList<String>(); for (int i = 0; i < pats.size(); i++) { Pattern p = pats.get(i); if (p.matcher(tok).matches()) { out.add(feats.get(i)); } } return out; } public static boolean isStopWord(String tok) { return stopHash.contains(tok); } public static float getY(PaperToken t, boolean upper) { if (upper) return t.getPdfToken().bounds.get(1); else return t.getPdfToken().bounds.get(3); } public static double smoothFreq(String tok, ObjectDoubleHashMap<String> hm) { double freq = hm.get(tok); if (freq > 0.0) freq -= 0.6; return Math.log10(freq + 0.1); } private static float height(PDFToken t) { return t.bounds.get(3) - t.bounds.get(1); } private static float width(PDFToken t) { return t.bounds.get(0) - t.bounds.get(2); } public static float getExtreme(List<PaperToken> toks, TokenPropertySelector s, boolean max) { float adj = -1.0f; float extremeSoFar = Float.NEGATIVE_INFINITY; if (max) { adj = 1.0f; } for (PaperToken pt : toks) { float propAdj = s.getProp(pt) * adj; if (propAdj > extremeSoFar) { extremeSoFar = propAdj; } } return extremeSoFar * adj; } public static float linearNormalize(float f, Pair<Float, Float> rng) { if (Math.abs(rng.getTwo() - rng.getOne()) < 0.00000001) return 0.5f; else return (f - rng.getOne()) / (rng.getTwo() - rng.getOne()); } public static Pair<Float, Float> getExtrema(List<PaperToken> toks, TokenPropertySelector s) { Pair<Float, Float> out = Tuples.pair(getExtreme(toks, s, false), getExtreme(toks, s, true)); return out; } public static float getFixedFont(PaperToken t) { float s = t.getPdfToken().fontMetrics.ptSize; if (s > 30.0f) //assume it's an error return 11.0f; else return s; } public double logYDelt(float y1, float y2) { return Math.log(Math.max(y1 - y2, 0.00001f)); } // String.format() ends up taking a very long time at scale, so we pre-compute all the // String.format() calls we might need and re-use them. public static final String[] wordEmbeddingFeatureNames; static { wordEmbeddingFeatureNames = new String[1000]; for (int i = 0; i < wordEmbeddingFeatureNames.length; ++i) wordEmbeddingFeatureNames[i] = String.format("%%emb%03d", i); } //assumes start/stop padded @Override public List<ObjectDoubleMap<String>> nodePredicates(List<PaperToken> elems) { List<ObjectDoubleMap<String>> out = new ArrayList<>(); Pair<Float, Float> hBounds = getExtrema(elems.subList(1, elems.size() - 1), (PaperToken t) -> { return height(t.getPdfToken()); }); Pair<Float, Float> fBounds = getExtrema(elems.subList(1, elems.size() - 1), (PaperToken t) -> { return getFixedFont(t); }); for (int i = 0; i < elems.size(); i++) { ObjectDoubleHashMap<String> m = new ObjectDoubleHashMap<String>(); float prevFont = -10.0f; float nextFont = -10.0f; float prevHeight = -10.0f; float nextHeight = -10.0f; float prevY = 0.0f; float nextY = -1000000.0f; int prevLine = -1; int nextLine = -1; if (i == 0) m.put("<S>", 1.0); else if (i == elems.size() - 1) m.put("</S>", 1.0); else { if (i != 1) { prevLine = elems.get(i - 1).getLine(); prevFont = getFixedFont(elems.get(i - 1)); prevHeight = height(elems.get(i - 1).getPdfToken()); prevY = getY(elems.get(i - 1), false); } if (i != elems.size() - 2) { nextLine = elems.get(i + 1).getLine(); nextFont = getFixedFont(elems.get(i + 1)); nextHeight = height(elems.get(i + 1).getPdfToken()); nextY = getY(elems.get(i + 1), true); } else { nextY = getY(elems.get(i), false) + height(elems.get(i).getPdfToken()); //guess that next line is height units below } float font = getFixedFont(elems.get(i)); float h = height(elems.get(i).getPdfToken()); int line = elems.get(i).getLine(); //font-change forward (fcf) or backward (fcb): if (font != prevFont) m.put("%fcb", 1.0); //binary, 1.0 if there is a font change forward, 0.0 otherwise if (font != nextFont) m.put("%fcf", 1.0); //font change backward if (line != prevLine) { m.put("%lcb", 1.0); //line change backward m.put("%hGapB", logYDelt(getY(elems.get(i), true), prevY)); //height gap backward } if (line != nextLine) { m.put("%lcf", 1.0); //line change forward m.put("%hGapF", logYDelt(nextY, getY(elems.get(i), false))); //height gap forward } if (Math.abs(Math.abs(nextHeight - h) / Math.abs(nextHeight + h)) > 0.1) { //larger than ~20% height change forward m.put("%hcf", 1.0); } if (Math.abs(Math.abs(prevHeight - h) / Math.abs(prevHeight + h)) > 0.1) { //larger than ~20% height change backward m.put("%hcb", 1.0); } //font value: float relativeF = linearNormalize(font, fBounds); m.put("%font", relativeF); //font size normalized relative to doc m.put("%line", Math.min(line, 10.0)); //cap to max 10 lines float relativeH = linearNormalize(h, hBounds); m.put("%h", relativeH); //normalized line height //word features: String tok = elems.get(i).getPdfToken().token; getCaseMasks(tok).forEach( (String s) -> m.put(s, 1.0)); //case masks if (isStopWord(tok)) { m.put("%stop", 1.0); //stop word if (line != prevLine && (m.containsKey("%XXX") || m.containsKey("%Xxx"))) m.put("%startCapStop", 1.0); //is a stop word that starts with a capital letter } else { if (m.containsKey("%xxx")) { m.put("%uncapns", 1.0); //is an uncapitalized stop word } } double adjLen = Math.min(tok.length(), 10.0) / 10.0; double adjLenSq = (adjLen - 0.5) * (adjLen - 0.5); m.put("%adjLen", adjLen); //adjusted word length m.put("%adjLenSq", adjLenSq); //adjusted word length squared (?) if (line <= 2) m.put("%first3lines", 1.0); //is it in the first three lines: if (lmFeats != null) { //how well does token match title/author gazeetters m.put("%tfreq", smoothFreq(tok, this.lmFeats.titleBow)); m.put("%tffreq", smoothFreq(tok, this.lmFeats.titleFirstBow)); m.put("%tlfreq", smoothFreq(tok, this.lmFeats.titleLastBow)); m.put("%afreq", smoothFreq(Parser.fixupAuthors(tok), this.lmFeats.authorBow)); m.put("%affreq", smoothFreq(Parser.fixupAuthors(tok), this.lmFeats.authorFirstBow)); m.put("%alfreq", smoothFreq(Parser.fixupAuthors(tok), this.lmFeats.authorLastBow)); m.put("%bfreq", smoothFreq(tok, this.lmFeats.backgroundBow)); m.put("%bafreq", smoothFreq(Parser.fixupAuthors(tok), this.lmFeats.backgroundBow)); } // add the token itself as a feature final String token = StringUtils.normalize(elems.get(i).getPdfToken().token); m.put("%t=" + token, 1.0); if(token.equals("and") || token.equals(",")) m.put("%and", 1.0); // add trigram features final String trigramSourceToken = token + "$"; for(int j = 0; j <= trigramSourceToken.length() - 3; ++j) { final String trigram = trigramSourceToken.substring(j, j + 3); final String feature = "%tri=" + trigram; m.updateValue(feature, 0.0, d -> d + 1); } // add word embeddings try { final Iterator<Double> vector = word2vecSearcher.getRawVector(tok).iterator(); int j = 0; while(vector.hasNext()) { final double value = vector.next(); m.put(wordEmbeddingFeatureNames[j], value); j += 1; } } catch (final Searcher.UnknownWordException e) { // do nothing } } out.add(m); } // print extensive debug information if(log.isDebugEnabled()) { // calculate a hash out of the tokens, so we can match feature values from different runs // based on the tokens final String tokens = out.stream().map(features -> features. keysView(). select(key -> key.startsWith("%t=")). collect(featureName -> featureName.substring(3)). makeString("-") ).collect(Collectors.joining(" ")); final String tokensHashPrefix = String.format("%x", tokens.hashCode()); log.debug("{} CRF Input for {}", tokensHashPrefix, tokens); PrintFeaturizedCRFInput.stringsFromFeaturizedSeq(out, tokensHashPrefix).stream().forEach(log::debug); } return out; } @Override public List<ObjectDoubleMap<String>> edgePredicates(List<PaperToken> elems) { val out = new ArrayList<ObjectDoubleMap<String>>(); for (int i = 0; i < elems.size() - 1; i++) { val odhm = new ObjectDoubleHashMap<String>(); odhm.put("B", 1.0); out.add(odhm); } return out; //I don't really understand these things. } private interface TokenPropertySelector { float getProp(PaperToken t); } }
11,878
36.355346
140
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/PDFToCRFInput.java
package org.allenai.scienceparse; import com.gs.collections.api.tuple.Pair; import com.gs.collections.impl.tuple.Tuples; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.allenai.scienceparse.pdfapi.PDFDoc; import org.allenai.scienceparse.pdfapi.PDFLine; import org.allenai.scienceparse.pdfapi.PDFPage; import org.allenai.scienceparse.pdfapi.PDFToken; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; @Slf4j public class PDFToCRFInput { /** * Returns the index start (inclusive) and end (exclusive) * of end of pattern sequence in token seq, starting from startposes. Returns -1 if not found * * @param seq * @param patOptional * @param seqStartPos * @param patStartPos * @return */ public static int findPatternEnd(List<String> seq, List<Pair<Pattern, Boolean>> patOptional, int seqStartPos, int patStartPos) { if (patOptional.size() == patStartPos) { //treated as completion return seqStartPos; } if (patOptional.size() == 0) { //treated as error rather than completion return -1; } if (seq.size() == 0 || seqStartPos == seq.size()) return -1; final String pt = StringUtils.normalize(seq.get(seqStartPos)); if (patOptional.get(patStartPos).getOne().matcher(pt).matches()) { //look forward: return findPatternEnd(seq, patOptional, seqStartPos + 1, patStartPos + 1); } if (patOptional.get(patStartPos).getTwo()) { //try skipping this pattern: return findPatternEnd(seq, patOptional, seqStartPos, patStartPos + 1); } //no matches from this token return -1; } private static String seqToString(final List<String> seq) { final StringBuilder b = new StringBuilder(seq.size() * 10); for(final String s: seq) { b.append(s); b.append(' '); } if(b.length() > 0) b.setLength(b.length() - 1); return b.toString(); } private static String patternToString(final List<Pair<Pattern, Boolean>> pattern) { final StringBuilder b = new StringBuilder(pattern.size() * 10); for(final Pair<Pattern, Boolean> p : pattern) { final boolean optional = p.getTwo(); if(optional) b.append('['); b.append(p.getOne().pattern()); if(optional) b.append(']'); b.append(' '); } b.setLength(b.length() - 1); return b.toString(); } /** * Returns the index start (inclusive) and end (exclusive) * of first occurrence of pattern sequence in token seq, or null if not found * * @param seq Token sequence * @param patOptional (Pattern, optional) pair indicating pattern to match and whether it can be skipped * @return */ public static Pair<Integer, Integer> findPatternSequence(List<String> seq, List<Pair<Pattern, Boolean>> patOptional) { if(log.isDebugEnabled()) { // patternToString() and seqToString() do a lot of work, and we don't want that done if debug // isn't enabled. log.debug("Finding {}\nin {}", patternToString(patOptional), seqToString(seq)); } for (int i = 0; i < seq.size(); i++) { int end = -1; if ((end = findPatternEnd(seq, patOptional, i, 0)) >= 0) { return Tuples.pair(i, end); } } return null; } /** * Returns the index of start (inclusive) and end (exclusive) * of first occurrence of string in seq, or null if not found * * @param seq String to find, assumes tokens are space-delimited * @return */ public static Pair<Integer, Integer> findString(List<String> seq, String toFind) { toFind = StringUtils.normalize(toFind); if (seq.size() == 0 || toFind.length() == 0) return null; String[] toks = toFind.split(" "); if (toks.length == 0) { //can happen if toFind is just spaces return null; } int nextToMatch = 0; for (int i = 0; i < seq.size(); i++) { String s = StringUtils.normalize(seq.get(i)); if (toks[nextToMatch].equalsIgnoreCase(s)) { nextToMatch++; } else { i -= nextToMatch; //start back at char after start of match nextToMatch = 0; } if (nextToMatch == toks.length) return Tuples.pair(i + 1 - toks.length, i + 1); } return null; } public static List<Pair<Pattern, Boolean>> authorToPatternOptPair(String author) { List<Pair<Pattern, Boolean>> out = new ArrayList<>(); //get rid of stuff that can break regexs: author = author.replace(")", ""); author = author.replace("(", ""); author = author.replace("?", ""); author = author.replace("*", ""); author = author.replace("+", ""); author = author.replace("^", ""); author = StringUtils.normalize(author); String[] toks = author.split(" "); for (int i = 0; i < toks.length; i++) { boolean optional = true; if (i == 0 || i == toks.length - 1) optional = false; String pat = ""; if (i < toks.length - 1) { if (toks[i].matches("[A-Z](\\.)?")) { //it's a single-letter abbreviation pat = toks[i].substring(0, 1) + "(((\\.)?)|([a-z]+))"; //allow arbitrary expansion } else { if (toks[i].length() > 1) //allow single-initial abbreviations pat = toks[i].substring(0, 1) + "(((\\.)?)|(" + toks[i].substring(1) + "))"; else pat = toks[i];//catch-all for edge cases } } else { pat = toks[i]; pat += "((\\W)|[0-9])*"; //allow some non-alpha or number (typically, footnote marker) at end of author } try { //log.info("trying pattern " + pat); out.add(Tuples.pair(Pattern.compile(pat, Pattern.CASE_INSENSITIVE), optional)); } catch (Exception e) { log.info("error in author pattern " + pat); } } if (toks.length == 2) { //special case, add optional middle initial Pair<Pattern, Boolean> temp = out.get(1); for (int i = 2; i < out.size(); i++) { val temp2 = out.get(i); out.set(i, temp); temp = temp2; } out.add(temp); out.set(1, Tuples.pair(Pattern.compile("[A-Z](\\.)?", Pattern.CASE_INSENSITIVE), true)); } return out; } public static Pair<Integer, Integer> findAuthor(List<String> seq, String toFind) { List<Pair<Pattern, Boolean>> pats = authorToPatternOptPair(toFind); return findPatternSequence(seq, pats); } private static void addLineTokens(List<PaperToken> accumulator, List<PDFLine> lines, final int pg) { int ln = 0; for (PDFLine l : lines) { final int lnF = ln++; //ugh (to get around compile error) l.tokens.forEach((PDFToken t) -> accumulator.add( new PaperToken(t, lnF, pg)) ); } } public static float getY(PDFLine l, boolean upper) { if (upper) return l.bounds().get(1); else return l.bounds().get(3); } public static float getXGap(PDFToken t1, PDFToken t2) { return getX(t2, true) - getX(t1, false); } public static float getX(PDFLine l, boolean left) { if (left) return l.bounds().get(0); else return l.bounds().get(2); } public static float getX(PDFToken t, boolean left) { if(left) return t.getBounds().get(0); else return t.getBounds().get(2); } public static float getY(PDFToken t, boolean upper) { if (upper) return t.getBounds().get(1); else return t.getBounds().get(3); } public static float getH(PDFLine l) { float result = l.bounds().get(3) - l.bounds().get(1); if (result < 0) { log.debug("Negative height? Guessing a height of 5."); return 5; } else { return result; } } /** * Returns the PaperToken sequence form of a given PDF document * * @param pdf The PDF Document to convert into instances * @return The data sequence */ public static List<PaperToken> getSequence(PDFDoc pdf) { ArrayList<PaperToken> out = new ArrayList<>(); List<PDFPage> pages = pdf.getPages(); for (int pageNum = 0; pageNum < pages.size(); pageNum++) { addLineTokens(out, pages.get(pageNum).lines, pageNum); } return out; } public static List<PaperToken> padSequence(List<PaperToken> seq) { ArrayList<PaperToken> out = new ArrayList<>(); out.add(PaperToken.generateStartStopToken()); out.addAll(seq); out.add(PaperToken.generateStartStopToken()); return out; } public static List<String> padTagSequence(List<String> seq) { ArrayList<String> out = new ArrayList<>(); out.add("<S>"); out.addAll(seq); out.add("</S>"); return out; } /** * Labels the (first occurrence of) given target in seq with given label * * @param seq The sequence * @param seqLabeled The same sequence with labels * @param target * @param labelStem * @return True if target was found in seq, false otherwise */ public static boolean findAndLabelWith( final String paperId, final List<PaperToken> seq, final List<Pair<PaperToken, String>> seqLabeled, final String target, final String labelStem, final boolean isAuthor ) { Pair<Integer, Integer> loc = null; if (isAuthor) loc = findAuthor(asStringList(seq), target); else loc = findString(asStringList(seq), target); if (loc == null) { log.debug("{}: could not find {} string {} in paper.", paperId, labelStem, target); return false; } else { if (loc.getOne() == loc.getTwo() - 1) { Pair<PaperToken, String> t = seqLabeled.get(loc.getOne()); seqLabeled.set(loc.getOne(), Tuples.pair(t.getOne(), "W_" + labelStem)); } else { for (int i = loc.getOne(); i < loc.getTwo(); i++) { Pair<PaperToken, String> t = seqLabeled.get(i); seqLabeled.set(i, Tuples.pair(t.getOne(), (i == loc.getOne() ? "B_" + labelStem : (i == loc.getTwo() - 1 ? "E_" + labelStem : "I_" + labelStem)))); } } return true; } } /** * Returns the given tokens in a new list with labeled ground truth attached * according to the given reference metadata. * Only labels positive the first occurrence of each ground-truth string. * <br> * Labels defined in ExtractedMetadata * * @param toks * @param truth * @return */ public static List<Pair<PaperToken, String>> labelMetadata( final String paperId, final List<PaperToken> toks, final LabeledData truth ) { val truthAuthorNamesOption = truth.javaAuthorNames(); if(!truthAuthorNamesOption.isPresent()) return null; val truthAuthorNames = truthAuthorNamesOption.get(); val truthTitleOption = truth.javaTitle(); if(!truthTitleOption.isPresent()) return null; val truthTitle = truthTitleOption.get(); val outTmp = new ArrayList<Pair<PaperToken, String>>(); for (PaperToken t : toks) { outTmp.add(Tuples.pair(t, "O")); } truthAuthorNames.forEach((String s) -> findAndLabelWith(paperId, toks, outTmp, s, ExtractedMetadata.authorTag, true)); if (!findAndLabelWith(paperId, toks, outTmp, truthTitle, ExtractedMetadata.titleTag, false)) //must have title to be valid return null; val out = new ArrayList<Pair<PaperToken, String>>(); out.add(Tuples.pair(PaperToken.generateStartStopToken(), "<S>")); out.addAll(outTmp); out.add(Tuples.pair(PaperToken.generateStartStopToken(), "</S>")); return out; } public static List<String> asStringList(List<PaperToken> toks) { return toks.stream().map(pt -> pt.getPdfToken().token).collect(Collectors.toList()); } public static String stringAt(List<PaperToken> toks, Pair<Integer, Integer> span) { List<PaperToken> pts = toks.subList(span.getOne(), span.getTwo()); List<String> words = pts.stream().map(pt -> (pt.getLine() == -1) ? "<S>" : pt.getPdfToken().token).collect(Collectors.toList()); return appendStringList(words).trim(); } public static String stringAtForStringList(List<String> toks, Pair<Integer, Integer> span) { List<String> words = toks.subList(span.getOne(), span.getTwo()); return appendStringList(words).trim(); } public static String appendStringList(List<String> toks) { StringBuilder sb = new StringBuilder(); for (String s : toks) { sb.append(s); sb.append(" "); } return sb.toString(); } public static String getLabelString(List<Pair<PaperToken, String>> seq) { return seq.stream().map(Pair::getTwo).collect(Collectors.toList()).toString(); } }
12,701
31.821705
132
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/PaperSource.java
package org.allenai.scienceparse; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.io.InputStream; /** * Encapsulates a way to get PDFs from paper ids. */ public abstract class PaperSource { abstract InputStream getPdf(String paperId) throws IOException; @VisibleForTesting public static PaperSource defaultPaperSource = null; static synchronized PaperSource getDefault() { if(defaultPaperSource == null) defaultPaperSource = new RetryPaperSource(S2PaperSource$.MODULE$, 5); return defaultPaperSource; } }
608
25.478261
81
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/PaperToken.java
package org.allenai.scienceparse; import org.allenai.scienceparse.pdfapi.PDFToken; public class PaperToken { private PDFToken pdfToken; //the underlying pdf token private int page; //page number in pdf doc private int line; //line number in pdf doc public PaperToken(PDFToken pt, int ln, int pg) { setPdfToken(pt); setLine(ln); setPage(pg); } public static PaperToken generateStartStopToken() { //needed to use CRF return new PaperToken(null, -1, -1); } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getLine() { return line; } public void setLine(int line) { this.line = line; } public PDFToken getPdfToken() { return pdfToken; } public void setPdfToken(PDFToken pdfToken) { this.pdfToken = pdfToken; } public String toStringShort() { if (pdfToken == null) return ""; else return pdfToken.token; } }
968
18
73
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/Parser.java
package org.allenai.scienceparse; import com.gs.collections.api.map.primitive.MutableCharIntMap; import com.gs.collections.api.set.MutableSet; import com.gs.collections.api.set.primitive.MutableIntSet; import com.gs.collections.api.tuple.Pair; import com.gs.collections.impl.factory.primitive.CharIntMaps; import com.gs.collections.impl.factory.primitive.IntSets; import com.gs.collections.impl.set.mutable.UnifiedSet; import com.gs.collections.impl.tuple.Tuples; import lombok.Data; import lombok.val; import org.allenai.datastore.Datastore; import org.allenai.ml.eval.TrainCriterionEval; import org.allenai.ml.linalg.DenseVector; import org.allenai.ml.linalg.Vector; import org.allenai.ml.sequences.Evaluation; import org.allenai.ml.sequences.StateSpace; import org.allenai.ml.sequences.crf.CRFFeatureEncoder; import org.allenai.ml.sequences.crf.CRFModel; import org.allenai.ml.sequences.crf.CRFTrainer; import org.allenai.ml.sequences.crf.CRFWeightsEncoder; import org.allenai.ml.util.IOUtils; import org.allenai.ml.util.Indexer; import org.allenai.ml.util.Parallel; import org.allenai.pdffigures2.FigureExtractor; import org.allenai.scienceparse.pdfapi.PDFDoc; import org.allenai.scienceparse.pdfapi.PDFExtractor; import org.apache.pdfbox.pdmodel.PDDocument; import org.nustaq.serialization.FSTObjectInput; import org.nustaq.serialization.FSTObjectOutput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.compat.java8.ScalaStreamSupport; import scala.compat.java8.OptionConverters; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.file.Path; import java.nio.file.Paths; import java.text.Normalizer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.function.ToDoubleFunction; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; public class Parser { public static final int MAXHEADERWORDS = 500; //set to something high for author/title parsing public static final String DATA_VERSION = "0.3"; // faster serialization private CRFModel<String, PaperToken, String> model; private ExtractReferences referenceExtractor; private final static Logger logger = LoggerFactory.getLogger(Parser.class); private final static Logger labeledDataLogger = LoggerFactory.getLogger(logger.getName() + ".labeledData"); private static final Datastore datastore = Datastore.apply(); public static Path getDefaultProductionModel() { return datastore.filePath("org.allenai.scienceparse", "productionModel.dat", 9); } public static Path getDefaultGazetteer() { return datastore.filePath("org.allenai.scienceparse", "gazetteer.json", 5); } public static Path getDefaultGazetteerDir() { return datastore.directoryPath("org.allenai.scienceparse", "kermit-gazetteers", 1); } public static Path getDefaultBibModel() { return datastore.filePath("org.allenai.scienceparse", "productionBibModel.dat", 7); } private static Parser defaultParser = null; public synchronized static Parser getInstance() throws Exception { if(defaultParser == null) defaultParser = new Parser(); return defaultParser; } public Parser() throws Exception { this(getDefaultProductionModel(), getDefaultGazetteer(), getDefaultBibModel()); } public Parser( final String modelFile, final String gazetteerFile, final String bibModelFile ) throws Exception { this(new File(modelFile), new File(gazetteerFile), new File(bibModelFile)); } public Parser( final Path modelFile, final Path gazetteerFile, final Path bibModelFile ) throws Exception { this(modelFile.toFile(), gazetteerFile.toFile(), bibModelFile.toFile()); } public Parser( final File modelFile, final File gazetteerFile, final File bibModelFile ) throws Exception { // Load main model in one thread, and the rest in another thread, to speed up startup. final AtomicReference<Exception> exceptionThrownByModelLoaderThread = new AtomicReference<>(); final Thread modelLoaderThread = new Thread(new Runnable() { @Override public void run() { logger.info("Loading model from {}", modelFile); try( final DataInputStream modelIs = new DataInputStream(new FileInputStream(modelFile)); ) { model = loadModel(modelIs); logger.info("Loaded model from {}", modelFile); } catch(final Exception e) { exceptionThrownByModelLoaderThread.compareAndSet(null, e); logger.warn("Failed loading model from {}", modelFile); } } }, "ModelLoaderThread"); modelLoaderThread.start(); // Load non-main model stuff logger.info("Loading gazetteer from {}", gazetteerFile); logger.info("Loading bib model from {}", bibModelFile); try( final InputStream gazetteerIs = new FileInputStream(gazetteerFile); final DataInputStream bibModelIs = new DataInputStream(new FileInputStream(bibModelFile)) ) { // Loading the gazetteer takes a long time, so we create a cached binary version of it that // loads very quickly. If that version is already there, we use it. Otherwise, we create it. val gazCacheFilename = String.format( "%s-%08x.gazetteerCache.bin", gazetteerFile.getName(), gazetteerFile.getCanonicalPath().hashCode()); val gazCachePath = Paths.get(System.getProperty("java.io.tmpdir"), gazCacheFilename); try ( final RandomAccessFile gazCacheFile = new RandomAccessFile(gazCachePath.toFile(), "rw"); final FileChannel gazCacheChannel = gazCacheFile.getChannel(); final FileLock gazCacheLock = gazCacheChannel.lock(); ) { if (gazCacheChannel.size() == 0) { logger.info("Creating gazetteer cache at {}", gazCachePath); referenceExtractor = ExtractReferences.createAndWriteGazCache( gazetteerIs, bibModelIs, Channels.newOutputStream(gazCacheChannel)); } else { logger.info("Reading from gazetteer cache at {}", gazCachePath); referenceExtractor = new ExtractReferences( gazetteerIs, bibModelIs, Channels.newInputStream(gazCacheChannel)); } } } logger.info("Loaded gazetteer from {}", gazetteerFile); logger.info("Loaded bib model from {}", bibModelFile); // Close out the model loader thread and make sure the results are OK. modelLoaderThread.join(); if(exceptionThrownByModelLoaderThread.get() != null) throw exceptionThrownByModelLoaderThread.get(); assert(model != null); } public Parser( final InputStream modelStream, final InputStream gazetteerStream, final InputStream bibModelStream ) throws Exception { final DataInputStream dis = new DataInputStream(modelStream); model = loadModel(dis); referenceExtractor = new ExtractReferences( gazetteerStream, new DataInputStream(bibModelStream)); } public static Pair<List<BibRecord>, List<CitationRecord>> getReferences( final List<String> raw, final List<String> rawReferences, final ExtractReferences er ) { final Pair<List<BibRecord>, ExtractReferences.BibStractor> fnd = er.findReferences(rawReferences); final List<BibRecord> brs = fnd.getOne().stream().map(BibRecord::withNormalizedAuthors).collect(Collectors.toList()); final ExtractReferences.BibStractor bs = fnd.getTwo(); final List<CitationRecord> crs = ExtractReferences.findCitations(raw, brs, bs); return Tuples.pair(brs, crs); } //slow public static String paperToString(File f) { try { FileInputStream fis = new FileInputStream(f); PDFDoc doc = (new PDFExtractor()).extractFromInputStream(fis); fis.close(); val seq = PDFToCRFInput.getSequence(doc); return PDFToCRFInput.stringAt(seq, Tuples.pair(0, seq.size())); } catch (Exception e) { return null; } } //from conll.Trainer: private static <T> Pair<List<T>, List<T>> splitData(List<T> original, double splitForSecond) { List<T> first = new ArrayList<>(); List<T> second = new ArrayList<>(); if (splitForSecond > 0.0) { Collections.shuffle(original, new Random(0L)); int numFirst = (int) ((1.0 - splitForSecond) * original.size()); first.addAll(original.subList(0, numFirst)); second.addAll(original.subList(numFirst, original.size())); } else { first.addAll(original); // second stays empty } return Tuples.pair(first, second); } public static List<Pair<PaperToken, String>> getPaperLabels( final String paperId, final InputStream is, final LabeledData labeledData, PDFExtractor ext, int headerMax, boolean checkAuthors ) throws IOException { logger.debug("{}: starting", paperId); final PDFDoc doc; try { doc = ext.extractFromInputStream(is); } catch(final Exception e) { logger.warn("{} failed: {}", paperId, e.toString()); return null; } if (doc == null) { return null; } List<PaperToken> seq = PDFToCRFInput.getSequence(doc); if (seq.size() == 0) return null; seq = seq.subList(0, Math.min(seq.size(), headerMax)); List<Pair<PaperToken, String>> labeledPaper = PDFToCRFInput.labelMetadata(paperId, seq, labeledData); if (labeledPaper != null && checkAuthors) { final ExtractedMetadata checkEM = new ExtractedMetadata( labeledPaper.stream().map(Pair::getOne).collect(Collectors.toList()), labeledPaper.stream().map(Pair::getTwo).collect(Collectors.toList())); final Collection<String> expectedAuthorNames = labeledData.javaAuthorNames().orElse(Collections.emptyList()); if(checkEM.authors.size() != expectedAuthorNames.size()) { logger.debug( "{}: author mismatch, discarding. Expected {}, got {}.", paperId, expectedAuthorNames, checkEM.authors); labeledPaper = null; } } return labeledPaper; } @Data private static class LabelingOutput { public final List<List<Pair<PaperToken, String>>> labeledData; public final Set<String> usedPaperIds; } private static LabelingOutput labelFromGroundTruth( final Iterator<LabeledPaper> labeledPapers, final int headerMax, final int maxFiles, final int minYear, final boolean checkAuthors, final Set<String> excludeIDs ) throws IOException { final PDFExtractor ext = new PDFExtractor(); // input we need final int parallelism = Runtime.getRuntime().availableProcessors() * 2; final int queueSize = parallelism * 4; final Queue<Future<List<Pair<PaperToken, String>>>> workQueue = new ArrayDeque<>(queueSize); // stuff we need while processing final ExecutorService executor = Executors.newFixedThreadPool(parallelism); final AtomicInteger triedCount = new AtomicInteger(); final ConcurrentMap<String, Long> paperId2startTime = new ConcurrentSkipListMap<>(); // capturing results final ArrayList<List<Pair<PaperToken, String>>> results = new ArrayList<>(maxFiles > 0 ? maxFiles : 1024); final MutableSet<String> usedPaperIds = new UnifiedSet<String>().asSynchronized(); try { if(maxFiles > 0) logger.info("Will be labeling {} papers in {} threads.", maxFiles, parallelism); else logger.info("Will be labeling all papers in {} threads.", parallelism); while (labeledPapers.hasNext() && (maxFiles <= 0 || results.size() < maxFiles)) { // fill up the queue while (labeledPapers.hasNext() && workQueue.size() < queueSize) { final LabeledPaper paper = labeledPapers.next(); final LabeledData labels = paper.labels(); val title = labels.javaTitle(); val authors = labels.javaAuthors(); if (excludeIDs.contains(paper.paperId())) continue; if(minYear > 0) { val year = labels.javaYear(); if(!year.isPresent() || year.getAsInt() < minYear) continue; } final Future<List<Pair<PaperToken, String>>> future = executor.submit(() -> { try { paperId2startTime.put(paper.paperId(), System.currentTimeMillis()); final List<Pair<PaperToken, String>> result; try(final InputStream is = paper.inputStream()) { result = getPaperLabels( paper.paperId(), is, labels, ext, headerMax, checkAuthors); } int tried = triedCount.incrementAndGet(); if (result != null) usedPaperIds.add(paper.paperId()); if (tried % 100 == 0) { // find the document that's been in flight the longest final long now = System.currentTimeMillis(); final Set<Map.Entry<String, Long>> entries = paperId2startTime.entrySet(); final Optional<Map.Entry<String, Long>> maxEntry = entries.stream().max( new Comparator<Map.Entry<String, Long>>() { @Override public int compare( final Map.Entry<String, Long> left, final Map.Entry<String, Long> right ) { final long l = now - left.getValue(); final long r = now - right.getValue(); if (l < r) return -1; else if (l > r) return 1; else return 0; } }); final int succeeded = usedPaperIds.size(); if (maxEntry.isPresent()) { logger.info(String.format( "Tried to label %d papers, succeeded %d times (%.2f%%), %d papers in flight, oldest is %s at %.2f seconds", tried, succeeded, succeeded * 100.0 / (double) tried, entries.size(), maxEntry.get().getKey(), (now - maxEntry.get().getValue()) / 1000.0)); } else { logger.info(String.format( "Tried to label %d papers, succeeded %d times (%.2f%%), 0 papers in flight", tried, succeeded, succeeded * 100.0 / (double) tried)); } } return result; } catch (final IOException e) { logger.warn( "IOException {} while processing paper {}", e.getMessage(), paper.paperId()); return null; } finally { paperId2startTime.remove(paper.paperId()); } }); workQueue.add(future); } // read from the queue val top = workQueue.poll(); try { val result = top.get(); if(result != null) results.add(result); } catch (final InterruptedException e) { logger.warn("Interrupted while processing paper", e); } catch (final ExecutionException e) { logger.warn("ExecutionException while processing paper", e); } } // read the queue empty if we have to while(!workQueue.isEmpty() && (maxFiles <= 0 || results.size() < maxFiles)) { try { val result = workQueue.poll().get(); if(result != null) results.add(result); } catch (final InterruptedException e) { logger.warn("Interrupted while processing paper", e); } catch (final ExecutionException e) { logger.warn("ExecutionException while processing paper", e); } } } finally { executor.shutdown(); try { logger.info("Done labeling papers. Waiting for threads to shut down."); executor.awaitTermination(10, TimeUnit.MINUTES); } catch(final InterruptedException e) { logger.warn("Interrupted while waiting for the executor to shut down. We may be leaking threads.", e); } } logger.info(String.format( "Tried to label %d papers, succeeded %d times (%.2f%%), all done!", triedCount.get(), usedPaperIds.size(), usedPaperIds.size() * 100.0 / triedCount.doubleValue())); return new LabelingOutput(results, usedPaperIds.asUnmodifiable()); } private static UnifiedSet<String> readSet(String inFile) throws IOException { val out = new UnifiedSet<String>(); BufferedReader brIn = new BufferedReader(new FileReader(inFile)); String sLine; while ((sLine = brIn.readLine()) != null) { out.add(sLine); } brIn.close(); return out; } public static void trainBibliographyCRF( final File bibsGroundTruthDirectory, final ParseOpts opts ) throws IOException { final File coraTrainFile = new File(bibsGroundTruthDirectory, "cora-citations.txt"); final File umassTrainFile = new File(bibsGroundTruthDirectory, "umass-citations.txt"); final File kermitTrainFile = new File(bibsGroundTruthDirectory, "kermit-citations.txt"); trainBibliographyCRF(coraTrainFile, umassTrainFile, kermitTrainFile, opts); } public static void trainBibliographyCRF(File coraTrainFile, File umassTrainFile, File kermitTrainFile, ParseOpts opts) throws IOException { List<List<Pair<String, String>>> labeledData; labeledData = CRFBibRecordParser.labelFromCoraFile(coraTrainFile); if(umassTrainFile != null) labeledData.addAll(CRFBibRecordParser.labelFromUMassFile(umassTrainFile)); if(kermitTrainFile != null) labeledData.addAll(CRFBibRecordParser.labelFromKermitFile(kermitTrainFile)); ReferencesPredicateExtractor predExtractor; GazetteerFeatures gf = null; try { if(opts.gazetteerDir != null) gf = new GazetteerFeatures(opts.gazetteerDir); } catch (IOException e) { logger.error("Error importing gazetteer directory, ignoring."); } ParserLMFeatures plf = null; if(opts.gazetteerFile != null) { ParserGroundTruth gaz = new ParserGroundTruth(opts.gazetteerFile); plf = new ParserLMFeatures( gaz.papers, new UnifiedSet<>(), new File(opts.backgroundDirectory), opts.backgroundSamples); predExtractor = new ReferencesPredicateExtractor(plf); } else { predExtractor = new ReferencesPredicateExtractor(); } predExtractor.setGf(gf); // Split train/test data logger.info("CRF training for bibs with {} threads and {} labeled examples", opts.threads, labeledData.size()); Pair<List<List<Pair<String, String>>>, List<List<Pair<String, String>>>> trainTestPair = splitData(labeledData, 1.0 - opts.trainFraction); val trainLabeledData = trainTestPair.getOne(); val testLabeledData = trainTestPair.getTwo(); // Set up Train options CRFTrainer.Opts trainOpts = new CRFTrainer.Opts(); trainOpts.optimizerOpts.maxIters = opts.iterations; trainOpts.numThreads = opts.threads; trainOpts.minExpectedFeatureCount = opts.minExpectedFeatureCount; // set up evaluation function final Parallel.MROpts evalMrOpts = Parallel.MROpts.withIdAndThreads("mr-crf-bib-train-eval", opts.threads); final ToDoubleFunction<CRFModel<String, String, String>> testEvalFn; { final List<List<Pair<String, String>>> testEvalData = testLabeledData. stream(). map(x -> x.stream().map(Pair::swap).collect(toList())). collect(toList()); testEvalFn = (model) -> { final Evaluation<String> eval = Evaluation.compute(model, testEvalData, evalMrOpts); return eval.tokenAccuracy.accuracy(); }; } // set up early stopping so that we stop training after 50 down-iterations final TrainCriterionEval<CRFModel<String, String, String>> earlyStoppingEvaluator = new TrainCriterionEval<>(testEvalFn); earlyStoppingEvaluator.maxNumDipIters = 100; trainOpts.iterCallback = earlyStoppingEvaluator; // training CRFTrainer<String, String, String> trainer = new CRFTrainer<>(trainLabeledData, predExtractor, trainOpts); trainer.train(trainLabeledData); final CRFModel<String, String, String> crfModel = earlyStoppingEvaluator.bestModel; Vector weights = crfModel.weights(); Parallel.shutdownExecutor(evalMrOpts.executorService, Long.MAX_VALUE); val dos = new DataOutputStream(new FileOutputStream(opts.modelFile)); logger.info("Writing model to {}", opts.modelFile); saveModel(dos, crfModel.featureEncoder, weights, plf, gf, ExtractReferences.DATA_VERSION); dos.close(); } public static void trainParser( final Iterator<LabeledPaper> labeledTrainingData, final ParseOpts opts ) throws IOException { trainParser(labeledTrainingData, opts, UnifiedSet.newSet()); } public static void trainParser( final Iterator<LabeledPaper> labeledTrainingData, final ParseOpts opts, final String excludeIDsFile ) throws IOException { final UnifiedSet<String> excludedIDs; if (excludeIDsFile == null) excludedIDs = new UnifiedSet<>(); else excludedIDs = readSet(excludeIDsFile); trainParser(labeledTrainingData, opts, excludedIDs); } public static void trainParser( Iterator<LabeledPaper> labeledTrainingData, ParseOpts opts, final UnifiedSet<String> excludeIDs ) throws IOException { final LabelingOutput labelingOutput = labelFromGroundTruth( labeledTrainingData, opts.headerMax, opts.documentCount, opts.minYear, opts.checkAuthors, excludeIDs); ParserLMFeatures plf = null; final PDFPredicateExtractor predExtractor; if (opts.gazetteerFile != null) { ParserGroundTruth gaz = new ParserGroundTruth(opts.gazetteerFile); UnifiedSet<String> excludedIds = new UnifiedSet<String>(labelingOutput.usedPaperIds); excludedIds.addAll(excludeIDs); plf = new ParserLMFeatures( gaz.papers, excludedIds, new File(opts.backgroundDirectory), opts.backgroundSamples); predExtractor = new PDFPredicateExtractor(plf); } else { predExtractor = new PDFPredicateExtractor(); } // Split train/test data logger.info( "CRF training with {} threads and {} labeled examples", opts.threads, labelingOutput.labeledData.size()); Pair<List<List<Pair<PaperToken, String>>>, List<List<Pair<PaperToken, String>>>> trainTestPair = splitData(labelingOutput.labeledData, 1.0 - opts.trainFraction); val trainLabeledData = trainTestPair.getOne(); val testLabeledData = trainTestPair.getTwo(); // log test and training data if(labeledDataLogger.isDebugEnabled()) { labeledDataLogger.info("Training data before:"); logLabeledData(trainLabeledData); labeledDataLogger.info("Test data before:"); logLabeledData(testLabeledData); } // Set up Train options CRFTrainer.Opts trainOpts = new CRFTrainer.Opts(); trainOpts.optimizerOpts.maxIters = opts.iterations; trainOpts.numThreads = opts.threads; trainOpts.minExpectedFeatureCount = opts.minExpectedFeatureCount; // set up evaluation function final Parallel.MROpts evalMrOpts = Parallel.MROpts.withIdAndThreads("mr-crf-train-eval", opts.threads); final ToDoubleFunction<CRFModel<String, PaperToken, String>> testEvalFn; { final List<List<Pair<String, PaperToken>>> testEvalData = testLabeledData. stream(). map(x -> x.stream().map(Pair::swap).collect(toList())). collect(toList()); testEvalFn = (model) -> { final Evaluation<String> eval = Evaluation.compute(model, testEvalData, evalMrOpts); logger.info("Test Label F-measures"); eval.stateFMeasures.forEach((label, fMeasure) -> { logger.info(String.format("-- %s: p:%.3f r:%.3f f1:%.3f", label, fMeasure.precision(), fMeasure.recall(), fMeasure.f1())); }); logger.info(""); return eval.tokenAccuracy.accuracy(); }; } // set up early stopping so that we stop training after 50 down-iterations final TrainCriterionEval<CRFModel<String, PaperToken, String>> earlyStoppingEvaluator = new TrainCriterionEval<>(testEvalFn); earlyStoppingEvaluator.maxNumDipIters = 100; trainOpts.iterCallback = earlyStoppingEvaluator; // training final CRFTrainer<String, PaperToken, String> trainer = new CRFTrainer<>(trainLabeledData, predExtractor, trainOpts); trainer.train(trainLabeledData); final CRFModel<String, PaperToken, String> crfModel = earlyStoppingEvaluator.bestModel; final Vector weights = crfModel.weights(); Parallel.shutdownExecutor(evalMrOpts.executorService, Long.MAX_VALUE); try(val dos = new DataOutputStream(new FileOutputStream(opts.modelFile))) { logger.info("Writing model to {}", opts.modelFile); saveModel(dos, crfModel.featureEncoder, weights, plf); } // log test and training data if(labeledDataLogger.isDebugEnabled()) { labeledDataLogger.info("Training data after:"); logLabeledData(trainLabeledData); labeledDataLogger.info("Test data after:"); logLabeledData(testLabeledData); } } private static void logLabeledData(final List<List<Pair<PaperToken, String>>> data) { for(List<Pair<PaperToken, String>> line : data) { final String logLine = line.stream().map(pair -> String.format( "%s/%x/%s", pair.getOne().getPdfToken() == null ? "null" : pair.getOne().getPdfToken().getToken(), pair.getOne().hashCode(), pair.getTwo())).collect(Collectors.joining(" ")); labeledDataLogger.info(logLine); } } public static <T> void saveModel( final DataOutputStream dos, final CRFFeatureEncoder<String, T, String> fe, final Vector weights, final ParserLMFeatures plf, final String dataVersion ) throws IOException { saveModel(dos, fe,weights, plf, null, dataVersion); } public static <T> void saveModel( final DataOutputStream dos, final CRFFeatureEncoder<String, T, String> fe, final Vector weights, final ParserLMFeatures plf, final GazetteerFeatures gf, final String dataVersion ) throws IOException { dos.writeUTF(dataVersion); fe.stateSpace.save(dos); fe.nodeFeatures.save(dos); fe.edgeFeatures.save(dos); IOUtils.saveDoubles(dos, weights.toDoubles()); logger.debug("Saving ParserLMFeatures"); try(final FSTObjectOutput out = new FSTObjectOutput(dos)) { out.writeObject(plf); if (plf != null) plf.logState(); logger.debug("Saving gazetteer features"); out.writeObject(gf); } } public static <T> void saveModel( final DataOutputStream dos, final CRFFeatureEncoder<String, T, String> fe, final Vector weights, final ParserLMFeatures plf ) throws IOException { saveModel(dos, fe, weights, plf, Parser.DATA_VERSION); } @Data public static class ModelComponents { public final PDFPredicateExtractor predExtractor; public final CRFFeatureEncoder<String, PaperToken, String> featureEncoder; public final CRFWeightsEncoder<String> weightsEncoder; public final CRFModel<String, PaperToken, String> model; } public static ModelComponents loadModelComponents( final DataInputStream dis, String dataVersion ) throws IOException { IOUtils.ensureVersionMatch(dis, dataVersion); val stateSpace = StateSpace.load(dis); Indexer<String> nodeFeatures = Indexer.load(dis); Indexer<String> edgeFeatures = Indexer.load(dis); Vector weights = DenseVector.of(IOUtils.loadDoubles(dis)); logger.debug("Loading ParserLMFeatures"); final ParserLMFeatures plf; try(final FSTObjectInput in = new FSTObjectInput(dis)) { try { plf = (ParserLMFeatures) in.readObject(); } catch (final ClassNotFoundException e) { throw new IOException("Model file contains unknown class.", e); } } if(plf != null && logger.isDebugEnabled()) plf.logState(); val predExtractor = new PDFPredicateExtractor(plf); val featureEncoder = new CRFFeatureEncoder<String, PaperToken, String> (predExtractor, stateSpace, nodeFeatures, edgeFeatures); val weightsEncoder = new CRFWeightsEncoder<String>(stateSpace, nodeFeatures.size(), edgeFeatures.size()); val model = new CRFModel<String, PaperToken, String>(featureEncoder, weightsEncoder, weights); return new ModelComponents(predExtractor, featureEncoder, weightsEncoder, model); } public static ModelComponents loadModelComponents( final DataInputStream dis ) throws IOException { return loadModelComponents(dis, DATA_VERSION); } public static CRFModel<String, PaperToken, String> loadModel( final DataInputStream dis ) throws IOException { return loadModelComponents(dis).model; } public static void clean(ExtractedMetadata em) { em.title = cleanTitle(em.title); em.authors = trimAuthors(em.authors); } public static String cleanTitle(String t) { if (t == null || t.length() == 0) return t; // strip accents and unicode changes t = Normalizer.normalize(t, Normalizer.Form.NFKD); // kill non-character letters // kill xml t = t.replaceAll("\\&.*?\\;", ""); if (t.endsWith(".")) t = t.substring(0, t.length() - 1); return t; } public static String processTitle(String t) { // case fold and remove lead/trail space if(t==null || t.length()==0) return t; t = t.trim().toLowerCase(); t = cleanTitle(t); // kill non-letter chars t = t.replaceAll("\\W", ""); return t.replaceAll("\\s+", " "); } //changes extraction to remove common failure modes public static String processExtractedTitle(String t) { String out = t.replaceAll("(?<=[a-z])\\- ", ""); //continuation dash if (!out.endsWith("?") && !out.endsWith("\"") && !out.endsWith(")")) out = out.replaceFirst("\\W$", ""); //end of title punctuation if not ?, ", or ) return out.trim(); } //lowercases public static String lastName(String s) { String[] words = s.split(" "); if (words.length > 0) return processTitle(words[words.length - 1]); else return ""; } public static List<String> lastNames(List<String> ss) { return (ss==null)?null:ss.stream().map(s -> lastName(s)).collect(Collectors.toList()); } public static int scoreAuthors(String[] expected, List<String> guessed) { List<String> guessLastName = lastNames(guessed); List<String> expectedLastName = lastNames(Arrays.asList(expected)); //slow: int truePos = 0; for (String s : expectedLastName) { if (guessLastName.contains(s)) truePos++; } return truePos; } /** Fixes common author problems. This is applied to the output of both normalized and * unnormalized author names, and it is used in training as well. Experience shows that if you * make changes here, there is a good chance you'll need to retrain, even if you think the change * is fairly trivial. */ public static String fixupAuthors(String s) { // delete trailing special characters String sFix = s.replaceAll("([^\\p{javaLowerCase}\\p{javaUpperCase}])+$", ""); if (sFix.contains(",")) sFix = sFix.substring(0, sFix.indexOf(",")); if (sFix.endsWith("Jr")) sFix = sFix + "."; return sFix; } private final static int MAX_AUTHOR_LENGTH = 32; private final static int MIN_AUTHOR_LENGTH = 2; public static List<String> trimAuthors(List<String> auth) { return auth.stream(). flatMap(s -> Arrays.stream(s.split("(?!,\\s*Jr),|\\band\\b"))). map(String::trim). map(Parser::fixupAuthors). filter(s -> !s.isEmpty()). filter(s -> s.length() <= MAX_AUTHOR_LENGTH). filter(s -> s.length() >= MIN_AUTHOR_LENGTH). distinct(). collect(Collectors.toList()); } public static class ParsingTimeout extends RuntimeException { } private final Timer parserKillerTimer = new Timer("Science-parse killer timer", true); private final MutableIntSet parseNumbersInProgress = IntSets.mutable.empty(); private final AtomicInteger nextParseNumber = new AtomicInteger(); public ExtractedMetadata doParseWithTimeout(final InputStream is, final long timeoutInMs) throws IOException { final int parseNumber = nextParseNumber.getAndIncrement(); final Thread t = Thread.currentThread(); final TimerTask killTaskHard = new TimerTask() { @Override public void run() { synchronized (parseNumbersInProgress) { if(parseNumbersInProgress.contains(parseNumber)) { logger.info("Killing parsing thread {} because it's taking too long", t.getId()); t.stop(); // I know this is dangerous. This is a last resort. } } } }; final TimerTask killTaskSoftly = new TimerTask() { @Override public void run() { synchronized (parseNumbersInProgress) { if(parseNumbersInProgress.contains(parseNumber)) { logger.info("Interrupting parsing thread {} because it's taking too long", t.getId()); t.interrupt(); } } } }; synchronized (parseNumbersInProgress) { parseNumbersInProgress.add(parseNumber); } final ExtractedMetadata result; final boolean wasInterrupted; parserKillerTimer.schedule(killTaskSoftly, timeoutInMs); parserKillerTimer.schedule(killTaskHard, 3*timeoutInMs); try { try { result = doParse(is); } catch(final ThreadDeath e) { throw new RuntimeException("Science-parse killer got impatient", e); } } finally { synchronized (parseNumbersInProgress) { parseNumbersInProgress.remove(parseNumber); } // This clears the interrupted flag, in case it happened after we were already done parsing, // but before we could remove the parse number. We don't want to leave this function with // the interrupted flag set on the thread. // Actually, the window of opportunity is from the last time that doParse() checks the // flag to the time we remove the parse number, which is quite a bit bigger. wasInterrupted = Thread.interrupted(); } if(wasInterrupted) logger.info("Overriding interruption of parsing thread {} because it finished before we could react", t.getId()); assert !Thread.interrupted(); return result; } public ExtractedMetadata doParse(final InputStream is) throws IOException { return doParse(is, MAXHEADERWORDS); } /** * Given a body of text (e.g. an entire section of a paper) within which a citation is mentioned, extracts a * single-sentence context from that larger body of text. Used both here for Science Parse extraction and in * GrobidParser for evaluation of Grobid citation mention extraction. */ public static CitationRecord extractContext(int referenceID, String context, int begin, int end) { int sentenceStart = begin; // Some citation have the form "This is my sentence.(1,2)". So if we just search backwards from // `begin`, we find the end of the sentence we want, rather than the beginning. Thus, we rewind // `sentenceStart` a little if necessary. while( sentenceStart > 0 && ( context.charAt(sentenceStart) == '(' || context.charAt(sentenceStart) == '[' || context.charAt(sentenceStart) == '.' || context.charAt(sentenceStart) == '⍐' ) ) { sentenceStart -= 1; } sentenceStart = context.substring(0, sentenceStart).lastIndexOf('.') + 1; // this evaluates to 0 if '.' is not found // Trim away superscripts at the beginning of sentences. if(context.charAt(sentenceStart) == '⍐') { final int newSentenceStart = context.indexOf('⍗', sentenceStart); if(newSentenceStart > 0 && newSentenceStart < begin) sentenceStart = newSentenceStart + 1; } int crSentenceEnd = context.indexOf('.', end); if(crSentenceEnd < 0) crSentenceEnd = context.length(); else crSentenceEnd += 1; String contextSentenceUntrimmed = context.substring(sentenceStart, crSentenceEnd); String contextSentence = contextSentenceUntrimmed.trim(); sentenceStart += contextSentenceUntrimmed.indexOf(contextSentence); return new CitationRecord(referenceID, contextSentence, begin - sentenceStart, end - sentenceStart); } public ExtractedMetadata doParse(final InputStream is, int headerMax) throws IOException { final ExtractedMetadata em; final PDDocument pdDoc = PDDocument.load(is); // // Run Science-parse // { PDFExtractor ext = new PDFExtractor(); final PDFDoc doc = ext.extractResultFromPDDocument(pdDoc).document; final PDFDoc docWithoutSuperscripts = doc.withoutSuperscripts(); List<PaperToken> seq = PDFToCRFInput.getSequence(docWithoutSuperscripts); seq = seq.subList(0, Math.min(seq.size(), headerMax)); seq = PDFToCRFInput.padSequence(seq); { // get title and authors from the CRF List<String> outSeq = model.bestGuess(seq); //the output tag sequence will not include the start/stop states! outSeq = PDFToCRFInput.padTagSequence(outSeq); em = new ExtractedMetadata(seq, outSeq); em.source = ExtractedMetadata.Source.CRF; } // use PDF metadata if it's there if (doc.meta != null) { if (doc.meta.title != null) { em.setTitle(doc.meta.title); em.source = ExtractedMetadata.Source.META; } if (doc.meta.createDate != null) em.setYearFromDate(doc.meta.createDate); } clean(em); if(doc.meta != null) em.creator = doc.meta.creator; // extract references try { final List<String> lines = PDFDocToPartitionedText.getRaw(doc); final List<String> rawReferences = PDFDocToPartitionedText.getRawReferences(doc); final Pair<List<BibRecord>, List<CitationRecord>> pair = getReferences(lines, rawReferences, referenceExtractor); em.references = new ArrayList<>(pair.getOne().size()); for(final BibRecord record : pair.getOne()) em.references.add(record.withoutSuperscripts()); // add contexts to the mentions List<CitationRecord> crs = new ArrayList<>(); for(final CitationRecord cr : pair.getTwo()) { final CitationRecord crWithContext = extractContext(cr.referenceID, cr.context, cr.startOffset, cr.endOffset); final int contextLength = crWithContext.context.length() - (crWithContext.endOffset - crWithContext.startOffset); if(contextLength >= 35) // Heuristic number crs.add(crWithContext); } // find the predominant mention style, and assign it to em.referenceMentions final Function<CitationRecord, Character> getMentionStyle = (final CitationRecord cr) -> { char firstChar = cr.context.charAt(cr.startOffset); if(firstChar == '(' || firstChar == '[' || firstChar == '⍐') return firstChar; else return '\0'; }; final MutableCharIntMap styleToCount = CharIntMaps.mutable.empty(); int maxStyleCount = 0; char predominantStyle = '\0'; for(final CitationRecord cr : crs) { final char style = getMentionStyle.apply(cr); final int newStyleCount = styleToCount.addToValue(style, 1); if(newStyleCount > maxStyleCount) { maxStyleCount = newStyleCount; predominantStyle = style; } } // Override this in a special case: If we have more than 4 in the [] style, let's take that // as the style. That style is unlikely to happen by accident, while the () style happens // all the time in other contexts. if(predominantStyle == '(' && styleToCount.getIfAbsent('[', 0) > 4) predominantStyle = '['; em.referenceMentions = new ArrayList<>(crs.size()); for(final CitationRecord cr : crs) if(predominantStyle == '\0' || getMentionStyle.apply(cr) == predominantStyle) em.referenceMentions.add(cr.withConvertedSuperscriptTags()); } catch (final RegexWithTimeout.RegexTimeout|Parser.ParsingTimeout e) { logger.warn("Timeout while extracting references. References may be incomplete or missing."); if (em.references == null) em.references = Collections.emptyList(); if (em.referenceMentions == null) em.referenceMentions = Collections.emptyList(); } logger.debug(em.references.size() + " refs for " + em.title); try { final List<String> lines = PDFDocToPartitionedText.getRaw(docWithoutSuperscripts); // Fix-up of lines that should not be necessary, but is for(int i = 0; i < lines.size(); ++i) { final String s = lines.get(i).replaceAll("-<lb>", "").replaceAll("<lb>", " "); lines.set(i, s); } em.abstractText = PDFDocToPartitionedText.getAbstract(lines, docWithoutSuperscripts).trim(); em.abstractText = em.abstractText.replaceAll("⍐[^⍗]⍗", ""); if (em.abstractText.isEmpty()) em.abstractText = null; } catch (final RegexWithTimeout.RegexTimeout|Parser.ParsingTimeout e) { logger.warn("Timeout while extracting abstract. Abstract will be missing."); em.abstractText = null; } } // // Run figure extraction to get sections // try { final FigureExtractor fe = new FigureExtractor(false, true, true, true, true); final FigureExtractor.Document doc = fe.getFiguresWithText(pdDoc, scala.Option.apply(null), scala.Option.apply(null)); em.sections = ScalaStreamSupport.stream(doc.sections()).map(documentSection -> new Section( OptionConverters.toJava(documentSection.titleText()).orElse(null), documentSection.bodyText() ) ).filter(documentSection -> // filter out reference sections !( documentSection.getHeading() != null && PDFDocToPartitionedText.referenceHeaders.contains( documentSection.getHeading().trim().toLowerCase().replaceAll("\\p{Punct}*$", "")) ) ).collect(Collectors.toList()); } catch (final Exception e) { logger.warn( "Exception {} while getting sections. Section data will be missing.", e.getMessage()); em.sections = null; } return em; } public static class ParseOpts { public String modelFile; public int iterations; public int threads; public int headerMax; public double trainFraction; public String gazetteerFile; //record of references public String gazetteerDir; //directory of entity lists (universities, person names, etc.) public int backgroundSamples; public String backgroundDirectory; public int minYear; //only process papers this year or later public boolean checkAuthors; //only bootstraps papers if all authors are found public int documentCount = -1; // how many documents to train on. set to -1 to train on all. public int minExpectedFeatureCount = 1; } }
45,921
37.687447
141
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/ParserGroundTruth.java
package org.allenai.scienceparse; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import lombok.Data; import lombok.extern.slf4j.Slf4j; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @Slf4j public class ParserGroundTruth { public List<Paper> papers; public HashMap<String, Integer> lookup = new HashMap<>(); private void buildLookup() { for (int i = 0; i < papers.size(); i++) { lookup.put(papers.get(i).id.substring(4), i); } } public ParserGroundTruth(List<Paper> papers) throws IOException { this.papers = papers; buildLookup(); } public ParserGroundTruth(final InputStream is) throws IOException { try(final BufferedReader reader = new BufferedReader( new InputStreamReader(is, "UTF-8"))) { ObjectMapper om = new ObjectMapper(); ObjectReader r = om.reader().forType(new TypeReference<Paper>() {}); papers = new ArrayList<Paper>(); while (true) { final String line = reader.readLine(); if (line == null) break; papers.add(r.readValue(line)); } } log.info("Read " + papers.size() + " papers."); buildLookup(); papers.forEach((Paper p) -> { for (int i = 0; i < p.authors.length; i++) p.authors[i] = invertAroundComma(p.authors[i]); }); } public ParserGroundTruth(String jsonFile) throws IOException { this(new FileInputStream(jsonFile)); } public static String invertAroundComma(String in) { String[] fields = in.split(","); if (fields.length == 2) return (fields[1] + " " + fields[0]).trim(); else return in; } public Paper forKey(String key) { if (!lookup.containsKey(key)) { log.info("key not found: " + key); return null; } return papers.get(lookup.get(key)); } @Data public static class Paper { String id; String url; String title; String[] authors; int year; String venue; } }
2,250
23.736264
74
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/ParserLMFeatures.java
package org.allenai.scienceparse; import com.gs.collections.api.block.procedure.primitive.ObjectDoubleProcedure; import com.gs.collections.impl.map.mutable.primitive.ObjectDoubleHashMap; import com.gs.collections.impl.set.mutable.UnifiedSet; import lombok.extern.slf4j.Slf4j; import org.allenai.scienceparse.ParserGroundTruth.Paper; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @Slf4j public class ParserLMFeatures implements Serializable { /** * */ private static final long serialVersionUID = 1L; final ObjectDoubleHashMap<String> titleBow = new ObjectDoubleHashMap<String>(); final ObjectDoubleHashMap<String> titleFirstBow = new ObjectDoubleHashMap<String>(); final ObjectDoubleHashMap<String> titleLastBow = new ObjectDoubleHashMap<String>(); final ObjectDoubleHashMap<String> titleBagOfCharTrigrams = new ObjectDoubleHashMap<String>(); final ObjectDoubleHashMap<String> authorBow = new ObjectDoubleHashMap<String>(); final ObjectDoubleHashMap<String> authorFirstBow = new ObjectDoubleHashMap<String>(); final ObjectDoubleHashMap<String> authorLastBow = new ObjectDoubleHashMap<String>(); final ObjectDoubleHashMap<String> authorBagOfCharTrigrams = new ObjectDoubleHashMap<String>(); final ObjectDoubleHashMap<String> backgroundBow = new ObjectDoubleHashMap<String>(); final ObjectDoubleHashMap<String> venueBow = new ObjectDoubleHashMap<String>(); final ObjectDoubleHashMap<String> venueFirstBow = new ObjectDoubleHashMap<String>(); final ObjectDoubleHashMap<String> venueLastBow = new ObjectDoubleHashMap<String>(); public ParserLMFeatures() { } //paperDirectory must contain pdf docs to use as background language model public ParserLMFeatures( List<Paper> ps, UnifiedSet<String> idsToExclude, File paperDirectory, int approxNumBackgroundDocs ) throws IOException { log.info("Excluding {} paper ids from LM features", idsToExclude.size()); for(Paper p : ps) { if (!idsToExclude.contains(p.id)) { fillBow(titleBow, p.title, titleFirstBow, titleLastBow, titleBagOfCharTrigrams, false); fillBow(venueBow, p.venue, venueFirstBow, venueLastBow, null, false); for (String a : p.authors) fillBow(authorBow, a, authorFirstBow, authorLastBow, authorBagOfCharTrigrams, true); } } log.info( "Getting token statistics from approximately {} background papers in {}", approxNumBackgroundDocs, paperDirectory); final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); final CompletionService<String[]> completionService = new ExecutorCompletionService<>(executor); try { final File[] pdfs = paperDirectory.listFiles(new FilenameFilter() { @Override public boolean accept(File f, String s) { return s.endsWith(".pdf"); } }); // put in the paper reading and tokenization tasks final double step = ((double) approxNumBackgroundDocs) / ((double) pdfs.length); double value = 0; int submittedPapers = 0; for(File pdf: pdfs) { value += step; if(value >= 1.0) { value -= 1.0; completionService.submit(() -> { final String paperString = Parser.paperToString(pdf); if(paperString != null) { return tokenize(paperString); } else { return null; } }); submittedPapers += 1; } } // process the tokenized papers int ct = 0; int successfulPapers = 0; int failedPapers = 0; while(submittedPapers > successfulPapers + failedPapers) { final String[] tokens; try { tokens = completionService.take().get(); } catch(final InterruptedException|ExecutionException e) { throw new RuntimeException(e); } if(tokens != null) { ct += fillBow(backgroundBow, tokens, null, null, null, false); successfulPapers += 1; } else { failedPapers += 1; } } log.info("Gazetteer loaded with {} tokens", ct); log.info( String.format( "Tried %d papers, succeeded on %d (%.2f%%)", submittedPapers, successfulPapers, 100.0 * successfulPapers / (double)submittedPapers)); } finally { executor.shutdown(); try { executor.awaitTermination(10, TimeUnit.SECONDS); } catch(final InterruptedException e) { // do nothing } } } public static int fillBow( ObjectDoubleHashMap<String> hm, String s, ObjectDoubleHashMap<String> firstHM, ObjectDoubleHashMap<String> lastHM, ObjectDoubleHashMap<String> trigramHM, boolean doTrim ) { if(s == null) return 0; else return fillBow(hm, tokenize(s), firstHM, lastHM, trigramHM, doTrim); } public static int fillBow(ObjectDoubleHashMap<String> hm, String s, boolean doTrim) { return fillBow(hm, s, null, null, null, doTrim); } public static void addTrigrams(ObjectDoubleHashMap<String> hm, String t) { if(t == null) return; t = "^" + t + "$"; int len = t.length(); for(int i=0; i<len - 3; i++) { hm.addToValue(t.substring(i, i+3), 1.0); } } private static int fillBow( ObjectDoubleHashMap<String> hm, String[] toks, ObjectDoubleHashMap<String> firstHM, ObjectDoubleHashMap<String> lastHM, ObjectDoubleHashMap<String> trigramHM, boolean doTrim ) { int ct = 0; if (toks.length > 0) { if (firstHM != null) firstHM.addToValue(doTrim ? Parser.fixupAuthors(toks[0]) : toks[0], 1.0); if (lastHM != null) lastHM.addToValue(doTrim ? Parser.fixupAuthors(toks[toks.length - 1]) : toks[toks.length - 1], 1.0); } for (String t : toks) { hm.addToValue(doTrim ? Parser.fixupAuthors(t) : t, 1.0); if(trigramHM != null) addTrigrams(trigramHM, doTrim ? Parser.fixupAuthors(t) : t); ct++; } return ct; } private static String[] tokenize(final String s) { return s.split("( )"); //not great } private void logBow(final String name, final ObjectDoubleHashMap<String> bow) { // This goes out of its way to print the BOW in a repeatable order. log.debug("{}: {} elements", name, bow.size()); final String[] keysArray = new String[bow.size()]; final String[] keys = bow.keySet().toArray(keysArray); Arrays.sort(keys); for(final String key: keys) { final double value = bow.get(key); log.debug("{}: {} = {}", name, key, value); } } public void logState() { logBow("titleBow", titleBow); logBow("titleFirstBow", titleFirstBow); logBow("titleLastBow", titleLastBow); logBow("titleBagOfCharTrigrams", titleBagOfCharTrigrams); logBow("authorBow", authorBow); logBow("authorFirstBow", authorFirstBow); logBow("authorLastBow", authorLastBow); logBow("authorBagOfCharTrigrams", authorBagOfCharTrigrams); logBow("backgroundBow", backgroundBow); logBow("venueBow", venueBow); logBow("venueFirstBow", venueFirstBow); logBow("venueLastBow", venueLastBow); } }
7,797
33.8125
108
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/ReferencesPredicateExtractor.java
package org.allenai.scienceparse; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; import org.allenai.ml.sequences.crf.CRFPredicateExtractor; import org.allenai.scienceparse.ExtractedMetadata.LabelSpan; import com.gs.collections.api.map.primitive.ObjectDoubleMap; import com.gs.collections.impl.map.mutable.primitive.ObjectDoubleHashMap; import org.allenai.word2vec.Searcher; import org.allenai.datastore.Datastore; import lombok.Setter; import lombok.val; public class ReferencesPredicateExtractor implements CRFPredicateExtractor<String, String> { private ParserLMFeatures lmFeats; private final Searcher word2vecSearcher; public static final Pattern yearPattern = Pattern.compile("((?:19|20)[0-9][0-9])"); @Setter private GazetteerFeatures gf; public ReferencesPredicateExtractor() { this(null); } public ReferencesPredicateExtractor(ParserLMFeatures lmf) { try { final Path word2VecModelPath = Datastore.apply().filePath("org.allenai.scienceparse", "Word2VecModel.bin", 1); word2vecSearcher = WordVectorCache.searcherForPath(word2VecModelPath); } catch(final IOException e) { throw new RuntimeException(e); } lmFeats = lmf; } public int locationBin(int i, int total) { return (12 * i) / total; } public int addPunctuationFeatures(String tok, ObjectDoubleHashMap<String> m) { //TODO: use a list and loop here Pattern pInitialQuote = Pattern.compile("\\p{Pi}"); Pattern pEndQuote = Pattern.compile("\\p{Pf}"); Pattern pDoubleDash = Pattern.compile("\\p{Pd}\\p{Pd}"); //Pattern pContinuing = Pattern.compile(",;:$"); Pattern pColon = Pattern.compile(":$"); Pattern pComma = Pattern.compile(",$"); Pattern pSemicolon = Pattern.compile(";$"); Pattern pEnding = Pattern.compile("(\\.$|\\p{Pf}$)"); Pattern pPairedBraces = Pattern.compile("\\p{Ps}.*\\p{Pe}"); int ct = 0; if(RegexWithTimeout.matcher(pInitialQuote, tok).find()) { m.put("%pInitialQuote", 1.0); ct++; } if(RegexWithTimeout.matcher(pEndQuote, tok).find()) { m.put("%pEndQuote", 1.0); ct++; } if(RegexWithTimeout.matcher(pDoubleDash, tok).find()) { m.put("%pDoubleDash", 1.0); ct++; } if(RegexWithTimeout.matcher(pComma, tok).find()) { m.put("%pComma", 1.0); ct++; } if(RegexWithTimeout.matcher(pColon, tok).find()) { m.put("%pColon", 1.0); ct++; } if(RegexWithTimeout.matcher(pSemicolon, tok).find()) { m.put("%pSemicolon", 1.0); ct++; } if(RegexWithTimeout.matcher(pEnding, tok).find()) { m.put("%pEnding", 1.0); ct++; } if(RegexWithTimeout.matcher(pPairedBraces, tok).find()) { m.put("%pPairedBraces", 1.0); ct++; } return ct; } //borrowing from ParsCit's features public int addNumberFeatures(String tok, ObjectDoubleHashMap<String> m) { int ct = 0; Pattern pPageRange = Pattern.compile("[0-9]+-[0-9]+\\p{P}?"); if(RegexWithTimeout.matcher(pPageRange, tok).matches()) { m.put("%pRange", 1.0); ct++; } if(RegexWithTimeout.matcher(yearPattern, tok).find()) { m.put("%hasYear", 1.0); } Pattern pVolume = Pattern.compile("[0-9](\\([0-9]+\\))?\\p{P}?"); if(RegexWithTimeout.matcher(pVolume, tok).matches()) { m.put("%pVolume", 1.0); ct++; } Pattern pDigits = Pattern.compile("[0-9]+\\p{P}?"); if(RegexWithTimeout.matcher(pDigits, tok).matches()) { int len = Math.min(tok.length(), 5); String digFeat = "%digs" + len; m.put(digFeat, 1.0); } if(RegexWithTimeout.matcher(pDigits, tok).find()) { m.put("%hasDigit", 1.0); } else { m.put("%noDigit", 1.0); } Pattern pOrdinal = Pattern.compile("[0-9]+(st|nd|rd|th)\\p{P}?"); if(RegexWithTimeout.matcher(pOrdinal, tok).find()) { m.put("%ordinal", 1.0); } return ct; } public static boolean containsEditor(List<String> elems) { for(String sOrig : elems) { String s = sOrig.replaceAll(",", ""); if(s.equalsIgnoreCase("eds.")||s.equalsIgnoreCase("ed.")||s.equalsIgnoreCase("editor")||s.equalsIgnoreCase("editors")) return true; } return false; } public static boolean isMonth(String tok) { List<String> months = Arrays.asList("January", "February", "March", "April", "June", "July", "August", "September", "October", "November", "December", "Jan.", "Feb.", "Mar.", "Apr.", "Jun.", "Jul.", "Aug.", "Sept.", "Oct.", "Nov.", "Dec."); if(months.contains(tok.replaceAll(",", ""))) return true; else return false; } public static boolean addTokenFeatures(String tok, ObjectDoubleHashMap<String> m) { // m.put("%raw=" + tok, 1.0); // m.put("%rawlc=" + tok.toLowerCase(), 1.0); m.put("%rawnopunct=" + tok.toLowerCase().replaceAll("\\p{P}", ""), 1.0); // ObjectDoubleHashMap<String> hmTgrams = new ObjectDoubleHashMap<>(); // ParserLMFeatures.addTrigrams(hmTgrams, tok); // for(String s: hmTgrams.keySet()) // m.put("%tgram=" + s, 1.0); String prefix = tok.substring(0, Math.min(tok.length(), 4)); String suffix = tok.substring(Math.max(tok.length() - 4, 0)); m.put("%prefix=" + prefix, 1.0); m.put("%suffix=" + suffix, 1.0); return true; } public void addGazetteerSpan(List<ObjectDoubleMap<String>> preds, LabelSpan ls) { if(ls.loc.getOne()==ls.loc.getTwo()-1) { ((ObjectDoubleHashMap<String>)preds.get(ls.loc.getOne())).put("%gaz_W_" + ls.tag, 1.0); } else { ((ObjectDoubleHashMap<String>)preds.get(ls.loc.getOne())).put("%gaz_B_" + ls.tag, 1.0); for(int i=ls.loc.getOne()+1; i<ls.loc.getTwo()-1; i++) { ((ObjectDoubleHashMap<String>)preds.get(i)).put("%gaz_I_" + ls.tag, 1.0); } ((ObjectDoubleHashMap<String>)preds.get(ls.loc.getTwo()-1)).put("%gaz_E_" + ls.tag, 1.0); } //why all the casts here? Java won't let me upcast to ObjectDoubleMap, but will let me //downcast to MutableObjectDoubleMap. I am confused by this. } /** * Adds gazetteer predicates to passed-in preds list * @param elems * @param preds */ public void addGazetteerPredicates(List<String> elems, List<ObjectDoubleMap<String>> preds) { if(gf != null) for(LabelSpan ls : gf.getSpans(elems)) { addGazetteerSpan(preds, ls); } } @Override public List<ObjectDoubleMap<String>> nodePredicates(List<String> elems) { List<ObjectDoubleMap<String>> out = new ArrayList<>(); boolean hasEditor = containsEditor(elems); for (int i = 0; i < elems.size(); i++) { ObjectDoubleHashMap<String> m = new ObjectDoubleHashMap<>(); //word features: String tok = elems.get(i); PDFPredicateExtractor.getCaseMasks(tok).forEach( (String s) -> m.put(s, 1.0)); //case masks if (PDFPredicateExtractor.isStopWord(tok)) { m.put("%stop", 1.0); //stop word if (m.containsKey("%XXX") || m.containsKey("%Xxx")) m.put("%startCapStop", 1.0); //is a stop word that starts with a capital letter } else { if (m.containsKey("%xxx")) { m.put("%uncapns", 1.0); //is an uncapitalized stop word } } double adjLen = Math.min(tok.length(), 10.0) / 10.0; double adjLenSq = (adjLen - 0.5) * (adjLen - 0.5); m.put("%adjLen", adjLen); //adjusted word length m.put("%adjLenSq", adjLenSq); //adjusted word length squared (?) if (lmFeats != null) { //how well does token match title/author gazeetters m.put("%tfreq", PDFPredicateExtractor.smoothFreq(tok, this.lmFeats.titleBow)); m.put("%tffreq", PDFPredicateExtractor.smoothFreq(tok, this.lmFeats.titleFirstBow)); m.put("%tlfreq", PDFPredicateExtractor.smoothFreq(tok, this.lmFeats.titleLastBow)); // ObjectDoubleHashMap<String> hmTgrams = new ObjectDoubleHashMap<>(); // ParserLMFeatures.addTrigrams(hmTgrams, tok); // for(String s: hmTgrams.keySet()) // m.addToValue("%titleTG", PDFPredicateExtractor.smoothFreq(s, this.lmFeats.titleBagOfCharTrigrams)); // m.put("%titleTG", m.get("%titleTG")/(tok.length()+2)); //use average m.put("%afreq", PDFPredicateExtractor.smoothFreq(Parser.fixupAuthors(tok), this.lmFeats.authorBow)); m.put("%affreq", PDFPredicateExtractor.smoothFreq(Parser.fixupAuthors(tok), this.lmFeats.authorFirstBow)); m.put("%alfreq", PDFPredicateExtractor.smoothFreq(Parser.fixupAuthors(tok), this.lmFeats.authorLastBow)); // hmTgrams = new ObjectDoubleHashMap<>(); // ParserLMFeatures.addTrigrams(hmTgrams, Parser.fixupAuthors(tok)); // for(String s: hmTgrams.keySet()) // m.addToValue("%authorTG", PDFPredicateExtractor.smoothFreq(s, this.lmFeats.authorBagOfCharTrigrams)); // m.put("%authorTG", m.get("%authorTG")/(Parser.fixupAuthors(tok).length()+2)); //use average m.put("%vfreq", PDFPredicateExtractor.smoothFreq(tok, this.lmFeats.venueBow)); m.put("%vffreq", PDFPredicateExtractor.smoothFreq(tok, this.lmFeats.venueFirstBow)); m.put("%vlfreq", PDFPredicateExtractor.smoothFreq(tok, this.lmFeats.venueLastBow)); m.put("%bfreq", PDFPredicateExtractor.smoothFreq(tok, this.lmFeats.backgroundBow)); m.put("%bafreq", PDFPredicateExtractor.smoothFreq(Parser.fixupAuthors(tok), this.lmFeats.backgroundBow)); // add word embeddings try { final Iterator<Double> vector = word2vecSearcher.getRawVector(tok).iterator(); int j = 0; while(vector.hasNext()) { final double value = vector.next(); m.put(PDFPredicateExtractor.wordEmbeddingFeatureNames[j], value); j += 1; } } catch (final Searcher.UnknownWordException e) { // do nothing } } String locBinFeat = "%locbin" + locationBin(i, elems.size()); m.put(locBinFeat, 1.0); addNumberFeatures(tok, m); if(hasEditor) m.put("%editor", 1.0); addTokenFeatures(tok, m); addPunctuationFeatures(tok, m); out.add(m); } addGazetteerPredicates(elems, out); return out; } @Override public List<ObjectDoubleMap<String>> edgePredicates(List<String> elems) { val out = new ArrayList<ObjectDoubleMap<String>>(); for (int i = 0; i < elems.size() - 1; i++) { val odhm = new ObjectDoubleHashMap<String>(); odhm.put("B", 1.0); out.add(odhm); } return out; //I don't really understand these things. } }
10,715
37.271429
124
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/RegexWithTimeout.java
package org.allenai.scienceparse; import lombok.NonNull; import java.util.regex.Matcher; import java.util.regex.Pattern; final class RegexWithTimeout { public static class RegexTimeout extends RuntimeException { } public static Matcher matcher(final Pattern pattern, final CharSequence string) { final long timeout = 1500; //ms class TimeoutCharSequence implements CharSequence { private CharSequence inner; private long abortTime; public TimeoutCharSequence(final CharSequence inner, final long abortTime) { super(); this.inner = inner; this.abortTime = abortTime; } public char charAt(int index) { if(System.currentTimeMillis() >= abortTime) throw new RegexTimeout(); return inner.charAt(index); } public int length() { return inner.length(); } public CharSequence subSequence(int start, int end) { return new TimeoutCharSequence(inner.subSequence(start, end), abortTime); } @NonNull public String toString() { return inner.toString(); } } return pattern.matcher(new TimeoutCharSequence(string, System.currentTimeMillis() + timeout)); } }
1,227
24.583333
98
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/RetryPaperSource.java
package org.allenai.scienceparse; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.io.InputStream; /** * An instance of PaperSource that wraps another, and retries a bunch of times to get the paper */ @Slf4j public class RetryPaperSource extends PaperSource { private final PaperSource inner; private final int tries; public RetryPaperSource(final PaperSource inner) { this(inner, 3); } public RetryPaperSource(final PaperSource inner, final int tries) { this.inner = inner; this.tries = tries; } private void wait(int seconds) { final long endTime = System.currentTimeMillis() + 1000 * seconds; while(System.currentTimeMillis() < endTime) { try { Thread.sleep(Math.max(endTime - System.currentTimeMillis() + 1, 1)); } catch(final InterruptedException e) { // do nothing } } } @Override public InputStream getPdf(final String paperId) throws IOException { int triesLeft = tries; int previousWait = 1; int nextWait = 1; while(true) { triesLeft -= 1; try { return inner.getPdf(paperId); } catch(final IOException e) { log.warn( "{} while downloading paper {}, {} tries left", e.getClass().getSimpleName(), paperId, triesLeft); if(triesLeft <= 0) { throw e; } else { wait(nextWait); final int waited = nextWait; nextWait += previousWait; previousWait = waited; } } } } }
1,827
27.5625
95
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/ScholarBucketPaperSource.java
package org.allenai.scienceparse; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.AmazonS3Exception; import com.amazonaws.services.s3.model.S3Object; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; /** * Gets papers from the ai2-s2-pdfs bucket */ public class ScholarBucketPaperSource extends PaperSource { // make this a singleton private static ScholarBucketPaperSource instance = new ScholarBucketPaperSource(); protected ScholarBucketPaperSource() { } public static ScholarBucketPaperSource getInstance() { return instance; } private final static String bucket = "ai2-s2-pdfs"; private final static String privateBucket = "ai2-s2-pdfs-private"; private final static String[] buckets = {bucket, privateBucket}; private final AmazonS3 s3 = new AmazonS3Client(); private S3Object getS3Object(final String paperId) { final String key = paperId.substring(0, 4) + "/" + paperId.substring(4) + ".pdf"; for(int bucketIndex = 0; bucketIndex < buckets.length; ++bucketIndex) { try { return s3.getObject(buckets[bucketIndex], key); } catch (final AmazonS3Exception e) { if(bucketIndex < buckets.length - 1 && e.getStatusCode() == 404) continue; // Try again with the next bucket. final AmazonS3Exception rethrown = new AmazonS3Exception( String.format( "Error for key s3://%s/%s", bucket, key), e); rethrown.setExtendedRequestId(e.getExtendedRequestId()); rethrown.setErrorCode(e.getErrorCode()); rethrown.setErrorType(e.getErrorType()); rethrown.setRequestId(e.getRequestId()); rethrown.setServiceName(e.getServiceName()); rethrown.setStatusCode(e.getStatusCode()); throw rethrown; } } throw new IllegalStateException("We should never get here."); } @Override public InputStream getPdf(final String paperId) throws IOException { // We download to a temp file first. If we gave out an InputStream that comes directly from // S3, it would time out if the caller of this function reads the stream too slowly. final S3Object object = getS3Object(paperId); final Path tempFile = Files.createTempFile(paperId + ".", ".paper.pdf"); try { Files.copy(object.getObjectContent(), tempFile, StandardCopyOption.REPLACE_EXISTING); return new BufferedInputStream(Files.newInputStream(tempFile)); } finally { Files.deleteIfExists(tempFile); } } }
3,070
39.946667
99
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/Section.java
package org.allenai.scienceparse; import lombok.Data; @Data public class Section { public Section(final String heading, final String text) { this.heading = heading; this.text = text; } public String heading; public String text; }
249
15.666667
59
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/StringLongHash.java
package org.allenai.scienceparse; /** * Taken from @sfussenegger * http://stackoverflow.com/questions/1660501/what-is-a-good-64bit-hash-function-in-java-for-textual-strings */ public class StringLongHash { //adapted from String.hashCode() public static long hash(String string) { long h = 1125899906842597L; // prime int len = string.length(); for (int i = 0; i < len; i++) { h = 31*h + string.charAt(i); } return h; } }
459
19.909091
108
java
science-parse
science-parse-master/core/src/main/java/org/allenai/scienceparse/WordVectorCache.java
package org.allenai.scienceparse; import org.allenai.word2vec.Searcher; import org.allenai.word2vec.Word2VecModel; import java.io.IOException; import java.nio.file.Path; import java.util.Map; import java.util.TreeMap; public class WordVectorCache { private static final Map<Path, Searcher> path2searchers = new TreeMap<Path, Searcher>(); public static Searcher searcherForPath(final Path path) throws IOException { synchronized (path2searchers) { Searcher result = path2searchers.get(path); if(result != null) return result; final Word2VecModel word2VecModel = Word2VecModel.fromBinFile(path.toFile()); result = word2VecModel.forSearch(); path2searchers.put(path, result); return result; } } }
815
29.222222
92
java