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 |
|---|---|---|---|---|---|---|
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/AtRelativeCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class AtRelativeCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
int allCount = 0;
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
char[] arr = chunk.toText().toCharArray();
for (int i = 0; i < arr.length; i++) {
allCount++;
if (arr[i]=='@') {
count++;
}
}
}
}
}
return (double) count / (double) allCount;
}
}
| 1,700 | 33.714286 | 79 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/KeywordsFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import java.util.Locale;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class KeywordsFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
String[] keywords = {"keywords", "key words", "index terms"};
for (String keyword : keywords) {
if (zone.toText().toLowerCase(Locale.ENGLISH).startsWith(keyword)) {
return 1.0;
}
}
return 0.0;
}
}
| 1,490 | 32.886364 | 80 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/IsOnSurroundingPagesFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Pawel Szostek
*/
public class IsOnSurroundingPagesFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone object, BxPage context) {
BxPage nextPage = context.getNext();
BxPage prevPage = context.getPrev();
if (nextPage != null) {
for (BxZone zone : nextPage) {
if (zone.toText().equals(object.toText())) {
return 1.0;
}
}
}
if (prevPage != null) {
for (BxZone zone : prevPage) {
if (zone.toText().equals(object.toText())) {
return 1.0;
}
}
}
return 0.0;
}
}
| 1,725 | 30.962963 | 84 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/DistanceFromNearestNeighbourFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Pawel Szostek
*/
public class DistanceFromNearestNeighbourFeature extends FeatureCalculator<BxZone, BxPage> {
private static double euclideanDist(double x0, double y0, double x1, double y1) {
return Math.sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));
}
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
double minDist = Double.MAX_VALUE;
for (BxZone otherZone : page) {
if (otherZone == zone) {
continue;
}
double dist;
double cx, cy, cw, ch, ox, oy, ow, oh;
cx = zone.getBounds().getX();
cy = zone.getBounds().getY();
cw = zone.getBounds().getWidth();
ch = zone.getBounds().getHeight();
ox = otherZone.getBounds().getX();
oy = otherZone.getBounds().getY();
ow = otherZone.getBounds().getWidth();
oh = otherZone.getBounds().getHeight();
// Determine Octant
//
// 0 | 1 | 2
// __|___|__
// 7 | 9 | 3
// __|___|__
// 6 | 5 | 4
int oct;
if (cx + cw <= ox) {
if (cy + ch <= oy) {
oct = 4;
} else if (cy >= oy + oh) {
oct = 2;
} else {
oct = 3;
}
} else if (ox + ow <= cx) {
if (cy + ch <= oy) {
oct = 6;
} else if (oy + oh <= cy) {
oct = 0;
} else {
oct = 7;
}
} else if (cy + ch <= oy) {
oct = 5;
} else if (oy + oh <= cy) {
oct = 1;
} else {
continue;
}
// determine distance based on octant
switch (oct) {
case 0:
dist = euclideanDist(ox + ow, oy + oh, cx, cy);
break;
case 1:
dist = cy - (oy + oh);
break;
case 2:
dist = euclideanDist(ox, oy + oh, cx + cw, cy);
break;
case 3:
dist = ox - (cx + cw);
break;
case 4:
dist = euclideanDist(cx + cw, cy + ch, ox, oy);
break;
case 5:
dist = oy - (cy + ch);
break;
case 6:
dist = euclideanDist(ox + ow, oy, cx, cx + ch);
break;
case 7:
dist = cx - (ox + ow);
break;
default:
dist = Double.MAX_VALUE;
}
if (dist < minDist) {
minDist = dist;
}
}
if (minDist == Double.MAX_VALUE) {
return 0.0;
} else {
return minDist;
}
}
};
| 4,094 | 30.992188 | 92 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/FeatureList.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import java.util.Arrays;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public final class FeatureList {
public static final FeatureVectorBuilder<BxZone, BxPage> VECTOR_BUILDER;
static {
VECTOR_BUILDER = new FeatureVectorBuilder<BxZone, BxPage>();
VECTOR_BUILDER.setFeatureCalculators(Arrays.<FeatureCalculator<BxZone, BxPage>>asList(
new AbstractFeature(),
new AcknowledgementFeature(),
new AffiliationFeature(),
new AreaFeature(),
new AtCountFeature(),
new AtRelativeCountFeature(),
new AuthorFeature(),
new AuthorNameRelativeFeature(),
new BibinfoFeature(),
new BracketCountFeature(),
new BracketedLineRelativeCountFeature(),
new BracketRelativeCountFeature(),
new CharCountFeature(),
new CharCountRelativeFeature(),
new CommaCountFeature(),
new CommaRelativeCountFeature(),
new ContainsCuePhrasesFeature(),
new ContainsPageNumberFeature(),
new ContributionFeature(),
new CorrespondenceFeature(),
new CuePhrasesRelativeCountFeature(),
new DateFeature(),
new DigitCountFeature(),
new DigitRelativeCountFeature(),
new DistanceFromNearestNeighbourFeature(),
new DotCountFeature(),
new DotRelativeCountFeature(),
new EditorFeature(),
new EmailFeature(),
new EmptySpaceFeature(),
new EmptySpaceRelativeFeature(),
new FigureFeature(),
new FigureTableFeature(),
new FontHeightMeanFeature(),
new FreeSpaceWithinZoneFeature(),
new FullWordsRelativeFeature(),
new GreekLettersFeature(),
new HeightFeature(),
new HeightRelativeFeature(),
new HorizontalRelativeProminenceFeature(),
new IsAfterMetTitleFeature(),
new IsAnywhereElseFeature(),
new IsFirstPageFeature(),
new IsFontBiggerThanNeighboursFeature(),
new IsGreatestFontOnPageFeature(),
new IsHighestOnThePageFeature(),
new IsItemizeFeature(),
new IsLastButOnePageFeature(),
new IsLastPageFeature(),
new IsLeftFeature(),
new IsLongestOnThePageFeature(),
new IsLowestOnThePageFeature(),
new IsOnSurroundingPagesFeature(),
new IsPageNumberFeature(),
new IsRightFeature(),
new IsSingleWordFeature(),
new IsWidestOnThePageFeature(),
new KeywordsFeature(),
new LastButOneZoneFeature(),
new LetterCountFeature(),
new LetterRelativeCountFeature(),
new LicenseFeature(),
new LineCountFeature(),
new LineHeightMaxMeanFeature(),
new LineHeightMeanFeature(),
new LineRelativeCountFeature(),
new LineWidthMeanFeature(),
new LineXPositionDiffFeature(),
new LineXPositionMeanFeature(),
new LineXWidthPositionDiffFeature(),
new LowercaseCountFeature(),
new LowercaseRelativeCountFeature(),
new MathSymbolsFeature(),
new PageNumberFeature(),
new PreviousZoneFeature(),
new ProportionsFeature(),
new PunctuationRelativeCountFeature(),
new ReferencesFeature(),
new ReferencesTitleFeature(),
new RelativeMeanLengthFeature(),
new StartsWithDigitFeature(),
new StartsWithHeaderFeature(),
new TypeFeature(),
new UppercaseCountFeature(),
new UppercaseRelativeCountFeature(),
new UppercaseWordCountFeature(),
new UppercaseWordRelativeCountFeature(),
new VerticalProminenceFeature(),
new WhitespaceCountFeature(),
new WhitespaceRelativeCountLogFeature(),
new WidthFeature(),
new WidthRelativeFeature(),
new WordCountFeature(),
new WordCountRelativeFeature(),
new WordLengthMeanFeature(),
new WordLengthMedianFeature(),
new WordWidthMeanFeature(),
new XPositionFeature(),
new XPositionRelativeFeature(),
new XVarianceFeature(),
new YearFeature(),
new YPositionFeature(),
new YPositionRelativeFeature()
));
}
private FeatureList() {}
}
| 5,707 | 38.09589 | 94 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/EmailFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import java.util.Locale;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
/**
* @author Pawel Szostek
*/
public class EmailFeature extends AbstractFeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone object, BxPage context) {
String text = object.toText();
text = text.toLowerCase(Locale.ENGLISH);
return text.matches(".*[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4}).*")
? 1.0 : 0.0;
}
}
| 1,359 | 34.789474 | 105 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/AreaFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class AreaFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
double charsArea = 0;
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
charsArea += chunk.getArea();
}
}
}
return (zone.getArea() == 0) ? 0 : charsArea / zone.getArea();
}
}
| 1,470 | 32.431818 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/StartsWithHeaderFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import pl.edu.icm.cermine.metadata.zoneclassification.tools.ZoneClassificationUtils;
import pl.edu.icm.cermine.structure.model.BxLine;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Pawel Szostek
*/
public class StartsWithHeaderFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone object, BxPage context) {
BxLine firstLine = object.getFirstChild();
String lineText = firstLine.toText();
String text = object.toText();
String itemizeString = "";
itemizeString += "|^\\d+\\.\\d+\\.\\s+\\p{Upper}.+";
itemizeString += "|^\\d+\\.\\s+\\p{Upper}.+";
itemizeString += "|^\\p{Upper}\\.\\s[^\\.]+";
itemizeString += "|^\\p{Lower}\\)\\s+.+";
Pattern itemizePattern = Pattern.compile(itemizeString);
String subpointsString = "";
subpointsString += "^\\d\\.\\d\\.\\s+\\p{Upper}.+";
subpointsString += "|^\\d\\.\\d\\.\\d\\.\\s+\\p{Upper}.+";
Pattern subpointsPattern = Pattern.compile(subpointsString, Pattern.DOTALL); //for multiline matching
Matcher matcher1 = itemizePattern.matcher(text);
Matcher matcher2 = subpointsPattern.matcher(text);
if (matcher1.matches() || matcher2.matches()) {
return 1.0;
}
if (object.childrenCount() <= 2) {
return 0;
}
if (!lineText.contains(" ") && !lineText.matches(".*\\d.*") && lineText.matches("\\p{Upper}.+")) {
return 1;
}
String[] words = lineText.split(" ");
boolean capitals = true;
for (String word : words) {
if (!(word.matches("\\{Upper}.+") || ZoneClassificationUtils.isConjunction(word))) {
capitals = false;
break;
}
}
return capitals ? 1.0 : 0;
}
}
| 2,869 | 36.763158 | 109 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/WordCountRelativeFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxLine;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class WordCountRelativeFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
for (BxLine line : zone) {
count += line.childrenCount();
}
int pCount = 0;
for (BxZone pZone: page) {
for (BxLine line : pZone) {
pCount += line.childrenCount();
}
}
return (double) count / (double) pCount;
}
}
| 1,594 | 31.55102 | 81 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/ContributionFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import java.util.Locale;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
/**
* @author Pawel Szostek
*/
public class ContributionFeature extends AbstractFeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
String[] keywords = {"contribution",
};
for (String keyword : keywords) {
if (zone.toText().toLowerCase(Locale.ENGLISH).contains(keyword)) {
return 1;
}
}
return 0;
}
}
| 1,405 | 31.697674 | 84 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/TypeFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class TypeFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
String[] keywords = {"research article", "review article", "editorial", "review", "debate", "case report",
"research", "original research", "methodology", "clinical study", "commentary", "article",
"hypothesis"};
int count = 0;
for (String keyword : keywords) {
if (zone.toText().equalsIgnoreCase(keyword)) {
count++;
}
}
return count;
}
}
| 1,674 | 34.638298 | 119 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/IsFirstPageFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Pawel Szostek
*/
public class IsFirstPageFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
return page.getId().equals("0") ? 1.0 : 0.0;
}
}
| 1,230 | 35.205882 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/XVarianceFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxLine;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class XVarianceFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
double meanX = 0;
for (BxLine line : zone) {
meanX += line.getX();
}
if (meanX == 0 || !zone.hasChildren()) {
return 0;
}
meanX /= zone.childrenCount();
double meanXDiff = 0;
for (BxLine line : zone) {
meanXDiff += Math.abs(line.getX() - meanX);
}
return meanXDiff / zone.childrenCount() / meanX;
}
}
| 1,729 | 31.037037 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/IsHighestOnThePageFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import com.google.common.collect.Lists;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.Utils;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Pawel Szostek
*/
public class IsHighestOnThePageFeature extends FeatureCalculator<BxZone, BxPage> {
private static final double EPS = 10.0;
private static class YCoordinateComparator implements Comparator<BxZone> {
@Override
public int compare(BxZone z1, BxZone z2) {
return Utils.compareDouble(z1.getY() + z1.getHeight(), z2.getY() + z2.getHeight(), 0.1);
}
}
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
List<BxZone> zones = Lists.newArrayList(page);
Collections.sort(zones, new YCoordinateComparator());
BxZone firstZone = zones.get(0);
if (zone.equals(firstZone)) {
return 1.0;
} else if (Math.abs(zone.getY() - firstZone.getY()) <= EPS) {
return 1.0;
} else {
return 0.0;
}
}
}
| 2,022 | 33.87931 | 100 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/LineHeightMaxMeanFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxLine;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class LineHeightMaxMeanFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
double zoneMean = 0;
for (BxLine line : zone) {
zoneMean += line.getBounds().getHeight();
}
zoneMean /= (double) zone.childrenCount();
for (BxZone z : page) {
if (z.equals(zone)) {
continue;
}
double pageMean = 0;
for (BxLine line : z) {
pageMean += line.getBounds().getHeight();
}
pageMean /= z.childrenCount();
if (pageMean > zoneMean + 1) {
return 0;
}
}
return 1;
}
}
| 1,841 | 32.490909 | 81 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/LowercaseCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class LowercaseCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
char[] arr = chunk.toText().toCharArray();
for (int i = 0; i < arr.length; i++) {
if (Character.isLowerCase(arr[i])) {
count++;
}
}
}
}
}
return (double) count;
}
}
| 1,638 | 33.87234 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/EditorFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import java.util.Locale;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class EditorFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
String[] keywords = {"academic", "editor"};
int count = 0;
for (String keyword : keywords) {
if (zone.toText().toLowerCase(Locale.ENGLISH).contains(keyword)) {
count++;
}
}
return count;
}
}
| 1,494 | 31.5 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/MathSymbolsFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class MathSymbolsFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
return (zone.toText().matches("^.*[=\\u2200-\\u22FF].*$")) ? 1 : 0;
}
}
| 1,285 | 34.722222 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/YearFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import pl.edu.icm.cermine.structure.model.BxLine;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.TextUtils;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class YearFeature extends FeatureCalculator<BxZone, BxPage> {
private static final int MIN_YEAR = 1800;
private static final int MAX_YEAR = 2100;
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int yearCount = 0;
for (BxLine line : zone) {
String toMatch = line.toText();
Pattern pattern = Pattern.compile("^\\D*(\\d+)(.*)$");
while (Pattern.matches("^.*\\d.*", toMatch)) {
Matcher matcher = pattern.matcher(toMatch);
if (!matcher.matches()) {
break;
}
String numbers = matcher.group(1);
if (TextUtils.isNumberBetween(numbers, MIN_YEAR, MAX_YEAR)) {
yearCount++;
}
toMatch = matcher.group(2);
}
}
return (double)yearCount / (double)zone.childrenCount();
}
}
| 2,159 | 34.409836 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/RelativeMeanLengthFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxLine;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class RelativeMeanLengthFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
BxLine firstLine = zone.getFirstChild();
BxLine line = firstLine;
double meanTotalWidth = line.getWidth();
int lineCount = 1;
while (line.hasPrev()) {
line = line.getPrev();
meanTotalWidth += line.getWidth();
lineCount++;
}
line = firstLine;
while (line.hasNext()) {
line = line.getNext();
meanTotalWidth += line.getWidth();
lineCount++;
}
if (lineCount == 0) {
return 0;
}
meanTotalWidth /= lineCount;
double meanZoneWidth = 0;
for (BxLine l : zone) {
meanZoneWidth += l.getWidth();
}
if (!zone.hasChildren() || meanTotalWidth == 0) {
return 0;
}
return meanZoneWidth / zone.childrenCount() / meanTotalWidth;
}
}
| 2,182 | 30.637681 | 82 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/YPositionRelativeFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class YPositionRelativeFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
if (page.getBounds().getHeight() < 0.00001) {
return 0.0;
}
return zone.getBounds().getY() / page.getBounds().getHeight();
}
}
| 1,358 | 33.846154 | 81 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/ProportionsFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxBounds;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class ProportionsFeature extends FeatureCalculator<BxZone, BxPage> {
private static final double MIN_WIDTH = 0.00005;
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
BxBounds bounds = zone.getBounds();
if (bounds.getWidth() < MIN_WIDTH) {
return 0.0;
} else {
return bounds.getHeight() / bounds.getWidth();
}
}
}
| 1,508 | 33.295455 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/DigitCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class DigitCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
char[] arr = chunk.toText().toCharArray();
for (int i = 0; i < arr.length; i++) {
if (Character.isDigit(arr[i])) {
count++;
}
}
}
}
}
return (double) count;
}
}
| 1,627 | 33.638298 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/HeightFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class HeightFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
return zone.getBounds().getHeight();
}
}
| 1,245 | 33.611111 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/DotRelativeCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class DotRelativeCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
int allCount = 0;
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
char[] arr = chunk.toText().toCharArray();
for (int i = 0; i < arr.length; i++) {
allCount++;
if (arr[i]=='.') {
count++;
}
}
}
}
}
return (double) count / (double) allCount;
}
}
| 1,701 | 33.734694 | 80 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/ReferencesTitleFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import java.util.Locale;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class ReferencesTitleFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
String[] keywords = {"referen", "biblio"};
for (String keyword : keywords) {
if (zone.toText().toLowerCase(Locale.ENGLISH).startsWith(keyword)) {
return 1;
}
}
return 0;
}
}
| 1,477 | 32.590909 | 80 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/AuthorFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import com.google.common.collect.Lists;
import java.util.Locale;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class AuthorFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
String[] keywords = {"author"};
int count = 0;
for (String keyword : keywords) {
if (zone.toText().toLowerCase(Locale.ENGLISH).startsWith(keyword)) {
count++;
}
}
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
BxBounds chb = chunk.getBounds();
BxBounds lb = line.getBounds();
String cht = chunk.toText();
if ((cht.matches("\\d") || cht.equals("*"))
&& Lists.newArrayList(word).indexOf(chunk) > word.childrenCount() - 3
&& chb.getHeight() < 3 * lb.getHeight() / 4
&& chb.getY() + chb.getHeight() < lb.getY() + lb.getHeight()) {
count++;
}
}
}
}
return count;
}
}
| 2,168 | 33.983871 | 97 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/HorizontalRelativeProminenceFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Pawel Szostek
*/
public class HorizontalRelativeProminenceFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
double leftProminence = zone.getX();
double rightProminence = page.getWidth() - (zone.getX() + zone.getWidth());
for (BxZone otherZone : page) {
if (otherZone == zone) {
continue;
}
double cx, cy, cw, ch, ox, oy, ow, oh;
double newLeftProminence, newRightProminence;
cx = zone.getBounds().getX();
cy = zone.getBounds().getY();
cw = zone.getBounds().getWidth();
ch = zone.getBounds().getHeight();
ox = otherZone.getBounds().getX();
oy = otherZone.getBounds().getY();
ow = otherZone.getBounds().getWidth();
oh = otherZone.getBounds().getHeight();
// Determine Octant
//
// 0 | 1 | 2
// __|___|__
// 7 | 9 | 3
// __|___|__
// 6 | 5 | 4
int oct;
if (cx + cw <= ox) {
if (cy + ch <= oy) {
oct = 4;
} else if (cy >= oy + oh) {
oct = 2;
} else {
oct = 3;
}
} else if (ox + ow <= cx) {
if (cy + ch <= oy) {
oct = 6;
} else if (oy + oh <= cy) {
oct = 0;
} else {
oct = 7;
}
} else if (cy + ch <= oy) {
oct = 5;
} else { // oy + oh <= cy
oct = 1;
}
if (oct != 7 && oct != 3) {
continue;
}
if (oct == 7) {
newLeftProminence = Math.min(leftProminence, cx - (ox + ow));
if (Math.abs(newLeftProminence - leftProminence) > Double.MIN_VALUE) {
leftProminence = newLeftProminence;
}
} else { //oct == 3
newRightProminence = Math.min(rightProminence, ox - (cx + cw));
if (Math.abs(newRightProminence - rightProminence) > Double.MIN_VALUE) {
rightProminence = newRightProminence;
}
}
}
double ret = (rightProminence + leftProminence + zone.getWidth()) / page.getWidth();
if (ret >= 0.0) {
return ret;
} else {
return 0.0;
}
}
};
| 3,603 | 33 | 92 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/AtCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class AtCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
char[] arr = chunk.toText().toCharArray();
for (int i = 0; i < arr.length; i++) {
if (arr[i]=='@') {
count++;
}
}
}
}
}
return (double) count;
}
}
| 1,611 | 32.583333 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/WordWidthMeanFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxLine;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxWord;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class WordWidthMeanFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
double mean = 0;
for (BxLine line : zone) {
for (BxWord word : line) {
count++;
mean += word.getBounds().getWidth();
}
}
return mean / (int) count;
}
}
| 1,567 | 32.361702 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/XPositionRelativeFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class XPositionRelativeFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
if (page.getBounds().getWidth() < 0.00001) {
return 0.0;
}
return zone.getBounds().getX() / page.getBounds().getWidth();
}
}
| 1,357 | 33.820513 | 81 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/UppercaseCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class UppercaseCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
char[] arr = chunk.toText().toCharArray();
for (int i = 0; i < arr.length; i++) {
if (Character.isUpperCase(arr[i])) {
count++;
}
}
}
}
}
return (double) count;
}
}
| 1,637 | 33.851064 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/LineHeightMeanFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxLine;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class LineHeightMeanFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
double mean = 0;
for (BxLine line : zone) {
mean += line.getHeight();
}
return mean / (double) zone.childrenCount();
}
}
| 1,419 | 33.634146 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/UppercaseRelativeCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class UppercaseRelativeCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
int allCount = 0;
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
char[] arr = chunk.toText().toCharArray();
for (int i = 0; i < arr.length; i++) {
allCount++;
if (Character.isUpperCase(arr[i])) {
count++;
}
}
}
}
}
return (double) count / (double) allCount;
}
}
| 1,725 | 34.22449 | 86 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/WordLengthMeanFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Pawel Szostek
*/
public class WordLengthMeanFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone object, BxPage context) {
int wordsLengthsSum = 0;
int numberOfWords = 0;
for (BxLine line : object) {
for (BxWord word : line) {
int curLength = 0;
for (BxChunk chunk : word) {
curLength += chunk.toText().length();
}
wordsLengthsSum += curLength;
++numberOfWords;
}
}
return (double) wordsLengthsSum / (double) numberOfWords;
}
}
| 1,596 | 33.717391 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/LineWidthMeanFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxLine;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class LineWidthMeanFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
double mean = 0;
for (BxLine line : zone) {
mean += line.getBounds().getWidth();
}
return mean / (double) zone.childrenCount();
}
}
| 1,429 | 33.878049 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/CorrespondenceFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import java.util.Locale;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class CorrespondenceFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
String[] keywords = {"addressed", "correspondence", "email", "address"};
int count = 0;
for (String keyword : keywords) {
if (zone.toText().toLowerCase(Locale.ENGLISH).contains(keyword)) {
count++;
}
}
return count;
}
}
| 1,531 | 32.304348 | 80 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/FigureFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import java.util.Locale;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Pawel Szostek
*/
public class FigureFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
String[] keywords = {"figure", "fig.", "table", "tab."};
for (String keyword : keywords) {
if (zone.toText().toLowerCase(Locale.ENGLISH).startsWith(keyword)) {
return 1;
}
}
return 0;
}
}
| 1,455 | 32.860465 | 80 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/IsLongestOnThePageFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Pawel Szostek
*/
public class IsLongestOnThePageFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone object, BxPage context) {
for (BxZone zone : context) {
if (zone.toText().length() > object.toText().length()) {
return 0.0;
}
}
return 1.0;
}
}
| 1,369 | 33.25 | 82 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/LineRelativeCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class LineRelativeCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int allLines = 0;
for (BxZone pZone : page) {
allLines += pZone.childrenCount();
}
return (double) zone.childrenCount() / (double) allLines;
}
}
| 1,405 | 33.292683 | 81 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/HeightRelativeFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class HeightRelativeFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
if (page.getBounds().getHeight() < 0.00001) {
return 0.0;
}
return zone.getBounds().getHeight() / page.getBounds().getHeight();
}
}
| 1,360 | 33.897436 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/LineCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class LineCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
return (double) zone.childrenCount();
}
}
| 1,249 | 33.722222 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/LicenseFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import java.util.Locale;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class LicenseFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
String[] keywords = {"terms", "distributed", "reproduction", "open", "commons",
"license", "©", "creative", "copyright", "cited", "distribution", "access"};
int count = 0;
for (String keyword : keywords) {
if (zone.toText().toLowerCase(Locale.ENGLISH).contains(keyword)) {
count++;
}
}
return count;
}
}
| 1,620 | 33.489362 | 88 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/LetterRelativeCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class LetterRelativeCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
int allCount = 0;
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
char[] arr = chunk.toText().toCharArray();
for (int i = 0; i < arr.length; i++) {
allCount++;
if (Character.isLetter(arr[i])) {
count++;
}
}
}
}
}
return (double) count / (double) allCount;
}
}
| 1,719 | 34.102041 | 83 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/WhitespaceRelativeCountLogFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Pawel Szostek
*/
public class WhitespaceRelativeCountLogFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
double spaceCount = new WhitespaceCountFeature().calculateFeatureValue(zone, page);
return -Math.log(spaceCount / (zone.toText().length()) + Double.MIN_VALUE);
}
}
| 1,366 | 36.972222 | 90 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/UppercaseWordCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class UppercaseWordCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
for (BxLine line : zone) {
for (BxWord word : line) {
StringBuilder sb = new StringBuilder();
for (BxChunk chunk : word) {
sb.append(chunk.toText());
}
String s = sb.toString();
if (!s.isEmpty() && Character.isUpperCase(s.charAt(0))) {
count++;
}
}
}
return (double) count;
}
}
| 1,638 | 33.145833 | 82 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/WordCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.BxLine;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class WordCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
for (BxLine line : zone) {
count += line.childrenCount();
}
return (double) count;
}
}
| 1,396 | 32.261905 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/PunctuationRelativeCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import org.apache.commons.lang.ArrayUtils;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class PunctuationRelativeCountFeature extends FeatureCalculator<BxZone, BxPage> {
private static final char[] PUNCT_CHARS = {'.', ',', '[', ']', ':', '-'};
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int punctuationCount = 0;
for (char character : zone.toText().toCharArray()) {
if (ArrayUtils.contains(PUNCT_CHARS, character)) {
punctuationCount++;
}
}
return (double)punctuationCount / (double)zone.toText().length();
}
}
| 1,636 | 35.377778 | 88 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/CommaRelativeCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class CommaRelativeCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
int allCount = 0;
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
char[] arr = chunk.toText().toCharArray();
for (int i = 0; i < arr.length; i++) {
allCount++;
if (arr[i]==',') {
count++;
}
}
}
}
}
return (double) count / (double) allCount;
}
}
| 1,703 | 33.77551 | 82 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/zoneclassification/features/LowercaseRelativeCountFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.zoneclassification.features;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class LowercaseRelativeCountFeature extends FeatureCalculator<BxZone, BxPage> {
@Override
public double calculateFeatureValue(BxZone zone, BxPage page) {
int count = 0;
int allCount = 0;
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
char[] arr = chunk.toText().toCharArray();
for (int i = 0; i < arr.length; i++) {
allCount++;
if (Character.isLowerCase(arr[i])) {
count++;
}
}
}
}
}
return (double) count / (double) allCount;
}
}
| 1,725 | 34.22449 | 86 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/affiliation/CRFAffiliationParser.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.affiliation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.cli.*;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import pl.edu.icm.cermine.exception.AnalysisException;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.metadata.affiliation.tools.AffiliationCRFTokenClassifier;
import pl.edu.icm.cermine.metadata.affiliation.tools.AffiliationFeatureExtractor;
import pl.edu.icm.cermine.metadata.affiliation.tools.AffiliationTokenizer;
import pl.edu.icm.cermine.metadata.model.AffiliationLabel;
import pl.edu.icm.cermine.metadata.model.DocumentAffiliation;
import pl.edu.icm.cermine.metadata.transformers.MetadataToNLMConverter;
import pl.edu.icm.cermine.parsing.model.Token;
import pl.edu.icm.cermine.parsing.tools.ParsableStringParser;
import pl.edu.icm.cermine.tools.ResourcesReader;
/**
* CRF-based Affiliation parser. Processes an instance of DocumentAffiliation by
* generating and tagging its tokens.
*
* @author Bartosz Tarnawski
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class CRFAffiliationParser implements ParsableStringParser<DocumentAffiliation> {
private static final int MAX_LENGTH = 3000;
private AffiliationTokenizer tokenizer = null;
private AffiliationFeatureExtractor featureExtractor = null;
private AffiliationCRFTokenClassifier classifier = null;
private static final String DEFAULT_MODEL_FILE
= "/pl/edu/icm/cermine/metadata/affiliation/acrf-affiliations-pubmed.ser.gz";
private static final String DEFAULT_COMMON_WORDS_FILE
= "/pl/edu/icm/cermine/metadata/affiliation/common-words-affiliations-pubmed.txt";
private static final String STATES_FILE
= "/pl/edu/icm/cermine/metadata/affiliation/features/states.txt";
private static final String STATE_CODES_FILE
= "/pl/edu/icm/cermine/metadata/affiliation/features/state_codes.txt";
private List<String> loadWords(String wordsFileName) throws AnalysisException {
BufferedReader in = null;
try {
List<String> commonWords = new ArrayList<String>();
InputStream is = CRFAffiliationParser.class.getResourceAsStream(wordsFileName);
if (is == null) {
throw new AnalysisException("Resource not found: " + wordsFileName);
}
in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
commonWords.add(line);
}
return commonWords;
} catch (IOException readException) {
throw new AnalysisException("An exception occured when the common word list "
+ wordsFileName + " was being read: " + readException);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
Logger.getLogger(CRFAffiliationParser.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* @param wordsFileName the name of the package resource to be used as the
* common words list
* @param acrfFileName the name of the package resource to be used as the
* ACRF model
* @throws AnalysisException AnalysisException
*/
public CRFAffiliationParser(String wordsFileName, String acrfFileName) throws AnalysisException {
List<String> commonWords = loadWords(wordsFileName);
tokenizer = new AffiliationTokenizer();
featureExtractor = new AffiliationFeatureExtractor(commonWords);
classifier = new AffiliationCRFTokenClassifier(
CRFAffiliationParser.class.getResourceAsStream(acrfFileName));
}
public CRFAffiliationParser() throws AnalysisException {
this(DEFAULT_COMMON_WORDS_FILE, DEFAULT_MODEL_FILE);
}
/**
* Sets the token list of the affiliation so that their labels determine the
* tagging of its text content.
*
* @param affiliation affiliation
* @throws AnalysisException AnalysisException
*/
@Override
public void parse(DocumentAffiliation affiliation) throws AnalysisException {
affiliation.setTokens(tokenizer.tokenize(affiliation.getRawText()));
for (Token<AffiliationLabel> t : affiliation.getTokens()) {
t.setLabel(AffiliationLabel.TEXT);
}
if (affiliation.getRawText().length() > MAX_LENGTH) {
affiliation.mergeTokens();
return;
}
featureExtractor.calculateFeatures(affiliation);
classifier.classify(affiliation.getTokens());
affiliation.mergeTokens();
if (affiliation.getCountry() == null) {
try {
List<String> states = ResourcesReader.readLinesAsList(STATES_FILE, ResourcesReader.TRIM_TRANSFORMER);
List<String> stateCodes = ResourcesReader.readLinesAsList(STATE_CODES_FILE, ResourcesReader.TRIM_TRANSFORMER);
boolean isUSA = false;
for (String state: states) {
Pattern p = Pattern.compile("(?<![0-9a-zA-Z])"+state+"(?![0-9a-zA-Z])");
Matcher m = p.matcher(affiliation.getRawText());
if (m.find()) {
isUSA = true;
}
}
for (String stateCode: stateCodes) {
int last = Math.max(0, affiliation.getRawText().length()-20);
Pattern p = Pattern.compile("(?<![0-9a-zA-Z])"+stateCode+"(?![0-9a-zA-Z])");
Matcher m = p.matcher(affiliation.getRawText().substring(last));
if (m.find()) {
isUSA = true;
}
}
if (isUSA) {
int last = affiliation.getRawText().length();
affiliation.setRawText(affiliation.getRawText()+", USA");
affiliation.addToken(new Token<AffiliationLabel>(",", last, last+1, AffiliationLabel.TEXT));
affiliation.addToken(new Token<AffiliationLabel>("USA", last+3, last+6, AffiliationLabel.COUN));
}
} catch (TransformationException ex) {
}
}
}
/**
* @param affiliationString string representation of the affiliation to
* parse
* @return XML Element with the tagged affiliation in NLM format
* @throws AnalysisException AnalysisException
* @throws TransformationException TransformationException
*/
@Override
public Element parse(String affiliationString) throws AnalysisException,
TransformationException {
DocumentAffiliation aff = new DocumentAffiliation(affiliationString);
parse(aff);
MetadataToNLMConverter converter = new MetadataToNLMConverter();
return converter.convertAffiliation(aff);
}
public static void main(String[] args) throws ParseException, AnalysisException, TransformationException {
Options options = new Options();
options.addOption("affiliation", true, "reference text");
CommandLineParser clParser = new DefaultParser();
CommandLine line = clParser.parse(options, args);
String affiliationText = line.getOptionValue("affiliation");
if (affiliationText == null) {
System.err.println("Usage: CRFAffiliationParser -affiliation <affiliation text>\n\n"
+ "Tool for extracting metadata from affiliation strings.\n\n"
+ "Arguments:\n"
+ " -affiliation the text of the affiliation\n");
System.exit(1);
}
CRFAffiliationParser parser = new CRFAffiliationParser();
Element affiliation = parser.parse(affiliationText);
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
System.out.println(outputter.outputString(affiliation));
}
}
| 9,134 | 42.5 | 126 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/affiliation/tools/AffiliationCRFTokenClassifier.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.affiliation.tools;
import edu.umass.cs.mallet.base.pipe.Pipe;
import edu.umass.cs.mallet.base.pipe.iterator.LineGroupIterator;
import edu.umass.cs.mallet.base.types.InstanceList;
import edu.umass.cs.mallet.base.types.LabelsSequence;
import edu.umass.cs.mallet.grmm.learning.ACRF;
import java.io.*;
import java.util.List;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import pl.edu.icm.cermine.exception.AnalysisException;
import pl.edu.icm.cermine.metadata.model.AffiliationLabel;
import pl.edu.icm.cermine.parsing.model.Token;
import pl.edu.icm.cermine.parsing.tools.GrmmUtils;
import pl.edu.icm.cermine.parsing.tools.TokenClassifier;
/**
* Token classifier suitable for processing affiliations.
*
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
* @author Bartosz Tarnawski
*/
public class AffiliationCRFTokenClassifier implements TokenClassifier<Token<AffiliationLabel>> {
private ACRF model;
private static final int DEFAULT_NEIGHBOR_INFLUENCE = 1;
private static final String DEFAULT_MODEL_FILE
= "/pl/edu/icm/cermine/metadata/affiliation/acrf-affiliations-pubmed.ser.gz";
/**
* @param modelInputStream the stream representing the ACRF model to be used
* @throws AnalysisException if the model cannot be loaded
*/
public AffiliationCRFTokenClassifier(InputStream modelInputStream) throws AnalysisException {
// prevents MALLET from printing info messages
System.setProperty("java.util.logging.config.file",
"edu/umass/cs/mallet/base/util/resources/logging.properties");
if (modelInputStream == null) {
throw new AnalysisException("Cannot set model, input stream is null!");
}
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new BufferedInputStream(new GZIPInputStream(
modelInputStream)));
model = (ACRF) (ois.readObject());
} catch (IOException ex) {
throw new AnalysisException("Cannot set model!", ex);
} catch (ClassNotFoundException ex) {
throw new AnalysisException("Cannot set model!", ex);
} finally {
try {
if (ois != null) {
ois.close();
}
} catch (IOException ex) {
throw new AnalysisException("Cannot set model!", ex);
}
}
}
/**
* Uses the default ACRF model.
*
* @throws AnalysisException AnalysisException
*/
public AffiliationCRFTokenClassifier() throws AnalysisException {
this(AffiliationCRFTokenClassifier.class.getResourceAsStream(DEFAULT_MODEL_FILE));
}
private LineGroupIterator getLineIterator(String data) {
return new LineGroupIterator(new StringReader(data), Pattern.compile("\\s*"), true);
}
/**
* When comma is the last token in a tagged part, its label is changed to
* 'TEXT'.
*
* @param tokens
*/
private void enhanceLabels(List<Token<AffiliationLabel>> tokens) {
Token<AffiliationLabel> lastToken = null;
for (Token<AffiliationLabel> token : tokens) {
if (lastToken != null && lastToken.getLabel() != token.getLabel()
&& lastToken.getText().equals(",")) {
lastToken.setLabel(AffiliationLabel.TEXT);
}
lastToken = token;
}
}
@Override
public void classify(List<Token<AffiliationLabel>> tokens) throws AnalysisException {
if (tokens == null || tokens.isEmpty()) {
return;
}
for (Token<AffiliationLabel> token : tokens) {
if (token.getLabel() == null) {
token.setLabel(AffiliationLabel.TEXT);
}
}
String data = GrmmUtils.toGrmmInput(tokens, DEFAULT_NEIGHBOR_INFLUENCE);
Pipe pipe = model.getInputPipe();
InstanceList instanceList = new InstanceList(pipe);
instanceList.add(getLineIterator(data));
LabelsSequence labelsSequence = null;
try {
labelsSequence = (LabelsSequence) model.getBestLabels(instanceList).get(0);
} catch (ArrayIndexOutOfBoundsException ex) {
throw new AnalysisException("ACRF model can't recognize some of the labels.");
}
for (int i = 0; i < labelsSequence.size(); i++) {
tokens.get(i).setLabel(AffiliationLabel.valueOf(labelsSequence.get(i).toString()));
}
enhanceLabels(tokens);
}
}
| 5,318 | 36.992857 | 97 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/affiliation/tools/CountryISOCodeFinder.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.affiliation.tools;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import pl.edu.icm.cermine.exception.TransformationException;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class CountryISOCodeFinder {
private static final String CODES_FILE
= "/pl/edu/icm/cermine/metadata/affiliation/country-codes.txt";
private final Map<String, String> countryCodes = new HashMap<String, String>();
private void loadCountryCodes() throws TransformationException {
InputStream is = CountryISOCodeFinder.class.getResourceAsStream(CODES_FILE);
if (is == null) {
throw new TransformationException("Resource not found: " + CODES_FILE);
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
String countryName = line.substring(0, line.length() - 3);
String countryCode = line.substring(line.length() - 2);
countryCodes.put(countryName, countryCode.toUpperCase(Locale.ENGLISH));
countryCodes.put(countryName.replaceAll("[^a-zA-Z]", ""), countryCode.toUpperCase(Locale.ENGLISH));
}
} catch (IOException ex) {
throw new TransformationException(ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
throw new TransformationException(ex);
}
}
}
public CountryISOCodeFinder() throws TransformationException {
loadCountryCodes();
}
public String getCountryISOCode(String country) {
if (countryCodes.get(country) != null) {
return countryCodes.get(country.toLowerCase(Locale.ENGLISH));
} else {
return countryCodes.get(country.toLowerCase(Locale.ENGLISH).replaceAll("[^a-zA-Z]", ""));
}
}
public Set<String> getCountries() {
return countryCodes.keySet();
}
}
| 3,044 | 34.823529 | 115 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/affiliation/tools/NLMAffiliationExtractor.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.affiliation.tools;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import pl.edu.icm.cermine.metadata.model.AffiliationLabel;
import pl.edu.icm.cermine.metadata.model.DocumentAffiliation;
import pl.edu.icm.cermine.parsing.model.Token;
import pl.edu.icm.cermine.parsing.tools.NLMParsableStringExtractor;
/**
* NLM string extractor suitable for extracting document affiliations.
*
* @author Bartosz Tarnawski
*/
public class NLMAffiliationExtractor extends
NLMParsableStringExtractor<AffiliationLabel, Token<AffiliationLabel>, DocumentAffiliation> {
private static final AffiliationTokenizer TOKENIZER = new AffiliationTokenizer();
@Override
protected List<String> getTags() {
return TAGS_AFFILIATION;
}
@Override
protected String getKeyText() {
return KEY_TEXT;
}
@Override
protected Map<String, AffiliationLabel> getTagLabelMap() {
return TAGS_LABEL_MAP;
}
@Override
protected DocumentAffiliation createParsableString() {
return new DocumentAffiliation("");
}
@Override
protected DocumentAffiliation createParsableString(String text) {
DocumentAffiliation instance = new DocumentAffiliation(text);
instance.setTokens(TOKENIZER.tokenize(instance.getRawText()));
return instance;
}
private static final List<String> TAGS_AFFILIATION = Arrays.asList("aff");
private static final String KEY_TEXT = "text";
private static final Map<String, AffiliationLabel> TAGS_LABEL_MAP =
new HashMap<String, AffiliationLabel>();
static {
TAGS_LABEL_MAP.put("addr-line", AffiliationLabel.ADDR);
TAGS_LABEL_MAP.put("institution", AffiliationLabel.INST);
TAGS_LABEL_MAP.put("country", AffiliationLabel.COUN);
TAGS_LABEL_MAP.put("author", AffiliationLabel.AUTH);
TAGS_LABEL_MAP.put("text", AffiliationLabel.TEXT);
}
}
| 2,675 | 31.634146 | 100 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/affiliation/tools/AffiliationTokenizer.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.affiliation.tools;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import pl.edu.icm.cermine.metadata.model.AffiliationLabel;
import pl.edu.icm.cermine.parsing.model.Token;
import pl.edu.icm.cermine.parsing.tools.TextTokenizer;
/**
* Text tokenizer suitable for tokenizing affiliation strings.
*
* @author Bartosz Tarnawski
*/
public class AffiliationTokenizer implements TextTokenizer<Token<AffiliationLabel>> {
private static List<Token<AffiliationLabel>> asciiTextToTokens(String text,
List<Integer> asciiIndices) {
final String DELIMITER_REGEX = "\\d+|\\W|_";
List<Token<AffiliationLabel>> tokens = new ArrayList<Token<AffiliationLabel>>();
Matcher delimeterMatcher = Pattern.compile(DELIMITER_REGEX).matcher(text);
int lastEnd = 0;
while (delimeterMatcher.find()) {
int currentStart = delimeterMatcher.start();
int currentEnd = delimeterMatcher.end();
// skippedText may contain only letters, it may be an empty string
String skippedText = text.substring(lastEnd, currentStart);
if (!skippedText.equals("")) {
tokens.add(new Token<AffiliationLabel>(skippedText,
asciiIndices.get(lastEnd), asciiIndices.get(currentStart)));
}
// matched text may be a sequence of digits or a single non-alphanumeric character
String matchedText = text.substring(currentStart, currentEnd);
// ignore whitespace
if (!matchedText.matches("\\s")) {
tokens.add(new Token<AffiliationLabel>(matchedText,
asciiIndices.get(currentStart), asciiIndices.get(currentEnd)));
}
lastEnd = currentEnd;
}
String skippedText = text.substring(lastEnd, text.length());
if (!skippedText.equals("")) {
tokens.add(new Token<AffiliationLabel>(skippedText,
asciiIndices.get(lastEnd), asciiIndices.get(text.length())));
}
return tokens;
}
/**
* Returns a list of indices of all ASCII characters in the text
*
* @param text
* @return list of indices
*/
private static List<Integer> getAsciiSubstringIndices(String text) {
List<Integer> indices = new ArrayList<Integer>();
Matcher asciiMatcher = Pattern.compile("\\p{ASCII}").matcher(text);
while (asciiMatcher.find()) {
indices.add(asciiMatcher.start());
}
return indices;
}
/**
* Returns a string formed by the characters in the text with the given
* indices.
*
* @param text
* @param indices
* @return a substring
*/
private static String getSubstring(String text, List<Integer> indices) {
StringBuilder substringBuilder = new StringBuilder();
for (int i : indices) {
substringBuilder.append(text.charAt(i));
}
return substringBuilder.toString();
}
/**
* Tokenizes a normalized string. The string should be in NFKD, so that the
* accents are separated from the letters.
*
* Non-ASCII characters are ignored. Words separated by spaces are treated
* as different tokens. Spaces are not kept as tokens. Sequences of digits
* are separated from sequences of letters. Non-alphanumeric characters are
* all treated as separate tokens.
*
* @param text the text to tokenize, should be in NFKD
* @return list of tokens
*/
@Override
public List<Token<AffiliationLabel>> tokenize(String text) {
List<Integer> asciiIndices = getAsciiSubstringIndices(text);
String asciiText = getSubstring(text, asciiIndices);
asciiIndices.add(text.length()); // Guardian index
return asciiTextToTokens(asciiText, asciiIndices);
}
}
| 4,709 | 36.983871 | 94 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/affiliation/tools/AffiliationFeatureExtractor.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.affiliation.tools;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import pl.edu.icm.cermine.exception.AnalysisException;
import pl.edu.icm.cermine.metadata.affiliation.features.AffiliationDictionaryFeature;
import pl.edu.icm.cermine.metadata.model.AffiliationLabel;
import pl.edu.icm.cermine.metadata.model.DocumentAffiliation;
import pl.edu.icm.cermine.parsing.features.*;
import pl.edu.icm.cermine.parsing.model.Token;
import pl.edu.icm.cermine.parsing.tools.FeatureExtractor;
/**
* Feature extractor suitable for processing affiliations.
*
* @author Bartosz Tarnawski
*/
public class AffiliationFeatureExtractor implements FeatureExtractor<DocumentAffiliation> {
private List<BinaryTokenFeatureCalculator> binaryFeatures;
private List<KeywordFeatureCalculator<Token<AffiliationLabel>>> keywordFeatures;
private WordFeatureCalculator wordFeature;
@SuppressWarnings("unchecked")
public AffiliationFeatureExtractor() throws AnalysisException {
binaryFeatures
= new ArrayList<BinaryTokenFeatureCalculator>(
Arrays.<BinaryTokenFeatureCalculator>asList(
new IsNumberFeature(),
new IsUpperCaseFeature(),
new IsAllUpperCaseFeature(),
new IsAllLowerCaseFeature()
));
keywordFeatures = Arrays.<KeywordFeatureCalculator<Token<AffiliationLabel>>>asList(
new AffiliationDictionaryFeature("KeywordAddress", "/pl/edu/icm/cermine/metadata/affiliation/features/address_keywords.txt", false),
new AffiliationDictionaryFeature("KeywordCountry", "/pl/edu/icm/cermine/metadata/affiliation/features/countries2.txt", true),
new AffiliationDictionaryFeature("KeywordInstitution", "/pl/edu/icm/cermine/metadata/affiliation/features/institution_keywords.txt", false)
);
wordFeature
= new WordFeatureCalculator(Arrays.<BinaryTokenFeatureCalculator>asList(
new IsNumberFeature()), false);
}
/**
* @param commonWords the words that are not considered 'Rare'
* @throws AnalysisException AnalysisException
*/
public AffiliationFeatureExtractor(List<String> commonWords) throws AnalysisException {
this();
binaryFeatures.add(new IsRareFeature(commonWords, true));
}
public AffiliationFeatureExtractor(List<BinaryTokenFeatureCalculator> binaryFeatures,
List<KeywordFeatureCalculator<Token<AffiliationLabel>>> keywordFeatures,
WordFeatureCalculator wordFeature) {
this.binaryFeatures = binaryFeatures;
this.keywordFeatures = keywordFeatures;
this.wordFeature = wordFeature;
}
@Override
public void calculateFeatures(DocumentAffiliation affiliation) {
List<Token<AffiliationLabel>> tokens = affiliation.getTokens();
for (Token<AffiliationLabel> token : tokens) {
for (BinaryTokenFeatureCalculator binaryFeatureCalculator : binaryFeatures) {
if (binaryFeatureCalculator.calculateFeaturePredicate(token, affiliation)) {
token.addFeature(binaryFeatureCalculator.getFeatureName());
}
}
String wordFeatureString = wordFeature.calculateFeatureValue(token, affiliation);
if (wordFeatureString != null) {
token.addFeature(wordFeatureString);
}
}
for (KeywordFeatureCalculator<Token<AffiliationLabel>> dictionaryFeatureCalculator
: keywordFeatures) {
dictionaryFeatureCalculator.calculateDictionaryFeatures(tokens);
}
}
}
| 4,540 | 43.087379 | 155 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/affiliation/features/AffiliationDictionaryFeature.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.affiliation.features;
import pl.edu.icm.cermine.exception.AnalysisException;
import pl.edu.icm.cermine.metadata.affiliation.tools.AffiliationTokenizer;
import pl.edu.icm.cermine.metadata.model.AffiliationLabel;
import pl.edu.icm.cermine.parsing.features.KeywordFeatureCalculator;
import pl.edu.icm.cermine.parsing.model.Token;
/**
* Keyword feature calculator suitable for processing affiliations.
*
* @author Bartosz Tarnawski
*/
public class AffiliationDictionaryFeature extends KeywordFeatureCalculator<Token<AffiliationLabel>> {
/**
* @param FeatureString the string which will be added to the matching
* tokens' features lists
* @param dictionaryFileName the name of the dictionary to be used (must be
* a package resource)
* @param caseSensitive whether dictionary lookups should be case sensitive
* @throws AnalysisException AnalysisException
*/
public AffiliationDictionaryFeature(String FeatureString, String dictionaryFileName,
boolean caseSensitive) throws AnalysisException {
super(FeatureString, dictionaryFileName, caseSensitive, new AffiliationTokenizer());
}
}
| 1,924 | 39.957447 | 101 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/model/IDType.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.model;
/**
* Identifier types.
*
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public enum IDType {
HINDAWI,
DOI,
URN;
}
| 934 | 26.5 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/model/DocumentDate.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.model;
import pl.edu.icm.cermine.content.cleaning.ContentCleaner;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class DocumentDate {
private String year;
private String month;
private String day;
public DocumentDate(String year) {
this(year, null, null);
}
public DocumentDate(String year, String month, String day) {
this.year = year;
this.month = month;
this.day = day;
clean();
}
public String getDay() {
return day;
}
public String getMonth() {
return month;
}
public String getYear() {
return year;
}
private void clean() {
day = ContentCleaner.clean(day);
month = ContentCleaner.clean(month);
year = ContentCleaner.clean(year);
}
}
| 1,606 | 24.109375 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/model/AffiliationLabel.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.model;
/**
* Document affiliation label. It is represented by a pair: XML tag used in the NML format
* and the GRMM label used in the ACRF.
*
* @author Bartosz Tarnawski
*/
public enum AffiliationLabel {
INST,
ADDR,
COUN,
AUTH,
TEXT;
}
| 1,042 | 25.74359 | 90 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/model/DocumentAffiliation.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.model;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import pl.edu.icm.cermine.content.cleaning.ContentCleaner;
import pl.edu.icm.cermine.metadata.tools.MetadataTools;
import pl.edu.icm.cermine.parsing.model.ParsableString;
import pl.edu.icm.cermine.parsing.model.Token;
/**
* Represents a document affiliation as a parsable string.
*
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
* @author Bartosz Tarnawski
*/
public class DocumentAffiliation implements ParsableString<Token<AffiliationLabel>> {
private String id = "";
private String index;
private String rawText;
private List<Token<AffiliationLabel>> tokens;
public DocumentAffiliation(String rawText) {
this(null, rawText);
}
public DocumentAffiliation(String index, String rawText) {
this.index = ContentCleaner.clean(index);
if (rawText.matches(".+ \\([^\\(\\)]*\\)$")) {
rawText = StringUtils.reverse(rawText).replaceFirst("\\)", "")
.replaceFirst("\\( ", " ,");
rawText = StringUtils.reverse(rawText);
}
this.rawText = MetadataTools.cleanAndNormalize(rawText);
this.tokens = new ArrayList<Token<AffiliationLabel>>();
}
public String getId() {
return id;
}
void setId(String id) {
this.id = id;
}
public String getIndex() {
return index;
}
@Override
public String getRawText() {
return rawText;
}
public void setRawText(String rawText) {
this.rawText = rawText;
}
@Override
public List<Token<AffiliationLabel>> getTokens() {
return tokens;
}
@Override
public void setTokens(List<Token<AffiliationLabel>> tokens) {
this.tokens = tokens;
}
@Override
public void addToken(Token<AffiliationLabel> token) {
this.tokens.add(token);
}
public void mergeTokens() {
if (tokens == null || tokens.isEmpty()) {
return;
}
Token<AffiliationLabel> actToken = null;
List<Token<AffiliationLabel>> newTokens = new ArrayList<Token<AffiliationLabel>>();
for (Token<AffiliationLabel> token : tokens) {
if (actToken == null) {
actToken = new Token<AffiliationLabel>(token.getText(), token.getStartIndex(), token.getEndIndex(), token.getLabel());
} else if (actToken.getLabel().equals(token.getLabel())) {
actToken.setEndIndex(token.getEndIndex());
} else {
newTokens.add(actToken);
actToken = new Token<AffiliationLabel>(token.getText(), token.getStartIndex(), token.getEndIndex(), token.getLabel());
}
}
newTokens.add(actToken);
for (Token<AffiliationLabel> token : newTokens) {
int i = newTokens.indexOf(token);
if (i + 1 == newTokens.size()) {
token.setEndIndex(rawText.length());
} else {
token.setEndIndex(newTokens.get(i + 1).getStartIndex());
}
token.setText(rawText.substring(token.getStartIndex(), token.getEndIndex()));
}
tokens = newTokens;
}
@Override
public void appendText(String text) {
this.rawText += text;
}
@Override
public void clean() {
index = ContentCleaner.clean(index);
rawText = ContentCleaner.cleanAllAndBreaks(rawText);
}
public String getOrganization() {
for (Token<AffiliationLabel> token : tokens) {
if (token.getLabel().equals(AffiliationLabel.INST)) {
return Normalizer.normalize(token.getText(), Normalizer.Form.NFC);
}
}
return null;
}
public String getCountry() {
for (Token<AffiliationLabel> token : tokens) {
if (token.getLabel().equals(AffiliationLabel.COUN)) {
return token.getText().replaceAll("[^ a-zA-Z]$", "");
}
}
return null;
}
}
| 4,862 | 30.173077 | 134 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/model/DocumentMetadata.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import pl.edu.icm.cermine.content.cleaning.ContentCleaner;
import pl.edu.icm.cermine.tools.timeout.TimeoutRegister;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class DocumentMetadata {
private String title;
private final Map<IDType, String> ids = new EnumMap<IDType, String>(IDType.class);
private final List<DocumentAuthor> authors = new ArrayList<DocumentAuthor>();
private final List<DocumentAuthor> editors = new ArrayList<DocumentAuthor>();
private String abstrakt;
private List<String> keywords = new ArrayList<String>();
private String journal;
private String journalISSN;
private String volume;
private String issue;
private String firstPage;
private String lastPage;
private String publisher;
private final Map<DateType, DocumentDate> dates = new EnumMap<DateType, DocumentDate>(DateType.class);
private final List<DocumentAffiliation> affiliations = new ArrayList<DocumentAffiliation>();
private final List<String> emails = new ArrayList<String>();
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<IDType> getIdTypes() {
List<IDType> idTypes = new ArrayList<IDType>();
idTypes.addAll(ids.keySet());
return idTypes;
}
public String getId(IDType idType) {
return ids.get(idType);
}
public void setDate(DateType type, String day, String month, String year) {
DocumentDate date = new DocumentDate(year, month, day);
dates.put(type, date);
}
public DocumentDate getDate(DateType type) {
return dates.get(type);
}
public void addAffiliationToAllAuthors(String affiliation) {
DocumentAffiliation aff = getAffiliationByName(affiliation);
if (aff == null) {
aff = new DocumentAffiliation(affiliation);
affiliations.add(aff);
}
for (DocumentAuthor author : authors) {
author.addAffiliation(aff);
}
}
public void setAffiliationByIndex(String index, String affiliation) {
DocumentAffiliation aff = getAffiliationByName(affiliation);
if (aff == null) {
aff = new DocumentAffiliation(affiliation);
affiliations.add(aff);
}
for (DocumentAuthor author : authors) {
if (author.getAffiliationRefs().contains(index)) {
author.addAffiliation(aff);
}
}
}
private DocumentAffiliation getAffiliationByName(String name) {
DocumentAffiliation ret = null;
for (DocumentAffiliation affiliation : affiliations) {
if (affiliation.getRawText().equals(name)){
ret = affiliation;
}
}
return ret;
}
public void addId(IDType type, String id) {
ids.put(type, id);
}
public void addAuthor(String authorName, List<String> affiliationIndexes) {
DocumentAuthor author = new DocumentAuthor(authorName, new ArrayList<String>(affiliationIndexes));
authors.add(author);
}
public void addAuthor(String authorName, List<String> affiliationIndexes, String email) {
if (email.isEmpty()) {
email = null;
}
if (email != null && !emails.contains(email)) {
emails.add(email);
}
DocumentAuthor author = new DocumentAuthor(authorName, email, new ArrayList<String>(affiliationIndexes));
authors.add(author);
}
public void addAuthorWithAffiliations(String authorName, String email, List<String> affiliations) {
if (email.isEmpty()) {
email = null;
}
if (email != null && !emails.contains(email)) {
emails.add(email);
}
DocumentAuthor author = new DocumentAuthor(authorName, email);
authors.add(author);
for (String affiliation: affiliations) {
DocumentAffiliation aff = getAffiliationByName(affiliation);
if (aff == null) {
aff = new DocumentAffiliation(affiliation);
this.affiliations.add(aff);
author.addAffiliation(aff);
}
}
}
public List<DocumentAuthor> getAuthors() {
return authors;
}
public List<String> getEmails() {
return emails;
}
public void addEmail(String email) {
emails.add(email);
}
public String getIssue() {
return issue;
}
public void setIssue(String issue) {
this.issue = issue;
}
public String getJournal() {
return journal;
}
public void setJournal(String journal) {
this.journal = journal;
}
public String getVolume() {
return volume;
}
public void setVolume(String volume) {
this.volume = volume;
}
public String getAbstrakt() {
return abstrakt;
}
public void setAbstrakt(String abstrakt) {
this.abstrakt = abstrakt;
}
public void addEditor(String editorName) {
editors.add(new DocumentAuthor(editorName));
}
public List<DocumentAuthor> getEditors() {
return editors;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getJournalISSN() {
return journalISSN;
}
public void setJournalISSN(String journalISSN) {
this.journalISSN = journalISSN;
}
public void setPages(String firstPage, String lastPage) {
this.firstPage = firstPage;
this.lastPage = lastPage;
}
public String getFirstPage() {
return firstPage;
}
public String getLastPage() {
return lastPage;
}
public void addKeyword(String keyword) {
keywords.add(keyword);
}
public List<String> getKeywords() {
return keywords;
}
public List<DocumentAffiliation> getAffiliations() {
return affiliations;
}
public void clean() {
title = ContentCleaner.cleanAllAndBreaks(title);
for (IDType id : ids.keySet()) {
ids.put(id, ContentCleaner.clean(ids.get(id)));
}
for (DocumentAffiliation affiliation : affiliations) {
affiliation.clean();
TimeoutRegister.get().check();
}
Collections.sort(affiliations, new Comparator<DocumentAffiliation>() {
@Override
public int compare(DocumentAffiliation a1, DocumentAffiliation a2) {
return a1.getRawText().compareTo(a2.getRawText());
}
});
int id = 0;
for (DocumentAffiliation affiliation : affiliations) {
affiliation.setId(String.valueOf(id++));
}
for (DocumentAuthor author : authors) {
author.clean();
Collections.sort(author.getAffiliationRefs());
Collections.sort(author.getEmails());
Collections.sort(author.getAffiliations(), new Comparator<DocumentAffiliation>() {
@Override
public int compare(DocumentAffiliation a1, DocumentAffiliation a2) {
if (!a1.getId().equals(a2.getId())) {
return a1.getId().compareTo(a2.getId());
}
return a1.getRawText().compareTo(a2.getRawText());
}
});
TimeoutRegister.get().check();
}
for (DocumentAuthor editor : editors) {
editor.clean();
}
Collections.sort(emails);
abstrakt = ContentCleaner.cleanAllAndBreaks(abstrakt);
List<String> newKeywords = new ArrayList<String>(keywords.size());
for (String keyword : keywords) {
newKeywords.add(ContentCleaner.clean(keyword));
}
keywords = newKeywords;
journal = ContentCleaner.clean(journal);
journalISSN = ContentCleaner.clean(journalISSN);
volume = ContentCleaner.clean(volume);
issue = ContentCleaner.clean(issue);
firstPage = ContentCleaner.clean(firstPage);
lastPage = ContentCleaner.clean(lastPage);
publisher = ContentCleaner.clean(publisher);
}
}
| 9,419 | 28.810127 | 113 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/model/DateType.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.model;
/**
* Date types.
*
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public enum DateType {
ACCEPTED,
RECEIVED,
REVISED,
PUBLISHED,
}
| 959 | 25.666667 | 78 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/model/DocumentAuthor.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.model;
import java.util.ArrayList;
import java.util.List;
import pl.edu.icm.cermine.content.cleaning.ContentCleaner;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class DocumentAuthor {
private String name;
private List<String> emails;
private List<String> affiliationRefs;
private List<DocumentAffiliation> affiliations;
public DocumentAuthor(String name) {
this(name, null, new ArrayList<String>());
}
public DocumentAuthor(String name, String email) {
this(name, email, new ArrayList<String>());
}
public DocumentAuthor(String name, List<String> affiliationRefs) {
this(name, null, affiliationRefs);
}
public DocumentAuthor(String name, String email, List<String> affiliationRefs) {
this.name = name;
this.emails = new ArrayList<String>();
if (email != null) {
this.emails.add(email);
}
this.affiliationRefs = affiliationRefs;
this.affiliations = new ArrayList<DocumentAffiliation>();
}
public List<String> getEmails() {
return emails;
}
public void addEmail(String email) {
if (email != null && !email.isEmpty() && !emails.contains(email)) {
emails.add(email);
}
}
public String getName() {
return name;
}
public void addAffiliation(DocumentAffiliation affiliation) {
if (!affiliations.contains(affiliation)) {
affiliations.add(affiliation);
}
}
public List<DocumentAffiliation> getAffiliations() {
return affiliations;
}
public List<String> getAffiliationRefs() {
return affiliationRefs;
}
void clean() {
name = ContentCleaner.clean(name);
List<String> newEmails = new ArrayList<String>();
for (String email: emails) {
newEmails.add(ContentCleaner.clean(email));
}
emails = newEmails;
}
}
| 2,749 | 27.061224 | 84 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/transformers/MetadataToNLMConverter.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.transformers;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import org.jdom.Element;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.metadata.affiliation.tools.CountryISOCodeFinder;
import pl.edu.icm.cermine.metadata.model.*;
import pl.edu.icm.cermine.parsing.model.Token;
import pl.edu.icm.cermine.tools.XMLTools;
import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class MetadataToNLMConverter implements ModelToModelConverter<DocumentMetadata, Element> {
@Override
public Element convert(DocumentMetadata source, Object... hints) throws TransformationException {
Element metadata = new Element(TAG_ARTICLE);
Element front = new Element(TAG_FRONT);
front.addContent(convertJournalMetadata(source));
front.addContent(convertArticleMetadata(source));
metadata.addContent(front);
return metadata;
}
@Override
public List<Element> convertAll(List<DocumentMetadata> source, Object... hints) throws TransformationException {
List<Element> elements = new ArrayList<Element>(source.size());
for (DocumentMetadata metadata : source) {
elements.add(convert(metadata));
}
return elements;
}
private Element convertJournalMetadata(DocumentMetadata source) {
Element metadata = new Element(TAG_JOURNAL_META);
String[] journalPath = new String[]{TAG_JOURNAL_TITLE_GROUP, TAG_JOURNAL_TITLE};
addElement(metadata, journalPath, source.getJournal());
addElement(metadata, TAG_ISSN, source.getJournalISSN(), TAG_PUB_TYPE, ATTR_VALUE_PUB_TYPE_PPUB);
String[] publisherPath = new String[]{TAG_PUBLISHER, TAG_PUBLISHER_NAME};
addElement(metadata, publisherPath, source.getPublisher());
return metadata;
}
private Element convertArticleMetadata(DocumentMetadata source) throws TransformationException {
Element metadata = new Element(TAG_ARTICLE_META);
Map<IDType, String> typeToAttr = new EnumMap<IDType, String>(IDType.class);
typeToAttr.put(IDType.DOI, "doi");
typeToAttr.put(IDType.HINDAWI, "hindawi-id");
typeToAttr.put(IDType.URN, "urn");
for (IDType idType : source.getIdTypes()) {
addElement(metadata, TAG_ARTICLE_ID, source.getId(idType), ATTR_PUB_ID_TYPE, typeToAttr.get(idType));
}
String[] titlePath = new String[]{TAG_TITLE_GROUP, TAG_ARTICLE_TITLE};
addElement(metadata, titlePath, source.getTitle());
if (!source.getAuthors().isEmpty() || !source.getEditors().isEmpty()
|| !source.getAffiliations().isEmpty()) {
Element contributors = new Element(TAG_CONTRIB_GROUP);
for (DocumentAuthor author : source.getAuthors()) {
contributors.addContent(convertAuthor(author));
}
for (DocumentAuthor editor : source.getEditors()) {
contributors.addContent(convertEditor(editor));
}
for (DocumentAffiliation affiliation : source.getAffiliations()) {
contributors.addContent(convertAffiliation(affiliation));
}
metadata.addContent(contributors);
}
DocumentDate pubDate = source.getDate(DateType.PUBLISHED);
if (pubDate != null) {
metadata.addContent(convertDate(TAG_PUB_DATE, DateType.PUBLISHED, pubDate));
}
addElement(metadata, TAG_VOLUME, source.getVolume());
addElement(metadata, TAG_ISSUE, source.getIssue());
addElement(metadata, TAG_FPAGE, source.getFirstPage());
addElement(metadata, TAG_LPAGE, source.getLastPage());
DocumentDate accDate = source.getDate(DateType.ACCEPTED);
DocumentDate recDate = source.getDate(DateType.RECEIVED);
DocumentDate revDate = source.getDate(DateType.REVISED);
if (accDate != null || recDate != null || revDate != null) {
Element history = new Element(TAG_HISTORY);
if (accDate != null) {
history.addContent(convertDate(TAG_DATE, DateType.ACCEPTED, accDate));
}
if (recDate != null) {
history.addContent(convertDate(TAG_DATE, DateType.RECEIVED, recDate));
}
if (revDate != null) {
history.addContent(convertDate(TAG_DATE, DateType.REVISED, revDate));
}
metadata.addContent(history);
}
String[] abstractPath = new String[]{TAG_ABSTRACT, TAG_P};
addElement(metadata, abstractPath, source.getAbstrakt());
if (!source.getKeywords().isEmpty()) {
Element keywords = new Element(TAG_KWD_GROUP);
for (String keyword : source.getKeywords()) {
addElement(keywords, TAG_KWD, keyword);
}
metadata.addContent(keywords);
}
return metadata;
}
private Element convertAuthor(DocumentAuthor author) {
Element contributor = new Element(TAG_CONTRIB);
contributor.setAttribute(ATTR_CONTRIB_TYPE, ATTR_VALUE_CONTRIB_AUTHOR);
addElement(contributor, TAG_STRING_NAME, author.getName());
for (String email: author.getEmails()) {
addElement(contributor, TAG_EMAIL, email);
}
for (DocumentAffiliation aff : author.getAffiliations()) {
Element affRef = createElement(TAG_XREF, aff.getId());
affRef.setAttribute(ATTR_REF_TYPE, ATTR_VALUE_REF_TYPE_AFF);
affRef.setAttribute(ATTR_RID, "aff" + aff.getId());
contributor.addContent(affRef);
}
return contributor;
}
public Element convertAffiliation(DocumentAffiliation affiliation) throws TransformationException {
Element aff = new Element(TAG_AFFILIATION);
aff.setAttribute(ATTR_ID, "aff" + affiliation.getId());
addElement(aff, TAG_LABEL, affiliation.getId());
for (Token<AffiliationLabel> token : affiliation.getTokens()) {
switch (token.getLabel()) {
case TEXT:
aff.addContent(token.getText());
break;
case COUN:
CountryISOCodeFinder finder = new CountryISOCodeFinder();
String isoCode = finder.getCountryISOCode(token.getText());
if (isoCode == null) {
addElement(aff, TAG_COUNTRY, token.getText());
} else {
addElement(aff, TAG_COUNTRY, token.getText(), ATTR_COUNTRY, isoCode);
} break;
case INST:
addElement(aff, TAG_INSTITUTION, token.getText());
break;
case ADDR:
addElement(aff, TAG_ADDRESS, token.getText());
break;
default:
break;
}
}
return aff;
}
private Element convertEditor(DocumentAuthor editor) {
Element contributor = new Element(TAG_CONTRIB);
contributor.setAttribute(ATTR_CONTRIB_TYPE, ATTR_VALUE_CONTRIB_EDITOR);
addElement(contributor, TAG_STRING_NAME, editor.getName());
return contributor;
}
private Element convertDate(String name, DateType type, DocumentDate date) {
Map<DateType, String> typeToAttr = new EnumMap<DateType, String>(DateType.class);
typeToAttr.put(DateType.ACCEPTED, ATTR_VALUE_DATE_ACCEPTED);
typeToAttr.put(DateType.RECEIVED, ATTR_VALUE_DATE_RECEIVED);
typeToAttr.put(DateType.REVISED, ATTR_VALUE_DATE_REVISED);
Element historyDate = new Element(name);
if (!type.equals(DateType.PUBLISHED)) {
historyDate.setAttribute(ATTR_DATE_TYPE, typeToAttr.get(type));
}
addElement(historyDate, TAG_DAY, date.getDay());
addElement(historyDate, TAG_MONTH, date.getMonth());
addElement(historyDate, TAG_YEAR, date.getYear());
return historyDate;
}
private void addElement(Element parent, String[] names, String text) {
if (text != null && names.length != 0) {
Element prev = parent;
for (String name : names) {
Element element = new Element(name);
prev.addContent(element);
prev = element;
}
prev.setText(XMLTools.removeInvalidXMLChars(text));
}
}
private void addElement(Element parent, String name, String text) {
if (text != null) {
Element element = createElement(name, text);
parent.addContent(element);
}
}
private void addElement(Element parent, String name, String text, String attrName, String attrValue) {
if (text != null) {
Element element = createElement(name, text);
element.setAttribute(attrName, attrValue);
parent.addContent(element);
}
}
private Element createElement(String name, String text) {
Element element = new Element(name);
element.setText(XMLTools.removeInvalidXMLChars(text));
return element;
}
private static final String TAG_ABSTRACT = "abstract";
private static final String TAG_ADDRESS = "addr-line";
private static final String TAG_AFFILIATION = "aff";
private static final String TAG_ARTICLE = "article";
private static final String TAG_ARTICLE_ID = "article-id";
private static final String TAG_ARTICLE_META = "article-meta";
private static final String TAG_ARTICLE_TITLE = "article-title";
private static final String TAG_CONTRIB = "contrib";
private static final String TAG_CONTRIB_GROUP = "contrib-group";
private static final String TAG_COUNTRY = "country";
private static final String TAG_DATE = "date";
private static final String TAG_DAY = "day";
private static final String TAG_EMAIL = "email";
private static final String TAG_FPAGE = "fpage";
private static final String TAG_FRONT = "front";
private static final String TAG_HISTORY = "history";
private static final String TAG_INSTITUTION = "institution";
private static final String TAG_ISSN = "issn";
private static final String TAG_ISSUE = "issue";
private static final String TAG_JOURNAL_META = "journal-meta";
private static final String TAG_JOURNAL_TITLE = "journal-title";
private static final String TAG_JOURNAL_TITLE_GROUP = "journal-title-group";
private static final String TAG_KWD = "kwd";
private static final String TAG_KWD_GROUP = "kwd-group";
private static final String TAG_LABEL = "label";
private static final String TAG_LPAGE = "lpage";
private static final String TAG_MONTH = "month";
private static final String TAG_P = "p";
private static final String TAG_PUB_DATE = "pub-date";
private static final String TAG_PUB_TYPE = "pub-type";
private static final String TAG_PUBLISHER = "publisher";
private static final String TAG_PUBLISHER_NAME = "publisher-name";
private static final String TAG_STRING_NAME = "string-name";
private static final String TAG_TITLE_GROUP = "title-group";
private static final String TAG_VOLUME = "volume";
private static final String TAG_YEAR = "year";
private static final String TAG_XREF = "xref";
private static final String ATTR_CONTRIB_TYPE = "contrib-type";
private static final String ATTR_COUNTRY = "country";
private static final String ATTR_DATE_TYPE = "date-type";
private static final String ATTR_ID = "id";
private static final String ATTR_PUB_ID_TYPE = "pub-id-type";
private static final String ATTR_REF_TYPE = "ref-type";
private static final String ATTR_RID = "rid";
private static final String ATTR_VALUE_DATE_ACCEPTED = "accepted";
private static final String ATTR_VALUE_CONTRIB_AUTHOR = "author";
private static final String ATTR_VALUE_CONTRIB_EDITOR = "editor";
private static final String ATTR_VALUE_PUB_TYPE_PPUB = "ppub";
private static final String ATTR_VALUE_DATE_RECEIVED = "received";
private static final String ATTR_VALUE_REF_TYPE_AFF = "aff";
private static final String ATTR_VALUE_DATE_REVISED = "revised";
}
| 14,148 | 46.006645 | 116 | java |
CERMINE | CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/transformers/NLMToMetadataConverter.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.metadata.transformers;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.metadata.model.DateType;
import pl.edu.icm.cermine.metadata.model.DocumentMetadata;
import pl.edu.icm.cermine.metadata.model.IDType;
import pl.edu.icm.cermine.tools.XMLTools;
import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class NLMToMetadataConverter implements ModelToModelConverter<Element, DocumentMetadata> {
@Override
public DocumentMetadata convert(Element source, Object... hints) throws TransformationException {
try {
DocumentMetadata metadata = new DocumentMetadata();
convertTitle(source, metadata);
convertAbstract(source, metadata);
convertJournal(source, metadata);
convertVolume(source, metadata);
convertIssue(source, metadata);
convertPages(source, metadata);
convertPublisher(source, metadata);
convertKeywords(source, metadata);
convertIds(source, metadata);
convertDates(source, metadata);
convertAuthors(source, metadata);
convertEditors(source, metadata);
convertAffiliations(source, metadata);
return metadata;
} catch (JDOMException ex) {
throw new TransformationException(ex);
}
}
private void convertTitle(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("./article-meta//article-title");
Element title = (Element)xpath.selectSingleNode(source);
if (title != null) {
metadata.setTitle(XMLTools.getTextContent(title));
}
}
private void convertAbstract(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("./article-meta//abstract");
Element abstrakt = (Element)xpath.selectSingleNode(source);
if (abstrakt != null) {
metadata.setAbstrakt(XMLTools.getTextContent(abstrakt));
}
}
private void convertJournal(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("./journal-meta//journal-title");
Element journal = (Element)xpath.selectSingleNode(source);
if (journal != null) {
metadata.setJournal(XMLTools.getTextContent(journal));
}
xpath = XPath.newInstance("./journal-meta//issn[@pub-type='ppub']");
Element journalISSN = (Element)xpath.selectSingleNode(source);
if (journalISSN != null) {
metadata.setJournalISSN(XMLTools.getTextContent(journalISSN));
}
}
private void convertVolume(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("./article-meta//volume");
Element volume = (Element)xpath.selectSingleNode(source);
if (volume != null) {
metadata.setVolume(XMLTools.getTextContent(volume));
}
}
private void convertIssue(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("./article-meta//issue");
Element issue = (Element)xpath.selectSingleNode(source);
if (issue != null) {
metadata.setIssue(XMLTools.getTextContent(issue));
}
}
private void convertPages(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("./article-meta//fpage");
Element fPage = (Element)xpath.selectSingleNode(source);
String fp = "";
if (fPage != null) {
fp = XMLTools.getTextContent(fPage);
}
xpath = XPath.newInstance("./article-meta//lpage");
Element lPage = (Element)xpath.selectSingleNode(source);
String lp = "";
if (lPage != null) {
lp = XMLTools.getTextContent(lPage);
}
metadata.setPages(fp, lp);
}
private void convertPublisher(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("./journal-meta//publisher-name");
Element publisher = (Element)xpath.selectSingleNode(source);
if (publisher != null) {
metadata.setPublisher(XMLTools.getTextContent(publisher));
}
}
private void convertKeywords(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("./article-meta//kwd-group/kwd");
List keywords = xpath.selectNodes(source);
for (Object keyword : keywords) {
metadata.addKeyword(XMLTools.getTextContent((Element)keyword));
}
}
private void convertIds(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("./article-meta//article-id");
List ids = xpath.selectNodes(source);
for (Object i : ids) {
Element id = (Element) i;
if ("doi".equals(id.getAttributeValue("pub-id-type"))) {
metadata.addId(IDType.DOI, XMLTools.getTextContent(id));
}
}
}
private void convertDates(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("./article-meta//pub-date[@pub-type='ppub']");
Element pubDate = (Element)xpath.selectSingleNode(source);
if (pubDate == null) {
xpath = XPath.newInstance("./article-meta//pub-date");
pubDate = (Element)xpath.selectSingleNode(source);
}
convertDate(DateType.PUBLISHED, pubDate, metadata);
xpath = XPath.newInstance("./article-meta//history/date[@date-type='received']");
convertDate(DateType.RECEIVED, (Element)xpath.selectSingleNode(source), metadata);
xpath = XPath.newInstance("./article-meta//history/date[@date-type='accepted']");
convertDate(DateType.ACCEPTED, (Element)xpath.selectSingleNode(source), metadata);
xpath = XPath.newInstance("./article-meta//history/date[@date-type='revised']");
convertDate(DateType.REVISED, (Element)xpath.selectSingleNode(source), metadata);
}
private void convertDate(DateType type, Element source, DocumentMetadata metadata) {
if (source == null) {
return;
}
String day = null;
if (source.getChild("day") != null) {
day = XMLTools.getTextContent(source.getChild("day"));
}
String month = null;
if (source.getChild("month") != null) {
month = XMLTools.getTextContent(source.getChild("month"));
}
String year = null;
if (source.getChild("year") != null) {
year = XMLTools.getTextContent(source.getChild("year"));
}
metadata.setDate(type, day, month, year);
}
private void convertAuthors(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("./article-meta//contrib[@contrib-type='author']");
List authors = xpath.selectNodes(source);
for (Object a : authors) {
Element author = (Element)a;
String name = author.getChildText("string-name");
if (name == null && author.getChild("name") != null) {
StringBuilder sb = new StringBuilder();
for (Object gn : author.getChild("name").getChildren("given-names")){
sb.append(XMLTools.getTextContent((Element)gn));
sb.append(" ");
}
sb.append(author.getChild("name").getChildText("surname"));
name = sb.toString().trim();
}
if (name == null) {
name = XMLTools.getTextContent(author.getChild("collab"));
}
List<String> aIs = new ArrayList<String>();
for (Object af : author.getChildren("xref")) {
Element aff = (Element)af;
if ("aff".equals(aff.getAttributeValue("ref-type"))) {
aIs.add(aff.getAttributeValue("rid"));
}
}
xpath = XPath.newInstance(".//email");
if (xpath.selectSingleNode(author) != null) {
String email = XMLTools.getTextContent((Element)xpath.selectSingleNode(author));
metadata.addAuthor(name, aIs, email);
} else {
metadata.addAuthor(name, aIs);
}
}
}
private void convertEditors(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("./article-meta//contrib[@contrib-type='editor']");
List authors = xpath.selectNodes(source);
for (Object a : authors) {
Element author = (Element)a;
String name = author.getChildText("string-name");
if (name == null) {
XPath xpath1 = XPath.newInstance("./name/given-names");
XPath xpath2 = XPath.newInstance("./name/surname");
name = XMLTools.getTextContent((Element)xpath1.selectSingleNode(author)) + " "
+ XMLTools.getTextContent((Element)xpath2.selectSingleNode(author));
}
metadata.addEditor(name);
}
}
private void convertAffiliations(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("./article-meta//aff");
List affs = xpath.selectNodes(source);
for (Object a : affs) {
Element affiliation = (Element)a;
String id = affiliation.getAttributeValue("id");
String label = affiliation.getChildText("label");
String text = XMLTools.getTextContent(affiliation);
if (label != null && text.startsWith(label)) {
text = text.substring(label.length());
}
text = text.replaceAll("\\s+", " ").trim();
if (id == null) {
metadata.addAffiliationToAllAuthors(text);
} else {
metadata.setAffiliationByIndex(id, text);
}
}
}
@Override
public List<DocumentMetadata> convertAll(List<Element> source, Object... hints) throws TransformationException {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| 11,439 | 42.333333 | 116 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/Main.java | package lu.uni.tsopen;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public class Main {
public static void main(String[] args) {
Analysis analysis = new Analysis(args);
analysis.run();
}
} | 1,200 | 31.459459 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/Analysis.java | package lu.uni.tsopen;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import org.javatuples.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.profiler.StopWatch;
import lu.uni.tsopen.logicBombs.PotentialLogicBombsRecovery;
import lu.uni.tsopen.pathPredicateRecovery.PathPredicateRecovery;
import lu.uni.tsopen.pathPredicateRecovery.SimpleBlockPredicateExtraction;
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import lu.uni.tsopen.utils.CommandLineOptions;
import lu.uni.tsopen.utils.Constants;
import lu.uni.tsopen.utils.TimeOut;
import lu.uni.tsopen.utils.Utils;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.jimple.IfStmt;
import soot.jimple.infoflow.InfoflowConfiguration.CallgraphAlgorithm;
import soot.jimple.infoflow.android.InfoflowAndroidConfiguration;
import soot.jimple.infoflow.android.SetupApplication;
import soot.jimple.infoflow.android.manifest.ProcessManifest;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public class Analysis {
private String pkgName;
private CommandLineOptions options;
private String fileName;
private PotentialLogicBombsRecovery plbr;
private InfoflowCFG icfg;
private int dexSize;
private int nbClasses;
private String fileSha256;
private SimpleBlockPredicateExtraction sbpe;
private PathPredicateRecovery ppr;
private Logger logger = LoggerFactory.getLogger(Main.class);
StopWatch stopWatchCG = new StopWatch("cg"),
stopWatchSBPE = new StopWatch("sbpe"),
stopWatchPPR = new StopWatch("ppr"),
stopWatchSE = new StopWatch("se"),
stopWatchPLBR = new StopWatch("plbr"),
stopWatchAPP = new StopWatch("app");
public Analysis(String[] args) {
this.options = new CommandLineOptions(args);
this.fileName = this.options.getFile();
this.pkgName = this.getPackageName(this.fileName);
this.fileSha256 = this.getFileSha256(this.fileName);
this.sbpe = null;
this.plbr = null;
this.icfg = null;
this.ppr = null;
}
public void run() {
try {
this.launchAnalysis();
} catch(Exception e) {
this.logger.error("Something went wrong : {}", e.getMessage());
this.logger.error("Ending program...");
this.printResultsInFile(true);
if (this.options.hasRaw()) {
this.printRawResults(true);
}
System.exit(0);
}
}
private void launchAnalysis() {
this.stopWatchAPP.start("app");
if(!this.options.hasQuiet() && !this.options.hasRaw()) {
System.out.println(String.format("TSOpen v1.0 started on %s\n", new Date()));
}
InfoflowAndroidConfiguration ifac = new InfoflowAndroidConfiguration();
ifac.setIgnoreFlowsInSystemPackages(false);
SetupApplication sa = null;
SootMethod dummyMainMethod = null;
SymbolicExecution se = null;
Thread sbpeThread = null,
pprThread = null,
seThread = null,
plbrThread = null;
TimeOut timeOut = new TimeOut(this.options.getTimeout(), this);
int timeout = timeOut.getTimeout();
timeOut.trigger();
if(!this.options.hasQuiet() && !this.options.hasRaw()) {
this.logger.info(String.format("%-35s : %s", "Package", this.getPackageName(this.fileName)));
this.logger.info(String.format("%-35s : %3s %s", "Timeout", timeout, timeout > 1 ? "mins" : "min"));
}
this.stopWatchCG.start("CallGraph");
ifac.getAnalysisFileConfig().setAndroidPlatformDir(this.options.getPlatforms());
ifac.getAnalysisFileConfig().setTargetAPKFile(this.fileName);
String cg = this.options.getCallGraph();
if(cg != null) {
switch(cg) {
case "SPARK": ifac.setCallgraphAlgorithm(CallgraphAlgorithm.SPARK);
break;
case "CHA": ifac.setCallgraphAlgorithm(CallgraphAlgorithm.CHA);
break;
case "VTA": ifac.setCallgraphAlgorithm(CallgraphAlgorithm.VTA);
break;
case "RTA": ifac.setCallgraphAlgorithm(CallgraphAlgorithm.RTA);
break;
}
}
sa = new SetupApplication(ifac);
sa.getConfig().setMergeDexFiles(true);
sa.constructCallgraph();
this.icfg = new InfoflowCFG();
this.stopWatchCG.stop();
this.nbClasses = Scene.v().getApplicationClasses().size();
if(!this.options.hasQuiet() && !this.options.hasRaw()) {
this.logger.info(String.format("%-35s : %s", "CallGraph construction", Utils.getFormattedTime(this.stopWatchCG.elapsedTime())));
}
dummyMainMethod = sa.getDummyMainMethod();
this.sbpe = new SimpleBlockPredicateExtraction(this.icfg, dummyMainMethod);
this.ppr = new PathPredicateRecovery(this.icfg, this.sbpe, dummyMainMethod, this.options.hasExceptions());
se = new SymbolicExecution(this.icfg, dummyMainMethod);
this.plbr = new PotentialLogicBombsRecovery(this.sbpe, se, this.ppr, this.icfg);
sbpeThread = new Thread(this.sbpe, "sbpe");
pprThread = new Thread(this.ppr, "pprr");
seThread = new Thread(se, "syex");
plbrThread = new Thread(this.plbr, "plbr");
this.stopWatchSBPE.start("sbpe");
sbpeThread.start();
this.stopWatchSE.start("se");
seThread.start();
try {
sbpeThread.join();
this.stopWatchSBPE.stop();
if(!this.options.hasQuiet() && !this.options.hasRaw()) {
this.logger.info(String.format("%-35s : %s", "Simple Block Predicate Extraction", Utils.getFormattedTime(this.stopWatchSBPE.elapsedTime())));
}
} catch (InterruptedException e) {
this.logger.error(e.getMessage());
}
this.stopWatchPPR.start("ppr");
pprThread.start();
try {
pprThread.join();
this.stopWatchPPR.stop();
if(!this.options.hasQuiet() && !this.options.hasRaw()) {
this.logger.info(String.format("%-35s : %s", "Path Predicate Recovery", Utils.getFormattedTime(this.stopWatchPPR.elapsedTime())));
}
seThread.join();
this.stopWatchSE.stop();
if(!this.options.hasQuiet() && !this.options.hasRaw()) {
this.logger.info(String.format("%-35s : %s", "Symbolic Execution", Utils.getFormattedTime(this.stopWatchSE.elapsedTime())));
}
} catch (InterruptedException e) {
this.logger.error(e.getMessage());
}
this.stopWatchPLBR.start("plbr");
plbrThread.start();
try {
plbrThread.join();
this.stopWatchPLBR.stop();
if(!this.options.hasQuiet() && !this.options.hasRaw()) {
this.logger.info(String.format("%-35s : %s", "Potential Logic Bombs Recovery", Utils.getFormattedTime(this.stopWatchPLBR.elapsedTime())));
}
} catch (InterruptedException e) {
this.logger.error(e.getMessage());
}
this.stopWatchAPP.stop();
if(!this.options.hasQuiet() && !this.options.hasRaw()) {
this.logger.info(String.format("%-35s : %s", "Application Execution Time", Utils.getFormattedTime(this.stopWatchAPP.elapsedTime())));
}
if(this.options.hasOutput()) {
this.printResultsInFile(false);
}
if (!this.options.hasQuiet()){
if (this.options.hasRaw()) {
this.printRawResults(false);
}else if(this.options.hasVerbose()) {
this.printVerboseResults();
}else {
this.printResults();
}
}
timeOut.cancel();
}
private void printVerboseResults() {
SootMethod ifMethod = null;
SootClass ifClass = null;
String ifComponent = null;
IfStmt ifStmt = null;
int LbCount = 0;
if(this.plbr.hasPotentialLogicBombs()) {
System.out.println(String.format("\n APK %s potentially contains the following logic bombs:", this.pkgName));
System.out.println("----------------------------------------------------------------");
for(Entry<IfStmt, Pair<List<SymbolicValue>, SootMethod>> e : this.plbr.getPotentialLogicBombs().entrySet()) {
LbCount += 1;
System.out.println(String.format("Potential logic bomb %d:", LbCount));
ifStmt = e.getKey();
ifMethod = this.icfg.getMethodOf(ifStmt);
ifClass = ifMethod.getDeclaringClass();
ifComponent = Utils.getComponentType(ifClass);
System.out.println(String.format("- It is located in class %s and in method %s", ifClass, ifMethod.getName()));
System.out.println(String.format("- The following \"if\" statement triggers the "
+ "potential logic bomb: \"if %s\" which contains the following possible predicates:", ifStmt.getCondition()));
for(SymbolicValue sv : e.getValue().getValue0()) {
System.out.println(String.format(" - %s %s", sv.getValue(), sv));
}
System.out.println(String.format("- The sequence of method calls to reach this potential logic"
+ " bomb starts in component of type %s and ends in component of type %s", Utils.getStartingComponent(ifMethod),
ifComponent));
System.out.println(String.format("- The sequence of method call to reach this potential logic bomb"
+ " (call stack) has a length of %s", Utils.join(", ", Utils.getLengthLogicBombCallStack(ifMethod))));
System.out.println(String.format("- The size of the logical formula to reach the potential logic bomb is %d", this.ppr.getSizeOfFullPath(ifStmt)));
System.out.println(String.format("- The following sensitive method was used to qualify the trigger as potentially a logic bomb: %s", e.getValue().getValue1().getSignature()));
System.out.println(Utils.isInCallGraph(ifMethod) ? "- The logic bomb is reachable from the program entry point" : "- The logic bomb is not "
+ "reachable from the program entry point");
System.out.println(String.format("- The potential logic bomb contains %d Jimple instructions", Utils.getGuardedBlocksDensity(this.ppr, ifStmt)));
System.out.println(Utils.isNested(ifStmt, this.icfg, this.plbr, this.ppr) ? "- The potential logic bomb is nested in another" : "- The potential logic bomb is not nested in another");
System.out.println("----------------------------------------------------------------\n");
}
}else {
System.out.println("\nNo Logic Bomb found\n");
}
}
private void printResults() {
SootMethod ifMethod = null;
SootClass ifClass = null;
String ifComponent = null;
IfStmt ifStmt = null;
if(this.plbr.hasPotentialLogicBombs()) {
System.out.println("\nPotential Logic Bombs found : ");
System.out.println("----------------------------------------------------------------");
for(Entry<IfStmt, Pair<List<SymbolicValue>, SootMethod>> e : this.plbr.getPotentialLogicBombs().entrySet()) {
ifStmt = e.getKey();
ifMethod = this.icfg.getMethodOf(ifStmt);
ifClass = ifMethod.getDeclaringClass();
ifComponent = Utils.getComponentType(ifClass);
System.out.println(String.format("- %-25s : if %s", "Statement", ifStmt.getCondition()));
System.out.println(String.format("- %-25s : %s", "Class", ifClass));
System.out.println(String.format("- %-25s : %s", "Method", ifMethod.getName()));
System.out.println(String.format("- %-25s : %s", "Starting Component", Utils.getStartingComponent(ifMethod)));
System.out.println(String.format("- %-25s : %s", "Ending Component", ifComponent));
System.out.println(String.format("- %-25s : %s", "CallStack length", Utils.join(", ", Utils.getLengthLogicBombCallStack(ifMethod))));
System.out.println(String.format("- %-25s : %s", "Size of formula", this.ppr.getSizeOfFullPath(ifStmt)));
System.out.println(String.format("- %-25s : %s", "Sensitive method", e.getValue().getValue1().getSignature()));
System.out.println(String.format("- %-25s : %s", "Reachable", Utils.isInCallGraph(ifMethod) ? "Yes" : "No"));
System.out.println(String.format("- %-25s : %s", "Guarded Blocks Density", Utils.getGuardedBlocksDensity(this.ppr, ifStmt)));
System.out.println(String.format("- %-25s : %s", "Nested", Utils.isNested(ifStmt, this.icfg, this.plbr, this.ppr) ? "Yes" : "No"));
for(SymbolicValue sv : e.getValue().getValue0()) {
System.out.println(String.format("- %-25s : %s (%s)", "Predicate", sv.getValue(), sv));
}
System.out.println("----------------------------------------------------------------\n");
}
}else {
System.out.println("\nNo Logic Bomb found\n");
}
}
/**
* Print analysis results in the given file
*/
private void printResultsInFile(boolean timeoutReached) {
PrintWriter writer = null;
try {
writer = new PrintWriter(new FileOutputStream(new File(this.options.getOutput()), true));
writer.append(this.getRawResults(timeoutReached));
writer.close();
} catch (Exception e) {
this.logger.error(e.getMessage());
}
}
private void printRawResults(boolean timeoutReached) {
System.out.println(this.getRawResults(timeoutReached));
}
/**
* Format :
* [sha256], [pkg_name], [count_of_triggers], [elapsed_time], [hasSuspiciousTrigger],
* [hasSuspiciousTriggerAfterControlDependency], [hasSuspiciousTriggerAfterPostFilters],
* [dex_size], [count_of_classes], [count_of_if], [if_depth], [count_of_objects]
* @param timeoutReached
* @return
*/
private String getRawResults(boolean timeoutReached) {
SootMethod ifMethod = null;
SootClass ifClass = null;
String ifStmtStr = null,
ifComponent = null;
List<SymbolicValue> values = null,
visitedValues = new ArrayList<SymbolicValue>();
SymbolicValue sv = null;
IfStmt ifStmt = null;
String symbolicValues = null;
StringBuilder result = new StringBuilder();
result.append(String.format("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%d,%d,%d,%d,%d,%d\n", this.fileSha256, this.pkgName,
timeoutReached ? 0 : this.plbr.getPotentialLogicBombs().size(), timeoutReached ? -1 : TimeUnit.SECONDS.convert(this.stopWatchAPP.elapsedTime(), TimeUnit.NANOSECONDS),
this.plbr == null ? 0 : this.plbr.ContainsSuspiciousCheck() ? 1 : 0, this.plbr == null ? 0 : this.plbr.ContainsSuspiciousCheckAfterControlDependency() ? 1 : 0,
this.plbr == null ? 0 : this.plbr.ContainsSuspiciousCheckAfterPostFilterStep() ? 1 : 0, this.dexSize, this.nbClasses,
this.sbpe == null ? 0 : this.sbpe.getIfCount(), this.sbpe == null ? 0 : this.sbpe.getIfDepthInMethods(), this.sbpe == null ? 0 : this.sbpe.getCountOfObject(),
TimeUnit.MILLISECONDS.convert(this.stopWatchCG.elapsedTime(), TimeUnit.NANOSECONDS),
TimeUnit.MILLISECONDS.convert(this.stopWatchPLBR.elapsedTime(), TimeUnit.NANOSECONDS),
TimeUnit.MILLISECONDS.convert(this.stopWatchPPR.elapsedTime(), TimeUnit.NANOSECONDS),
TimeUnit.MILLISECONDS.convert(this.stopWatchSBPE.elapsedTime(), TimeUnit.NANOSECONDS),
TimeUnit.MILLISECONDS.convert(this.stopWatchSE.elapsedTime(), TimeUnit.NANOSECONDS),
timeoutReached ? -1 : TimeUnit.MILLISECONDS.convert(this.stopWatchAPP.elapsedTime(), TimeUnit.NANOSECONDS)));
if(this.plbr != null) {
for(Entry<IfStmt, Pair<List<SymbolicValue>, SootMethod>> e : this.plbr.getPotentialLogicBombs().entrySet()) {
ifStmt = e.getKey();
symbolicValues = "";
ifMethod = this.icfg.getMethodOf(ifStmt);
ifClass = ifMethod.getDeclaringClass();
ifStmtStr = String.format("if %s", ifStmt.getCondition());
ifComponent = Utils.getComponentType(ifMethod.getDeclaringClass());
symbolicValues += String.format("%s%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;", Constants.FILE_LOGIC_BOMBS_DELIMITER,
ifStmtStr, ifClass, ifMethod.getName(), e.getValue().getValue1().getSignature(), ifComponent,
this.ppr.getSizeOfFullPath(ifStmt), Utils.isInCallGraph(ifMethod) ? 1 : 0, Utils.getStartingComponent(ifMethod),
Utils.getGuardedBlocksDensity(this.ppr, ifStmt), Utils.join(", ", Utils.getLengthLogicBombCallStack(ifMethod)),
Utils.guardedBlocksContainApplicationInvoke(this.ppr, ifStmt) ? 1 : 0,
Utils.isNested(ifStmt, this.icfg, this.plbr, this.ppr) ? 1 : 0);
values = e.getValue().getValue0();
visitedValues.clear();
for(int i = 0 ; i < values.size() ; i++) {
sv = values.get(i);
if(!visitedValues.contains(sv)) {
visitedValues.add(sv);
if(i != 0) {
symbolicValues += ":";
}
symbolicValues += String.format("%s (%s)", sv.getValue(), sv);
}
}
symbolicValues += "\n";
result.append(symbolicValues);
}
}
return result.toString();
}
public void timeoutReachedPrintResults() {
this.printResultsInFile(true);
if(this.options.hasRaw()) {
this.printRawResults(true);
}
}
private String getPackageName(String fileName) {
String pkgName = null;
ProcessManifest pm = null;
try {
pm = new ProcessManifest(fileName);
pkgName = pm.getPackageName();
this.dexSize = pm.getApk().getInputStream(Constants.CLASSES_DEX).available();
pm.close();
} catch (Exception e) {
this.logger.error(e.getMessage());
}
return pkgName;
}
private String getFileSha256(String file) {
MessageDigest sha256 = null;
FileInputStream fis = null;
StringBuffer sb = null;
byte[] data = null;
int read = 0;
byte[] hashBytes = null;
try {
sha256 = MessageDigest.getInstance("SHA-256");
fis = new FileInputStream(file);
data = new byte[1024];
read = 0;
while ((read = fis.read(data)) != -1) {
sha256.update(data, 0, read);
};
hashBytes = sha256.digest();
sb = new StringBuffer();
for (int i = 0; i < hashBytes.length; i++) {
sb.append(Integer.toString((hashBytes[i] & 0xff) + 0x100, 16).substring(1));
}
fis.close();
} catch (Exception e) {
this.logger.error(e.getMessage());
}
return sb.toString();
}
}
| 18,324 | 39.631929 | 187 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/logicBombs/PotentialLogicBombsRecovery.java | package lu.uni.tsopen.logicBombs;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.javatuples.Pair;
import org.javatuples.Septet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lu.uni.tsopen.pathPredicateRecovery.PathPredicateRecovery;
import lu.uni.tsopen.pathPredicateRecovery.SimpleBlockPredicateExtraction;
import lu.uni.tsopen.symbolicExecution.ContextualValues;
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.symbolicValues.BinOpValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.ConstantValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import lu.uni.tsopen.utils.Constants;
import lu.uni.tsopen.utils.Utils;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.AssignStmt;
import soot.jimple.ConditionExpr;
import soot.jimple.Constant;
import soot.jimple.DoubleConstant;
import soot.jimple.FloatConstant;
import soot.jimple.IfStmt;
import soot.jimple.IntConstant;
import soot.jimple.LongConstant;
import soot.jimple.NullConstant;
import soot.jimple.ReturnStmt;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public class PotentialLogicBombsRecovery implements Runnable {
private final SimpleBlockPredicateExtraction sbpe;
private final SymbolicExecution se;
private final PathPredicateRecovery ppr;
private Map<IfStmt, Pair<List<SymbolicValue>, SootMethod>> potentialLogicBombs;
private List<SootMethod> visitedMethods;
private List<IfStmt> visitedIfs;
private InfoflowCFG icfg;
private boolean containsSuspiciousCheck;
private boolean containsSuspiciousCheckAfterControlDependency;
private boolean containsSuspiciousCheckAfterPostFilterStep;
private SootMethod currentSensitiveMethod;
protected Logger logger = LoggerFactory.getLogger(this.getClass());
public PotentialLogicBombsRecovery(SimpleBlockPredicateExtraction sbpe, SymbolicExecution se, PathPredicateRecovery ppr, InfoflowCFG icfg) {
this.sbpe = sbpe;
this.se = se;
this.ppr = ppr;
this.visitedMethods = new ArrayList<SootMethod>();
this.visitedIfs = new ArrayList<IfStmt>();
this.potentialLogicBombs = new HashMap<IfStmt, Pair<List<SymbolicValue>, SootMethod>>();
this.icfg = icfg;
this.containsSuspiciousCheck = false;
this.containsSuspiciousCheckAfterControlDependency = false;
this.containsSuspiciousCheckAfterPostFilterStep = false;
this.currentSensitiveMethod = null;
}
@Override
public void run() {
this.retrievePotentialLogicBombs();
}
private void retrievePotentialLogicBombs() {
for(IfStmt ifStmt : this.sbpe.getConditions()) {
if(!this.isTrigger(ifStmt)) {
this.potentialLogicBombs.remove(ifStmt);
}
}
}
private boolean isTrigger(IfStmt ifStmt) {
this.visitedMethods.clear();
if(!this.isSuspicious(ifStmt)) {
return false;
}
this.containsSuspiciousCheck = true;
if(this.logger.isDebugEnabled()) {
this.logger.debug("Predicate is suspicious : {}", ifStmt);
}
if(!this.controlSensitiveAction(ifStmt)) {
return false;
}
this.containsSuspiciousCheckAfterControlDependency = true;
if(this.logger.isDebugEnabled()) {
this.logger.debug("Predicate is suspicious after post filters : {}", ifStmt);
}
if(this.isSuspiciousAfterPostFilters(ifStmt)) {
this.containsSuspiciousCheckAfterPostFilterStep = true;
return true;
}
if(this.logger.isDebugEnabled()) {
this.logger.debug("Predicate does not control sensitive action : {}", ifStmt);
}
return false;
}
private boolean isSuspiciousAfterPostFilters(IfStmt ifStmt) {
Septet<List<SymbolicValue>, List<SymbolicValue>, List<SymbolicValue>, Value, Value, Constant, Boolean> contextualValues = this.getContextualValues(ifStmt);
List<SymbolicValue> values = contextualValues.getValue0();
Constant constant = contextualValues.getValue5();
boolean isNullCheck = contextualValues.getValue6();
boolean isSuspicious = false;
if(values != null) {
for(SymbolicValue sv : values) {
if((sv.containsTag(Constants.SECONDS_TAG)
|| sv.containsTag(Constants.MINUTES_TAG)
|| sv.containsTag(Constants.MONTH_TAG)
|| sv.containsTag(Constants.HOUR_TAG)
|| sv.containsTag(Constants.YEAR_TAG)
|| sv.containsTag(Constants.LONGITUDE_TAG)
|| sv.containsTag(Constants.LATITUDE_TAG)
|| sv.containsTag(Constants.CURRENT_TIME_MILLIS)
|| sv.containsTag(Constants.NOW_TAG)
|| sv.containsTag(Constants.HERE_TAG)
|| sv.containsTag(Constants.SMS_TAG)
|| sv.containsTag(Constants.SMS_SENDER_TAG)
|| sv.containsTag(Constants.SMS_BODY_TAG)
|| sv.containsTag(Constants.SUSPICIOUS))
&& ((constant != null)
&& (constant instanceof IntConstant && ((IntConstant)constant).value == -1
|| (constant instanceof NullConstant)))
|| isNullCheck) {
continue;
}else if(!sv.hasTag()) {
continue;
}else {
isSuspicious = true;
if(!this.isInFilteredLib(ifStmt)) {
this.addPotentialLogicBomb(ifStmt, sv);
}
}
}
}
return isSuspicious;
}
private boolean isInFilteredLib(IfStmt ifStmt) {
SootClass cl = this.icfg.getMethodOf(ifStmt).getDeclaringClass();
if(Utils.isFilteredLib(cl)) {
return true;
}
return false;
}
private void addPotentialLogicBomb(IfStmt ifStmt, SymbolicValue sv) {
List<SymbolicValue> lbs = null;
Pair<List<SymbolicValue>, SootMethod> pair = this.potentialLogicBombs.get(ifStmt);
if(pair == null) {
lbs = new ArrayList<SymbolicValue>();
pair = new Pair<List<SymbolicValue>, SootMethod>(lbs, this.currentSensitiveMethod);
this.potentialLogicBombs.put(ifStmt, pair);
}
lbs = pair.getValue0();
lbs.add(sv);
}
private boolean controlSensitiveAction(IfStmt ifStmt) {
List<Unit> guardedBlocks = this.ppr.getGuardedBlocks(ifStmt);
if(this.isSensitive(guardedBlocks)) {
return true;
}
for(Unit block : guardedBlocks) {
for(ValueBox vb : block.getDefBoxes()) {
for(IfStmt i : this.getRelatedPredicates(vb.getValue())) {
if(ifStmt != i && !this.visitedIfs.contains(i)) {
this.visitedIfs.add(i);
if(this.controlSensitiveAction(i)) {
return true;
}
}
}
}
}
if(this.ifControlBoolReturn(ifStmt)) {
SootMethod methodOfIf = this.icfg.getMethodOf(ifStmt);
AssignStmt callerAssign = null;
Value leftOp = null;
for(Unit caller : this.icfg.getCallersOf(methodOfIf)) {
if(caller instanceof AssignStmt) {
callerAssign = (AssignStmt) caller;
leftOp = callerAssign.getLeftOp();
for(Unit u : this.icfg.getSuccsOf(callerAssign)) {
if(u instanceof IfStmt) {
for(ValueBox vb : u.getUseBoxes()) {
if(vb.getValue() == leftOp) {
guardedBlocks = this.ppr.getGuardedBlocks((IfStmt)u);
if(this.isSensitive(guardedBlocks)) {
return true;
}
}
}
}
}
}
}
}
return false;
}
private boolean ifControlBoolReturn(IfStmt ifStmt) {
ReturnStmt ret = null;
Value retOp = null;
IntConstant retCons = null;
boolean controlBoolReturn = false;
for(Unit u : this.icfg.getSuccsOf(ifStmt)) {
if(u instanceof ReturnStmt) {
ret = (ReturnStmt)u;
retOp = ret.getOp();
if(retOp instanceof IntConstant) {
retCons = (IntConstant) retOp;
if(retCons.value == 1 || retCons.value == 0) {
controlBoolReturn = true;
}else {
controlBoolReturn = false;
}
}
}
}
return controlBoolReturn;
}
private List<IfStmt> getRelatedPredicates(Value value) {
List<IfStmt> ifs = new ArrayList<IfStmt>();
for(IfStmt ifStmt : this.sbpe.getConditions()) {
for(ValueBox vb : ifStmt.getUseBoxes()) {
if(vb.getValue() == value) {
ifs.add(ifStmt);
}
}
}
return ifs;
}
private boolean isSensitive(Collection<Unit> guardedBlocks) {
Collection<Unit> units = null;
for(Unit block : guardedBlocks) {
for(SootMethod m : Utils.getInvokedMethods(block, this.icfg)) {
if(!this.visitedMethods.contains(m)) {
this.visitedMethods.add(m);
if(Utils.isSensitiveMethod(m)) {
this.currentSensitiveMethod = m;
return true;
}
if(m.getDeclaringClass().isApplicationClass() && m.isConcrete()) {
units = m.retrieveActiveBody().getUnits();
if(units != null) {
if(this.isSensitive(units)) {
return true;
}
}
}
}
}
}
return false;
}
private boolean isSuspicious(IfStmt ifStmt) {
Septet<List<SymbolicValue>, List<SymbolicValue>, List<SymbolicValue>, Value, Value, Constant, Boolean> contextualValues = this.getContextualValues(ifStmt);
List<SymbolicValue> values = contextualValues.getValue0(),
valuesOp1 = contextualValues.getValue1(),
valuesOp2 = contextualValues.getValue2();
Value op1 = contextualValues.getValue3(),
op2 = contextualValues.getValue4();
if(values != null) {
for(SymbolicValue sv : values) {
if(sv.containsTag(Constants.SECONDS_TAG)
|| sv.containsTag(Constants.MINUTES_TAG)
|| sv.containsTag(Constants.HOUR_TAG)
|| sv.containsTag(Constants.YEAR_TAG)
|| sv.containsTag(Constants.MONTH_TAG)
|| sv.containsTag(Constants.LONGITUDE_TAG)
|| sv.containsTag(Constants.LATITUDE_TAG)
|| sv.containsTag(Constants.CURRENT_TIME_MILLIS)
|| sv.containsTag(Constants.NOW_TAG)
|| sv.containsTag(Constants.SUSPICIOUS)) {
return true;
}
}
}
if(!(op1 instanceof Constant) && !(op2 instanceof Constant)) {
if(valuesOp1 != null) {
for(SymbolicValue sv1 : valuesOp1) {
if(sv1.containsTag(Constants.HERE_TAG)
|| sv1.containsTag(Constants.NOW_TAG)
|| sv1.containsTag(Constants.HOUR_TAG)
|| sv1.containsTag(Constants.YEAR_TAG)
|| sv1.containsTag(Constants.LATITUDE_TAG)
|| sv1.containsTag(Constants.LONGITUDE_TAG)
|| sv1.containsTag(Constants.MINUTES_TAG)
|| sv1.containsTag(Constants.SECONDS_TAG)
|| sv1.containsTag(Constants.MONTH_TAG)) {
return true;
}
}
}
if(valuesOp2 != null) {
for(SymbolicValue sv2 : valuesOp2) {
if(sv2.containsTag(Constants.HERE_TAG)
|| sv2.containsTag(Constants.HOUR_TAG)
|| sv2.containsTag(Constants.YEAR_TAG)
|| sv2.containsTag(Constants.NOW_TAG)
|| sv2.containsTag(Constants.LATITUDE_TAG)
|| sv2.containsTag(Constants.LONGITUDE_TAG)
|| sv2.containsTag(Constants.MINUTES_TAG)
|| sv2.containsTag(Constants.SECONDS_TAG)
|| sv2.containsTag(Constants.MONTH_TAG)) {
return true;
}
}
}
}
return false;
}
private Septet<List<SymbolicValue>, List<SymbolicValue>, List<SymbolicValue>, Value, Value, Constant, Boolean> getContextualValues(IfStmt ifStmt) {
ConditionExpr conditionExpr = (ConditionExpr) ifStmt.getCondition();
Value op1 = conditionExpr.getOp1(),
op2 = conditionExpr.getOp2();
ContextualValues contextualValuesOp1 = null,
contextualValuesOp2 = null;
List<SymbolicValue> valuesOp1 = null,
valuesOp2 = null,
values = null;
Constant constant = null;
boolean isNullCheck = false;
if(!(op1 instanceof Constant)) {
contextualValuesOp1 = this.se.getContextualValues(op1);
}
if(!(op2 instanceof Constant)) {
contextualValuesOp2 = this.se.getContextualValues(op2);
}
if(contextualValuesOp1 != null) {
valuesOp1 = contextualValuesOp1.getLastCoherentValues(ifStmt);
}
if(contextualValuesOp2 != null) {
valuesOp2 = contextualValuesOp2.getLastCoherentValues(ifStmt);
}
if(valuesOp1 != null) {
values = valuesOp1;
if(op2 instanceof Constant) {
constant = (Constant) op2;
}else if(this.containConstantSymbolicValue(op2)) {
constant = this.getConstantValue(op2);
}
isNullCheck = this.isNullCheck(valuesOp1);
}else if (valuesOp2 != null) {
values = valuesOp2;
if(op1 instanceof Constant) {
constant = (Constant) op1;
}else if(this.containConstantSymbolicValue(op1)) {
constant = this.getConstantValue(op1);
}
isNullCheck = this.isNullCheck(valuesOp2);
}
return new Septet<List<SymbolicValue>, List<SymbolicValue>, List<SymbolicValue>, Value, Value, Constant, Boolean>(values, valuesOp1, valuesOp2, op1, op2, constant, isNullCheck);
}
private boolean isNullCheck(List<SymbolicValue> values) {
BinOpValue binOpValue = null;
Value binOpValueOp = null;
for(SymbolicValue sv : values) {
if(sv instanceof BinOpValue) {
binOpValue = (BinOpValue) sv;
binOpValueOp = binOpValue.getOp2();
if(binOpValueOp instanceof FloatConstant) {
if(((FloatConstant)binOpValueOp).value == 0 || ((FloatConstant)binOpValueOp).value == -1) {
return true;
}
}else if(binOpValueOp instanceof IntConstant) {
if(((IntConstant)binOpValueOp).value == 0 || ((IntConstant)binOpValueOp).value == -1) {
return true;
}
}else if(binOpValueOp instanceof DoubleConstant) {
if(((DoubleConstant)binOpValueOp).value == 0 || ((DoubleConstant)binOpValueOp).value == -1) {
return true;
}
}else if(binOpValueOp instanceof LongConstant) {
if(((LongConstant)binOpValueOp).value == 0 || ((LongConstant)binOpValueOp).value == -1) {
return true;
}
}
}
}
return false;
}
private boolean containConstantSymbolicValue(Value v) {
List<SymbolicValue> values = null;
ContextualValues contextualValues = null;
if(v != null) {
contextualValues = this.se.getContext().get(v);
if(contextualValues != null) {
values = contextualValues.getAllValues();
if(values != null) {
for(SymbolicValue sv: values) {
if(sv instanceof ConstantValue) {
return true;
}
}
}
}
}
return false;
}
private Constant getConstantValue(Value v) {
List<SymbolicValue> values = null;
ContextualValues contextualValues = null;
ConstantValue cv = null;
Constant c = null;
if(v != null) {
contextualValues = this.se.getContext().get(v);
if(contextualValues != null) {
values = contextualValues.getAllValues();
if(values != null) {
for(SymbolicValue sv: values) {
if(sv instanceof ConstantValue) {
cv = (ConstantValue)sv;
c = cv.getConstant();
if(c instanceof IntConstant) {
return IntConstant.v(((IntConstant) c).value);
}
}
}
}
}
}
return null;
}
public Map<IfStmt, Pair<List<SymbolicValue>, SootMethod>> getPotentialLogicBombs(){
return this.potentialLogicBombs;
}
public boolean hasPotentialLogicBombs() {
return !this.potentialLogicBombs.isEmpty();
}
public boolean ContainsSuspiciousCheck() {
return this.containsSuspiciousCheck;
}
public boolean ContainsSuspiciousCheckAfterControlDependency() {
return this.containsSuspiciousCheckAfterControlDependency;
}
public boolean ContainsSuspiciousCheckAfterPostFilterStep() {
return this.containsSuspiciousCheckAfterPostFilterStep;
}
}
| 16,001 | 31.197183 | 179 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/graphTraversal/ICFGTraversal.java | package lu.uni.tsopen.graphTraversal;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lu.uni.tsopen.utils.Constants;
import lu.uni.tsopen.utils.Utils;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.DefinitionStmt;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
/**
* Base class to traverse the ICFG backward or forward.
* Implementing class would actually do the job on nodes.
* @author Jordan Samhi
*
*/
public abstract class ICFGTraversal implements Runnable{
protected final String nameOfAnalysis;
protected final InfoflowCFG icfg;
private List<SootMethod> visitedMethods;
private LinkedList<SootMethod> methodWorkList;
private Map<Unit, String> visitedNodes;
private LinkedList<Unit> currentPath;
protected Logger logger = LoggerFactory.getLogger(this.getClass());
public ICFGTraversal(InfoflowCFG icfg, String nameOfAnalysis, SootMethod mainMethod) {
this.nameOfAnalysis = nameOfAnalysis;
this.icfg = icfg;
this.visitedMethods = new LinkedList<SootMethod>();
this.methodWorkList = new LinkedList<SootMethod>();
this.visitedNodes = new HashMap<Unit, String>();
this.currentPath = new LinkedList<Unit>();
this.methodWorkList.add(mainMethod);
}
@Override
public void run() {
this.traverse();
}
/**
* Begin the traversal of the ICFG as long as
* the method work-list is not empty.
*/
public void traverse() {
SootMethod methodToAnalyze = null;
Collection<Unit> extremities = null;
while(!this.methodWorkList.isEmpty()) {
methodToAnalyze = this.methodWorkList.removeFirst();
this.visitedMethods.add(methodToAnalyze);
extremities = this.getExtremities(methodToAnalyze);
for(Unit extremity : extremities) {
this.traverseNode(extremity);
}
}
}
/**
* Propagate analysis on neighbors node and propagate
* discovered unvisited methods.
* @param node the basic block to process during analysis
*/
private void traverseNode(Unit node) {
DefinitionStmt defUnit = null;
if(this.checkNodeColor(node)) {
this.currentPath.add(node);
if(node instanceof InvokeStmt) {
this.propagateTargetMethod(node);
}else if(node instanceof DefinitionStmt) {
defUnit = (DefinitionStmt) node;
if(defUnit.getRightOp() instanceof InvokeExpr) {
this.propagateTargetMethod(defUnit);
}
}
this.processNodeBeforeNeighbors(node);
for(Unit neighbour : this.getNeighbors(node)) {
this.traverseNode(neighbour);
this.processNeighbor(node, neighbour);
}
this.currentPath.removeLast();
this.processNodeAfterNeighbors(node);
}
}
private boolean checkNodeColor(Unit node) {
String nodeColor = this.visitedNodes.get(node);
if(nodeColor == null) {
nodeColor = Constants.WHITE;
this.visitedNodes.put(node, nodeColor);
}
if(nodeColor != Constants.BLACK) {
if(nodeColor.equals(Constants.WHITE)) {
nodeColor = Constants.GREY;
}else if(nodeColor.equals(Constants.GREY)) {
nodeColor = Constants.BLACK;
}
this.visitedNodes.put(node, nodeColor);
return true;
}
return false;
}
/**
* Propagate the analysis on the points-to set
* of the invocation if methods have not yet been visited.
* Note that only methods of application classes are propagated.
* @param invocation the basic block representing a method invocation
*/
private void propagateTargetMethod(Unit invocation) {
Collection<SootMethod> pointsTo = Utils.getInvokedMethods(invocation, this.icfg);
for(SootMethod callee : pointsTo) {
if(callee.getDeclaringClass().isApplicationClass()) {
if(!this.visitedMethods.contains(callee)) {
this.methodWorkList.add(callee);
}
}
}
}
public void addMethodToWorkList(SootMethod m) {
if(!this.methodWorkList.contains(m)) {
this.methodWorkList.add(m);
}else {
while(this.methodWorkList.contains(m)) {
this.methodWorkList.remove(m);
}
this.methodWorkList.add(m);
}
}
public boolean isMethodVisited(SootMethod m) {
return this.visitedMethods.contains(m);
}
public LinkedList<Unit> getCurrentPath() {
return this.currentPath;
}
/**
* Implementation depending on the kind of analysis
* @param node the current node being analyzed
*/
protected abstract void processNodeAfterNeighbors(Unit node);
/**
* Implementation depending on the kind of analysis
* @param node the current node being analyzed
*/
protected abstract void processNodeBeforeNeighbors(Unit node);
/**
* Implementation depending on the kind of analysis.
* @param node the current node being analyzed
* @param neighbour the current neighbor of the node
*/
protected abstract void processNeighbor(Unit node, Unit neighbour);
/**
* Returns predecessors or successors of the node depending
* on the kind of analysis (forward or backward)
* @param node
* @return a list of nodes
*/
protected abstract List<Unit> getNeighbors(Unit node);
/**
* Return start-points or end-points depending on
* the kind of analysis (forward or backward)
* @param m
* @return a list of nodes
*/
protected abstract Collection<Unit> getExtremities(SootMethod m);
} | 6,333 | 29.161905 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/graphTraversal/ICFGForwardTraversal.java | package lu.uni.tsopen.graphTraversal;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.List;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
/**
* Implementation of the forward ICFG traversal
* @author Jordan Samhi
*
*/
public abstract class ICFGForwardTraversal extends ICFGTraversal {
public ICFGForwardTraversal(InfoflowCFG icfg, String nameOfAnalysis, SootMethod mainMethod) {
super(icfg, nameOfAnalysis, mainMethod);
}
@Override
public List<Unit> getNeighbors(Unit u) {
return this.icfg.getSuccsOf(u);
}
@Override
public Collection<Unit> getExtremities(SootMethod m) {
return this.icfg.getStartPointsOf(m);
}
}
| 1,733 | 27.9 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/graphTraversal/ICFGBackwardTraversal.java | package lu.uni.tsopen.graphTraversal;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.List;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
/**
* Implementation of the backward ICFG traversal
* @author Jordan Samhi
*
*/
public abstract class ICFGBackwardTraversal extends ICFGTraversal {
public ICFGBackwardTraversal(InfoflowCFG icfg, String nameOfAnalysis, SootMethod mainMethod) {
super(icfg, nameOfAnalysis, mainMethod);
}
@Override
public List<Unit> getNeighbors(Unit u) {
return this.icfg.getPredsOf(u);
}
@Override
public Collection<Unit> getExtremities(SootMethod m) {
return this.icfg.getEndPointsOf(m);
}
}
| 1,734 | 27.916667 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/pathPredicateRecovery/PathPredicateRecovery.java | package lu.uni.tsopen.pathPredicateRecovery;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.logicng.formulas.Formula;
import org.logicng.formulas.FormulaFactory;
import org.logicng.formulas.Literal;
import org.logicng.transformations.DistributiveSimplifier;
import lu.uni.tsopen.graphTraversal.ICFGBackwardTraversal;
import lu.uni.tsopen.utils.Edge;
import lu.uni.tsopen.utils.Utils;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.IfStmt;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public class PathPredicateRecovery extends ICFGBackwardTraversal {
private final SimpleBlockPredicateExtraction sbpe;
private Map<Unit, List<Formula>> nodeToPathPredicates;
private Map<Unit, Formula> nodeToFullPathPredicate;
private final FormulaFactory formulaFactory;
private final DistributiveSimplifier simplifier;
private final boolean handleExceptions;
private Map<IfStmt, List<Unit>> guardedBlocks;
public PathPredicateRecovery(InfoflowCFG icfg, SimpleBlockPredicateExtraction sbpe, SootMethod mainMethod, boolean handleExceptions) {
super(icfg, "Path Predicate Recovery", mainMethod);
this.sbpe = sbpe;
this.nodeToPathPredicates = new HashMap<Unit, List<Formula>>();
this.nodeToFullPathPredicate = new HashMap<Unit, Formula>();
this.formulaFactory = new FormulaFactory();
this.simplifier = new DistributiveSimplifier();
this.handleExceptions = handleExceptions;
this.guardedBlocks = new HashMap<IfStmt, List<Unit>>();
}
private void annotateNodeWithPathPredicate(Unit node, Unit neighbour) {
Edge edge = this.sbpe.getAnnotatedEdge(neighbour, node);
Formula currentPathPredicate = null,
neighborPathPredicate = this.nodeToFullPathPredicate.get(neighbour);
List<Formula> nodePredicates = this.nodeToPathPredicates.get(node);
if(edge != null) {
if(neighborPathPredicate != null) {
currentPathPredicate = this.formulaFactory.and(edge.getPredicate(), neighborPathPredicate);
}else {
currentPathPredicate = edge.getPredicate();
}
}else {
currentPathPredicate = neighborPathPredicate;
}
if(currentPathPredicate != null) {
if(nodePredicates == null) {
nodePredicates = new ArrayList<Formula>();
this.nodeToPathPredicates.put(node, nodePredicates);
}
nodePredicates.add(currentPathPredicate);
}
}
public Formula getNodeFullPath(Unit node) {
if(this.nodeToFullPathPredicate.containsKey(node)) {
return this.nodeToFullPathPredicate.get(node);
}
return null;
}
public int getSizeOfFullPath(Unit node) {
Formula formula = this.getNodeFullPath(node);
int size = 1;
if(formula == null) {
return size;
}
size = formula.literals().size();
if(size == 0) {
return 1;
}
return size;
}
@Override
protected void processNeighbor(Unit node, Unit neighbour) {
if(this.handleExceptions || !Utils.isCaughtException(node)) {
this.annotateNodeWithPathPredicate(node, neighbour);
}
}
/**
* Merge path predicates with logical OR and simplify the formula
*/
@Override
protected void processNodeAfterNeighbors(Unit node) {
List<Formula> nodePredicates = this.nodeToPathPredicates.get(node);
Formula simplifiedPredicate = null,
or = null;
if(nodePredicates != null) {
or = this.formulaFactory.or(nodePredicates);
simplifiedPredicate = this.simplifier.apply(or, true);
this.nodeToFullPathPredicate.put(node, simplifiedPredicate);
this.computeGuardedBlocks(node);
}
}
private void computeGuardedBlocks(Unit node) {
Formula fullPath = this.getNodeFullPath(node);
IfStmt ifStmt = null;
List<Unit> blocks = null;
if(fullPath != null) {
for(Literal lit : fullPath.literals()) {
ifStmt = this.sbpe.getCondtionFromLiteral(lit);
blocks = this.guardedBlocks.get(ifStmt);
if(ifStmt != null) {
if(blocks == null) {
blocks = new ArrayList<Unit>();
this.guardedBlocks.put(ifStmt, blocks);
}
if(!blocks.contains(node)) {
blocks.add(node);
}
}
}
}
}
public List<Unit> getGuardedBlocks(IfStmt ifStmt){
if(this.guardedBlocks.containsKey(ifStmt)) {
return this.guardedBlocks.get(ifStmt);
}
return Collections.emptyList();
}
@Override
protected void processNodeBeforeNeighbors(Unit node) {}
}
| 5,354 | 30.875 | 135 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/pathPredicateRecovery/SimpleBlockPredicateExtraction.java | package lu.uni.tsopen.pathPredicateRecovery;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.logicng.formulas.FormulaFactory;
import org.logicng.formulas.Literal;
import lu.uni.tsopen.graphTraversal.ICFGForwardTraversal;
import lu.uni.tsopen.utils.Edge;
import lu.uni.tsopen.utils.Utils;
import soot.Local;
import soot.RefLikeType;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.IfStmt;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
/**
* This class extract the simple block predicates for the
* future full path predicate recovery
* @author Jordan Samhi
*
*/
public class SimpleBlockPredicateExtraction extends ICFGForwardTraversal {
private Map<Literal, IfStmt> literalToCondition = null;
private List<IfStmt> conditions;
private List<Edge> annotatedEdges;
private final FormulaFactory formulaFactory;
private List<IfStmt> visitedIfs;
private Map<SootMethod, Integer> countOfIfByMethod;
private List<SootMethod> visitedMethods;
private int countOfObject;
private int maxIf;
public SimpleBlockPredicateExtraction(InfoflowCFG icfg, SootMethod mainMethod) {
super(icfg, "Simple Block Predicate Extraction", mainMethod);
this.literalToCondition = new HashMap<Literal, IfStmt>();
this.annotatedEdges = new ArrayList<Edge>();
this.formulaFactory = new FormulaFactory();
this.conditions = new ArrayList<IfStmt>();
this.visitedIfs = new ArrayList<IfStmt>();
this.countOfIfByMethod = new HashMap<SootMethod, Integer>();
this.visitedMethods = new ArrayList<SootMethod>();
this.countOfObject = 0;
this.maxIf = 0;
}
/**
* Annotate simple predicates on condition's edges
* @param node the current node being traversed
* @param successor one of the successor of the current node
*/
private void annotateEdgeWithSimplePredicate(Unit node, Unit successor) {
IfStmt ifStmt = null;
String condition = null;
Edge edge = null;
Literal simplePredicate = null;
SootMethod method = this.icfg.getMethodOf(node);
Integer countOfIfByMethod = null;
if(!Utils.isCaughtException(successor)) {
if(node instanceof IfStmt && !Utils.isDummy(this.icfg.getMethodOf(node))) {
edge = new Edge(node, successor);
this.annotatedEdges.add(edge);
ifStmt = (IfStmt) node;
condition = String.format("([%s] => %s)", ifStmt.hashCode(), ifStmt.getCondition().toString());
if(successor == ifStmt.getTarget()) {
simplePredicate = this.formulaFactory.literal(condition, true);
}else {
simplePredicate = this.formulaFactory.literal(condition, false);
}
this.literalToCondition.put(simplePredicate, ifStmt);
if(!this.conditions.contains(ifStmt)) {
this.conditions.add(ifStmt);
}
edge.setPredicate(simplePredicate);
if(!this.visitedIfs.contains(ifStmt)) {
this.visitedIfs.add(ifStmt);
countOfIfByMethod = this.countOfIfByMethod.get(method);
if(countOfIfByMethod == null) {
this.countOfIfByMethod.put(method, 1);
}else {
countOfIfByMethod += 1;
this.countOfIfByMethod.put(method, countOfIfByMethod);
if (countOfIfByMethod > this.maxIf) {
this.maxIf = countOfIfByMethod;
}
}
}
}
if(!this.visitedMethods.contains(method)) {
this.visitedMethods.add(method);
for(Local l : method.retrieveActiveBody().getLocals()) {
if(l.getType() instanceof RefLikeType) {
this.countOfObject += 1;
}
}
}
}
}
/**
* Return the edge corresponding to the units in
* the given order
* @param source the source node of the edge
* @param target the target node of the edge
* @return the edge corresponding to the nodes
*/
public Edge getAnnotatedEdge(Unit source, Unit target) {
for(Edge edge : this.annotatedEdges) {
if(edge.correspondsTo(source, target)) {
return edge;
}
}
return null;
}
public IfStmt getCondtionFromLiteral(Literal l) {
if(this.literalToCondition.containsKey(l)) {
return this.literalToCondition.get(l);
}
return null;
}
public List<IfStmt> getConditions(){
return this.conditions;
}
public int getIfCount() {
return this.visitedIfs.size();
}
public int getIfDepthInMethods() {
return this.maxIf;
}
@Override
protected void processNeighbor(Unit node, Unit neighbour) {
this.annotateEdgeWithSimplePredicate(node, neighbour);
}
@Override
protected void processNodeAfterNeighbors(Unit node) {}
@Override
protected void processNodeBeforeNeighbors(Unit node) {}
public int getCountOfObject() {
return this.countOfObject;
}
}
| 5,609 | 29.48913 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/utils/Constants.java | package lu.uni.tsopen.utils;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public class Constants {
/**
* Methods
*/
public static final String GET_INSTANCE = "getInstance";
public static final String GET = "get";
public static final String NOW = "now";
public static final String GET_LAST_KNOW_LOCATION = "getLastKnownLocation";
public static final String GET_LAST_LOCATION = "getLastLocation";
public static final String CREATE_FROM_PDU = "createFromPdu";
public static final String GET_LONGITUDE = "getLongitude";
public static final String GET_LATITUDE = "getLatitude";
public static final String CURRENT_TIME_MILLIS = "currentTimeMillis";
public static final String SET_TO_NOW = "setToNow";
public static final String GET_MINUTES = "getMinutes";
public static final String GET_SECONDS = "getSeconds";
public static final String GET_HOURS = "getHours";
public static final String GET_YEAR = "getYear";
public static final String GET_MONTH = "getMonth";
public static final String APPEND = "append";
public static final String VALUEOF = "valueOf";
public static final String SUBSTRING = "substring";
public static final String TOSTRING = "toString";
public static final String GET_MESSAGE_BODY = "getMessageBody";
public static final String GET_DISPLAY_MESSAGE_BODY = "getDisplayMessageBody";
public static final String GET_ORIGINATING_ADDRESS = "getOriginatingAddress";
public static final String GET_DISPLAY_ORIGINATING_ADDRESS = "getDisplayOriginatingAddress";
public static final String AFTER = "after";
public static final String BEFORE = "before";
public static final String EQUALS = "equals";
public static final String CONTAINS = "contains";
public static final String STARTS_WITH = "startsWith";
public static final String ENDS_WITH = "endsWith";
public static final String MATCHES = "matches";
public static final String FORMAT = "format";
public static final String TO_LOWER_CASE = "toLowerCase";
public static final String TO_UPPER_CASE = "toUpperCase";
public static final String ON_LOCATION_CHANGED = "onLocationChanged";
public static final String DISTANCE_BETWEEN = "distanceBetween";
/**
* Tags
*/
public static final String NOW_TAG = "#now";
public static final String HERE_TAG = "#here";
public static final String SMS_TAG = "#sms";
public static final String LONGITUDE_TAG = "#here/#longitude";
public static final String LATITUDE_TAG = "#here/#latitude";
public static final String SECONDS_TAG = "#now/#seconds";
public static final String MINUTES_TAG = "#now/#minutes";
public static final String HOUR_TAG = "#now/#hour";
public static final String YEAR_TAG = "#now/#year";
public static final String MONTH_TAG = "#now/#month";
public static final String SMS_BODY_TAG = "#sms/#body";
public static final String SMS_SENDER_TAG = "#sms/#sender";
public static final String SUSPICIOUS = "#Suspicious";
/**
* Classes, types
*/
public static final String JAVA_UTIL_CALENDAR = "java.util.Calendar";
public static final String JAVA_TEXT_SIMPLE_DATE_FORMAT = "java.text.SimpleDateFormat";
public static final String JAVA_UTIL_DATE = "java.util.Date";
public static final String JAVA_UTIL_GREGORIAN_CALENDAR = "java.util.GregorianCalendar";
public static final String JAVA_TIME_LOCAL_DATE_TIME = "java.time.LocalDateTime";
public static final String JAVA_TIME_LOCAL_DATE = "java.time.LocalDate";
public static final String ANDROID_TEXT_FORMAT_TIME = "android.text.format.Time";
public static final String JAVA_LANG_STRING = "java.lang.String";
public static final String JAVA_LANG_STRING_BUILDER = "java.lang.StringBuilder";
public static final String JAVA_LANG_STRING_BUFFER = "java.lang.StringBuffer";
public static final String ANDROID_LOCATION_LOCATION = "android.location.Location";
public static final String ANDROID_LOCATION_LOCATION_MANAGER = "android.location.LocationManager";
public static final String COM_GOOGLE_ANDROID_GMS_LOCATION_LOCATION_RESULT = "com.google.android.gms.location.LocationResult";
public static final String ANDROID_TELEPHONY_SMSMESSAGE = "android.telephony.SmsMessage";
public static final String JAVA_LANG_SYSTEM = "java.lang.System";
public static final String INT = "int";
public static final String LONG = "long";
public static final String DOUBLE = "double";
public static final String FLOAT_ARRAY = "float[]";
public static final String FLOAT = "float";
public static final String BOOLEAN = "boolean";
public static final String BYTE = "byte";
public static final String ANDROID_LOCATION_LOCATION_LISTENER = "android.location.LocationListener";
public static final String ANDROID_APP_ACTIVITY = "android.app.Activity";
public static final String ANDROID_CONTENT_BROADCASTRECEIVER = "android.content.BroadcastReceiver";
public static final String ANDROID_APP_SERVICE = "android.app.Service";
public static final String ANDROID_CONTENT_CONTENTPROVIDER = "android.content.ContentProvider";
/**
* Files
*/
public static final String SENSITIVE_METHODS_FILE = "/sensitiveMethods.pscout";
public static final String FILTERED_LIBS = "/filteredLibs.txt";
public static final String CLASSES_DEX = "classes.dex";
/**
* Misc
*/
public static final String SUBSTRACTION = "-";
public static final String ADDITION = "+";
public static final String MULTIPLICATION = "x";
public static final String DIVISION = "/";
public static final String MODULO = "%";
public static final String WHITE = "white";
public static final String GREY = "grey";
public static final String UNKNOWN_VALUE = "{#}";
public static final String BLACK = "black";
public static final String UNKNOWN_STRING = "UNKNOWN_STRING";
public static final String EMPTY_STRING = "";
public static final String NULL = "null";
public static final String FILE_LOGIC_BOMBS_DELIMITER = "%";
public static final String BROADCAST_RECEIVER = "BroadcastReceiver";
public static final String ACTIVITY = "Activity";
public static final String CONTENT_PROVIDER = "ContentProvider";
public static final String SERVICE = "Service";
public static final String BASIC_CLASS = "BasicClass";
}
| 7,105 | 46.691275 | 127 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/utils/Edge.java | package lu.uni.tsopen.utils;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import org.logicng.formulas.Formula;
import soot.Unit;
/**
* This class represents an edge between two unit in a CFG/ICFG.
* It can be annotated with a predicate.
* @author Jordan Samhi
*
*/
public class Edge {
private final Unit source;
private final Unit target;
private Formula predicate;
public Edge(Unit s, Unit t) {
this.source = s;
this.target = t;
this.predicate = null;
}
public Unit getSource() {
return source;
}
public Unit getTarget() {
return target;
}
public Formula getPredicate() {
return predicate;
}
public void setPredicate(Formula predicate) {
this.predicate = predicate;
}
public boolean correspondsTo(Unit source, Unit target) {
return source == this.source && target == this.target;
}
@Override
public String toString() {
return String.format("(%s) -> (%s)", this.source, this.target);
}
}
| 1,947 | 23.658228 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/utils/TimeOut.java | package lu.uni.tsopen.utils;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lu.uni.tsopen.Analysis;
public class TimeOut {
private Timer timer;
private TimerTask exitTask = null;
private int timeout;
protected Logger logger = LoggerFactory.getLogger(this.getClass());
public TimeOut(int n, Analysis analysis) {
this.timer = new Timer();
this.exitTask = new TimerTask() {
@Override
public void run() {
TimeOut.this.logger.warn("Timeout reached !");
TimeOut.this.logger.warn("Ending program...");
analysis.timeoutReachedPrintResults();
System.exit(0);
}
};
this.timeout = n != 0 ? n : 60;
}
public void trigger() {
Calendar c = Calendar.getInstance();
c.add(Calendar.MINUTE, this.timeout);
this.timer.schedule(this.exitTask, c.getTime());
}
public void cancel() {
this.timer.cancel();
}
public int getTimeout() {
return this.timeout;
}
}
| 2,047 | 25.597403 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/utils/Utils.java | package lu.uni.tsopen.utils;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import org.javatuples.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import lu.uni.tsopen.logicBombs.PotentialLogicBombsRecovery;
import lu.uni.tsopen.pathPredicateRecovery.PathPredicateRecovery;
import lu.uni.tsopen.symbolicExecution.ContextualValues;
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import soot.FastHierarchy;
import soot.MethodOrMethodContext;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.DefinitionStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
import soot.jimple.internal.IdentityRefBox;
import soot.jimple.toolkits.callgraph.Edge;
import soot.tagkit.StringConstantValueTag;
import soot.toolkits.graph.DominatorTree;
import soot.toolkits.graph.MHGDominatorsFinder;
public class Utils {
protected static Logger logger = LoggerFactory.getLogger(Utils.class);
/**
* Check whether the unit is catching
* an exception, useful for predicate recovery.
* @param u the unit to check
* @return true if u catches an exception, false otherwise
*/
public static boolean isCaughtException(Unit u) {
for(ValueBox useBox : u.getUseBoxes()) {
if(useBox instanceof IdentityRefBox) {
if(((IdentityRefBox) useBox).getValue() instanceof CaughtExceptionRef) {
return true;
}
}
}
return false;
}
public static boolean containsTag(Value v, String tag, SymbolicExecution se) {
List<SymbolicValue> values = getSymbolicValues(v, se);
if(values != null) {
for(SymbolicValue sv : values) {
if(sv.containsTag(tag)) {
return true;
}
}
}
return false;
}
public static boolean containsTags(Value v, SymbolicExecution se) {
List<SymbolicValue> values = getSymbolicValues(v, se);
if(values != null) {
for(SymbolicValue sv : values) {
if(sv.hasTag()) {
return true;
}
}
}
return false;
}
public static void propagateTags(Value src, SymbolicValue dst, SymbolicExecution se) {
List<SymbolicValue> values = getSymbolicValues(src, se);
if(values != null) {
for(SymbolicValue sv : values) {
if(sv != null) {
if(sv.hasTag()) {
for(StringConstantValueTag t : sv.getTags()) {
if(!dst.containsTag(t.getStringValue())) {
dst.addTag(new StringConstantValueTag(t.getStringValue()));
}
}
}
}
}
}
}
private static List<SymbolicValue> getSymbolicValues(Value v, SymbolicExecution se) {
List<SymbolicValue> values = null;
ContextualValues contextualValues = null;
if(v != null) {
contextualValues = se.getContext().get(v);
if(contextualValues == null && v instanceof InstanceFieldRef) {
for(Entry<Value, ContextualValues> e : se.getContext().entrySet()) {
if(e.getKey().toString().contains(v.toString())) {
contextualValues = se.getContext().get(e.getKey());
}
}
}
if(contextualValues != null) {
values = contextualValues.getAllValues();
if(values == null) {
values = contextualValues.getAllValues();
}
}
}
return values;
}
public static String getFormattedTime(long time) {
long millis = TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS),
seconds = 0,
minutes = 0,
hours = 0;
String strTime = "";
if(millis >= 1000) {
seconds = millis / 1000;
if(seconds >= 60) {
minutes = seconds / 60;
if(minutes >=60) {
hours = minutes / 60;
strTime += String.format("%3s %s", hours, hours > 1 ? "hours" : "hour");
}else {
strTime += String.format("%3s %s", minutes, minutes > 1 ? "mins" : "min");
}
}else {
strTime += String.format("%3s %s", seconds, "s");
}
}else {
strTime += String.format("%3s %s", millis, "ms");
}
return strTime;
}
public static Collection<SootMethod> getInvokedMethods(Unit block, InfoflowCFG icfg) {
FastHierarchy fh = Scene.v().getOrMakeFastHierarchy();
Collection<SootClass> classes = null;
Collection<SootMethod> methods = new ArrayList<SootMethod>();
SootMethod method = null;
DefinitionStmt defUnit = null;
Value value = null;
if(block instanceof InvokeStmt) {
methods.addAll(icfg.getCalleesOfCallAt(block));
}else if(block instanceof DefinitionStmt) {
defUnit = (DefinitionStmt) block;
if(defUnit.getRightOp() instanceof InvokeExpr) {
methods.addAll(icfg.getCalleesOfCallAt(defUnit));
}
}
if(methods.isEmpty()) {
for(ValueBox v : block.getUseAndDefBoxes()) {
value = v.getValue();
if(value instanceof InvokeExpr) {
method = ((InvokeExpr)value).getMethod();
if(method.isAbstract()) {
classes = fh.getSubclassesOf(method.getDeclaringClass());
for(SootClass c : classes) {
for(SootMethod m : c.getMethods()) {
if(m.getSubSignature().equals(method.getSubSignature())) {
if(!methods.contains(m)) {
methods.add(m);
}
}
}
}
}else {
methods.add(method);
}
}
}
}
return methods;
}
public static boolean isDummy(SootMethod m) {
return m.getName().startsWith("dummyMainMethod");
}
private static List<SootClass> getAllSuperClasses(SootClass sootClass) {
List<SootClass> classes = new ArrayList<SootClass>();
if (sootClass.hasSuperclass()) {
classes.add(sootClass.getSuperclass());
classes.addAll(getAllSuperClasses(sootClass.getSuperclass()));
}
return classes;
}
public static String getComponentType(SootClass sc) {
List<SootClass> classes = getAllSuperClasses(sc);
for(SootClass c : classes) {
switch (c.getName()) {
case Constants.ANDROID_APP_ACTIVITY : return Constants.ACTIVITY;
case Constants.ANDROID_CONTENT_BROADCASTRECEIVER : return Constants.BROADCAST_RECEIVER;
case Constants.ANDROID_CONTENT_CONTENTPROVIDER : return Constants.CONTENT_PROVIDER;
case Constants.ANDROID_APP_SERVICE : return Constants.SERVICE;
}
}
return Constants.BASIC_CLASS;
}
public static boolean isInCallGraph(SootMethod m) {
MethodOrMethodContext next = null;
Iterator<MethodOrMethodContext> itMethod = Scene.v().getCallGraph().sourceMethods();
Iterator<soot.jimple.toolkits.callgraph.Edge> itEdge = null;
soot.jimple.toolkits.callgraph.Edge e = null;
while(itMethod.hasNext()){
next = itMethod.next();
itEdge = Scene.v().getCallGraph().edgesOutOf(next);
while(itEdge.hasNext()) {
e = itEdge.next();
if(e.tgt().equals(m)) {
return true;
}
}
}
return false;
}
public static int getGuardedBlocksDensity(PathPredicateRecovery ppr, IfStmt ifStmt) {
return ppr.getGuardedBlocks(ifStmt).size();
}
public static boolean guardedBlocksContainApplicationInvoke(PathPredicateRecovery ppr, IfStmt ifStmt) {
SootMethod m = null;
for(Unit u : ppr.getGuardedBlocks(ifStmt)) {
if(u instanceof InvokeStmt) {
m = ((InvokeStmt) u).getInvokeExpr().getMethod();
if(m.getDeclaringClass().isApplicationClass()) {
return true;
}
}
}
return false;
}
public static <T> String join(String sep, List<T> list) {
String s = "(";
for(int i = 0 ; i < list.size() ; i++) {
s += list.get(i).toString();
if(i != list.size()-1) {
s += sep;
}
}
s += ")";
return s;
}
public static String getStartingComponent(SootMethod method) {
return Utils.getComponentType(Scene.v().getSootClass(Lists.reverse(getLogicBombCallStack(method)).get(1).getReturnType().toString()));
}
public static List<SootMethod> getLogicBombCallStack(SootMethod m){
Iterator<Edge> it = Scene.v().getCallGraph().edgesInto(m);
Edge next = null;
List<SootMethod> methods = new LinkedList<SootMethod>();
methods.add(m);
while(it.hasNext()) {
next = it.next();
methods.addAll(getLogicBombCallStack(next.src()));
return methods;
}
return methods;
}
public static List<Integer> getLengthLogicBombCallStack(SootMethod m, Integer c, List<Integer> l, List<SootMethod> visitedMethods) {
Iterator<Edge> it = Scene.v().getCallGraph().edgesInto(m);
Edge next = null;
visitedMethods.add(m);
if(!it.hasNext()) {
l.add(c.intValue());
}
while(it.hasNext()) {
next = it.next();
if(visitedMethods.contains(next.src())){
continue;
}
c += 1;
getLengthLogicBombCallStack(next.src(), c, l, visitedMethods);
visitedMethods.remove(m);
c -= 1;
}
return l;
}
public static List<Integer> getLengthLogicBombCallStack(SootMethod m) {
return getLengthLogicBombCallStack(m, 0, new ArrayList<Integer>(), new ArrayList<SootMethod>());
}
public static boolean isSensitiveMethod(SootMethod m) {
InputStream fis = null;
BufferedReader br = null;
String line = null;
try {
fis = Utils.class.getResourceAsStream(Constants.SENSITIVE_METHODS_FILE);
br = new BufferedReader(new InputStreamReader(fis));
while ((line = br.readLine()) != null) {
if(m.getSignature().equals(line)) {
br.close();
fis.close();
return true;
}
}
} catch (IOException e) {
logger.error(e.getMessage());
}
try {
br.close();
fis.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
return false;
}
public static boolean isNested(IfStmt ifStmt, InfoflowCFG icfg, PotentialLogicBombsRecovery plbr, PathPredicateRecovery ppr) {
Map<IfStmt, Pair<List<SymbolicValue>, SootMethod>> plbs = plbr.getPotentialLogicBombs();
IfStmt currentIf = null;
SootMethod method1 = icfg.getMethodOf(ifStmt),
method2 = null;
MHGDominatorsFinder<Unit> df = new MHGDominatorsFinder<Unit>(icfg.getOrCreateUnitGraph(method1));
DominatorTree<Unit> dt = new DominatorTree<Unit>(df);
for(Entry<IfStmt, Pair<List<SymbolicValue>, SootMethod>> e : plbs.entrySet()) {
currentIf = e.getKey();
method2 = icfg.getMethodOf(currentIf);
if(ifStmt != currentIf) {
if(method1 == method2) {
if(dt.isDominatorOf(dt.getDode(currentIf), dt.getDode(ifStmt))) {
if(ppr.getGuardedBlocks(currentIf).contains(ifStmt)) {
return true;
}
}
}
}
}
return false;
}
public static boolean isFilteredLib(SootClass sc) {
InputStream fis = null;
BufferedReader br = null;
String line = null;
try {
fis = Utils.class.getResourceAsStream(Constants.FILTERED_LIBS);
br = new BufferedReader(new InputStreamReader(fis));
while ((line = br.readLine()) != null) {
if(sc.getName().startsWith(line)) {
br.close();
fis.close();
return true;
}
}
} catch (IOException e) {
logger.error(e.getMessage());
}
try {
br.close();
fis.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
return false;
}
}
| 12,261 | 28.405276 | 136 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/utils/CommandLineOptions.java | package lu.uni.tsopen.utils;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.javatuples.Triplet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class sets the different option for the application
* @author Jordan Samhi
*
*/
public class CommandLineOptions {
private static final Triplet<String, String, String> FILE = new Triplet<String, String, String>("file", "f", "Apk file");
private static final Triplet<String, String, String> HELP = new Triplet<String, String, String>("help", "h", "Print this message");
private static final Triplet<String, String, String> TIMEOUT =
new Triplet<String, String, String>("timeout", "t", "Set a timeout in minutes (60 by default) to exit the application");
private static final Triplet<String, String, String> PLATFORMS =
new Triplet<String, String, String>("platforms", "p", "Android platforms folder");
private static final Triplet<String, String, String> EXCEPTIONS =
new Triplet<String, String, String>("exceptions", "e", "Take exceptions into account during full path predicate recovery");
private static final Triplet<String, String, String> OUTPUT =
new Triplet<String, String, String>("output", "o", "Output results in given file");
private static final Triplet<String, String, String> QUIET =
new Triplet<String, String, String>("quiet", "q", "Do not output results in console");
private static final Triplet<String, String, String> CALLGRAPH =
new Triplet<String, String, String>("callgraph", "c", "Define the call-graph algorithm to use (SPARK, CHA, RTA, VTA)");
private static final Triplet<String, String, String> RAW =
new Triplet<String, String, String>("raw", "r", "write raw results in stdout");
private static final Triplet<String, String, String> VERBOSE =
new Triplet<String, String, String>("verbose", "v", "Output verbose results");
private static final String TSOPEN = "TSOpen";
private Options options, firstOptions;
private CommandLineParser parser;
private CommandLine cmdLine, cmdFirstLine;
private Logger logger = LoggerFactory.getLogger(this.getClass());
public CommandLineOptions(String[] args) {
this.options = new Options();
this.firstOptions = new Options();
this.initOptions();
this.parser = new DefaultParser();
this.parse(args);
}
/**
* This method does the parsing of the arguments.
* It distinguished, real options and help option.
* @param args the arguments of the application
*/
private void parse(String[] args) {
HelpFormatter formatter = null;
try {
this.cmdFirstLine = this.parser.parse(this.firstOptions, args, true);
if (this.cmdFirstLine.hasOption(HELP.getValue0())) {
formatter = new HelpFormatter();
formatter.printHelp(TSOPEN, this.options, true);
System.exit(0);
}
this.cmdLine = this.parser.parse(this.options, args);
} catch (ParseException e) {
this.logger.error(e.getMessage());
System.exit(1);
}
}
/**
* Initialization of all recognized options
*/
private void initOptions() {
final Option file = Option.builder(FILE.getValue1())
.longOpt(FILE.getValue0())
.desc(FILE.getValue2())
.hasArg(true)
.argName(FILE.getValue0())
.required(true)
.build();
final Option platforms = Option.builder(PLATFORMS.getValue1())
.longOpt(PLATFORMS.getValue0())
.desc(PLATFORMS.getValue2())
.hasArg(true)
.argName(PLATFORMS.getValue0())
.required(true)
.build();
final Option help = Option.builder(HELP.getValue1())
.longOpt(HELP.getValue0())
.desc(HELP.getValue2())
.argName(HELP.getValue0())
.build();
final Option exceptions = Option.builder(EXCEPTIONS.getValue1())
.longOpt(EXCEPTIONS.getValue0())
.desc(EXCEPTIONS.getValue2())
.argName(EXCEPTIONS.getValue0())
.build();
final Option timeout = Option.builder(TIMEOUT.getValue1())
.longOpt(TIMEOUT.getValue0())
.desc(TIMEOUT.getValue2())
.argName(TIMEOUT.getValue0())
.hasArg(true)
.build();
timeout.setOptionalArg(true);
timeout.setType(Number.class);
final Option output = Option.builder(OUTPUT.getValue1())
.longOpt(OUTPUT.getValue0())
.desc(OUTPUT.getValue2())
.hasArg(true)
.argName(OUTPUT.getValue0())
.build();
final Option quiet = Option.builder(QUIET.getValue1())
.longOpt(QUIET.getValue0())
.desc(QUIET.getValue2())
.argName(QUIET.getValue0())
.build();
final Option raw = Option.builder(RAW.getValue1())
.longOpt(RAW.getValue0())
.desc(RAW.getValue2())
.argName(RAW.getValue0())
.build();
final Option verbose = Option.builder(VERBOSE.getValue1())
.longOpt(VERBOSE.getValue0())
.desc(VERBOSE.getValue2())
.argName(VERBOSE.getValue0())
.build();
final Option callgraph = Option.builder(CALLGRAPH.getValue1())
.longOpt(CALLGRAPH.getValue0())
.desc(CALLGRAPH.getValue2())
.argName(CALLGRAPH.getValue0())
.hasArg(true)
.build();
timeout.setOptionalArg(true);
this.firstOptions.addOption(help);
this.options.addOption(file);
this.options.addOption(platforms);
this.options.addOption(exceptions);
this.options.addOption(timeout);
this.options.addOption(output);
this.options.addOption(quiet);
this.options.addOption(callgraph);
this.options.addOption(raw);
this.options.addOption(verbose);
for(Option o : this.firstOptions.getOptions()) {
this.options.addOption(o);
}
}
public String getFile() {
return this.cmdLine.getOptionValue(FILE.getValue0());
}
public String getPlatforms() {
return this.cmdLine.getOptionValue(PLATFORMS.getValue0());
}
public boolean hasExceptions() {
return this.cmdLine.hasOption(EXCEPTIONS.getValue1());
}
public boolean hasOutput() {
return this.cmdLine.hasOption(OUTPUT.getValue1());
}
public String getOutput() {
return this.cmdLine.getOptionValue(OUTPUT.getValue0());
}
public boolean hasQuiet() {
return this.cmdLine.hasOption(QUIET.getValue1());
}
public boolean hasRaw() {
return this.cmdLine.hasOption(RAW.getValue1());
}
public boolean hasVerbose() {
return this.cmdLine.hasOption(VERBOSE.getValue1());
}
public int getTimeout() {
Number n = null;
try {
n = (Number)this.cmdLine.getParsedOptionValue(TIMEOUT.getValue1());
if(n == null) {
return 0;
}else {
return n.intValue();
}
} catch (Exception e) {}
return 0;
}
public String getCallGraph() {
String cg = this.cmdLine.getOptionValue(CALLGRAPH.getValue0());
if(cg != null) {
if(cg.equals("SPARK") || cg.equals("CHA") || cg.equals("RTA") || cg.equals("VTA")) {
return cg;
}
}
return null;
}
}
| 7,929 | 30.593625 | 132 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/SymbolicExecution.java | package lu.uni.tsopen.symbolicExecution;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.javatuples.Pair;
import lu.uni.tsopen.graphTraversal.ICFGForwardTraversal;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import lu.uni.tsopen.symbolicExecution.typeRecognition.BooleanRecognition;
import lu.uni.tsopen.symbolicExecution.typeRecognition.ByteRecognition;
import lu.uni.tsopen.symbolicExecution.typeRecognition.DateTimeRecognition;
import lu.uni.tsopen.symbolicExecution.typeRecognition.DoubleRecognition;
import lu.uni.tsopen.symbolicExecution.typeRecognition.FloatArrayRecognition;
import lu.uni.tsopen.symbolicExecution.typeRecognition.FloatRecognition;
import lu.uni.tsopen.symbolicExecution.typeRecognition.IntRecognition;
import lu.uni.tsopen.symbolicExecution.typeRecognition.LocationRecognition;
import lu.uni.tsopen.symbolicExecution.typeRecognition.LongRecognition;
import lu.uni.tsopen.symbolicExecution.typeRecognition.SmsRecognition;
import lu.uni.tsopen.symbolicExecution.typeRecognition.StringRecognition;
import lu.uni.tsopen.symbolicExecution.typeRecognition.TypeRecognitionHandler;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
/**
*
* Model int, String, Location, SMS and Time related locals and fields
* @author Jordan Samhi
*
*/
public class SymbolicExecution extends ICFGForwardTraversal {
private Map<Value, ContextualValues> symbolicExecutionResults;
private Map<Unit, Map<Value, List<SymbolicValue>>> valuesAtNode;
private Map<Value, List<SymbolicValue>> currentValues;
private TypeRecognitionHandler trh;
public SymbolicExecution(InfoflowCFG icfg, SootMethod mainMethod) {
super(icfg, "Symbolic Execution", mainMethod);
this.symbolicExecutionResults = new HashMap<Value, ContextualValues>();
this.valuesAtNode = new HashMap<Unit, Map<Value,List<SymbolicValue>>>();
this.currentValues = new HashMap<Value, List<SymbolicValue>>();
this.trh = new StringRecognition(null, this, this.icfg);
this.trh = new DateTimeRecognition(this.trh, this, this.icfg);
this.trh = new LocationRecognition(this.trh, this, this.icfg);
this.trh = new SmsRecognition(this.trh, this, this.icfg);
this.trh = new LongRecognition(this.trh, this, this.icfg);
this.trh = new IntRecognition(this.trh, this, this.icfg);
this.trh = new BooleanRecognition(this.trh, this, icfg);
this.trh = new ByteRecognition(this.trh, this, icfg);
this.trh = new DoubleRecognition(this.trh, this, icfg);
this.trh = new FloatArrayRecognition(this.trh, this, icfg);
this.trh = new FloatRecognition(this.trh, this, icfg);
}
/**
* Process the symbolic execution of the current node.
*/
@Override
protected void processNodeBeforeNeighbors(Unit node) {
ContextualValues contextualValues = null;
List<Pair<Value, SymbolicValue>> results = this.trh.recognizeType(node);
Value value = null;
SymbolicValue symbolicValue = null;
this.updateValuesAtNode(results, node);
if(results != null) {
for(Pair<Value, SymbolicValue> p : results) {
value = p.getValue0();
symbolicValue = p.getValue1();
contextualValues = this.symbolicExecutionResults.get(value);
if(contextualValues == null) {
contextualValues = new ContextualValues(this, value);
if(value != null) {
this.symbolicExecutionResults.put(value, contextualValues);
}
}
contextualValues.addValue(node, symbolicValue);
}
}
}
private void updateValuesAtNode(List<Pair<Value, SymbolicValue>> results, Unit node) {
Value value = null;
SymbolicValue symbolicValue = null;
List<SymbolicValue> symValues = null;
Map<Value, List<SymbolicValue>> currentSymValues = new HashMap<Value, List<SymbolicValue>>();
Map<Value, List<SymbolicValue>> tmpSymValues = new HashMap<Value, List<SymbolicValue>>();
currentSymValues.putAll(this.currentValues);
if(results != null) {
for(Pair<Value, SymbolicValue> p : results) {
value = p.getValue0();
symbolicValue = p.getValue1();
symValues = tmpSymValues.get(value);
if(symValues == null) {
symValues = new ArrayList<SymbolicValue>();
tmpSymValues.put(value, symValues);
}
symValues.add(symbolicValue);
}
for(Entry<Value, List<SymbolicValue>> e : tmpSymValues.entrySet()) {
currentSymValues.put(e.getKey(), e.getValue());
}
}
this.valuesAtNode.put(node, currentSymValues);
this.currentValues = currentSymValues;
}
public Map<Value, ContextualValues> getContext() {
return this.symbolicExecutionResults;
}
public ContextualValues getContextualValues(Value v) {
if(this.symbolicExecutionResults.containsKey(v)) {
return this.symbolicExecutionResults.get(v);
}
return null;
}
public Map<Value, List<SymbolicValue>> getValuesAtNode(Unit node) {
return this.valuesAtNode.get(node);
}
@Override
protected void processNeighbor(Unit node, Unit neighbour) {}
@Override
protected void processNodeAfterNeighbors(Unit node) {}
}
| 6,110 | 36.956522 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/ContextualValues.java | package lu.uni.tsopen.symbolicExecution;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import soot.Unit;
import soot.Value;
public class ContextualValues {
private Value receiver;
private LinkedHashMap<Unit, LinkedList<SymbolicValue>> nodesToSymbolicValues;
private SymbolicExecution se;
public ContextualValues(SymbolicExecution se, Value receiver) {
this.nodesToSymbolicValues = new LinkedHashMap<Unit, LinkedList<SymbolicValue>>();
this.se = se;
this.receiver = receiver;
}
public void addValue(Unit node, SymbolicValue sv) {
LinkedList<SymbolicValue> valuesOfNode = this.nodesToSymbolicValues.get(node);
if(valuesOfNode == null) {
valuesOfNode = new LinkedList<SymbolicValue>();
this.nodesToSymbolicValues.put(node, valuesOfNode);
}
valuesOfNode.add(sv);
}
/**
* Return last available values on the current path if possible.
* Otherwise the last computed values
* @return a list of symbolic values
*/
public List<SymbolicValue> getLastCoherentValues(Unit node) {
Iterator<Unit> it = this.se.getCurrentPath().descendingIterator();
LinkedList<SymbolicValue> values = null;
Unit n = null;
Map<Value, List<SymbolicValue>> valuesAtNode = null;
if(node == null) {
while(it.hasNext()) {
n = it.next();
if(n != this.se.getCurrentPath().getLast()) {
values = this.nodesToSymbolicValues.get(n);
if(values != null) {
return values;
}
}
}
}else {
valuesAtNode = this.se.getValuesAtNode(node);
if(valuesAtNode != null) {
return valuesAtNode.get(this.receiver);
}
}
return this.getAllValues();
}
public List<SymbolicValue> getAllValues() {
List<SymbolicValue> values = new ArrayList<SymbolicValue>();
for(Entry<Unit, LinkedList<SymbolicValue>> e : this.nodesToSymbolicValues.entrySet()) {
values.addAll(e.getValue());
}
return values;
}
}
| 3,117 | 29.871287 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/FloatArrayRecognition.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.utils.Constants;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public class FloatArrayRecognition extends NumericRecognition {
public FloatArrayRecognition(TypeRecognitionHandler next, SymbolicExecution se, InfoflowCFG icfg) {
super(next, se, icfg);
this.authorizedTypes.add(Constants.FLOAT_ARRAY);
}
}
| 1,503 | 34.809524 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/DoubleRecognition.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric.GetLatitudeRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric.GetLongitudeRecognition;
import lu.uni.tsopen.utils.Constants;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public class DoubleRecognition extends NumericRecognition {
public DoubleRecognition(TypeRecognitionHandler next, SymbolicExecution se, InfoflowCFG icfg) {
super(next, se, icfg);
this.authorizedTypes.add(Constants.DOUBLE);
this.nmrh = new GetLongitudeRecognition(null, se);
this.nmrh = new GetLatitudeRecognition(this.nmrh, se);
}
}
| 1,780 | 36.893617 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/NumericRecognition.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.javatuples.Pair;
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric.NumericMethodsRecognitionHandler;
import lu.uni.tsopen.symbolicExecution.symbolicValues.BinOpValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.MethodRepresentationValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.ObjectValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import lu.uni.tsopen.utils.Utils;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.NewArrayExpr;
import soot.jimple.ParameterRef;
import soot.jimple.StaticFieldRef;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public abstract class NumericRecognition extends TypeRecognitionHandler {
protected NumericMethodsRecognitionHandler nmrh;
public NumericRecognition(TypeRecognitionHandler next, SymbolicExecution se, InfoflowCFG icfg) {
super(next, se, icfg);
}
@Override
public void handleConstructorTag(List<Value> args, ObjectValue object) {}
@Override
public List<Pair<Value, SymbolicValue>> handleDefinitionStmt(DefinitionStmt defUnit) {
Value leftOp = defUnit.getLeftOp(),
rightOp = defUnit.getRightOp(),
base = null,
binOp1 = null,
binOp2 = null;
List<Pair<Value, SymbolicValue>> results = new LinkedList<Pair<Value,SymbolicValue>>();
InvokeExpr rightOpInvExpr = null;
SootMethod method = null;
List<Value> args = null;
SymbolicValue object = null;
BinopExpr BinOpRightOp = null;
Value callerRightOp = null;
InvokeExpr invExprCaller = null;
Collection<Unit> callers = null;
InvokeStmt invStmtCaller = null;
AssignStmt assignCaller = null;
if(rightOp instanceof InvokeExpr) {
rightOpInvExpr = (InvokeExpr) rightOp;
method = rightOpInvExpr.getMethod();
args = rightOpInvExpr.getArgs();
if(rightOp instanceof InstanceInvokeExpr) {
base = ((InstanceInvokeExpr)rightOpInvExpr).getBase();
}
object = new MethodRepresentationValue(base, args, method, this.se);
if(this.nmrh != null) {
this.nmrh.recognizeNumericMethod(method, base, object);
}
}else if(rightOp instanceof InstanceFieldRef) {
this.checkAndProcessContextValues(rightOp, results, leftOp, defUnit);
}else if(rightOp instanceof StaticFieldRef) {
this.checkAndProcessContextValues(rightOp, results, leftOp, defUnit);
}else if(rightOp instanceof BinopExpr){
BinOpRightOp = (BinopExpr) rightOp;
binOp1 = BinOpRightOp.getOp1();
binOp2 = BinOpRightOp.getOp2();
object = new BinOpValue(this.se, binOp1, binOp2, BinOpRightOp.getSymbol());
Utils.propagateTags(binOp1, object, this.se);
Utils.propagateTags(binOp2, object, this.se);
}else if(rightOp instanceof ParameterRef){
callers = this.icfg.getCallersOf(this.icfg.getMethodOf(defUnit));
for(Unit caller : callers) {
if(caller instanceof InvokeStmt) {
invStmtCaller = (InvokeStmt) caller;
invExprCaller = invStmtCaller.getInvokeExpr();
}else if(caller instanceof AssignStmt) {
assignCaller = (AssignStmt) caller;
callerRightOp = assignCaller.getRightOp();
if(callerRightOp instanceof InvokeExpr) {
invExprCaller = (InvokeExpr)callerRightOp;
}else if(callerRightOp instanceof InvokeStmt) {
invExprCaller = ((InvokeStmt)callerRightOp).getInvokeExpr();
}
}
this.checkAndProcessContextValues(invExprCaller.getArg(((ParameterRef) rightOp).getIndex()), results, leftOp, caller);
}
}else if (rightOp instanceof NewArrayExpr){
object = new ObjectValue(leftOp.getType(), null, this.se);
}else if(rightOp instanceof ArrayRef) {
this.checkAndProcessContextValues(((ArrayRef)rightOp).getBase(), results, leftOp, defUnit);
}else if(leftOp instanceof StaticFieldRef) {
this.checkAndProcessContextValues(rightOp, results, leftOp, defUnit);
}else if(leftOp instanceof InstanceFieldRef && !(rightOp instanceof Constant)) {
this.checkAndProcessContextValues(rightOp, results, leftOp, defUnit);
}else if(leftOp instanceof InstanceFieldRef && rightOp instanceof Constant) {
this.checkAndProcessContextValues(rightOp, results, leftOp, defUnit);
}else if(rightOp instanceof CastExpr) {
this.checkAndProcessContextValues(((CastExpr) rightOp).getOp(), results, leftOp, defUnit);
}else {
return results;
}
if(object != null) {
results.add(new Pair<Value, SymbolicValue>(leftOp, object));
}
return results;
}
@Override
public void handleInvokeTag(List<Value> args, Value base, SymbolicValue object, SootMethod method) {}
}
| 6,056 | 38.077419 | 122 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/TypeRecognition.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import org.javatuples.Pair;
import lu.uni.tsopen.symbolicExecution.symbolicValues.ObjectValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.DefinitionStmt;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.ReturnStmt;
public interface TypeRecognition {
public List<Pair<Value, SymbolicValue>> recognizeType(Unit node);
public List<Pair<Value, SymbolicValue>> processDefinitionStmt(DefinitionStmt defUnit);
public List<Pair<Value, SymbolicValue>> processInvokeStmt(InvokeStmt invUnit);
public void handleConstructor(InvokeExpr invExprUnit, Value base, List<Pair<Value, SymbolicValue>> results);
public void handleConstructorTag(List<Value> args, ObjectValue object);
public List<Pair<Value, SymbolicValue>> handleDefinitionStmt(DefinitionStmt defUnit);
public List<Pair<Value, SymbolicValue>> processReturnStmt(ReturnStmt node);
public abstract void handleInvokeTag(List<Value> args, Value base, SymbolicValue object, SootMethod method);
} | 2,214 | 40.018519 | 109 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/IntRecognition.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric.GetHoursRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric.GetMinutesRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric.GetMonthRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric.GetRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric.GetSecondsRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric.GetYearRecognition;
import lu.uni.tsopen.utils.Constants;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public class IntRecognition extends NumericRecognition {
public IntRecognition(TypeRecognitionHandler next, SymbolicExecution se, InfoflowCFG icfg) {
super(next, se, icfg);
this.authorizedTypes.add(Constants.INT);
this.nmrh = new GetMonthRecognition(null, se);
this.nmrh = new GetMinutesRecognition(this.nmrh, se);
this.nmrh = new GetSecondsRecognition(this.nmrh, se);
this.nmrh = new GetHoursRecognition(this.nmrh, se);
this.nmrh = new GetYearRecognition(this.nmrh, se);
this.nmrh = new GetRecognition(this.nmrh, se);
}
}
| 2,312 | 41.833333 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/StringRecognition.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.javatuples.Pair;
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.strings.AppendRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.strings.FormatRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.strings.GetMessageBodyRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.strings.GetOriginatingAddressRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.strings.StringMethodsRecognitionHandler;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.strings.SubStringRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.strings.ToLowerCaseRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.strings.ToStringRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.strings.ToUpperCaseRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.strings.ValueOfRecognition;
import lu.uni.tsopen.symbolicExecution.symbolicValues.ConstantValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.MethodRepresentationValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.ObjectValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import lu.uni.tsopen.utils.Constants;
import lu.uni.tsopen.utils.Utils;
import soot.Local;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.CastExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.ParameterRef;
import soot.jimple.ReturnStmt;
import soot.jimple.StringConstant;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public class StringRecognition extends TypeRecognitionHandler{
private StringMethodsRecognitionHandler smrh;
public StringRecognition(TypeRecognitionHandler next, SymbolicExecution se, InfoflowCFG icfg) {
super(next, se, icfg);
this.smrh = new AppendRecognition(null, se);
this.smrh = new ValueOfRecognition(this.smrh, se);
this.smrh = new ToStringRecognition(this.smrh, se);
this.smrh = new SubStringRecognition(this.smrh, se);
this.smrh = new GetMessageBodyRecognition(this.smrh, se);
this.smrh = new FormatRecognition(this.smrh, se);
this.smrh = new ToLowerCaseRecognition(this.smrh, se);
this.smrh = new ToUpperCaseRecognition(this.smrh, se);
this.smrh = new GetOriginatingAddressRecognition(this.smrh, se);
this.authorizedTypes.add(Constants.JAVA_LANG_STRING);
this.authorizedTypes.add(Constants.JAVA_LANG_STRING_BUFFER);
this.authorizedTypes.add(Constants.JAVA_LANG_STRING_BUILDER);
}
@Override
public List<Pair<Value, SymbolicValue>> handleDefinitionStmt(DefinitionStmt defUnit) {
Value leftOp = defUnit.getLeftOp(),
rightOp = defUnit.getRightOp(),
callerRightOp = null,
base = null;
InvokeExpr rightOpInvokeExpr = null,
invExprCaller = null;
SootMethod method = null;
List<Value> args = null;
List<Pair<Value, SymbolicValue>> results = new LinkedList<Pair<Value,SymbolicValue>>();
CastExpr rightOpExpr = null;
Collection<Unit> callers = null;
InvokeStmt invStmtCaller = null;
AssignStmt assignCaller = null;
List<SymbolicValue> recognizedValues = null;
SymbolicValue object = null;
if(rightOp instanceof StringConstant) {
results.add(new Pair<Value, SymbolicValue>(leftOp, new ConstantValue((StringConstant)rightOp, this.se)));
}else if(rightOp instanceof ParameterRef) {
callers = this.icfg.getCallersOf(this.icfg.getMethodOf(defUnit));
for(Unit caller : callers) {
if(caller instanceof InvokeStmt) {
invStmtCaller = (InvokeStmt) caller;
invExprCaller = invStmtCaller.getInvokeExpr();
}else if(caller instanceof AssignStmt) {
assignCaller = (AssignStmt) caller;
callerRightOp = assignCaller.getRightOp();
if(callerRightOp instanceof InvokeExpr) {
invExprCaller = (InvokeExpr)callerRightOp;
}else if(callerRightOp instanceof InvokeStmt) {
invExprCaller = ((InvokeStmt)callerRightOp).getInvokeExpr();
}
}
this.checkAndProcessContextValues(invExprCaller.getArg(((ParameterRef) rightOp).getIndex()), results, leftOp, caller);
}
}else if(rightOp instanceof Local && !(leftOp instanceof InstanceFieldRef)) {
this.checkAndProcessContextValues(rightOp, results, leftOp, null);
}else if (rightOp instanceof CastExpr) {
rightOpExpr = (CastExpr) rightOp;
this.checkAndProcessContextValues(rightOpExpr.getOp(), results, leftOp, null);
}else if(rightOp instanceof InvokeExpr) {
rightOpInvokeExpr = (InvokeExpr) rightOp;
method = rightOpInvokeExpr.getMethod();
args = rightOpInvokeExpr.getArgs();
base = rightOpInvokeExpr instanceof InstanceInvokeExpr ? ((InstanceInvokeExpr) rightOpInvokeExpr).getBase() : null;
recognizedValues = this.smrh.recognizeStringMethod(method, base, args);
if(recognizedValues != null) {
for(SymbolicValue recognizedValue : recognizedValues) {
results.add(new Pair<Value, SymbolicValue>(leftOp, recognizedValue));
}
}else {
object = new MethodRepresentationValue(base, args, method, this.se);
results.add(new Pair<Value, SymbolicValue>(leftOp, object));
}
if(!this.se.isMethodVisited(method)) {
this.se.addMethodToWorkList(this.icfg.getMethodOf(defUnit));
}else {
if(method.isConcrete()) {
for(Unit u : method.retrieveActiveBody().getUnits()) {
if(u instanceof ReturnStmt) {
if(object != null) {
Utils.propagateTags(((ReturnStmt)u).getOp(), object, this.se);
}
}
}
}
}
}else if(rightOp instanceof InstanceFieldRef){
this.checkAndProcessContextValues(rightOp, results, leftOp, defUnit);
}else if(leftOp instanceof InstanceFieldRef) {
this.checkAndProcessContextValues(rightOp, results, leftOp, defUnit);
}
return results;
}
@Override
public void handleConstructor(InvokeExpr invExprUnit, Value base, List<Pair<Value, SymbolicValue>> results) {
Value arg = null;
List<Value> args = invExprUnit.getArgs();
ConstantValue cv = null;
if(args.size() == 0) {
results.add(new Pair<Value, SymbolicValue>(base, new ConstantValue(StringConstant.v(Constants.EMPTY_STRING), this.se)));
}else {
arg = args.get(0);
if(arg instanceof Local) {
this.checkAndProcessContextValues(arg, results, base, null);
}else {
if(arg instanceof StringConstant) {
cv = new ConstantValue((StringConstant)arg, this.se);
}
else {
cv = new ConstantValue(StringConstant.v(Constants.EMPTY_STRING), this.se);
}
results.add(new Pair<Value, SymbolicValue>(base, cv));
}
}
}
@Override
public void handleConstructorTag(List<Value> args, ObjectValue object) {}
@Override
public void handleInvokeTag(List<Value> args, Value base, SymbolicValue object, SootMethod method) {}
}
| 8,108 | 40.372449 | 123 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/LongRecognition.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric.CurrentTimeMillisRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric.GetLatitudeRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric.GetLongitudeRecognition;
import lu.uni.tsopen.utils.Constants;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public class LongRecognition extends NumericRecognition {
public LongRecognition(TypeRecognitionHandler next, SymbolicExecution se, InfoflowCFG icfg) {
super(next, se, icfg);
this.authorizedTypes.add(Constants.LONG);
this.nmrh = new GetLongitudeRecognition(null, se);
this.nmrh = new GetLatitudeRecognition(this.nmrh, se);
this.nmrh = new CurrentTimeMillisRecognition(this.nmrh, se);
}
}
| 1,931 | 39.25 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/DateTimeRecognition.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.LinkedList;
import java.util.List;
import org.javatuples.Pair;
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.dateTime.DateTimeMethodsRecognitionHandler;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.dateTime.GetInstanceRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.dateTime.NowRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.dateTime.SetToNowRecognition;
import lu.uni.tsopen.symbolicExecution.symbolicValues.ObjectValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import lu.uni.tsopen.utils.Constants;
import soot.SootMethod;
import soot.Value;
import soot.jimple.DefinitionStmt;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
import soot.tagkit.StringConstantValueTag;
public class DateTimeRecognition extends TypeRecognitionHandler {
private DateTimeMethodsRecognitionHandler dtmrh;
public DateTimeRecognition(TypeRecognitionHandler next, SymbolicExecution se, InfoflowCFG icfg) {
super(next, se, icfg);
this.authorizedTypes.add(Constants.JAVA_UTIL_DATE);
this.authorizedTypes.add(Constants.JAVA_UTIL_CALENDAR);
this.authorizedTypes.add(Constants.JAVA_UTIL_GREGORIAN_CALENDAR);
this.authorizedTypes.add(Constants.JAVA_TIME_LOCAL_DATE_TIME);
this.authorizedTypes.add(Constants.JAVA_TIME_LOCAL_DATE);
this.authorizedTypes.add(Constants.JAVA_TEXT_SIMPLE_DATE_FORMAT);
this.authorizedTypes.add(Constants.ANDROID_TEXT_FORMAT_TIME);
this.dtmrh = new GetInstanceRecognition(null, se);
this.dtmrh = new NowRecognition(this.dtmrh, se);
this.dtmrh = new SetToNowRecognition(this.dtmrh, se);
}
@Override
public List<Pair<Value, SymbolicValue>> handleDefinitionStmt(DefinitionStmt defUnit) {
Value leftOp = defUnit.getLeftOp(),
rightOp = defUnit.getRightOp();
List<Pair<Value, SymbolicValue>> results = new LinkedList<Pair<Value,SymbolicValue>>();
StaticInvokeExpr rightOpStaticInvokeExpr = null;
SootMethod method = null;
List<Value> args = null;
ObjectValue object = null;
if(rightOp instanceof StaticInvokeExpr) {
rightOpStaticInvokeExpr = (StaticInvokeExpr) rightOp;
method = rightOpStaticInvokeExpr.getMethod();
args = rightOpStaticInvokeExpr.getArgs();
object = new ObjectValue(method.getDeclaringClass().getType(), args, this.se);
this.dtmrh.recognizeDateTimeMethod(method, object);
results.add(new Pair<Value, SymbolicValue>(leftOp, object));
}
return results;
}
@Override
public void handleConstructorTag(List<Value> args, ObjectValue object) {
if(args.size() == 0) {
object.addTag(new StringConstantValueTag(Constants.NOW_TAG));
}
}
@Override
public void handleInvokeTag(List<Value> args, Value base, SymbolicValue object, SootMethod method) {
this.dtmrh.recognizeDateTimeMethod(method, object);
}
}
| 4,011 | 38.333333 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/LocationRecognition.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.javatuples.Pair;
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.location.GetLastKnowLocationRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.location.GetLastLocationRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.location.LocationMethodsRecognitionHandler;
import lu.uni.tsopen.symbolicExecution.symbolicValues.ObjectValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import lu.uni.tsopen.utils.Constants;
import soot.SootClass;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.DefinitionStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.ParameterRef;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
import soot.tagkit.StringConstantValueTag;
public class LocationRecognition extends TypeRecognitionHandler {
private LocationMethodsRecognitionHandler lmrh;
public LocationRecognition(TypeRecognitionHandler next, SymbolicExecution se, InfoflowCFG icfg) {
super(next, se, icfg);
this.authorizedTypes.add(Constants.ANDROID_LOCATION_LOCATION);
this.lmrh = new GetLastKnowLocationRecognition(null, se);
this.lmrh = new GetLastLocationRecognition(this.lmrh, se);
}
@Override
public void handleConstructorTag(List<Value> args, ObjectValue object) {}
@Override
public List<Pair<Value, SymbolicValue>> handleDefinitionStmt(DefinitionStmt defUnit) {
Value leftOp = defUnit.getLeftOp(),
rightOp = defUnit.getRightOp(),
base = null;
List<Pair<Value, SymbolicValue>> results = new LinkedList<Pair<Value,SymbolicValue>>();
InvokeExpr rightOpInvExpr = null;
SootMethod method = null;
SootClass declaringClass = null;
List<Value> args = null;
SymbolicValue object = null;
Type type = null;
Value callerRightOp = null;
InvokeExpr invExprCaller = null;
Collection<Unit> callers = null;
InvokeStmt invStmtCaller = null;
AssignStmt assignCaller = null;
if(rightOp instanceof InvokeExpr) {
rightOpInvExpr = (InvokeExpr) rightOp;
method = rightOpInvExpr.getMethod();
declaringClass = method.getDeclaringClass();
args = rightOpInvExpr.getArgs();
if(rightOpInvExpr instanceof StaticInvokeExpr) {
type = declaringClass.getType();
}else if(rightOpInvExpr instanceof InstanceInvokeExpr){
base = ((InstanceInvokeExpr)rightOpInvExpr).getBase();
type = base.getType();
}
object = new ObjectValue(type, args, this.se);
this.lmrh.recognizeLocationMethod(method, object);
}else if(rightOp instanceof ParameterRef) {
method = this.icfg.getMethodOf(defUnit);
declaringClass = method.getDeclaringClass();
if(method.getName().equals(Constants.ON_LOCATION_CHANGED)) {
for(SootClass sc : declaringClass.getInterfaces()) {
if(sc.getName().equals(Constants.ANDROID_LOCATION_LOCATION_LISTENER)) {
type = method.retrieveActiveBody().getParameterLocal(0).getType();
object = new ObjectValue(type, null, this.se);
object.addTag(new StringConstantValueTag(Constants.HERE_TAG));
}
}
}else {
callers = this.icfg.getCallersOf(this.icfg.getMethodOf(defUnit));
for(Unit caller : callers) {
if(caller instanceof InvokeStmt) {
invStmtCaller = (InvokeStmt) caller;
invExprCaller = invStmtCaller.getInvokeExpr();
}else if(caller instanceof AssignStmt) {
assignCaller = (AssignStmt) caller;
callerRightOp = assignCaller.getRightOp();
if(callerRightOp instanceof InvokeExpr) {
invExprCaller = (InvokeExpr)callerRightOp;
}else if(callerRightOp instanceof InvokeStmt) {
invExprCaller = ((InvokeStmt)callerRightOp).getInvokeExpr();
}
}
this.checkAndProcessContextValues(invExprCaller.getArg(((ParameterRef) rightOp).getIndex()), results, leftOp, caller);
}
}
}
if(object != null) {
results.add(new Pair<Value, SymbolicValue>(leftOp, object));
}
return results;
}
@Override
public void handleInvokeTag(List<Value> args, Value base, SymbolicValue object, SootMethod method) {}
}
| 5,409 | 35.554054 | 123 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/TypeRecognitionHandler.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.javatuples.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lu.uni.tsopen.symbolicExecution.ContextualValues;
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.location.DistanceBetweenRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.location.LocationMethodsRecognitionHandler;
import lu.uni.tsopen.symbolicExecution.symbolicValues.ConstantValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.MethodRepresentationValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.ObjectValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.UnknownValue;
import lu.uni.tsopen.utils.Utils;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.ReturnStmt;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public abstract class TypeRecognitionHandler implements TypeRecognition {
private TypeRecognitionHandler next;
protected SymbolicExecution se;
protected InfoflowCFG icfg;
protected List<String> authorizedTypes;
private LocationMethodsRecognitionHandler lmrh;
protected Logger logger = LoggerFactory.getLogger(this.getClass());
public TypeRecognitionHandler(TypeRecognitionHandler next, SymbolicExecution se, InfoflowCFG icfg) {
this.next = next;
this.se = se;
this.icfg = icfg;
this.authorizedTypes = new LinkedList<String>();
this.lmrh = new DistanceBetweenRecognition(null, se);
}
@Override
public List<Pair<Value, SymbolicValue>> recognizeType(Unit node) {
List<Pair<Value, SymbolicValue>> result = null;
if(node instanceof DefinitionStmt) {
result = this.processDefinitionStmt((DefinitionStmt) node);
}else if (node instanceof InvokeStmt) {
result = this.processInvokeStmt((InvokeStmt) node);
}else if(node instanceof ReturnStmt) {
result = this.processReturnStmt((ReturnStmt)node);
}
if(result != null && !result.isEmpty()) {
return result;
}
if(this.next != null) {
return this.next.recognizeType(node);
}
else {
return null;
}
}
@Override
public List<Pair<Value, SymbolicValue>> processReturnStmt(ReturnStmt returnStmt) {
Collection<Unit> callers = this.icfg.getCallersOf(this.icfg.getMethodOf(returnStmt));
AssignStmt callerAssign = null;
Value leftOp = null,
returnOp = returnStmt.getOp();
List<SymbolicValue> values = null;
ContextualValues contextualValues = this.se.getContext().get(returnOp);
List<Pair<Value, SymbolicValue>> results = new LinkedList<Pair<Value,SymbolicValue>>();
SymbolicValue object = null;
SootMethod callerMethod = null;
for(Unit caller : callers) {
callerMethod = this.icfg.getMethodOf(caller);
if(caller instanceof AssignStmt) {
callerAssign = (AssignStmt) caller;
leftOp = callerAssign.getLeftOp();
if(contextualValues == null) {
if(returnOp instanceof Constant) {
object = new ConstantValue((Constant)returnOp, this.se);
}else {
object = new UnknownValue(this.se);
}
Utils.propagateTags(returnOp, object, this.se);
results.add(new Pair<Value, SymbolicValue>(leftOp, object));
}else {
values = contextualValues.getLastCoherentValues(null);
if(values != null) {
for(SymbolicValue sv : values) {
results.add(new Pair<Value, SymbolicValue>(leftOp, sv));
}
}
}
}
if(this.se.isMethodVisited(callerMethod)) {
this.se.addMethodToWorkList(callerMethod);
}
}
return results;
}
@Override
public List<Pair<Value, SymbolicValue>> processDefinitionStmt(DefinitionStmt defUnit) {
if(this.isAuthorizedType(defUnit.getLeftOp().getType().toString())) {
return this.handleDefinitionStmt(defUnit);
}
return null;
}
@Override
public List<Pair<Value, SymbolicValue>> processInvokeStmt(InvokeStmt invUnit) {
Value base = null;
InvokeExpr invExprUnit = invUnit.getInvokeExpr();
SootMethod m = invExprUnit.getMethod();
List<Pair<Value, SymbolicValue>> results = new LinkedList<Pair<Value,SymbolicValue>>();
if(invExprUnit instanceof InstanceInvokeExpr) {
base = ((InstanceInvokeExpr) invExprUnit).getBase();
if(base != null) {
if(this.isAuthorizedType(base.getType().toString())) {
if(m.isConstructor()) {
this.handleConstructor(invExprUnit, base, results);
}else if(invExprUnit instanceof InstanceInvokeExpr){
this.handleInvokeStmt(invExprUnit, base, results);
}
}
}
}else if (invExprUnit instanceof StaticInvokeExpr) {
this.handleInvokeStmt(invExprUnit, base, results);
}
return results;
}
protected void handleInvokeStmt(InvokeExpr invExprUnit, Value base, List<Pair<Value, SymbolicValue>> results) {
SootMethod method = invExprUnit.getMethod();
List<Value> args = invExprUnit.getArgs();
SymbolicValue object = new MethodRepresentationValue(base, args, method, this.se);
this.lmrh.recognizeLocationMethod(method, object);
this.handleInvokeTag(args, base, object, method);
results.add(new Pair<Value, SymbolicValue>(base, object));
}
@Override
public abstract void handleInvokeTag(List<Value> args, Value base, SymbolicValue object, SootMethod method);
@Override
public void handleConstructor(InvokeExpr invExprUnit, Value base, List<Pair<Value, SymbolicValue>> results) {
List<Value> args = invExprUnit.getArgs();
ObjectValue object = new ObjectValue(base.getType(), args, this.se);
this.handleConstructorTag(args, object);
results.add(new Pair<Value, SymbolicValue>(base, object));
}
protected boolean isAuthorizedType(String type) {
return this.authorizedTypes.contains(type);
}
protected void checkAndProcessContextValues(Value v, List<Pair<Value, SymbolicValue>> results, Value leftOp, Unit node) {
ContextualValues contextualValues = this.se.getContext().get(v);
List<SymbolicValue> values = null;
if(contextualValues == null) {
results.add(new Pair<Value, SymbolicValue>(leftOp, new UnknownValue(this.se)));
}else {
values = contextualValues.getLastCoherentValues(node);
if(values != null) {
for(SymbolicValue sv : values) {
results.add(new Pair<Value, SymbolicValue>(leftOp, sv));
}
}
}
}
} | 7,625 | 34.802817 | 122 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/BooleanRecognition.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.LinkedList;
import java.util.List;
import org.javatuples.Pair;
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.bool.AfterRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.bool.BeforeRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.bool.BooleanMethodsRecognitionHandler;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.bool.ContainsRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.bool.EndsWithRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.bool.EqualsRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.bool.MatchesRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.bool.StartsWithRecognition;
import lu.uni.tsopen.symbolicExecution.symbolicValues.FieldValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.MethodRepresentationValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.ObjectValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import lu.uni.tsopen.utils.Constants;
import lu.uni.tsopen.utils.Utils;
import soot.SootMethod;
import soot.Value;
import soot.jimple.DefinitionStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public class BooleanRecognition extends TypeRecognitionHandler {
private BooleanMethodsRecognitionHandler bmrh;
public BooleanRecognition(TypeRecognitionHandler next, SymbolicExecution se, InfoflowCFG icfg) {
super(next, se, icfg);
this.authorizedTypes.add(Constants.BOOLEAN);
this.bmrh = new AfterRecognition(null, se);
this.bmrh = new BeforeRecognition(this.bmrh, se);
this.bmrh = new EqualsRecognition(this.bmrh, se);
this.bmrh = new ContainsRecognition(this.bmrh, se);
this.bmrh = new StartsWithRecognition(this.bmrh, se);
this.bmrh = new EndsWithRecognition(this.bmrh, se);
this.bmrh = new MatchesRecognition(this.bmrh, se);
}
@Override
public void handleConstructorTag(List<Value> args, ObjectValue object) {}
@Override
public List<Pair<Value, SymbolicValue>> handleDefinitionStmt(DefinitionStmt defUnit) {
Value leftOp = defUnit.getLeftOp(),
rightOp = defUnit.getRightOp(),
base = null;
List<Pair<Value, SymbolicValue>> results = new LinkedList<Pair<Value,SymbolicValue>>();
InstanceInvokeExpr rightOpInvExpr = null;
InstanceFieldRef field = null;
SootMethod method = null;
List<Value> args = null;
SymbolicValue object = null;
if(rightOp instanceof InstanceInvokeExpr) {
rightOpInvExpr = (InstanceInvokeExpr) rightOp;
method = rightOpInvExpr.getMethod();
args = rightOpInvExpr.getArgs();
base = rightOpInvExpr.getBase();
object = new MethodRepresentationValue(base, args, method, this.se);
this.bmrh.recognizeBooleanMethod(method, base, object, args);
}else if(rightOp instanceof InstanceFieldRef){
field = (InstanceFieldRef) rightOp;
base = field.getBase();
object = new FieldValue(base, field.getField().getName(), this.se);
Utils.propagateTags(rightOp, object, this.se);
}else {
return results;
}
results.add(new Pair<Value, SymbolicValue>(leftOp, object));
return results;
}
@Override
public void handleInvokeTag(List<Value> args, Value base, SymbolicValue object, SootMethod method) {}
}
| 4,482 | 39.387387 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/ByteRecognition.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.LinkedList;
import java.util.List;
import org.javatuples.Pair;
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.symbolicValues.BinOpValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.ObjectValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import lu.uni.tsopen.utils.Constants;
import lu.uni.tsopen.utils.Utils;
import soot.SootMethod;
import soot.Value;
import soot.jimple.BinopExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public class ByteRecognition extends TypeRecognitionHandler {
public ByteRecognition(TypeRecognitionHandler next, SymbolicExecution se, InfoflowCFG icfg) {
super(next, se, icfg);
this.authorizedTypes.add(Constants.BYTE);
}
@Override
public void handleConstructorTag(List<Value> args, ObjectValue object) {}
@Override
public List<Pair<Value, SymbolicValue>> handleDefinitionStmt(DefinitionStmt defUnit) {
Value leftOp = defUnit.getLeftOp(),
rightOp = defUnit.getRightOp(),
binOp1 = null,
binOp2 = null;
List<Pair<Value, SymbolicValue>> results = new LinkedList<Pair<Value,SymbolicValue>>();
SymbolicValue object = null;
BinopExpr BinOpRightOp = null;
if(rightOp instanceof BinopExpr){
BinOpRightOp = (BinopExpr) rightOp;
binOp1 = BinOpRightOp.getOp1();
binOp2 = BinOpRightOp.getOp2();
object = new BinOpValue(this.se, binOp1, binOp2, BinOpRightOp.getSymbol());
Utils.propagateTags(binOp1, object, this.se);
Utils.propagateTags(binOp2, object, this.se);
}else {
return results;
}
results.add(new Pair<Value, SymbolicValue>(leftOp, object));
return results;
}
@Override
public void handleInvokeTag(List<Value> args, Value base, SymbolicValue object, SootMethod method) {}
}
| 2,922 | 33.388235 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/FloatRecognition.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.utils.Constants;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public class FloatRecognition extends NumericRecognition {
public FloatRecognition(TypeRecognitionHandler next, SymbolicExecution se, InfoflowCFG icfg) {
super(next, se, icfg);
this.authorizedTypes.add(Constants.FLOAT);
}
}
| 1,488 | 33.627907 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/typeRecognition/SmsRecognition.java | package lu.uni.tsopen.symbolicExecution.typeRecognition;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.LinkedList;
import java.util.List;
import org.javatuples.Pair;
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.sms.CreateFromPduRecognition;
import lu.uni.tsopen.symbolicExecution.methodRecognizers.sms.SmsMethodsRecognitionHandler;
import lu.uni.tsopen.symbolicExecution.symbolicValues.ObjectValue;
import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue;
import lu.uni.tsopen.utils.Constants;
import soot.SootMethod;
import soot.Value;
import soot.jimple.DefinitionStmt;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
public class SmsRecognition extends TypeRecognitionHandler {
private SmsMethodsRecognitionHandler smrh;
public SmsRecognition(TypeRecognitionHandler next, SymbolicExecution se, InfoflowCFG icfg) {
super(next, se, icfg);
this.authorizedTypes.add(Constants.ANDROID_TELEPHONY_SMSMESSAGE);
this.smrh = new CreateFromPduRecognition(null, se);
}
@Override
public void handleConstructorTag(List<Value> args, ObjectValue object) {}
@Override
public List<Pair<Value, SymbolicValue>> handleDefinitionStmt(DefinitionStmt defUnit) {
Value leftOp = defUnit.getLeftOp(),
rightOp = defUnit.getRightOp();
List<Pair<Value, SymbolicValue>> results = new LinkedList<Pair<Value,SymbolicValue>>();
StaticInvokeExpr rightOpStaticInvokeExpr = null;
SootMethod method = null;
List<Value> args = null;
ObjectValue object = null;
if(rightOp instanceof StaticInvokeExpr) {
rightOpStaticInvokeExpr = (StaticInvokeExpr) rightOp;
method = rightOpStaticInvokeExpr.getMethod();
args = rightOpStaticInvokeExpr.getArgs();
object = new ObjectValue(method.getDeclaringClass().getType(), args, this.se);
this.smrh.recognizeSmsMethod(method, object);
results.add(new Pair<Value, SymbolicValue>(leftOp, object));
}
return results;
}
@Override
public void handleInvokeTag(List<Value> args, Value base, SymbolicValue object, SootMethod method) {}
}
| 3,137 | 35.917647 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/symbolicValues/ConcreteValue.java | package lu.uni.tsopen.symbolicExecution.symbolicValues;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
public abstract class ConcreteValue extends AbstractSymbolicValue {
public ConcreteValue(SymbolicExecution se) {
super(se);
}
@Override
public boolean isSymbolic() {
return false;
}
@Override
public boolean isMethodRepresentation() {
return false;
}
}
| 1,434 | 28.285714 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/symbolicValues/ConstantValue.java | package lu.uni.tsopen.symbolicExecution.symbolicValues;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import soot.jimple.Constant;
public class ConstantValue extends ConcreteValue {
private Constant constant;
public ConstantValue(Constant c, SymbolicExecution se) {
super(se);
this.constant = c;
}
@Override
public String getValue() {
return this.constant.toString().replace("\"", "").replace("\\", "");
}
@Override
public boolean isConstant() {
return true;
}
@Override
public boolean isObject() {
return false;
}
public Constant getConstant() {
return this.constant;
}
}
| 1,668 | 25.919355 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/symbolicValues/ObjectValue.java | package lu.uni.tsopen.symbolicExecution.symbolicValues;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import soot.Type;
import soot.Value;
public class ObjectValue extends ConcreteValue {
private Type type;
private List<Value> args;
public ObjectValue(Type t, List<Value> args, SymbolicExecution se) {
super(se);
this.type = t;
this.args = args == null ? new ArrayList<Value>() : args;
}
@Override
public String getValue() {
return String.format("%s(%s)", this.type, this.computeArgs());
}
private String computeArgs() {
String args = "";
List<SymbolicValue> values = null;
for(Value arg : this.args) {
values = this.getSymbolicValues(arg);
if(values != null) {
for(SymbolicValue sv : values) {
args += sv;
if(sv != values.get(values.size() - 1)) {
args += " | ";
}
}
}else {
args += arg.getType();
}
if(arg != this.args.get(this.args.size() - 1)) {
args += ", ";
}
}
return args;
}
@Override
public boolean isConstant() {
return false;
}
@Override
public boolean isObject() {
return true;
}
}
| 2,207 | 24.674419 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/symbolicValues/BinOpValue.java | package lu.uni.tsopen.symbolicExecution.symbolicValues;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import soot.Value;
public class BinOpValue extends AbstractSymbolicValue {
private Value op1;
private Value op2;
private String symbol;
public BinOpValue(SymbolicExecution se, Value op1, Value op2, String symbol) {
super(se);
this.op1 = op1;
this.op2 = op2;
this.symbol = symbol;
if(this.op1 != null) {
this.values.put(this.op1, this.getSymbolicValues(this.op1));
}
if(this.op2 != null) {
this.values.put(this.op2, this.getSymbolicValues(this.op2));
}
}
@Override
public String getValue() {
return String.format("%s%s%s", this.computeValue(this.op1), this.symbol, this.computeValue(this.op2));
}
@Override
public boolean isSymbolic() {
return true;
}
@Override
public boolean isConstant() {
return false;
}
@Override
public boolean isMethodRepresentation() {
return false;
}
@Override
public boolean isObject() {
return false;
}
public Value getOp1() {
return this.op1;
}
public Value getOp2() {
return this.op2;
}
}
| 2,151 | 24.023256 | 104 | java |
TSOpen | TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/symbolicValues/MethodRepresentationValue.java | package lu.uni.tsopen.symbolicExecution.symbolicValues;
/*-
* #%L
* TSOpen - Open-source implementation of TriggerScope
*
* Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf
*
* %%
* Copyright (C) 2019 Jordan Samhi
* University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import lu.uni.tsopen.symbolicExecution.SymbolicExecution;
import soot.SootMethod;
import soot.Value;
import soot.jimple.Constant;
public class MethodRepresentationValue extends AbstractSymbolicValue {
private Value base;
private List<Value> args;
private SootMethod method;
public MethodRepresentationValue(Value b, List<Value> a, SootMethod m, SymbolicExecution se) {
super(se);
this.method = m;
this.base = b;
this.args = a;
if(this.base != null) {
this.values.put(this.base, this.getSymbolicValues(this.base));
}
for(Value arg : this.args) {
if(!(arg instanceof Constant)) {
this.values.put(arg, this.getSymbolicValues(arg));
}
}
}
@Override
public String getValue() {
String value = "(";
if(this.base != null) {
value += this.computeValue(this.base);
value += ".";
}
value += this.method.getName();
value += "(";
for(Value arg : this.args) {
value += this.computeValue(arg);
if(arg != this.args.get(this.args.size() - 1)) {
value += ", ";
}
}
value += "))";
return value;
}
@Override
public boolean isSymbolic() {
return false;
}
@Override
public boolean isConstant() {
return false;
}
@Override
public boolean isMethodRepresentation() {
return true;
}
@Override
public boolean isObject() {
return false;
}
@Override
public Value getBase() {
return this.base;
}
public List<Value> getArgs() {
return this.args;
}
}
| 2,563 | 22.740741 | 104 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.