file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
BaseX.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/tools/BaseX.java | package com.referendum.tools;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* allows you to convert a whole number into a compacted representation of that number,
* based upon the dictionary you provide. very similar to base64 encoding, or indeed hex
* encoding.
*/
public class BaseX {
/**
* contains hexadecimals 0-F only.
*/
public static final char[] DICTIONARY_16 =
new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
/**
* contains only alphanumerics, in capitals and excludes letters/numbers which can be confused,
* eg. 0 and O or L and I and 1.
*/
public static final char[] DICTIONARY_32 =
new char[]{'1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','M','N','P','Q','R','S','T','U','V','W','X','Y','Z'};
/**
* contains only alphanumerics, including both capitals and smalls.
*/
public static final char[] DICTIONARY_62 =
new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
/**
* contains alphanumerics, including both capitals and smalls, and the following special chars:
* +"@*#%&/|()=?'~[!]{}-_:.,; (you might not be able to read all those using a browser!
*/
public static final char[] DICTIONARY_89 =
new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','+','"','@','*','#','%','&','/','|','(',')','=','?','~','[',']','{','}','$','-','_','.',':',',',';','<','>'};
protected char[] dictionary;
/**
* create an encoder with the given dictionary.
*
* @param dictionary the dictionary to use when encoding and decoding.
*/
public BaseX(char[] dictionary){
this.dictionary = dictionary;
}
/**
* creates an encoder with the {@link #DICTIONARY_62} dictionary.
*
* @param dictionary the dictionary to use when encoding and decoding.
*/
public BaseX(){
this.dictionary = DICTIONARY_62;
}
/**
* tester method.
*/
public static void main(String[] args) {
String original = "123456789012345678901234567890";
System.out.println("Original: " + original);
BaseX bx = new BaseX(DICTIONARY_62);
String encoded = bx.encode(new BigInteger(original));
System.out.println("encoded: " + encoded);
BigInteger decoded = bx.decode(encoded);
System.out.println("decoded: " + decoded);
if(original.equals(decoded.toString())){
System.out.println("Passed! decoded value is the same as the original.");
}else{
System.err.println("FAILED! decoded value is NOT the same as the original!!");
}
}
/**
* encodes the given string into the base of the dictionary provided in the constructor.
* @param value the number to encode.
* @return the encoded string.
*/
public String encode(BigInteger value) {
List<Character> result = new ArrayList<Character>();
BigInteger base = new BigInteger("" + dictionary.length);
int exponent = 1;
BigInteger remaining = value;
while(true){
BigInteger a = base.pow(exponent); //16^1 = 16
BigInteger b = remaining.mod(a); //119 % 16 = 7 | 112 % 256 = 112
BigInteger c = base.pow(exponent - 1);
BigInteger d = b.divide(c);
//if d > dictionary.length, we have a problem. but BigInteger doesnt have
//a greater than method :-( hope for the best. theoretically, d is always
//an index of the dictionary!
result.add(dictionary[d.intValue()]);
remaining = remaining.subtract(b); //119 - 7 = 112 | 112 - 112 = 0
//finished?
if(remaining.equals(BigInteger.ZERO)){
break;
}
exponent++;
}
//need to reverse it, since the start of the list contains the least significant values
StringBuffer sb = new StringBuffer();
for(int i = result.size()-1; i >= 0; i--){
sb.append(result.get(i));
}
return sb.toString();
}
/**
* decodes the given string from the base of the dictionary provided in the constructor.
* @param str the string to decode.
* @return the decoded number.
*/
public BigInteger decode(String str) {
//reverse it, coz its already reversed!
char[] chars = new char[str.length()];
str.getChars(0, str.length(), chars, 0);
char[] chars2 = new char[str.length()];
int i = chars2.length -1;
for(char c : chars){
chars2[i--] = c;
}
//for efficiency, make a map
Map<Character, BigInteger> dictMap = new HashMap<Character, BigInteger>();
int j = 0;
for(char c : dictionary){
dictMap.put(c, new BigInteger("" + j++));
}
BigInteger bi = BigInteger.ZERO;
BigInteger base = new BigInteger("" + dictionary.length);
int exponent = 0;
for(char c : chars2){
BigInteger a = dictMap.get(c);
BigInteger b = base.pow(exponent).multiply(a);
bi = bi.add(new BigInteger("" + b));
exponent++;
}
return bi;
}
}
| 5,329 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
ScriptRunner.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/tools/ScriptRunner.java | package com.referendum.tools;
/*
* Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class
* from the iBATIS Apache project. Only removed dependency on Resource class
* and a constructor
* GPSHansl, 06.08.2015: regex for delimiter, rearrange comment/delimiter detection, remove some ide warnings.
*/
/*
* Copyright 2004 Clinton Begin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Tool to run database scripts
*/
public class ScriptRunner {
private static final String DEFAULT_DELIMITER = ";";
/**
* regex to detect delimiter.
* ignores spaces, allows delimiter in comment, allows an equals-sign
*/
public static final Pattern delimP = Pattern.compile("^\\s*(--)?\\s*delimiter\\s*=?\\s*([^\\s]+)+\\s*.*$", Pattern.CASE_INSENSITIVE);
private final Connection connection;
private final boolean stopOnError;
private final boolean autoCommit;
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private PrintWriter logWriter = new PrintWriter(System.out);
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private PrintWriter errorLogWriter = new PrintWriter(System.err);
private String delimiter = DEFAULT_DELIMITER;
private boolean fullLineDelimiter = false;
/**
* Default constructor
*/
public ScriptRunner(Connection connection, boolean autoCommit,
boolean stopOnError) {
this.connection = connection;
this.autoCommit = autoCommit;
this.stopOnError = stopOnError;
}
public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
this.delimiter = delimiter;
this.fullLineDelimiter = fullLineDelimiter;
}
/**
* Setter for logWriter property
*
* @param logWriter - the new value of the logWriter property
*/
public void setLogWriter(PrintWriter logWriter) {
this.logWriter = logWriter;
}
/**
* Setter for errorLogWriter property
*
* @param errorLogWriter - the new value of the errorLogWriter property
*/
public void setErrorLogWriter(PrintWriter errorLogWriter) {
this.errorLogWriter = errorLogWriter;
}
/**
* Runs an SQL script (read in using the Reader parameter)
*
* @param reader - the source of the script
*/
public void runScript(Reader reader) throws IOException, SQLException {
try {
boolean originalAutoCommit = connection.getAutoCommit();
try {
if (originalAutoCommit != this.autoCommit) {
connection.setAutoCommit(this.autoCommit);
}
runScript(connection, reader);
} finally {
connection.setAutoCommit(originalAutoCommit);
}
} catch (IOException | SQLException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error running script. Cause: " + e, e);
}
}
/**
* Runs an SQL script (read in using the Reader parameter) using the
* connection passed in
*
* @param conn - the connection to use for the script
* @param reader - the source of the script
* @throws SQLException if any SQL errors occur
* @throws IOException if there is an error reading from the Reader
*/
private void runScript(Connection conn, Reader reader) throws IOException,
SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
final Matcher delimMatch = delimP.matcher(trimmedLine);
if (trimmedLine.length() < 1
|| trimmedLine.startsWith("//")) {
// Do nothing
} else if (delimMatch.matches()) {
setDelimiter(delimMatch.group(2), false);
} else if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter
&& trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter
&& trimmedLine.equals(getDelimiter())) {
command.append(line.substring(0, line
.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
try {
hasResults = statement.execute(command.toString());
} catch (SQLException e) {
final String errText = String.format("Error executing '%s' (line %d): %s", command, lineReader.getLineNumber(), e.getMessage());
if (stopOnError) {
throw new SQLException(errText, e);
} else {
println(errText);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 0; i < cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
statement.close();
} catch (Exception e) {
// Ignore to workaround a bug in Jakarta DBCP
}
} else {
command.append(line);
command.append("\n");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (Exception e) {
throw new IOException(String.format("Error executing '%s': %s", command, e.getMessage()), e);
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private void print(Object o) {
if (logWriter != null) {
System.out.print(o);
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}
}
| 8,592 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
VotingSystem.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/voting_system/VotingSystem.java | package com.referendum.voting.voting_system;
public interface VotingSystem {
enum VotingSystemType {
MULTIPLE_CHOICE, SINGLE_CHOICE;
}
abstract VotingSystemType getVotingSystemType();
}
| 196 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
UnrankedVotingSystem.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/voting_system/rank_type/UnrankedVotingSystem.java | package com.referendum.voting.voting_system.rank_type;
import com.referendum.voting.voting_system.choice_type.MultipleChoiceVotingSystem;
import com.referendum.voting.voting_system.choice_type.MultipleChoiceVotingSystem.MultipleChoiceVotingSystemType;
public interface UnrankedVotingSystem extends MultipleChoiceVotingSystem {
@Override
default MultipleChoiceVotingSystemType getMultipleChoiceVotingSystemType() {
return MultipleChoiceVotingSystemType.UNRANKED;
}
}
| 476 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
RankedVotingSystem.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/voting_system/rank_type/RankedVotingSystem.java | package com.referendum.voting.voting_system.rank_type;
import com.referendum.voting.voting_system.choice_type.MultipleChoiceVotingSystem;
import com.referendum.voting.voting_system.choice_type.MultipleChoiceVotingSystem.MultipleChoiceVotingSystemType;
public interface RankedVotingSystem extends MultipleChoiceVotingSystem {
enum RankedVotingSystemType {
STV, IRV;
}
RankedVotingSystemType getRankedVotingSystemType();
default MultipleChoiceVotingSystemType getMultipleChoiceVotingSystemType() {
return MultipleChoiceVotingSystemType.RANKED;
}
}
| 565 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
RangeVotingSystem.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/voting_system/choice_type/RangeVotingSystem.java | package com.referendum.voting.voting_system.choice_type;
import com.referendum.voting.voting_system.VotingSystem;
public interface RangeVotingSystem extends VotingSystem {
public enum RangeVotingSystemType {
AVERAGE, MEDIAN, NORMALIZED;
}
RangeVotingSystemType getRangeVotingSystemType();
default VotingSystemType getVotingSystemType() {
return VotingSystemType.MULTIPLE_CHOICE;
}
}
| 401 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
MultipleChoiceVotingSystem.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/voting_system/choice_type/MultipleChoiceVotingSystem.java | package com.referendum.voting.voting_system.choice_type;
import com.referendum.voting.voting_system.VotingSystem;
import com.referendum.voting.voting_system.VotingSystem.VotingSystemType;
public interface MultipleChoiceVotingSystem extends VotingSystem {
enum MultipleChoiceVotingSystemType {
UNRANKED, RANKED;
}
MultipleChoiceVotingSystemType getMultipleChoiceVotingSystemType();
default VotingSystemType getVotingSystemType() {
return VotingSystemType.MULTIPLE_CHOICE;
}
}
| 500 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
SingleChoiceVotingSystem.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/voting_system/choice_type/SingleChoiceVotingSystem.java | package com.referendum.voting.voting_system.choice_type;
import com.referendum.voting.voting_system.VotingSystem;
import com.referendum.voting.voting_system.VotingSystem.VotingSystemType;
public interface SingleChoiceVotingSystem extends VotingSystem {
enum SingleChoiceVotingSystemType {
FPTP;
}
SingleChoiceVotingSystemType getSingleChoiceVotingSystemType();
default VotingSystemType getVotingSystemType() {
return VotingSystemType.SINGLE_CHOICE;
}
}
| 473 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
RangeBallot.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/ballot/RangeBallot.java | package com.referendum.voting.ballot;
import com.referendum.voting.candidate.RangeCandidate;
public class RangeBallot implements Ballot {
private RangeCandidate candidate;
public RangeBallot(RangeCandidate candidate) {
this.candidate = candidate;
}
public RangeCandidate getCandidate() {
return candidate;
}
}
| 323 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
Ballot.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/ballot/Ballot.java | package com.referendum.voting.ballot;
import java.util.List;
import com.referendum.voting.candidate.RankedCandidate;
public interface Ballot {
}
| 152 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
RankedBallot.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/ballot/RankedBallot.java | package com.referendum.voting.ballot;
import java.util.Collections;
import java.util.List;
import com.referendum.voting.candidate.RankedCandidate;
import com.referendum.voting.candidate.RankedCandidate.RankedCandidateComparator;
public class RankedBallot implements Ballot {
private List<RankedCandidate> rankings;
public RankedBallot(List<RankedCandidate> rankings) {
this.rankings = rankings;
Collections.sort(this.rankings, new RankedCandidateComparator());
}
public List<RankedCandidate> getRankings() {
return rankings;
}
}
| 552 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
RangeCandidateResult.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/candidate/RangeCandidateResult.java | package com.referendum.voting.candidate;
import java.util.Comparator;
public class RangeCandidateResult implements Candidate {
private Integer id, count;
private Double score;
public RangeCandidateResult(Integer id, Double score, Integer count) {
this.id = id;
this.score = score;
this.count = count;
}
@Override
public Integer getId() {
return id;
}
@Override public String toString() {
return id.toString();
}
public Double getScore() {
return score;
}
public Integer getCount() {
return count;
}
public static class RangeCandidateResultComparator implements Comparator<RangeCandidateResult> {
@Override
public int compare(RangeCandidateResult o1, RangeCandidateResult o2) {
return o1.getScore().compareTo(o2.getScore());
}
}
}
| 786 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
RankedCandidate.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/candidate/RankedCandidate.java | package com.referendum.voting.candidate;
import java.util.Comparator;
public class RankedCandidate implements Candidate {
private Integer id, rank;
public RankedCandidate(Integer id, Integer rank) {
this.id = id;
this.rank = rank;
}
@Override
public Integer getId() {
return id;
}
@Override public String toString() {
return id.toString();
}
public Integer getRank() {
return rank;
}
public static class RankedCandidateComparator implements Comparator<RankedCandidate> {
@Override
public int compare(RankedCandidate o1, RankedCandidate o2) {
return o1.getRank().compareTo(o2.getRank());
}
}
}
| 643 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
RangeCandidate.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/candidate/RangeCandidate.java | package com.referendum.voting.candidate;
import java.util.Comparator;
public class RangeCandidate implements Candidate {
private Integer id;
private Double rank;
public RangeCandidate(Integer id, Double rank) {
this.id = id;
this.rank = rank;
}
@Override
public Integer getId() {
return id;
}
@Override public String toString() {
return id.toString();
}
public Double getRank() {
return rank;
}
public static class RangeCandidateComparator implements Comparator<RangeCandidate> {
@Override
public int compare(RangeCandidate o1, RangeCandidate o2) {
return o1.getRank().compareTo(o2.getRank());
}
}
}
| 650 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
Election.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/election/Election.java | package com.referendum.voting.election;
public interface Election {
Integer getId();
void runElection();
}
| 119 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
ElectionRoundItem.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/election/ElectionRoundItem.java | package com.referendum.voting.election;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import com.referendum.voting.candidate.RankedCandidate;
public class ElectionRoundItem {
public enum Status {
STAYS, DEFEATED, ELECTED, ELECTED_PREVIOUSLY;
}
private Status status = Status.STAYS;
private RankedCandidate candidate;
private Integer votes;
public Map<Integer, DistributedVote> distributedVotes;
public static class DistributedVote {
private Integer votes, candidateId;
public DistributedVote(Integer candidateId) {
votes = 1;
this.candidateId = candidateId;
}
public void addVote() {
votes++;
}
}
public ElectionRoundItem(RankedCandidate candidate) {
this.candidate = candidate;
votes = 0;
distributedVotes = new HashMap<>();
}
public void addVote() {
votes++;
}
public Integer getVotes() {
return votes;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public RankedCandidate getCandidate() {
return candidate;
}
public void addVotes(Integer votes) {
this.votes += votes;
}
public static class ElectionRoundItemComparator implements Comparator<ElectionRoundItem> {
@Override
public int compare(ElectionRoundItem o1, ElectionRoundItem o2) {
return o1.getCandidate().getId().compareTo(o2.getCandidate().getId());
}
}
}
| 1,432 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
RangeElection.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/election/RangeElection.java | package com.referendum.voting.election;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.referendum.voting.ballot.RangeBallot;
import com.referendum.voting.candidate.RangeCandidate;
import com.referendum.voting.candidate.RangeCandidateResult;
import com.referendum.voting.results.RangeElectionResults;
import com.referendum.voting.voting_system.choice_type.RangeVotingSystem;
import static com.referendum.voting.candidate.RangeCandidateResult.RangeCandidateResultComparator;
public class RangeElection implements RangeVotingSystem, RangeElectionResults {
static final Logger log = LoggerFactory.getLogger(RangeElection.class);
public RangeVotingSystemType type;
public List<RangeBallot> ballots;
public List<RangeCandidateResult> rankings;
public Integer id;
public Integer minimumPctThreshold;
// A helpful map of candidates ids to ballots
Map<Integer, List<RangeCandidate>> candidateBallots;
public RangeElection(Integer id, RangeVotingSystemType type, List<RangeBallot> ballots,
Integer minimumPctThreshold) {
this.id = id;
this.type = type;
this.ballots = ballots;
this.minimumPctThreshold = minimumPctThreshold;
runElection();
}
/**
* This ones simple, just organize by each candidate vote, then create a new RangeCandidate
* to do the rankings
*/
@Override
public void runElection() {
fillCandidateBallotsMap();
calculateScoreForEachCandidate();
}
public void fillCandidateBallotsMap() {
candidateBallots = new HashMap<>();
for (RangeBallot ballot : ballots) {
RangeCandidate candidate = ballot.getCandidate();
if (candidateBallots.get(candidate.getId()) == null) {
List<RangeCandidate> candidateList = new ArrayList<>();
candidateList.add(candidate);
candidateBallots.put(candidate.getId(), candidateList);
} else {
candidateBallots.get(candidate.getId()).add(candidate);
}
}
}
public void calculateScoreForEachCandidate() {
// Loop over all the individual grouped candidates, and find the score
rankings = new ArrayList<>();
// The highest number of ballots for any candidate
Integer maxVotes = 0;
for (Entry<Integer, List<RangeCandidate>> candidateGrouped : candidateBallots.entrySet()) {
Integer count = candidateGrouped.getValue().size();
if (count >= maxVotes) {
maxVotes = count;
}
}
Integer threshold = (maxVotes * minimumPctThreshold / 100);
log.debug("vote count threshold = " + threshold);
for (Entry<Integer, List<RangeCandidate>> candidateGrouped : candidateBallots.entrySet()) {
Double score = null;
// Add the integers to a collection
List<Double> ints = new ArrayList<>();
for (RangeCandidate rc : candidateGrouped.getValue()) {
ints.add(rc.getRank());
}
if (type == RangeVotingSystemType.AVERAGE) {
score = average(ints);
} else if (type == RangeVotingSystemType.MEDIAN) {
score = median(ints);
}
Integer count = candidateGrouped.getValue().size();
RangeCandidateResult result = new RangeCandidateResult(candidateGrouped.getKey(),
score, count);
log.debug("candidate = " + candidateGrouped.getKey() + " , vote count = " + count);
if (count >= threshold) {
rankings.add(result);
}
}
Collections.sort(rankings, new RangeCandidateResultComparator().reversed());
}
public Double median(List<Double> ints) {
Collections.sort(ints);
int middle = ints.size() / 2;
Double median;
if (ints.size() % 2 == 1) {
median = (double) ints.get(middle);
} else {
median = (double) (ints.get(middle - 1) + ints.get(middle)) / 2;
}
return median;
}
public Double average(List<Double> ints) {
Double sum = 0.0, count = 0.0;
for (Double i : ints) {
sum += i;
count++;
}
Double avg = (double) (sum / count);
return avg;
}
@Override
public List<RangeCandidateResult> getRankings() {
return rankings;
}
@Override
public Integer getId() {
return id;
}
@Override
public RangeVotingSystemType getRangeVotingSystemType() {
return type;
}
@Override
public ElectionResultsType getElectionResultsType() {
return ElectionResultsType.MULTIPLE_WINNER;
}
}
| 4,318 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
FPTPElection.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/election/FPTPElection.java | package com.referendum.voting.election;
import com.referendum.voting.voting_system.choice_type.SingleChoiceVotingSystem;
public interface FPTPElection extends SingleChoiceVotingSystem {
@Override
default SingleChoiceVotingSystemType getSingleChoiceVotingSystemType() {
return SingleChoiceVotingSystemType.FPTP;
}
}
| 326 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
STVElection.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/election/STVElection.java | package com.referendum.voting.election;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.referendum.tools.Tools;
import com.referendum.voting.ballot.RankedBallot;
import com.referendum.voting.candidate.Candidate;
import com.referendum.voting.candidate.RankedCandidate;
import com.referendum.voting.election.ElectionRoundItem.DistributedVote;
import com.referendum.voting.election.ElectionRoundItem.Status;
import com.referendum.voting.results.MultipleWinnerElectionResults;
import com.referendum.voting.voting_system.rank_type.RankedVotingSystem;
public class STVElection implements MultipleWinnerElectionResults, RankedVotingSystem {
static final Logger log = LoggerFactory.getLogger(STVElection.class);
public enum Quota {
HARE, DROOP;
}
public Quota quota;
public List<RankedBallot> ballots;
public List<ElectionRound> electionRounds;
public Integer seats, votePool, roundNumber = 0;
// A helpful map of candidates ids to ballots
Map<Integer, List<RankedBallot>> candidateBallots;
// A helpful map from rounds to candidates to round items
// IE [round 0, candidate 1, [status, votes, etc]]
Map<Integer, Map<Integer, ElectionRoundItem>> roundToCandidateToItem;
Map<Integer, RankedCandidate> candidateIdToCandidate = new HashMap<>();
public STVElection(Quota quota, List<RankedBallot> ballots, Integer seats) {
this.quota = quota;
this.ballots = ballots;
this.seats = seats;
runElection();
}
@Override
public void runElection() {
Integer winners = 0;
electionRounds = new ArrayList<>();
votePool = ballots.size();
fillCandidateMaps();
Integer aliveCandidates = roundToCandidateToItem.get(roundNumber).size();
while (winners < seats) {
log.debug("alive = " + aliveCandidates + " seats = " + seats);
Integer threshold = getThreshold(votePool, seats);
aliveCandidates = roundToCandidateToItem.get(roundNumber).size();
// log.debug("candidate ballots total: " + Tools.GSON2.toJson(candidateBallots));
List<ElectionRoundItem> roundItems = new ArrayList<>();
ElectionRound er = new ElectionRound(roundItems, threshold);
electionRounds.add(er);
Boolean areWinners = false;
log.debug("treshold = " + threshold);
// Now you have all the ballots round counted, now do the rules
for (Entry<Integer, ElectionRoundItem> e : roundToCandidateToItem.get(roundNumber).entrySet()) {
Integer cCandidateId = e.getKey();
RankedCandidate cCandidate = candidateIdToCandidate.get(cCandidateId);
ElectionRoundItem eri = e.getValue();
Integer votes = eri.getVotes();
// Check to see if they win
if (votes >= threshold && !eri.getStatus().equals(Status.ELECTED_PREVIOUSLY)) {
log.debug("Candidate: " + cCandidate.getId() + " won with " + votes + "/" + threshold);
eri.setStatus(Status.ELECTED);
Integer surplusVotes = votes - threshold;
// Loop over the ballots in order, if they have that for the current round,
// then add that surplus to their next hopeful
for (int i = 0; i < surplusVotes; i++) {
RankedBallot ballot = candidateBallots.get(cCandidate.getId()).get(i);
distributeVote(roundNumber, cCandidate, ballot);
}
// If next preference doesn't exist, then eliminate those votes from the pool
winners++;
areWinners = true;
}
if (eri.getStatus() == Status.ELECTED || eri.getStatus() == Status.ELECTED_PREVIOUSLY) {
// Add their ERI to the next round, but with only the threshold votes:
// Fill it if its empty.
// This stuff adds the elected to the next round
ElectionRoundItem newEri = new ElectionRoundItem(cCandidate);
newEri.setStatus(Status.ELECTED_PREVIOUSLY);
newEri.addVotes(threshold);
if (roundToCandidateToItem.get(roundNumber+1) == null) {
HashMap<Integer, ElectionRoundItem> eriMap = new HashMap<Integer, ElectionRoundItem>();
// log.debug(distributedToCandidate.getId().toString());
eriMap.put(cCandidate.getId(), newEri);
roundToCandidateToItem.put(roundNumber+1, eriMap);
}
if (roundToCandidateToItem.get(roundNumber+1).get(cCandidate.getId()) == null) {
roundToCandidateToItem.get(roundNumber+1).put(cCandidate.getId(), newEri);
}
}
roundItems.add(eri);
}
// If there were no winners after those were counted, then eliminate the lowest, and distribute them
log.debug("winners2 = " + winners + " seats = " + seats);
if (!areWinners && winners < seats) {
log.debug("No Winners");
RankedCandidate eliminatedCandidate = null;
Integer maxVotes = Integer.MAX_VALUE;
// Find the candidate with the lowest votes
for (Entry<Integer, ElectionRoundItem> e : roundToCandidateToItem.get(roundNumber).entrySet()) {
Integer cVotes = e.getValue().getVotes();
if (cVotes < maxVotes) {
Integer eliminatedCandidateId = e.getKey();
eliminatedCandidate = candidateIdToCandidate.get(eliminatedCandidateId);
maxVotes = e.getValue().getVotes();
log.debug("maxVotes = " + maxVotes + "elim = " + eliminatedCandidate.getId());
}
}
// Set them as defeated
log.debug("round # " + roundNumber + " eliminatedCandidate = " + eliminatedCandidate.getId());
roundToCandidateToItem.get(roundNumber).get(eliminatedCandidate.getId()).setStatus(Status.DEFEATED);
log.debug("Candidate " + eliminatedCandidate.getId() + " defeated");
// Transfer their votes to their next choice
// should've transferred ballots previously
// If that candidate received no first-choice votes, then remove them from the pool
// only transfer the votes if the eliminated candidate was one of those ranked
if (candidateBallots.get(eliminatedCandidate.getId()) == null) {
votePool -= 1; // TODO not sure about this
log.debug("Candidate " + eliminatedCandidate.getId() + " had no first choice votes\n"
+ "vote pool = " + votePool);
} else {
for (RankedBallot ballot : candidateBallots.get(eliminatedCandidate.getId())) {
distributeVote(roundNumber, eliminatedCandidate, ballot);
}
}
}
transferVotesToNextRound();
roundNumber++;
}
// Set the remaining candidates as a winners or losers(not stays)
for (Entry<Integer, ElectionRoundItem> e : roundToCandidateToItem.get(roundNumber-1).entrySet()) {
log.debug("winners = " + winners + " alive = " + aliveCandidates + " seats " +
seats + " status = " + e.getValue().getStatus());
if (e.getValue().getStatus() == Status.STAYS) {
if (winners < seats) {
e.getValue().setStatus(Status.ELECTED);
} else {
e.getValue().setStatus(Status.DEFEATED);
}
}
// log.debug("winners = " + winners + " alive = " + aliveCandidates + " seats " +
// seats + " status = " + e.getValue().getStatus());
// if (winners <= seats && e.getValue().getStatus() == Status.STAYS) {
// e.getValue().setStatus(Status.ELECTED);
// } else {
// e.getValue().setStatus(Status.DEFEATED);
// }
}
}
private void distributeVote(
int roundNumber,
RankedCandidate candidate,
RankedBallot ballot) {
ElectionRoundItem eri = roundToCandidateToItem.get(roundNumber).get(candidate.getId());
// log.debug("round number = " + roundNumber + " ballot rankings size = " + ballot.getRankings().size());
// log.debug(Tools.GSON2.toJson(ballot));
log.debug("ballot ranking size = " + ballot.getRankings().size());
// add those excess votes to the first alive choice on their ballot
RankedCandidate distributedToCandidate = findNextRankedCandidateOnBallot(
roundNumber, ballot);
// If it couldn't find a next ranked candidate, subtract from the voting pool
if (distributedToCandidate == null) {
votePool -= 1;
log.debug("Couldn't distributed because no next candidate, vote pool now = " + votePool);
}
// distributed candidate is still in race
else {
// Fill it if its empty
if (roundToCandidateToItem.get(roundNumber+1) == null) {
ElectionRoundItem newEri = new ElectionRoundItem(distributedToCandidate);
HashMap<Integer, ElectionRoundItem> eriMap = new HashMap<Integer, ElectionRoundItem>();
// log.debug(distributedToCandidate.getId().toString());
eriMap.put(distributedToCandidate.getId(), newEri);
roundToCandidateToItem.put(roundNumber+1, eriMap);
}
if (roundToCandidateToItem.get(roundNumber+1).get(distributedToCandidate.getId()) == null) {
ElectionRoundItem newEri = new ElectionRoundItem(distributedToCandidate);
roundToCandidateToItem.get(roundNumber+1).put(distributedToCandidate.getId(), newEri);
}
if (eri.distributedVotes.get(distributedToCandidate.getId()) == null) {
log.debug("First distributed vote from " + eri.getCandidate().getId() +
" to " + distributedToCandidate.getId());
DistributedVote dv = new DistributedVote(distributedToCandidate.getId());
eri.distributedVotes.put(distributedToCandidate.getId(), dv);
} else {
log.debug("distributed vote from " + eri.getCandidate().getId() +
" to " + distributedToCandidate.getId());
eri.distributedVotes.get(distributedToCandidate.getId()).addVote();
}
// Add the vote
roundToCandidateToItem.get(roundNumber + 1).get(distributedToCandidate.getId()).addVote();
// Also distribute the ballot over
addToCandidateBallots(ballot, distributedToCandidate);
// log.debug("Distributed next eri = "
// + Tools.GSON2.toJson(roundToCandidateToItem.get(roundNumber + 1).
// get(distributedToCandidate.getId())));
// log.debug(Tools.GSON2.toJson(eri));
}
}
private RankedCandidate findNextRankedCandidateOnBallot(int roundNumber,
RankedBallot ballot) {
RankedCandidate distributedToCandidate = null;
for (RankedCandidate candidateOption : ballot.getRankings()) {
ElectionRoundItem optionERI = roundToCandidateToItem.get(roundNumber).get(candidateOption.getId());
// log.debug("candidate option = " + Tools.GSON2.toJson(optionERI));
if (optionERI != null && optionERI.getStatus() == Status.STAYS) {
distributedToCandidate = candidateOption;
break;
}
}
return distributedToCandidate;
}
private void transferVotesToNextRound() {
// Create the next round
if (roundToCandidateToItem.get(roundNumber + 1) == null) {
roundToCandidateToItem.put(roundNumber + 1, new HashMap<>());
}
for (Entry<Integer, ElectionRoundItem> e : roundToCandidateToItem.get(roundNumber).entrySet()) {
Integer candidateId = e.getKey();
ElectionRoundItem eri = e.getValue();
// Only transfer the candidates still in the race,
// and if they haven't been distributed already
if (eri.getStatus() == Status.STAYS) {
ElectionRoundItem nextERI = roundToCandidateToItem.get(roundNumber + 1).get(candidateId);
// log.debug("transferred eri to next round = " + Tools.GSON2.toJson(eri));
if (nextERI == null) {
ElectionRoundItem newERI = new ElectionRoundItem(candidateIdToCandidate.get(candidateId));
newERI.addVotes(eri.getVotes());
roundToCandidateToItem.get(roundNumber + 1).put(candidateId, newERI);
} else {
roundToCandidateToItem.get(roundNumber + 1).get(candidateId).addVotes(eri.getVotes());
}
}
}
log.debug("round to candidate items: " + Tools.GSON2.toJson(roundToCandidateToItem.get(roundNumber)));
}
private void fillCandidateMaps() {
// Loop over the ballots
for (RankedBallot cBallot : ballots) {
// Find all the candidates, and add them to a map from candidateId to candidate
for (int i = 0; i < cBallot.getRankings().size(); i++) {
RankedCandidate cCandidate = cBallot.getRankings().get(i);
candidateIdToCandidate.put(cCandidate.getId(), cCandidate);
// Fill the first round maps
if (i == 0) {
addToRoundMap(cCandidate, true);
addToCandidateBallots(cBallot, cCandidate);
} else {
addToRoundMap(cCandidate, false);
}
}
}
}
private void addToRoundMap(RankedCandidate cCandidate, Boolean initialVote) {
ElectionRoundItem eri = new ElectionRoundItem(cCandidate);
if (initialVote) {
eri.addVote();
}
if (roundToCandidateToItem == null) {
roundToCandidateToItem = new HashMap<>();
Map<Integer, ElectionRoundItem> eriMap = new HashMap<>();
eriMap.put(cCandidate.getId(), eri);
roundToCandidateToItem.put(roundNumber, eriMap);
} else {
if (roundToCandidateToItem.get(roundNumber) == null) {
Map<Integer, ElectionRoundItem> eriMap = new HashMap<>();
eriMap.put(cCandidate.getId(), eri);
roundToCandidateToItem.put(roundNumber, eriMap);
} else {
if (roundToCandidateToItem.get(roundNumber).get(cCandidate.getId()) == null) {
log.debug("Creating an election round item for candidate " + cCandidate.getId());
roundToCandidateToItem.get(roundNumber).put(cCandidate.getId(),
eri);
} else {
if (initialVote) {
log.debug("adding a vote for candidate " + cCandidate.getId());
roundToCandidateToItem.get(roundNumber).get(cCandidate.getId()).addVote();
}
}
}
}
}
private void addToCandidateBallots(RankedBallot cBallot,
RankedCandidate cCandidate) {
if (candidateBallots == null) {
candidateBallots = new HashMap<>();
candidateBallots.put(cCandidate.getId(), new ArrayList<>(Arrays.asList(cBallot)));
} else {
if (candidateBallots.get(cCandidate.getId()) == null) {
log.debug("new candidate = " + cCandidate.getId());
List<RankedBallot> ballotList = new ArrayList<>();
ballotList.add(cBallot);
candidateBallots.put(cCandidate.getId(), ballotList);
} else {
candidateBallots.get(cCandidate.getId()).add(cBallot);
}
}
}
@Override
public Integer getThreshold(Integer votes, Integer seats) {
Integer threshold = null;
switch (quota) {
case DROOP :
threshold = (votes/(seats + 1) + 1);
break;
case HARE :
threshold = (votes/seats);
break;
}
return threshold;
}
@Override
public RankedVotingSystemType getRankedVotingSystemType() {
return RankedVotingSystemType.STV;
}
@Override
public Integer getId() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ElectionRound> getRounds() {
return electionRounds;
}
@Override
public List<RankedBallot> getBallots() {
return ballots;
}
}
| 14,661 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
ElectionRound.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/election/ElectionRound.java | package com.referendum.voting.election;
import java.util.Collections;
import java.util.List;
import com.referendum.voting.election.ElectionRoundItem.ElectionRoundItemComparator;
public class ElectionRound {
private List<ElectionRoundItem> electionRoundItems;
private Integer threshold;
public ElectionRound(List<ElectionRoundItem> electionRoundItems, Integer threshold) {
this.electionRoundItems = electionRoundItems;
this.threshold = threshold;
Collections.sort(this.electionRoundItems, new ElectionRoundItemComparator());
}
public List<ElectionRoundItem> getRoundItems() {
return electionRoundItems;
}
public Integer getThreshold() {
return threshold;
}
}
| 704 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
MultipleWinnerElectionResults.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/results/MultipleWinnerElectionResults.java | package com.referendum.voting.results;
import java.util.List;
import com.referendum.voting.ballot.RankedBallot;
import com.referendum.voting.election.ElectionRound;
public interface MultipleWinnerElectionResults extends ElectionResults {
List<ElectionRound> getRounds();
List<RankedBallot> getBallots();
Integer getThreshold(Integer votes, Integer seats);
default ElectionResultsType getElectionResultsType() {
return ElectionResultsType.MULTIPLE_WINNER;
}
}
| 480 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
RangeElectionResults.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/results/RangeElectionResults.java | package com.referendum.voting.results;
import java.util.List;
import com.referendum.voting.candidate.RangeCandidateResult;
public interface RangeElectionResults extends ElectionResults {
List<RangeCandidateResult> getRankings();
default ElectionResultsType getElectionResultsType() {
return ElectionResultsType.MULTIPLE_WINNER;
}
}
| 343 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
ElectionResults.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/voting/results/ElectionResults.java | package com.referendum.voting.results;
import com.referendum.voting.election.Election;
public interface ElectionResults extends Election {
enum ElectionResultsType {
MULTIPLE_WINNER, SINGLE_WINNER;
}
ElectionResultsType getElectionResultsType();
}
| 267 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
DynamicPages.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/webservice/DynamicPages.java | package com.referendum.webservice;
import static spark.Spark.get;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.referendum.DataSources;
import com.referendum.tools.Tools;
public class DynamicPages {
static final Logger log = LoggerFactory.getLogger(API.class);
public static void setup() {
get("poll/:pollId", (req, res) -> {
Tools.allowAllHeaders(req, res);
Tools.set15MinuteCache(req, res);
return Tools.readFile(DataSources.PAGES("poll"));
});
get("private_poll/:pollId", (req, res) -> {
Tools.allowAllHeaders(req, res);
Tools.set15MinuteCache(req, res);
return Tools.readFile(DataSources.PAGES("private_poll"));
});
get("comment/:commentId", (req, res) -> {
Tools.allowAllHeaders(req, res);
Tools.set15MinuteCache(req, res);
return Tools.readFile(DataSources.PAGES("comment"));
});
get("tag/:tagId", (req, res) -> {
Tools.allowAllHeaders(req, res);
Tools.set15MinuteCache(req, res);
return Tools.readFile(DataSources.PAGES("tag"));
});
get("user/:userId", (req, res) -> {
Tools.allowAllHeaders(req, res);
Tools.set15MinuteCache(req, res);
return Tools.readFile(DataSources.PAGES("user"));
});
get("trending_tags", (req, res) -> {
Tools.allowAllHeaders(req, res);
Tools.set15MinuteCache(req, res);
return Tools.readFile(DataSources.PAGES("trending_tags"));
});
get("trending_polls", (req, res) -> {
Tools.allowAllHeaders(req, res);
Tools.set15MinuteCache(req, res);
return Tools.readFile(DataSources.PAGES("trending_polls"));
});
}
}
| 1,646 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
API.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/webservice/API.java | package com.referendum.webservice;
import static spark.Spark.get;
import static spark.Spark.post;
import static spark.Spark.before;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.javalite.activejdbc.LazyList;
import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.Paginator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.Response;
import com.referendum.db.Actions;
import com.referendum.db.Tables.CommentView;
import com.referendum.db.Tables.Poll;
import com.referendum.db.Tables.User;
import com.referendum.db.Tables.UserLoginView;
import com.referendum.tools.SampleData;
import com.referendum.tools.Tools;
import com.referendum.voting.ballot.RankedBallot;
import com.referendum.voting.election.ElectionRound;
import com.referendum.voting.election.STVElection;
import com.referendum.voting.election.STVElection.Quota;
import static com.referendum.db.Tables.*;
import static com.referendum.tools.Tools.ALPHA_ID;
public class API {
static final Logger log = LoggerFactory.getLogger(API.class);
public static void setup() {
// Get the user id
get("get_user", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getOrCreateUserFromCookie(req, res);
return uv.toJson(false);
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("get_user_info/:userAid", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
String userId = ALPHA_ID.decode(req.params(":userAid")).toString();
String json = USER_VIEW.findFirst("id = ?", userId).toJson(false);
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("get_user_comments/:userAid/:pageSize/:startIndex", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Integer commentUserId = ALPHA_ID.decode(req.params(":userAid")).intValue();
Integer pageSize = Integer.valueOf(req.params(":pageSize"));
Integer startIndex = Integer.valueOf(req.params(":startIndex"));
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
Integer pageNum = (startIndex/pageSize)+1;
String json = Actions.fetchUserComments(uv.getInteger("id"),
commentUserId, "created desc", pageNum, pageSize);
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("get_user_messages/:userAid/:pageSize/:startIndex", (req, res) -> {
// TODO needs a lot of work, no pagination...
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Integer parentUserId = ALPHA_ID.decode(req.params(":userAid")).intValue();
Integer pageSize = Integer.valueOf(req.params(":pageSize"));
Integer startIndex = Integer.valueOf(req.params(":startIndex"));
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
Integer pageNum = (startIndex/pageSize)+1;
String json = Actions.fetchUserMessages(
uv.getInteger("id"), parentUserId, "created desc", pageNum, pageSize, null);
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
// Get the user id
get("get_unread_message_count", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
LazyList<CommentView> cvs = Actions.fetchUserMessageList(
uv.getInteger("id"), uv.getInteger("id"), null, null, null, false);
String size = (cvs.size() > 0) ? String.valueOf(cvs.size()) : "";
return size;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/create_empty_poll", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
Map<String, String> vars = Tools.createMapFromAjaxPost(req.body());
String pollId = Actions.createEmptyPoll(uv.getId().toString());
String pollAid = ALPHA_ID.encode(new BigInteger(pollId));
return pollAid;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/save_poll", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
Map<String, String> vars = Tools.createMapFromAjaxPost(req.body());
String subject = vars.get("subject").trim();
String text = (vars.get("poll_text") != null) ? vars.get("poll_text").trim() : null;
String pollId = ALPHA_ID.decode(vars.get("poll_id")).toString();
Boolean private_ = vars.get("public_radio").equals("private");
String password = (private_) ? vars.get("private_password") : null;
String pollSumTypeId = vars.get("sum_type_radio");
Boolean fullUsersOnly = (vars.get("full_users_only") != null) ? true : false;
Timestamp expireTime = (vars.get("expire_time") != null) ? new Timestamp(Tools.DATE_PICKER_FORMAT.parse(vars.get("expire_time")).getTime()) : null ;
Timestamp addCandidatesExpireTime = (vars.get("add_candidates_expire_time") != null) ? new Timestamp(Tools.DATE_PICKER_FORMAT.parse(vars.get("add_candidates_expire_time")).getTime()) : null;
Integer pctThreshold = (vars.get("pct_threshold") != null) ? Integer.valueOf(vars.get("pct_threshold")) : 30;
String message = Actions.savePoll(uv.getId().toString(), pollId,
subject, text, password, pollSumTypeId, fullUsersOnly,
expireTime, addCandidatesExpireTime, pctThreshold, res);
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/unlock_poll", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
Map<String, String> vars = Tools.createMapFromAjaxPost(req.body());
String password = vars.get("password");
String pollId = ALPHA_ID.decode(vars.get("poll_id")).toString();
String message = Actions.unlockPoll(pollId, password, res);
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/delete_poll/:pollId", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
String pollId = ALPHA_ID.decode(req.params(":pollId")).toString();
String message = Actions.deletePoll(uv.getId().toString(), pollId);
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/save_candidate", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
Map<String, String> vars = Tools.createMapFromAjaxPost(req.body());
String subject = vars.get("subject").trim();
String text = (vars.get("text") != null) ? vars.get("text").trim() : null;
String pollId = ALPHA_ID.decode(vars.get("poll_id")).toString();
String candidateId = vars.get("candidate_id");
String message;
if (candidateId == null) {
message = Actions.createCandidate(uv.getId().toString(), pollId, subject, text);
} else {
message = Actions.saveCandidate(uv.getId().toString(), candidateId, subject, text);
}
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("/get_poll_candidates/:pollAid/:pageSize/:startIndex", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
String pollId = ALPHA_ID.decode(req.params(":pollAid")).toString();
Integer pageSize = Integer.valueOf(req.params(":pageSize"));
Integer startIndex = Integer.valueOf(req.params(":startIndex"));
Tools.dbInit();
Paginator candidates =
new Paginator<CandidateView>(CandidateView.class,
pageSize,
"poll_id = ?", pollId).orderBy("avg_rank desc");
Integer pageNum = (startIndex/pageSize)+1;
String json = Tools.wrapPaginatorArray(
Tools.replaceNewlines(candidates.getPage(pageNum).toJson(false)),
candidates.getCount());
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/delete_candidate/:candidateId", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
String candidateId = req.params(":candidateId");
String message = Actions.deleteCandidate(uv.getId().toString(), candidateId);
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/edit_comment", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
Map<String, String> vars = Tools.createMapFromAjaxPost(req.body());
String text = (vars.get("text") != null) ? vars.get("text").trim() : null;
String commentId = vars.get("comment_id");
String message;
message = Actions.editComment(uv.getId().toString(), commentId, text);
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/delete_comment/:commentId", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
String commentId = req.params(":commentId");
String message;
message = Actions.deleteComment(uv.getId().toString(), commentId);
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/create_comment", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
Map<String, String> vars = Tools.createMapFromAjaxPost(req.body());
String text = vars.get("text").trim();
String discussionId = vars.get("discussion_id");
String parentCommentId = vars.get("parent_comment_id");
List<String> parentBreadCrumbs = null;
if (parentCommentId != null) {
// Fetch the parent breadCrumbs from scratch(required for comment pages)
parentBreadCrumbs = Arrays.asList(COMMENT_VIEW.findFirst("id = ?", parentCommentId)
.getString("breadcrumbs").split(","));
}
String message;
message = Actions.createComment(uv.getId().toString(), discussionId,
parentBreadCrumbs, text);
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("/get_poll/:pollAid", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Integer pollId = ALPHA_ID.decode(req.params(":pollAid")).intValue();
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
PollView pv = POLL_VIEW.findFirst("id = ?", pollId);
// check if its private, and if it is, make sure the cookie is there
String json = null;
if (pv.getBoolean("private") == true) {
String cookiePassword = req.cookie("poll_password_" + pollId);
// fetch the poll for the encrypted password
Poll p = POLL.findFirst("id = ?", pollId);
Boolean correctPass = Tools.PASS_ENCRYPT.checkPassword(cookiePassword, p.getString("private_password"));
// If its incorrect, then redirect to the password page
if (cookiePassword != null && correctPass) {
json = Tools.replaceNewlines(pv.toJson(false));
} else {
json = "incorrect_password";
}
} else {
json = Tools.replaceNewlines(pv.toJson(false));
Actions.addPollVisit(uv.getId().toString(), pollId);
}
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("/get_user_poll_votes/:pollId", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
String pollId = ALPHA_ID.decode(req.params(":pollId")).toString();
String json = BALLOT_VIEW.find("poll_id = ? and user_id = ?",
pollId, uv.getId().toString()).toJson(false);
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("/get_poll_results/:pollId", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
String pollId = ALPHA_ID.decode(req.params(":pollId")).toString();
Tools.dbInit();
String json = Actions.rangePollResults(pollId);
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("/get_comments/:pollId", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
String pollId = ALPHA_ID.decode(req.params(":pollId")).toString();
Integer discussionId = POLL.findFirst("id = ?", pollId).getInteger("discussion_id");
String json = Actions.fetchPollComments(uv.getInteger("id"), discussionId);
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("/get_comment/:commentId", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
Integer commentId = ALPHA_ID.decode(req.params(":commentId")).intValue();
String json = Actions.fetchComments(uv.getInteger("id"), commentId);
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("/get_comment_parent/:commentId", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
Integer commentId = ALPHA_ID.decode(req.params(":commentId")).intValue();
// Fetch the parent breadCrumbs from scratch(required for comment pages)
List<String> parentBreadCrumbs = Arrays.asList(COMMENT_VIEW.findFirst("id = ?", commentId)
.getString("breadcrumbs").split(","));
String parentAid = "-1";
if (parentBreadCrumbs.size() > 1) {
String parentId = parentBreadCrumbs.get(parentBreadCrumbs.size() - 2);
parentAid = ALPHA_ID.encode(new BigInteger(parentId));
}
log.info(parentAid);
return parentAid;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("/get_trending_polls/:tagAid/:userAid/:order/:pageSize/:startIndex", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
String tagAid = req.params(":tagAid");
String tagId = (tagAid.equals("all")) ? "all" : ALPHA_ID.decode(tagAid).toString();
String userAid = req.params(":userAid");
String userId = (userAid.equals("all")) ? "all" : ALPHA_ID.decode(userAid).toString();
String order = req.params(":order");
Integer pageSize = Integer.valueOf(req.params(":pageSize"));
Integer startIndex = Integer.valueOf(req.params(":startIndex"));
Paginator polls = null;
if (tagId.equals("all") && userId.equals("all")) {
polls = new Paginator<PollView>(PollView.class,
pageSize,
"subject is not null").
orderBy(order + " desc");
} else if (tagId.equals("all") && !userId.equals("all")){
polls = new Paginator<PollView>(PollView.class,
pageSize,
"subject is not null and user_id = ?", userId).
orderBy(order + " desc");
} else if (!tagId.equals("all") && userId.equals("all")){
polls = new Paginator<PollUngroupedView>(PollUngroupedView.class,
pageSize,
"subject is not null and tag_id = ?", tagId).
orderBy(order + " desc");
} else {
polls = new Paginator<PollView>(PollView.class,
pageSize,
"subject is not null and user_id = ? and tag_id = ?", userId, tagId).
orderBy(order + " desc");
}
Integer pageNum = (startIndex/pageSize)+1;
// Exclude private password from the query
String json = Tools.wrapPaginatorArray(
Tools.replaceNewlines(polls.getPage(pageNum).toJson(false)),
polls.getCount());
/*
* "aid", "created","day_hits", "day_score", "hour_hits", "hour_score",
"discussion_id", "full_user_only", "id", "modified", "month_hits",
"month_score", "number_of_comments", "poll_sum_type_id", "poll_sum_type_name",
"poll_type_id", "poll_type_name", "subject", "tag_aid",
"tag_id", "tag_name", "user_aid", "user_id", "user_name",
"week_hits", "week_score", "year_hits", "year_score"
*/
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("/get_trending_tags/:order/:pageSize/:startIndex", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
String order = req.params(":order");
Integer pageSize = Integer.valueOf(req.params(":pageSize"));
Integer startIndex = Integer.valueOf(req.params(":startIndex"));
Paginator tags = null;
tags = new Paginator<TagView>(TagView.class,
pageSize,
"1=?", "1").
orderBy(order + " desc");
Integer pageNum = (startIndex/pageSize)+1;
String json = tags.getPage(pageNum).toJson(false);
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("/get_poll_tags/:pollAid", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
String pollId = ALPHA_ID.decode(req.params(":pollAid")).toString();
String json = POLL_TAG_VIEW.find("poll_id = ?", pollId).toJson(false);
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("/get_tag/:tagAid", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
String tagAid = req.params(":tagAid");
Integer tagId = Tools.ALPHA_ID.decode(tagAid).intValue();
Actions.addTagVisit(uv.getId().toString(), tagId);
String json = TAG_VIEW.findFirst("id = ?", tagId).toJson(false);
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/save_ballot/:pollId/:candidateId/:rank", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
String pollId = ALPHA_ID.decode(req.params(":pollId")).toString();
String candidateId = req.params(":candidateId");
String rank = req.params(":rank");
if (rank.equals("null")) {
rank = null;
}
String message = Actions.saveBallot(uv.getId().toString(), pollId, candidateId, rank);
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/save_comment_vote/:commentId/:rank", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
String commentId = req.params(":commentId");
String rank = req.params(":rank");
if (rank.equals("null")) {
rank = null;
}
String message = Actions.saveCommentVote(uv.getId().toString(), commentId, rank);
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("/tag_search/:query", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
String query = req.params(":query");
String json = null;
String queryStr = constructQueryString(query, "name");
json = TAG_VIEW.find(queryStr.toString()).limit(5).orderBy("day_score desc").toJson(false);
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
get("/poll_search/:query", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
String query = req.params(":query");
String json = null;
String queryStr = constructQueryString(query, "subject");
json = POLL_VIEW.find(queryStr.toString()).limit(5).orderBy("day_score desc").toJson(false,
"aid", "subject", "day_hits");
return json;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/save_poll_tag", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
Map<String, String> vars = Tools.createMapFromAjaxPost(req.body());
String pollId = ALPHA_ID.decode(vars.get("poll_id")).toString();
String tagId = vars.get("tag_id");
String tagName = vars.get("tag_name").trim();
String message = Actions.savePollTag(uv.getId().toString(), pollId, tagId, tagName);
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/clear_tags/:pollAid", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
String pollId = ALPHA_ID.decode(req.params(":pollAid")).toString();
String message = Actions.clearTags(uv.getId().toString(), pollId);
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/mark_messages_as_read", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
UserLoginView uv = Actions.getUserFromCookie(req, res);
String message = Actions.markMessagesAsRead(uv.getInteger("id"));
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/login", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
Map<String, String> vars = Tools.createMapFromAjaxPost(req.body());
String userOrEmail = vars.get("user_or_email");
String password = vars.get("password");
String recaptchaResponse = vars.get("g-recaptcha-response");
String message = Actions.login(userOrEmail, password, recaptchaResponse, req, res);
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
post("/signup", (req, res) -> {
try {
Tools.allowAllHeaders(req, res);
Tools.logRequestInfo(req);
Tools.dbInit();
Map<String, String> vars = Tools.createMapFromAjaxPost(req.body());
String userName = vars.get("username");
String password = vars.get("password");
String email = vars.get("email");
String recaptchaResponse = vars.get("g-recaptcha-response");
String message = Actions.signup(userName, password, email, recaptchaResponse, req, res);
return message;
} catch (Exception e) {
res.status(666);
e.printStackTrace();
return e.getMessage();
} finally {
Tools.dbClose();
}
});
}
public static String constructQueryString(String query, String columnName) {
try {
query = java.net.URLDecoder.decode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String[] splitWords = query.split(" ");
StringBuilder queryStr = new StringBuilder();
for(int i = 0;;) {
String word = splitWords[i++].replaceAll("'", "_");
String likeQuery = columnName + " like '%" + word + "%'";
queryStr.append(likeQuery);
if (i < splitWords.length) {
queryStr.append(" and ");
} else {
break;
}
}
return queryStr.toString();
}
} | 26,788 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
WebService.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/webservice/WebService.java | package com.referendum.webservice;
import static spark.Spark.get;
import static spark.Spark.port;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.Spark;
import spark.utils.GzipUtils;
import com.referendum.DataSources;
import com.referendum.tools.Tools;
public class WebService {
static final Logger log = LoggerFactory.getLogger(WebService.class);
public static void start() {
// Spark.secure(DataSources.KEYSTORE(), "foobar",null,null);
if (DataSources.SSL) {
Spark.secure(DataSources.KEYSTORE_FILE(), "changeit", null,null);
}
port(DataSources.INTERNAL_SPARK_WEB_PORT);
API.setup();
DynamicPages.setup();
get("/hello", (req, res) -> {
Tools.allowOnlyLocalHeaders(req, res);
return "hi from the referendum web service";
});
get("/", (req, res) -> {
Tools.allowAllHeaders(req, res);
Tools.set15MinuteCache(req, res);
return Tools.readFile(DataSources.BASE_ENDPOINT);
});
get("/*", (req, res) -> {
Tools.allowAllHeaders(req, res);
Tools.set15MinuteCache(req, res);
String pageName = req.splat()[0];
String webHomePath = DataSources.WEB_HOME() + "/" + pageName;
Tools.setContentTypeFromFileName(pageName, res);
return Tools.writeFileToResponse(webHomePath, req, res);
});
}
}
| 1,423 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
BuildFastTables.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/scheduled/BuildFastTables.java | package com.referendum.scheduled;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.referendum.DataSources;
import com.referendum.tools.ScriptRunner;
public class BuildFastTables implements Job {
static final Logger log = LoggerFactory.getLogger(BuildFastTables.class);
private static void create() {
Properties prop = DataSources.DB_PROP;
Connection mConnection;
try {
Class.forName("com.mysql.jdbc.Driver");
mConnection = DriverManager.getConnection(prop.getProperty("dburl"),
prop.getProperty("dbuser"),
prop.getProperty("dbpassword"));
ScriptRunner runner = new ScriptRunner(mConnection, false, false);
runner.setErrorLogWriter(null);
runner.setLogWriter(null);
log.info("Rebuilding fast tables....");
runner.runScript(new BufferedReader(new FileReader(DataSources.SQL_FAST_TABLES_FILE())));
} catch (ClassNotFoundException e) {
log.error("Unable to get mysql driver: " + e);
} catch (SQLException e) {
log.error("Unable to connect to server: " + e);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try {
// ArrayList<String> cmd = new ArrayList<String>();
// cmd.add("mysql");
// cmd.add("-u" + prop.getProperty("dbuser"));
// cmd.add("-p" + prop.getProperty("dbpassword"));
// cmd.add(prop.getProperty("dburl"));
// cmd.add("<");
// cmd.add(DataSources.SQL_FAST_TABLES_FILE());
//
// for (String uz : cmd) {System.out.println(uz);}
//
// ProcessBuilder b = new ProcessBuilder(cmd);
// b.inheritIO();
// Process p;
//
// p = b.start();
//
//
// p.waitFor();
//
// log.info("Fast Tables created succesfully.");
//
// } catch (IOException | InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
create();
}
}
| 2,403 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
ScheduledJobs.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/scheduled/ScheduledJobs.java | package com.referendum.scheduled;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
public class ScheduledJobs {
public static void start() {
// Another
try {
// Grab the Scheduler instance from the Factory
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
// and start it off
scheduler.start();
JobDetail job = newJob(BuildFastTables.class)
.build();
// Trigger the job to run now, and then repeat every 20 minutes
Trigger trigger = newTrigger()
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInMinutes(15)
.repeatForever())
.build();
// Tell quartz to schedule the job using our trigger
scheduler.scheduleJob(job, trigger);
} catch (SchedulerException se) {
se.printStackTrace();
}
}
}
| 1,086 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
ExampleUnitTest.java | /FileExtraction/Java_unseen/CactiChameleon9_Gecko-Browser/app/src/test/java/com/example/geckobrowser/ExampleUnitTest.java | package com.example.geckobrowser;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | 385 | Java | .java | CactiChameleon9/Gecko-Browser | 9 | 0 | 0 | 2020-08-18T08:49:37Z | 2021-06-25T11:34:25Z |
SettingsActivity.java | /FileExtraction/Java_unseen/CactiChameleon9_Gecko-Browser/app/src/main/java/com/example/geckobrowser/SettingsActivity.java | package com.example.geckobrowser;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import androidx.appcompat.app.AppCompatActivity;
//TODO homepage setting
//TODO clear tabs on exit setting
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Button b = findViewById(R.id.settingsSaveButton);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences.Editor editor = getSharedPreferences("settingsPrefs", MODE_PRIVATE).edit();
Switch s;
s = findViewById(R.id.desktopToggle);
if (s.isChecked()){
editor.putBoolean("desktopMode", true);
} else {
editor.putBoolean("desktopMode", false);
}
s = findViewById(R.id.disableJavascriptToggle);
if (s.isChecked()){
editor.putBoolean("javascript", false);
} else {
editor.putBoolean("javascript", true);
}
s = findViewById(R.id.autoHideBarToggle);
if (s.isChecked()){
editor.putBoolean("autoHideBar", true);
} else {
editor.putBoolean("autoHideBar", false);
}
s = findViewById(R.id.disableTPToggle);
if (s.isChecked()){
editor.putBoolean("trackingProtection", false);
} else {
editor.putBoolean("trackingProtection", true);
}
s = findViewById(R.id.privateModeToggle);
if (s.isChecked()){
editor.putBoolean("privateMode", true);
} else {
editor.putBoolean("privateMode", false);
}
s = findViewById(R.id.hideWhiteSplashToggle);
if (s.isChecked()){
editor.putBoolean("hideWhiteSplash", true);
} else {
editor.putBoolean("hideWhiteSplash", false);
}
s = findViewById(R.id.searchSuggestionsToggle);
if (s.isChecked()){
editor.putBoolean("searchSuggestions", true);
} else {
editor.putBoolean("searchSuggestions", false);
}
EditText e;
e = findViewById(R.id.userAgentEditText);
editor.putString("userAgent", e.getText().toString());
e = findViewById(R.id.searchEngineEditText);
editor.putString("searchEngine", e.getText().toString());
editor.commit(); //needs to be commit otherwise its stopped by restart
restartApp();
}
});
SharedPreferences prefs = getSharedPreferences("settingsPrefs", MODE_PRIVATE);
Switch s;
s = findViewById(R.id.desktopToggle);
s.setChecked(prefs.getBoolean("desktopMode", false));
s = findViewById(R.id.disableJavascriptToggle);
s.setChecked(!prefs.getBoolean("javascript", true)); //reversed with !
s = findViewById(R.id.autoHideBarToggle);
s.setChecked(prefs.getBoolean("autoHideBar", false));
s = findViewById(R.id.disableTPToggle);
s.setChecked(!prefs.getBoolean("trackingProtection", true)); //reversed with !
s = findViewById(R.id.privateModeToggle);
s.setChecked(prefs.getBoolean("privateMode", false));
s = findViewById(R.id.searchSuggestionsToggle);
s.setChecked(prefs.getBoolean("searchSuggestions", true));
s = findViewById(R.id.hideWhiteSplashToggle);
s.setChecked(prefs.getBoolean("hideWhiteSplash", false));
EditText e;
e = findViewById(R.id.userAgentEditText);
e.setText(prefs.getString("userAgent", ""));
e = findViewById(R.id.searchEngineEditText);
e.setText(prefs.getString("searchEngine", ""));
}
private void restartApp() {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
this.startActivity(intent);
Runtime.getRuntime().exit(0);
}
public void hideKeyboard(View v) {
InputMethodManager imm = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
View view = this.getCurrentFocus();
if (view == null) {
view = new View(this);
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
} | 5,085 | Java | .java | CactiChameleon9/Gecko-Browser | 9 | 0 | 0 | 2020-08-18T08:49:37Z | 2021-06-25T11:34:25Z |
MainActivity.java | /FileExtraction/Java_unseen/CactiChameleon9_Gecko-Browser/app/src/main/java/com/example/geckobrowser/MainActivity.java | package com.example.geckobrowser;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import org.mozilla.geckoview.ContentBlocking;
import org.mozilla.geckoview.GeckoRuntime;
import org.mozilla.geckoview.GeckoSession;
import org.mozilla.geckoview.GeckoSessionSettings;
import org.mozilla.geckoview.GeckoView;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
//TODO add horizontal tablet tab picker
//TODO add downloads
//TODO undo and redo
//TODO TABS
//TODO search completion
public class MainActivity extends AppCompatActivity {
public String SEARCH_URI_BASE = "https://duckduckgo.com/?q=";
public String INITIAL_URL = "https://start.duckduckgo.com";
boolean autoHideBar;
boolean hideWhiteSplash;
boolean searchSuggestions;
private GeckoView mGeckoView;
private GeckoSession mGeckoSession;
private GeckoSessionSettings.Builder settingsBuilder = new GeckoSessionSettings.Builder();
private EditText urlEditText;
private ProgressBar mProgressView;
private TextView trackersCountView;
private ArrayList<String> trackersBlockedList;
private String[] tabURLs;
private int activeTab = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressView = findViewById(R.id.pageProgressView);
setupUrlEditText();
setupSettings();
setupGeckoView();
setupTabs();
//allow opening url from another app
Intent mIntent = getIntent();
String action = mIntent.getAction();
if (action != null && action.equals(Intent.ACTION_VIEW)) {
commitURL(mIntent.getData().toString());
}
}
private void setupTabs() {
//restoring tabs
SharedPreferences prefs = getSharedPreferences("dataPrefs", MODE_PRIVATE);
tabURLs = prefs.getString("tabURLs", "").split(", ");
Log.e("DEBUG", tabURLs[0]);
activeTab = prefs.getInt("activeTab", 0);
commitURL(tabURLs[activeTab]);
// <TextView
// app:layout_rowWeight="1"
// app:layout_columnWeight="1"
// android:text="A"
// android:textAppearance="?android:attr/textAppearanceLarge"
// android:padding="30dp"
// app:layout_column="0"
// app:layout_row="0"
// app:layout_gravity="fill" />
//tabview stuff
TextView tabsCountView = findViewById(R.id.tabsCountView);
tabsCountView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// View darkOverlayView = findViewById(R.id.darkOverlayView);
// GridLayout tabsGridLayout = findViewById(R.id.tabsGridLayout);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog
.setTitle("Tabs")
.setItems(tabURLs, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
activeTab = i;
commitURL(tabURLs[activeTab]);
}
})
.setPositiveButton("New Tab", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
activeTab = tabURLs.length;
// create a new ArrayList
List<String> tmpList = new ArrayList<>(Arrays.asList(tabURLs));
// Add the new element
tmpList.add("");
// Convert the Arraylist to array
tabURLs = tmpList.toArray(tabURLs);
tabURLs[activeTab] = "";
commitURL(tabURLs[activeTab]);
}
})
.setNegativeButton("Delete Current Tab", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (tabURLs.length > 1) {
// create a new ArrayList
// List<String> tmpList = new ArrayList<>(Arrays.asList(tabURLs));
List<String> tmpList = new ArrayList<String>();
for (int j = 0; j < tabURLs.length; j++) {
if (j!=activeTab) { //add all to a new list apart from old
tmpList.add(tabURLs[j]);
}
}
// Convert the Arraylist to array
tabURLs = tmpList.toArray(new String[tmpList.size()]);
activeTab = tabURLs.length - 1;
commitURL(tabURLs[activeTab]);
} else {
commitURL("");
}
}
})
.create()
.show();
// for (String tabURL : tabURLs) {
// Button mValue = new Button(MainActivity.this);
// mValue.setLayoutParams(new TableLayout.LayoutParams(
// TableLayout.LayoutParams.WRAP_CONTENT,
// TableLayout.LayoutParams.WRAP_CONTENT));
// mValue.setTextSize(20);
// mValue.setPadding(10,10,10,10);
// mValue.setAllCaps(false);
//// mValue.setBackgroundResource(R.color.colorAccent);
// mValue.setText(tabURL);
// mValue.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// activeTab = Arrays.asList(tabURLs).indexOf(tabURL);
// commitURL(tabURL);
// }
// });
//
// tabsGridLayout.addView(mValue);
// }
//
//
// if (tabsGridLayout.getVisibility() == View.GONE) {
// tabsGridLayout.setVisibility(View.VISIBLE);
// darkOverlayView.setVisibility(View.VISIBLE);
// } else {
// tabsGridLayout.setVisibility(View.GONE);
// darkOverlayView.setVisibility(View.GONE);
// }
}
});
}
private void setupSettings() {
ImageButton settingsButton = findViewById(R.id.settingsButton);
settingsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(view.getContext(), SettingsActivity.class);
startActivity(i);
}
});
SharedPreferences prefs = getSharedPreferences("settingsPrefs", MODE_PRIVATE);
// if (cookieStoreId != null) {
// settingsBuilder.contextId(cookieStoreId);
// }
settingsBuilder.allowJavascript(prefs.getBoolean("javascript", true));
settingsBuilder.useTrackingProtection(prefs.getBoolean("trackingProtection", true));
settingsBuilder.usePrivateMode(prefs.getBoolean("privateMode", false));
if (!prefs.getString("userAgent", "").equals("")) { //reversed using !
settingsBuilder.userAgentOverride(prefs.getString("userAgent", ""));
} else if (prefs.getBoolean("desktopMode", false)) {
settingsBuilder.userAgentMode(GeckoSessionSettings.USER_AGENT_MODE_DESKTOP);
settingsBuilder.displayMode(GeckoSessionSettings.USER_AGENT_MODE_DESKTOP); // not used in example code, remove if issues are caused
settingsBuilder.viewportMode(GeckoSessionSettings.USER_AGENT_MODE_DESKTOP);
} else {
settingsBuilder.userAgentMode(GeckoSessionSettings.USER_AGENT_MODE_MOBILE); //better safe than sorry
settingsBuilder.viewportMode(GeckoSessionSettings.USER_AGENT_MODE_MOBILE); //better safe than sorry
}
autoHideBar = prefs.getBoolean("autoHideBar", false); //TODO autoHideBar need to set/use elsewhere
hideWhiteSplash = prefs.getBoolean("hideWhiteSplash", false);
searchSuggestions = prefs.getBoolean("searchSuggestions", true);
if (!prefs.getString("searchEngine", "").equals("")) {
SEARCH_URI_BASE = prefs.getString("searchEngine", "https://duckduckgo.com/?q=");
}
}
private void setupGeckoView() {
mGeckoView = findViewById(R.id.geckoView);
GeckoRuntime runtime = GeckoRuntime.create(this);
mGeckoSession = new GeckoSession(settingsBuilder.build());
setupTrackersCounter();
mGeckoSession.setProgressDelegate(new createProgressDelegate());
mGeckoSession.open(runtime);
mGeckoView.setSession(mGeckoSession);
mGeckoSession.loadUri(INITIAL_URL);
// mGeckoSession.getSettings().setUseTrackingProtection(true); moved elsewhere
mGeckoSession.setContentBlockingDelegate(new createBlockingDelegate());
}
private void setupTrackersCounter() {
trackersCountView = findViewById(R.id.trackerCountView);
trackersCountView.setText(R.string._0);
trackersBlockedList = new ArrayList<String>();
trackersCountView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!(trackersBlockedList.isEmpty())) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog
.setTitle(R.string.trackers_blocked)
.setItems(trackersBlockedList.toArray(new String[0]), null)
.create()
.show();
}
}
});
}
private void setupUrlEditText() {
urlEditText = findViewById(R.id.urlEditText);
urlEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) {
// if (actionId == KeyEvent.KEYCODE_ENDCALL || actionId == KeyEvent.KEYCODE_ENTER) {
commitURL(urlEditText.getText().toString());
// }
return true;
}
});
}
private void commitURL(String url) {
if ((url.contains(".") || url.contains(":")) && !url.contains(" ")) { //maybe add list of domain endings here though an array
url = url.toLowerCase();
if (!url.contains("https://") && !url.contains("http://")) {
url = "https://" + url;
}
mGeckoSession.loadUri(url);
} else if (url.equals("") || url.equals(" ")) {
mGeckoSession.loadUri(INITIAL_URL);
} else {
mGeckoSession.loadUri(SEARCH_URI_BASE + url);
}
mGeckoView.requestFocus();
hideKeyboard(this);
}
private void clearTrackersCount() {
try {
trackersBlockedList.clear();
trackersCountView.setText(R.string._0);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void refreshTabCount() {
TextView tabsCountView = findViewById(R.id.tabsCountView);
tabsCountView.setText("" + tabURLs.length);
}
private void hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
//Find the currently focused view, so we can grab the correct window token from it.
View view = activity.getCurrentFocus();
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = new View(activity);
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
protected void changeLockColour(boolean isHttps) {
ImageView v = findViewById(R.id.trackerCountViewImage);
if (isHttps) {
v.setImageResource(R.drawable.lock_icon_green);
} else {
v.setImageResource(R.drawable.lock_icon_red);
}
}
@Override
protected void onDestroy() {
Runtime.getRuntime().exit(0); //fix only one runtime allowed crash
super.onDestroy();
}
@Override
protected void onPause() {
//saving stuff
SharedPreferences.Editor editor = getSharedPreferences("dataPrefs", MODE_PRIVATE).edit();
//tabs
StringBuilder a = new StringBuilder();
for (int i = 0; i < tabURLs.length; ) {
a.append(tabURLs[i]).append(", ");
i++;
}
editor.putString("tabURLs", a.toString());
Log.e("DEBUG", a.toString());
//activeTab
editor.putInt("activeTab", activeTab);
editor.apply();
super.onPause();
}
private class createProgressDelegate implements GeckoSession.ProgressDelegate {
@Override
public void onPageStart(GeckoSession session, String url) {
urlEditText.setText(url);
tabURLs[activeTab] = url;
if (url.contains("https://")) {
changeLockColour(true);
} else {
changeLockColour(false);
}
clearTrackersCount();
refreshTabCount();
}
@Override
public void onProgressChange(GeckoSession session, int progress) {
mProgressView.setProgress(progress);
if (progress > 0 && progress < 100) {
mProgressView.setVisibility(View.VISIBLE);
if (hideWhiteSplash) {
mGeckoView.setVisibility(View.INVISIBLE);
}
} else {
mProgressView.setVisibility(View.GONE);
mGeckoView.setVisibility(View.VISIBLE);
}
}
}
private class createBlockingDelegate implements ContentBlocking.Delegate {
@Override
public void onContentBlocked(GeckoSession session, ContentBlocking.BlockEvent event) {
Log.e("DEBUG", "Something happened here" + event);
URL url = null;
try {
url = new URL(event.uri);
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
trackersBlockedList.add(url.getHost());
trackersCountView.setText("" + trackersBlockedList.size());
}
}
}
| 15,896 | Java | .java | CactiChameleon9/Gecko-Browser | 9 | 0 | 0 | 2020-08-18T08:49:37Z | 2021-06-25T11:34:25Z |
ExampleInstrumentedTest.java | /FileExtraction/Java_unseen/CactiChameleon9_Gecko-Browser/app/src/androidTest/java/com/example/geckobrowser/ExampleInstrumentedTest.java | package com.example.geckobrowser;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.geckobrowser", appContext.getPackageName());
}
} | 762 | Java | .java | CactiChameleon9/Gecko-Browser | 9 | 0 | 0 | 2020-08-18T08:49:37Z | 2021-06-25T11:34:25Z |
PropertiesTest.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/test/java/com/tek271/reverseProxy/config/PropertiesTest.java | package com.tek271.reverseProxy.config;
import static org.junit.Assert.*;
import org.junit.Test;
import com.tek271.reverseProxy.model.Mappings;
import com.tek271.reverseProxy.utils.PropertiesFile;
public class PropertiesTest {
private static final String FILE= "reverseProxy.test.properties";
@Test
public void testReadMappings() {
PropertiesFile propertiesFile= new PropertiesFile(FILE, true);
Mappings mappings = Properties.readMappings(propertiesFile);
assertEquals(5, mappings.size());
assertEquals("maps.google.com", mappings.get(0).hiddenDomain);
}
}
| 587 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
RegexToolsTest.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/test/java/com/tek271/reverseProxy/utils/RegexToolsTest.java | package com.tek271.reverseProxy.utils;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
public class RegexToolsTest {
@Test
public void testFindAll() {
String pattern= "A+";
String text= "A-AA-AAA-";
List<Tuple3<Integer, Integer, String>> found = RegexTools.findAll(pattern, text, true);
assertEquals(3, found.size());
List<Tuple3<Integer, Integer, String>> expected= ImmutableList.of(
Tuple3.tuple3(0, 1, "A"),
Tuple3.tuple3(2, 4, "AA"),
Tuple3.tuple3(5, 8, "AAA")
);
assertEquals(expected, found);
}
@Test
public void testFindAllWithGroups() {
String pattern= "\\bhref\\b\\s*=\\s*(\\S*?)[\\s>]";
String text= "<A href= a.c at >t</a>";
List<Tuple3<Integer, Integer, String>> found = RegexTools.findAll(pattern, text, true);
assertEquals(1, found.size());
List<Tuple3<Integer, Integer, String>> expected= ImmutableList.of(
Tuple3.tuple3(9, 12, "a.c")
);
assertEquals(expected, found);
}
}
| 1,108 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
PropertiesFileTest.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/test/java/com/tek271/reverseProxy/utils/PropertiesFileTest.java | package com.tek271.reverseProxy.utils;
import static org.junit.Assert.*;
import org.junit.Test;
public class PropertiesFileTest {
private static final String FILE= "reverseProxy.test.properties";
@Test
public void testSubset() {
PropertiesFile propertiesFile= new PropertiesFile(FILE);
PropertiesFile subset = propertiesFile.subset("mapping");
assertEquals(5, subset.getProperties().size());
}
}
| 423 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
TextToolsTest.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/test/java/com/tek271/reverseProxy/utils/TextToolsTest.java | package com.tek271.reverseProxy.utils;
import static org.junit.Assert.*;
import org.junit.Test;
public class TextToolsTest {
@Test public void testRemoveControlChars() {
assertEquals("", TextTools.removeControlChars(null));
assertEquals("", TextTools.removeControlChars(""));
assertEquals(" ", TextTools.removeControlChars(" "));
assertEquals(" ", TextTools.removeControlChars(" \t\n "));
}
}
| 436 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
UrlMapperTest.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/test/java/com/tek271/reverseProxy/text/UrlMapperTest.java | package com.tek271.reverseProxy.text;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.tek271.reverseProxy.model.ModelFactory;
public class UrlMapperTest {
private UrlMapper target= new UrlMapper(ModelFactory.MAPPING1);
@Test
public void testMapContentUrlUrl() {
assertEquals("http://a.b", target.mapContentUrl("http://a.b"));
String prefix = ModelFactory.MAPPING1.proxyResource; // /rp/maps
assertEquals(prefix + "/home", target.mapContentUrl("/home"));
}
}
| 534 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
TagTranslatorTest.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/test/java/com/tek271/reverseProxy/text/TagTranslatorTest.java | package com.tek271.reverseProxy.text;
import static org.junit.Assert.assertEquals;
import java.util.regex.Pattern;
import org.junit.Test;
import com.tek271.reverseProxy.model.ModelFactory;
public class TagTranslatorTest {
// Will find all <a .*> tags
private static final String ANCHORE_REGEX= "<[aA]\\b(\"[^\"]*\"|'[^']*'|[^'\">])*>"; // match <a .*> tags
private static final Pattern ANCHORE_PATTERN= Pattern.compile(ANCHORE_REGEX);
private static final String HREF_REGEX= "\\bhref\\b\\s*=\\s*(\\S*?)[\\s>]"; // match href value
private static final Pattern HREF_PATTERN= Pattern.compile(HREF_REGEX, Pattern.CASE_INSENSITIVE);
TagTranslator target= new TagTranslator(ModelFactory.MAPPING1, ANCHORE_PATTERN, HREF_PATTERN);
@Test
public void testTranslateAnchor() {
assertEquals("", target.translateTag(""));
assertEquals("<a></a>", target.translateTag("<a></a>"));
assertEquals("<a/>", target.translateTag("<a/>"));
assertEquals("<a href></a>", target.translateTag("<a href></a>"));
assertEquals("<a href=\"\"></a>", target.translateTag("<a href=\"\"></a>"));
assertEquals("<a href=\"\"></a>", target.translateTag("<a href=''></a>"));
assertEquals("<a href= \"\" ></a>", target.translateTag("<a href= '' ></a>"));
}
@Test public void testAttributeValue() {
assertEquals("abc", target.attributeValue("<A href='abc'>t</a>").e3);
assertEquals("abc", target.attributeValue("<A href=\"abc\">t</a>").e3);
assertEquals("abc", target.attributeValue("<A href= 'abc' >t</a>").e3);
assertEquals("abc", target.attributeValue("<a href=abc>t</a>").e3);
assertEquals("abc", target.attributeValue("<a href=abc>t</a>").e3);
assertEquals("abc", target.attributeValue("<a href=abc >t</a>").e3);
assertEquals("abc", target.attributeValue("<a href='abc>t</a>").e3);
}
}
| 1,852 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
TextTranslatorTest.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/test/java/com/tek271/reverseProxy/text/TextTranslatorTest.java | package com.tek271.reverseProxy.text;
import static org.junit.Assert.*;
import java.util.regex.*;
import org.junit.Test;
import com.tek271.reverseProxy.model.ModelFactory;
public class TextTranslatorTest {
private TextTranslator target= new TextTranslator(ModelFactory.MAPPING1);
@Test public void testRegEx() {
String regex= "\\bhref\\b\\s*=\\s*(\\S*?)[\\s>]";
String text= "<A href= a.c at >t</a>";
Pattern pattern= Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
matcher.find();
String found = matcher.group(1);
assertEquals("a.c", found);
}
@Test
public void testTranslate() {
assertEquals("", target.translate(""));
assertEquals("", target.translate(null));
assertEquals("hello", target.translate("hello"));
assertEquals("<a href=\"\">click</a>", target.translate("<a href=''>click</a>"));
assertEquals("<a href=\"yahoo\">click</a>", target.translate("<a href='yahoo'>click</a>"));
assertEquals("<a href=\"/rp/maps/abc\">click</a>", target.translate("<a href='/abc'>click</a>"));
assertEquals("<a at= 'ab' href=\"/rp/maps/abc\">click</a>", target.translate("<a at= 'ab' href='/abc'>click</a>"));
assertEquals("<a href=\"/rp/maps/abc\" >click</a>", target.translate("<a href='/abc' >click</a>"));
assertEquals("hello<a href=\"/rp/maps/abc\">click</a>", target.translate("hello<a href='/abc'>click</a>"));
assertEquals("hello<a href=\"/rp/maps/abc\">click</a>", target.translate("hello<a href=\"/abc\">click</a>"));
assertEquals("hello<a href=\"/rp/maps/abc\">click</a>", target.translate("hello<a href=/abc>click</a>"));
}
}
| 1,645 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
MappingTest.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/test/java/com/tek271/reverseProxy/model/MappingTest.java | package com.tek271.reverseProxy.model;
import static org.junit.Assert.*;
import org.junit.Test;
public class MappingTest {
@Test
public void constructorShouldParseInput() {
Mapping mapping = new Mapping("maps.google.com, localhost:8080, /rp/maps");
assertEquals("maps.google.com", mapping.hiddenDomain);
assertEquals("localhost:8080", mapping.proxyDomain);
assertEquals("/rp/maps", mapping.proxyResource);
}
@SuppressWarnings("unused")
@Test(expected=IllegalArgumentException.class)
public void constructorShouldFailIfNoInput() {
new Mapping("");
}
@SuppressWarnings("unused")
@Test(expected=IllegalArgumentException.class)
public void constructorShouldFailIfInvalid() {
new Mapping("maps.google.com, localhost:8080");
}
@Test
public void testMapProxyToHidden() {
String proxyUrl= "http://localhost:8080/rp/maps/home";
String actual= ModelFactory.MAPPING1.mapProxyToHidden(proxyUrl);
String expected= "http://maps.google.com/home";
assertEquals(expected, actual);
}
@Test
public void testMapHiddenToProxy() {
String hiddenUrl= "http://maps.google.com/home";
String actual= ModelFactory.MAPPING1.mapHiddenToProxy(hiddenUrl);
String expected= "http://localhost:8080/rp/maps/home";
assertEquals(expected, actual);
}
}
| 1,319 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
ModelFactory.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/test/java/com/tek271/reverseProxy/model/ModelFactory.java | package com.tek271.reverseProxy.model;
public class ModelFactory {
public static final Mapping MAPPING1= new Mapping("maps.google.com, localhost:8080, /rp/maps");
public static final Mapping MAPPING2= new Mapping("www.facebook.com, localhost:8080, /rp/fb");
public static final Mappings MAPPINGS = Mappings.create(MAPPING1, MAPPING2);
}
| 352 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
MappingsTest.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/test/java/com/tek271/reverseProxy/model/MappingsTest.java | package com.tek271.reverseProxy.model;
import static org.junit.Assert.*;
import org.junit.Test;
public class MappingsTest {
@Test public void testfindByProxyUrl() {
Mappings mappings= ModelFactory.MAPPINGS;
assertEquals(mappings.get(0), mappings.findByProxyUrl("http://localhost:8080/rp/maps/1"));
assertEquals(mappings.get(1), mappings.findByProxyUrl("http://localhost:8080/rp/fb/2"));
}
@Test public void testfindByHiddenUrl() {
Mappings mappings= ModelFactory.MAPPINGS;
assertEquals(mappings.get(0), mappings.findByHiddenUrl("http://maps.google.com/1"));
assertEquals(mappings.get(1), mappings.findByHiddenUrl("http://www.facebook.com/2"));
}
}
| 693 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
Config.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/config/Config.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.config;
import com.tek271.reverseProxy.model.Mappings;
public enum Config {
singleton;
public final Mappings mappings;
public final Properties properties;
private Config() {
properties= new Properties();
mappings= properties.mappings;
}
}
| 1,031 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
Properties.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/config/Properties.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.config;
import com.google.common.annotations.VisibleForTesting;
import com.tek271.reverseProxy.model.*;
import com.tek271.reverseProxy.utils.PropertiesFile;
public class Properties {
private static final String FILE= "reverseProxy.properties";
public final Mappings mappings;
public Properties() {
PropertiesFile propertiesFile= new PropertiesFile(FILE, true);
mappings= readMappings(propertiesFile);
}
@VisibleForTesting
static Mappings readMappings(PropertiesFile propertiesFile) {
Mappings mappings= new Mappings();
PropertiesFile subset = propertiesFile.subset("mapping.");
for(String key: subset.keys()) {
String value = subset.getString(key);
mappings.add( new Mapping(value) );
}
return mappings;
}
}
| 1,550 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
PropertiesFile.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/utils/PropertiesFile.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.utils;
import java.util.*;
import com.google.common.collect.*;
import static org.apache.commons.lang.StringUtils.*;
public class PropertiesFile {
private static final String COMMENT = "#";
private static final String EQ = "=";
private Map<String, String> props;
private boolean allowInLineComments= false;
private PropertiesFile() {}
public PropertiesFile(String fileName, boolean allowInLineComments) {
List<String> lines = FileTools.readLinesFromContext(fileName);
this.allowInLineComments= allowInLineComments;
props= parse(lines);
}
public PropertiesFile(String fileName) {
this(fileName, false);
}
public static Map<String, String> read(String fileName) {
PropertiesFile pf= new PropertiesFile(fileName);
return pf.props;
}
private Map<String, String> parse(List<String> lines) {
Map<String, String> map= new LinkedHashMap<String, String>();
for(String line: lines) {
Tuple2<String, String> tuple = parseLine(line);
if (tuple!=null) {
map.put(tuple.e1, tuple.e2);
}
}
return map;
}
private Tuple2<String, String> parseLine(String line) {
line= trim(line);
if (isEmpty(line)) return null;
if (line.startsWith(COMMENT)) return null;
if (allowInLineComments) line= substringBefore(line, COMMENT);
if (! line.contains(EQ)) return null;
String key= trim(substringBefore(line, EQ));
if (isEmpty(key)) return null;
String value= trim(substringAfter(line, EQ));
return Tuple2.tuple2(key, value);
}
public Map<String, String> getProperties() {
return props;
}
public String getString(String key) {
return props.get(key);
}
public Integer getInteger(String key) {
String v= props.get(key);
if (isEmpty(v)) return null;
return Integer.parseInt(v);
}
public Long getLong(String key) {
String v= props.get(key);
if (isEmpty(v)) return null;
return Long.parseLong(v);
}
private static final Set<String> TRUES= ImmutableSet.of("true", "t", "yes", "y", "1");
public Boolean getBoolean(String key) {
String v= props.get(key);
if (isEmpty(v)) return null;
v= lowerCase(v);
return TRUES.contains(v);
}
/** get a subset of element with the given key prefix */
public PropertiesFile subset(String keyPrefix) {
PropertiesFile subset= new PropertiesFile();
subset.props= Maps.newLinkedHashMap();
subset.allowInLineComments= allowInLineComments;
for (Map.Entry<String, String> e: props.entrySet()) {
String k= e.getKey();
if (startsWith(k, keyPrefix)) subset.props.put(k, e.getValue());
}
return subset;
}
public Set<String> keys() {
return props.keySet();
}
}
| 3,536 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
FileTools.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/utils/FileTools.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.utils;
import java.io.*;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
public class FileTools {
public static InputStream readFromContextToInputStream(String fileName) {
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
if (inputStream == null) {
throw new IllegalArgumentException("Cannot find " + fileName);
}
return inputStream;
}
public static String readTextFileFromContext(String fileName) {
InputStream stream = readFromContextToInputStream(fileName);
return toString(stream);
}
static String toString(InputStream stream) {
try {
return IOUtils.toString(stream);
} catch (Exception e) {
throw new IllegalArgumentException("Cannot read stream", e);
}
}
public static List<String> readLinesFromContext(String fileName) {
InputStream is = readFromContextToInputStream(fileName);
try {
return IOUtils.readLines(is);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot read file: " + fileName, e);
}
}
public static long size(File file) {
if (file == null) {
return 0;
}
return file.length();
}
public static String readTextFileContent(File file) {
if (file == null ) return "";
String text;
try {
text = FileUtils.readFileToString(file);
} catch (IOException e) {
throw new IllegalArgumentException("Could not read file's text.", e);
}
return StringUtils.defaultString(text);
}
}
| 2,397 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
RegexFlagsEnum.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/utils/RegexFlagsEnum.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.utils;
import java.util.regex.Pattern;
public enum RegexFlagsEnum {
CANON_EQ(Pattern.CANON_EQ),
CASE_INSENSITIVE(Pattern.CASE_INSENSITIVE),
COMMENTS(Pattern.COMMENTS),
DOTALL(Pattern.DOTALL),
LITERAL(Pattern.LITERAL),
MULTILINE(Pattern.MULTILINE),
UNICODE_CASE(Pattern.UNICODE_CASE),
UNIX_LINES(Pattern.UNIX_LINES);
public final int code;
private RegexFlagsEnum(int code) {
this.code= code;
}
public static int addCodes(RegexFlagsEnum... flags) {
int sum=0;
for (RegexFlagsEnum flag : flags) {
sum += flag.code;
}
return sum;
}
}
| 1,361 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
RegexTools.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/utils/RegexTools.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.utils;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import com.google.common.collect.Lists;
public class RegexTools {
/** Find all matches in a string */
public static List<Tuple3<Integer, Integer, String>> findAll(Pattern pattern, String text, boolean matchGroups) {
if (StringUtils.isEmpty(text)) return Collections.emptyList();
Matcher matcher = pattern.matcher(text);
List<Tuple3<Integer, Integer, String>> r= Lists.newArrayList();
while (matcher.find()) {
int groupCount = matcher.groupCount();
if (groupCount==0 || !matchGroups) {
r.add(getMatch(matcher, 0));
} else {
for (int i=1; i<=groupCount; i++) {
r.add(getMatch(matcher, i));
}
}
}
return r;
}
private static Tuple3<Integer, Integer, String> getMatch(Matcher matcher, int groupIndex) {
return Tuple3.tuple3(matcher.start(groupIndex), matcher.end(groupIndex), matcher.group(groupIndex));
}
public static List<Tuple3<Integer, Integer, String>> findAll(String pattern, String text, boolean matchGroups, RegexFlagsEnum... flags) {
int codes= RegexFlagsEnum.addCodes(flags);
Pattern pat= Pattern.compile(pattern, codes);
return findAll(pat, text, matchGroups);
}
}
| 2,136 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
TextTools.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/utils/TextTools.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.utils;
import org.apache.commons.lang.StringUtils;
public class TextTools {
public static String dquoteAround(String value) {
return '"' + value + '"';
}
public static boolean isQuote(char quote) {
return quote=='\'' || quote=='"';
}
/** remove chars less than 32 and replace with space */
public static String removeControlChars(String text) {
StringBuilder sb= new StringBuilder();
for (int i=0, n=StringUtils.length(text) ; i<n; i++) {
char ch= text.charAt(i);
if (ch < ' ') ch= ' ';
sb.append(ch);
}
return sb.toString();
}
}
| 1,363 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
Tuple3.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/utils/Tuple3.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.utils;
import org.apache.commons.lang.builder.*;
public class Tuple3<E1, E2, E3> {
private static final Tuple3<?, ?, ?> NULL= tuple3(null, null, null);
public final E1 e1;
public final E2 e2;
public final E3 e3;
public Tuple3(E1 e1, E2 e2, E3 e3) {
this.e1= e1;
this.e2= e2;
this.e3= e3;
}
public static <E1, E2, E3> Tuple3<E1, E2, E3> tuple3(E1 e1, E2 e2, E3 e3) {
return new Tuple3<E1, E2, E3>(e1, e2, e3);
}
@SuppressWarnings("unchecked")
public static <E1, E2, E3> Tuple3<E1, E2, E3> nil() {
return (Tuple3<E1, E2, E3>) NULL;
}
public boolean isNull() {
return this == NULL;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
@Override
public boolean equals(Object obj) {
if (obj == null) { return false; }
if (obj == this) { return true; }
if (obj.getClass() != getClass()) { return false; }
@SuppressWarnings("unchecked")
Tuple3<E1, E2, E3> rhs = (Tuple3<E1, E2, E3>) obj;
return new EqualsBuilder()
.append(e1, rhs.e1)
.append(e2, rhs.e2)
.append(e3, rhs.e3)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(e1)
.append(e2)
.append(e3)
.toHashCode();
}
}
| 2,200 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
Tuple2.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/utils/Tuple2.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.utils;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
public class Tuple2<E1, E2> {
@SuppressWarnings({ "unchecked", "rawtypes" })
private static final Tuple2 NULL= new Tuple2(null, null);
public final E1 e1;
public final E2 e2;
public Tuple2(E1 e1, E2 e2) {
this.e1= e1;
this.e2= e2;
}
public static <E1, E2> Tuple2<E1, E2> tuple2(E1 e1, E2 e2) {
return new Tuple2<E1, E2>(e1, e2);
}
@SuppressWarnings("unchecked")
public static <E1, E2> Tuple2<E1, E2> nil() {
return NULL;
}
public boolean isNull() {
return this == NULL;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
public static <E1, E2> Map<E1, E2> toMap(boolean skipNullValues, Tuple2<E1, E2>...tuples) {
Map<E1, E2> map= new LinkedHashMap<E1, E2>();
for (Tuple2<E1, E2> t: tuples) {
if (!skipNullValues || t.e2!=null) {
map.put(t.e1, t.e2);
}
}
return map;
}
}
| 1,996 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
ContentType.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/servlet/ContentType.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.servlet;
import static org.apache.commons.lang.StringUtils.*;
import org.apache.http.Header;
public class ContentType {
private static final String DEFAULT_CHARSET= "UTF-8";
public final String value;
public final String charset;
public final boolean isText;
public final boolean isBinary;
public final boolean isJavaScript;
public final String url;
public ContentType(Header header, String url) {
value= trimToEmpty( header.getValue() );
charset= extractCharset(value);
isText= isText(value);
isBinary= !isText;
this.url= url;
String path= extractPath(url);
isJavaScript= isJavaScript(path);
}
private static String extractCharset(String value) {
value= lowerCase( trimToEmpty(value));
String cs= substringAfter(value, "charset=");
if (isEmpty(cs)) return DEFAULT_CHARSET;
cs= trimToEmpty(cs);
cs= trim(substringBefore(cs, ";"));
if (isEmpty(cs)) cs= DEFAULT_CHARSET;
return cs;
}
private static boolean isText(String value) {
if (containsIgnoreCase(value, "image")) return false;
return true;
}
private static boolean isJavaScript(String path) {
return endsWithIgnoreCase(path, ".js");
}
private static String extractPath(String url) {
return substringBefore(url, "?");
}
}
| 2,083 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
ProxyFilter.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/servlet/ProxyFilter.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.servlet;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.tek271.reverseProxy.model.Mapping;
import com.tek271.reverseProxy.text.UrlMapper;
import com.tek271.reverseProxy.utils.Tuple2;
public class ProxyFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (!isHttp(request, response)) return;
Tuple2<Mapping, String> mapped = mapUrlProxyToHidden(request);
if (mapped.isNull()) {
chain.doFilter(request, response);
return;
}
executeRequest(response, mapped.e1, mapped.e2);
}
private static boolean isHttp(ServletRequest request, ServletResponse response) {
return (request instanceof HttpServletRequest) && (response instanceof HttpServletResponse);
}
private static Tuple2<Mapping, String> mapUrlProxyToHidden(ServletRequest request) {
String oldUrl = ((HttpServletRequest)request).getRequestURL().toString();
return UrlMapper.mapFullUrlProxyToHidden(oldUrl);
}
private static void executeRequest(ServletResponse response, Mapping mapping, String newUrl)
throws IOException, ClientProtocolException {
//System.out.println(newUrl);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(newUrl);
HttpResponse r = httpclient.execute(httpget);
HttpEntity entity = r.getEntity();
ContentTranslator contentTranslator= new ContentTranslator(mapping, newUrl);
contentTranslator.translate(entity, response);
}
}
| 2,656 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
ContentUtils.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/servlet/ContentUtils.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.servlet;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import com.google.common.base.Throwables;
public class ContentUtils {
public static void copyBinary(HttpEntity entity, ServletResponse response) {
try {
InputStream content = entity.getContent();
ServletOutputStream outputStream = response.getOutputStream();
IOUtils.copy(content, outputStream);
} catch (IOException e) {
Throwables.propagate(e);
}
}
public static void copyText(String text, ServletResponse response, ContentType contentType) {
//response.setCharacterEncoding(contentType.charset);
response.setContentType(contentType.value);
try {
response.getWriter().print(text);
} catch (IOException e) {
Throwables.propagate(e);
}
}
public static String getContentText(HttpEntity entity, String charset) {
try {
return IOUtils.toString(entity.getContent(), charset);
} catch (IOException e) {
Throwables.propagate(e);
return null;
}
}
}
| 1,950 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
ContentTranslator.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/servlet/ContentTranslator.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.servlet;
import javax.servlet.ServletResponse;
import org.apache.http.HttpEntity;
import com.tek271.reverseProxy.model.Mapping;
import com.tek271.reverseProxy.text.*;
public class ContentTranslator {
private final Mapping mapping;
private final String newUrl;
public ContentTranslator(Mapping mapping, String newUrl) {
this.mapping= mapping;
this.newUrl= newUrl;
}
public void translate(HttpEntity entity, ServletResponse response) {
if (entity==null) return;
ContentType contentType= new ContentType(entity.getContentType(), newUrl);
if (contentType.isBinary) {
ContentUtils.copyBinary(entity, response);
return;
}
String text = ContentUtils.getContentText(entity, contentType.charset);
if (contentType.isJavaScript) {
ContentUtils.copyText(text, response, contentType);
return;
}
text= translateText(text);
ContentUtils.copyText(text, response, contentType);
}
private String translateText(String text) {
TextTranslator textTranslator= new TextTranslator(mapping);
return textTranslator.translate(text);
}
}
| 1,894 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
TextTranslator.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/text/TextTranslator.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.text;
import java.util.List;
import com.google.common.collect.*;
import com.tek271.reverseProxy.model.*;
import static com.tek271.reverseProxy.model.RegexPair.*;
public class TextTranslator {
private static final RegexPair ANCHOR= pair("<[aA]\\b(\"[^\"]*\"|'[^']*'|[^'\">])*>", // match <a .*> tags
"\\bhref\\b\\s*=\\s*(\\S*?)[\\s>]"); // match href attribute value
private static final RegexPair IMAGE= pair("<img\\b(\"[^\"]*\"|'[^']*'|[^'\">])*>", // match <img .*> tags
"\\bsrc\\b\\s*=\\s*(\\S*?)[\\s>]"); // match src attribute value
private static final RegexPair LINK= pair("<link\\b(\"[^\"]*\"|'[^']*'|[^'\">])*>", // match <link .*> tags
"\\bhref\\b\\s*=\\s*(\\S*?)[\\s>]"); // match href attribute value
private static final RegexPair SCRIPT= pair("<script\\b(\"[^\"]*\"|'[^']*'|[^'\">])*>", // match <script .*> tags
"\\bsrc\\b\\s*=\\s*(\\S*?)[\\s>]"); // match src attribute value
private static final List<RegexPair> TAGS_PATTERNS= ImmutableList.of(ANCHOR, IMAGE, LINK, SCRIPT);
private final List<TagTranslator> tagTranslators= Lists.newArrayList();
public TextTranslator(Mapping mapping) {
for (RegexPair pair: TAGS_PATTERNS) {
tagTranslators.add( new TagTranslator(mapping, pair.tagPattern, pair.attributePattern) );
}
}
public String translate(String text) {
for (TagTranslator translator : tagTranslators) {
text= translator.translate(text);
}
return text;
}
}
| 2,447 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
UrlMapper.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/text/UrlMapper.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.text;
import static org.apache.commons.lang.StringUtils.*;
import com.tek271.reverseProxy.config.Config;
import com.tek271.reverseProxy.model.Mapping;
import com.tek271.reverseProxy.utils.Tuple2;
public class UrlMapper {
private Mapping currentMapping;
public UrlMapper(Mapping currentMapping) {
this.currentMapping= currentMapping;
}
public String mapContentUrl(String url) {
if (isEmpty(url)) return EMPTY;
if (startsWith(url, "/")) {
url = currentMapping.proxyResource + url;
}
url= mapFullUrlIfCan(url);
return url;
}
private static String mapFullUrlIfCan(String url) {
if (! isFullUrl(url)) return url;
Tuple2<Mapping, String> mapped = mapFullUrlHiddenToProxy(url);
if (mapped.isNull()) return url;
return mapped.e2;
}
private static Tuple2<Mapping, String> mapFullUrlHiddenToProxy(String fullHiddenUrl) {
Mapping mapping= Config.singleton.mappings.findByHiddenUrl(fullHiddenUrl);
if (mapping==null) return Tuple2.nil();
String newUrl= mapping.mapHiddenToProxy(fullHiddenUrl);
return Tuple2.tuple2(mapping, newUrl);
}
public static Tuple2<Mapping, String> mapFullUrlProxyToHidden(String fullProxyUrl) {
Mapping mapping= Config.singleton.mappings.findByProxyUrl(fullProxyUrl);
if (mapping==null) return Tuple2.nil();
String newUrl= mapping.mapProxyToHidden(fullProxyUrl);
return Tuple2.tuple2(mapping, newUrl);
}
private static boolean isFullUrl(String url) {
return startsWithIgnoreCase(url, "http://");
}
}
| 2,327 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
TagTranslator.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/text/TagTranslator.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.text;
import static org.apache.commons.lang.StringUtils.defaultString;
import static org.apache.commons.lang.StringUtils.left;
import static org.apache.commons.lang.StringUtils.substring;
import static org.apache.commons.lang.StringUtils.substringAfter;
import static org.apache.commons.lang.StringUtils.substringBetween;
import java.util.List;
import java.util.regex.Pattern;
import com.google.common.annotations.VisibleForTesting;
import com.tek271.reverseProxy.model.Mapping;
import com.tek271.reverseProxy.utils.*;
import static com.tek271.reverseProxy.utils.TextTools.*;
public class TagTranslator {
private final UrlMapper urlMapper;
private final Pattern tagPattern;
private final Pattern attributePattern;
public TagTranslator(Mapping mapping, Pattern tagPattern, Pattern attributePattern) {
this.urlMapper= new UrlMapper(mapping);
this.tagPattern= tagPattern;
this.attributePattern= attributePattern;
}
public String translate(String text) {
StringBuilder sb= new StringBuilder();
List<Tuple3<Integer, Integer, String>> matches = RegexTools.findAll(tagPattern, text, false);
int lastEnd=0;
for (Tuple3<Integer, Integer, String> match : matches) {
sb.append(text.substring(lastEnd, match.e1));
sb.append( translateTag(match.e3) );
lastEnd= match.e2;
}
String remaining = substring(text, lastEnd);
sb.append(defaultString(remaining));
return sb.toString();
}
@VisibleForTesting
String translateTag(String tag) {
Tuple3<Integer, Integer, String> value = attributeValue(tag);
if (value.isNull()) return tag;
String newUrl = urlMapper.mapContentUrl(value.e3);
return left(tag, value.e1) + dquoteAround(newUrl) + substring(tag, value.e2);
}
@VisibleForTesting
Tuple3<Integer, Integer, String> attributeValue(String tag) {
String normalized= TextTools.removeControlChars(tag);
List<Tuple3<Integer, Integer, String>> matches = RegexTools.findAll(attributePattern, normalized, true);
if (matches.isEmpty()) return Tuple3.nil();
Tuple3<Integer, Integer, String> match = matches.get(0);
String value = match.e3;
char quote= value.charAt(0);
if (isQuote(quote)) {
value= extractBetweenQuotes(value, quote);
}
return Tuple3.tuple3(match.e1, match.e2, value);
}
private static String extractBetweenQuotes(String value, char quote) {
String q = String.valueOf(quote);
String v= substringBetween(value, q);
if (v==null) v= substringAfter(value, q);
return v;
}
}
| 3,328 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
Mappings.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/model/Mappings.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.model;
import static org.apache.commons.lang.StringUtils.*;
import java.util.ArrayList;
public class Mappings extends ArrayList<Mapping> {
private static final long serialVersionUID = 1L;
public static Mappings create(Mapping...mappings) {
Mappings r= new Mappings();
for (Mapping mapping: mappings) {
r.add(mapping);
}
return r;
}
private static final String SEP = "://";
public Mapping findByProxyUrl(String proxyUrl) {
String noProtocol= substringAfter(proxyUrl, SEP);
for (Mapping mapping: this) {
if (startsWithIgnoreCase(noProtocol, mapping.proxy)) return mapping;
}
return null;
}
public Mapping findByHiddenUrl(String hiddenUrl) {
String noProtocol= substringAfter(hiddenUrl, SEP);
for (Mapping mapping: this) {
if (startsWithIgnoreCase(noProtocol, mapping.hiddenDomain)) return mapping;
}
return null;
}
}
| 1,687 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
Mapping.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/model/Mapping.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.model;
import static org.apache.commons.lang.StringUtils.*;
import java.util.List;
import com.google.common.base.*;
import com.google.common.collect.Lists;
import static com.google.common.base.Preconditions.*;
public class Mapping {
public final String hiddenDomain;
public final String proxyDomain;
public final String proxyResource;
public final String proxy;
public Mapping(String mapping) {
checkArgument(isNotBlank(mapping), "mapping must contain a value");
mapping= trimToEmpty(mapping);
List<String> items= Lists.newArrayList(Splitter.on(',').trimResults().split(mapping));
checkArgument(items.size()==3, "mappings must have 3 comma-separated values");
hiddenDomain= items.get(0);
proxyDomain= items.get(1);
proxyResource= items.get(2);
proxy= proxyDomain + proxyResource;
}
private static final String SEP = "://";
public String mapProxyToHidden(String proxyUrl) {
String path = extractPath(proxyUrl, proxyDomain, proxyResource);
return extractProtocol(proxyUrl) + SEP + hiddenDomain + path;
}
public String mapHiddenToProxy(String hiddenUrl) {
String path = extractPath(hiddenUrl, hiddenDomain, "");
return extractProtocol(hiddenUrl) + SEP + proxy + path;
}
private static String extractProtocol(String url) {
return substringBefore(url, SEP);
}
private String extractPath(String url, String domain, String resource) {
String prefix= domain + resource;
return substringAfter(url, prefix);
}
}
| 2,291 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
RegexPair.java | /FileExtraction/Java_unseen/ahabra_reverse-proxy/project/src/main/java/com/tek271/reverseProxy/model/RegexPair.java | /*
This file is part of Tek271 Reverse Proxy Server.
Tek271 Reverse Proxy Server 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 3 of the License, or
(at your option) any later version.
Tek271 Reverse Proxy Server 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Tek271 Reverse Proxy Server. If not, see http://www.gnu.org/licenses/
*/
package com.tek271.reverseProxy.model;
import java.util.regex.Pattern;
import com.google.common.base.Objects;
public class RegexPair {
public final Pattern tagPattern;
public final Pattern attributePattern;
private final String tagRegex;
private final String attributeRegex;
private RegexPair(String tagRegex, String attributeRegex) {
tagPattern= Pattern.compile(tagRegex, Pattern.CASE_INSENSITIVE);
attributePattern= Pattern.compile(attributeRegex, Pattern.CASE_INSENSITIVE);
this.tagRegex= tagRegex;
this.attributeRegex= attributeRegex;
}
public static RegexPair pair(String tagRegex, String attributeRegex) {
return new RegexPair(tagRegex, attributeRegex);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("tagRegex", tagRegex)
.add("attributeRegex", attributeRegex)
.toString();
}
}
| 1,642 | Java | .java | ahabra/reverse-proxy | 33 | 14 | 2 | 2011-03-13T21:38:24Z | 2011-03-26T04:51:43Z |
RSACipherTesting.java | /FileExtraction/Java_unseen/gonespy_bstormps3/test/main/java/com/gonespy/service/testing/RSACipherTesting.java | package com.gonespy.service.testing;
import com.gonespy.service.shared.Constants;
import com.gonespy.service.util.CertificateUtils;
import org.junit.Ignore;
import org.junit.Test;
import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
public class RSACipherTesting {
@Test
@Ignore
public void atlasCheck() throws Exception {
// gamespy ATLAS keys - doesnt work without private key
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(CertificateUtils.WS_AUTHSERVICE_SIGNATURE_KEY, 16), new BigInteger(CertificateUtils.WS_AUTHSERVICE_SIGNATURE_EXP, 16)); // game client
RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(new BigInteger(CertificateUtils.WS_AUTHSERVICE_SIGNATURE_KEY, 16), new BigInteger(CertificateUtils.WS_AUTHSERVICE_SIGNATURE_PRIVATE_EXP, 16)); // gamespy server - PRIVATE KEY UNKNOWN
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
// encrypt the message
byte [] encrypted = encrypt(privateKey, "This is a secret message");
System.out.println(new String(encrypted)); // <<encrypted message>>
// decrypt the message
byte[] secret = decrypt(pubKey, encrypted);
System.out.println(DatatypeConverter.printHexBinary(secret));
System.out.println(new String(secret)); // This is a secret message
}
@Test
public void eaEmuCheck() throws Exception {
// test peer keys from eaEmu
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(CertificateUtils.PEER_KEY_MODULUS, 16), new BigInteger(CertificateUtils.WS_AUTHSERVICE_SIGNATURE_EXP, 16));
RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(new BigInteger(CertificateUtils.PEER_KEY_MODULUS, 16), new BigInteger(Constants.PEER_KEY_PRIVATE, 16));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
// encrypt the message
byte [] encrypted = encrypt(privateKey, "This is a secret message");
System.out.println(new String(encrypted)); // <<encrypted message>>
// decrypt the message
byte[] secret = decrypt(pubKey, encrypted);
System.out.println(new String(secret)); // This is a secret message
}
@Test
public void atlasWithEaEmuSig() throws Exception {
// gamespy ATLAS keys
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(CertificateUtils.WS_AUTHSERVICE_SIGNATURE_KEY, 16), new BigInteger(CertificateUtils.WS_AUTHSERVICE_SIGNATURE_EXP, 16)); // game client
// try decrypting this:
byte[] encrypted = DatatypeConverter.parseHexBinary("181A4E679AC27D83543CECB8E1398243113EF6322D630923C6CD26860F265FC031C2C61D4F9D86046C07BBBF9CF86894903BD867E3CB59A0D9EFDADCB34A7FB3CC8BC7650B48E8913D327C38BB31E0EEB06E1FC1ACA2CFC52569BE8C48840627783D7FFC4A506B1D23A1C4AEAF12724DEB12B5036E0189E48A0FCB2832E1FB00");
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
System.out.println(new String(encrypted)); // <<encrypted message>>
// decrypt the message
// decrypts to [md5Header][md5Hash]
// [3020300C06082A864886F70D020505000410][6A9F632A5175F4C4AEAF4C6B7A3615EA]
// (why is the header/padding missing? does java decrypt remove it for you?)
byte[] secret = decrypt(pubKey, encrypted);
System.out.println(DatatypeConverter.printHexBinary(secret));
System.out.println(new String(secret)); // This is a secret message
}
@Test
public void exampleCheck() throws Exception {
final String EXAMPLE_MOD = ("00df1e0a07074067271ff8853d03ab" +
"f2124f42da7b7725585f7c105363fb" +
"72886a108de34c4f56630bb9010d43" +
"a7794e8ea8412c8ce6993192c74f7d" +
"38e57f8e953f88e54068d72b8bf247" +
"32e61f6457f499f80ba759221d2966" +
"50f0dca2282439b808b93ea923f805" +
"85701e7aa704c17516b0c3739d4556" +
"ccb27854b899a5c1e7");
final String EXAMPLE_PUBLIC_EXP = "10001";
final String EXAMPLE_PRIVATE_EXP = ("00d68804ae435bba93951b19c9d408" +
"f5c6832dcdf41f58ea434d80491e7e" +
"bcdecbd54508c3ec192d3d2d530495" +
"03a8114ffc1a46a2e86b6e8e2a5495" +
"1c2b175e58f9c2fcb9d4944bf99781" +
"b6f6cb6f2260e64a950eab6f9724d6" +
"995a4ca8f22307ec1057d1d1c50916" +
"c6a2927b214b199dfa3ee40b65efb5" +
"71335da094d6fc0399");
// test some generated keys
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(EXAMPLE_MOD, 16), new BigInteger(EXAMPLE_PUBLIC_EXP, 16));
RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(new BigInteger(EXAMPLE_MOD, 16), new BigInteger(EXAMPLE_PRIVATE_EXP, 16));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
// encrypt the message
byte [] encrypted = encrypt(privateKey, "This is a secret message");
System.out.println(new String(encrypted)); // <<encrypted message>>
// decrypt the message
byte[] secret = decrypt(pubKey, encrypted);
System.out.println(new String(secret)); // This is a secret message
}
private static byte[] encrypt(PrivateKey privateKey, String message) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(message.getBytes());
}
private static byte[] decrypt(PublicKey publicKey, byte [] encrypted) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(encrypted);
}
} | 6,409 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
RsaExample.java | /FileExtraction/Java_unseen/gonespy_bstormps3/test/main/java/com/gonespy/service/testing/RsaExample.java | package com.gonespy.service.testing;
import org.apache.commons.codec.digest.DigestUtils;
import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;
import java.security.*;
import static java.nio.charset.StandardCharsets.UTF_8;
public class RsaExample {
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024, new SecureRandom());
KeyPair pair = generator.generateKeyPair();
return pair;
}
public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherText = encryptCipher.doFinal(plainText.getBytes(UTF_8));
return DatatypeConverter.printHexBinary(cipherText);
}
public static String decrypt(String cipherText, PrivateKey privateKey) throws Exception {
//byte[] bytes = Base64.getDecoder().decode(cipherText);
byte[] bytes = DatatypeConverter.parseHexBinary(cipherText);
Cipher decriptCipher = Cipher.getInstance("RSA");
decriptCipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(decriptCipher.doFinal(bytes), UTF_8);
}
public static String sign(String plainText, PrivateKey privateKey) throws Exception {
Signature privateSignature = Signature.getInstance("MD5withRSA");
privateSignature.initSign(privateKey);
privateSignature.update(plainText.getBytes(UTF_8));
byte[] signature = privateSignature.sign();
return DatatypeConverter.printHexBinary(signature);
}
public static boolean verify(String plainText, String signature, PublicKey publicKey) throws Exception {
Signature publicSignature = Signature.getInstance("MD5withRSA");
publicSignature.initVerify(publicKey);
publicSignature.update(plainText.getBytes(UTF_8));
byte[] signatureBytes = DatatypeConverter.parseHexBinary(signature);
return publicSignature.verify(signatureBytes);
}
public static void main(String... argv) throws Exception {
//First generate a public/private key pair
KeyPair pair = generateKeyPair();
//Our secret message
String message = "the answer to life the universe and everything";
//Encrypt the message
String cipherText = encrypt(message, pair.getPublic());
//Now decrypt it
String decipheredMessage = decrypt(cipherText, pair.getPrivate());
System.out.println(decipheredMessage);
//Let's sign our message
String signature = sign("foobar", pair.getPrivate());
// md5
String md5 = DigestUtils.md5Hex("foobar");
// 3858f62230ac3c915f300c664312c63f
// decrypt instead of checking signing
String decryptedSignature = decrypt(signature, pair.getPublic());
// [3020300C06082A864886F70D020505000410][3858F62230AC3C915F300C664312C63F]
// cf. decrypted signature from eaEmu - MD5 header matches :)
// [3020300C06082A864886F70D020505000410][6A9F632A5175F4C4AEAF4C6B7A3615EA]
//Let's check the signature
boolean isCorrect = verify("foobar", signature, pair.getPublic());
System.out.println("Signature correct: " + isCorrect);
}
public static String decrypt(String cipherText, PublicKey publicKey) throws Exception {
//byte[] bytes = Base64.getDecoder().decode(cipherText);
byte[] bytes = DatatypeConverter.parseHexBinary(cipherText);
Cipher decriptCipher = Cipher.getInstance("RSA");
decriptCipher.init(Cipher.DECRYPT_MODE, publicKey);
return DatatypeConverter.printHexBinary(decriptCipher.doFinal(bytes));
}
} | 3,834 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
TestStringUtils.java | /FileExtraction/Java_unseen/gonespy_bstormps3/test/main/java/com/gonespy/service/util/TestStringUtils.java | package com.gonespy.service.util;
import org.junit.Ignore;
import org.junit.Test;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.gonespy.service.util.CertificateUtils.SERVER_DATA;
import static com.google.common.truth.Truth.assertThat;
public class TestStringUtils {
// GOLDEN MD5 - this is what signature contains & what we need!
private static final String EA_EMU_MD5 = "6a9f632a5175f4c4aeaf4c6b7a3615ea";
@Test
public void testGsLoginProof() {
String md5 = StringUtils.gsLoginProof("password","user","clientchallenge","serverchallenge");
assertThat(md5).isEqualTo("19a0f989ac154aaf8039b2af1ea314bb");
}
@Test
public void testHashCertificate() {
Map<String, String> certificateData = new LinkedHashMap<>();
fillIntegers(certificateData);
fillStrings(certificateData);
fillPeerKey(certificateData);
fillServerData(certificateData);
String md5 = StringUtils.hashCertificate(certificateData);
assertThat(md5).isEqualTo("535350f3423eb1d125a54b39e7b3a57f"); // verified in C v2
assertThat(md5).isEqualTo(EA_EMU_MD5); // what we actually want
}
@Test
@Ignore
public void testHashCertificateExperiment() {
Map<String, String> certificateData = new LinkedHashMap<>();
fillIntegers(certificateData);
fillStrings(certificateData);
fillPeerKey(certificateData);
fillServerData(certificateData);
for(int partnerCode=0; partnerCode<=1; partnerCode++) {
for(int namespaceId=0; namespaceId<=1; namespaceId++) {
for(int version=0; version<=5; version++) {
for(int userId=0; userId<=10000; userId++) {
for (int profileId = 0; profileId <= 10000; profileId++) {
certificateData.put("version", "" + version);
certificateData.put("partnercode", "" + partnerCode);
certificateData.put("namespaceid", "" + namespaceId);
certificateData.put("userid", "" + userId);
certificateData.put("profileid", "" + profileId);
String md5 = StringUtils.hashCertificate(certificateData).toLowerCase();
//System.out.println(md5);
if (md5.equals(EA_EMU_MD5)) {
System.out.println("partnerCode=" + partnerCode + ",namespaceId=" + namespaceId + ",version=" + version);
}
}
}
}
}
}
}
@Test
public void testHashCertificateIntegers() {
Map<String, String> certificateData = new LinkedHashMap<>();
fillIntegers(certificateData);
String md5 = StringUtils.hashCertificate(certificateData);
assertThat(md5).isEqualTo("7b5634841b57ff7bf9ccc97750f13621"); // verified in C
}
@Test
public void testHashCertificateStrings() {
Map<String, String> certificateData = new LinkedHashMap<>();
fillIntegers(certificateData);
fillStrings(certificateData);
String md5 = StringUtils.hashCertificate(certificateData);
assertThat(md5).isEqualTo("e2f084037c39bd2bcf3f936dd2fe2a81"); // verified in C
}
@Test
public void testHashCertificateServerData() {
Map<String, String> certificateData = new LinkedHashMap<>();
fillIntegers(certificateData);
fillStrings(certificateData);
fillServerData(certificateData);
String md5 = StringUtils.hashCertificate(certificateData);
assertThat(md5).isEqualTo("c0ebc484d51e2797d23d6e737ce2cc04"); // verified in C
}
private static void fillIntegers(Map<String, String> certificateData) {
certificateData.put("length", "303");
certificateData.put("version", "1");
certificateData.put("partnercode", "0");
certificateData.put("namespaceid", "0");
certificateData.put("userid", "11111");
certificateData.put("profileid", "22222");
certificateData.put("expiretime", "0");
}
private static void fillStrings(Map<String, String> certificateData) {
certificateData.put("profilenick", "Jackalus");
certificateData.put("uniquenick", "Jackalus");
certificateData.put("cdkeyhash", "");
}
private static void fillPeerKey(Map<String, String> certificateData) {
certificateData.put("peerkeymodulus",
"95375465E3FAC4900FC912E7B30EF7171B0546DF4D185DB04F21C79153CE091859DF2EBDDFE5047D80C2EF86A2169B05A933AE2EAB2962F7B32CFE3CB0C25E7E3A26BB6534C9CF19640F1143735BD0CEAA7AA88CD64ACEC6EEB037007567F1EC51D00C1D2F1FFCFECB5300C93D6D6A50C1E3BDF495FC17601794E5655C476819");
certificateData.put("peerkeyexponent", "010001");
}
private static void fillServerData(Map<String, String> certificateData) {
certificateData.put("serverdata", SERVER_DATA);
}
}
| 5,062 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
TestGsLargeInt.java | /FileExtraction/Java_unseen/gonespy_bstormps3/test/main/java/com/gonespy/service/util/TestGsLargeInt.java | package com.gonespy.service.util;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import java.util.Arrays;
import static com.google.common.truth.Truth.assertThat;
// NOTE: all functions tested against C except where specified
public class TestGsLargeInt {
@Test
public void testGsLargeIntSetFromHexStringShorter() {
String hex = "1";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
assertThat(s.length).isEqualTo(1);
assertThat(Arrays.copyOfRange(s.data,0, s.length)).asList().isEqualTo(ImmutableList.of(1L));
}
@Test
public void testGsLargeIntSetFromHexStringShort() {
String hex = "01f";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
assertThat(s.length).isEqualTo(1);
assertThat(Arrays.copyOfRange(s.data,0, s.length)).asList().isEqualTo(ImmutableList.of(31L));
}
@Test
public void testGsLargeIntSetFromHexStringShort2() {
String hex = "01ff";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
assertThat(s.length).isEqualTo(1);
assertThat(Arrays.copyOfRange(s.data,0, s.length)).asList().isEqualTo(ImmutableList.of(511L));
}
@Test
public void testGsLargeIntSetFromHexStringLong() {
String hex = "01234567890123456789";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
assertThat(s.length).isEqualTo(3);
assertThat(Arrays.copyOfRange(s.data,0, s.length)).asList().isEqualTo(ImmutableList.of(591751049L, 1164413185L, 291L));
}
@Test
public void testGsLargeIntSetFromHexStringManyFs() {
String hex = "ffffffffffffffffffff";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
assertThat(s.length).isEqualTo(3);
assertThat(Arrays.copyOfRange(s.data,0, s.length)).asList().isEqualTo(ImmutableList.of(4294967295L, 4294967295L, 65535L));
}
@Test
public void testGsLargeIntSetFromHexString256Chars() {
String hex = "95375465E3FAC4900FC912E7B30EF7171B0546DF4D185DB04F21C79153CE091859DF2EBDDFE5047D80C2EF86A2169B05A933AE2EAB2962F7B32CFE3CB0C25E7E3A26BB6534C9CF19640F1143735BD0CEAA7AA88CD64ACEC6EEB037007567F1EC51D00C1D2F1FFCFECB5300C93D6D6A50C1E3BDF495FC17601794E5655C476819";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
assertThat(s.length).isEqualTo(32);
assertThat(Arrays.copyOfRange(s.data, 0, s.length)).asList().isEqualTo(ImmutableList.of(1548183577L,395634021L,2516326240L,3252927988L,1030580816L,3411214537L,790625534L,1372589085L,1969746412L,4004525824L,3595226822L,2860165260L,1935397070L,1678709059L,885640985L,975616869L,2965528190L,3006070332L,2871616247L,2838736430L,2719390469L,2160258950L,3756328061L,1507798717L,1406011672L,1327613841L,1293442480L,453330655L,3004102423L,264835815L,3824862352L,2503431269L));
}
@Test
public void testGsLargeIntReverseBytesOneLength() {
GsLargeInt s = new GsLargeInt();
s.length = 1;
s.data[0] = 511L;
s.gsLargeIntReverseBytes();
assertThat(s.length).isEqualTo(1);
assertThat(Arrays.copyOfRange(s.data,0, s.length)).asList().isEqualTo(ImmutableList.of(511L));
}
@Test
public void testGsLargeIntReverseBytesZeroLength() {
GsLargeInt s = new GsLargeInt();
s.length = 0;
s.gsLargeIntReverseBytes();
assertThat(s.length).isEqualTo(0);
}
@Test
public void testGsLargeIntReverseBytesOdd() {
GsLargeInt s = new GsLargeInt();
s.length = 3;
s.data[0] = 1L;
s.data[1] = 2L;
s.data[2] = 3L;
s.gsLargeIntReverseBytes();
assertThat(s.length).isEqualTo(3);
assertThat(Arrays.copyOfRange(s.data,0, s.length)).asList().isEqualTo(ImmutableList.of(3L, 2L, 1L));
}
@Test
public void testGsLargeIntReverseBytesEven() {
GsLargeInt s = new GsLargeInt();
s.length = 4;
s.data[0] = 1L;
s.data[1] = 2L;
s.data[2] = 3L;
s.data[3] = 4L;
s.gsLargeIntReverseBytes();
assertThat(s.length).isEqualTo(4);
assertThat(Arrays.copyOfRange(s.data,0, s.length)).asList().isEqualTo(ImmutableList.of(4L, 3L, 2L, 1L));
}
@Test
public void testGsLargeIntGetByteLengthZeroLength() {
String hex = "";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
long byteLength = s.gsLargeIntGetByteLength();
assertThat(byteLength).isEqualTo(0);
}
@Test
public void testGsLargeIntGetByteLengthZero() {
String hex = "0";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
long byteLength = s.gsLargeIntGetByteLength();
assertThat(byteLength).isEqualTo(0);
}
@Test
public void testGsLargeIntGetByteLengthShorter() {
String hex = "1";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
long byteLength = s.gsLargeIntGetByteLength();
assertThat(byteLength).isEqualTo(1);
}
@Test
public void testGsLargeIntGetByteLengthShort() {
String hex = "01f";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
long byteLength = s.gsLargeIntGetByteLength();
assertThat(byteLength).isEqualTo(1);
}
@Test
public void testGsLargeIntGetByteLengthShort22() {
String hex = "10f";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
long byteLength = s.gsLargeIntGetByteLength();
assertThat(byteLength).isEqualTo(2);
}
@Test
public void testGsLargeIntGetByteLengthShort2() {
String hex = "01ff";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
long byteLength = s.gsLargeIntGetByteLength();
assertThat(byteLength).isEqualTo(2);
}
@Test
public void testGsLargeIntGetByteLengthLong() {
String hex = "01234567890123456789";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
long byteLength = s.gsLargeIntGetByteLength();
assertThat(byteLength).isEqualTo(10);
}
@Test
public void testGsLargeIntGetByteLengthManyFs() {
String hex = "ffffffffffffffffffff";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
long byteLength = s.gsLargeIntGetByteLength();
assertThat(byteLength).isEqualTo(10);
}
@Test
public void testGsLargeIntGetByteLength256Chars() {
String hex = "95375465E3FAC4900FC912E7B30EF7171B0546DF4D185DB04F21C79153CE091859DF2EBDDFE5047D80C2EF86A2169B05A933AE2EAB2962F7B32CFE3CB0C25E7E3A26BB6534C9CF19640F1143735BD0CEAA7AA88CD64ACEC6EEB037007567F1EC51D00C1D2F1FFCFECB5300C93D6D6A50C1E3BDF495FC17601794E5655C476819";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
long byteLength = s.gsLargeIntGetByteLength();
assertThat(byteLength).isEqualTo(128);
}
@Test
// TODO: more tests
// TODO: test against C?
public void testDataAsByteArray() {
String hex = "1";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
byte[] bytes = s.dataAsByteArray();
assertThat(bytes).asList().hasSize(4);
}
@Test
public void testToHexStringFourBytes() {
String hex = "00070001";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
String hexAgain = s.toHexString();
assertThat(hexAgain).isEqualTo(hex);
}
@Test
public void testToHexString128Bytes() {
String hex = "95375465E3FAC4900FC912E7B30EF7171B0546DF4D185DB04F21C79153CE091859DF2EBDDFE5047D80C2EF86A2169B05A933AE2EAB2962F7B32CFE3CB0C25E7E3A26BB6534C9CF19640F1143735BD0CEAA7AA88CD64ACEC6EEB037007567F1EC51D00C1D2F1FFCFECB5300C93D6D6A50C1E3BDF495FC17601794E5655C476819";
GsLargeInt s = GsLargeInt.gsLargeIntSetFromHexString(hex);
String hexAgain = s.toHexString();
assertThat(hexAgain).isEqualTo(hex);
}
}
| 7,979 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
TestCertificateUtils.java | /FileExtraction/Java_unseen/gonespy_bstormps3/test/main/java/com/gonespy/service/util/TestCertificateUtils.java | package com.gonespy.service.util;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import javax.crypto.Cipher;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPublicKeySpec;
import java.util.Map;
import static com.google.common.truth.Truth.assertThat;
public class TestCertificateUtils {
@Test
public void testGetCertificate() {
Map<String, Object> input = ImmutableMap.of(
"partnercode", "0",
"namespaceid", "0",
"version", "1"
);
Map<String, String> certificate = CertificateUtils.getCertificate(input);
assertThat(certificate).hasSize(14);
assertThat(certificate).containsEntry("length", "303");
assertThat(certificate).containsEntry("version", "1");
assertThat(certificate).containsEntry("partnercode", "0");
assertThat(certificate).containsEntry("namespaceid", "0");
assertThat(certificate).containsEntry("userid", "6666");
assertThat(certificate).containsEntry("profileid", "7777");
assertThat(certificate).containsEntry("expiretime", "0");
assertThat(certificate).containsEntry("profilenick", "BulletstormPlayer");
assertThat(certificate).containsEntry("uniquenick", "BulletstormPlayer");
assertThat(certificate).containsEntry("cdkeyhash", "");
assertThat(certificate).containsEntry("peerkeymodulus", "95375465E3FAC4900FC912E7B30EF7171B0546DF4D185DB04F21C79153CE091859DF2EBDDFE5047D80C2EF86A2169B05A933AE2EAB2962F7B32CFE3CB0C25E7E3A26BB6534C9CF19640F1143735BD0CEAA7AA88CD64ACEC6EEB037007567F1EC51D00C1D2F1FFCFECB5300C93D6D6A50C1E3BDF495FC17601794E5655C476819");
assertThat(certificate).containsEntry("peerkeyexponent", "010001");
assertThat(certificate).containsEntry("serverdata", "908EA21B9109C45591A1A011BF84A18940D22E032601A1B2DD235E278A9EF131404E6B07F7E2BE8BF4A658E2CB2DDE27E09354B7127C8A05D10BB4298837F96518CCB412497BE01ABA8969F9F46D23EBDE7CC9BE6268F0E6ED8209AD79727BC8E0274F6725A67CAB91AC87022E5871040BF856E541A76BB57C07F4B9BE4C6316");
String signature = certificate.get("signature");
assertThat(signature).hasLength(256);
//assertThat(signature).isEqualTo("6846C883E473E0037E9D7C490F1676F49E868BCFCBBF98A28467435A4261C81D52D6F7C607A452376976D896DE8EF8440D8A4595233063D5F88AE80E3AF5CE36F89D4CF18322E109F23B2531F70BB4B3B3F413C1DD9026FA4DBE061468E1CEFCE6255C428071D8D25C6F27ED1A65DB775E9F4EA5EFA093D3629FE32C81B327BD");
//String descrypted = decrypt(CertificateUtils.WS_AUTHSERVICE_SIGNATURE_KEY, CertificateUtils.WS_AUTHSERVICE_SIGNATURE_EXP, signature);
//assertThat(descrypted).isEqualTo(
// CertificateUtils.CRYPTO_PREFIX + Strings.repeat("FF", 80) + CertificateUtils.CRYPTO_SEPARATOR_BYTE +
// CertificateUtils.MD5_HEADER_STRING + "e52fe9ab3aad190b99598845f07a3f3a"
//);
}
private String decrypt(String modString, String expString, String base) {
try {
Cipher cipher = Cipher.getInstance("RSA");
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//String modString = mod.toHexString();
//String expString = power.toHexString();
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modString, 16), new BigInteger(expString, 16));
RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
cipher.init(Cipher.DECRYPT_MODE, pubKey);
byte[] cipherText = cipher.doFinal(GsLargeInt.gsLargeIntSetFromHexString(base).dataAsByteArray());
//String encrypted = new String(cipherText);
//System.out.println("cipher: " + encrypted);
byte[] bytes = cipherText;
StringBuilder sb = new StringBuilder();
for(int i = bytes.length - 1; i >= 0; i -= Integer.BYTES) {
for(int j = i-3; j <= i; j++) {
sb.append(String.format("%02X", bytes[j]));
}
}
String decrypted = sb.toString();
return decrypted;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
}
| 4,338 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
TestSoapUtils.java | /FileExtraction/Java_unseen/gonespy_bstormps3/test/main/java/com/gonespy/service/util/TestSoapUtils.java | package com.gonespy.service.util;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import java.util.Map;
import static com.google.common.truth.Truth.assertThat;
public class TestSoapUtils {
@Test
public void testEmptySoapTag() {
String tag = SoapUtils.emptySoapTag("sometag");
assertThat(tag).isEqualTo("<ns1:sometag></ns1:sometag>");
}
@Test
public void testCreateSoapTagWithValue() {
String tag = SoapUtils.createSoapTagWithValue("sometag", "somevalue");
assertThat(tag).isEqualTo("<ns1:sometag>somevalue</ns1:sometag>");
}
@Test
public void testWrapSoapData() {
String path = "mypath";
String type = "mytype";
String soapData = "SOME_SOAP_DATA";
String finalSoapData = SoapUtils.wrapSoapData(path, type, soapData);
assertThat(finalSoapData).isEqualTo(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:ns1=\"http://gamespy.net/" + path + "\"><SOAP-ENV:Body>" +
"<ns1:" + type + ">" + soapData + "</ns1:" + type + ">" +
"</SOAP-ENV:Body></SOAP-ENV:Envelope>\r\n"
);
}
@Test
public void testParseSoapData() {
String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:ns1=\"http://gamespy.net/AuthService/\"><SOAP-ENV:Body><ns1:LoginPs3Cert><ns1:version>1</ns1:version><ns1:gameid>2188</ns1:gameid><ns1:partnercode>0</ns1:partnercode><ns1:namespaceid>0</ns1:namespaceid><ns1:npticket><ns1:Value>IQEAAAAAAPAwAACkAAgAFPIyPmD0qSOwfjWy2CLrmF65ZbzVAAEABAAAAQAABwAIAAABYnMkGq4ABwAIAAABYnMtP4AAAgAIFBsdFI2xVbMABAAgRG9jdG9yX19fUm9ja3pvAAAAAAAAAAAAAAAAAAAAAAAACAAEdXMAAQAEAARkMQAAAAgAGFVQMTAxOC1CTFVTMzAyNTFfMDAAAAAAAAABAAQkAAIAAAAAAAAAAAAwAgBEAAgABCJfNjgACAA4MDQCGGPoGctsiTp228enBIE0uh3YBvuxMQ1QzgIYbjniP4oW4FdH8X5r7i8sDuw09WTBzvsoAAA=</ns1:Value></ns1:npticket></ns1:LoginPs3Cert></SOAP-ENV:Body></SOAP-ENV:Envelope>";
Map<String, Object> map = SoapUtils.parseSoapData(data);
assertThat(map).hasSize(6);
assertThat(map).containsEntry("gameid", "2188");
assertThat(map).containsEntry("namespaceid", "0");
assertThat(map).containsEntry("partnercode", "0");
assertThat(map).containsEntry("ns1", "LoginPs3Cert");
assertThat(map).containsEntry("version", "1");
assertThat(map).containsEntry("npticket", ImmutableMap.of("Value", "IQEAAAAAAPAwAACkAAgAFPIyPmD0qSOwfjWy2CLrmF65ZbzVAAEABAAAAQAABwAIAAABYnMkGq4ABwAIAAABYnMtP4AAAgAIFBsdFI2xVbMABAAgRG9jdG9yX19fUm9ja3pvAAAAAAAAAAAAAAAAAAAAAAAACAAEdXMAAQAEAARkMQAAAAgAGFVQMTAxOC1CTFVTMzAyNTFfMDAAAAAAAAABAAQkAAIAAAAAAAAAAAAwAgBEAAgABCJfNjgACAA4MDQCGGPoGctsiTp228enBIE0uh3YBvuxMQ1QzgIYbjniP4oW4FdH8X5r7i8sDuw09WTBzvsoAAA="));
}
}
| 3,245 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
TestGPMessageUtils.java | /FileExtraction/Java_unseen/gonespy_bstormps3/test/main/java/com/gonespy/service/util/TestGPMessageUtils.java | package com.gonespy.service.util;
import org.junit.Test;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.google.common.truth.Truth.assertThat;
public class TestGPMessageUtils {
@Test
public void testParseClientLogin() {
String test = "\\login\\\\challenge\\ZXX7h9eiTe0EP5teW1yiajFqY5URTykw\\authtoken\\11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111\\partnerid\\19\\response\\fdd3c298e993ba03b70575a743a4e323\\port\\6500\\productid\\12999\\gamename\\bstormps3\\namespaceid\\28\\sdkrevision\\59\\quiet\\0\\id\\1\\final\\";
Map<String, String> map = GPMessageUtils.parseClientLogin(test);
assertThat(map).hasSize(11);
assertThat(map).doesNotContainKey("login");
assertThat(map).doesNotContainKey("final");
assertThat(map.get("challenge")).isEqualTo("ZXX7h9eiTe0EP5teW1yiajFqY5URTykw");
assertThat(map.get("id")).isEqualTo("1");
assertThat(map.get("partnerid")).isEqualTo("19");
}
@Test
public void testCreateGPMessage() {
Map<String,String> loginResponseData = new LinkedHashMap<>();
loginResponseData.put("lc", "2"); // int
loginResponseData.put("sesskey", "5555555555"); // int
loginResponseData.put("userid", "1234567890"); // int
loginResponseData.put("profileid", "9876543210"); // int
loginResponseData.put("lt", "XdR2LlH69XYzk3KCPYDkTY__"); // string
loginResponseData.put("proof", "someproof"); // int
loginResponseData.put("id", "1"); // int
String loginData = GPMessageUtils.createGPMessage(loginResponseData);
assertThat(loginData).isEqualTo("\\lc\\2" +
"\\sesskey\\5555555555" + // int
"\\userid\\1234567890" + // int
"\\profileid\\9876543210" + // int
"\\lt\\XdR2LlH69XYzk3KCPYDkTY__" + // string
"\\proof\\someproof"+
"\\id\\1" +
"\\final\\");
}
@Test
public void testCreateGPEmptyListMessage() {
String blkData = GPMessageUtils.createGPEmptyListMessage("blk");
assertThat(blkData).isEqualTo("\\blk\\0\\list\\\\final\\");
}
@Test
public void testGetGPDirective() {
String data = GPMessageUtils.getGPDirective("\\blah\\1\\foo\\x\\bar\\1\\final\\");
assertThat(data).isEqualTo("blah");
}
@Test
public void testGetGPDirectiveNull() {
String data = GPMessageUtils.getGPDirective("blah\\1\\foo\\x\\bar\\1\\final\\");
assertThat(data).isNull();
}
}
| 2,637 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
RunAllServices.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/RunAllServices.java | package com.gonespy.service;
import com.gonespy.service.auth.AuthService;
import com.gonespy.service.availability.AvailabilityService;
import com.gonespy.service.gpcm.GPCMService;
import com.gonespy.service.gpsp.GPSPService;
import com.gonespy.service.sake.SakeService;
import com.gonespy.service.stats.GStatsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RunAllServices {
private static final String DISPLAY_NAME = RunAllServices.class.getSimpleName();
private static final Logger LOG = LoggerFactory.getLogger(DISPLAY_NAME);
public static void main(String[] args) {
Thread availabilityServiceThread = new Thread(() -> new AvailabilityService().run());
Thread gpcmServiceThread = new Thread(() -> new GPCMService().run());
Thread gpspServiceThread = new Thread(() -> new GPSPService().run());
Thread gstatsServiceThread = new Thread(() -> new GStatsService().run());
Thread authServiceThread = new Thread(() -> AuthService.main(new String[]{"server", "resources/dw-auth-config.yml"}));
Thread sakeServiceThread = new Thread(() -> SakeService.main(new String[]{"server", "resources/dw-sake-config.yml"}));
gpcmServiceThread.start();
availabilityServiceThread.start();
gpspServiceThread.start();
gstatsServiceThread.start();
authServiceThread.start();
DropwizardProbe.probeOnPort(443, true);
sakeServiceThread.start();
DropwizardProbe.probeOnPort(80, true);
LOG.info("=== ALL SERVICES STARTED! ===");
}
}
| 1,590 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
DropwizardProbe.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/DropwizardProbe.java | package com.gonespy.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
public abstract class DropwizardProbe {
private static final String DISPLAY_NAME = DropwizardProbe.class.getSimpleName();
private static final Logger LOG = LoggerFactory.getLogger(DISPLAY_NAME);
static {
disableSslVerification();
}
// wait for service to be running before continuing
public static void probeOnPort(int port, boolean waitForConnect) {
boolean keepGoing = true;
while (keepGoing) {
try {
URL url;
if(port == 443) {
url = new URL("https://127.0.0.1/probe");
} else {
url = new URL("http://127.0.0.1/probe");
}
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "Gonespy Dropwizard Probe");
con.setRequestMethod("GET");
LOG.info("Port " + port + " is responding: " + con.getResponseCode());
break;
} catch(SSLHandshakeException e) {
LOG.info("Port " + port + " is responding but with SSL error which is ok");
break;
} catch (IOException io) {
LOG.info("Waiting for port " + port + " to accept connection");
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
}
// stop if we don't want to retry
keepGoing = waitForConnect;
}
}
private static void disableSslVerification() {
try
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException|KeyManagementException e) {
e.printStackTrace();
}
}
}
| 3,266 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
AvailabilityTestClient.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/availability/AvailabilityTestClient.java | package com.gonespy.service.availability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;
import static com.gonespy.service.util.StringUtils.bytesToReadableHex;
public class AvailabilityTestClient {
private static final Logger LOG = LoggerFactory.getLogger(AvailabilityTestClient.class.getSimpleName());
public static void main(String[] args) throws IOException {
String host = "localhost";
if (args.length == 1) {
host = args[0];
}
// get a datagram socket
DatagramSocket socket = new DatagramSocket();
socket.setSoTimeout(5000);
// send request
byte[] buf = new byte[256];
InetAddress address = InetAddress.getByName(host);
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 27900);
LOG.info("Sending packet to " + packet.getSocketAddress());
socket.send(packet);
// get response
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// display response
byte[] receivedBytes = Arrays.copyOfRange(packet.getData(), 0, packet.getLength() - 1);
String received = bytesToReadableHex(receivedBytes);
LOG.info("Received: " + received);
socket.close();
}
}
| 1,436 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
AvailabilityService.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/availability/AvailabilityService.java | package com.gonespy.service.availability;
import com.gonespy.service.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class AvailabilityService implements Runnable {
private static final String DISPLAY_NAME = AvailabilityService.class.getSimpleName();
private static final int AVAILABLE_SERVER_PORT = 27900;
private static final Logger LOG = LoggerFactory.getLogger(DISPLAY_NAME);
public static void main(String[] args) {
new AvailabilityService().run();
}
@Override
public void run() {
DatagramSocket socket = null;
try {
socket = new DatagramSocket( AVAILABLE_SERVER_PORT );
LOG.info("Listening on port " + AVAILABLE_SERVER_PORT + "[UDP]");
} catch ( SocketException e ) {
LOG.error( "Could not open socket on port " + AVAILABLE_SERVER_PORT + ". " + e.getMessage());
System.exit( 1 );
}
boolean loop = true;
while (loop) {
try {
byte[] buffer = new byte[2048];
DatagramPacket packet = new DatagramPacket( buffer, buffer.length );
socket.receive(packet);
new AvailabilityServerThread(socket, packet).run();
} catch ( IOException e ) {
LOG.error( "Could not spawn thread to handle connection: " + e.getMessage() );
loop = false;
}
}
socket.close();
}
public static class AvailabilityServerThread extends Thread {
private final byte[] AVAILABLE_RESPONSE = new byte[] { (byte)0xFE, (byte)0xFD, 0x09, 0x00, 0x00, 0x00, 0x00};
// private final byte[] UNAVAILABLE_RESPONSE = new byte[] {(byte)0xFE, (byte)0xFD, 0x09, 0x00, 0x00, 0x00, 0x01};
// private final byte[] TEMP_UNAVAILABLE_RESPONSE = new byte[] {(byte)0xFE, (byte)0xFD, 0x09, 0x00, 0x00, 0x00, 0x02};
private DatagramSocket socket = null;
private DatagramPacket incomingPacket = null;
public AvailabilityServerThread(DatagramSocket socket, DatagramPacket packet) {
this(AvailabilityServerThread.class.getSimpleName(), socket, packet);
}
public AvailabilityServerThread(String name, DatagramSocket socket, DatagramPacket incomingPacket) {
super(name);
this.socket = socket;
this.incomingPacket = incomingPacket;
}
public void run() {
try {
final byte[] buf = AVAILABLE_RESPONSE;
socket.send(new DatagramPacket(buf, buf.length, incomingPacket.getAddress(), incomingPacket.getPort()));
LOG.info("Sent to " + incomingPacket.getSocketAddress().toString() + " - " + StringUtils.asciiToReadableHex(buf));
} catch (IOException e) {
LOG.error("Failed to send packet to " + incomingPacket.getSocketAddress() + ": " + e.getMessage());
}
}
}
}
| 3,087 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
GPCMService.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/gpcm/GPCMService.java | package com.gonespy.service.gpcm;
/**
* Created by gonespy on 8/02/2018.
*
* gpcm.gamespy.com:29900
*
*/
import java.io.IOException;
import java.net.ServerSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GPCMService implements Runnable {
private static final String DISPLAY_NAME = GPCMService.class.getSimpleName();
private static final Logger LOG = LoggerFactory.getLogger(DISPLAY_NAME);
public static final int GPCM_PORT_NUMBER = 29900;
public static void main(String[] args) {
new GPCMService().run();
}
@Override
public void run() {
try (ServerSocket serverSocket = new ServerSocket(GPCM_PORT_NUMBER)) {
LOG.info("Listening on port " + GPCM_PORT_NUMBER);
while (true) {
new GPCMServiceThread(serverSocket.accept()).start();
}
} catch (IOException e) {
System.err.println("Could not listen on port " + GPCM_PORT_NUMBER);
throw new RuntimeException();
}
}
}
| 1,041 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
GPCMTestClient.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/gpcm/GPCMTestClient.java | package com.gonespy.service.gpcm;
/**
* Created by gonespy on 8/02/2018.
*/
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import static com.gonespy.service.util.GPMessageUtils.readGPMessage;
public class GPCMTestClient {
public static void main(String[] args) {
String hostName = "localhost";
try (
Socket socket = new Socket(hostName, GPCMService.GPCM_PORT_NUMBER);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
) {
String data = readGPMessage(is);
System.out.println("Response: " + data);
PrintWriter p = new PrintWriter(os);
p.write("\\login\\\\challenge\\9uJW3IzSHMRgzUF6lYLiVMxODy1a1ENo\\authtoken\\11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111\\partnerid\\19\\response\\ef38c71bfa573a0c4a075c8f3b738f62\\port\\6500\\productid\\12999\\gamename\\bstormps3\\namespaceid\\28\\sdkrevision\\59\\quiet\\0\\id\\1\\final\\");
p.flush();
String data2 = readGPMessage(is);
System.out.println("Response: " + data2);
socket.close();
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
| 1,595 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
GPCMServiceThread.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/gpcm/GPCMServiceThread.java | package com.gonespy.service.gpcm;
/**
* Created by gonespy on 8/02/2018.
*/
import com.gonespy.service.shared.GPState;
import com.gonespy.service.util.GPNetworkException;
import com.gonespy.service.util.StringUtils;
import com.gonespy.service.shared.Constants;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.gonespy.service.shared.GPState.*;
import static com.gonespy.service.util.GPMessageUtils.*;
public class GPCMServiceThread extends Thread {
private static final Logger LOG = LoggerFactory.getLogger(GPCMServiceThread.class);
public static final int INT_AUTH_LENGTH = 4;
private static final String DUMMY_SERVER_CHALLENGE = "ZXX7h9eiTe0EP5teW1yiajFqY5URTykw";
private static final String DUMMY_SESSION_KEY = Strings.padEnd("", INT_AUTH_LENGTH, '5');
public static final String DUMMY_USER_ID = Strings.padEnd("", INT_AUTH_LENGTH, '6');
public static final String DUMMY_PROFILE_ID = Strings.padEnd("", INT_AUTH_LENGTH, '7');
private static final String DUMMY_LOGIN_TOKEN = "XdR2LlH69XYzk3KCPYDkTY__";
public static final String DUMMY_UNIQUE_NICK = "BulletstormPlayer";
private Socket socket;
public GPCMServiceThread(Socket socket) {
super("GPSPServiceThread");
this.socket = socket;
}
// additional calls seen:
// UT3
// \addbuddy\\sesskey\5555\newprofileid\0\reason\PS3 Buddy Sync\final\\addbuddy\\sesskey\5555\newprofileid\0\reason\PS3 Buddy Sync\final\
public void run() {
GPState state = CONNECT;
try (
InputStream reader = socket.getInputStream();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
) {
while(socket.isConnected() && state != DONE) {
if(state == CONNECT) {
// server talks first
// \lc\1\challenge\ZXX7h9eiTe0EP5teW1yiajFqY5URTykw\id\1\final\
Map<String,String> responseDataMap = new LinkedHashMap<>();
responseDataMap.put("lc", "1");
responseDataMap.put("challenge", DUMMY_SERVER_CHALLENGE);
responseDataMap.put("id", "1");
out.print(createGPMessage(responseDataMap));
out.flush();
state = WAIT;
} else if(state == WAIT) {
sleep(10);
final String clientString = readGPMessage(reader);
final String directive = getGPDirective(clientString);
if(directive == null) {
if(clientString != null && clientString.length() > 0) {
// unrecognized message format
LOG.warn("Unrecognized message format. Message: " + clientString);
}
} else if(directive.equals("login")) {
// request should look like:
// \login\\challenge\l0OtMmxlm2pPSy5ra4lynHSMB2Qbci7M\authtoken\1111\partnerid\19\response\d3e1370bf11b79770e2dc6b36cecfb6a\port\6500\productid\12999\gamename\bstormps3\namespaceid\28\sdkrevision\59\quiet\0\id\1\final\
Map<String, String> inputMap = parseClientLogin(clientString);
LOG.info(clientString);
// response should look like:
// \blk\0\list\\final\\bdy\0\list\\final\\lc\2\sesskey\55555555555555555555555555555555\ userid\66666666666666666666666666666666\profileid\77777777777777777777777777777777\lt\XdR2LlH69XYzk3KCPYDkTY__\proof\10504cc226cc97f1d15f8c3269407500\id\1\final\
final String user = inputMap.get("authtoken"); // user = authtoken for PS3 preauth
final String clientChallenge = inputMap.get("challenge");
// block list - empty
final String blkData = createGPEmptyListMessage("blk");
// buddy list - empty
final String bdyData = createGPEmptyListMessage("bdy");
// login data
Map<String, String> responseDataMap = new LinkedHashMap<>();
responseDataMap.put("lc", "2"); // int
responseDataMap.put("sesskey", DUMMY_SESSION_KEY); // int
responseDataMap.put("userid", DUMMY_USER_ID); // int
responseDataMap.put("profileid", DUMMY_PROFILE_ID); // int
responseDataMap.put("uniquenick", DUMMY_UNIQUE_NICK); // should be PSNID from PSN login - don't think we have any way of knowing this
responseDataMap.put("lt", DUMMY_LOGIN_TOKEN); // string // login token
// password = partnerChallenge for PS3 preauth
responseDataMap.put("proof", StringUtils.gsLoginProof(Constants.DUMMY_PARTNER_CHALLENGE, user, clientChallenge, DUMMY_SERVER_CHALLENGE));
responseDataMap.put("id", "1"); // int
out.print(blkData + bdyData + createGPMessage(responseDataMap));
out.flush();
} else if(directive.equals("updatepro")) {
// \ updatepro\\sesskey\5555\publicmask\0\partnerid\19\final\
/*// update profile, setting publicmask=0 ? maybe making the profile invisible to the rest of
// the gamespy network because it is a shadow PS account?
// try sending back current user's info
Map<String, String> loginResponseData = new LinkedHashMap<>();
loginResponseData.put("pi", ""); // int
loginResponseData.put("profileid", Strings.padEnd("", INT_AUTH_LENGTH, '7')); // int
loginResponseData.put("nick", "someguy");
loginResponseData.put("uniquenick", "someguy");
loginResponseData.put("sig", "xxx"); // don't know what this is
String loginData = createGPMessage(loginResponseData);
out.print(loginData);*/
out.flush();
} else if(directive.equals("ka")) {
// \ka\\final\
// keep-alive - just send it back (client will ignore)
Map<String,String> responseData = new LinkedHashMap<>();
responseData.put("ka", "");
out.print(createGPMessage(responseData));
out.flush();
} else {
// directive unknown/not implemented yet
String clientRequestString = readGPMessage(reader);
if(clientRequestString != null && clientRequestString.length() > 0) {
LOG.info("unimplemented directive '" + directive + "': " + clientRequestString);
}
}
}
}
} catch (GPNetworkException e) {
LOG.info("Client closed connection");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
try {
LOG.info("Closing socket");
socket.close();
} catch(IOException e) {
LOG.info("Could not close socket. Oh well..");
}
}
}
}
| 7,777 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
GPSPTestClient.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/gpsp/GPSPTestClient.java | package com.gonespy.service.gpsp;
/**
* Created by gonespy on 8/02/2018.
*/
import com.gonespy.service.util.GPMessageUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class GPSPTestClient {
public static void main(String[] args) {
String hostName = "localhost";
try (
Socket socket = new Socket(hostName, GPSPService.GPSP_PORT_NUMBER);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream()
) {
PrintWriter p = new PrintWriter(os);
p.write("\\searchunique\\\\sesskey\\5555\\profileid\\7777\\uniquenick\\CSlucher818\\namespaces\\28\\gamename\\bstormps3\\final\\");
p.flush();
String data2 = GPMessageUtils.readGPMessage(is);
System.out.println("Response: " + data2);
socket.close();
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
| 1,338 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
GPSPService.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/gpsp/GPSPService.java | package com.gonespy.service.gpsp;
/**
* Created by gonespy on 8/02/2018.
*
* gpsp.gamespy.com:29901
*
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.ServerSocket;
public class GPSPService implements Runnable {
private static final String DISPLAY_NAME = GPSPService.class.getSimpleName();
private static final Logger LOG = LoggerFactory.getLogger(DISPLAY_NAME);
public static final int GPSP_PORT_NUMBER = 29901;
public static void main(String[] args) {
new GPSPService().run();
}
@Override
public void run() {
try (ServerSocket serverSocket = new ServerSocket(GPSP_PORT_NUMBER)) {
LOG.info("Listening on port " + GPSP_PORT_NUMBER);
while (true) {
new GPSPServiceThread(serverSocket.accept()).start();
}
} catch (IOException e) {
System.err.println("Could not listen on port " + GPSP_PORT_NUMBER);
System.exit(-1);
}
}
}
| 1,031 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
GPSPServiceThread.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/gpsp/GPSPServiceThread.java | package com.gonespy.service.gpsp;
/**
* Created by gonespy on 8/02/2018.
*
*/
import com.gonespy.service.util.GPMessageUtils;
import com.gonespy.service.shared.GPState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.gonespy.service.shared.GPState.DONE;
import static com.gonespy.service.shared.GPState.WAIT;
public class GPSPServiceThread extends Thread {
private static final Logger LOG = LoggerFactory.getLogger(GPSPServiceThread.class);
private Socket socket;
public GPSPServiceThread(Socket socket) {
super("GPSPServiceThread");
this.socket = socket;
}
// SEE GP/gpiSearch.c
// requests:
// search - search profile
// searchunique - search profile uniquenick
// valid - check if valid email address?
// nicks - search nicks
// pmatch - search players (other players playing this game?)
// check - search check
// newuser - new user?
// others - search other's buddy
// otherslist - search others buddy list
// uniquesearch - search suggest unique (for suggesting a unique nickname, given a preferred nickname)
// responses:
// search
// searchunique
// bsr / bsrdone / more (multiple)
// valid
// vr
// nicks
// nr / ndone (multiple)
// pmatch
// psr / psrdone (multiple)
// check
// cur
// newuser
// nur
// others
// o / odone (multiple)
// otherslist
// o / oldone (multiple)
// uniquesearch
// us / usdone
//
// * start of record's value is the profile id (eg. bsr)
// * end of list has no value (eg. bsrdone)
public void run() {
GPState state = WAIT;
try (
InputStream reader = socket.getInputStream();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)
) {
while(socket.isConnected() && state != DONE) {
if(state == WAIT) {
sleep(10);
String clientString = GPMessageUtils.readGPMessage(reader);
String directive = GPMessageUtils.getGPDirective(clientString);
if(directive == null) {
if(clientString != null && clientString.length() > 0) {
// unrecognized message format
LOG.warn("Unrecognized message format. Message: " + clientString);
}
} else if(directive.equals("searchunique")) {
// this is querying everyone on your PSN friends list one by one, by their PSN username
// this is necessary in order to populate the friends list when you want to send game invites
Map<String, String> inputMap = GPMessageUtils.parseClientLogin(clientString);
// \searchunique\\sesskey\5555\profileid\7777\ uniquenick\CSlucher818\namespaces\28\gamename\bstormps3\final\
final String name = inputMap.get("uniquenick");
// searchunique result data
Map<String,String> responseDataMap = new LinkedHashMap<>();
responseDataMap.put("bsr", ""); // TODO: make a random profileid
responseDataMap.put("nick", name);
responseDataMap.put("uniquenick", name);
responseDataMap.put("namespaceid", inputMap.get("namespaces"));
responseDataMap.put("bsrdone", "");
out.print(GPMessageUtils.createGPMessage(responseDataMap));
out.flush();
} else {
// directive unknown/not implemented yet
String clientRequestString = GPMessageUtils.readGPMessage(reader);
if(clientRequestString != null && clientRequestString.length() > 0) {
LOG.info("UNKNOWN DIRECTIVE: " + clientRequestString);
}
}
}
}
} catch (IOException | InterruptedException e) {
LOG.info("Client closed exception");
//e.printStackTrace();
} finally {
try {
LOG.info("Closing socket");
socket.close();
} catch(IOException e) {
LOG.info("Could not close socket. Oh well..");
}
}
}
}
| 4,860 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
SakeServiceConfiguration.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/sake/SakeServiceConfiguration.java | package com.gonespy.service.sake;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import io.federecio.dropwizard.swagger.SwaggerBundleConfiguration;
public class SakeServiceConfiguration extends Configuration {
@JsonProperty("swagger")
public SwaggerBundleConfiguration swaggerBundleConfiguration;
}
| 354 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
DummyHealthCheck.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/sake/DummyHealthCheck.java | package com.gonespy.service.sake;
import com.codahale.metrics.health.HealthCheck;
public class DummyHealthCheck extends HealthCheck {
@Override
protected Result check() throws Exception {
return Result.builder()
// TODO Add proper health check
.withMessage("Add proper health check here")
.healthy()
.build();
}
}
| 402 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
SakeService.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/sake/SakeService.java | package com.gonespy.service.sake;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.gonespy.service.sake.resources.SakeResource;
import com.gonespy.service.sake.resources.VersionResource;
import io.dropwizard.Application;
import io.dropwizard.configuration.EnvironmentVariableSubstitutor;
import io.dropwizard.configuration.SubstitutingSourceProvider;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.federecio.dropwizard.swagger.SwaggerBundle;
import io.federecio.dropwizard.swagger.SwaggerBundleConfiguration;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
public class SakeService extends Application<SakeServiceConfiguration> {
public static void main(String[] args) {
try {
new SakeService().run(args);
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public void initialize(Bootstrap<SakeServiceConfiguration> bootstrap) {
bootstrap.setConfigurationSourceProvider(
new SubstitutingSourceProvider(
bootstrap.getConfigurationSourceProvider(),
// not strict as we want to be able to supply defaults
new EnvironmentVariableSubstitutor(false)
)
);
bootstrap.addBundle(
new SwaggerBundle<SakeServiceConfiguration>() {
@Override
protected SwaggerBundleConfiguration getSwaggerBundleConfiguration(SakeServiceConfiguration configuration) {
return configuration.swaggerBundleConfiguration;
}
}
);
}
@Override
public void run(SakeServiceConfiguration configuration, Environment environment) {
SakeResource sakeResource = new SakeResource();
// resources
environment.jersey().register(new VersionResource());
environment.jersey().register(sakeResource);
environment.jersey().register(new JerseyObjectMapper());
environment.jersey().register(new JsonProcessingExceptionMapper());
environment.getObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
environment.getObjectMapper().registerModule(new Jdk8Module());
// health checks
environment.healthChecks().register("dummy1", new DummyHealthCheck());
//MetricRegistry retrievedMetricRegistry = SharedMetricRegistries.getOrCreate("default");
//environment.metrics().register("registry1", retrievedMetricRegistry);
}
@Provider
public static class JerseyObjectMapper implements ContextResolver<ObjectMapper> {
private ObjectMapper mapper;
public JerseyObjectMapper() {
mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}
public class JsonProcessingExceptionMapper implements ExceptionMapper<JsonProcessingException> {
@Override
public Response toResponse(JsonProcessingException exception) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
}
| 3,306 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
SakeResource.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/sake/resources/SakeResource.java | package com.gonespy.service.sake.resources;
import com.gonespy.service.util.SoapUtils;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.gonespy.service.shared.Constants.DUMMY_AUTH_TOKEN;
import static com.gonespy.service.shared.Constants.DUMMY_PARTNER_CHALLENGE;
// sake = HTTP : 80
@Api(value = "gonespy")
@Path("/")
@Produces(MediaType.TEXT_XML)
public class SakeResource {
private static final Logger LOG = LoggerFactory.getLogger(SakeResource.class);
private static final String SAKE_GET_MY_RECORDS = "GetMyRecords";
public SakeResource() {
}
@POST
@Consumes(MediaType.TEXT_XML)
@Path("SakeStorageServer/StorageServer.asmx")
public Response sakeStorageServer(String request /*HttpConnection debugInformation*/) {
return generateSakeResponse(request);
}
// just for testing without SSH/POST getting in the way
/*@GET
@Path("/AuthService/GetAuthService.asmx")
public Response getAuthService(String request) {
return generateResponse(request);
}*/
// demo leash unlocked?
// <?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns1="http://gamespy.net/sake"><SOAP-ENV:Body><ns1:GetMyRecords><ns1:gameid>3144</ns1:gameid><ns1:secretKey>2skyJh</ns1:secretKey><ns1:loginTicket>XdR2LlH69XYzk3KCPYDkTY__</ns1:loginTicket><ns1:tableid>DemoLeash</ns1:tableid><ns1:fields><ns1:string>unlocked</ns1:string></ns1:fields></ns1:GetMyRecords></SOAP-ENV:Body></SOAP-ENV:Envelope>
// what are my friends' scores for this map?
// <?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns1="http://gamespy.net/sake"><SOAP-ENV:Body><ns1:SearchForRecords><ns1:gameid>3144</ns1:gameid><ns1:secretKey>2skyJh</ns1:secretKey><ns1:loginTicket>XdR2LlH69XYzk3KCPYDkTY__</ns1:loginTicket><ns1:tableid>PlayerStats_v14</ns1:tableid><ns1:filter>Nick IN ('CSlucher818', 'Lightn1ng-_-', 'TheMain-pro-', 'hiyoshi-', 'Flatline_Freedom', 'Erroneus', 'StrangeRoostar', 'Mitchell3212', 'KeanuKou', 'RickertdeH', 'The_Cydonian', 'Nabil-D-Jin', 'hopewell26', 'ANTZ4SHAW', 'Ironduke-70', 'tessarai', 'noobsauce2010', 'JakeTheDude', 'Chunhea', 'CRASHBASHUK', 'StrangleholdCCR', 'Qismat', 'TumekeMus', 'Big_mac_53', 'vitalive', 'CreateToBeGreat', 'BlazinDankAllDay', 'THE-BLACK_JIN', 'NickMeister77', 'lMATT-SNIPERl', 'THEPEOPLESASS00', 'ChampZilla', 'NeM2k3', 'lordzeze', 'Medrah-', 'sundevilfan50', 'FerrariFSX', 'shbris', 'Karumph', 'feba-slb', 'Willmoar', 'Kaerion42', 'phoenixbelg', 'Xehinor', 'Radiophoenix', 'Ahmed13', 'McFood2', 'chucknorris078', 'Warchild0350', 'WWE_Kratos2810', 'PeppyRou', 'Naulziator', 'BearGrylls78', 'ryannumber3gamer', 'PickIe_Rick-91', 'TiGeRthaCReaTOR', 'florinisa', 'GrimVenomReaver', 'StrangeRooster', 'Kuervo_001', 'Nellio84', 'MadDogSquids', 'chris0crusade', 'gruelingsix32', 'LegionOfFish56', 'shiro-ltp-809', 'Repolaine', 'staker158', 'mickgook', 'TripYoRift', 'cloud25679', 'SquidZzGamer1456', 'ProblemedPopler', 'Sizz07', 'mordeckai81', 'Edwards_0127', 'Motley1969Crue', 'MadGadabout', 'kheoth', 'spencer26587', 'Jambici', 'LandersWagstaff', 'geroldhulahoop', 'HULKnDaSTYX', 'MaverickHunterX', 'Aazesyne', 'Modifiedw0lves', 'Hitsugaya900', 'MorbusIff', 'rpg49ers', 'lawrencejohnliu', 'Spade-77', 'Doctor___Rockzo', 'DoM-the1337kid', 'elite_hero99')</ns1:filter><ns1:sort>STAT_ChaosMap_WaveHighScore0_ScoreChase5 desc</ns1:sort><ns1:offset>0</ns1:offset><ns1:max>95</ns1:max><ns1:surrounding>0</ns1:surrounding><ns1:ownerids></ns1:ownerids><ns1:cacheFlag>0</ns1:cacheFlag><ns1:fields><ns1:string>STAT_ChaosMap_WaveHighScore0_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore1_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore2_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore3_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore4_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore5_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore6_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore7_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore8_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore9_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore10_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore11_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore12_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore13_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore14_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore15_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore16_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore17_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore18_ScoreChase5</ns1:string><ns1:string>STAT_ChaosMap_WaveHighScore19_ScoreChase5</ns1:string><ns1:string>ownerid</ns1:string><ns1:string>row</ns1:string><ns1:string>Nick</ns1:string></ns1:fields></ns1:SearchForRecords></SOAP-ENV:Body></SOAP-ENV:Envelope>
// statistics
// <?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns1="http://gamespy.net/sake"><SOAP-ENV:Body><ns1:SearchForRecords><ns1:gameid>3144</ns1:gameid><ns1:secretKey>2skyJh</ns1:secretKey><ns1:loginTicket>XdR2LlH69XYzk3KCPYDkTY__</ns1:loginTicket><ns1:tableid>PlayerStats_v14</ns1:tableid><ns1:filter>MPGlobal > 0</ns1:filter><ns1:sort>Kills_MPGlobal desc</ns1:sort><ns1:offset>0</ns1:offset><ns1:max>1</ns1:max><ns1:surrounding>0</ns1:surrounding><ns1:ownerids><ns1:int>7777</ns1:int></ns1:ownerids><ns1:cacheFlag>0</ns1:cacheFlag><ns1:fields><ns1:string>Kills_MPGlobal</ns1:string><ns1:string>Revives_MPGlobal</ns1:string><ns1:string>Skillpoints_MPGlobal</ns1:string><ns1:string>Skillshots_MPGlobal</ns1:string><ns1:string>ChallengesComplete_MPGlobal</ns1:string><ns1:string>WavesComplete_MPGlobal</ns1:string><ns1:string>FullMatchesComplete_MPGlobal</ns1:string><ns1:string>ownerid</ns1:string><ns1:string>row</ns1:string><ns1:string>Nick</ns1:string></ns1:fields></ns1:SearchForRecords></SOAP-ENV:Body></SOAP-ENV:Envelope>
// leaderboards
// <?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns1="http://gamespy.net/sake"><SOAP-ENV:Body><ns1:SearchForRecords><ns1:gameid>3144</ns1:gameid><ns1:secretKey>2skyJh</ns1:secretKey><ns1:loginTicket>XdR2LlH69XYzk3KCPYDkTY__</ns1:loginTicket><ns1:tableid>PlayerStats_v14</ns1:tableid><ns1:filter>MPGlobal > 0</ns1:filter><ns1:sort>Kills_MPGlobal desc</ns1:sort><ns1:offset>0</ns1:offset><ns1:max>1</ns1:max><ns1:surrounding>0</ns1:surrounding><ns1:ownerids><ns1:int>7777</ns1:int></ns1:ownerids><ns1:cacheFlag>0</ns1:cacheFlag><ns1:fields><ns1:string>Kills_MPGlobal</ns1:string><ns1:string>Revives_MPGlobal</ns1:string><ns1:string>ownerid</ns1:string><ns1:string>row</ns1:string><ns1:string>Nick</ns1:string></ns1:fields></ns1:SearchForRecords></SOAP-ENV:Body></SOAP-ENV:Envelope>
private Response generateSakeResponse(String request) {
LOG.info("REQUEST:");
LOG.info(request);
// WARNING: the request contains an encrypted field from the PSN
// don't expose this - if it was brute-force decrypted, who knows what the raw data might contain?
Map<String,String> soapData = new LinkedHashMap<>();
soapData.put("responseCode", "0");
soapData.put("authToken", DUMMY_AUTH_TOKEN);
soapData.put("partnerChallenge", DUMMY_PARTNER_CHALLENGE);
String response = generateSakeSoapResponse(SAKE_GET_MY_RECORDS, soapData);
LOG.info("RESPONSE:");
LOG.info(response);
return Response.status(Response.Status.OK)
.entity(response)
.build();
}
// sakeRequestRead.c
private String generateSakeSoapResponse(String type, Map<String, String> soapData) {
// TODO: all sake responses return no table rows for now
return SoapUtils.wrapSoapData("sake", type, SoapUtils.emptySoapTag("values"));
}
}
| 10,551 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
VersionResource.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/sake/resources/VersionResource.java | package com.gonespy.service.sake.resources;
import com.google.common.collect.ImmutableMap;
import io.swagger.annotations.Api;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import static com.google.common.base.Strings.isNullOrEmpty;
@Api
@Path("/version")
@Produces(MediaType.APPLICATION_JSON)
public class VersionResource {
private static final Map<String, Object> VERSION_INFO;
static {
String version = "unknown";
String scmRevision = "unknown";
try (InputStream is = VersionResource.class.getResourceAsStream("/META-INF/MANIFEST.MF")) {
Manifest manifest = new Manifest(is);
Attributes attr = manifest.getMainAttributes();
String implementationVersion = attr.getValue("Implementation-Version");
if (!isNullOrEmpty(implementationVersion)) {
version = implementationVersion;
}
String implementationScmRevision = attr.getValue("Implementation-SCM-Revision");
if (!isNullOrEmpty(implementationScmRevision)) {
scmRevision = implementationScmRevision;
}
} catch (IOException ioEx) {
throw new RuntimeException(ioEx);
}
VERSION_INFO = ImmutableMap.of(
"version", version,
"scmRevision", scmRevision
);
}
@GET
public Map<String, Object> getVersionInfo() {
return VERSION_INFO;
}
}
| 1,486 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
GPState.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/shared/GPState.java | package com.gonespy.service.shared;
public enum GPState {
CONNECT,
WAIT,
DONE
}
| 93 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
Constants.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/shared/Constants.java | package com.gonespy.service.shared;
import com.google.common.base.Strings;
public abstract class Constants {
public static final int STRING_AUTH_LENGTH = 32;
public static final String DUMMY_AUTH_TOKEN = Strings.padEnd("", STRING_AUTH_LENGTH, '1');
public static final String DUMMY_PARTNER_CHALLENGE = Strings.padEnd("", STRING_AUTH_LENGTH, '2');
// taken from eaEmu
public static final String PEER_KEY_PRIVATE =
"8818DA2AC0E0956E0C67CA8D785CFAF3" +
"A11A9404D1ED9A6E580EA8569E087B75" +
"316B85D77B2208916BE2E0D37C7D7FD1" +
"8EFD6B2E77C11CDA6E1B689BF460A40B" +
"BAF861D800497822004880024B4E7F98" +
"A020B1896F536D7219E67AB24B17D60A" +
"7BDD7D42E3501BB2FA50BB071EF7A80F" +
"29870FFD7C409C0B7BB7A8F70489D04D";
}
| 887 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
AuthServiceConfiguration.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/auth/AuthServiceConfiguration.java | package com.gonespy.service.auth;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import io.federecio.dropwizard.swagger.SwaggerBundleConfiguration;
public class AuthServiceConfiguration extends Configuration {
@JsonProperty("swagger")
public SwaggerBundleConfiguration swaggerBundleConfiguration;
}
| 354 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
DummyHealthCheck.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/auth/DummyHealthCheck.java | package com.gonespy.service.auth;
import com.codahale.metrics.health.HealthCheck;
public class DummyHealthCheck extends HealthCheck {
@Override
protected Result check() throws Exception {
return Result.builder()
// TODO Add proper health check
.withMessage("Add proper health check here")
.healthy()
.build();
}
}
| 402 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
AuthService.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/auth/AuthService.java | package com.gonespy.service.auth;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.gonespy.service.auth.resources.AuthResource;
import com.gonespy.service.auth.resources.VersionResource;
import io.dropwizard.Application;
import io.dropwizard.configuration.EnvironmentVariableSubstitutor;
import io.dropwizard.configuration.SubstitutingSourceProvider;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.federecio.dropwizard.swagger.SwaggerBundle;
import io.federecio.dropwizard.swagger.SwaggerBundleConfiguration;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import java.security.Security;
public class AuthService extends Application<AuthServiceConfiguration> {
static {
Security.setProperty("jdk.tls.disabledAlgorithms", "");
Security.setProperty("https.cipherSuites", "SSL_RSA_WITH_RC4_128_MD5");
Security.setProperty("jdk.tls.legacyAlgorithms", "SSL_RSA_WITH_RC4_128_MD5");
}
public static void main(String[] args) {
try {
new AuthService().run(args);
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public void initialize(Bootstrap<AuthServiceConfiguration> bootstrap) {
bootstrap.setConfigurationSourceProvider(
new SubstitutingSourceProvider(
bootstrap.getConfigurationSourceProvider(),
// not strict as we want to be able to supply defaults
new EnvironmentVariableSubstitutor(false)
)
);
bootstrap.addBundle(
new SwaggerBundle<AuthServiceConfiguration>() {
@Override
protected SwaggerBundleConfiguration getSwaggerBundleConfiguration(AuthServiceConfiguration configuration) {
return configuration.swaggerBundleConfiguration;
}
}
);
}
@Override
public void run(AuthServiceConfiguration configuration, Environment environment) {
AuthResource authResource = new AuthResource();
// resources
environment.jersey().register(new VersionResource());
environment.jersey().register(authResource);
environment.jersey().register(new JerseyObjectMapper());
environment.jersey().register(new JsonProcessingExceptionMapper());
environment.getObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
environment.getObjectMapper().registerModule(new Jdk8Module());
// health checks
environment.healthChecks().register("dummy2", new DummyHealthCheck());
//MetricRegistry retrievedMetricRegistry = SharedMetricRegistries.getOrCreate("default");
//environment.metrics().register("registry2", retrievedMetricRegistry);
}
@Provider
public static class JerseyObjectMapper implements ContextResolver<ObjectMapper> {
private ObjectMapper mapper;
public JerseyObjectMapper() {
mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}
public class JsonProcessingExceptionMapper implements ExceptionMapper<JsonProcessingException> {
@Override
public Response toResponse(JsonProcessingException exception) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
}
| 3,562 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
AuthResource.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/auth/resources/AuthResource.java | package com.gonespy.service.auth.resources;
import com.gonespy.service.util.CertificateUtils;
import com.gonespy.service.util.SoapUtils;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.gonespy.service.shared.Constants.DUMMY_AUTH_TOKEN;
import static com.gonespy.service.shared.Constants.DUMMY_PARTNER_CHALLENGE;
import static com.gonespy.service.shared.Constants.PEER_KEY_PRIVATE;
// AuthService = HTTPS : 443
@Api(value = "gonespy")
@Path("/")
@Produces(MediaType.TEXT_XML)
public class AuthResource {
private static final Logger LOG = LoggerFactory.getLogger(AuthResource.class);
private static final String LOGIN_PS3_CERT_RESULT = "LoginPs3CertResult";
private static final String LOGIN_REMOTE_AUTH_RESULT = "LoginRemoteAuthResult";
public AuthResource() {
}
@POST
@Consumes(MediaType.TEXT_XML)
@Path("AuthService/AuthService.asmx")
public Response authService(String request /*HttpConnection debugInformation*/) {
return generateResponse(request);
}
// just for testing without SSH/POST getting in the way
/*@GET
@Path("/AuthService/GetAuthService.asmx")
public Response getAuthService(String request) {
return generateResponse(request);
}*/
private Response generateResponse(String request) {
LOG.info("REQUEST:");
LOG.info(request);
Map<String, Object> map = SoapUtils.parseSoapData(request);
String requestType = (String)map.get("ns1");
Response response = null;
switch(requestType) {
case "LoginPs3Cert":
response = loginPs3AuthResponse();
break;
case "LoginRemoteAuth":
response = loginRemoteAuthResponse(map);
}
return response;
}
private Response loginPs3AuthResponse() {
Map<String,Object> soapData = new LinkedHashMap<>();
soapData.put("responseCode", "0");
soapData.put("authToken", DUMMY_AUTH_TOKEN);
soapData.put("partnerChallenge", DUMMY_PARTNER_CHALLENGE);
String response = generateSoapResponse(LOGIN_PS3_CERT_RESULT, soapData);
LOG.info("RESPONSE:");
LOG.info(response);
return Response.status(Response.Status.OK)
.entity(response)
.build();
}
private Response loginRemoteAuthResponse(Map<String, Object> inputData) {
LOG.warn("WARNING: game uses remote auth login which does not work!");
Map<String,Object> soapData = new LinkedHashMap<>();
soapData.put("responseCode", "0");
soapData.put("certificate",
//CertificateUtils.getCertificate(inputData)
CertificateUtils.getCertificateEaEmu(inputData)
);
soapData.put("peerkeyprivate", PEER_KEY_PRIVATE);
String response = generateSoapResponse(LOGIN_REMOTE_AUTH_RESULT, soapData);
LOG.info("RESPONSE:");
LOG.info(response);
return Response.status(Response.Status.OK)
.entity(response)
.build();
}
private String generateSoapResponse(String type, Map<String, Object> soapData) {
StringBuilder b = new StringBuilder();
for(String key : soapData.keySet()) {
b.append(SoapUtils.createSoapTagWithValue(key, soapData.get(key)));
}
return SoapUtils.wrapSoapData("AuthService/", type, b.toString());
}
}
| 3,703 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
VersionResource.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/auth/resources/VersionResource.java | package com.gonespy.service.auth.resources;
import com.google.common.collect.ImmutableMap;
import io.swagger.annotations.Api;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import static com.google.common.base.Strings.isNullOrEmpty;
@Api
@Path("/version")
@Produces(MediaType.APPLICATION_JSON)
public class VersionResource {
private static final Map<String, Object> VERSION_INFO;
static {
String version = "unknown";
String scmRevision = "unknown";
try (InputStream is = VersionResource.class.getResourceAsStream("/META-INF/MANIFEST.MF")) {
Manifest manifest = new Manifest(is);
Attributes attr = manifest.getMainAttributes();
String implementationVersion = attr.getValue("Implementation-Version");
if (!isNullOrEmpty(implementationVersion)) {
version = implementationVersion;
}
String implementationScmRevision = attr.getValue("Implementation-SCM-Revision");
if (!isNullOrEmpty(implementationScmRevision)) {
scmRevision = implementationScmRevision;
}
} catch (IOException ioEx) {
throw new RuntimeException(ioEx);
}
VERSION_INFO = ImmutableMap.of(
"version", version,
"scmRevision", scmRevision
);
}
@GET
public Map<String, Object> getVersionInfo() {
return VERSION_INFO;
}
}
| 1,486 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
GStatsTestClient.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/stats/GStatsTestClient.java | package com.gonespy.service.stats;
/**
* Created by gonespy on 8/02/2018.
*/
import com.gonespy.service.util.GPMessageUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class GStatsTestClient {
public static void main(String[] args) {
String hostName = "localhost";
try (
Socket socket = new Socket(hostName, GStatsService.GSTATS_PORT_NUMBER);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream()
) {
PrintWriter p = new PrintWriter(os);
p.write("\\searchunique\\\\sesskey\\5555\\profileid\\7777\\uniquenick\\CSlucher818\\namespaces\\28\\gamename\\bstormps3\\final\\");
p.flush();
String data2 = GPMessageUtils.readGPMessage(is);
System.out.println("Response: " + data2);
socket.close();
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
public static String readMessage(InputStream reader) throws IOException {
StringBuilder msg = new StringBuilder();
byte[] buffer = new byte[1024];
int read;
while((read = reader.read(buffer))!=-1) {
String bytesRead = new String(buffer, 0, read);
msg.append(bytesRead);
}
return msg.toString();
}
}
| 1,723 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
GStatsServiceThread.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/stats/GStatsServiceThread.java | package com.gonespy.service.stats;
/**
* Created by gonespy on 8/02/2018.
*
*/
import com.gonespy.service.shared.GPState;
import com.gonespy.service.util.GPMessageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.gonespy.service.shared.GPState.DONE;
import static com.gonespy.service.shared.GPState.WAIT;
public class GStatsServiceThread extends Thread {
private static final Logger LOG = LoggerFactory.getLogger(GStatsServiceThread.class);
private Socket socket;
public GStatsServiceThread(Socket socket) {
super("GStatsServiceThread");
this.socket = socket;
}
public void run() {
GPState state = WAIT;
try (
InputStream reader = socket.getInputStream();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)
) {
while(socket.isConnected() && state != DONE) {
if(state == WAIT) {
sleep(10);
String clientString = GPMessageUtils.readGPMessage(reader);
//String directive = GPMessageUtils.getGPDirective(clientString);
if(clientString != null && clientString.length() > 0) {
LOG.info("received: " + clientString);
Map<String, String> responseDataMap = new LinkedHashMap<>();
out.print(GPMessageUtils.createGPMessage(responseDataMap));
out.flush();
}
/*if(directive == null) {
if(clientString != null && clientString.length() > 0) {
// unrecognized message format
LOG.warn("Unrecognized message format. Message: " + clientString);
}
} else if(directive.equals("searchunique")) {
// this is querying everyone on your PSN friends list one by one, by their PSN username
// this is necessary in order to populate the friends list when you want to send game invites
Map<String, String> inputMap = GPMessageUtils.parseClientLogin(clientString);
// \searchunique\\sesskey\5555\profileid\7777\ uniquenick\CSlucher818\namespaces\28\gamename\bstormps3\final\
final String name = inputMap.get("uniquenick");
// searchunique result data
Map<String,String> responseDataMap = new LinkedHashMap<>();
responseDataMap.put("bsr", ""); // TODO: make a random profileid
responseDataMap.put("nick", name);
responseDataMap.put("uniquenick", name);
responseDataMap.put("namespaceid", inputMap.get("namespaces"));
responseDataMap.put("bsrdone", "");
out.print(GPMessageUtils.createGPMessage(responseDataMap));
out.flush();
} else {
// directive unknown/not implemented yet
String clientRequestString = GPMessageUtils.readGPMessage(reader);
if(clientRequestString != null && clientRequestString.length() > 0) {
LOG.info("UNKNOWN DIRECTIVE: " + clientRequestString);
}
}*/
}
}
} catch (IOException | InterruptedException e) {
LOG.info("Client closed exception");
//e.printStackTrace();
} finally {
try {
LOG.info("Closing socket");
socket.close();
} catch(IOException e) {
LOG.info("Could not close socket. Oh well..");
}
}
}
}
| 4,057 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
GStatsService.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/stats/GStatsService.java | package com.gonespy.service.stats;
/**
* Created by gonespy on 8/02/2018.
*
* gstats.gamespy.com:29920
*
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.ServerSocket;
public class GStatsService implements Runnable {
private static final String DISPLAY_NAME = GStatsService.class.getSimpleName();
private static final Logger LOG = LoggerFactory.getLogger(DISPLAY_NAME);
public static final int GSTATS_PORT_NUMBER = 29920;
public static void main(String[] args) {
new GStatsService().run();
}
@Override
public void run() {
try (ServerSocket serverSocket = new ServerSocket(GSTATS_PORT_NUMBER)) {
LOG.info("Listening on port " + GSTATS_PORT_NUMBER);
while (true) {
new GStatsServiceThread(serverSocket.accept()).start();
}
} catch (IOException e) {
System.err.println("Could not listen on port " + GSTATS_PORT_NUMBER);
System.exit(-1);
}
}
}
| 1,050 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
GPMessageUtils.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/util/GPMessageUtils.java | package com.gonespy.service.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class GPMessageUtils {
private static String MESSAGE_DELIMITER = "\\";
private static String REGEX_ESCAPED_MESSAGE_DELIMITER = "\\\\";
private static String MESSAGE_TERMINATOR = MESSAGE_DELIMITER + "final" + MESSAGE_DELIMITER;
private static Pattern DIRECTIVE_PATTERN = Pattern.compile("^" + REGEX_ESCAPED_MESSAGE_DELIMITER + "([^" +
REGEX_ESCAPED_MESSAGE_DELIMITER + "]*)" + REGEX_ESCAPED_MESSAGE_DELIMITER);
public static String readGPMessage(InputStream reader) throws IOException {
StringBuilder msg = new StringBuilder();
byte[] buffer = new byte[1024];
int read;
while((read = reader.read(buffer))!=-1) {
String bytesRead = new String(buffer, 0, read);
msg.append(bytesRead);
if(bytesRead.endsWith(MESSAGE_TERMINATOR)) {
break;
}
}
return msg.toString();
}
public static String getGPDirective(String s) {
Matcher m = DIRECTIVE_PATTERN.matcher(s);
if(m.find()) {
return m.group(1);
}
return null;
}
public static String createGPMessage(Map<String, String> data) {
StringBuilder b = new StringBuilder();
for(String key : data.keySet()) {
b.append(MESSAGE_DELIMITER).append(key).append(MESSAGE_DELIMITER).append(data.get(key));
}
b.append(MESSAGE_TERMINATOR);
return b.toString();
}
public static String createGPEmptyListMessage(String key) {
Map<String, String> map = new LinkedHashMap<>();
map.put(key, "0");
map.put("list", "");
return createGPMessage(map);
}
public static Map<String, String> parseClientLogin (String clientLoginString) {
Map<String, String> map = new HashMap<>();
// remove directive (leading '\xxx\\')
String str = clientLoginString.replaceFirst(
REGEX_ESCAPED_MESSAGE_DELIMITER + "[^" + REGEX_ESCAPED_MESSAGE_DELIMITER + "]*" +
REGEX_ESCAPED_MESSAGE_DELIMITER + REGEX_ESCAPED_MESSAGE_DELIMITER,
""
);
String[] parts = str.split(REGEX_ESCAPED_MESSAGE_DELIMITER);
for(int i = 0; i < parts.length-1; i += 2) {
map.put(parts[i], parts[i + 1]);
}
return map;
}
}
| 2,584 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
GsLargeInt.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/util/GsLargeInt.java | package com.gonespy.service.util;
import javax.crypto.Cipher;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPublicKeySpec;
import java.util.ArrayList;
import java.util.List;
public class GsLargeInt {
private static int GS_LARGEINT_BINARY_SIZE = 2048;
public static int GS_LARGEINT_DIGIT_SIZE_BYTES = 4;
private static int GS_LARGEINT_DIGIT_SIZE_BITS = GS_LARGEINT_DIGIT_SIZE_BYTES * 8;
private static int GS_LARGEINT_MAX_DIGITS = GS_LARGEINT_BINARY_SIZE / GS_LARGEINT_DIGIT_SIZE_BITS;
public int length = 0;
// using long because Java doesn't have unsigned int
public long[] data = new long[64]; // 2048 / 32
public static GsLargeInt gsLargeIntSetFromHexString(String hex) {
int len = hex.length();
GsLargeInt ret = new GsLargeInt();
if (len == 0) {
ret.length = 0;
ret.data[0] = 0;
return ret;
}
if (len / 2 > GS_LARGEINT_MAX_DIGITS * GS_LARGEINT_DIGIT_SIZE_BYTES) {
ret.length = 0;
ret.data[0] = 0;
return ret;
}
ret.length = ((len + (2 * GS_LARGEINT_DIGIT_SIZE_BYTES - 1)) / (2 * GS_LARGEINT_DIGIT_SIZE_BYTES));
ret.data[ret.length - 1] = 0;
int byteIndex = 0;
long temp;
int writePos = 0;
while (len > 0) {
if (len >= 2) {
String s = hex.substring(len - 2, len);
temp = ((Character.digit(s.charAt(0), 16) << 4)
+ Character.digit(s.charAt(1), 16));
} else {
String s = hex.substring(len - 1, len);
temp = (Character.digit(s.charAt(0), 16));
}
ret.data[writePos] |= (temp << (byteIndex * 8));
if (++byteIndex == GS_LARGEINT_DIGIT_SIZE_BYTES) {
writePos++;
byteIndex = 0;
}
len -= Math.min(2, len);
}
return ret;
}
public void gsLargeIntReverseBytes() {
int left = 0;
int right = this.length - 1;
long temp;
while(right >= 0 && left < right) {
temp = this.data[left];
this.data[left++] = this.data[right];
this.data[right--] = temp;
}
}
public int gsLargeIntGetByteLength() {
/*
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Length in bytes so leading zeroes can be dropped from hex strings
gsi_u32 gsLargeIntGetByteLength(const gsLargeInt_t *lint)
{
int intSize = (int)lint->mLength;
int byteSize = 0;
int i=0;
l_word mask = 0xFF;
// skip leading zeroes
while(intSize > 0 && lint->mData[intSize-1] == 0)
intSize --;
if (intSize == 0)
return 0; // no data
byteSize = intSize * (gsi_i32)sizeof(l_word);
// subtract bytes for each leading 0x00 byte
mask = 0xFF;
for (i=1; i < GS_LARGEINT_DIGIT_SIZE_BYTES; i++)
{
if (lint->mData[intSize-1] <= mask)
{
byteSize -= sizeof(l_word)-i;
break;
}
mask = (l_word)((mask << 8) | 0xFF);
}
return (gsi_u32)byteSize;
}
*/
int intSize = this.length;
// skip leading zeroes
while(intSize > 0 && this.data[intSize-1] == 0)
intSize --;
if (intSize == 0)
return 0; // no data
int byteSize = intSize * Integer.BYTES;
// subtract bytes for each leading 0x00 byte
long mask = 0xFF;
for (int i=1; i < GS_LARGEINT_DIGIT_SIZE_BYTES; i++)
{
if (this.data[intSize-1] <= mask)
{
byteSize -= Integer.BYTES-i;
break;
}
mask = ((mask << 8) | 0xFF);
}
return byteSize;
}
// GsLargeInt.data in C can be passed to MD5 function as byte array parameter by casting a pointer
// in Java we need to convert each long (acting as an unsigned int) explictly to 4 bytes
public byte[] dataAsByteArray() {
byte[] bytes = new byte[this.length * Integer.BYTES];
for(int integerIndex = 0; integerIndex < this.length; integerIndex++) {
long byteVal = this.data[integerIndex];
for(int byteIndex = 0; byteIndex < Integer.BYTES; byteIndex++) {
if(byteIndex > 0) {
byteVal >>>= 8;
}
bytes[Integer.BYTES * integerIndex + byteIndex] = (byte)byteVal;
}
}
return bytes;
}
//gsi_bool gsLargeIntPowerMod(const gsLargeInt_t *b, const gsLargeInt_t *p, const gsLargeInt_t *m, gsLargeInt_t *dest)
public static GsLargeInt encrypt(GsLargeInt base, GsLargeInt privateExp, GsLargeInt privateMod) {
// let's use RSA stuff instead of the C custom implementation
try {
Cipher cipher = Cipher.getInstance("RSA");
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
String modString = privateMod.toHexString();
String expString = privateExp.toHexString();
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modString, 16), new BigInteger(expString, 16));
RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherBytes = cipher.doFinal(base.dataAsByteArray());
StringBuilder sb = new StringBuilder();
for(int i = cipherBytes.length - 1; i >= 0; i -= Integer.BYTES) {
for(int j = i-3; j <= i; j++) {
sb.append(String.format("%02X", cipherBytes[j]));
}
}
String encrypted = sb.toString();
return GsLargeInt.gsLargeIntSetFromHexString(encrypted);
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public String toHexString() {
byte[] bytes = dataAsByteArray();
StringBuilder sb = new StringBuilder();
for(int i = bytes.length - 1; i >= 0; i -= Integer.BYTES) {
for(int j = i-3; j <= i; j++) {
sb.append(String.format("%02X", bytes[j]));
}
}
return sb.toString();
}
public String toString() {
String arrData = "";
for (long i : data) {
arrData += i + ",";
}
return "{length=" + length + ", data=" + arrData + "}";
}
} | 6,790 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
SoapUtils.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/util/SoapUtils.java | package com.gonespy.service.util;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class SoapUtils {
private static final String TAG_PREAMBLE = "ns1:";
private static final String SOAP_POSTAMBLE = "</SOAP-ENV:Body></SOAP-ENV:Envelope>\r\n";
private static final String SOAP_PREAMBLE_1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:ns1=\"http://gamespy.net/";
private static final String SOAP_PREAMBLE_2 = "\"><SOAP-ENV:Body>";
public static String wrapSoapData(String path, String type, String soap) {
final String soapPreamble = SOAP_PREAMBLE_1 + path + SOAP_PREAMBLE_2;
return soapPreamble + openSoapTag(type) + soap + closeSoapTag(type) + SOAP_POSTAMBLE;
}
public static String emptySoapTag(String tag) {
return openSoapTag(tag) + closeSoapTag(tag);
}
public static String createSoapTagWithValue(String tag, Object value) {
if(value instanceof String) {
return openSoapTag(tag) + value + closeSoapTag(tag);
} else {
// map
Map<String, String> map = (Map)value;
String valueString = "";
for(String key : map.keySet()) {
valueString += openSoapTag(key) + map.get(key) + closeSoapTag(key);
}
return openSoapTag(tag) + valueString + closeSoapTag(tag);
}
}
private static String openSoapTag(String tag) {
return "<" + TAG_PREAMBLE + tag + ">";
}
private static String closeSoapTag(String tag) {
return "</" + TAG_PREAMBLE + tag + ">";
}
public static Map<String, Object> parseSoapData(String soapData) {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
Map<String, Object> data = new HashMap<>();
try {
dBuilder = dbFactory.newDocumentBuilder();
} catch(ParserConfigurationException e) {
return null;
}
InputStream stream = new ByteArrayInputStream(soapData.getBytes(StandardCharsets.UTF_8));
Document doc;
try {
doc = dBuilder.parse(stream);
} catch (IOException|SAXException e) {
return null;
}
doc.getDocumentElement().normalize();
Node soapBody = doc.getDocumentElement().getFirstChild(); // soap-env-body
if(!soapBody.getNodeName().equals("SOAP-ENV:Body")) {
return null;
}
Node ns1TopNode = soapBody.getFirstChild();
data.put("ns1", stripTagPreamble(ns1TopNode.getNodeName()));
NodeList nodeList = ns1TopNode.getChildNodes();
for(int i=0; i<nodeList.getLength(); i++) {
Node n = nodeList.item(i);
NodeList nl = n.getChildNodes();
for(int j=0; j<nl.getLength(); j++) {
Node n2 = nl.item(j);
if(n2.getNodeType() == Node.TEXT_NODE) {
data.put(stripTagPreamble(n.getNodeName()), n2.getNodeValue());
} else {
data.put(stripTagPreamble(n.getNodeName()), nodesToMap(n2));
}
}
}
return data;
}
private static Map<String, Object> nodesToMap(Node node) {
Map<String, Object> data = new HashMap<>();
NodeList nl = node.getChildNodes();
for(int j=0; j<nl.getLength(); j++) {
Node n2 = nl.item(j);
if(n2.getNodeType() == Node.TEXT_NODE) {
data.put(stripTagPreamble(node.getNodeName()), n2.getNodeValue());
} else {
data.put(stripTagPreamble(n2.getNodeName()), nodesToMap(n2));
}
}
return data;
}
private static String stripTagPreamble(String nodeName) {
String ret = nodeName;
if (nodeName.startsWith(TAG_PREAMBLE)) {
ret = nodeName.replaceFirst(TAG_PREAMBLE, "");
}
return ret;
}
}
| 4,580 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
GPNetworkException.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/util/GPNetworkException.java | package com.gonespy.service.util;
import java.io.IOException;
public class GPNetworkException extends IOException {
public GPNetworkException(String s) {
super(s);
}
}
| 186 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
StringUtils.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/util/StringUtils.java | package com.gonespy.service.util;
import com.google.common.base.Strings;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.util.Map;
import java.util.Random;
import static com.gonespy.service.util.GsLargeInt.GS_LARGEINT_DIGIT_SIZE_BYTES;
public abstract class StringUtils {
private static final String MD5_FILLER = Strings.padEnd("", 48, ' ');
public static String asciiToReadableHex(byte[] bytes) {
StringBuilder hex = new StringBuilder();
for (byte b : bytes) {
hex.append(String.format("%02X ", b));
}
return hex.toString();
}
private final static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToReadableHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 3 - 1];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 3] = HEX_ARRAY[v >>> 4];
hexChars[j * 3 + 1] = HEX_ARRAY[v & 0x0F];
if(j != bytes.length - 1) {
hexChars[j * 3 + 2] = ' ';
}
}
return new String(hexChars);
}
public static String gsLoginProof(final String password, final String user, final String clientChallenge,
final String serverChallenge) {
final String passwordHash = DigestUtils.md5Hex(password);
final String preHash = passwordHash + MD5_FILLER + user + serverChallenge + clientChallenge + passwordHash;
return DigestUtils.md5Hex(preHash);
}
private static byte[] hexStringToByteArray(String hexString) {
byte[] serverData = new byte[0];
try {
serverData = Hex.decodeHex(hexString.toCharArray());
} catch (DecoderException d) {
}
return serverData;
}
public static String hashCertificate(Map<String,String> certificateData) {
MessageDigest md = DigestUtils.getMd5Digest();
// integers
// temp = wsiMakeLittleEndian32(cert->mLength);
// MD5Update(&md5, (unsigned char*)&temp, 4);
messageDigestUpdateInteger(md, certificateData.get("length"));
messageDigestUpdateInteger(md, certificateData.get("version"));
messageDigestUpdateInteger(md, certificateData.get("partnercode"));
messageDigestUpdateInteger(md, certificateData.get("namespaceid"));
messageDigestUpdateInteger(md, certificateData.get("userid"));
messageDigestUpdateInteger(md, certificateData.get("profileid"));
messageDigestUpdateInteger(md, certificateData.get("expiretime"));
// strings
// MD5Update(&md5, (unsigned char*)&cert->mProfileNick, strlen(cert->mProfileNick));
messageDigestUpdateString(md, certificateData.get("profilenick"));
messageDigestUpdateString(md, certificateData.get("uniquenick"));
messageDigestUpdateString(md, certificateData.get("cdkeyhash"));
// Largeints from peer public key
// XML: big-endian
// SDK read: converts to little-endian internally
// SDK MD5: converts back to big-endian before MD5 update
// gsLargeIntAddToMD5(&cert->mPeerPublicKey.modulus, &md5);
messageDigestUpdateLargeInt(md, certificateData.get("peerkeymodulus"));
messageDigestUpdateLargeInt(md, certificateData.get("peerkeyexponent"));
// serverdata string
// In XML: hex
// SDK read: converts from hex to string on read
// SDK MD5:
// TODO: endian-ness? in SDK when reading the hex string from the cert: // switch endianess, e.g. first character in hexstring is HI byte
messageDigestUpdateHexString(md, certificateData.get("serverdata"));
return Hex.encodeHexString(md.digest());
}
private static void messageDigestUpdateInteger(MessageDigest md, String str) {
if(str != null) {
Integer i = Integer.parseInt(str);
byte[] bytes = ByteBuffer.allocate(Integer.BYTES).putInt(i).array();
md.update(bytes, 0, Integer.BYTES);
}
}
private static void messageDigestUpdateString(MessageDigest md, String str) {
if(str != null) {
byte[] arr = str.getBytes();
md.update(arr, 0, arr.length);
}
}
private static void messageDigestUpdateHexString(MessageDigest md, String str) {
if(str != null) {
byte[] arr = hexStringToByteArray(str);
md.update(arr, 0, arr.length);
}
}
private static void messageDigestUpdateLargeInt(MessageDigest md, String str) {
/*
// hashing is made complicated by differing byte orders
void gsLargeIntAddToMD5(const gsLargeInt_t * _lint, MD5_CTX * md5)
{
int byteLength = 0;
gsi_u8 * dataStart = NULL;
// Create a non-const copy so we can reverse bytes to add to the MD5 hash
gsLargeInt_t lint;
memcpy(&lint, _lint, sizeof(lint));
// first, calculate the byte length
byteLength = (int)gsLargeIntGetByteLength(&lint);
if (byteLength == 0)
return; // no data
dataStart = (gsi_u8*)lint.mData;
if ((byteLength % GS_LARGEINT_DIGIT_SIZE_BYTES) != 0)
dataStart += GS_LARGEINT_DIGIT_SIZE_BYTES - (byteLength % GS_LARGEINT_DIGIT_SIZE_BYTES);
// reverse to big-endian (MS) then hash
gsLargeIntReverseBytes(&lint);
MD5Update(md5, dataStart, (unsigned int)byteLength);
gsLargeIntReverseBytes(&lint);
}
*/
if(str != null) {
GsLargeInt lint = GsLargeInt.gsLargeIntSetFromHexString(str);
int byteLength = lint.gsLargeIntGetByteLength();
if (byteLength == 0) {
return;
}
int dataStart = 0;
if (byteLength % GS_LARGEINT_DIGIT_SIZE_BYTES != 0) {
dataStart += GS_LARGEINT_DIGIT_SIZE_BYTES - (byteLength % GS_LARGEINT_DIGIT_SIZE_BYTES);
}
lint.gsLargeIntReverseBytes();
md.update(lint.dataAsByteArray(), dataStart, byteLength);
lint.gsLargeIntReverseBytes();
}
}
}
| 6,423 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
CertificateUtils.java | /FileExtraction/Java_unseen/gonespy_bstormps3/src/main/java/com/gonespy/service/util/CertificateUtils.java | package com.gonespy.service.util;
import com.gonespy.service.gpcm.GPCMServiceThread;
import com.google.common.base.Strings;
import java.util.LinkedHashMap;
import java.util.Map;
public abstract class CertificateUtils {
// PUBLIC EXPONENT / POWER
public static final String WS_AUTHSERVICE_SIGNATURE_EXP = "010001";
// SHARED MODULUS
// 256 chars = 128 bytes
public static final String WS_AUTHSERVICE_SIGNATURE_KEY =
"BF05D63E93751AD4A59A4A7389CF0BE8" +
"A22CCDEEA1E7F12C062D6E194472EFDA"+
"5184CCECEB4FBADF5EB1D7ABFE911814"+
"53972AA971F624AF9BA8F0F82E2869FB"+
"7D44BDE8D56EE50977898F3FEE758696"+
"22C4981F07506248BD3D092E8EA05C12"+
"B2FA37881176084C8F8B8756C4722CDC"+
"57D2AD28ACD3AD85934FB48D6B2D2027";
// don't know what this is :(
// value here is commented out from AuthService.c - worth a try
public static final String WS_AUTHSERVICE_SIGNATURE_PRIVATE_EXP = "D589F4433FAB2855F85A4EB40E6311F0" +
"284C7882A72380938FD0C55CC1D65F7C" +
"6EE79EDEF06C1AE5EDE139BDBBAB4219" +
"B7D2A3F0AC3D3B23F59F580E0E89B9EC" +
"787F2DD5A49788C633D5D3CE79438934" +
"861EA68AE545D5BBCAAAD917CE9F5C7C" +
"7D1452D9214F989861A7511097C35E60" +
"A7273DECEA71CB5F8251653B26ACE781";
// PEER KEY
// 256 chars = 128 bytes
public static final String PEER_KEY_MODULUS =
"95375465E3FAC4900FC912E7B30EF717"+
"1B0546DF4D185DB04F21C79153CE0918" +
"59DF2EBDDFE5047D80C2EF86A2169B05" +
"A933AE2EAB2962F7B32CFE3CB0C25E7E" +
"3A26BB6534C9CF19640F1143735BD0CE" +
"AA7AA88CD64ACEC6EEB037007567F1EC" +
"51D00C1D2F1FFCFECB5300C93D6D6A50" +
"C1E3BDF495FC17601794E5655C476819";
// 256 chars = 128 bytes
public static final String SERVER_DATA =
"908EA21B9109C45591A1A011BF84A189" +
"40D22E032601A1B2DD235E278A9EF131" +
"404E6B07F7E2BE8BF4A658E2CB2DDE27" +
"E09354B7127C8A05D10BB4298837F965" +
"18CCB412497BE01ABA8969F9F46D23EB" +
"DE7CC9BE6268F0E6ED8209AD79727BC8" +
"E0274F6725A67CAB91AC87022E587104" +
"0BF856E541A76BB57C07F4B9BE4C6316";
public static final String MD5_HEADER_STRING = "3020300C06082A864886F70D020505000410";
public static final String CRYPTO_PREFIX = "0001";
public static final String CRYPTO_SEPARATOR_BYTE = "00";
public static Map<String, String> getCertificate(Map<String, Object> inputData) {
Map<String, String> certificateData = new LinkedHashMap<>();
certificateData.put("length", "303");
certificateData.put("version", (String)inputData.get("version"));
certificateData.put("partnercode", (String)inputData.get("partnercode"));
certificateData.put("namespaceid", (String)inputData.get("namespaceid"));
certificateData.put("userid", GPCMServiceThread.DUMMY_USER_ID);
certificateData.put("profileid", GPCMServiceThread.DUMMY_PROFILE_ID);
certificateData.put("expiretime", "0");
certificateData.put("profilenick", GPCMServiceThread.DUMMY_UNIQUE_NICK);
certificateData.put("uniquenick", GPCMServiceThread.DUMMY_UNIQUE_NICK);
certificateData.put("cdkeyhash", "");
certificateData.put("peerkeymodulus", PEER_KEY_MODULUS); // 256 chars = 128 bytes
certificateData.put("peerkeyexponent", WS_AUTHSERVICE_SIGNATURE_EXP);
certificateData.put("serverdata", SERVER_DATA); // 256 chars = 128 bytes
String md5 = StringUtils.hashCertificate(certificateData);
String signature = generateSignature(md5);
certificateData.put("signature", signature);
return certificateData;
}
// // A user's login certificate, signed by the GameSpy AuthService
//// The certificate is public and may be freely passed around
//// Avoid use of pointer members so that structure may be easily copied
// gsi_u8 = unsigned char (0 -> 255)
// gsi_u32 = l_word = unsigned int
//typedef struct GSLoginCertificate
//{
// gsi_bool mIsValid;
//
// gsi_u32 mLength;
// gsi_u32 mVersion;
// gsi_u32 mPartnerCode; // aka Account space
// gsi_u32 mNamespaceId;
// gsi_u32 mUserId;
// gsi_u32 mProfileId;
// gsi_u32 mExpireTime;
// gsi_char mProfileNick[WS_LOGIN_NICK_LEN];
// gsi_char mUniqueNick[WS_LOGIN_UNIQUENICK_LEN];
// gsi_char mCdKeyHash[WS_LOGIN_KEYHASH_LEN]; // hexstr - bigendian
// gsCryptRSAKey mPeerPublicKey;
// gsi_u8 mSignature[GS_CRYPT_RSA_BYTE_SIZE]; // binary - bigendian // 128
// gsi_u8 mServerData[WS_LOGIN_SERVERDATA_LEN]; // binary - bigendian // 128
//} GSLoginCertificate;
//
// typedef struct
//{
// gsLargeInt_t modulus;
// gsLargeInt_t exponent;
//} gsCryptRSAKey;
// GS_LARGEINT_DIGIT_TYPE = gsi_u32
// GS_LARGEINT_MAX_DIGITS = 2048 / (4*8) = 64
// typedef struct gsLargeInt_s
//{
// GS_LARGEINT_DIGIT_TYPE mLength;
// GS_LARGEINT_DIGIT_TYPE mData[GS_LARGEINT_MAX_DIGITS];
//} gsLargeInt_t;
//// Private information for the owner of the certificate only
//// -- careful! private key information must be kept secret --
//typedef struct GSLoginCertificatePrivate
//{
// gsCryptRSAKey mPeerPrivateKey;
// char mKeyHash[GS_CRYPT_MD5_HASHSIZE];
//} GSLoginPrivateData;
// client reads cert ints like this: (no endian stuff when reading the SOAP)
// if (gsi_is_false(gsXmlReadChildAsInt (reader, "length", (int*)&cert->mLength)) ||
// strings like this: (null-terminated)
// gsi_is_false(gsXmlReadChildAsTStringNT (reader, "profilenick", cert->mProfileNick, WS_LOGIN_NICK_LEN)) ||
// peerkeymodulus / peerkeyexponent - gsLargeIntSetFromHexString implemented in gonespy. hex -> int array weirdness
// GS_CRYPT_RSA_BYTE_SIZE = 128 , times 2 chars per byte = 256 characters, plus one for null termination
// gsi_is_false(gsXmlReadChildAsStringNT (reader, "peerkeymodulus", hexstr, GS_CRYPT_RSA_BYTE_SIZE*2 +1)) ||
// gsi_is_false(gsLargeIntSetFromHexString(&cert->mPeerPublicKey.modulus, hexstr)) ||
// serverdata - WS_LOGIN_SERVERDATA_LEN = 128
// gsi_is_false(gsXmlReadChildAsHexBinary(reader, "serverdata", cert->mServerData, WS_LOGIN_SERVERDATA_LEN, &hexlen)) ||
// signature - WS_LOGIN_SIGNATURE_LEN = 128
// gsi_is_false(gsXmlReadChildAsHexBinary(reader, "signature", cert->mSignature, WS_LOGIN_SIGNATURE_LEN, &hexlen))
// and private exponent
// gsi_is_false(gsXmlReadChildAsLargeInt(theResponseXml, "peerkeyprivate", &response.mPrivateData.mPeerPrivateKey.exponent))
// peer privatekey modulus is same as peer public key modulus
// memcpy(&response.mPrivateData.mPeerPrivateKey.modulus, &cert->mPeerPublicKey.modulus, sizeof(cert->mPeerPublicKey.modulus));
// verify certificate
// cert->mIsValid = wsLoginCertIsValid(cert);
private static String generateSignature(String md5) {
// raw length should be 128 bytes / 256 chars
// Signature format:
// [ 0x00 0x01 0xFF ... 0x00 HashHeader Hash(Data) ]
// gsi_u8 md5Header[18] = {0x30,0x20,0x30,0x0C,0x06,0x08,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x02,0x05,0x05,0x00,0x04,0x10};
// md5 is 32 characters long
// eg. 256 - (4 + 2 + 36 + 32) = 182 = 91 pairs of FF as padding
int paddingCount = (
256 - CRYPTO_PREFIX.length() - CRYPTO_SEPARATOR_BYTE.length() - MD5_HEADER_STRING.length() - md5.length()
) / 2 - 22;
String rawSignature = CRYPTO_PREFIX + Strings.repeat("FF", paddingCount) + CRYPTO_SEPARATOR_BYTE +
MD5_HEADER_STRING + md5;
/*
// "decrypt" the signature
lintRSASignature.mLength = (l_word)(sigLen / 4);
memcpy(lintRSASignature.mData, sig, sigLen);
gsLargeIntReverseBytes(&lintRSASignature);
gsLargeIntPowerMod(&lintRSASignature, &publicKey->exponent, &publicKey->modulus, &lintRSASignature);
gsLargeIntReverseBytes(&lintRSASignature);
*/
GsLargeInt lint = GsLargeInt.gsLargeIntSetFromHexString(rawSignature);
// TODO: should be encrypting with PRIVATE key - what is it?
// client decrypts with public key WS_AUTHSERVICE_SIGNATURE_KEY / WS_AUTHSERVICE_SIGNATURE_EXP
lint.gsLargeIntReverseBytes();
GsLargeInt encryptedLint = GsLargeInt.encrypt(
lint,
GsLargeInt.gsLargeIntSetFromHexString(WS_AUTHSERVICE_SIGNATURE_PRIVATE_EXP),
GsLargeInt.gsLargeIntSetFromHexString(WS_AUTHSERVICE_SIGNATURE_KEY)
);
encryptedLint.gsLargeIntReverseBytes();
return encryptedLint.toHexString();
}
// copied from eaEmu https://github.com/teknogods/eaEmu/blob/master/eaEmu/gamespy/webServices.py
// for c&c red alert 3 - doesn't seem to work for other games?
// Possibly because version/partnercode/namespaceid are different, thus affect the signature
public static Map<String, String> getCertificateEaEmu(Map<String, Object> inputData) {
Map<String, String> certificateData = new LinkedHashMap<>();
certificateData.put("length", "303");
certificateData.put("version", (String)inputData.get("version")); // 1?
certificateData.put("partnercode", (String)inputData.get("partnercode")); // what is this for c&c ra3?
certificateData.put("namespaceid", (String)inputData.get("namespaceid")); // what is this for c&c ra3?
certificateData.put("userid", "11111");
certificateData.put("profileid", "22222");
certificateData.put("expiretime", "0");
certificateData.put("profilenick", "Jackalus");
certificateData.put("uniquenick", "Jackalus");
certificateData.put("cdkeyhash", "");
certificateData.put("peerkeymodulus", PEER_KEY_MODULUS);
certificateData.put("peerkeyexponent", WS_AUTHSERVICE_SIGNATURE_EXP);
certificateData.put("serverdata", SERVER_DATA);
certificateData.put("signature",
"181A4E679AC27D83543CECB8E1398243113EF6322D630923C6CD26860F265FC031C2C61D4F9D86046C07BBBF9CF86894903BD867E3CB59A0D9EFDADCB34A7FB3CC8BC7650B48E8913D327C38BB31E0EEB06E1FC1ACA2CFC52569BE8C48840627783D7FFC4A506B1D23A1C4AEAF12724DEB12B5036E0189E48A0FCB2832E1FB00");
return certificateData;
}
}
| 10,726 | Java | .java | gonespy/bstormps3 | 27 | 6 | 4 | 2018-02-13T06:47:07Z | 2020-10-13T08:47:07Z |
ExampleUnitTest.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/test/java/com/example/drclient/ExampleUnitTest.java | package com.example.drclient;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | 381 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.