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 |
---|---|---|---|---|---|---|---|---|---|---|---|
LabelTextReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/text/LabelTextReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.text;
import org.openjdk.backports.report.BackportStatus;
import org.openjdk.backports.report.model.IssueModel;
import org.openjdk.backports.report.model.LabelModel;
import java.io.PrintStream;
import java.util.Date;
public class LabelTextReport extends AbstractTextReport {
private final LabelModel model;
public LabelTextReport(LabelModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
out.println("LABEL REPORT: " + model.label());
printMajorDelimiterLine(out);
out.println();
out.println("This report shows bugs with the given label, along with their backporting status.");
out.println();
out.println("Report generated: " + new Date());
out.println();
out.println("Minimal actionable level to display: " + model.minLevel());
out.println();
out.println("For actionable issues, search for these strings:");
out.println(" \"" + statusToText(BackportStatus.MISSING) + "\"");
out.println(" \"" + statusToText(BackportStatus.APPROVED) + "\"");
out.println(" \"" + statusToText(BackportStatus.WARNING) + "\"");
out.println();
out.println("For lingering issues, search for these strings:");
out.println(" \"" + statusToText(BackportStatus.BAKING) + "\"");
out.println();
printMinorDelimiterLine(out);
for (IssueModel im : model.issues()) {
new IssueTextReport(im, debugLog, logPrefix).generateSimple(out);
printMinorDelimiterLine(out);
}
out.println();
out.println("" + model.issues().size() + " issues shown.");
}
}
| 3,001 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
FilterTextReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/text/FilterTextReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.text;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.google.common.collect.Multimap;
import org.openjdk.backports.Main;
import org.openjdk.backports.report.model.FilterModel;
import java.io.PrintStream;
import java.util.Date;
public class FilterTextReport extends AbstractTextReport {
private final FilterModel model;
public FilterTextReport(FilterModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
out.println("FILTER REPORT");
printMajorDelimiterLine(out);
out.println();
out.println("This report shows brief list of issues matching the filter.");
out.println();
out.println("Report generated: " + new Date());
out.println();
out.println("Filter: " + model.name());
out.println("Filter URL: " + Main.JIRA_URL + "issues/?filter=" + model.filterId());
out.println();
out.println("Hint: Prefix bug IDs with " + Main.JIRA_URL + "browse/ to reach the relevant JIRA entry.");
out.println();
Multimap<String, Issue> byComponent = model.byComponent();
for (String component : byComponent.keySet()) {
out.println(component + ":");
for (Issue i : byComponent.get(component)) {
out.println(" " + i.getKey() + ": " + i.getSummary());
}
out.println();
}
out.println();
}
}
| 2,759 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
PendingPushModel.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/model/PendingPushModel.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.model;
import com.atlassian.jira.rest.client.api.domain.Issue;
import org.openjdk.backports.hg.HgDB;
import org.openjdk.backports.jira.Clients;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
public class PendingPushModel extends AbstractModel {
private final String release;
private final List<IssueModel> models;
public PendingPushModel(Clients clients, HgDB hgDB, PrintStream debugOut, String release) {
super(clients, debugOut);
this.release = release;
String query = "labels = jdk" + release + "u-fix-yes AND labels != openjdk-na AND fixVersion !~ '" + release + ".*'";
switch (release) {
case "8":
query += " AND fixVersion !~ 'openjdk8u*'";
query += " AND issue not in linked-subquery(\"issue in subquery(\\\"fixVersion ~ 'openjdk8u*' AND (status = Closed OR status = Resolved)\\\")\")";
break;
default:
query += " AND issue not in linked-subquery(\"issue in subquery(\\\"fixVersion ~ '" + release + ".*' AND fixVersion !~ '*oracle' AND (status = Closed OR status = Resolved)\\\")\")";
}
List<Issue> found = jiraIssues.getIssues(query, false);
found.sort(DEFAULT_ISSUE_SORT);
models = new ArrayList<>();
for (Issue i : found) {
models.add(new IssueModel(clients, hgDB, debugOut, i));
}
}
public String release() {
return release;
}
public List<IssueModel> models() {
return models;
}
}
| 2,791 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
FilterModel.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/model/FilterModel.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.model;
import com.atlassian.jira.rest.client.api.domain.Filter;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import org.openjdk.backports.jira.Accessors;
import org.openjdk.backports.jira.Clients;
import java.io.PrintStream;
import java.util.List;
public class FilterModel extends AbstractModel {
private final long filterId;
private final Multimap<String, Issue> byComponent;
private final String name;
private final List<Issue> issues;
public FilterModel(Clients clients, PrintStream debugOut, long filterId) {
super(clients, debugOut);
this.filterId = filterId;
Filter filter = searchCli.getFilter(filterId).claim();
name = filter.getName();
issues = jiraIssues.getBasicIssues(filter.getJql());
issues.sort(DEFAULT_ISSUE_SORT);
byComponent = TreeMultimap.create(String::compareTo, DEFAULT_ISSUE_SORT);
for (Issue issue : issues) {
byComponent.put(Accessors.extractComponents(issue), issue);
}
}
public long filterId() {
return filterId;
}
public Multimap<String, Issue> byComponent() {
return byComponent;
}
public String name() {
return name;
}
public List<Issue> issues() {
return issues;
}
}
| 2,611 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
ReleaseNotesModel.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/model/ReleaseNotesModel.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.model;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import org.openjdk.backports.jira.Accessors;
import org.openjdk.backports.jira.Clients;
import org.openjdk.backports.jira.Versions;
import java.io.PrintStream;
import java.util.*;
public class ReleaseNotesModel extends AbstractModel {
private final String release;
private final boolean includeCarryovers;
private final List<Issue> jepIssues;
private final Map<String, Multimap<Issue, Issue>> relNotes;
private final Multimap<String, Issue> byComponent;
private final SortedSet<Issue> carriedOver;
public ReleaseNotesModel(Clients clients, PrintStream debugOut, boolean includeCarryovers, String release) {
super(clients, debugOut);
this.release = release;
this.includeCarryovers = includeCarryovers;
Multimap<Issue, Issue> issues = jiraIssues.getIssuesWithBackportsFull("project = JDK" +
" AND (status in (Closed, Resolved))" +
" AND (resolution not in (\"Won't Fix\", Duplicate, \"Cannot Reproduce\", \"Not an Issue\", Withdrawn))" +
" AND (labels not in (release-note, testbug, openjdk-na, testbug) OR labels is EMPTY)" +
" AND (summary !~ 'testbug')" +
" AND (summary !~ 'problemlist') AND (summary !~ 'problem list') AND (summary !~ 'release note')" +
" AND (issuetype != CSR)" +
" AND fixVersion = " + release);
jepIssues = jiraIssues.getParentIssues("project = JDK AND issuetype = JEP" +
" AND fixVersion = " + release + "" +
" ORDER BY summary ASC");
byComponent = TreeMultimap.create(String::compareTo, DEFAULT_ISSUE_SORT);
carriedOver = new TreeSet<>(DEFAULT_ISSUE_SORT);
int majorRelease = Versions.parseMajor(release);
int minorRelease = Versions.parseMinor(release);
for (Issue issue : issues.keySet()) {
boolean firstInTrain = false;
// Check the root issue is later than the one we want for the backport
for (String ver : Accessors.getFixVersions(issue)) {
if (Versions.parseMajor(ver) >= majorRelease) {
firstInTrain = true;
break;
}
}
// Check the root issue does not fix earlier minor versions in the same major train
if (firstInTrain) {
for (String ver : Accessors.getFixVersions(issue)) {
if (Versions.isOpen(ver) &&
Versions.parseMajor(ver) == majorRelease &&
Versions.parseMinor(ver) < minorRelease) {
firstInTrain = false;
break;
}
}
}
// Check there are no backports in earlier minor versions in the same major train
if (firstInTrain) {
for (Issue bp : issues.get(issue)) {
if (!Accessors.isDelivered(bp)) continue;
for (String ver : Accessors.getFixVersions(bp)) {
if (Versions.isOpen(ver) &&
Versions.parseMajor(ver) == majorRelease &&
Versions.parseMinor(ver) < minorRelease) {
firstInTrain = false;
break;
}
}
}
}
if (firstInTrain) {
byComponent.put(Accessors.extractComponents(issue), issue);
} else {
// These are parent issues that have "accidental" forward port to requested release.
// Filter them out as "carried over".
carriedOver.add(issue);
}
}
debugOut.println("Filtered " + carriedOver.size() + " issues carried over, " + byComponent.size() + " pushes left.");
relNotes = new HashMap<>();
for (String component : byComponent.keySet()) {
Multimap<Issue, Issue> m = HashMultimap.create();
relNotes.put(component, m);
for (Issue i : byComponent.get(component)) {
Collection<Issue> rns = jiraIssues.getReleaseNotes(i);
if (!rns.isEmpty()) {
m.putAll(i, rns);
}
}
}
}
public boolean includeCarryovers() {
return includeCarryovers;
}
public String release() {
return release;
}
public List<Issue> jeps() {
return jepIssues;
}
public Map<String, Multimap<Issue, Issue>> relNotes() {
return relNotes;
}
public Multimap<String, Issue> byComponent() {
return byComponent;
}
public SortedSet<Issue> carriedOver() {
return carriedOver;
}
}
| 6,239 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
IssueModel.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/model/IssueModel.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.model;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.IssueLink;
import com.atlassian.jira.rest.client.api.domain.Version;
import org.openjdk.backports.Actionable;
import org.openjdk.backports.Actions;
import org.openjdk.backports.hg.HgDB;
import org.openjdk.backports.hg.HgRecord;
import org.openjdk.backports.jira.Accessors;
import org.openjdk.backports.jira.Clients;
import org.openjdk.backports.jira.IssuePromise;
import org.openjdk.backports.jira.Versions;
import org.openjdk.backports.report.BackportStatus;
import java.io.PrintStream;
import java.util.*;
public class IssueModel extends AbstractModel {
private final HgDB hgDB;
private final SortedMap<Integer, List<Issue>> existingPorts = new TreeMap<>();
private final SortedMap<Integer, BackportStatus> pendingPorts = new TreeMap<>();
private final SortedMap<Integer, String> pendingPortsDetails = new TreeMap<>();
private final SortedMap<Integer, BackportStatus> shenandoahPorts = new TreeMap<>();
private final SortedMap<Integer, String> shenandoahPortsDetails = new TreeMap<>();
private Collection<Issue> relNotes;
private Issue issue;
private int fixVersion;
private final Actions actions = new Actions();
private String components;
private long daysAgo;
private int priority;
private List<String> warnings = new ArrayList<>();
public IssueModel(Clients clients, HgDB hgDB, PrintStream debugOut, String issueId) {
super(clients, debugOut);
this.hgDB = hgDB;
init(issueCli.getIssue(issueId).claim());
}
public IssueModel(Clients clients, HgDB hgDB, PrintStream debugOut, Issue issue) {
super(clients, debugOut);
this.hgDB = hgDB;
init(issue);
}
private static <T> Iterable<T> orEmpty(Iterable<T> it) {
return (it != null) ? it : Collections.emptyList();
}
private void init(Issue issue) {
this.issue = issue;
components = Accessors.extractComponents(issue);
Set<Integer> oracleBackports = new HashSet<>();
daysAgo = Accessors.getPushDaysAgo(issue);
priority = Accessors.getPriority(issue);
fixVersion = Versions.parseMajor(Accessors.getFixVersion(issue));
recordExistingStatus(existingPorts, issue);
Set<Integer> affectedReleases = new HashSet<>();
Set<Integer> affectedShenandoah = new HashSet<>();
for (Version v : orEmpty(issue.getAffectedVersions())) {
String verName = v.getName();
int ver = Versions.parseMajor(verName);
int verSh = Versions.parseMajorShenandoah(verName);
if (ver == 0) {
// Special case: odd version, ignore it
} else if (ver > 0) {
affectedReleases.add(ver);
} else if (verSh > 0) {
affectedShenandoah.add(verSh);
} else {
warnings.add("Unknown version: " + ver);
actions.update(Actionable.CRITICAL);
}
}
if (affectedReleases.isEmpty() && affectedShenandoah.isEmpty()) {
warnings.add("Affected versions are not set");
actions.update(Actionable.CRITICAL);
}
List<IssuePromise> links = new ArrayList<>();
for (IssueLink link : orEmpty(issue.getIssueLinks())) {
if (link.getIssueLinkType().getName().equals("Backport")) {
String linkKey = link.getTargetIssueKey();
links.add(jiraIssues.getIssue(linkKey));
}
}
for (IssuePromise p : links) {
Issue subIssue = p.claim();
recordExistingStatus(existingPorts, subIssue);
recordOracleStatus(oracleBackports, subIssue);
}
int highRel = existingPorts.isEmpty() ? fixVersion : existingPorts.lastKey();
for (int release : VERSIONS_TO_CARE_FOR) {
if (release == fixVersion) continue;
List<Issue> lines = existingPorts.get(release);
if (lines != null) {
affectedReleases.add(release);
}
}
for (int release : VERSIONS_TO_CARE_FOR) {
if (existingPorts.containsKey(release)) continue;
BackportStatus status;
String msg = "";
if (issue.getLabels().contains("jdk" + release + "u-critical-yes")) {
actions.update(Actionable.PUSHABLE, importanceCritical(release));
msg = "jdk" + release + "u-critical-yes is set";
status = BackportStatus.APPROVED;
} else if (issue.getLabels().contains("jdk" + release + "u-fix-yes")) {
actions.update(Actionable.PUSHABLE, importanceDefault(release));
msg = "jdk" + release + "u-fix-yes is set";
status = BackportStatus.APPROVED;
} else if (issue.getLabels().contains("jdk" + release + "u-fix-no")) {
msg = "jdk" + release + "u-fix-no is set";
status = BackportStatus.REJECTED;
} else if (issue.getLabels().contains("jdk" + release + "u-critical-request")) {
actions.update(Actionable.REQUESTED);
msg = "jdk" + release + "u-critical-request is set";
status = BackportStatus.REJECTED;
} else if (issue.getLabels().contains("jdk" + release + "u-fix-request")) {
actions.update(Actionable.REQUESTED);
msg = "jdk" + release + "u-fix-request is set";
status = BackportStatus.REQUESTED;
} else if (release > highRel) {
status = BackportStatus.INHERITED;
} else if (!affectedReleases.contains(release)) {
status = BackportStatus.NOT_AFFECTED;
} else if (daysAgo >= 0 && daysAgo < ISSUE_BAKE_TIME_DAYS) {
actions.update(Actionable.WAITING);
msg = (ISSUE_BAKE_TIME_DAYS - daysAgo) + " days more";
status = BackportStatus.BAKING;
} else if (oracleBackports.contains(release)) {
actions.update(Actionable.MISSING, importanceOracle(release));
status = BackportStatus.MISSING_ORACLE;
} else {
actions.update(Actionable.MISSING, importanceDefault(release));
status = BackportStatus.MISSING;
}
pendingPorts.put(release, status);
pendingPortsDetails.put(release, msg);
}
if (issue.getLabels().contains("gc-shenandoah")) {
String msg = "";
BackportStatus status;
if (!affectedShenandoah.contains(8)) {
status = BackportStatus.NOT_AFFECTED;
} else if (!hgDB.hasRepo("shenandoah/jdk8")) {
actions.update(Actionable.CRITICAL);
msg = "No Mercurial data available to judge";
status = BackportStatus.WARNING;
} else {
String nonBackport = tryPrintHg("shenandoah/jdk8", issue.getKey().replaceFirst("JDK-", ""));
if (nonBackport != null) {
msg = nonBackport;
status = BackportStatus.FIXED;
} else {
String backports = tryPrintHg("shenandoah/jdk8", issue.getKey().replaceFirst("JDK-", "[backport] "));
if (backports != null) {
msg = backports;
status = BackportStatus.FIXED;
} else if (daysAgo >= 0 && daysAgo < ISSUE_BAKE_TIME_DAYS) {
actions.update(Actionable.WAITING);
msg = (ISSUE_BAKE_TIME_DAYS - daysAgo) + " days more";
status = BackportStatus.BAKING;
} else {
actions.update(Actionable.MISSING, importanceMerge());
status = BackportStatus.MISSING;
}
}
}
shenandoahPorts.put(8, status);
shenandoahPortsDetails.put(8, msg);
}
relNotes = jiraIssues.getReleaseNotes(issue);
}
private String tryPrintHg(String repo, String synopsis) {
List<HgRecord> rs = hgDB.search(repo, synopsis);
if (rs.isEmpty()) {
return null;
}
StringBuilder sb = new StringBuilder();
for (HgRecord r : rs) {
sb.append(r.toString());
sb.append("\n");
}
return sb.toString();
}
private void recordOracleStatus(Set<Integer> results, Issue issue) {
String fixVersion = Accessors.getFixVersion(issue);
if (Versions.isOracle(fixVersion)) {
results.add(Versions.parseMajor(fixVersion));
}
}
private void recordExistingStatus(Map<Integer, List<Issue>> results, Issue issue) {
String fixVersion = Accessors.getFixVersion(issue);
// Oracle-internal push? Ignore.
if (Versions.isOracle(fixVersion)) return;
// No push recorded? Ignore.
String pushURL = Accessors.getPushURL(issue);
if (pushURL.equals("N/A")) return;
int ver = Versions.parseMajor(fixVersion);
List<Issue> list = results.computeIfAbsent(ver, k -> new ArrayList<>());
list.add(issue);
}
public Issue issue() {
return issue;
}
public String issueKey() {
return issue.getKey();
}
public String components() {
return components;
}
public int priority() {
return priority;
}
public long daysAgo() {
return daysAgo;
}
public Collection<Issue> releaseNotes() {
return relNotes;
}
public int fixVersion() {
return fixVersion;
}
public Actions actions() {
return actions;
}
public SortedMap<Integer, List<Issue>> existingPorts() {
return existingPorts;
}
public SortedMap<Integer, BackportStatus> pendingPorts() {
return pendingPorts;
}
public SortedMap<Integer, String> pendingPortsDetails() {
return pendingPortsDetails;
}
public SortedMap<Integer, BackportStatus> shenandoahPorts() {
return shenandoahPorts;
}
public SortedMap<Integer, String> shenandoahPortsDetails() {
return shenandoahPortsDetails;
}
public List<String> warnings() {
return warnings;
}
}
| 11,692 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
PushesModel.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/model/PushesModel.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.model;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.google.common.collect.*;
import org.openjdk.backports.jira.Accessors;
import org.openjdk.backports.jira.Clients;
import org.openjdk.backports.jira.IssuePromise;
import org.openjdk.backports.jira.UserCache;
import java.io.PrintStream;
import java.util.*;
public class PushesModel extends AbstractModel {
private final boolean directOnly;
private final String release;
private final List<Issue> issues;
private final Map<Issue, Issue> issueToParent;
private final Multiset<String> byPriority;
private final Multiset<String> byComponent;
private final Multimap<String, Issue> byOriginalCommitter;
private final Multimap<String, Issue> byCommitter;
private final Set<Issue> byTime;
private final SortedSet<Issue> noChangesets;
public PushesModel(Clients clients, PrintStream debugOut, boolean directOnly, String release) {
super(clients, debugOut);
this.directOnly = directOnly;
this.release = release;
this.issues = jiraIssues.getIssues("project = JDK" +
" AND (status in (Closed, Resolved))" +
" AND (resolution not in (\"Won't Fix\", Duplicate, \"Cannot Reproduce\", \"Not an Issue\", Withdrawn, Other))" +
(directOnly ? " AND type != Backport" : "") +
" AND (issuetype != CSR)" +
" AND fixVersion = " + release,
false);
Comparator<Issue> chronologicalCompare = Comparator.comparing(Accessors::getPushSecondsAgo).thenComparing(Comparator.comparing(Issue::getKey).reversed());
issueToParent = new HashMap<>();
byPriority = TreeMultiset.create();
byComponent = HashMultiset.create();
byCommitter = TreeMultimap.create(String::compareTo, DEFAULT_ISSUE_SORT);
byOriginalCommitter = TreeMultimap.create(String::compareTo, DEFAULT_ISSUE_SORT);
byTime = new TreeSet<>(chronologicalCompare);
noChangesets = new TreeSet<>(chronologicalCompare);
List<Issue> parentIssues = jiraIssues.getParentIssues(issues);
for (int i = 0; i < issues.size(); i++) {
Issue issue = issues.get(i);
String committer = Accessors.getPushUser(issue);
if (committer.equals("N/A")) {
// These are pushes to internal repos
noChangesets.add(issue);
} else {
byPriority.add(issue.getPriority().getName());
byComponent.add(Accessors.extractComponents(issue));
byCommitter.put(committer, issue);
Issue parent = parentIssues.get(i);
issueToParent.put(issue, parent);
byOriginalCommitter.put(Accessors.getPushUser(parent), issue);
byTime.add(issue);
}
}
debugOut.println("Filtered " + noChangesets.size() + " issues without pushes:");
for (Issue i : noChangesets) {
debugOut.printf(" %s: %s%n", i.getKey(), i.getSummary());
}
debugOut.println(byPriority.size() + " pushes left.");
}
public String release() {
return release;
}
public boolean directOnly() {
return directOnly;
}
public UserCache users() {
return users;
}
public List<Issue> issues() {
return issues;
}
public Multiset<String> byPriority() {
return byPriority;
}
public Multiset<String> byComponent() {
return byComponent;
}
public Multimap<String, Issue> byCommitter() {
return byCommitter;
}
public Multimap<String, Issue> byOriginalCommitter() {
return byOriginalCommitter;
}
public Map<Issue, Issue> issueToParent() {
return issueToParent;
}
public Set<Issue> byTime() {
return byTime;
}
public SortedSet<Issue> noChangesets() {
return noChangesets;
}
}
| 5,234 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
ParityModel.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/model/ParityModel.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.model;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.IssueField;
import com.atlassian.jira.rest.client.api.domain.Project;
import com.atlassian.jira.rest.client.api.domain.Version;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.openjdk.backports.jira.*;
import java.io.PrintStream;
import java.time.LocalDateTime;
import java.util.*;
public class ParityModel extends AbstractModel {
private final int majorVer;
private final SortedMap<Issue, SingleVers> exactOpenFirst;
private final SortedMap<Issue, SingleVers> exactOracleFirst;
private final SortedMap<Issue, DoubleVers> exactUnknown;
private final SortedMap<Issue, DoubleVers> lateOpenFirst;
private final SortedMap<Issue, DoubleVers> lateOracleFirst;
private final Map<String, Map<Issue, SingleVers>> onlyOpen;
private final Map<String, Map<Issue, SingleVers>> openRejected;
private final Map<String, Map<Issue, SingleVersMetadata>> onlyOracle;
private int versLen;
public ParityModel(Clients clients, PrintStream debugOut, int majorVer) {
super(clients, debugOut);
this.majorVer = majorVer;
Multimap<Issue, Issue> mp = HashMultimap.create();
List<String> vers = new ArrayList<>();
Project proj = jiraCli.getProjectClient().getProject("JDK").claim();
for (Version ver : proj.getVersions()) {
String v = ver.getName();
if (Versions.parseMajor(v) != majorVer) continue;
if (Versions.isShared(v)) continue;
vers.add(v);
}
debugOut.println("Auto-detected versions:");
for (String ver : vers) {
debugOut.println(" " + ver);
versLen = Math.max(versLen, ver.length());
}
debugOut.println();
for (String ver : vers) {
Multimap<Issue, Issue> pb = jiraIssues.getIssuesWithBackportsOnly("project = JDK" +
" AND (status in (Closed, Resolved))" +
" AND (labels not in (release-note) OR labels is EMPTY)" +
" AND (issuetype != CSR)" +
" AND (resolution not in (\"Won't Fix\", Duplicate, \"Cannot Reproduce\", \"Not an Issue\", Withdrawn, Other))" +
" AND fixVersion = " + ver);
for (Issue parent : pb.keySet()) {
if (majorVer == 8 && Accessors.extractComponents(parent).startsWith("javafx")) {
// JavaFX is not the part of OpenJDK 8, no parity.
continue;
}
if (mp.containsKey(parent)) {
// Already parsed, skip
continue;
}
for (Issue backport : pb.get(parent)) {
if (Accessors.isDelivered(backport)) {
mp.put(parent, backport);
}
}
}
}
debugOut.println("Discovered " + mp.size() + " issues.");
onlyOpen = new TreeMap<>(Versions::compare);
openRejected = new TreeMap<>(Versions::compare);
onlyOracle = new TreeMap<>(Versions::compare);
exactOpenFirst = new TreeMap<>(DEFAULT_ISSUE_SORT);
exactOracleFirst = new TreeMap<>(DEFAULT_ISSUE_SORT);
exactUnknown = new TreeMap<>(DEFAULT_ISSUE_SORT);
lateOpenFirst = new TreeMap<>(DEFAULT_ISSUE_SORT);
lateOracleFirst = new TreeMap<>(DEFAULT_ISSUE_SORT);
for (Issue p : mp.keySet()) {
boolean isShared = false;
String firstOracle = null;
String firstOracleRaw = null;
String firstOpen = null;
String firstOpenRaw = null;
LocalDateTime timeOracle = null;
LocalDateTime timeOpen = null;
// Awkward hack: parent needs to be counted for parity, on the off-chance
// it has the fix-version after the open/closed split.
List<Issue> issues = new ArrayList<>();
issues.addAll(mp.get(p)); // all sub-issues
issues.add(p); // and the issue itself
for (Issue subIssue : issues) {
IssueField rdf = subIssue.getField("resolutiondate");
LocalDateTime rd = null;
if (rdf != null && rdf.getValue() != null) {
String rds = rdf.getValue().toString();
rd = LocalDateTime.parse(rds.substring(0, rds.indexOf(".")));
}
for (String fv : Accessors.getFixVersions(subIssue)) {
if (Versions.parseMajor(fv) != majorVer) {
// Not the release we are looking for
continue;
}
if (Versions.isShared(fv)) {
isShared = true;
}
String sub = Versions.stripVendor(fv);
if (Versions.isOracle(fv)) {
if (firstOracle == null) {
firstOracle = sub;
firstOracleRaw = fv;
timeOracle = rd;
} else {
if (Versions.compare(sub, firstOracle) < 0) {
firstOracle = sub;
firstOracleRaw = fv;
timeOracle = rd;
}
}
} else {
if (firstOpen == null) {
firstOpen = sub;
firstOpenRaw = fv;
timeOpen = rd;
} else {
if (Versions.compare(sub, firstOpen) < 0) {
firstOpen = sub;
firstOpenRaw = fv;
timeOpen = rd;
}
}
}
}
}
if (isShared) {
continue;
}
if (Accessors.isOracleSpecific(p) ||
Accessors.isOpenJDKWontFix(p, majorVer) ||
Accessors.ifUpdateReleaseNo(p, majorVer) ||
Accessors.ifUpdateReleaseNA(p, majorVer)) {
Map<Issue, SingleVers> map = openRejected.computeIfAbsent(firstOracle, k -> new TreeMap<>(DEFAULT_ISSUE_SORT));
map.put(p, new SingleVers(firstOracle));
continue;
}
if (firstOracle == null && firstOpen != null) {
Map<Issue, SingleVers> map = onlyOpen.computeIfAbsent(firstOpen, k -> new TreeMap<>(DEFAULT_ISSUE_SORT));
map.put(p, new SingleVers(firstOpenRaw));
}
if (firstOracle != null && firstOpen == null) {
Map<Issue, SingleVersMetadata> map = onlyOracle.computeIfAbsent(firstOracle, k -> new TreeMap<>(DEFAULT_ISSUE_SORT));
boolean backportRequested = p.getLabels().contains("jdk" + majorVer + "u-fix-request");
String interestTags = InterestTags.shortTags(p.getLabels());
Collection<String> reviewLinks = Accessors.getReviewURLs(rawRest, p, majorVer);
map.put(p, new SingleVersMetadata(firstOracleRaw, interestTags, backportRequested, reviewLinks));
}
if (firstOracle != null && firstOpen != null && Versions.compare(firstOracleRaw, firstOpen) == 0) {
if (timeOpen == null || timeOracle == null) {
exactUnknown.put(p, new DoubleVers(firstOpenRaw, firstOracleRaw));
} else if (timeOpen.compareTo(timeOracle) < 0) {
exactOpenFirst.put(p, new SingleVers(firstOpenRaw));
} else {
exactOracleFirst.put(p, new SingleVers(firstOracleRaw));
}
}
if (firstOracle != null && firstOpen != null && Versions.compare(firstOpen, firstOracle) < 0) {
lateOpenFirst.put(p, new DoubleVers(firstOpenRaw, firstOracleRaw));
}
if (firstOracle != null && firstOpen != null && Versions.compare(firstOpen, firstOracle) > 0) {
lateOracleFirst.put(p, new DoubleVers(firstOracleRaw, firstOpenRaw));
}
}
}
public int majorVer() {
return majorVer;
}
public Map<String, Map<Issue, SingleVers>> onlyOpen() {
return onlyOpen;
}
public Map<String, Map<Issue, SingleVersMetadata>> onlyOracle() {
return onlyOracle;
}
public SortedMap<Issue, SingleVers> exactOpenFirst() {
return exactOpenFirst;
}
public SortedMap<Issue, SingleVers> exactOracleFirst() {
return exactOracleFirst;
}
public Map<String, Map<Issue, SingleVers>> openRejected() {
return openRejected;
}
public SortedMap<Issue, DoubleVers> exactUnknown() {
return exactUnknown;
}
public SortedMap<Issue, DoubleVers> lateOpenFirst() {
return lateOpenFirst;
}
public SortedMap<Issue, DoubleVers> lateOracleFirst() {
return lateOracleFirst;
}
public int getVersLen() {
return versLen;
}
public static class SingleVers {
private final String ver;
public SingleVers(String ver) {
this.ver = ver;
}
public String version() {
return ver;
}
}
public static class SingleVersMetadata {
private final String ver;
private final String interestTags;
private final boolean backportRequested;
private final Collection<String> reviewLinks;
public SingleVersMetadata(String ver, String interestTags, boolean backportRequested, Collection<String> reviewLinks) {
this.ver = ver;
this.interestTags = interestTags;
this.backportRequested = backportRequested;
this.reviewLinks = reviewLinks;
}
public String version() {
return ver;
}
public String interestTags() {
return interestTags;
}
public boolean backportRequested() {
return backportRequested;
}
public Collection<String> reviewLinks() {
return reviewLinks;
}
}
public static class DoubleVers {
private final String v1, v2;
public DoubleVers(String v1, String v2) {
this.v1 = v1;
this.v2 = v2;
}
public String version1() {
return v1;
}
public String version2() {
return v2;
}
}
}
| 12,029 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
LabelHistoryModel.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/model/LabelHistoryModel.java | /*
* Copyright (c) 2020, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.model;
import com.atlassian.jira.rest.client.api.domain.ChangelogGroup;
import com.atlassian.jira.rest.client.api.domain.ChangelogItem;
import com.atlassian.jira.rest.client.api.domain.Issue;
import org.joda.time.DateTime;
import org.openjdk.backports.jira.Clients;
import org.openjdk.backports.jira.UserCache;
import java.io.PrintStream;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
public class LabelHistoryModel extends AbstractModel {
private final String label;
private final SortedSet<Record> set;
public LabelHistoryModel(Clients clients, PrintStream debugOut, String label) {
super(clients, debugOut);
this.label = label;
List<Issue> found = jiraIssues.getIssues("labels = " + label +
" AND type != Backport", true);
set = new TreeSet<>();
for (Issue i : found) {
Record rd = findUpdate(i);
if (rd != null) {
set.add(rd);
}
}
}
private Record findUpdate(Issue i) {
// Look in the changelog first:
Iterable<ChangelogGroup> cl = i.getChangelog();
if (cl != null) {
for (ChangelogGroup cg : cl) {
for (ChangelogItem item : cg.getItems()) {
if (!item.getField().equals("labels")) continue;
boolean noFrom = item.getFromString() == null || !item.getFromString().contains(label);
boolean yesTo = item.getToString() != null && item.getToString().contains(label);
if (noFrom && yesTo) {
return new Record(users.getDisplayName(cg.getAuthor().getName()), cg.getCreated(), i);
}
}
}
}
// No hits in changelog? Maybe it was filed with the label right away:
if (i.getLabels().contains(label)) {
return new Record(users.getDisplayName(i.getReporter().getName()), i.getCreationDate(), i);
}
return null;
}
public String label() {
return label;
}
public SortedSet<Record> records() {
return set;
}
public UserCache users() {
return users;
}
public static class Record implements Comparable<Record> {
public final String user;
public final DateTime date;
public final Issue issue;
private Record(String user, DateTime date, Issue issue) {
this.user = user;
this.date = date;
this.issue = issue;
}
@Override
public int compareTo(Record o) {
int c1 = o.date.compareTo(date);
if (c1 != 0) {
return c1;
}
return issue.getKey().compareTo(o.issue.getKey());
}
}
}
| 4,042 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
AffiliationModel.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/model/AffiliationModel.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.model;
import org.openjdk.backports.jira.Clients;
import org.openjdk.backports.jira.UserCache;
import java.io.PrintStream;
import java.util.List;
public class AffiliationModel extends AbstractModel {
private final List<String> userIds;
public AffiliationModel(Clients clients, PrintStream debugOut) {
super(clients, debugOut);
userIds = users.resolveCensus();
debugOut.print("Got " + userIds.size() + " users, resolving");
int cnt = 0;
for (String uid : userIds) {
if (cnt++ % 50 == 0) debugOut.print(".");
users.getDisplayName(uid);
users.getAffiliation(uid);
}
debugOut.println();
debugOut.println("Resolved " + userIds.size() + " users.");
}
public List<String> userIds() {
return userIds;
}
public UserCache users() {
return users;
}
}
| 2,122 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
AbstractModel.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/model/AbstractModel.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.model;
import com.atlassian.jira.rest.client.api.IssueRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.SearchRestClient;
import org.openjdk.backports.jira.Clients;
import org.openjdk.backports.jira.Issues;
import org.openjdk.backports.jira.RawRestClient;
import org.openjdk.backports.jira.UserCache;
import org.openjdk.backports.report.Common;
import java.io.PrintStream;
abstract class AbstractModel extends Common {
protected final SearchRestClient searchCli;
protected final IssueRestClient issueCli;
protected final PrintStream debugOut;
protected final Issues jiraIssues;
protected final UserCache users;
protected final RawRestClient rawRest;
protected final JiraRestClient jiraCli;
public AbstractModel(Clients clients, PrintStream debugOut) {
this.jiraCli = clients.getJiraRest();
this.rawRest = clients.getRawRest();
this.searchCli = jiraCli.getSearchClient();
this.issueCli = jiraCli.getIssueClient();
this.debugOut = debugOut;
this.jiraIssues = new Issues(debugOut, searchCli, issueCli);
this.users = new UserCache(jiraCli.getUserClient());
}
}
| 2,444 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
LabelModel.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/model/LabelModel.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.model;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.google.common.collect.*;
import org.openjdk.backports.Actionable;
import org.openjdk.backports.hg.HgDB;
import org.openjdk.backports.jira.Clients;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class LabelModel extends AbstractModel {
private final String label;
private final Actionable minLevel;
private final List<IssueModel> models;
private final LinkedListMultimap<String, IssueModel> byComponent;
private final Integer maxVersion;
private final Integer minVersion;
public LabelModel(Clients cli, HgDB hgDB, PrintStream debugOut, Actionable minLevel, String label) {
super(cli, debugOut);
this.label = label;
this.minLevel = minLevel;
List<Issue> found = jiraIssues.getIssues("labels = " + label +
" AND (status in (Closed, Resolved))" +
" AND (resolution not in (\"Won't Fix\", Duplicate, \"Cannot Reproduce\", \"Not an Issue\", Withdrawn, Other))" +
" AND type != Backport",
false);
Comparator<IssueModel> comparator = Comparator
.comparing(IssueModel::actions)
.thenComparing(IssueModel::components)
.thenComparing(IssueModel::priority)
.thenComparing(Comparator.comparing(IssueModel::daysAgo).reversed())
.thenComparing(IssueModel::issueKey);
models = found.parallelStream()
.map(i -> new IssueModel(cli, hgDB, debugOut, i))
.filter(im -> im.actions().getActionable().ordinal() >= minLevel.ordinal())
.sorted(comparator)
.collect(Collectors.toList());
byComponent = LinkedListMultimap.create();
for (IssueModel m : models) {
byComponent.put(m.components(), m);
}
maxVersion = models.stream()
.map(IssueModel::fixVersion)
.filter(i -> i > 0)
.reduce(Arrays.stream(VERSIONS_TO_CARE_FOR).reduce(Integer.MIN_VALUE, Math::max), Math::max);
minVersion = models.stream()
.map(IssueModel::fixVersion)
.filter(i -> i > 0)
.reduce(Arrays.stream(VERSIONS_TO_CARE_FOR).reduce(Integer.MAX_VALUE, Math::min), Math::min);
}
public List<IssueModel> issues() {
return models;
}
public LinkedListMultimap<String, IssueModel> byComponent() {
return byComponent;
}
public String label() {
return label;
}
public Actionable minLevel() {
return minLevel;
}
public int maxVersion() {
return maxVersion;
}
public int minVersion() {
return minVersion;
}
}
| 4,114 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Census.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/census/Census.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.census;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Census {
public static List<String> userIds() {
try {
Document doc = Jsoup.connect("http://openjdk.org/census").get();
for (Element row : doc.body().select("div#main > table > tbody > tr")) {
if (row.toString().contains("People")) {
Element td = row.select("td").last();
List<String> result = new ArrayList<>();
for (Element links : td.select("a")) {
result.add(links.text());
}
return result;
}
}
} catch (IOException e) {
System.out.println("ERROR: Cannot read Census");
e.printStackTrace();
}
return Collections.emptyList();
}
}
| 2,234 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Accessors.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/Accessors.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import com.atlassian.jira.rest.client.api.IssueRestClient;
import com.atlassian.jira.rest.client.api.domain.*;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import java.util.*;
public class Accessors {
public static String getFixVersion(Issue issue) {
Iterator<Version> it = issue.getFixVersions().iterator();
if (!it.hasNext()) {
return "N/A";
}
Version fixVersion = it.next();
if (it.hasNext()) {
// TODO: Deal with this properly. See for example JDK-8259847.
return "ERROR";
}
return fixVersion.getName();
}
public static List<String> getFixVersions(Issue issue) {
List<String> res = new ArrayList<>();
for (Version ver : issue.getFixVersions()) {
res.add(ver.getName());
}
return res;
}
private static boolean isBotPushComment(Comment c) {
String name = c.getAuthor().getName();
if (!name.equals("hgupdate") &&
!name.equals("roboduke") &&
!name.equals("dukebot")) {
return false;
}
if (c.getBody().contains("A pull request was submitted for review.")) {
return false;
}
return true;
}
public static String getPushURL(Issue issue) {
for (Comment c : issue.getComments()) {
if (isBotPushComment(c)) {
Optional<String> opt = Parsers.parseURL(c.getBody());
if (opt.isPresent()) {
return opt.get();
}
}
}
String fixVersion = getFixVersion(issue);
if (Versions.parseMajor(fixVersion) >= 11 &&
Versions.parseMinor(fixVersion) == 1) {
// Oh yeah, issues would have these versions set as "fix", but there would
// be no public pushes until CPU releases. Awesome.
return "(The push URL is not available until CPU is released)";
}
return "N/A";
}
public static String getPushUser(Issue issue) {
for (Comment c : issue.getComments()) {
if (isBotPushComment(c)) {
Optional<String> opt = Parsers.parseUser(c.getBody());
if (opt.isPresent()) {
return opt.get();
}
}
}
return "N/A";
}
public static long getPushDaysAgo(Issue issue) {
for (Comment c : issue.getComments()) {
if (isBotPushComment(c)) {
Optional<Long> opt = Parsers.parseDaysAgo(c.getBody());
if (opt.isPresent()) {
return opt.get();
}
}
}
return -1;
}
public static long getPushSecondsAgo(Issue issue) {
for (Comment c : issue.getComments()) {
if (isBotPushComment(c)) {
Optional<Long> opt = Parsers.parseSecondsAgo(c.getBody());
if (opt.isPresent()) {
return opt.get();
}
}
}
return -1;
}
public static int getPriority(Issue issue) {
if (issue.getPriority() != null) {
return Parsers.parsePriority(issue.getPriority().getName());
}
return -1;
}
public static String extractComponents(Issue issue) {
StringJoiner joiner = new StringJoiner("/");
for (BasicComponent c : issue.getComponents()) {
joiner.add(c.getName());
}
IssueField subcomponent = issue.getFieldByName("Subcomponent");
if (subcomponent != null && subcomponent.getValue() != null) {
try {
JSONObject o = new JSONObject(subcomponent.getValue().toString());
joiner.add(o.get("name").toString());
} catch (JSONException e) {
// Do nothing
}
}
return joiner.toString();
}
private static String getStatus(Issue issue) {
Status s = issue.getStatus();
if (s == null) {
return "";
}
String n = s.getName();
if (n == null) {
return "";
}
return n;
}
private static String getResolution(Issue issue) {
Resolution r = issue.getResolution();
if (r == null) {
return "";
}
String n = r.getName();
if (n == null) {
return "";
}
return n;
}
public static boolean isDelivered(Issue issue) {
switch (getStatus(issue)) {
case "Closed":
case "Resolved":
break;
case "Withdrawn":
return false;
default:
// Default to "not delivered"
return false;
}
switch (getResolution(issue)) {
case "Withdrawn":
case "Won't Fix":
case "Duplicate":
case "Cannot Reproduce":
case "Not an Issue":
return false;
case "Resolved":
case "Fixed":
case "Other":
return true;
default:
// Default to "delivered"
return true;
}
}
public static boolean isOracleSpecific(Issue issue) {
return issue.getLabels().contains("openjdk-na");
}
public static boolean isOpenJDKWontFix(Issue issue, int majorVer) {
return issue.getLabels().contains("openjdk" + majorVer + "u-WNF");
}
public static boolean ifUpdateReleaseNo(Issue issue, int majorVer) {
return issue.getLabels().contains("jdk" + majorVer + "u-fix-no");
}
public static boolean ifUpdateReleaseNA(Issue issue, int majorVer) {
return issue.getLabels().contains("jdk" + majorVer + "u-na");
}
public static boolean isReleaseNoteTag(Issue issue) {
return issue.getLabels().contains("release-note");
}
public static boolean isReleaseNote(Issue issue) {
// Brilliant, we cannot trust "release-note" tags?
// See: https://mail.openjdk.org/pipermail/jdk-dev/2019-July/003083.html
return (isReleaseNoteTag(issue) || issue.getSummary().toLowerCase().trim().startsWith("release note"))
&& isDelivered(issue);
}
public static Collection<String> getReviewURLs(RawRestClient raw, Issue issue, int majorVer) {
Collection<String> res = new ArrayList<>();
for (String link : raw.remoteLinks(issue.getKey())) {
if (link.contains("jdk" + majorVer + "/pull/") ||
link.contains("jdk" + majorVer + "u/pull/") ||
link.contains("jdk" + majorVer + "u-dev/pull/")) {
res.add(link);
}
}
return res;
}
}
| 8,076 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Clients.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/Clients.java | /*
* Copyright (c) 2021, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import com.atlassian.jira.rest.client.api.JiraRestClient;
public class Clients implements AutoCloseable {
private final JiraRestClient jiraRest;
private final RawRestClient rawRest;
public Clients(JiraRestClient jiraRest, RawRestClient rawRest) {
this.jiraRest = jiraRest;
this.rawRest = rawRest;
}
public JiraRestClient getJiraRest() {
return jiraRest;
}
public RawRestClient getRawRest() {
return rawRest;
}
@Override
public void close() throws Exception {
jiraRest.close();
}
}
| 1,798 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
RetryableIssuePromise.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/RetryableIssuePromise.java | /*
* Copyright (c) 2018, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import com.atlassian.jira.rest.client.api.IssueRestClient;
import com.atlassian.jira.rest.client.api.domain.Issue;
import io.atlassian.util.concurrent.Promise;
import java.util.Collections;
public class RetryableIssuePromise extends RetryablePromise<Issue> implements IssuePromise {
private final Issues issues;
private final IssueRestClient cli;
private final String key;
private final boolean full;
public RetryableIssuePromise(Issues issues, IssueRestClient cli, String key, boolean full) {
this.issues = issues;
this.cli = cli;
this.key = key;
this.full = full;
init();
}
protected Promise<Issue> get() {
if (full) {
return cli.getIssue(key, Collections.singleton(IssueRestClient.Expandos.CHANGELOG));
} else {
return cli.getIssue(key);
}
}
public Issue claim() {
Issue issue = super.claim();
if (issue != null && issues != null) {
issues.registerIssueCache(key, issue);
}
return issue;
}
}
| 2,301 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
RetryableSearchPromise.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/RetryableSearchPromise.java | /*
* Copyright (c) 2018, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import com.atlassian.jira.rest.client.api.SearchRestClient;
import com.atlassian.jira.rest.client.api.domain.SearchResult;
import io.atlassian.util.concurrent.Promise;
public class RetryableSearchPromise extends RetryablePromise<SearchResult> {
private final SearchRestClient searchCli;
private final String query;
private final int pageSize;
private final int cnt;
public RetryableSearchPromise(SearchRestClient searchCli, String query, int pageSize, int cnt) {
this.searchCli = searchCli;
this.query = query;
this.pageSize = pageSize;
this.cnt = cnt;
init();
}
@Override
protected Promise<SearchResult> get() {
return searchCli.searchJql(query, pageSize, cnt, null);
}
}
| 1,990 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
RetryableUserPromise.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/RetryableUserPromise.java | /*
* Copyright (c) 2018, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import com.atlassian.jira.rest.client.api.UserRestClient;
import com.atlassian.jira.rest.client.api.domain.User;
import io.atlassian.util.concurrent.Promise;
public class RetryableUserPromise extends RetryablePromise<User> {
private final UserRestClient userCli;
private final String user;
public RetryableUserPromise(UserRestClient userCli, String user) {
this.userCli = userCli;
this.user = user;
init();
}
@Override
protected Promise<User> get() {
return userCli.getUser(user);
}
}
| 1,778 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
InterestTags.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/InterestTags.java | /*
* Copyright (c) 2020, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class InterestTags {
public static String shortTags(Collection<String> labels) {
List<String> tags = new ArrayList<>();
for (String label : labels) {
String tag = shortTagFor(label);
if (!tag.isEmpty()) {
tags.add(tag);
}
}
if (tags.isEmpty()) return "";
Collections.sort(tags);
StringBuilder sb = new StringBuilder();
for (String tag : tags) {
sb.append(tag);
}
return sb.toString();
}
private static String shortTagFor(String label) {
switch (label) {
case "redhat-interest":
return "R";
case "sap-interest":
return "S";
case "amazon-interest":
return "A";
case "google-interest":
return "G";
case "azul-interest":
return "a";
case "tencent-interest":
return "t";
case "jdk11u-jvmci-defer":
return "C";
default:
if (label.endsWith("-interest")) {
return "?";
} else {
return "";
}
}
}
}
| 2,604 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Versions.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/Versions.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
public class Versions {
public static int parseMajor(String version) {
if (version.equals("solaris_10u7")) {
// Special-case odd issue: https://bugs.openjdk.org/browse/JDK-6913047
return 0;
}
if (version.startsWith("hs")) {
// Special case odd issues that reference Hotspot versions:
// https://bugs.openjdk.org/browse/JDK-8035493
return 0;
}
if (version.startsWith("emb-")) {
// Special case odd issues that reference embedded versions:
// https://bugs.openjdk.org/browse/JDK-8042557
return 0;
}
if (version.equals("8-aarch64")) {
// Special case odd issues that reference old pre-integration 8-aarch64 versions:
// https://bugs.openjdk.org/browse/JDK-8236179
return 0;
}
version = version.toLowerCase();
if (version.startsWith("openjdk")) {
version = version.substring("openjdk".length());
}
if (version.endsWith("shenandoah")) {
return -1;
}
if (version.endsWith("-pool")) {
int dashIdx = version.lastIndexOf("-");
try {
return Integer.parseInt(version.substring(0, dashIdx));
} catch (Exception e) {
return -1;
}
}
int dotIdx = version.indexOf(".");
if (dotIdx != -1) {
try {
return Integer.parseInt(version.substring(0, dotIdx));
} catch (Exception e) {
return -1;
}
}
int uIdx = version.indexOf("u");
if (uIdx != -1) {
try {
return Integer.parseInt(version.substring(0, uIdx));
} catch (Exception e) {
return -1;
}
}
try {
return Integer.parseInt(version);
} catch (Exception e) {
return -1;
}
}
public static int parseMinor(String version) {
if (version.startsWith("openjdk7")) {
return -1;
}
if (parseMajor(version) <= 8) {
int uIdx = version.indexOf("u");
if (uIdx != -1) {
if (uIdx + 1 == version.length()) {
return 0;
}
try {
return Integer.parseInt(version.substring(uIdx + 1));
} catch (Exception e) {
return -1;
}
}
}
if (parseMajor(version) >= 11) {
String sub = stripVendor(version);
int dotIdx = sub.lastIndexOf(".");
if (dotIdx + 1 == version.length()) {
return 0;
}
if (dotIdx != -1) {
String[] args = sub.split("\\.");
if (args.length < 3) {
return -1;
}
try {
return Integer.parseInt(args[2]);
} catch (Exception e) {
return -1;
}
}
}
return -1;
}
public static int parseMajorShenandoah(String version) {
if (!version.endsWith("-shenandoah")) {
return -1;
}
version = version.substring(0, version.indexOf("shenandoah") - 1);
try {
return Integer.parseInt(version);
} catch (Exception e) {
return -1;
}
}
public static boolean isOracle(String version) {
if (parseMajor(version) >= 11 && version.endsWith("-oracle")) {
return true;
}
if (parseMajor(version) == 8 && parseMinor(version) >= 211 && !version.startsWith("openjdk")) {
return true;
}
return false;
}
public static boolean isMaintenanceRelease(String version) {
// These are 8u MR releases:
// MR1-MR2: 8u40 (technically the part of usual JDK 8 release chain, so excluded here)
// MR3: 8u41
// MR4: 8u42
int minor = parseMinor(version);
if (parseMajor(version) == 8 &&
41 <= minor && minor <= 42) {
return true;
}
return false;
}
public static boolean isOpen(String version) {
return !isOracle(version) && !isMaintenanceRelease(version);
}
public static boolean isShared(String version) {
if (isOracle(version)) {
return false;
}
if (parseMajor(version) >= 11 && parseMinor(version) <= 2) {
return true;
}
if (parseMajor(version) == 8 && parseMinor(version) < 211) {
return true;
}
return false;
}
public static String stripVendor(String version) {
if (version.endsWith("-oracle")) {
return version.substring(0, version.indexOf("-oracle"));
}
if (version.startsWith("openjdk")) {
return version.substring(7);
}
return version;
}
public static int compare(String left, String right) {
String stripLeft = stripVendor(left);
String stripRight = stripVendor(right);
int major = Integer.compare(parseMajor(stripLeft), parseMajor(stripRight));
if (major != 0) {
return major;
}
int minor = Integer.compare(parseMinor(stripLeft), parseMinor(stripRight));
if (minor != 0) {
if (parseMajor(stripLeft) == 8 && parseMajor(stripRight) == 8) {
// Special case: adjacent 8u releases
if (Math.abs(parseMinor(stripLeft) - parseMinor(stripRight)) > 1) {
return minor;
}
} else {
return minor;
}
}
return 0;
}
}
| 7,100 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Connect.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/Connect.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.httpclient.apache.httpcomponents.DefaultHttpClientFactory;
import com.atlassian.httpclient.api.HttpClient;
import com.atlassian.httpclient.api.factory.HttpClientOptions;
import com.atlassian.jira.rest.client.api.AuthenticationHandler;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.auth.AnonymousAuthenticationHandler;
import com.atlassian.jira.rest.client.auth.BasicHttpAuthenticationHandler;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClient;
import com.atlassian.jira.rest.client.internal.async.AtlassianHttpClientDecorator;
import com.atlassian.jira.rest.client.internal.async.DisposableHttpClient;
import com.atlassian.sal.api.ApplicationProperties;
import com.atlassian.sal.api.UrlMode;
import com.atlassian.sal.api.executor.ThreadLocalContextManager;
import org.openjdk.backports.Auth;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.util.Date;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Connect {
public static Clients getClients(String jiraURL, Auth auth, int maxConnections) throws URISyntaxException {
final URI uri = new URI(jiraURL);
DefaultHttpClientFactory factory = new DefaultHttpClientFactory(
new MyEventPublisher(),
new MyApplicationProperties(uri),
new ThreadLocalContextManager() {
@Override public Object getThreadLocalContext() { return null; }
@Override public void setThreadLocalContext(Object context) {}
@Override public void clearThreadLocalContext() {}
});
HttpClientOptions opts = new HttpClientOptions();
// All this mess is needed to change timeouts:
opts.setRequestTimeout(2, TimeUnit.MINUTES);
opts.setSocketTimeout(2, TimeUnit.MINUTES);
opts.setLeaseTimeout(TimeUnit.MINUTES.toMillis(30));
// And configure the cache as well. 5K x 100K = 500M cache "should be enough".
opts.setMaxCacheEntries(5_000);
opts.setMaxCacheObjectSize(100_000);
// Make sure we do not overwhelm the target with too many concurrent
// requests. Limiting the number of connections should do the trick,
// assuming similar request rate per connection.
opts.setMaxTotalConnections(maxConnections);
// Make sure we have enough threads to process the requests.
// Choose the most scalable executor availabe.
opts.setCallbackExecutor(Executors.newWorkStealingPool());
HttpClient client = factory.create(opts);
AuthenticationHandler authHandler;
if (auth.isAnonymous()) {
authHandler = new AnonymousAuthenticationHandler();
} else {
authHandler = new BasicHttpAuthenticationHandler(auth.getUser(), auth.getPass());
}
DisposableHttpClient dispClient = new AtlassianHttpClientDecorator(client, authHandler) {
@Override public void destroy() throws Exception { factory.dispose(client); }
};
return new Clients(
new AsynchronousJiraRestClient(uri, dispClient),
new RawRestClient(uri, dispClient)
);
}
private static class MyEventPublisher implements EventPublisher {
@Override public void publish(Object o) {}
@Override public void register(Object o) {}
@Override public void unregister(Object o) {}
@Override public void unregisterAll() {}
}
private static class MyApplicationProperties implements ApplicationProperties {
private final String url;
private MyApplicationProperties(URI uri) {
this.url = uri.getPath();
}
@Override
public String getBaseUrl() {
return url;
}
@Override
public String getBaseUrl(UrlMode mode) {
return url;
}
@Override
public String getDisplayName() {
return "Atlassian JIRA Rest Java Client";
}
@Override
public String getPlatformId() {
return ApplicationProperties.PLATFORM_JIRA;
}
@Override
public String getVersion() {
return "4.0.0-custom";
}
@Override
public Date getBuildDate() {
throw new UnsupportedOperationException();
}
@Override
public String getBuildNumber() {
return String.valueOf(0);
}
@Override
public File getHomeDirectory() {
return new File(".");
}
@Override
public Optional<Path> getLocalHomeDirectory() {
return Optional.empty();
}
@Override
public Optional<Path> getSharedHomeDirectory() {
return Optional.empty();
}
@Override
public String getPropertyValue(final String s) {
throw new UnsupportedOperationException();
}
@Override
public String getApplicationFileEncoding() {
return null;
}
}
}
| 6,519 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
IssuePromise.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/IssuePromise.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import com.atlassian.jira.rest.client.api.domain.Issue;
public interface IssuePromise {
Issue claim();
}
| 1,340 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Issues.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/Issues.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import com.atlassian.jira.rest.client.api.IssueRestClient;
import com.atlassian.jira.rest.client.api.SearchRestClient;
import com.atlassian.jira.rest.client.api.domain.*;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.lang3.text.WordUtils;
import org.openjdk.backports.StringUtils;
import java.io.PrintStream;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class Issues {
private static final int PAGE_SIZE = 50;
private final PrintStream out;
private final SearchRestClient searchCli;
private final IssueRestClient issueCli;
private final ConcurrentMap<String, IssuePromise> issueCache;
public Issues(PrintStream out, SearchRestClient searchCli, IssueRestClient issueCli) {
this.out = out;
this.searchCli = searchCli;
this.issueCli = issueCli;
this.issueCache = new ConcurrentHashMap<>();
}
public IssuePromise getIssue(String key) {
return getIssue(key, false);
}
public IssuePromise getIssue(String key, boolean full) {
return issueCache.computeIfAbsent(key,
k -> new RetryableIssuePromise(this, issueCli, k, full));
}
void registerIssueCache(String key, Issue issue) {
issueCache.put(key, new ResolvedIssuePromise(issue));
}
/**
* Reply with basic issues for a given JIRA query.
* Basic issues have only a few populated fields, and are much faster to acquire.
*
* @param query query
* @return list of issues
*/
public List<Issue> getBasicIssues(String query) {
out.println("JIRA Query:");
out.println(WordUtils.wrap(query, StringUtils.DEFAULT_WIDTH));
out.println();
SearchResult poll = new RetryableSearchPromise(searchCli, query, 1, 0).claim();
int total = poll.getTotal();
out.print("Acquiring pages (" + total + " total): ");
List<RetryableSearchPromise> searchPromises = new ArrayList<>();
for (int cnt = 0; cnt < total; cnt += PAGE_SIZE) {
searchPromises.add(new RetryableSearchPromise(searchCli, query, PAGE_SIZE, cnt));
out.print(".");
out.flush();
}
out.println(" done");
out.print("Loading issues (" + total + " total): ");
List<Issue> issues = new ArrayList<>();
for (RetryableSearchPromise sp : searchPromises) {
for (Issue i : sp.claim().getIssues()) {
issues.add(i);
}
out.print(".");
out.flush();
}
out.println(" done");
return issues;
}
/**
* Reply with resolved issues for a given JIRA query.
* Resolved issues have all their fields filled in.
*
* @param query query
* @param full load all metadata
* @return list of issues
*/
public List<Issue> getIssues(String query, boolean full) {
List<Issue> basicIssues = getBasicIssues(query);
int total = basicIssues.size();
List<IssuePromise> batch = new ArrayList<>();
for (Issue i : basicIssues) {
batch.add(getIssue(i.getKey(), full));
}
int count = 0;
out.print("Resolving issues (" + total + " total): ");
List<Issue> issues = new ArrayList<>();
for (IssuePromise ip : batch) {
issues.add(ip.claim());
if ((++count % PAGE_SIZE) == 0) {
out.print(".");
out.flush();
}
}
out.println(" done");
return issues;
}
public IssuePromise getParent(Issue start) {
for (IssueLink link : start.getIssueLinks()) {
IssueLinkType type = link.getIssueLinkType();
if (type.getName().equals("Backport") && type.getDirection() == IssueLinkType.Direction.INBOUND) {
return getIssue(link.getTargetIssueKey());
}
}
return null;
}
/**
* Reply with parent issues for a given JIRA query.
* For every issue that has a parent, its parent is returned. If issue has no
* parents, the issue itself is replied.
*
* @param query query
* @return list issues
*/
public List<Issue> getParentIssues(String query) {
List<Issue> basicIssues = getBasicIssues(query);
int totalSize = basicIssues.size();
List<IssuePromise> basicPromises = new ArrayList<>();
for (Issue i : basicIssues) {
basicPromises.add(getIssue(i.getKey()));
}
int c1 = 0;
out.print("Resolving issues (" + totalSize + " total): ");
List<IssuePromise> parentPromises = new ArrayList<>();
for (IssuePromise ip : basicPromises) {
IssuePromise parent = getParent(ip.claim());
parentPromises.add(parent != null ? parent : ip);
if ((++c1 % PAGE_SIZE) == 0) {
out.print(".");
out.flush();
}
}
out.println(" done");
int c2 = 0;
out.print("Resolving parents (" + totalSize + " total): ");
List<Issue> issues = new ArrayList<>();
for (IssuePromise ip : parentPromises) {
issues.add(ip.claim());
if ((++c2 % PAGE_SIZE) == 0) {
out.print(".");
out.flush();
}
}
out.println(" done");
return issues;
}
private Multimap<Issue, Issue> getIssuesWithBackports(String query, boolean includeOnly) {
List<Issue> parents = getParentIssues(query);
int totalSize = parents.size();
Multimap<Issue, IssuePromise> promises = HashMultimap.create();
for (Issue parent : parents) {
if (parent.getIssueLinks() != null) {
for (IssueLink link : parent.getIssueLinks()) {
if (link.getIssueLinkType().getName().equals("Backport")) {
String linkKey = link.getTargetIssueKey();
promises.put(parent, getIssue(linkKey));
}
}
}
}
int c1 = 0;
out.print("Resolving backports (" + totalSize + " total): ");
Multimap<Issue, Issue> result = HashMultimap.create();
for (Issue parent : parents) {
for (IssuePromise ip : promises.get(parent)) {
result.put(parent, ip.claim());
}
if ((++c1 % PAGE_SIZE) == 0) {
out.print(".");
out.flush();
}
}
if (!includeOnly) {
// Make sure that key mapping exists even for issues without backports.
for (Issue parent : parents) {
result.put(parent, parent);
}
}
out.println(" done");
return result;
}
public Multimap<Issue, Issue> getIssuesWithBackportsOnly(String query) {
return getIssuesWithBackports(query, true);
}
public Multimap<Issue, Issue> getIssuesWithBackportsFull(String query) {
Multimap<Issue, Issue> res = getIssuesWithBackports(query, false);
// Resolve the related issues and subtasks
Multimap<Issue, IssuePromise> promises = HashMultimap.create();
for (Issue parent : res.keySet()) {
if (parent.getIssueLinks() != null) {
for (IssueLink link : parent.getIssueLinks()) {
promises.put(parent, getIssue(link.getTargetIssueKey()));
}
}
if (parent.getSubtasks() != null) {
for (Subtask subtask : parent.getSubtasks()) {
promises.put(parent, getIssue(subtask.getIssueKey()));
}
}
}
int c1 = 0;
out.print("Resolving related/subtasks (" + res.keySet().size() + " total): ");
Multimap<Issue, Issue> result = HashMultimap.create();
for (Issue parent : res.keySet()) {
for (IssuePromise ip : promises.get(parent)) {
result.put(parent, ip.claim());
}
if ((++c1 % PAGE_SIZE) == 0) {
out.print(".");
out.flush();
}
}
out.println(" done");
return res;
}
public Collection<Issue> getReleaseNotes(Issue start) {
List<IssuePromise> relnotes = new ArrayList<>();
Set<Issue> releaseNotes = new HashSet<>();
// Direct hit?
if (Accessors.isReleaseNote(start)) {
releaseNotes.add(start);
}
// Search in sub-tasks
for (Subtask link : start.getSubtasks()) {
relnotes.add(getIssue(link.getIssueKey()));
}
// Search in related issues
for (IssueLink link : start.getIssueLinks()) {
if (link.getIssueLinkType().getName().equals("Relates")) {
relnotes.add(getIssue(link.getTargetIssueKey()));
}
}
for (IssuePromise p : relnotes) {
Issue i = p.claim();
if (Accessors.isReleaseNote(i)) {
releaseNotes.add(i);
}
}
return releaseNotes;
}
public List<Issue> getParentIssues(List<Issue> basics) {
int c1 = 0;
out.print("Resolving issues (" + basics.size() + " total): ");
List<IssuePromise> parentPromises = new ArrayList<>();
for (Issue ip : basics) {
IssuePromise parent = getParent(ip);
parentPromises.add(parent);
if ((++c1 % PAGE_SIZE) == 0) {
out.print(".");
out.flush();
}
}
out.println(" done");
out.print("Resolving parents (" + basics.size() + " total): ");
List<Issue> issues = new ArrayList<>();
for (int i = 0; i < parentPromises.size(); i++) {
IssuePromise ip = parentPromises.get(i);
if (ip != null) {
issues.add(ip.claim());
} else {
issues.add(basics.get(i));
}
if ((i % PAGE_SIZE) == 0) {
out.print(".");
out.flush();
}
}
out.println(" done");
return issues;
}
}
| 11,548 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
UserCache.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/UserCache.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import com.atlassian.jira.rest.client.api.UserRestClient;
import com.atlassian.jira.rest.client.api.domain.User;
import io.atlassian.util.concurrent.Promise;
import org.openjdk.backports.census.Census;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserCache {
private final UserRestClient client;
private final Map<String, User> users;
private final Map<String, RetryableUserPromise> userPromises;
private final Map<String, String> displayNames;
private final Map<String, String> affiliations;
private List<String> censusIds;
public UserCache(UserRestClient client) {
this.client = client;
this.users = new HashMap<>();
this.userPromises = new HashMap<>();
this.displayNames = new HashMap<>();
this.affiliations = new HashMap<>();
}
public List<String> resolveCensus() {
if (censusIds == null) {
censusIds = Census.userIds();
// Start async resolve for all users
for (String uid : censusIds) {
userPromises.put(uid, new RetryableUserPromise(client, uid));
}
}
return censusIds;
}
private User lookupByEmail(String email) {
for (String uid : resolveCensus()) {
User u = getUser(uid);
if (u != null && u.getEmailAddress().equalsIgnoreCase(email)) {
return u;
}
}
return null;
}
private User getUser(String id) {
return users.computeIfAbsent(id, u -> {
try {
RetryableUserPromise p = userPromises.get(u);
if (p == null) {
p = new RetryableUserPromise(client, u);
userPromises.put(u, p);
}
return p.claim();
} catch (Exception e) {
return null;
}
});
}
public String getDisplayName(String id) {
return displayNames.computeIfAbsent(id, u -> {
User user = getUser(u);
if (user == null) {
// No user with such User ID, try to fuzzy match the email
user = lookupByEmail(u);
}
if (user != null) {
return user.getDisplayName();
} else {
// No hits in Census.
int email = u.indexOf("@");
if (email != -1) {
// Looks like email, extract.
return u.substring(0, email);
} else {
// No dice, report verbatim.
return u;
}
}
});
}
public String getAffiliation(String id) {
return affiliations.computeIfAbsent(id, u -> {
User user = getUser(u);
if (user == null) {
// No user with such User ID, try to fuzzy match the email
user = lookupByEmail(u);
}
if (user != null) {
// Look up in Census succeeded, pick the email address.
String email = user.getEmailAddress();
return generifyAffiliation(user.getDisplayName(), email.substring(email.indexOf("@")));
} else {
// No hits in Census.
int email = u.indexOf("@");
if (email != -1) {
// Looks like email, extract.
return generifyAffiliation(u, u.substring(email));
} else {
// No dice, report as unknown.
return "Unknown";
}
}
});
}
static final String[] INDEPENDENTS = {
"@wambold.com",
"@yandex.ru",
"@gmail.com",
"@freenet.de",
"@hollowman.ml",
"@ludovic.dev",
"@samersoff.net",
"@volkhart.com",
"@xlate.io",
"@apache.org",
"@users.noreply.github.com",
"@outlook.com",
"@j-kuhn.de",
"@yahoo.com",
"@ckozak.net",
"@cs.oswego.edu",
"@integralblue.com",
"@gmx.de",
"@gmx.at",
"@gmx.ch",
"@gmx.com",
"@mail.ru",
"@univ-mlv.fr",
"@joda.org",
"@pnnl.gov",
"@comcast.net",
"@thetaphi.de",
"@haupz.de",
"@duigou.org",
"@bempel.fr",
"@lagergren.net",
"@zoulas.com",
"@urma.com",
"@reshnm.de",
"@randahl.dk",
"@reini.net",
"@free.fr",
"@xs4all.nl",
"@tbee.org",
"@tabjy.com",
"@aaronbedra.com",
"@carl.pro",
"@gafter.com",
"@jugs.org",
"@jku.at",
"@sterbenz.net",
"@icloud.com",
"@jonathangiles.net",
"@ngmr",
"@126.com",
"@protonmail.com",
"@headcrashing.eu",
"@hotmail.com",
"@udel.edu",
"@javaspecialists.eu",
"@selskabet.org",
"@qq.com",
"@progrm-jarvis.ru",
"@jcornell.net",
"@icus.se",
"@prinzing.net",
"@utexas.edu",
"@cs.washington.edu",
"@iscas.ac.cn",
"@iernst.net",
"@cosoco.de",
"@foxmail.com",
"@cbfiddle.com",
"@iwes.fraunhofer.de",
"@nyssen.org",
"@lgonqn.org",
"@stanfordcomputing.com",
"@tai-dev.co.uk",
"@metricspace.net",
"@eyesbeyond.com",
"@posteo.de",
"@status6.com",
"@midverk.is",
"@csail.mit.edu",
"@mountainminds.com",
"@doppel-helix.eu",
"@web.de",
"@chello.at",
"@ngmr.net",
"@cs.usfca.edu",
"@knytt.se",
"@malloc.se",
};
static final String[][] COMPANIES = {
{"@oracle.com", "Oracle"},
{"@redhat.com", "Red Hat"},
{"@sap.com", "SAP"},
{"@tencent.com", "Tencent"},
{"@global.tencent.com", "Tencent"},
{"@amazon.com", "Amazon"},
{"@amazon.co.uk", "Amazon"},
{"@amazon.de", "Amazon"},
{"@huawei.com", "Huawei"},
{"@bell-sw.com", "BellSoft"},
{"@arm.com", "ARM"},
{"@azul.com", "Azul"},
{"@azulsystems.com", "Azul"},
{"@intel.com", "Intel"},
{"@microsoft.com", "Microsoft"},
{"@alibaba-inc.com", "Alibaba"},
{"@oss.nttdata.com", "NTT DATA"},
{"@microdoc.com", "Microdoc"},
{"@os.amperecomputing.com", "Ampere"},
{"@datadoghq.com", "DataDog"},
{"@google.com", "Google"},
{"@skymatic.de", "Skymatic"},
{"@gapfruit.com", "GapFruit"},
{"@loongson.cn", "Loongson"},
{"@tradingscreen.com", "TradingScreen"},
{"@jetbrains.com", "JetBrains"},
{"@twitter.com", "Twitter"},
{"@apple.com", "Apple"},
{"@sun.com", "Sun Microsystems"},
{"@linaro.com", "Linaro"},
{"@linaro.org", "Linaro"},
{"@amd.com", "AMD"},
{"@gluonhq.com", "Gluon"},
{"@vmware.com", "VMWare"},
{"@caviumnetworks.com", "Cavium"},
{"@ubuntu.com", "Ubuntu"},
{"@canonical.com", "Canonical"},
{"@freebsd.org", "FreeBSD"},
{"@suse.de", "SUSE"},
{"@fujitsu.com", "Fujitsu"},
{"@jp.fujitsu.com", "Fujitsu"},
{"@marvell.com", "Marvell"},
{"@tagtraum.com", "Tagtraum"},
{"@fb.com", "Facebook"},
{"@dynatrace.com", "Dynatrace"},
{"@rivosinc.com", "Rivos"},
};
static final String[][] SPECIAL_CASES = {
{"Thomas Stuefe", "SAP"},
{"Martin Buchholz", "Google"},
{"Tagir Valeev", "JetBrains"},
{"Volker Simonis", "Amazon"},
{"Charles Nutter", "Red Hat"},
{"Marcus Hirt", "DataDog"},
{"John Paul Adrian Glaubitz", "Debian"},
{"Lukas Eder", "DataGeekery"},
{"Andrew Haley", "Red Hat"},
{"Hamlin Li", "Huawei"},
{"Wang Huang", "Huawei"},
};
private String generifyAffiliation(String full, String v) {
// Pick a company first, if we can
for (String[] kv : COMPANIES) {
if (v.equals(kv[0])) {
return kv[1];
}
}
// Lots of prefixes here: @in.ibm.com, @linux.ibm.com etc.
if (v.endsWith("ibm.com")) {
return "IBM";
}
// Sometimes internal prefixes leak
if (v.endsWith("oracle.com")) {
return "Oracle";
}
// AWS leak
if (v.endsWith("compute.internal")) {
return "Amazon";
}
// Special cases for special people
for (String[] kv : SPECIAL_CASES) {
if (full.equals(kv[0])) {
return kv[1];
}
}
for (String ind : INDEPENDENTS) {
if (v.equals(ind)) {
return "Independent";
}
}
return v;
}
public int maxAffiliation() {
int r = 0;
for (String v : affiliations.values()) {
r = Math.max(r, v.length());
}
return r;
}
public int maxDisplayName() {
int r = 0;
for (String v : displayNames.values()) {
r = Math.max(r, v.length());
}
return r;
}
}
| 11,145 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Parsers.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/Parsers.java | /*
* Copyright (c) 2018, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import org.openjdk.backports.StringUtils;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Parsers {
static final Pattern OPENJDK_USER_ID = Pattern.compile("(.*)<(.*)@openjdk.org>");
static final Pattern GENERIC_USER_ID = Pattern.compile("(.*)<(.*)>");
public static Optional<String> parseURL(String s) {
for (String l : StringUtils.lines(s)) {
if (l.startsWith("URL")) {
return Optional.of(l.replaceFirst("URL:", "").trim());
}
}
return Optional.empty();
}
public static Optional<String> parseUser(String s) {
for (String l : StringUtils.lines(s)) {
if (l.startsWith("User")) {
return Optional.of(l.replaceFirst("User:", "").trim());
}
if (l.startsWith("Author")) {
Matcher m1 = OPENJDK_USER_ID.matcher(l);
if (m1.matches()) {
return Optional.of(m1.group(2));
}
Matcher m2 = GENERIC_USER_ID.matcher(l);
if (m2.matches()) {
return Optional.of(m2.group(2));
}
}
}
return Optional.empty();
}
public static Optional<Long> parseDaysAgo(String s) {
for (String l : StringUtils.lines(s)) {
if (l.startsWith("Date")) {
String d = l.replaceFirst("Date:", "").trim();
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss Z");
return Optional.of(ChronoUnit.DAYS.between(LocalDate.parse(d, formatter), LocalDate.now()));
}
}
return Optional.empty();
}
public static Optional<Long> parseSecondsAgo(String s) {
for (String l : StringUtils.lines(s)) {
if (l.startsWith("Date")) {
String d = l.replaceFirst("Date:", "").trim();
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss Z");
return Optional.of(ChronoUnit.SECONDS.between(LocalDateTime.parse(d, formatter), LocalDateTime.now()));
}
}
return Optional.empty();
}
public static int parsePriority(String s) {
if (s.length() != 2 && !s.startsWith("P")) {
return -1;
}
try {
return Integer.parseInt(s.substring(1));
} catch (NumberFormatException nfe) {
return -1;
}
}
}
| 3,911 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
RetryablePromise.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/RetryablePromise.java | /*
* Copyright (c) 2022, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import com.atlassian.jira.rest.client.api.RestClientException;
import io.atlassian.util.concurrent.Promise;
import java.util.concurrent.TimeUnit;
public abstract class RetryablePromise<T> {
private Promise<T> cur;
protected abstract Promise<T> get();
protected void init() {
cur = get();
}
public T claim() {
for (int t = 0; t < 10; t++) {
try {
return cur.claim();
} catch (Exception e) {
if (isValidError(e)) {
throw e;
}
try {
TimeUnit.MILLISECONDS.sleep((1 + t*t)*100);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
cur = get();
}
}
return cur.claim();
}
private boolean isValidError(Exception e) {
if (e instanceof RestClientException) {
RestClientException rce = (RestClientException) e;
Integer errCode = rce.getStatusCode().orNull();
if (errCode != null) {
return errCode >= 400 && errCode < 500;
}
}
return false;
}
}
| 2,437 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
ResolvedIssuePromise.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/ResolvedIssuePromise.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import com.atlassian.jira.rest.client.api.domain.Issue;
public class ResolvedIssuePromise implements IssuePromise {
private final Issue issue;
public ResolvedIssuePromise(Issue issue) {
this.issue = issue;
}
@Override
public Issue claim() {
return issue;
}
}
| 1,530 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
RelNotesIssue.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/RelNotesIssue.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
public class RelNotesIssue implements Comparable<RelNotesIssue> {
final String output;
final String priority;
final int fixVer;
final boolean hasNotes;
public RelNotesIssue(String output, String priority, int fixVer, boolean hasNotes) {
this.output = output;
this.priority = priority;
this.fixVer = fixVer;
this.hasNotes = hasNotes;
}
public String getOutput() {
return output;
}
@Override
public int compareTo(RelNotesIssue other) {
int v1 = Boolean.compare(other.hasNotes, hasNotes);
if (v1 != 0) {
return v1;
}
int v2 = Integer.compare(other.fixVer, fixVer);
if (v2 != 0) {
return v2;
}
int v3 = priority.compareTo(other.priority);
if (v3 != 0) {
return v3;
}
return this.output.compareTo(other.output);
}
}
| 2,145 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
RawRestClient.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/jira/RawRestClient.java | /*
* Copyright (c) 2021, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.jira;
import com.atlassian.httpclient.api.HttpClient;
import com.atlassian.httpclient.api.Response;
import com.atlassian.httpclient.api.ResponsePromise;
import org.json.JSONArray;
import javax.ws.rs.core.UriBuilder;
import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class RawRestClient {
private final URI baseUri;
private final HttpClient httpClient;
public RawRestClient(URI uri, HttpClient httpClient) {
this.baseUri = uri;
this.httpClient = httpClient;
}
public Collection<String> remoteLinks(String key) {
URI resolve = UriBuilder.fromUri(baseUri).path("/rest/api/latest/issue/" + key + "/remotelink").build(new Object[0]);
ResponsePromise p = httpClient.newRequest(resolve).get();
Response r = p.claim();
if (!r.isSuccessful()) {
return Collections.emptyList();
}
try (InputStream is = r.getEntityStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr)) {
Collection<String> links = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
JSONArray arr = new JSONArray(line);
for (int a = 0; a < arr.length(); a++) {
String s = arr.getJSONObject(a).getJSONObject("object").getString("url");
links.add(s);
}
}
return links;
} catch (IOException e) {
return Collections.emptyList();
}
}
}
| 2,873 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Predictor.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/test/java/mxnet/Predictor.java | package mxnet;
public class Predictor {
static {
System.loadLibrary("mxnet_predict");
}
public static class InputNode {
String key;
int[] shape;
public InputNode(String key, int[] shape) {
this.key = key;
this.shape = shape;
}
}
public static class Device {
public enum Type {
CPU, GPU, CPU_PINNED
}
public Device(Type t, int i) {
this.type = t;
this.id = i;
}
Type type;
int id;
int ctype() {
return this.type == Type.CPU? 1: this.type == Type.GPU? 2: 3;
}
}
private long handle = 0;
public Predictor(byte[] symbol, byte[] params, Device dev, InputNode[] input) {
String[] keys = new String[input.length];
int[][] shapes = new int[input.length][];
for (int i=0; i<input.length; ++i) {
keys[i] = input[i].key;
shapes[i] = input[i].shape;
}
this.handle = createPredictor(symbol, params, dev.ctype(), dev.id, keys, shapes);
}
public void free() {
if (this.handle != 0) {
nativeFree(handle);
this.handle = 0;
}
}
public float[] getOutput(int index) {
if (this.handle == 0) return null;
return nativeGetOutput(this.handle, index);
}
public void forward(String key, float[] input) {
if (this.handle == 0) return;
nativeForward(this.handle, key, input);
}
private native static long createPredictor(byte[] symbol, byte[] params, int devType, int devId, String[] keys, int[][] shapes);
private native static void nativeFree(long handle);
private native static float[] nativeGetOutput(long handle, int index);
private native static void nativeForward(long handle, String key, float[] input);
}
| 1,651 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
MxnetException.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/test/java/mxnet/MxnetException.java | package mxnet;
public class MxnetException extends Exception {
public MxnetException(){}
public MxnetException(String txt) {
super(txt);
}
}
| 153 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
ExampleUnitTest.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/test/java/de/hpi/xnor_mxnet/ExampleUnitTest.java | package de.hpi.xnor_mxnet;
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() throws Exception {
assertEquals(4, 2 + 2);
}
} | 395 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
Predictor.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/org/dmlc/mxnet/Predictor.java | package org.dmlc.mxnet;
import android.graphics.Bitmap;
import android.graphics.Color;
public class Predictor {
static {
System.loadLibrary("mxnet_predict");
}
public static class InputNode {
String key;
int[] shape;
public InputNode(String key, int[] shape) {
this.key = key;
this.shape = shape;
}
}
public static class Device {
public enum Type {
CPU, GPU, CPU_PINNED
}
public Device(Type t, int i) {
this.type = t;
this.id = i;
}
Type type;
int id;
int ctype() {
return this.type == Type.CPU? 1: this.type == Type.GPU? 2: 3;
}
}
private long handle = 0;
public Predictor(byte[] symbol, byte[] params, Device dev, InputNode[] input) {
String[] keys = new String[input.length];
int[][] shapes = new int[input.length][];
for (int i=0; i<input.length; ++i) {
keys[i] = input[i].key;
shapes[i] = input[i].shape;
}
this.handle = createPredictor(symbol, params, dev.ctype(), dev.id, keys, shapes);
}
public void free() {
if (this.handle != 0) {
nativeFree(handle);
this.handle = 0;
}
}
public float[] getOutput(int index) {
if (this.handle == 0) return null;
return nativeGetOutput(this.handle, index);
}
public void forward(String key, float[] input) {
if (this.handle == 0) return;
nativeForward(this.handle, key, input);
}
static public float[] inputFromImage(Bitmap[] bmps, float meanR, float meanG, float meanB) {
if (bmps.length == 0) return null;
int width = bmps[0].getWidth();
int height = bmps[0].getHeight();
float[] buf = new float[height * width * 3 * bmps.length];
for (int x=0; x<bmps.length; x++) {
Bitmap bmp = bmps[x];
if (bmp.getWidth() != width || bmp.getHeight() != height)
return null;
int[] pixels = new int[ height * width ];
bmp.getPixels(pixels, 0, width, 0, 0, height, width);
int start = width * height * 3 * x;
for (int i=0; i<height; i++) {
for (int j=0; j<width; j++) {
int pos = i * width + j;
int pixel = pixels[pos];
buf[start + pos] = Color.red(pixel) - meanR;
buf[start + width * height + pos] = Color.green(pixel) - meanG;
buf[start + width * height * 2 + pos] = Color.blue(pixel) - meanB;
}
}
}
return buf;
}
private native static long createPredictor(byte[] symbol, byte[] params, int devType, int devId, String[] keys, int[][] shapes);
private native static void nativeFree(long handle);
private native static float[] nativeGetOutput(long handle, int index);
private native static void nativeForward(long handle, String key, float[] input);
}
| 2,706 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
MxnetException.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/org/dmlc/mxnet/MxnetException.java | package org.dmlc.mxnet;
public class MxnetException extends Exception {
public MxnetException(){}
public MxnetException(String txt) {
super(txt);
}
}
| 162 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
LocationDetails.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/LocationDetails.java | package de.hpi.xnor_mxnet;
import java.util.HashMap;
import java.util.Map;
class LocationDetails {
public String title;
String descritpion;
String date;
LocationDetails(String title, String descritpion, String date) {
this.title = title;
this.descritpion = descritpion;
this.date = date;
}
Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("title", title);
result.put("description", descritpion);
result.put("date", date);
return result;
}
}
| 581 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
CameraFrameCapture.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/CameraFrameCapture.java | package de.hpi.xnor_mxnet;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.graphics.YuvImage;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.legacy.app.FragmentCompat;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class CameraFrameCapture extends Fragment
implements View.OnClickListener, FragmentCompat.OnRequestPermissionsResultCallback {
private static final int REQUEST_CAMERA_PERMISSION = 2;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
private static final int MAX_PREVIEW_WIDTH = 1080;
private static final int MAX_PREVIEW_HEIGHT = 1920;
private static final String FRAGMENT_DIALOG = "";
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private final TextureView.SurfaceTextureListener mSurfaceTextureListener
= new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) {
openCamera(width, height);
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {
configureTransform(width, height);
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture texture) {
}
};
/**
* ID of the current {@link CameraDevice}.
*/
private String mCameraId;
/**
* An {@link AutoFitTextureView} for camera preview.
*/
private AutoFitTextureView mTextureView;
/**
* A {@link CameraCaptureSession } for camera preview.
*/
private CameraCaptureSession mCaptureSession;
/**
* A reference to the opened {@link CameraDevice}.
*/
private CameraDevice mCameraDevice;
/**
* The {@link android.util.Size} of camera preview.
*/
private Size mPreviewSize;
/**
* {@link CameraDevice.StateCallback} is called when {@link CameraDevice} changes its state.
*/
private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice cameraDevice) {
// This method is called when the camera is opened. We start camera preview here.
mCameraOpenCloseLock.release();
mCameraDevice = cameraDevice;
createCameraPreviewSession();
}
@Override
public void onDisconnected(@NonNull CameraDevice cameraDevice) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
}
@Override
public void onError(@NonNull CameraDevice cameraDevice, int error) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
Activity activity = getActivity();
if (null != activity) {
activity.finish();
}
}
};
/**
* An additional thread for running tasks that shouldn't block the UI.
*/
private HandlerThread mBackgroundThread;
/**
* A {@link Handler} for running tasks in the background.
*/
private Handler mBackgroundHandler;
/**
* An {@link ImageReader} that handles still image capture.
*/
private ImageReader mImageReader;
/**
* This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
* still image is ready to be saved.
*/
private ImageReader.OnImageAvailableListener mOnImageAvailableListener;
/**
* {@link CaptureRequest.Builder} for the camera preview
*/
private CaptureRequest.Builder mPreviewRequestBuilder;
/**
* {@link CaptureRequest} generated by {@link #mPreviewRequestBuilder}
*/
private CaptureRequest mPreviewRequest;
/**
* A {@link Semaphore} to prevent the app from exiting before closing the camera.
*/
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
/**
* A {@link CameraCaptureSession.CaptureCallback} that handles events related to JPEG capture.
*/
private CameraCaptureSession.CaptureCallback mCaptureCallback
= new CameraCaptureSession.CaptureCallback() {
};
private final ConnectionCallback mCameraConnectionCallback;
public interface ConnectionCallback {
void onPreviewSizeChosen(Size size);
}
private CameraFrameCapture(ConnectionCallback connectionCallback, ImageReader.OnImageAvailableListener imageListener) {
this.mCameraConnectionCallback = connectionCallback;
this.mOnImageAvailableListener = imageListener;
}
public static CameraFrameCapture newInstance(
final ConnectionCallback connectionCallback,
final ImageReader.OnImageAvailableListener imageListener) {
return new CameraFrameCapture(connectionCallback, imageListener);
}
/**
* Given {@code choices} of {@code Size}s supported by a camera, choose the smallest one that
* is at least as large as the respective texture view size, and that is at most as large as the
* respective max size, and whose aspect ratio matches with the specified value. If such size
* doesn't exist, choose the largest one that is at most as large as the respective max size,
* and whose aspect ratio matches with the specified value.
*
* @param choices The list of sizes that the camera supports for the intended output
* class
* @param textureViewWidth The width of the texture view relative to sensor coordinate
* @param textureViewHeight The height of the texture view relative to sensor coordinate
* @param maxWidth The maximum width that can be chosen
* @param maxHeight The maximum height that can be chosen
* @param aspectRatio The aspect ratio
* @return The optimal {@code Size}, or an arbitrary one if none were big enough
*/
private static Size chooseOptimalSize(Size[] choices, int textureViewWidth,
int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio) {
// Collect the supported resolutions that are at least as big as the preview Surface
List<Size> bigEnough = new ArrayList<>();
// Collect the supported resolutions that are smaller than the preview Surface
List<Size> notBigEnough = new ArrayList<>();
int w = aspectRatio.getWidth();
int h = aspectRatio.getHeight();
for (Size option : choices) {
if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
option.getHeight() == option.getWidth() * h / w) {
if (option.getWidth() >= textureViewWidth &&
option.getHeight() >= textureViewHeight) {
bigEnough.add(option);
} else {
notBigEnough.add(option);
}
}
}
// Pick the smallest of those big enough. If there is no one big enough, pick the
// largest of those not big enough.
if (bigEnough.size() > 0) {
return Collections.min(bigEnough, new CompareSizesByArea());
} else if (notBigEnough.size() > 0) {
return Collections.max(notBigEnough, new CompareSizesByArea());
} else {
return choices[0];
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.placerecognizer_ui, container, false);
}
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
mTextureView = (AutoFitTextureView) view.findViewById(R.id.texture);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
startBackgroundThread();
// When the screen is turned off and turned back on, the SurfaceTexture is already
// available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open
// a camera and start preview from here (otherwise, we wait until the surface is ready in
// the SurfaceTextureListener).
if (mTextureView.isAvailable()) {
openCamera(mTextureView.getWidth(), mTextureView.getHeight());
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
}
@Override
public void onPause() {
closeCamera();
stopBackgroundThread();
super.onPause();
}
private void requestCameraPermission() {
if (FragmentCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
new ConfirmationDialog().show(getChildFragmentManager(), FRAGMENT_DIALOG);
} else {
FragmentCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode != REQUEST_CAMERA_PERMISSION) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
/**
* Sets up member variables related to camera.
*
* @param width The width of available size for camera preview
* @param height The height of available size for camera preview
*/
private void setUpCameraOutputs(int width, int height) {
Activity activity = getActivity();
int mSensorOrientation;
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
for (String cameraId : manager.getCameraIdList()) {
CameraCharacteristics characteristics
= manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
continue;
}
// For still image captures, we use the largest available size.
Size largest = Collections.max(
Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
new CompareSizesByArea());
mImageReader =
ImageReader.newInstance(
mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.YUV_420_888, /*maxImages*/2);
// mImageReader = ImageReader.newInstance(mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.JPEG, /*maxImages*/2);
mImageReader.setOnImageAvailableListener(
mOnImageAvailableListener, mBackgroundHandler);
// Find out if we need to swap dimension to get the preview size relative to sensor
// coordinate.
int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
//noinspection ConstantConditions
mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
boolean swappedDimensions = false;
switch (displayRotation) {
case Surface.ROTATION_0:
case Surface.ROTATION_180:
if (mSensorOrientation == 90 || mSensorOrientation == 270) {
swappedDimensions = true;
}
break;
case Surface.ROTATION_90:
case Surface.ROTATION_270:
if (mSensorOrientation == 0 || mSensorOrientation == 180) {
swappedDimensions = true;
}
break;
default:
}
Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
int rotatedPreviewWidth = width;
int rotatedPreviewHeight = height;
int maxPreviewWidth = displaySize.x;
int maxPreviewHeight = displaySize.y;
if (swappedDimensions) {
//noinspection SuspiciousNameCombination
rotatedPreviewWidth = height;
//noinspection SuspiciousNameCombination
rotatedPreviewHeight = width;
//noinspection SuspiciousNameCombination
maxPreviewWidth = displaySize.y;
//noinspection SuspiciousNameCombination
maxPreviewHeight = displaySize.x;
}
if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
maxPreviewWidth = MAX_PREVIEW_WIDTH;
}
if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
maxPreviewHeight = MAX_PREVIEW_HEIGHT;
}
// Danger, W.R.! Attempting to use too large a preview size could exceed the camera
// bus' bandwidth limitation, resulting in gorgeous previews but the storage of
// garbage capture data.
mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
maxPreviewHeight, largest);
// We fit the aspect ratio of TextureView to the size of preview we picked.
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
mTextureView.setAspectRatio(
mPreviewSize.getWidth(), mPreviewSize.getHeight());
} else {
mTextureView.setAspectRatio(
mPreviewSize.getHeight(), mPreviewSize.getWidth());
}
mCameraId = cameraId;
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Opens the camera specified by {@link CameraFrameCapture#mCameraId}.
*/
private void openCamera(int width, int height) {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestCameraPermission();
return;
}
setUpCameraOutputs(width, height);
configureTransform(width, height);
Activity activity = getActivity();
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Time out waiting to lock camera opening.");
}
manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
mCameraConnectionCallback.onPreviewSizeChosen(mPreviewSize);
} catch (CameraAccessException e) {
e.printStackTrace();
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
}
}
/**
* Closes the current {@link CameraDevice}.
*/
private void closeCamera() {
try {
mCameraOpenCloseLock.acquire();
if (null != mCaptureSession) {
mCaptureSession.close();
mCaptureSession = null;
}
if (null != mCameraDevice) {
mCameraDevice.close();
mCameraDevice = null;
}
if (null != mImageReader) {
mImageReader.close();
mImageReader = null;
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
} finally {
mCameraOpenCloseLock.release();
}
}
/**
* Starts a background thread and its {@link Handler}.
*/
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
/**
* Stops the background thread and its {@link Handler}.
*/
private void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Creates a new {@link CameraCaptureSession} for camera preview.
*/
private void createCameraPreviewSession() {
try {
SurfaceTexture texture = mTextureView.getSurfaceTexture();
assert texture != null;
// We configure the size of default buffer to be the size of camera preview we want.
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
// This is the output Surface we need to start preview.
Surface surface = new Surface(texture);
// We set up a CaptureRequest.Builder with the output Surface.
mPreviewRequestBuilder
= mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.addTarget(surface);
mPreviewRequestBuilder.addTarget(mImageReader.getSurface());
// Here, we create a CameraCaptureSession for camera preview.
mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
// The camera is already closed
if (null == mCameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
mCaptureSession = cameraCaptureSession;
try {
// Auto focus should be continuous for camera preview.
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
// Finally, we start displaying the camera preview.
mPreviewRequest = mPreviewRequestBuilder.build();
mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(
@NonNull CameraCaptureSession cameraCaptureSession) {
}
}, null
);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
/**
* Configures the necessary {@link android.graphics.Matrix} transformation to `mTextureView`.
* This method should be called after the camera preview size is determined in
* setUpCameraOutputs and also the size of `mTextureView` is fixed.
*
* @param viewWidth The width of `mTextureView`
* @param viewHeight The height of `mTextureView`
*/
private void configureTransform(int viewWidth, int viewHeight) {
Activity activity = getActivity();
if (null == mTextureView || null == mPreviewSize || null == activity) {
return;
}
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
Matrix matrix = new Matrix();
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
float centerX = viewRect.centerX();
float centerY = viewRect.centerY();
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
float scale = Math.max(
(float) viewHeight / mPreviewSize.getHeight(),
(float) viewWidth / mPreviewSize.getWidth());
matrix.postScale(scale, scale, centerX, centerY);
matrix.postRotate(90 * (rotation - 2), centerX, centerY);
} else if (Surface.ROTATION_180 == rotation) {
matrix.postRotate(180, centerX, centerY);
}
mTextureView.setTransform(matrix);
}
@Override
public void onClick(View view) {
}
/**
* Compares two {@code Size}s based on their areas.
*/
static class CompareSizesByArea implements Comparator<Size> {
@Override
public int compare(Size lhs, Size rhs) {
// We cast here to ensure the multiplications won't overflow
return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
(long) rhs.getWidth() * rhs.getHeight());
}
}
/**
* Shows OK/Cancel confirmation dialog about camera permission.
*/
public static class ConfirmationDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Fragment parent = getParentFragment();
return new AlertDialog.Builder(getActivity())
.setMessage("CreateTest")//R.string.request_permission)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
FragmentCompat.requestPermissions(parent,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Activity activity = parent.getActivity();
if (activity != null) {
activity.finish();
}
}
})
.create();
}
}
} | 25,439 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
OverlayView.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/OverlayView.java | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
package de.hpi.xnor_mxnet;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import java.util.LinkedList;
import java.util.List;
/**
* A simple View providing a render callback to other classes.
*/
public class OverlayView extends View {
private final List<DrawCallback> callbacks = new LinkedList<DrawCallback>();
public OverlayView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
/**
* Interface defining the callback for client classes.
*/
public interface DrawCallback {
public void drawCallback(final Canvas canvas);
}
public void addCallback(final DrawCallback callback) {
callbacks.add(callback);
}
@Override
public synchronized void draw(final Canvas canvas) {
for (final DrawCallback callback : callbacks) {
callback.drawCallback(canvas);
}
}
}
| 1,588 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
AutoFitTextureView.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/AutoFitTextureView.java | /*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hpi.xnor_mxnet;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Size;
import android.view.TextureView;
/**
* A {@link TextureView} that can be adjusted to a specified aspect ratio.
*/
public class AutoFitTextureView extends TextureView {
private int mRatioWidth = 0;
private int mRatioHeight = 0;
public AutoFitTextureView(Context context) {
this(context, null);
}
public AutoFitTextureView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AutoFitTextureView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Sets the aspect ratio for this view. The size of the view will be measured based on the ratio
* calculated from the parameters. Note that the actual sizes of parameters don't matter, that
* is, calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result.
*
* @param width Relative horizontal size
* @param height Relative vertical size
*/
public void setAspectRatio(int width, int height) {
if (width < 0 || height < 0) {
throw new IllegalArgumentException("Size cannot be negative.");
}
mRatioWidth = width;
mRatioHeight = height;
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
if (0 == mRatioWidth || 0 == mRatioHeight) {
setMeasuredDimension(width, height);
} else {
if (width < height * mRatioWidth / mRatioHeight) {
setMeasuredDimension(width, width * mRatioHeight / mRatioWidth);
} else {
setMeasuredDimension(height * mRatioWidth / mRatioHeight, height);
}
}
}
} | 2,648 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
GPSTracker.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/GPSTracker.java | package de.hpi.xnor_mxnet;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled && isNetworkEnabled) {
this.canGetLocation = true;
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS permissions");
alertDialog.setMessage("Please grant the App permissions to use GPS.");
}
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public boolean canGetLocation() {
return this.canGetLocation;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
}
| 6,124 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
GetWiki.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/GetWiki.java | package de.hpi.xnor_mxnet;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
//Json parser for wikipedia
class GetWiki extends AsyncTask<String, Object, LocationDetails> {
private static final String WIK = "WikiActivity";
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected LocationDetails doInBackground(String... strings) {
String urlTitle = strings[0];
String url = "https://en.wikipedia.org/w/api.php?format=json&action=query&redirects&exintro=&explaintext=&prop=extracts&titles=" + urlTitle;
HttpHandler handler = new HttpHandler();
// Making a request to url and getting response
String jsonStr = handler.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject pages = jsonObj.getJSONObject("query").getJSONObject("pages");
Iterator<String> keys = pages.keys();
String pageId= keys.next();
JSONObject page = pages.getJSONObject(pageId);
String title = page.getString("title");
String extract = page.getString("extract");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String date = sdf.format(new Date());
return new LocationDetails(title,extract,date);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(LocationDetails result) {
super.onPostExecute(result);
Log.i(WIK,"good");
}
} | 1,847 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
MainActivity.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/MainActivity.java | package de.hpi.xnor_mxnet;
import android.Manifest;
import android.app.Fragment;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.media.Image;
import android.media.ImageReader;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Trace;
import android.util.Log;
import android.util.Size;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.Toast;
import java.nio.ByteBuffer;
import java.util.Vector;
import de.hpi.xnor_mxnet.imageclassification.ImageClassifier;
import de.hpi.xnor_mxnet.imageclassification.ImageNetClassifier;
public class MainActivity extends CameraLiveViewActivity implements ImageReader.OnImageAvailableListener {
static {
System.loadLibrary("native-image-utils");
}
private static final int PERMISSIONS_REQUEST = 1;
private static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
private static final String PERMISSION_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE;
private static final float TEXT_SIZE_DIP = 10;
private static String TAG;
private Handler handler;
private HandlerThread handlerThread;
private ImageClassifier mImageClassifier;
private byte[][] yuvBytes;
private int[] rgbBytes;
private int previewWidth;
private int previewHeight;
private Bitmap rgbFrameBitmap;
private Bitmap croppedBitmap;
private Matrix frameToCropTransform;
private Matrix cropToFrameTransform;
private boolean debug;
private Bitmap cropCopyBitmap;
private BorderedText borderedText;
private long lasProcessingTimeMs;
private boolean isFirstImage = true;
private boolean hasPermission() {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
checkSelfPermission(PERMISSION_CAMERA) == PackageManager.PERMISSION_GRANTED &&
checkSelfPermission(PERMISSION_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(PERMISSION_CAMERA) || shouldShowRequestPermissionRationale(PERMISSION_STORAGE)) {
Toast.makeText(MainActivity.this, "Camera AND storage permission are required for this demo", Toast.LENGTH_LONG).show();
}
requestPermissions(new String[] {PERMISSION_CAMERA, PERMISSION_STORAGE}, PERMISSIONS_REQUEST);
}
}
private void buildImageClassifier() {
mImageClassifier = new ImageNetClassifier(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
TAG = getResources().getString(R.string.app_name);
setContentView(R.layout.main_activity);
if (hasPermission()) {
buildImageClassifier();
} else {
requestPermission();
}
}
@Override
public synchronized void onResume() {
super.onResume();
handlerThread = new HandlerThread("inference");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
}
@Override
public synchronized void onPause() {
Log.d(TAG, "Pausing");
if (!isFinishing()) {
finish();
}
handlerThread.quitSafely();
try {
handlerThread.join();
handlerThread = null;
handler = null;
} catch (final InterruptedException e) {
Log.e(TAG, e.getMessage());
}
super.onPause();
}
public void runCameraLiveView() {
final Fragment cameraView = CameraConnectionFragment.newInstance(
new CameraConnectionFragment.ConnectionCallback() {
@Override
public void onPreviewSizeChosen(Size size, int rotation) {
MainActivity.this.onPreviewSizeChosen(size);
}
},
this,
R.layout.placerecognizer_ui,
new Size(mImageClassifier.getImageWidth(), mImageClassifier.getImageHeight())
);
getFragmentManager().beginTransaction()
.replace(R.id.container, cameraView)
.commit();
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
switch (requestCode) {
case PERMISSIONS_REQUEST: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
buildImageClassifier();
} else {
requestPermission();
}
}
}
}
public void onPreviewSizeChosen(final Size size) {
final float textSizePx =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, getResources().getDisplayMetrics());
borderedText = new BorderedText(textSizePx);
borderedText.setTypeface(Typeface.MONOSPACE);
previewWidth = size.getWidth();
previewHeight = size.getHeight();
Log.i(TAG, String.format("Initializing cameraPreview at size %dx%d", previewWidth, previewHeight));
rgbBytes = new int[previewWidth * previewHeight];
rgbFrameBitmap = Bitmap.createBitmap(previewWidth, previewHeight, Bitmap.Config.ARGB_8888);
croppedBitmap = Bitmap.createBitmap(mImageClassifier.getImageWidth(), mImageClassifier.getImageHeight(), Bitmap.Config.ARGB_8888);
frameToCropTransform =
ImageUtils.getTransformationMatrix(
previewWidth, previewHeight,
mImageClassifier.getImageWidth(), mImageClassifier.getImageHeight(),
90, true);
cropToFrameTransform = new Matrix();
frameToCropTransform.invert(cropToFrameTransform);
yuvBytes = new byte[3][];
addCallback(
new OverlayView.DrawCallback() {
@Override
public void drawCallback(final Canvas canvas) {
renderDebug(canvas);
}
});
}
protected void fillBytes(final Image.Plane[] planes, final byte[][] yuvBytes) {
// Because of the variable row stride it's not possible to know in
// advance the actual necessary dimensions of the yuv planes.
for (int i = 0; i < planes.length; ++i) {
final ByteBuffer buffer = planes[i].getBuffer();
if (yuvBytes[i] == null) {
Log.d(TAG, String.format("Initializing buffer %d at size %d", i, buffer.capacity()));
yuvBytes[i] = new byte[buffer.capacity()];
}
buffer.get(yuvBytes[i]);
}
}
public void requestRender() {
final OverlayView overlay = (OverlayView) findViewById(R.id.debug_overlay);
if (overlay != null) {
overlay.postInvalidate();
}
}
public void addCallback(final OverlayView.DrawCallback callback) {
final OverlayView overlay = (OverlayView) findViewById(R.id.debug_overlay);
if (overlay != null) {
overlay.addCallback(callback);
}
}
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
debug = !debug;
requestRender();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void renderDebug(final Canvas canvas) {
if (!debug) {
return;
}
final Bitmap copy = cropCopyBitmap;
if (copy != null) {
final Matrix matrix = new Matrix();
final float scaleFactor = 2;
matrix.postScale(scaleFactor, scaleFactor);
matrix.postTranslate(
canvas.getWidth() - copy.getWidth() * scaleFactor,
canvas.getHeight() - copy.getHeight() * scaleFactor);
canvas.drawBitmap(copy, matrix, new Paint());
final Vector<String> lines = new Vector<>();
lines.add("Frame: " + previewWidth + "x" + previewHeight);
lines.add("Crop: " + copy.getWidth() + "x" + copy.getHeight());
lines.add("View: " + canvas.getWidth() + "x" + canvas.getHeight());
lines.add("Inference time: " + lasProcessingTimeMs + "ms");
borderedText.drawLines(canvas, 10, canvas.getHeight() - 10, lines);
}
}
@Override
public void onImageAvailable(ImageReader imageReader) {
Image image = null;
try {
image = imageReader.acquireLatestImage();
if (image == null) {
return;
}
if (computing || isFirstImage) {
isFirstImage = false;
image.close();
return;
}
computing = true;
Trace.beginSection("imageAvailable");
final Image.Plane[] planes = image.getPlanes();
fillBytes(planes, yuvBytes);
final int yRowStride = planes[0].getRowStride();
final int uvRowStride = planes[1].getRowStride();
final int uvPixelStride = planes[1].getPixelStride();
ImageUtils.convertYUV420ToARGB8888(
yuvBytes[0],
yuvBytes[1],
yuvBytes[2],
rgbBytes,
previewWidth,
previewHeight,
yRowStride,
uvRowStride,
uvPixelStride,
false);
image.close();
Trace.endSection();
} catch (final Exception e) {
if (image != null) {
image.close();
}
Log.e(TAG, String.format("Exception in onImageAvailable: %s", e));
Trace.endSection();
return;
}
rgbFrameBitmap.setPixels(rgbBytes, 0, previewWidth, 0, 0, previewWidth, previewHeight);
final Canvas canvas = new Canvas(croppedBitmap);
canvas.drawBitmap(rgbFrameBitmap, frameToCropTransform, null);
cropCopyBitmap = Bitmap.createBitmap(croppedBitmap);
if (handler != null) {
handler.post(new ImageClassificationTask(croppedBitmap, this, mImageClassifier));
}
}
public void setLasProcessingTimeMs(long lasProcessingTimeMs) {
this.lasProcessingTimeMs = lasProcessingTimeMs;
}
}
| 11,106 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
ImageClassificationTask.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/ImageClassificationTask.java | package de.hpi.xnor_mxnet;
import android.app.Activity;
import android.graphics.Bitmap;
import android.widget.TextView;
import de.hpi.xnor_mxnet.imageclassification.Classification;
import de.hpi.xnor_mxnet.imageclassification.ImageClassifier;
import de.hpi.xnor_mxnet.imageclassification.ImageNetClassifier;
class ImageClassificationTask implements Runnable {
private final Bitmap mImage;
private final ImageClassifier mClassifier;
private final CameraLiveViewActivity mActivity;
ImageClassificationTask(Bitmap image, CameraLiveViewActivity activity, ImageClassifier classifier) {
mImage = image;
mClassifier = classifier;
mActivity = activity;
}
private String join(String delimiter, String[] s) {
StringBuilder out = new StringBuilder();
out.append(s[0]);
for (int i = 1; i < s.length; ++i) {
out.append(delimiter).append(s[i]);
}
return out.toString();
}
@Override
public void run() {
final Classification[] results = mClassifier.classifyImage(mImage);
final String[] resultStrings = new String[results.length];
for (int i = 0; i < results.length; ++i) {
resultStrings[i] = String.format("%s, %.3f", results[i].get_label(), results[i].get_probability());
}
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textView = (TextView) mActivity.findViewById(R.id.classDisplay);
String text = join("\n", resultStrings);
if (textView != null) {
textView.setText(text);
}
System.out.println(text);
mActivity.setComputing(false);
}
});
}
}
| 1,804 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
BorderedText.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/BorderedText.java | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
package de.hpi.xnor_mxnet;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.Typeface;
import java.util.Vector;
/**
* A class that encapsulates the tedious bits of rendering legible, bordered text onto a canvas.
*/
public class BorderedText {
private final Paint interiorPaint;
private final Paint exteriorPaint;
private final float textSize;
/**
* Creates a left-aligned bordered text object with a white interior, and a black exterior with
* the specified text size.
*
* @param textSize text size in pixels
*/
public BorderedText(final float textSize) {
this(Color.WHITE, Color.BLACK, textSize);
}
/**
* Create a bordered text object with the specified interior and exterior colors, text size and
* alignment.
*
* @param interiorColor the interior text color
* @param exteriorColor the exterior text color
* @param textSize text size in pixels
*/
public BorderedText(final int interiorColor, final int exteriorColor, final float textSize) {
interiorPaint = new Paint();
interiorPaint.setTextSize(textSize);
interiorPaint.setColor(interiorColor);
interiorPaint.setStyle(Style.FILL);
interiorPaint.setAntiAlias(false);
interiorPaint.setAlpha(255);
exteriorPaint = new Paint();
exteriorPaint.setTextSize(textSize);
exteriorPaint.setColor(exteriorColor);
exteriorPaint.setStyle(Style.FILL_AND_STROKE);
exteriorPaint.setStrokeWidth(textSize / 8);
exteriorPaint.setAntiAlias(false);
exteriorPaint.setAlpha(255);
this.textSize = textSize;
}
public void setTypeface(Typeface typeface) {
interiorPaint.setTypeface(typeface);
exteriorPaint.setTypeface(typeface);
}
public void drawText(final Canvas canvas, final float posX, final float posY, final String text) {
canvas.drawText(text, posX, posY, exteriorPaint);
canvas.drawText(text, posX, posY, interiorPaint);
}
public void drawLines(Canvas canvas, final float posX, final float posY, Vector<String> lines) {
int lineNum = 0;
for (final String line : lines) {
drawText(canvas, posX, posY - getTextSize() * (lines.size() - lineNum - 1), line);
++lineNum;
}
}
public void setInteriorColor(final int color) {
interiorPaint.setColor(color);
}
public void setExteriorColor(final int color) {
exteriorPaint.setColor(color);
}
public float getTextSize() {
return textSize;
}
public void setAlpha(final int alpha) {
interiorPaint.setAlpha(alpha);
exteriorPaint.setAlpha(alpha);
}
public void getTextBounds(
final String line, final int index, final int count, final Rect lineBounds) {
interiorPaint.getTextBounds(line, index, count, lineBounds);
}
public void setTextAlign(final Align align) {
interiorPaint.setTextAlign(align);
exteriorPaint.setTextAlign(align);
}
}
| 3,910 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
CameraConnectionFragment.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/CameraConnectionFragment.java | /*
* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hpi.xnor_mxnet;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.ImageReader;
import android.media.ImageReader.OnImageAvailableListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.TextUtils;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
public class CameraConnectionFragment extends Fragment {
/**
* The camera preview size will be chosen to be the smallest frame by pixel size capable of
* containing a DESIRED_SIZE x DESIRED_SIZE square.
*/
private static final int MINIMUM_PREVIEW_SIZE = 320;
/**
* Conversion from screen rotation to JPEG orientation.
*/
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
private static final String FRAGMENT_DIALOG = "dialog";
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
/**
* {@link android.view.TextureView.SurfaceTextureListener} handles several lifecycle events on a
* {@link TextureView}.
*/
private final TextureView.SurfaceTextureListener surfaceTextureListener =
new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(
final SurfaceTexture texture, final int width, final int height) {
openCamera(width, height);
}
@Override
public void onSurfaceTextureSizeChanged(
final SurfaceTexture texture, final int width, final int height) {
configureTransform(width, height);
}
@Override
public boolean onSurfaceTextureDestroyed(final SurfaceTexture texture) {
return true;
}
@Override
public void onSurfaceTextureUpdated(final SurfaceTexture texture) {}
};
/**
* Callback for Activities to use to initialize their data once the
* selected preview size is known.
*/
public interface ConnectionCallback {
void onPreviewSizeChosen(Size size, int cameraRotation);
}
/**
* ID of the current {@link CameraDevice}.
*/
private String cameraId;
/**
* An {@link AutoFitTextureView} for camera preview.
*/
private AutoFitTextureView textureView;
/**
* A {@link CameraCaptureSession } for camera preview.
*/
private CameraCaptureSession captureSession;
/**
* A reference to the opened {@link CameraDevice}.
*/
private CameraDevice cameraDevice;
/**
* The rotation in degrees of the camera sensor from the display.
*/
private Integer sensorOrientation;
/**
* The {@link android.util.Size} of camera preview.
*/
private Size previewSize;
/**
* {@link android.hardware.camera2.CameraDevice.StateCallback}
* is called when {@link CameraDevice} changes its state.
*/
private final CameraDevice.StateCallback stateCallback =
new CameraDevice.StateCallback() {
@Override
public void onOpened(final CameraDevice cd) {
// This method is called when the camera is opened. We start camera preview here.
cameraOpenCloseLock.release();
cameraDevice = cd;
createCameraPreviewSession();
}
@Override
public void onDisconnected(final CameraDevice cd) {
cameraOpenCloseLock.release();
cd.close();
cameraDevice = null;
}
@Override
public void onError(final CameraDevice cd, final int error) {
cameraOpenCloseLock.release();
cd.close();
cameraDevice = null;
final Activity activity = getActivity();
if (null != activity) {
activity.finish();
}
}
};
/**
* An additional thread for running tasks that shouldn't block the UI.
*/
private HandlerThread backgroundThread;
/**
* A {@link Handler} for running tasks in the background.
*/
private Handler backgroundHandler;
/**
* An {@link ImageReader} that handles preview frame capture.
*/
private ImageReader previewReader;
/**
* {@link android.hardware.camera2.CaptureRequest.Builder} for the camera preview
*/
private CaptureRequest.Builder previewRequestBuilder;
/**
* {@link CaptureRequest} generated by {@link #previewRequestBuilder}
*/
private CaptureRequest previewRequest;
/**
* A {@link Semaphore} to prevent the app from exiting before closing the camera.
*/
private final Semaphore cameraOpenCloseLock = new Semaphore(1);
/**
* A {@link OnImageAvailableListener} to receive frames as they are available.
*/
private final OnImageAvailableListener imageListener;
/** The input size in pixels desired by TensorFlow (width and height of a square bitmap). */
private final Size inputSize;
/**
* The layout identifier to inflate for this Fragment.
*/
private final int layout;
private final ConnectionCallback cameraConnectionCallback;
private CameraConnectionFragment(
final ConnectionCallback connectionCallback,
final OnImageAvailableListener imageListener,
final int layout,
final Size inputSize) {
this.cameraConnectionCallback = connectionCallback;
this.imageListener = imageListener;
this.layout = layout;
this.inputSize = inputSize;
}
/**
* Shows a {@link Toast} on the UI thread.
*
* @param text The message to show
*/
private void showToast(final String text) {
final Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(
new Runnable() {
@Override
public void run() {
Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
}
});
}
}
/**
* Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose
* width and height are at least as large as the minimum of both, or an exact match if possible.
*
* @param choices The list of sizes that the camera supports for the intended output class
* @param width The minimum desired width
* @param height The minimum desired height
* @return The optimal {@code Size}, or an arbitrary one if none were big enough
*/
private static Size chooseOptimalSize(final Size[] choices, final int width, final int height) {
final int minSize = Math.max(Math.min(width, height), MINIMUM_PREVIEW_SIZE);
final Size desiredSize = new Size(width, height);
// Collect the supported resolutions that are at least as big as the preview Surface
boolean exactSizeFound = false;
final List<Size> bigEnough = new ArrayList<Size>();
final List<Size> tooSmall = new ArrayList<Size>();
for (final Size option : choices) {
if (option.equals(desiredSize)) {
// Set the size but don't return yet so that remaining sizes will still be logged.
exactSizeFound = true;
}
if (option.getHeight() >= minSize && option.getWidth() >= minSize) {
bigEnough.add(option);
} else {
tooSmall.add(option);
}
}
if (exactSizeFound) {
return desiredSize;
}
// Pick the smallest of those, assuming we found any
if (bigEnough.size() > 0) {
final Size chosenSize = Collections.min(bigEnough, new CompareSizesByArea());
return chosenSize;
} else {
return choices[0];
}
}
public static CameraConnectionFragment newInstance(
final ConnectionCallback callback,
final OnImageAvailableListener imageListener,
final int layout,
final Size inputSize) {
return new CameraConnectionFragment(callback, imageListener, layout, inputSize);
}
@Override
public View onCreateView(
final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return inflater.inflate(layout, container, false);
}
@Override
public void onViewCreated(final View view, final Bundle savedInstanceState) {
textureView = (AutoFitTextureView) view.findViewById(R.id.texture);
}
@Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
startBackgroundThread();
// When the screen is turned off and turned back on, the SurfaceTexture is already
// available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open
// a camera and start preview from here (otherwise, we wait until the surface is ready in
// the SurfaceTextureListener).
if (textureView.isAvailable()) {
openCamera(textureView.getWidth(), textureView.getHeight());
} else {
textureView.setSurfaceTextureListener(surfaceTextureListener);
}
}
@Override
public void onPause() {
closeCamera();
stopBackgroundThread();
super.onPause();
}
/**
* Sets up member variables related to camera.
*
* @param width The width of available size for camera preview
* @param height The height of available size for camera preview
*/
private void setUpCameraOutputs(final int width, final int height) {
final Activity activity = getActivity();
final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
for (final String cameraId : manager.getCameraIdList()) {
final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
// We don't use a front facing camera in this sample.
final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
continue;
}
final StreamConfigurationMap map =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
continue;
}
sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
// Danger, W.R.! Attempting to use too large a preview size could exceed the camera
// bus' bandwidth limitation, resulting in gorgeous previews but the storage of
// garbage capture data.
previewSize =
chooseOptimalSize(
map.getOutputSizes(SurfaceTexture.class),
inputSize.getWidth(),
inputSize.getHeight());
// We fit the aspect ratio of TextureView to the size of preview we picked.
final int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
textureView.setAspectRatio(previewSize.getWidth(), previewSize.getHeight());
} else {
textureView.setAspectRatio(previewSize.getHeight(), previewSize.getWidth());
}
CameraConnectionFragment.this.cameraId = cameraId;
}
} catch (final CameraAccessException e) {
e.printStackTrace();
} catch (final NullPointerException e) {
// Currently an NPE is thrown when the Camera2API is used but not supported on the
// device this code runs.
// TODO(andrewharp): abstract ErrorDialog/RuntimeException handling out into new method and
// reuse throughout app.
ErrorDialog.newInstance(getString(R.string.camera_error))
.show(getChildFragmentManager(), FRAGMENT_DIALOG);
throw new RuntimeException(getString(R.string.camera_error));
}
cameraConnectionCallback.onPreviewSizeChosen(previewSize, sensorOrientation);
}
/**
* Opens the camera specified by {@link CameraConnectionFragment#cameraId}.
*/
private void openCamera(final int width, final int height) {
setUpCameraOutputs(width, height);
configureTransform(width, height);
final Activity activity = getActivity();
final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
if (!cameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Time out waiting to lock camera opening.");
}
manager.openCamera(cameraId, stateCallback, backgroundHandler);
} catch (final CameraAccessException e) {
e.printStackTrace();
} catch (final InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
}
}
/**
* Closes the current {@link CameraDevice}.
*/
private void closeCamera() {
try {
cameraOpenCloseLock.acquire();
if (null != captureSession) {
captureSession.close();
captureSession = null;
}
if (null != cameraDevice) {
cameraDevice.close();
cameraDevice = null;
}
if (null != previewReader) {
previewReader.close();
previewReader = null;
}
} catch (final InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
} finally {
cameraOpenCloseLock.release();
}
}
/**
* Starts a background thread and its {@link Handler}.
*/
private void startBackgroundThread() {
backgroundThread = new HandlerThread("ImageListener");
backgroundThread.start();
backgroundHandler = new Handler(backgroundThread.getLooper());
}
/**
* Stops the background thread and its {@link Handler}.
*/
private void stopBackgroundThread() {
backgroundThread.quitSafely();
try {
backgroundThread.join();
backgroundThread = null;
backgroundHandler = null;
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
private final CameraCaptureSession.CaptureCallback captureCallback =
new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureProgressed(
final CameraCaptureSession session,
final CaptureRequest request,
final CaptureResult partialResult) {}
@Override
public void onCaptureCompleted(
final CameraCaptureSession session,
final CaptureRequest request,
final TotalCaptureResult result) {}
};
/**
* Creates a new {@link CameraCaptureSession} for camera preview.
*/
private void createCameraPreviewSession() {
try {
final SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
// We configure the size of default buffer to be the size of camera preview we want.
texture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight());
// This is the output Surface we need to start preview.
final Surface surface = new Surface(texture);
// We set up a CaptureRequest.Builder with the output Surface.
previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
previewRequestBuilder.addTarget(surface);
// Create the reader for the preview frames
previewReader =
ImageReader.newInstance(previewSize.getWidth(), previewSize.getHeight(), ImageFormat.YUV_420_888, 2);
previewReader.setOnImageAvailableListener(imageListener, backgroundHandler);
previewRequestBuilder.addTarget(previewReader.getSurface());
// Here, we create a CameraCaptureSession for camera preview.
cameraDevice.createCaptureSession(
Arrays.asList(surface, previewReader.getSurface()),
// Arrays.asList(surface),
new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(final CameraCaptureSession cameraCaptureSession) {
// The camera is already closed
if (null == cameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
captureSession = cameraCaptureSession;
try {
// Auto focus should be continuous for camera preview.
previewRequestBuilder.set(
CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
// Flash is automatically enabled when necessary.
previewRequestBuilder.set(
CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
// Finally, we start displaying the camera preview.
previewRequest = previewRequestBuilder.build();
captureSession.setRepeatingRequest(
previewRequest, captureCallback, backgroundHandler);
} catch (final CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(final CameraCaptureSession cameraCaptureSession) {
showToast("Failed");
}
},
null);
} catch (final CameraAccessException e) {
e.printStackTrace();
}
}
/**
* Configures the necessary {@link android.graphics.Matrix} transformation to `mTextureView`.
* This method should be called after the camera preview size is determined in
* setUpCameraOutputs and also the size of `mTextureView` is fixed.
*
* @param viewWidth The width of `mTextureView`
* @param viewHeight The height of `mTextureView`
*/
private void configureTransform(final int viewWidth, final int viewHeight) {
final Activity activity = getActivity();
if (null == textureView || null == previewSize || null == activity) {
return;
}
final int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
final Matrix matrix = new Matrix();
final RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
final RectF bufferRect = new RectF(0, 0, previewSize.getHeight(), previewSize.getWidth());
final float centerX = viewRect.centerX();
final float centerY = viewRect.centerY();
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
final float scale =
Math.max(
(float) viewHeight / previewSize.getHeight(),
(float) viewWidth / previewSize.getWidth());
matrix.postScale(scale, scale, centerX, centerY);
matrix.postRotate(90 * (rotation - 2), centerX, centerY);
} else if (Surface.ROTATION_180 == rotation) {
matrix.postRotate(180, centerX, centerY);
}
textureView.setTransform(matrix);
}
/**
* Compares two {@code Size}s based on their areas.
*/
static class CompareSizesByArea implements Comparator<Size> {
@Override
public int compare(final Size lhs, final Size rhs) {
// We cast here to ensure the multiplications won't overflow
return Long.signum(
(long) lhs.getWidth() * lhs.getHeight() - (long) rhs.getWidth() * rhs.getHeight());
}
}
/**
* Shows an error message dialog.
*/
public static class ErrorDialog extends DialogFragment {
private static final String ARG_MESSAGE = "message";
public static ErrorDialog newInstance(final String message) {
final ErrorDialog dialog = new ErrorDialog();
final Bundle args = new Bundle();
args.putString(ARG_MESSAGE, message);
dialog.setArguments(args);
return dialog;
}
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
final Activity activity = getActivity();
return new AlertDialog.Builder(activity)
.setMessage(getArguments().getString(ARG_MESSAGE))
.setPositiveButton(
android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialogInterface, final int i) {
activity.finish();
}
})
.create();
}
}
}
| 22,370 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
HttpHandler.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/HttpHandler.java | package de.hpi.xnor_mxnet;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
HttpHandler() {
}
String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
} | 1,920 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
ImageUtils.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/ImageUtils.java | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
package de.hpi.xnor_mxnet;
import android.graphics.Matrix;
public class ImageUtils {
/**
* Utility method to compute the allocated size in bytes of a YUV420SP image
* of the given dimensions.
*/
public static int getYUVByteSize(final int width, final int height) {
// The luminance plane requires 1 byte per pixel.
final int ySize = width * height;
// The UV plane works on 2x2 blocks, so dimensions with odd size must be rounded up.
// Each 2x2 block takes 2 bytes to encode, one each for U and V.
final int uvSize = ((width + 1) / 2) * ((height + 1) / 2) * 2;
return ySize + uvSize;
}
/**
* Converts YUV420 semi-planar data to ARGB 8888 data using the supplied width
* and height. The input and output must already be allocated and non-null.
* For efficiency, no error checking is performed.
*
* @param input The array of YUV 4:2:0 input data.
* @param output A pre-allocated array for the ARGB 8:8:8:8 output data.
* @param width The width of the input image.
* @param height The height of the input image.
* @param halfSize If true, downsample to 50% in each dimension, otherwise not.
*/
public static native void convertYUV420SPToARGB8888(
byte[] input, int[] output, int width, int height, boolean halfSize);
/**
* Converts YUV420 semi-planar data to ARGB 8888 data using the supplied width
* and height. The input and output must already be allocated and non-null.
* For efficiency, no error checking is performed.
*
* @param y
* @param u
* @param v
* @param uvPixelStride
* @param width The width of the input image.
* @param height The height of the input image.
* @param halfSize If true, downsample to 50% in each dimension, otherwise not.
* @param output A pre-allocated array for the ARGB 8:8:8:8 output data.
*/
public static native void convertYUV420ToARGB8888(
byte[] y,
byte[] u,
byte[] v,
int[] output,
int width,
int height,
int yRowStride,
int uvRowStride,
int uvPixelStride,
boolean halfSize);
/**
* Converts YUV420 semi-planar data to RGB 565 data using the supplied width
* and height. The input and output must already be allocated and non-null.
* For efficiency, no error checking is performed.
*
* @param input The array of YUV 4:2:0 input data.
* @param output A pre-allocated array for the RGB 5:6:5 output data.
* @param width The width of the input image.
* @param height The height of the input image.
*/
public static native void convertYUV420SPToRGB565(
byte[] input, byte[] output, int width, int height);
/**
* Returns a transformation matrix from one reference frame into another.
* Handles cropping (if maintaining aspect ratio is desired) and rotation.
*
* @param srcWidth Width of source frame.
* @param srcHeight Height of source frame.
* @param dstWidth Width of destination frame.
* @param dstHeight Height of destination frame.
* @param applyRotation Amount of rotation to apply from one frame to another.
* Must be a multiple of 90.
* @param maintainAspectRatio If true, will ensure that scaling in x and y remains constant,
* cropping the image if necessary.
* @return The transformation fulfilling the desired requirements.
*/
public static Matrix getTransformationMatrix(
final int srcWidth,
final int srcHeight,
final int dstWidth,
final int dstHeight,
final int applyRotation,
final boolean maintainAspectRatio) {
final Matrix matrix = new Matrix();
if (applyRotation != 0) {
// Translate so center of image is at origin.
matrix.postTranslate(-srcWidth / 2.0f, -srcHeight / 2.0f);
// Rotate around origin.
matrix.postRotate(applyRotation);
}
// Account for the already applied rotation, if any, and then determine how
// much scaling is needed for each axis.
final boolean transpose = (Math.abs(applyRotation) + 90) % 180 == 0;
final int inWidth = transpose ? srcHeight : srcWidth;
final int inHeight = transpose ? srcWidth : srcHeight;
// Apply scaling if necessary.
if (inWidth != dstWidth || inHeight != dstHeight) {
final float scaleFactorX = dstWidth / (float) inWidth;
final float scaleFactorY = dstHeight / (float) inHeight;
if (maintainAspectRatio) {
// Scale by minimum factor so that dst is filled completely while
// maintaining the aspect ratio. Some image may fall off the edge.
final float scaleFactor = Math.max(scaleFactorX, scaleFactorY);
matrix.postScale(scaleFactor, scaleFactor);
} else {
// Scale exactly to fill dst from src.
matrix.postScale(scaleFactorX, scaleFactorY);
}
}
if (applyRotation != 0) {
// Translate back from origin centered reference to destination frame.
matrix.postTranslate(dstWidth / 2.0f, dstHeight / 2.0f);
}
return matrix;
}
}
| 6,102 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
CameraLiveViewActivity.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/CameraLiveViewActivity.java | package de.hpi.xnor_mxnet;
import android.app.Activity;
public abstract class CameraLiveViewActivity extends Activity {
protected boolean computing = false;
abstract public void runCameraLiveView();
public void setComputing(boolean computing) {
this.computing = computing;
}
}
| 306 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
ModelPreparationTask.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/imageclassification/ModelPreparationTask.java | package de.hpi.xnor_mxnet.imageclassification;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import de.hpi.xnor_mxnet.CameraLiveViewActivity;
import de.hpi.xnor_mxnet.R;
public class ModelPreparationTask extends AsyncTask<ImageClassifier, Void, Void> {
private ProgressDialog mProgressDialog;
private CameraLiveViewActivity context;
public void setContext(CameraLiveViewActivity context) {
this.context = context;
}
@Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(context);
mProgressDialog.setTitle(R.string.loading_model);
mProgressDialog.setCancelable(false);
mProgressDialog.setIndeterminate(true);
mProgressDialog.show();
}
@Override
protected Void doInBackground(ImageClassifier... imageClassifiers) {
for (ImageClassifier classifier: imageClassifiers) {
classifier.loadModel();
classifier.loadLabels();
classifier.loadMean();
classifier.loadStdDev();
}
return null;
}
@Override
protected void onPostExecute(Void voids) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
context.runCameraLiveView();
}
}
| 1,287 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
ImageNetClassifier.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/imageclassification/ImageNetClassifier.java | package de.hpi.xnor_mxnet.imageclassification;
import android.graphics.Bitmap;
import android.os.SystemClock;
import android.os.Trace;
import org.dmlc.mxnet.Predictor;
import java.nio.ByteBuffer;
import java.util.HashMap;
import de.hpi.xnor_mxnet.MainActivity;
import de.hpi.xnor_mxnet.R;
public class ImageNetClassifier extends AbstractClassifier {
protected final boolean modelNeedsMeanAdjust = true;
protected final boolean modelNeedsStdAdjust = true;
public ImageNetClassifier(MainActivity activity) {
super(activity);
mImageWidth = 224;
mImageHeight = 224;
}
public Classification[] classifyImage(Bitmap bitmap) {
Trace.beginSection("create Image Buffer");
ByteBuffer byteBuffer = ByteBuffer.allocate(bitmap.getByteCount());
bitmap.copyPixelsToBuffer(byteBuffer);
byte[] bytes = byteBuffer.array();
Trace.endSection();
Trace.beginSection("color adaption");
float[] colors;
colors = prepareInputImage(bytes);
Trace.endSection();
Trace.beginSection("Model execution");
final long startTime = SystemClock.uptimeMillis();
mPredictor.forward("data", colors);
mActivity.setLasProcessingTimeMs(SystemClock.uptimeMillis() - startTime);
final float[] result = mPredictor.getOutput(0);
Trace.endSection();
Trace.beginSection("gather top results");
Classification[] results = getTopKresults(result, 5);
Trace.endSection();
mActivity.requestRender();
return results;
}
@Override
public void loadModel() {
final byte[] symbol = readRawFile(mActivity, R.raw.binarized_densenet_28_symbol);
final byte[] params = readRawFile(mActivity, R.raw.binarized_densenet_28_params);
final Predictor.Device device = new Predictor.Device(Predictor.Device.Type.CPU, 0);
final int[] shape = {1, 3, mImageHeight, mImageWidth};
final String key = "data";
final Predictor.InputNode node = new Predictor.InputNode(key, shape);
mPredictor = new Predictor(symbol, params, device, new Predictor.InputNode[]{node});
}
@Override
public void loadLabels() {
mLabels = readRawTextFile(mActivity, R.raw.synset);
}
@Override
public void loadMean() {
mMean = new HashMap<>();
if (modelNeedsMeanAdjust) {
mMean.put("b", (float) 103.939);
mMean.put("g", (float) 116.779);
mMean.put("r", (float) 123.68);
}
}
@Override
public void loadStdDev() {
mStdDev = new HashMap<>();
if (modelNeedsStdAdjust) {
mStdDev.put("b", (float) 57.375);
mStdDev.put("g", (float) 57.12);
mStdDev.put("r", (float) 58.393);
}
}
}
| 2,822 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
ImageClassifier.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/imageclassification/ImageClassifier.java | package de.hpi.xnor_mxnet.imageclassification;
import android.graphics.Bitmap;
public interface ImageClassifier {
int getImageWidth();
int getImageHeight();
Classification[] classifyImage(Bitmap bitmap);
void loadModel();
void loadLabels();
void loadMean();
void loadStdDev();
}
| 309 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
AbstractClassifier.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/imageclassification/AbstractClassifier.java | package de.hpi.xnor_mxnet.imageclassification;
import android.content.Context;
import org.dmlc.mxnet.Predictor;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import de.hpi.xnor_mxnet.BuildConfig;
import de.hpi.xnor_mxnet.MainActivity;
abstract class AbstractClassifier implements ImageClassifier {
final MainActivity mActivity;
Predictor mPredictor;
List<String> mLabels;
Map<String, Float> mMean;
Map<String, Float> mStdDev;
int mImageWidth;
int mImageHeight;
protected final boolean modelNeedsMeanAdjust = true;
protected final boolean modelNeedsStdAdjust = true;
@Override
public int getImageWidth() {
return mImageWidth;
}
@Override
public int getImageHeight() {
return mImageHeight;
}
AbstractClassifier(MainActivity activity) {
mActivity = activity;
ModelPreparationTask preparationTask = new ModelPreparationTask();
preparationTask.setContext(activity);
preparationTask.execute(this);
}
static byte[] readRawFile(Context ctx, int resId)
{
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
int size = 0;
byte[] buffer = new byte[1024];
try (InputStream ins = ctx.getResources().openRawResource(resId)) {
while((size=ins.read(buffer,0,1024))>=0){
outputStream.write(buffer,0,size);
}
} catch (IOException e) {
e.printStackTrace();
}
return outputStream.toByteArray();
}
static List<String> readRawTextFile(Context ctx, int resId)
{
List<String> result = new ArrayList<>();
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
try {
while (( line = buffreader.readLine()) != null) {
result.add(line);
}
} catch (IOException e) {
return null;
}
return result;
}
Classification[] getTopKresults(float[] input_matrix, int k) {
float[] sorted_values = input_matrix.clone();
Arrays.sort(sorted_values);
Classification[] topK = new Classification[k];
List<Float> input_list = new ArrayList<>();
for (float f: input_matrix) {
input_list.add(f);
}
if (BuildConfig.DEBUG && sorted_values.length < k) {
throw new RuntimeException("Too few predicted values for getting topK results!");
}
for (int i = 0; i < topK.length; ++i) {
int classId = input_list.indexOf(sorted_values[sorted_values.length - i - 1]);
String tag = mLabels.get(classId);
String [] tagInfo = tag.split(" ", 2);
topK[i] = new Classification(classId, tagInfo[1], input_matrix[classId]);
}
return topK;
}
float[] prepareInputImage(byte[] bytes) {
float[] colors = new float[bytes.length / 4 * 3];
// the R,G,B order has been tested (by HJ, 19.10.17), the R->G->B (1,2,3) got better results from prediction
int imageOffset = mImageWidth * mImageHeight;
for (int i = 0; i < bytes.length; i += 4) {
int j = i / 4;
int indexR = j;
int indexG = imageOffset + j;
int indexB = 2 * imageOffset + j;
colors[indexR] = (float)(((int)(bytes[i + 1])) & 0xFF);
colors[indexG] = (float)(((int)(bytes[i + 2])) & 0xFF);
colors[indexB] = (float)(((int)(bytes[i + 3])) & 0xFF);
if (modelNeedsMeanAdjust) {
colors[indexR] -= mMean.get("r");
colors[indexG] -= mMean.get("g");
colors[indexB] -= mMean.get("b");
}
if (modelNeedsStdAdjust) {
colors[indexR] /= mStdDev.get("r");
colors[indexG] /= mStdDev.get("g");
colors[indexB] /= mStdDev.get("b");
}
}
return colors;
}
}
| 4,341 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
Classification.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/main/java/de/hpi/xnor_mxnet/imageclassification/Classification.java | package de.hpi.xnor_mxnet.imageclassification;
public class Classification {
private String _id;
private String _label;
private float _probability;
Classification(String id, String label, float probability) {
_id = id; _label = label; _probability = probability;
}
public Classification(int id, String label, float probability) {
_id = String.valueOf(id); _label = label; _probability = probability;
}
public String get_id() { return _id; }
public String get_label() { return _label; }
public float get_probability() { return _probability; }
}
| 604 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
ExampleInstrumentedTest.java | /FileExtraction/Java_unseen/hpi-xnor_android-image-classification/app/src/androidTest/java/de/hpi/xnor_mxnet/ExampleInstrumentedTest.java | package de.hpi.xnor_mxnet;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation 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() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("de.hpi.placerecognizer", appContext.getPackageName());
}
}
| 743 | Java | .java | hpi-xnor/android-image-classification | 17 | 10 | 0 | 2017-05-22T14:33:00Z | 2020-06-09T17:06:46Z |
ExampleMain.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/examples/ImagesAndAnimations/ExampleMain.java | package com.dsh105.holoapi.example;
import com.dsh105.holoapi.api.AnimatedHologram;
import com.dsh105.holoapi.api.AnimatedHologramFactory;
import com.dsh105.holoapi.api.Hologram;
import com.dsh105.holoapi.api.HologramFactory;
import com.dsh105.holoapi.image.AnimatedImageGenerator;
import com.dsh105.holoapi.image.ImageChar;
import com.dsh105.holoapi.image.ImageGenerator;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
/**
* Example:
* - This example adds two commands. /image and /animation
* - /image will create an image hologram
* - /animation will create two animated holograms
* <p/>
* What you will achieve by following this:
* - Knowledge of how to create image holograms using both saved files and URLs
* - Knowledge of how to create animated holograms from a GIF file
* - Knowledge of how to create animated holograms using ImageGenerators as separate frames
* - Knowledge of how to create a simple hologram with no persistence
* - Knowledge of how to remove a hologram
*/
public class ExampleMain extends JavaPlugin {
@Override
public void onEnable() {
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("You can't do that!");
return true;
}
if (command.getName().equalsIgnoreCase("image")) {
// Here a new image hologram is created from the given URL (which happens to be the HoloAPI logo)
// The height has been set to 10, the char type to BLOCK and border to false
// Because of the nature of this image, it's not going to look the best in-game
// Selecting images that have clear colour outlines (and possibly even pixel-art) will work the best
Hologram h = new HologramFactory(this)
.withLocation(((Player) sender).getLocation())
.withImage(new ImageGenerator("http://dev.bukkit.org/media/images/70/44/Banner_PNG.png",
10, // A height of 10
ImageChar.BLOCK, // Char type to use
false)).build(); // No extra border for this image, seeing as it is a filled image with not much transparency
sender.sendMessage("You created an image hologram at " + h.getDefaultX() + ", " + h.getDefaultY() + ", " + h.getDefaultZ() + "!");
return true;
} else if (command.getName().equalsIgnoreCase("animation")) {
// Animated holograms from GIFs are slightly different
// If you haven't seen the tutorial on text animations, it is recommended you check that out first
// We'll go over two ways of creating images here
// In this example, we're pretending there's a GIF file located at `plugins/MyPlugin/mygif.gif`
AnimatedHologram h = new AnimatedHologramFactory(this)
.withLocation(((Player) sender).getLocation())
.withImage(new AnimatedImageGenerator(new File(this.getDataFolder() + File.separator + "mygif.gif"), 5, 10, ImageChar.BLOCK, false))
.build();
// This will overlap the one above. For the purpose of this tutorial, that doesn't matter
// The ImageGenerator above can be used to create the frames of AnimatedHolograms
// This hologram has three different frames created from different PNG images
// From what we did above, you should be able to figure out what's going on here :)
AnimatedHologram h2 = new AnimatedHologramFactory(this)
.withLocation(((Player) sender).getLocation())
.withImage(new AnimatedImageGenerator(5,
new ImageGenerator(new File(this.getDataFolder() + File.separator + "firstframe.png"), 10, ImageChar.BLOCK, false),
new ImageGenerator(new File(this.getDataFolder() + File.separator + "secondframe.png"), 10, ImageChar.BLOCK, false),
new ImageGenerator(new File(this.getDataFolder() + File.separator + "thirdframe.png"), 10, ImageChar.BLOCK, false)))
.build();
sender.sendMessage("You created two animated holograms! Well done!");
return true;
}
return false;
}
} | 4,505 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
ExampleMain.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/examples/AnimatedHolograms/ExampleMain.java | package com.dsh105.holoapi.example;
import com.dsh105.holoapi.api.AnimatedHologram;
import com.dsh105.holoapi.api.AnimatedHologramFactory;
import com.dsh105.holoapi.image.AnimatedTextGenerator;
import com.dsh105.holoapi.image.Frame;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Example:
* - This example adds one command - /animation
* - This command creates an animated hologram consisting of three text frames
* <p/>
* What you will achieve by following this:
* - Knowledge of how to create an animated hologram using frames of text
*/
public class ExampleMain extends JavaPlugin {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("You can't do that!");
return true;
}
if (command.getName().equalsIgnoreCase("animation")) {
// Create our animated text hologram
// It will consist of three frames, each varying in line number. HoloAPI will automatically piece it together for you
//Animations can have as many frames as you want
AnimatedHologram h = new AnimatedHologramFactory(this)
.withText(new AnimatedTextGenerator(
new Frame(5, "First line, first frame", "Many lines", "Such wow"), // The first frame of the animation
new Frame(10, "This frame is slightly longer", "And can have a different number of lines than the first"), // The second frame
new Frame(15, "&sWow, such colours"))) // In this frame, HoloAPI's &s code is used to create a colourful display of text
.build();
// As well as the methods that the Hologram class provides a few extra methods, such as: getNext(), getCurrent(), getFrames(), getFrame(int)
// That's pretty much all there is to it
return true;
}
return false;
}
} | 2,114 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
ExampleMain.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/examples/SimpleHolograms/ExampleMain.java | package com.dsh105.holoapi.example;
import com.dsh105.holoapi.HoloAPI;
import com.dsh105.holoapi.api.Hologram;
import com.dsh105.holoapi.api.HologramFactory;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Example:
* - When a player dies, create a hologram at their death location
* - This hologram will be removed after 30 seconds
* <p/>
* What you will achieve by following this:
* - Knowledge of how to create a simple hologram with no persistence
* - Knowledge of how to remove a hologram
*/
public class ExampleMain extends JavaPlugin implements Listener {
@Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(this, this);
}
@EventHandler
public void onDeath(PlayerDeathEvent event) {
Player who = event.getEntity();
// Initiate the factory to build our new hologram
final Hologram hologram = new HologramFactory(this)
// This is where we want the hologram to be
.withLocation(who.getLocation())
// This hologram will have two lines of text
.withText("RIP " + who.getName(), "Better luck next time!")
// We don't want this hologram to save to file, so we can set it to a simple hologram
.withSimplicity(true)
// Build the hologram. Also shows to all nearby players
.build();
this.getServer().getScheduler().runTaskLater(this, new Runnable() {
@Override
public void run() {
// Remove the hologram that was created above
HoloAPI.getManager().stopTracking(hologram);
}
}, 20 * 30);
}
} | 1,880 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
ExampleMain.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/examples/TouchScreens/ExampleMain.java | package com.dsh105.holoapi.example;
import com.dsh105.holoapi.api.Hologram;
import com.dsh105.holoapi.api.HologramFactory;
import com.dsh105.holoapi.api.events.HoloTouchActionLoadEvent;
import com.dsh105.holoapi.api.events.HoloTouchEvent;
import com.dsh105.holoapi.api.touch.TouchAction;
import com.dsh105.holoapi.protocol.Action;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.LinkedHashMap;
/**
* Example:
* - Creating and managing touchscreen enabled holograms through the TouchScreen API
* - On startup, two holograms are created
* - The first has two touch actions added - one persistent saved under "travel"
* - The second is touch enabled and handled using the HoloTouchEvent
* <p/>
* What you will achieve by following this:
* - Creating touchable holograms using the TouchScreen API
* - Add touch actions in two different ways
* - Add both persistent and temporary touch actions to a hologram
* - Loading persistent data for hologram touch actions and re-applying to a hologram
* - Enabling touchscreen functionality on a hologram without adding any touch actions
* - Using various events to manipulate touchscreen enabled holograms
*/
public class ExampleMain extends JavaPlugin implements Listener {
private Hologram touchEventHologram;
@Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(this, this);
// Just creating a hologram here. If you don't know how to do this yet, see the other examples
// NOTE: This hologram will be created on startup every time.
Hologram hologram = new HologramFactory(this).withLocation(new Location(Bukkit.getWorld("world"), 0, 50, 0)).withText("Click to travel to spawn!").build();
// This is where we get to the fun stuff
// This method allows us to add actions that are performed when this hologram is touched (clicked)
hologram.addTouchAction(new TravelTouchAction(new Location(Bukkit.getWorld("world"), 10, 50, 10)));
// Another example of how to implement a touch action
// This one won't be persistent
hologram.addTouchAction(new TouchAction() {
@Override
public void onTouch(Player who, Action action) {
who.sendMessage("Congrats! You touched a hologram");
}
@Override
public String getSaveKey() {
// We don't want this action saved, so return null here
return null;
}
@Override
public LinkedHashMap<String, Object> getDataToSave() {
// Seeing as the save key is null, this method won't ever be called for this touch action
return null;
}
});
// Creating and storing another hologram. This will be used later on
touchEventHologram = new HologramFactory(this).withLocation(new Location(Bukkit.getWorld("world"), 0, 50, 0)).withText("Want some XP?").build();
// Seeing as we aren't specifically adding any touch actions, this hologram won't be touch enabled yet
// Consequently, we have to make sure it's enabled
touchEventHologram.setTouchEnabled(true); // That wasn't too hard was it? :D
// Once a hologram is touch enabled, HoloAPI won't remove that functionality unless specifically told to using that method
// As you can see, the possibilities of touchscreens are limitless using HoloAPI
// And it's fairly easy too :)
}
// This event handles data loading
// For the hologram above, this won't matter much because it's created on startup anyway
// For other holograms utilising the custom touch action, this becomes extremely useful for keeping touch actions saved between restarts
@EventHandler
public void onDataLoad(HoloTouchActionLoadEvent event) {
// Check if this is the touch action we wanted
if (event.getSaveKey().equals("travel")) {
// Retrieve all the data from the event
// It would be best to check if the data actually exists first
// For the purpose of this tutorial, I won't do that here
int x = (Integer) event.getConfigMap().get("x");
int y = (Integer) event.getConfigMap().get("y");
int z = (Integer) event.getConfigMap().get("z");
World world = Bukkit.getWorld((String) event.getConfigMap().get("world"));
// Put the touch action back into the hologram that was loaded
event.getHologram().addTouchAction(new TravelTouchAction(new Location(world, x, y, z)));
}
}
// In this event, we are going to handle the touch actions slightly differently
// Instead of app
@EventHandler
public void onTouch(HoloTouchEvent event) {
// First check if it's the hologram we want
if (event.getHologram().equals(this.touchEventHologram)) {
// Give them XP for touching it and send them a message
event.getPlayer().giveExpLevels(5);
event.getPlayer().sendMessage("You just gained 5 XP levels by touching that hologram. Well done!");
}
}
/**
* Our extension of the TouchAction
* This will be persistent, using the event above
*/
public class TravelTouchAction implements TouchAction {
Location to;
public TravelTouchAction(Location to) {
this.to = to;
}
@Override
public void onTouch(Player who, Action action) {
// No matter who clicks it, teleport them to the location we stored above
who.teleport(to);
}
@Override
public String getSaveKey() {
// What do we want to save it as?
// Might be a good idea to use something more unique than this, especially if other plugins on your server are utilising this API
// If two actions have the same save key, data will be overwritten
return "travel";
}
@Override
public LinkedHashMap<String, Object> getDataToSave() {
// By putting all these values into the map and sending it back to HoloAPI, we can make sure that all the data we need to load it back in is there
// See the load event above for how to load everything back into holograms
LinkedHashMap<String, Object> data = new LinkedHashMap<String, Object>();
data.put("x", to.getX());
data.put("y", to.getY());
data.put("z", to.getZ());
data.put("world", to.getWorld());
return data;
}
}
} | 6,803 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
ScriptLoaderTest.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/test/java/com/dsh105/holoapi/script/ScriptLoaderTest.java | package com.dsh105.holoapi.script;
import org.junit.Test;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ScriptLoaderTest {
@Test
public void testScript() throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
Script script = new Script("test", "return \"Success!\"") {
@Override
public String getSignature() {
return "";
}
@Override
public Object eval(ScriptEngine engine, Object... args) throws ScriptException {
super.compile(engine);
try {
Object result = ((Invocable) engine).invokeFunction(this.name, args);
return result;
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Failed to compile " + this.name + " into the ScriptEngine!", e);
}
}
};
System.out.println(script.eval(engine, null, null));
}
} | 1,198 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
HoloAPI.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/HoloAPI.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi;
import com.dsh105.command.CommandManager;
import com.dsh105.commodus.config.Options;
import com.dsh105.commodus.config.YAMLConfig;
import com.dsh105.commodus.logging.Log;
import com.dsh105.holoapi.api.HoloManager;
import com.dsh105.holoapi.api.HoloUpdater;
import com.dsh105.holoapi.api.TagFormatter;
import com.dsh105.holoapi.api.visibility.VisibilityMatcher;
import com.dsh105.holoapi.config.ConfigType;
import com.dsh105.holoapi.hook.BungeeProvider;
import com.dsh105.holoapi.hook.VanishProvider;
import com.dsh105.holoapi.hook.VaultProvider;
import com.dsh105.holoapi.image.AnimatedImageGenerator;
import com.dsh105.holoapi.image.ImageGenerator;
import com.dsh105.holoapi.image.ImageLoader;
public class HoloAPI {
private static HoloAPICore CORE;
public static Log LOG;
public static void setCore(HoloAPICore plugin) {
if (CORE != null) {
throw new RuntimeException("Core already set!");
}
CORE = plugin;
LOG = new Log("HoloAPI");
}
public static HoloAPICore getCore() {
return CORE;
}
public static String getPrefix() {
return getPrefix("HoloAPI") + "••• ";
}
public static String getPrefix(String internalText) {
return getCore().prefix.replace("%text%", internalText);
}
/**
* Gets the HoloAPI Hologram Manager
* <p>
* The Hologram Manager is used to register and manage the holograms created from both within and outside the
* HoloAPI plugin
*
* @return {@link com.dsh105.holoapi.api.HoloManager} that manages and controls registration of holograms
*/
public static HoloManager getManager() {
return getCore().HOLO_MANAGER;
}
/**
* Gets the HoloAPI Image Loader
* <p>
* The Image Loader stores and handles registration of all images configured in the HoloAPI Configuration file
*
* @return Image Loader that controls and stores all pre-loaded image generators
*/
public static ImageLoader<ImageGenerator> getImageLoader() {
return getCore().IMAGE_LOADER;
}
/**
* Gets the HoloAPI Animation Loader
* <p>
* The Animated Loader stores and handles registration of all animations configured in the HoloAPI Configuration
* file
*
* @return Animation Loader that controls and stores all pre-loaded animation generators
*/
public static ImageLoader<AnimatedImageGenerator> getAnimationLoader() {
return getCore().ANIMATION_LOADER;
}
/**
* Gets the HoloAPI TagFormatter
* <p>
* The TagFormatter stores all valid replacements for hologram tags
*
* @return TagFormatter that stores all valid replacements for hologram tags
*/
public static TagFormatter getTagFormatter() {
return getCore().TAG_FORMATTER;
}
/**
* Gets the HoloAPI VisibilityMatcher
* <p>
* The VisibilityMatcher stores all registrations of hologram visibilities for use in commands and other HoloAPI
* functions
*
* @return VisibilityMatcher that stores all registrations of hologram visibilities
*/
public static VisibilityMatcher getVisibilityMatcher() {
return getCore().VISIBILITY_MATCHER;
}
public static HoloUpdater getHoloUpdater() {
return getCore().HOLO_UPDATER;
}
public static CommandManager getCommandManager() {
return getCore().COMMAND_MANAGER;
}
public static <T extends Options> T getSettings(Class<T> settingsClass) {
return getCore().getSettings(settingsClass);
}
public static Options getSettings(ConfigType configType) {
return getCore().getSettings(configType);
}
public static YAMLConfig getConfig(ConfigType type) {
return getCore().getConfig(type);
}
public static VaultProvider getVaultProvider() {
if (getCore().vaultProvider == null) {
throw new RuntimeException("VaultProvider is NULL!");
}
return getCore().vaultProvider;
}
public static VanishProvider getVanishProvider() {
if (getCore().vanishProvider == null) {
throw new RuntimeException("VanishProvider is NULL!");
}
return getCore().vanishProvider;
}
public static BungeeProvider getBungeeProvider() {
return getCore().bungeeProvider;
}
}
| 5,073 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
HoloAPICore.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/HoloAPICore.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi;
import com.dsh105.command.CommandListener;
import com.dsh105.command.CommandManager;
import com.dsh105.commodus.config.Options;
import com.dsh105.commodus.config.YAMLConfig;
import com.dsh105.commodus.config.YAMLConfigManager;
import com.dsh105.commodus.data.Metrics;
import com.dsh105.commodus.data.Updater;
import com.dsh105.holoapi.api.HoloUpdater;
import com.dsh105.holoapi.api.SimpleHoloManager;
import com.dsh105.holoapi.api.TagFormatter;
import com.dsh105.holoapi.api.visibility.VisibilityMatcher;
import com.dsh105.holoapi.command.HoloCommand;
import com.dsh105.holoapi.command.sub.*;
import com.dsh105.holoapi.config.ConfigType;
import com.dsh105.holoapi.config.Lang;
import com.dsh105.holoapi.config.Settings;
import com.dsh105.holoapi.data.DependencyGraphUtil;
import com.dsh105.holoapi.hook.BungeeProvider;
import com.dsh105.holoapi.hook.VanishProvider;
import com.dsh105.holoapi.hook.VaultProvider;
import com.dsh105.holoapi.image.SimpleAnimationLoader;
import com.dsh105.holoapi.image.SimpleImageLoader;
import com.dsh105.holoapi.listeners.HoloDataLoadListener;
import com.dsh105.holoapi.listeners.HoloListener;
import com.dsh105.holoapi.listeners.IndicatorListener;
import com.dsh105.holoapi.listeners.WorldListener;
import com.dsh105.holoapi.protocol.InjectionManager;
import com.dsh105.holoapi.script.ScriptLoader;
import com.dsh105.holoapi.script.ScriptManager;
import com.dsh105.holoapi.util.Debugger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class HoloAPICore extends JavaPlugin {
protected static CommandManager COMMAND_MANAGER;
protected static SimpleHoloManager HOLO_MANAGER;
protected static SimpleImageLoader IMAGE_LOADER;
protected static SimpleAnimationLoader ANIMATION_LOADER;
protected static TagFormatter TAG_FORMATTER;
protected static VisibilityMatcher VISIBILITY_MATCHER;
protected static HoloUpdater HOLO_UPDATER;
protected static InjectionManager INJECTION_MANAGER;
protected static ScriptManager SCRIPT_MANAGER;
protected YAMLConfigManager configManager;
private HashMap<ConfigType, YAMLConfig> CONFIG_FILES = new HashMap<>();
private HashMap<ConfigType, Options> SETTINGS = new HashMap<>();
protected VaultProvider vaultProvider;
protected VanishProvider vanishProvider;
protected BungeeProvider bungeeProvider;
// Update Checker stuff
public boolean updateAvailable = false;
public String updateName = "";
public boolean updateChecked = false;
public File file;
protected String prefix = ChatColor.WHITE + "[" + ChatColor.BLUE + "%text%" + ChatColor.WHITE + "]" + ChatColor.RESET + " ";
@Override
public void onDisable() {
if (HOLO_MANAGER != null) {
HOLO_MANAGER.clearAll();
}
if (INJECTION_MANAGER != null) {
INJECTION_MANAGER.close();
INJECTION_MANAGER = null;
}
this.getServer().getScheduler().cancelTasks(this);
}
@Override
public void onEnable() {
HoloAPI.setCore(this);
PluginManager manager = getServer().getPluginManager();
this.loadConfiguration();
Debugger.getInstance().setOutput(getServer().getConsoleSender());
Debugger.getInstance().setEnabled(Settings.DEBUGGING_ENABLED.getValue());
Debugger.getInstance().setLevel(Settings.DEBUGGING_LEVEL.getValue(10));
INJECTION_MANAGER = new InjectionManager(this);
Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
/* try {
SCRIPT_MANAGER = new ScriptManager(this);
} catch (IOException e) {
HoloAPI.LOG.warning("Failed to create the ScriptManager!");
ScriptLoader.SCRIPTING_ENABLED = false;
} */
HOLO_UPDATER = new HoloUpdater();
TAG_FORMATTER = new TagFormatter();
VISIBILITY_MATCHER = new VisibilityMatcher();
HOLO_MANAGER = new SimpleHoloManager();
IMAGE_LOADER = new SimpleImageLoader();
ANIMATION_LOADER = new SimpleAnimationLoader();
this.loadCommands();
manager.registerEvents(new HoloListener(), this);
manager.registerEvents(new WorldListener(), this);
manager.registerEvents(new IndicatorListener(), this);
manager.registerEvents(new HoloDataLoadListener(), this);
// Vault Hook
this.vaultProvider = new VaultProvider(this);
// VanishNoPacket Hook
this.vanishProvider = new VanishProvider(this);
// BungeeCord Hook
this.bungeeProvider = new BungeeProvider(this);
this.loadHolograms();
/**
* All metrics
*/
try {
Metrics metrics = new Metrics(this);
metrics.start();
/**
* Dependencies
*/
Metrics.Graph dependingPlugins = metrics.createGraph("Depending Plugins");
synchronized (Bukkit.getPluginManager()) {
for (final Plugin otherPlugin : DependencyGraphUtil.getPluginsUnsafe()) {
if (!otherPlugin.isEnabled()) {
continue;
}
if (!DependencyGraphUtil.isDepending(otherPlugin, this) && !DependencyGraphUtil.isSoftDepending(otherPlugin, this)) {
continue;
}
dependingPlugins.addPlotter(new Metrics.Plotter(otherPlugin.getName()) {
@Override
public int getValue() {
return 1;
}
});
}
}
metrics.addGraph(dependingPlugins);
} catch (IOException e) {
HoloAPI.LOG.warning("Plugin Metrics (MCStats) has failed to start.");
e.printStackTrace();
}
this.checkUpdates();
}
private void loadCommands() {
COMMAND_MANAGER = new CommandManager(this, HoloAPI.getPrefix());
COMMAND_MANAGER.getMessenger().setFormatColour(ChatColor.getByChar(Settings.BASE_CHAT_COLOUR.getValue()));
COMMAND_MANAGER.getMessenger().setHighlightColour(ChatColor.getByChar(Settings.HIGHLIGHT_CHAT_COLOUR.getValue()));
COMMAND_MANAGER.getHelpService().setIgnoreCommandAccess(false);
COMMAND_MANAGER.getHelpService().setIncludePermissionListing(false);
CommandListener parent = new HoloCommand();
COMMAND_MANAGER.register(parent);
// TODO: A way to do this dynamically
COMMAND_MANAGER.nestCommandsIn(parent, new AddLineCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new BuildCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new CopyCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new ClearCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new CreateCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new EditCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new HelpCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new HideCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new IdCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new InfoCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new MoveCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new NearbyCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new ReadTxtCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new RefreshCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new ReloadCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new RemoveCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new ShowCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new TeleportCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new TouchCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new UpdateCommand());
COMMAND_MANAGER.nestCommandsIn(parent, new VisibilityCommand());
}
protected void checkUpdates() {
if (Settings.CHECK_FOR_UPDATES.getValue()) {
file = this.getFile();
final Updater.UpdateType updateType = Settings.CHECK_FOR_UPDATES.getValue() ? Updater.UpdateType.DEFAULT : Updater.UpdateType.NO_DOWNLOAD;
getServer().getScheduler().runTaskAsynchronously(this, new Runnable() {
@Override
public void run() {
Updater updater = new Updater(HoloAPI.getCore(), 74914, file, updateType, false);
updateAvailable = updater.getResult() == Updater.UpdateResult.UPDATE_AVAILABLE;
if (updateAvailable) {
updateName = updater.getLatestName();
HoloAPI.LOG.console(ChatColor.DARK_AQUA + "An update is available: " + updateName);
HoloAPI.LOG.console(ChatColor.DARK_AQUA + "Type /holo update to update.");
if (!updateChecked) {
updateChecked = true;
}
}
}
});
}
}
public void loadHolograms() {
HOLO_MANAGER.clearAll();
new BukkitRunnable() {
@Override
public void run() {
IMAGE_LOADER.loadImageConfiguration(getConfig(ConfigType.MAIN));
ANIMATION_LOADER.loadAnimationConfiguration(getConfig(ConfigType.MAIN));
}
}.runTaskAsynchronously(this);
final ArrayList<String> unprepared = HOLO_MANAGER.loadFileData();
new BukkitRunnable() {
@Override
public void run() {
if (HoloAPI.getImageLoader().isLoaded()) {
for (String s : unprepared) {
HOLO_MANAGER.loadFromFile(s);
}
HoloAPI.LOG.info("Holograms loaded");
this.cancel();
}
}
}.runTaskTimer(this, 20 * 5, 20 * 10);
}
public void loadConfiguration() {
configManager = new YAMLConfigManager(this);
YAMLConfig config,
dataConfig,
langConfig;
config = configManager.getNewConfig("config.yml", new String[]{
"HoloAPI",
"---------------------",
"Configuration File",
"",
"See the HoloAPI Wiki before editing this file",
"(https://github.com/DSH105/HoloAPI/wiki)"
});
langConfig = configManager.getNewConfig("messages.yml", new String[]{"HoloAPI", "---------------------", "Language Configuration File"});
dataConfig = configManager.getNewConfig("data.yml");
CONFIG_FILES.put(ConfigType.MAIN, config);
CONFIG_FILES.put(ConfigType.LANG, langConfig);
CONFIG_FILES.put(ConfigType.DATA, dataConfig);
for (YAMLConfig yamlConfig : CONFIG_FILES.values()) {
yamlConfig.reloadConfig();
}
SETTINGS.put(ConfigType.MAIN, new Settings(config));
SETTINGS.put(ConfigType.LANG, new Lang(langConfig));
}
public static InjectionManager getInjectionManager() {
if (INJECTION_MANAGER == null)
throw new RuntimeException("InjectionManager is NULL!");
return INJECTION_MANAGER;
}
public static ScriptManager getScriptManager() {
if (SCRIPT_MANAGER == null || !ScriptLoader.SCRIPTING_ENABLED)
throw new RuntimeException("ScriptManager is NULL or scripting is disabled due to an error!");
return SCRIPT_MANAGER;
}
public <T extends Options> T getSettings(Class<T> settingsClass) {
for (Options options : SETTINGS.values()) {
if (options.getClass().equals(settingsClass)) {
return (T) options;
}
}
return null;
}
public Options getSettings(ConfigType configType) {
for (Map.Entry<ConfigType, Options> entry : SETTINGS.entrySet()) {
if (entry.getKey() == configType) {
return entry.getValue();
}
}
return null;
}
public YAMLConfig getConfig(ConfigType configType) {
return CONFIG_FILES.get(configType);
}
} | 13,553 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
ModuleLogger.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/ModuleLogger.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class ModuleLogger extends Logger {
private final String[] modulePath;
private final String prefix;
public ModuleLogger(String... modulePath) {
this(Bukkit.getLogger(), modulePath);
}
public ModuleLogger(Logger parent, String... modulePath) {
super(StringUtils.join(modulePath, "."), null);
this.setParent(parent);
this.setLevel(Level.ALL);
this.modulePath = modulePath;
StringBuilder builder = new StringBuilder();
for (String module : modulePath) {
builder.append("[").append(module).append("] ");
}
this.prefix = builder.toString();
}
public ModuleLogger getModule(String... path) {
return new ModuleLogger(this.getParent(), appendArray(this.modulePath, path));
}
@Override
public void log(LogRecord logRecord) {
logRecord.setMessage(this.prefix + logRecord.getMessage());
super.log(logRecord);
}
protected static boolean nullOrEmpty(Object[] array) {
return array == null || array.length != 0;
}
protected static boolean nullOrEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
protected static <T> T[] createArray(Class<T> type, int length) {
return (T[]) Array.newInstance(type, length);
}
protected static <T> T[] appendArray(T[] array, T... values) {
if (nullOrEmpty(array)) {
return values;
}
if (nullOrEmpty(values)) {
return array;
}
T[] rval = createArray((Class<T>) array.getClass().getComponentType(), array.length + values.length);
System.arraycopy(array, 0, rval, 0, array.length);
System.arraycopy(values, 0, rval, array.length, values.length);
return rval;
}
}
| 2,764 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
DependencyGraphUtil.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/data/DependencyGraphUtil.java | package com.dsh105.holoapi.data;
import com.captainbern.reflection.Reflection;
import com.captainbern.reflection.accessor.FieldAccessor;
import com.dsh105.holoapi.util.LogicUtil;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.SimplePluginManager;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class DependencyGraphUtil {
private static final FieldAccessor<Collection> pluginsField = new Reflection().reflect(SimplePluginManager.class).getSafeFieldByNameAndType("plugins", Collection.class).getAccessor();
public static Collection<Plugin> getPluginsUnsafe() {
final PluginManager man = Bukkit.getPluginManager();
if (man instanceof SimplePluginManager) {
return pluginsField.get(man);
} else {
return Arrays.asList(man.getPlugins());
}
}
public static boolean isDepending(Plugin plugin, Plugin depending) {
final List<String> dep = plugin.getDescription().getDepend();
return !LogicUtil.nullOrEmpty(dep) && dep.contains(depending.getName());
}
public static boolean isSoftDepending(Plugin plugin, Plugin depending) {
final List<String> dep = plugin.getDescription().getSoftDepend();
return !LogicUtil.nullOrEmpty(dep) && dep.contains(depending.getName());
}
}
| 1,397 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
FancyMessageFailedException.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/exceptions/FancyMessageFailedException.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.exceptions;
public class FancyMessageFailedException extends RuntimeException {
public FancyMessageFailedException() {
}
} | 834 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
ImageResourceNotFound.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/exceptions/ImageResourceNotFound.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.exceptions;
public class ImageResourceNotFound extends RuntimeException {
public ImageResourceNotFound(String s) {
super(s);
}
} | 848 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
ImageNotLoadedException.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/exceptions/ImageNotLoadedException.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.exceptions;
public class ImageNotLoadedException extends RuntimeException {
public ImageNotLoadedException(String customImageKey) {
super("Image not loaded: " + customImageKey);
}
} | 901 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
DuplicateSaveIdException.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/exceptions/DuplicateSaveIdException.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.exceptions;
public class DuplicateSaveIdException extends RuntimeException {
public DuplicateSaveIdException(String s) {
super(s);
}
} | 854 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
HologramNotPreparedException.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/exceptions/HologramNotPreparedException.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.exceptions;
public class HologramNotPreparedException extends RuntimeException {
public HologramNotPreparedException(String s) {
super(s);
}
} | 862 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
LangSetting.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/config/LangSetting.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.config;
import com.dsh105.holoapi.HoloAPI;
import com.dsh105.powermessage.markup.MarkupBuilder;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.conversations.Conversable;
import org.bukkit.entity.Player;
public class LangSetting extends Setting<String> {
public LangSetting(ConfigType configType, String path, String defaultValue, String... comments) {
super(configType, path, defaultValue, comments);
}
public LangSetting(String path, String defaultValue, String... comments) {
super(path, defaultValue, comments);
}
public String getValue(String... pairedReplacements) {
String message = super.getValue();
for (int i = 0; i < pairedReplacements.length; i += 2) {
if ((i + 1) >= pairedReplacements.length) {
break;
}
message = message.replace("%" + pairedReplacements[i] + "%", pairedReplacements[i + 1]);
}
if (message == null || message.isEmpty() || message.equalsIgnoreCase("NONE")) {
return null;
}
return ChatColor.translateAlternateColorCodes('&', HoloAPI.getCommandManager().getMessenger().format(message));
}
public void send(Player player, String... pairedReplacements) {
send((CommandSender) player, pairedReplacements);
}
// Not ideal, but it's easy to call
public void send(CommandSender sender, String... pairedReplacements) {
String message = getValue(pairedReplacements);
if (message == null) {
return;
}
new MarkupBuilder().withText(HoloAPI.getPrefix() + ChatColor.translateAlternateColorCodes('&', message)).build().send(sender);
}
public void send(Conversable conversable, String... pairedReplacements) {
send(conversable, getValue(pairedReplacements));
}
public static void send(CommandSender sender, String message) {
if (message == null) {
return;
}
new MarkupBuilder().withText(HoloAPI.getPrefix() + ChatColor.translateAlternateColorCodes('&', message)).build().send(sender);
}
public static void send(Conversable conversable, String message) {
if (conversable instanceof CommandSender) {
send((CommandSender) conversable, message);
return;
}
if (message != null) {
conversable.sendRawMessage(HoloAPI.getPrefix() + ChatColor.translateAlternateColorCodes('&', message));
}
}
} | 3,212 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
ConfigType.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/config/ConfigType.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.config;
public enum ConfigType {
MAIN("config.yml"), DATA("data.yml"), LANG("lang.yml");
private String path;
ConfigType(String path) {
this.path = path;
}
public String getPath() {
return path;
}
} | 944 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
Settings.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/config/Settings.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.config;
import com.dsh105.commodus.config.Options;
import com.dsh105.commodus.config.YAMLConfig;
import java.util.HashMap;
import java.util.Map;
public class Settings extends Options {
private HashMap<String, String> specialCharacters = new HashMap<>();
public Settings(YAMLConfig config) {
super(config);
}
private void prepareSpecialCharacters() {
specialCharacters = new HashMap<>();
String[] codes = {"x", "xx", "xxx", "xxxx", "/", "<3", ":)", ":(", "s", "*", "|"};
String[] characters = {"2591", "2592", "2593", "2588", "26A1", "2764", "263A", "2639", "2600", "2605", "23B9"};
for (int i = 0; i < codes.length && i < characters.length; i++) {
specialCharacters.put("[" + codes[i] + "]", characters[i]);
}
}
@Override
public void setDefaults() {
for (Setting setting : Setting.getOptions(Settings.class, Setting.class)) {
if (!setting.getPath().contains("%s")) {
set(setting);
}
}
// Special characters
prepareSpecialCharacters();
for (Map.Entry<String, String> entry : specialCharacters.entrySet()) {
set(SPECIAL_CHARACTER.getPath(entry.getKey()), entry.getValue());
}
// Indicators
String[] types = {"damage", "potion", "gainHealth", "exp"};
String[] damageTypes = {"drowning", "fire", "magic", "poison", "starvation", "thorns", "wither"};
String[] potionTypes = {"speed", "slow", "fast_digging", "slow_digging", "increase_damage", "heal", "harm", "jump", "confusion", "regeneration", "damage_resistance", "fire_resistance", "water_breathing", "invisibility", "blindness", "night_vision", "hunger", "weakness", "poison", "wither", "health_boost", "absorption", "saturation"};
for (String indicatorType : types) {
set(INDICATOR_ENABLE, indicatorType);
set(INDICATOR_Y_OFFSET, indicatorType);
set(INDICATOR_TIME_VISIBLE, indicatorType);
set(INDICATOR_FORMAT, indicatorType, "default");
if (!indicatorType.equalsIgnoreCase("EXP")) {
set(INDICATOR_SHOW_FOR_PLAYERS, indicatorType);
set(INDICATOR_SHOW_FOR_MOBS, indicatorType);
}
}
set(INDICATOR_FORMAT.getPath("damage", "default"), "&c&l");
for (String damageType : damageTypes) {
set(INDICATOR_ENABLE_TYPE, "damage", damageType);
set(INDICATOR_FORMAT.getPath("damage", damageType), "&c&l");
}
for (String potionType : potionTypes) {
set(INDICATOR_FORMAT.getPath("potion", potionType), "&e&l %effect% %amp%");
}
set(INDICATOR_FORMAT.getPath("potion", "goldenapple"), "&e&l+ %effect%");
set(INDICATOR_FORMAT.getPath("potion", "godapple"), "&e&l+ %effect% II");
}
public static final Setting<Boolean> DEBUGGING_ENABLED = new Setting<Boolean>("debugging.enabled", false);
public static final Setting<Integer> DEBUGGING_LEVEL = new Setting<Integer>("debugging.level", 10);
public static final Setting<String> COMMAND = new Setting<>("command", "holo");
public static final Setting<Boolean> USE_BUNGEE = new Setting<>("bungecord", false);
public static final Setting<Boolean> AUTO_UPDATE = new Setting<>("autoUpdate", false);
public static final Setting<Boolean> CHECK_FOR_UPDATES = new Setting<>("checkForUpdates", true);
public static final Setting<String> BASE_CHAT_COLOUR = new Setting<>("baseChatColour", "3");
public static final Setting<String> HIGHLIGHT_CHAT_COLOUR = new Setting<>("highlightChatColour", "b");
public static final Setting<Double> VERTICAL_LINE_SPACING = new Setting<>("verticalLineSpacing", 0.25D);
public static final Setting<String> TRANSPARENCY_WITH_BORDER = new Setting<>("transparency.withBorder", " &r ");
public static final Setting<String> TRANSPARENCY_WITHOUT_BORDER = new Setting<>("transparency.noBorder", " ");
public static final Setting<Integer> TIMEZONE_OFFSET = new Setting<>("timezone.offset", 0);
public static final Setting<Boolean> TIMEZONE_SHOW_ZONE_MARKER = new Setting<>("timezone.showZoneMarker", true);
public static final Setting<String> MULTICOLOR_CHARACTER = new Setting<>("multicolorFormat.character", "&s");
public static final Setting<String> MULTICOLOR_COLOURS = new Setting<>("multicolorFormat.colours", "&d,&5,&1,&9,&b,&a,&e,&6,&c,&3");
public static final Setting<Integer> MULTICOLOR_DELAY = new Setting<>("multicolorFormat.delay", 5);
public static final Setting<Boolean> CHATBUBBLES_SHOW = new Setting<>("chatBubbles.show", false);
public static final Setting<Boolean> CHATBUBBLES_RISE = new Setting<>("chatBubbles.rise", true);
public static final Setting<Boolean> CHATBUBBLES_FOLLOW_PLAYER = new Setting<>("chatBubbles.followPlayer", true);
public static final Setting<Boolean> CHATBUBBLES_SHOW_PLAYER_NAME = new Setting<>("chatBubbles.showPlayerName", true);
public static final Setting<String> CHATBUBBLES_NAME_FORMAT = new Setting<>("chatBubbles.nameFormat", "&6&o");
public static final Setting<Integer> CHATBUBBLES_DISPLAY_DURATION = new Setting<>("chatBubbles.displayDurationSeconds", 8);
public static final Setting<Integer> CHATBUBBLES_CHARACTERS_PER_LINE = new Setting<>("chatBubbles.charactersPerLine", 30);
public static final Setting<Double> CHATBUBBLES_DISTANCE_ABOVE = new Setting<>("chatBubbles.distanceAbovePlayerTag", 0.5D);
public static final Setting<Double> SPECIAL_CHARACTER = new Setting<>("specialCharacters.%s", 0.5D);
public static final Setting<Boolean> INDICATOR_ENABLE = new Setting<>("indicators.%s.enable", false);
public static final Setting<Boolean> INDICATOR_ENABLE_TYPE = new Setting<>("indicators.%s.enableType.%s", true);
public static final Setting<Double> INDICATOR_Y_OFFSET = new Setting<>("indicators.%s.yOffset", 2D);
public static final Setting<Integer> INDICATOR_TIME_VISIBLE = new Setting<>("indicators.%s.timeVisible", 4);
public static final Setting<String> INDICATOR_FORMAT = new Setting<>("indicators.%s.format.%s", "&a&l");
public static final Setting<Boolean> INDICATOR_SHOW_FOR_PLAYERS = new Setting<>("indicators.%s.showForPlayers", true);
public static final Setting<Boolean> INDICATOR_SHOW_FOR_MOBS = new Setting<>("indicators.%s.showForMobs", true);
} | 7,106 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
Setting.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/config/Setting.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.config;
import com.dsh105.commodus.config.Option;
import com.dsh105.holoapi.HoloAPI;
import java.util.ArrayList;
public class Setting<T> extends Option<T> {
private ConfigType configType;
public Setting(ConfigType configType, String path, String... comments) {
super(HoloAPI.getConfig(configType).config(), path, comments);
this.configType = configType;
}
public Setting(ConfigType configType, String path, T defaultValue, String... comments) {
super(HoloAPI.getConfig(configType).config(), path, defaultValue, comments);
this.configType = configType;
}
public Setting(String path, T defaultValue, String... comments) {
this(ConfigType.MAIN, path, defaultValue, comments);
}
public T getValue(Object... replacements) {
return super.getValue(HoloAPI.getSettings(configType), replacements);
}
public T getValue(T defaultValue, Object... replacements) {
return super.getValue(HoloAPI.getSettings(configType), defaultValue, replacements);
}
public void setValue(T value, Object... replacements) {
super.setValue(HoloAPI.getSettings(configType), value, replacements);
}
} | 1,894 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
Lang.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/config/Lang.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.config;
import com.dsh105.commodus.config.Options;
import com.dsh105.commodus.config.YAMLConfig;
public class Lang extends Options {
public Lang(YAMLConfig config) {
super(config);
}
@Override
public void setDefaults() {
for (LangSetting setting : Setting.getOptions(Lang.class, LangSetting.class)) {
set(setting.getPath(), setting.getDefaultValue(), setting.getComments());
}
}
public static LangSetting
UPDATE_NOT_AVAILABLE = new LangSetting("update_not_available", "{c1}An update is not available."),
HELP_INDEX_TOO_BIG = new LangSetting("help_index_too_big", "{c1}Page {c2}%index% {c1}does not exist."),
NOT_CONVERSABLE = new LangSetting("not_conversable", "{c1}Command Sender cannot be conversed with. Please use an alternate command with more arguments."),
NOT_LOCATION = new LangSetting("not_location", "{c1}Could not create Location. Please revise command arguments."),
NULL_PLAYER = new LangSetting("null_player", "{c2}%player% {c1}is not online. Please try a different Player."),
INT_ONLY = new LangSetting("int_only", "{c2}%string% {c1}must to be an integer."),
CONFIGS_RELOADED = new LangSetting("configs_reloaded", "{c1}Configuration files reloaded."),
PLUGIN_INFORMATION = new LangSetting("plugin_information", "{c1}Running HoloAPI v{c2}%version%{c1}. Use {c2}/" + Settings.COMMAND.getValue() + " help {c1}for help."),
LINE_INDEX_TOO_BIG = new LangSetting("line_index_too_big", "{c1}Line {c2}%index% {c1}does not exist."),
TIP_HOVER_PREVIEW = new LangSetting("hover_tip", "&e&oHover over to see a preview of the hologram. Click to insert teleport command."),
TIP_HOVER_COMMANDS = new LangSetting("hover_tip_commands", "&e&oHover over to see more information about the commands. Click to insert it into the chat window."),
IMAGE_LOADED = new LangSetting("url_image_loaded", "{c1}Custom URL image of key {c2}%key% loaded."),
ANIMATION_LOADED = new LangSetting("url_animation_loaded", "{c1}Custom URL animation of key {c2}%key% loaded."),
LOADING_URL_IMAGE = new LangSetting("loading_url_image", "{c1}Loading custom URL image of key {c2}%key%{c1}. Create hologram when the image has finished loading."),
LOADING_URL_ANIMATION = new LangSetting("loading_url_animation", "{c1}Loading custom URL animation of key {c2}%key%{c1}. Create hologram when the animation has finished loading."),
ACTIVE_DISPLAYS = new LangSetting("active_displays", "{c1}Active holograms:"),
IMAGES_NOT_LOADED = new LangSetting("images_not_loaded", "{c1}Images are not loaded yet. Try again later."),
INVALID_VISIBILITY = new LangSetting("invalid_invisibility", "{c2}%visibility% {c1}is not a registered visibility type."),
VALID_VISIBILITIES = new LangSetting("valid_invisibilities", "{c1}Valid visibilities are: {c2}%vis%{c1}."),
READING_TXT = new LangSetting("reading_txt", "{c1}Reading text from {c2}%url%{c1}..."),
INVALID_CLEAR_TYPE = new LangSetting("invalid_clear_type", "{c2}%type% {c1}is an invalid clear type. Valid types: {c2}%valid%"),
TOUCH_ACTIONS = new LangSetting("touch_actions", "{c1}Touch actions for hologram of ID {c2}%id%{c1}:"),
NO_TOUCH_ACTIONS = new LangSetting("no_touch_actions", "{c1}Hologram of ID {c2}%id% {c1}does not have any Touch Actions stored."),
TOUCH_ACTIONS_CLEARED = new LangSetting("touch_actions_cleared", "{c1}Touch Actions for Hologram of ID {c2}%id% {c1}cleared."),
COMMAND_TOUCH_ACTION_ADDED = new LangSetting("command_touch_action_added", "{c1}Touch Action for command {c2}%command% {c1}added to hologram of ID {c2}%id%{c1}."),
COMMAND_TOUCH_ACTION_REMOVED = new LangSetting("command_touch_action_removed", "{c1}Touch Action for command {c2}%command% {c1}removed from hologram of ID {c2}%id%{c1}."),
TOUCH_ACTION_REMOVED = new LangSetting("touch_action_removed", "{c1}Touch Action of ID {c2}%touchid% {c1}removed from hologram of ID {c2}%id%{c1}."),
TOUCH_ACTION_NOT_FOUND = new LangSetting("touch_action_not_found", "{c1}Touch Action of ID {c2}%touchid% {c1}not found."),
FAILED_IMAGE_LOAD = new LangSetting("failed_image_load", "{c1}Failed to load custom image. Make sure that it is correctly configured in {c2}config.yml{c1}."),
FAILED_ANIMATION_LOAD = new LangSetting("failed_animation_load", "{c1}Failed to load custom animation. Make sure that it is correctly configured in {c2}config.yml{c1}."),
IMAGE_NOT_FOUND = new LangSetting("image_not_found", "{c1}Image generator {c1}not found."),
HOLOGRAM_NOT_FOUND = new LangSetting("hologram_not_found", "{c1}Hologram of ID {c2}%id% {c1}not found."),
NO_ACTIVE_HOLOGRAMS = new LangSetting("no_active_holograms", "{c1}There are currently no active holograms."),
HOLOGRAM_CREATED = new LangSetting("hologram_created", "{c1}Hologram of ID {c2}%id% {c1}created."),
HOLOGRAM_REMOVED_MEMORY = new LangSetting("hologram_removed_memory", "{c1}Hologram of ID {c2}%id% {c1}removed from memory."),
HOLOGRAM_CLEARED_FILE = new LangSetting("hologram_cleared_file", "{c1}Hologram of ID {c2}%id% {c1}cleared from file and memory."),
HOLOGRAM_MOVED = new LangSetting("hologram_moved", "{c1}Hologram position moved."),
HOLOGRAM_RELOAD = new LangSetting("hologram_reload", "{c1}Performing manual reload of all holograms and images..."),
HOLOGRAM_TELEPORT_TO = new LangSetting("hologram_teleport_to", "{c1}You have been teleported to the hologram of ID {c2}%id%{c1}."),
HOLOGRAM_UPDATE_LINE = new LangSetting("hologram_update_line", "{c1}Line {c2}%index% {c1}has been updated to &r%input%{c1}."),
HOLOGRAM_REFRESH = new LangSetting("hologram_refresh", "{c1}Hologram of ID {c2}%id% {c1}refreshed."),
HOLOGRAMS_REFRESHED = new LangSetting("holograms_refreshed", "{c1}All holograms refreshed."),
HOLOGRAM_COPIED = new LangSetting("hologram_copied", "{c1}Hologram of ID {c2}%id% {c1}copied."),
HOLOGRAM_ANIMATED_COPIED = new LangSetting("hologram_animated_copied", "{c1}Animated Hologram of ID {c2}%id% {c1}copied."),
HOLOGRAM_NEARBY = new LangSetting("hologram_nearby", "{c1}Holograms within a radius of {c2}%radius%{c1}:"),
HOLOGRAM_ADDED_LINE = new LangSetting("hologram_added_line", "{c1}Line added to hologram of ID {c2}%id%{c1}."),
HOLOGRAM_ADD_LINE_ANIMATED = new LangSetting("hologram_add_line_animated", "{c1}Lines cannot be added to Animated Holograms."),
HOLOGRAM_VISIBILITY_SET = new LangSetting("hologram_visibility_set", "{c1}Visibility of Hologram of ID {c2}%id% {c1}set to {c2}%visibility%{c1}."),
HOLOGRAM_VISIBILITY_UNREGISTERED = new LangSetting("hologram_visibility_unregistered", "{c1}Hologram of ID {c2}%id% {c1}has an unknown or unregistered visibility."),
HOLOGRAM_VISIBILITY = new LangSetting("hologram_visibility", "{c1}Visibility of Hologram of ID {c2}%id% {c1}is registered as {c2}%visibility%{c1}."),
HOLOGRAM_ALREADY_SEE = new LangSetting("hologram_already_see", "{c2}%player% {c1}can already see Hologram {c2}%id%{c1}."),
HOLOGRAM_ALREADY_NOT_SEE = new LangSetting("hologram_already_not_see", "{c1}Hologram {c2}%id% {c1}is already hidden for {c2}%player%{c1}."),
HOLOGRAM_SHOW = new LangSetting("hologram_show", "{c2}%player% {c1}can now see Hologram {c2}%id%{c1}."),
HOLOGRAM_HIDE = new LangSetting("hologram_hide", "{c1}Hologram {c2}%id% {c1}hidden for {c2}%player%{c1}."),
HOLOGRAM_DUPLICATE_ID = new LangSetting("hologram_duplicate_id", "{c1}Hologram save IDs must be unique. A hologram of ID {c2}%id% {c1}already exists in the HoloAPI data files!"),
HOLOGRAM_SET_ID = new LangSetting("hologram_set_id", "{c1}Save ID of hologram {c2}%oldid% {c1}set to {c2}%newid%{c1}."),
NO_NEARBY_HOLOGRAMS = new LangSetting("no_nearby_holograms", "{c1}There are no holograms within a radius of {c2}%radius%{c1}."),
COMPLEX_HOLOGRAMS_CLEARED = new LangSetting("complex_holograms_cleared", "{c1}All complex holograms cleared."),
SIMPLE_HOLOGRAMS_CLEARED = new LangSetting("simple_holograms_cleared", "{c1}All simple holograms cleared."),
ALL_HOLOGRAMS_CLEARED = new LangSetting("all_holograms_cleared", "{c1}All holograms cleared."),
YES_NO_INPUT_INVALID = new LangSetting("yes_no_input_invalid", "{c1}Please enter either {c2}Yes {c1}or {c2}No{c1}."),
YES_NO_CLEAR_FROM_FILE = new LangSetting("yes_no_clear_from_file", "{c1}Would you like to clear this hologram from the save file? Please enter either {c2}Yes {c1}or {c2}No{c1}."),
YES_NO_COMMAND_TOUCH_ACTION_AS_CONSOLE = new LangSetting("yes_no_command_touch_action_as_console", "{c1}Should this command be executed as the console? Please enter either {c2}Yes {c1}or {c2}No{c1}."),
PROMPT_UPDATE_LINE = new LangSetting("prompt_update_line", "{c1}What do you want to set this line to?"),
PROMPT_DELAY = new LangSetting("prompt_delay", "{c1}Enter the desired delay (in ticks) of the frames in the new animated hologram."),
PROMPT_INPUT = new LangSetting("prompt_input", "{c1}Enter the desired lines of the new hologram. Enter {c2}Done {c1}when finished."),
PROMPT_INPUT_FRAMES = new LangSetting("prompt_input_frames", "{c1}Enter the desired lines of the new animated hologram. Enter {c2}Done {c1}when finished or {c2}Next {c1}to start building the next frame."),
PROMPT_INPUT_NEXT = new LangSetting("prompt_input_next", "{c1}Added new line: &r%input%{c1}. Enter next line."),
PROMPT_INPUT_FAIL = new LangSetting("prompt_input_fail", "{c1}Hologram lines cannot be empty. Retry or enter {c2}Exit {c1} to cancel."),
PROMPT_INPUT_INVALID = new LangSetting("prompt_input_invalid", "{c1}Input invalid."),
PROMPT_NEXT_FRAME = new LangSetting("prompt_next_frame", "{c1}Frame %num% selected. Enter first line."),
PROMPT_FIND_LOCATION = new LangSetting("prompt_find_location", "{c1}Enter the location of the new hologram in the following format: {c2}world x y z{c1}."),
PROMPT_INPUT_FAIL_INT = new LangSetting("prompt_input_fail_int", "{c1}X, Y and Z coordinates must be integers."),
PROMPT_INPUT_FAIL_WORLD = new LangSetting("prompt_input_fail_world", "{c2}%world% {c1}world doesn't exist. Please re-enter the location."),
PROMPT_INPUT_FAIL_FORMAT = new LangSetting("prompt_input_fail_format", "{c1}Please use the following format: {c2}world x y z{c1}."),
PROMPT_ENTER_NEW_LINE = new LangSetting("prompt_enter_new_line", "{c1}Enter the new line for the hologram."),
PROMPT_SCRIPT_TYPE = new LangSetting("prompt_script_type", "{c1}What type of script would you like to build? ({c2}touch {c1} or {c2}format{c1})."),
PROMPT_SCRIPT_VALID_TYPE = new LangSetting("prompt_script_valid_type", "{c1}Please specify a {c2}valid {c1}script type ({c2}touch {c1} or {c2}format{c1})."),
PROMPT_SCRIPT_ENTER = new LangSetting("prompt_script_enter", "{c1}Begin defining your script:"),
PROMPT_SCRIPT_LINE_CHANGE = new LangSetting("prompt_script_line_change", "{c1}Now editing line {c2}%line%{c1}."),
PROMPT_SCRIPT_NOT_EDITING = new LangSetting("prompt_script_not_editing", "{c1}You are not currently editing a script!"),
BUILDER_EMPTY_LINES = new LangSetting("hologram_not_created", "{c1}The hologram was not created as it was empty."),
BUILDER_INPUT_FAIL_TEXT_IMAGE = new LangSetting("builder_input_fail_text_image", "{c1}Enter a valid line type ({c2}Text {c1}or {c2}Image{c1})."),
BUILDER_INPUT_FIRST = new LangSetting("builder_input_fail_text_image", "{c1}Enter type for next line ({c2}Text {c1}or {c2}Image{c1})."),
BUILDER_INPUT_LINE_DATA = new LangSetting("builder_input_line_data", "{c1}What would you like this line to say?"),
BUILDER_INPUT_IMAGE_PATH = new LangSetting("builder_input_image_path", "{c1}What image do you want to add?"),
BUILDER_INPUT_NEXT_WITH_NUMBER = new LangSetting("builder_input_next_with_number", "{c1}Added %line% line. Enter type for next line ({c2}Text {c1} or {c2}Image).");
} | 13,181 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
InputFactory.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/InputFactory.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation;
import com.dsh105.holoapi.HoloAPI;
import org.bukkit.conversations.ConversationFactory;
public class InputFactory {
public static ConversationFactory buildBasicConversation() {
return new ConversationFactory(HoloAPI.getCore())
.withModality(true)
.withLocalEcho(false)
.withPrefix(new InputConversationPrefix())
.withTimeout(90)
.withEscapeSequence("exit");
}
} | 1,176 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
InputConversationPrefix.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/InputConversationPrefix.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation;
import com.dsh105.holoapi.HoloAPI;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.ConversationPrefix;
public class InputConversationPrefix implements ConversationPrefix {
@Override
public String getPrefix(ConversationContext conversationContext) {
return HoloAPI.getPrefix("HoloAPI") + "••• ";
}
} | 1,080 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
InputPrompt.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/InputPrompt.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation;
import com.dsh105.holoapi.config.Lang;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.Prompt;
import org.bukkit.conversations.ValidatingPrompt;
import org.bukkit.entity.Player;
import java.util.ArrayList;
public class InputPrompt extends ValidatingPrompt {
private ArrayList<String> lines = new ArrayList<>();
private String lastAdded;
private boolean first = true;
private InputSuccessPrompt successPrompt = new InputSuccessPrompt();
public InputPrompt() {
}
public InputPrompt(InputSuccessPrompt successPrompt) {
this.successPrompt = successPrompt;
}
public InputPrompt(ArrayList<String> lines, InputSuccessPrompt successPrompt, String lastAdded) {
this.lines = lines;
this.successPrompt = successPrompt;
this.lastAdded = lastAdded;
this.first = false;
}
@Override
protected boolean isInputValid(ConversationContext conversationContext, String s) {
return !(this.first && s.equalsIgnoreCase("DONE"));
}
@Override
protected Prompt acceptValidatedInput(ConversationContext conversationContext, String s) {
Object findLoc = conversationContext.getSessionData("findloc");
if (findLoc != null && ((Boolean) findLoc)) {
if (s.contains(" ")) {
String[] split = s.split("\\s");
if (split.length == 4) {
if (Bukkit.getWorld(split[0]) != null) {
try {
conversationContext.setSessionData("location", new Location(Bukkit.getWorld(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3])));
return this.successPrompt;
} catch (NumberFormatException e) {
conversationContext.setSessionData("fail_int", true);
}
} else {
conversationContext.setSessionData("fail_world", true);
}
} else {
conversationContext.setSessionData("fail_format", true);
}
} else {
conversationContext.setSessionData("fail_format", true);
}
} else if (s.equalsIgnoreCase("DONE")) {
conversationContext.setSessionData("lines", this.lines.toArray(new String[this.lines.size()]));
if (conversationContext.getSessionData("location") == null) {
if (conversationContext.getForWhom() instanceof Player) {
conversationContext.setSessionData("location", ((Player) conversationContext.getForWhom()).getLocation());
return this.successPrompt;
} else {
conversationContext.setSessionData("findloc", true);
}
} else {
return this.successPrompt;
}
} else {
this.lines.add(s);
}
return new InputPrompt(this.lines, this.successPrompt, s);
}
@Override
public String getPromptText(ConversationContext conversationContext) {
Object findLoc = conversationContext.getSessionData("findloc");
if (findLoc != null && ((Boolean) findLoc)) {
return Lang.PROMPT_FIND_LOCATION.getValue();
}
if (this.first) {
return Lang.PROMPT_INPUT.getValue();
} else
return Lang.PROMPT_INPUT_NEXT.getValue("input", ChatColor.translateAlternateColorCodes('&', this.lastAdded));
}
@Override
protected String getFailedValidationText(ConversationContext context, String invalidInput) {
Object failInt = context.getSessionData("fail_int");
Object failFormat = context.getSessionData("fail_format");
Object failWorld = context.getSessionData("fail_world");
if (failInt != null && ((Boolean) failInt)) {
return Lang.PROMPT_INPUT_FAIL_INT.getValue();
} else if (failFormat != null && (Boolean) failFormat) {
return Lang.PROMPT_INPUT_FAIL_FORMAT.getValue();
} else if (failWorld != null && (Boolean) failWorld) {
return Lang.PROMPT_INPUT_FAIL_WORLD.getValue("world", invalidInput.split(" ")[0]);
}
return Lang.PROMPT_INPUT_FAIL.getValue();
}
}
| 5,159 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
InputSuccessPrompt.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/InputSuccessPrompt.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation;
import com.dsh105.holoapi.HoloAPI;
import com.dsh105.holoapi.api.Hologram;
import com.dsh105.holoapi.api.HologramFactory;
import com.dsh105.holoapi.config.Lang;
import org.bukkit.Location;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.MessagePrompt;
import org.bukkit.conversations.Prompt;
public class InputSuccessPrompt extends MessagePrompt {
@Override
protected Prompt getNextPrompt(ConversationContext conversationContext) {
return END_OF_CONVERSATION;
}
@Override
public String getPromptText(ConversationContext conversationContext) {
String[] lines = (String[]) conversationContext.getSessionData("lines");
Location location = (Location) conversationContext.getSessionData("location");
Hologram h = new HologramFactory(HoloAPI.getCore()).withText(lines).withLocation(location).build();
return Lang.HOLOGRAM_CREATED.getValue("id", h.getSaveId());
}
} | 1,679 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
SimpleInputPrompt.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/basic/SimpleInputPrompt.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation.basic;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.Prompt;
import org.bukkit.conversations.ValidatingPrompt;
public class SimpleInputPrompt extends ValidatingPrompt {
private SimpleInputFunction function;
private SimpleInputSuccessPrompt successPrompt;
public SimpleInputPrompt(SimpleInputFunction function) {
this.function = function;
}
public SimpleInputPrompt(SimpleInputFunction function, SimpleInputSuccessPrompt successPrompt) {
this.function = function;
this.successPrompt = successPrompt;
}
@Override
protected boolean isInputValid(ConversationContext conversationContext, String s) {
return this.function.isValid(conversationContext, s);
}
@Override
protected Prompt acceptValidatedInput(ConversationContext context, String input) {
Prompt next = this.function.function(context, input);
if (next != null) {
return next;
}
return this.successPrompt != null ? this.successPrompt : new SimpleInputSuccessPrompt(this.function.getSuccessMessage(context, input));
}
@Override
public String getPromptText(ConversationContext context) {
return this.function.getPromptText(context);
}
@Override
protected String getFailedValidationText(ConversationContext context, String invalidInput) {
return this.function.getFailedText(context, invalidInput);
}
} | 2,179 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
SimpleInputReturningFunction.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/basic/SimpleInputReturningFunction.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation.basic;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.Prompt;
public abstract class SimpleInputReturningFunction extends SimpleInputFunction {
private String input;
@Override
public String getInput() {
return input;
}
@Override
protected Prompt function(ConversationContext context, String input) {
this.input = input;
return this.onFunctionRequest(context, input);
}
public abstract Prompt onFunctionRequest(ConversationContext context, String input);
} | 1,269 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
YesNoFunction.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/basic/YesNoFunction.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation.basic;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.conversations.ConversationContext;
public abstract class YesNoFunction extends SimpleInputFunction {
@Override
public boolean isValid(ConversationContext conversationContext, String input) {
String[] accepted = {"true", "false", "on", "off", "yes", "no"};
return ArrayUtils.contains(accepted, input.toLowerCase());
}
} | 1,132 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
LocationFunction.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/basic/LocationFunction.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation.basic;
import com.dsh105.commodus.GeneralUtil;
import com.dsh105.holoapi.config.Lang;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.conversations.ConversationContext;
public abstract class LocationFunction extends SimpleInputFunction {
private Location location;
@Override
public boolean isValid(ConversationContext context, String input) {
if (input.contains(" ")) {
String[] split = input.split("\\s");
if (split.length == 4) {
if (Bukkit.getWorld(split[0]) != null) {
for (int i = 1; i <= 3; i++) {
if (!GeneralUtil.isInt(split[i])) {
context.setSessionData("fail_int", true);
return false;
}
}
this.location = new Location(Bukkit.getWorld(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]));
} else {
context.setSessionData("fail_world", true);
return false;
}
} else {
context.setSessionData("fail_format", true);
return false;
}
} else {
context.setSessionData("fail_format", true);
return false;
}
return true;
}
@Override
public String getPromptText(ConversationContext context) {
return Lang.PROMPT_FIND_LOCATION.getValue();
}
@Override
public String getFailedText(ConversationContext context, String invalidInput) {
Object failInt = context.getSessionData("fail_int");
Object failFormat = context.getSessionData("fail_format");
Object failWorld = context.getSessionData("fail_world");
if (failInt != null && ((Boolean) failInt)) {
return Lang.PROMPT_INPUT_FAIL_INT.getValue();
} else if (failFormat != null && (Boolean) failFormat) {
return Lang.PROMPT_INPUT_FAIL_FORMAT.getValue();
} else if (failWorld != null && (Boolean) failWorld) {
return Lang.PROMPT_INPUT_FAIL_WORLD.getValue("world", invalidInput.split("\\s")[0]);
}
return "";
}
public Location getLocation() {
return location;
}
} | 3,043 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
SimpleInputFunction.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/basic/SimpleInputFunction.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation.basic;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.Prompt;
public abstract class SimpleInputFunction {
private String input;
public String getInput() {
return input;
}
protected Prompt function(ConversationContext context, String input) {
this.input = input;
this.onFunction(context, input);
return null;
}
public abstract void onFunction(ConversationContext context, String input);
public abstract String getSuccessMessage(ConversationContext context, String input);
public abstract String getPromptText(ConversationContext context);
public abstract String getFailedText(ConversationContext context, String invalidInput);
public boolean isValid(ConversationContext conversationContext, String s) {
return true;
}
} | 1,565 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
SimpleInputSuccessPrompt.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/basic/SimpleInputSuccessPrompt.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation.basic;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.MessagePrompt;
import org.bukkit.conversations.Prompt;
public class SimpleInputSuccessPrompt extends MessagePrompt {
private String successMessage;
public SimpleInputSuccessPrompt(String successMessage) {
this.successMessage = successMessage;
}
@Override
protected Prompt getNextPrompt(ConversationContext conversationContext) {
return END_OF_CONVERSATION;
}
@Override
public String getPromptText(ConversationContext conversationContext) {
return this.successMessage;
}
} | 1,344 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
ScriptBuilderSuccess.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/script/ScriptBuilderSuccess.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation.script;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.MessagePrompt;
import org.bukkit.conversations.Prompt;
import java.util.List;
public class ScriptBuilderSuccess extends MessagePrompt {
private List<String> lines;
private String scriptName;
public ScriptBuilderSuccess(List<String> lines, String scriptName) {
this.lines = lines;
this.scriptName = scriptName;
}
@Override
protected Prompt getNextPrompt(ConversationContext context) {
return END_OF_CONVERSATION;
}
@Override
public String getPromptText(ConversationContext context) {
// TODO: Apply scripting stuff here
return null;
}
} | 1,430 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
ScriptBuilderPrompt.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/script/ScriptBuilderPrompt.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation.script;
import com.dsh105.commodus.StringUtil;
import com.dsh105.holoapi.config.LangSetting;
import com.dsh105.powermessage.core.PowerMessage;
import org.bukkit.ChatColor;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.Prompt;
import org.bukkit.conversations.StringPrompt;
import java.util.ArrayList;
import java.util.List;
public class ScriptBuilderPrompt extends StringPrompt {
private String type;
private String scriptName;
private List<String> lines = new ArrayList<>();
private int currentlyEditing = 0;
public ScriptBuilderPrompt(String type, String scriptName) {
this.type = type;
this.scriptName = scriptName;
}
public String getType() {
return type;
}
public void setCurrentlyEditing(int currentlyEditing) {
this.currentlyEditing = currentlyEditing;
}
public int getCurrentlyEditing() {
return currentlyEditing;
}
public String[] buildCompiledOutput() {
return new ArrayList<>(lines).toArray(StringUtil.EMPTY_STRING_ARRAY);
}
@Override
public Prompt acceptInput(ConversationContext context, String input) {
if (input.equalsIgnoreCase("DONE")) {
LangSetting.send(context.getForWhom(), "}");
return new ScriptBuilderSuccess(this.lines, this.scriptName);
}
this.lines.add(currentlyEditing, input);
return this;
}
@Override
public String getPromptText(ConversationContext context) {
if (this.currentlyEditing == 0 && lines.isEmpty()) {
return ChatColor.DARK_AQUA + "function(hologram, player) {";
}
int edit = currentlyEditing;
currentlyEditing = lines.size() - 1;
return new PowerMessage().then(edit).colour(ChatColor.DARK_AQUA).then(lines.get(edit)).colour(ChatColor.AQUA).group().tooltip(buildCompiledOutput()).tooltip(ChatColor.YELLOW + "" + ChatColor.ITALIC + "Click to edit this line").perform("script editcurrent " + edit).exit().toJson();
}
} | 2,757 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
BuilderInputSuccessPrompt.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/builder/BuilderInputSuccessPrompt.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation.builder;
import com.dsh105.holoapi.HoloAPI;
import com.dsh105.holoapi.api.Hologram;
import com.dsh105.holoapi.api.HologramFactory;
import com.dsh105.holoapi.config.Lang;
import com.dsh105.holoapi.image.ImageGenerator;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.MessagePrompt;
import org.bukkit.conversations.Prompt;
import org.bukkit.entity.Player;
import java.util.ArrayList;
public class BuilderInputSuccessPrompt extends MessagePrompt {
@Override
protected Prompt getNextPrompt(ConversationContext conversationContext) {
return END_OF_CONVERSATION;
}
@Override
public String getPromptText(ConversationContext conversationContext) {
ArrayList<HoloInputBuilder> builders = (ArrayList<HoloInputBuilder>) conversationContext.getSessionData("builders");
//ArrayList<String> lines = new ArrayList<String>();
HologramFactory hf = new HologramFactory(HoloAPI.getCore());
for (HoloInputBuilder b : builders) {
if (b.getType() == null || b.getLineData() == null) {
continue;
}
if (b.getType().equalsIgnoreCase("IMAGE")) {
ImageGenerator gen = HoloAPI.getImageLoader().getGenerator(b.getLineData());
if (gen == null) {
continue;
}
hf.withImage(gen);
} else {
hf.withText(b.getLineData());
}
}
if (hf.isEmpty()) {
return Lang.BUILDER_EMPTY_LINES.getValue();
}
hf.withLocation(((Player) conversationContext.getForWhom()).getLocation());
Hologram h = hf.build();
return Lang.HOLOGRAM_CREATED.getValue("id", h.getSaveId());
}
} | 2,477 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
HoloInputBuilder.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/builder/HoloInputBuilder.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation.builder;
public class HoloInputBuilder {
private String type;
private String lineData;
public HoloInputBuilder() {
}
public HoloInputBuilder(String type, String lineData) {
this.type = type;
this.lineData = lineData;
}
public HoloInputBuilder withType(String type) {
this.type = type;
return this;
}
public HoloInputBuilder withLineData(String lineData) {
this.lineData = lineData;
return this;
}
public String getType() {
return type;
}
public String getLineData() {
return lineData;
}
} | 1,331 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
BuilderInputPrompt.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/builder/BuilderInputPrompt.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation.builder;
import com.dsh105.holoapi.HoloAPI;
import com.dsh105.holoapi.api.Hologram;
import com.dsh105.holoapi.api.HologramFactory;
import com.dsh105.holoapi.config.Lang;
import com.dsh105.holoapi.conversation.basic.LocationFunction;
import com.dsh105.holoapi.conversation.basic.SimpleInputPrompt;
import com.dsh105.holoapi.image.ImageGenerator;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.Prompt;
import org.bukkit.conversations.ValidatingPrompt;
import org.bukkit.entity.Player;
import java.util.ArrayList;
public class BuilderInputPrompt extends ValidatingPrompt {
private ArrayList<HoloInputBuilder> builders = new ArrayList<HoloInputBuilder>();
private HoloInputBuilder currentBuilder;
//private boolean success;
private boolean b = true;
public BuilderInputPrompt() {
}
private BuilderInputPrompt(HoloInputBuilder currentBuilder, ArrayList<HoloInputBuilder> builders, boolean b) {
this.currentBuilder = currentBuilder;
this.builders = builders;
this.b = b;
}
private BuilderInputPrompt(HoloInputBuilder currentBuilder, ArrayList<HoloInputBuilder> builders) {
this.currentBuilder = currentBuilder;
this.builders = builders;
}
public BuilderInputPrompt(ArrayList<HoloInputBuilder> builders) {
this.builders = builders;
}
@Override
protected boolean isInputValid(ConversationContext conversationContext, String s) {
if (s.equalsIgnoreCase("DONE")) {
return true;
}
return this.currentBuilder != null || s.equalsIgnoreCase("TEXT") || s.equalsIgnoreCase("IMAGE");
}
@Override
protected Prompt acceptValidatedInput(ConversationContext context, String s) {
if (s.equalsIgnoreCase("DONE")) {
context.setSessionData("builders", this.builders);
if (context.getForWhom() instanceof Player) {
return new BuilderInputSuccessPrompt();
} else {
new SimpleInputPrompt(new LocationFunction() {
Hologram h;
boolean success;
@Override
public void onFunction(ConversationContext context, String input) {
ArrayList<HoloInputBuilder> builders = (ArrayList<HoloInputBuilder>) context.getSessionData("builders");
//ArrayList<String> lines = new ArrayList<String>();
HologramFactory hf = new HologramFactory(HoloAPI.getCore()).withLocation(this.getLocation());
for (HoloInputBuilder b : builders) {
if (b.getType() == null || b.getLineData() == null) {
continue;
}
if (b.getType().equalsIgnoreCase("IMAGE")) {
ImageGenerator gen = HoloAPI.getImageLoader().getGenerator(b.getLineData());
if (gen == null) {
continue;
}
hf.withImage(gen);
} else {
hf.withText(b.getLineData());
}
}
if (hf.isEmpty()) {
success = false;
return;
}
h = hf.build();
success = true;
}
@Override
public String getSuccessMessage(ConversationContext context, String input) {
return success ? Lang.HOLOGRAM_CREATED.getValue("id", h.getSaveId()) : Lang.BUILDER_EMPTY_LINES.getValue();
}
});
}
return END_OF_CONVERSATION;
}
if (currentBuilder == null) {
String type = s.toUpperCase();
if (type.equalsIgnoreCase("TEXT") || type.equalsIgnoreCase("IMAGE")) {
//this.success = true;
this.currentBuilder = new HoloInputBuilder().withType(type);
return new BuilderInputPrompt(this.currentBuilder, this.builders);
}
} else {
if (this.currentBuilder.getType().equalsIgnoreCase("TEXT")) {
//this.success = true;
if (s.equalsIgnoreCase("none")) {
this.builders.add(this.currentBuilder.withLineData(" "));
} else {
this.builders.add(this.currentBuilder.withLineData(s));
}
return new BuilderInputPrompt(this.builders);
} else if (this.currentBuilder.getType().equalsIgnoreCase("IMAGE")) {
if (HoloAPI.getImageLoader().exists(s) || HoloAPI.getImageLoader().existsAsUnloadedUrl(s)) {
//this.success = true;
this.builders.add(this.currentBuilder.withLineData(s));
return new BuilderInputPrompt(this.builders);
} else {
return new BuilderInputPrompt(this.currentBuilder, this.builders, false);
}
}
}
return new BuilderInputPrompt(this.builders);
}
@Override
public String getPromptText(ConversationContext conversationContext) {
if (this.currentBuilder != null) {
if (this.currentBuilder.getLineData() == null) {
return this.currentBuilder.getType().equalsIgnoreCase("TEXT") ? Lang.BUILDER_INPUT_LINE_DATA.getValue() : Lang.BUILDER_INPUT_IMAGE_PATH.getValue();
} else {
if (b) {
int size = this.builders.size();
return Lang.BUILDER_INPUT_NEXT_WITH_NUMBER.getValue("line", size + (size == 1 ? "st" : (size == 2 ? "nd" : (size == 3 ? "rd" : "4th"))));
} else {
return Lang.IMAGE_NOT_FOUND.getValue();
}
}
} else {
return Lang.BUILDER_INPUT_FIRST.getValue();
}
}
@Override
protected String getFailedValidationText(ConversationContext context, String invalidInput) {
return Lang.BUILDER_INPUT_FAIL_TEXT_IMAGE.getValue();
}
} | 7,058 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
AnimationBuilderInputPrompt.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/builder/animation/AnimationBuilderInputPrompt.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation.builder.animation;
import com.dsh105.commodus.GeneralUtil;
import com.dsh105.holoapi.HoloAPI;
import com.dsh105.holoapi.api.AnimatedHologram;
import com.dsh105.holoapi.api.AnimatedHologramFactory;
import com.dsh105.holoapi.config.Lang;
import com.dsh105.holoapi.conversation.basic.LocationFunction;
import com.dsh105.holoapi.conversation.basic.SimpleInputPrompt;
import com.dsh105.holoapi.image.AnimatedTextGenerator;
import com.dsh105.holoapi.image.Frame;
import org.bukkit.ChatColor;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.Prompt;
import org.bukkit.conversations.ValidatingPrompt;
import org.bukkit.entity.Player;
import java.util.ArrayList;
public class AnimationBuilderInputPrompt extends ValidatingPrompt {
private boolean first = true;
private ArrayList<String> lines;
private ArrayList<Frame> frames;
public AnimationBuilderInputPrompt() {
this.lines = new ArrayList<>();
this.frames = new ArrayList<>();
}
public AnimationBuilderInputPrompt(ArrayList<String> lines, ArrayList<Frame> frames) {
this.lines = lines;
this.frames = frames;
this.first = false;
}
@Override
protected boolean isInputValid(ConversationContext conversationContext, String s) {
if (conversationContext.getSessionData("askingForDelay") == null) {
conversationContext.setSessionData("askingForDelay", false);
}
if (conversationContext.getSessionData("nextFrame") == null) {
conversationContext.setSessionData("nextFrame", false);
}
return !((Boolean) conversationContext.getSessionData("askingForDelay") && !GeneralUtil.isInt(s)) && !(this.first && s.equalsIgnoreCase("DONE")) && !(s.equalsIgnoreCase("NEXT") && this.lines.isEmpty());
}
@Override
protected Prompt acceptValidatedInput(final ConversationContext context, final String s) {
if ((Boolean) context.getSessionData("askingForDelay")) {
if (GeneralUtil.isInt(s)) {
if (context.getForWhom() instanceof Player) {
return new AnimationBuilderInputSuccessPrompt(this.frames, Integer.parseInt(s));
} else {
new SimpleInputPrompt(new LocationFunction() {
AnimatedHologram h;
@Override
public void onFunction(ConversationContext context, String input) {
context.setSessionData("location", this.getLocation());
ArrayList<Frame> frames = new ArrayList<>();
for (Frame f : frames) {
frames.add(new Frame(Integer.parseInt(s), f.getLines()));
}
try {
h = new AnimatedHologramFactory(HoloAPI.getCore()).withText(new AnimatedTextGenerator(frames.toArray(new Frame[frames.size()]))).withLocation(this.getLocation()).build();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String getSuccessMessage(ConversationContext context, String input) {
return Lang.HOLOGRAM_CREATED.getValue("id", h.getSaveId());
}
});
}
return END_OF_CONVERSATION;
}
}
if (s.equalsIgnoreCase("DONE")) {
if (!this.lines.isEmpty()) {
this.frames.add(new Frame(5, this.lines.toArray(new String[this.lines.size()])));
this.lines.clear();
}
context.setSessionData("askingForDelay", true);
return new AnimationBuilderInputPrompt(this.lines, this.frames);
}
if (s.equalsIgnoreCase("NEXT")) {
if (this.lines.isEmpty()) {
return new AnimationBuilderInputPrompt(this.lines, this.frames);
}
this.frames.add(new Frame(5, this.lines.toArray(new String[this.lines.size()])));
this.lines.clear();
context.setSessionData("nextFrame", true);
return new AnimationBuilderInputPrompt(this.lines, this.frames);
}
context.setSessionData("lastAdded", s);
this.lines.add(s);
return new AnimationBuilderInputPrompt(this.lines, this.frames);
}
@Override
public String getPromptText(ConversationContext conversationContext) {
if (conversationContext.getSessionData("askingForDelay") == null) {
conversationContext.setSessionData("askingForDelay", false);
}
if (conversationContext.getSessionData("nextFrame") == null) {
conversationContext.setSessionData("nextFrame", false);
}
if ((Boolean) conversationContext.getSessionData("askingForDelay")) {
return Lang.PROMPT_DELAY.getValue();
}
if ((Boolean) conversationContext.getSessionData("nextFrame")) {
conversationContext.setSessionData("nextFrame", false);
return Lang.PROMPT_NEXT_FRAME.getValue("num", (this.frames.size() + 1) + "");
}
if (this.first) {
return Lang.PROMPT_INPUT_FRAMES.getValue();
} else {
return Lang.PROMPT_INPUT_NEXT.getValue("input", ChatColor.translateAlternateColorCodes('&', conversationContext.getSessionData("lastAdded") + ""));
}
}
@Override
protected String getFailedValidationText(ConversationContext context, String invalidInput) {
return Lang.PROMPT_INPUT_INVALID.getValue();
}
} | 6,461 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
AnimationBuilderInputSuccessPrompt.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/conversation/builder/animation/AnimationBuilderInputSuccessPrompt.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.conversation.builder.animation;
import com.dsh105.holoapi.HoloAPI;
import com.dsh105.holoapi.api.AnimatedHologram;
import com.dsh105.holoapi.api.AnimatedHologramFactory;
import com.dsh105.holoapi.config.Lang;
import com.dsh105.holoapi.image.AnimatedTextGenerator;
import com.dsh105.holoapi.image.Frame;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.MessagePrompt;
import org.bukkit.conversations.Prompt;
import org.bukkit.entity.Player;
import java.util.ArrayList;
public class AnimationBuilderInputSuccessPrompt extends MessagePrompt {
private ArrayList<Frame> frames;
private int delay;
public AnimationBuilderInputSuccessPrompt(ArrayList<Frame> frames, int delay) {
this.frames = frames;
this.delay = delay;
}
@Override
protected Prompt getNextPrompt(ConversationContext conversationContext) {
return END_OF_CONVERSATION;
}
@Override
public String getPromptText(ConversationContext conversationContext) {
ArrayList<Frame> frames = new ArrayList<>();
for (Frame f : this.frames) {
frames.add(new Frame(delay, f.getLines()));
}
// If we're here it should be a player
AnimatedHologram h = new AnimatedHologramFactory(HoloAPI.getCore()).withText(new AnimatedTextGenerator(frames.toArray(new Frame[frames.size()]))).withLocation(((Player) conversationContext.getForWhom()).getLocation()).build();
return Lang.HOLOGRAM_CREATED.getValue("id", h.getSaveId());
}
} | 2,230 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
ScriptManager.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/script/ScriptManager.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.script;
import com.dsh105.holoapi.HoloAPI;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.IOException;
public class ScriptManager {
private final Plugin plugin;
private File scriptDir;
private ScriptLoader loader;
public ScriptManager(Plugin plugin) throws IOException {
this.plugin = plugin;
this.scriptDir = new File(HoloAPI.getCore().getDataFolder(), "Scripts");
if (!this.scriptDir.exists()) {
this.scriptDir.mkdir();
}
this.loader = new ScriptLoader(this.scriptDir);
}
public Plugin getPlugin() {
return this.plugin;
}
public File getScriptDir() {
return this.scriptDir;
}
public ScriptLoader getLoader() {
return this.loader;
}
public Script getScript(String scriptName) {
for (Script script : this.loader.getScripts()) {
if (script.getName().equalsIgnoreCase(scriptName))
return script;
}
return null;
}
}
| 1,792 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
TouchActionScript.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/script/TouchActionScript.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.script;
import com.dsh105.holoapi.api.Hologram;
import com.dsh105.holoapi.api.touch.Action;
import com.dsh105.holoapi.api.touch.TouchAction;
import org.bukkit.entity.Player;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.LinkedHashMap;
public class TouchActionScript extends Script<Boolean> implements TouchAction {
public TouchActionScript(String name, String code) {
super(name, code);
}
@Override
public String getSignature() {
return "hologram,player,action";
}
@Override
public Boolean eval(ScriptEngine engine, Object... args) throws ScriptException {
return null;
}
@Override
public void onTouch(Player who, Action action) {
}
@Override
public String getSaveKey() {
return getName();
}
@Override
public LinkedHashMap<String, Object> getDataToSave() {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
return null;
}
}
| 1,763 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
ScriptLoader.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/script/ScriptLoader.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.script;
import com.dsh105.holoapi.util.Debugger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class ScriptLoader {
public static boolean SCRIPTING_ENABLED = false;
public static final String SCRIPT_EXTENSION = ".script";
private static ScriptEngine SCRIPT_ENGINE;
private final File scriptDir;
private List<Script> scripts;
public ScriptLoader(File scriptDir) throws IOException {
if (!scriptDir.isDirectory()) {
throw new IllegalArgumentException("Given File object isn't a directory!");
}
try {
initializeScriptEngine();
} catch (ScriptException e) {
Debugger.getInstance().log(7, "ScriptEngine failed to initialize: " + e.getMessage());
throw new RuntimeException("Failed to initialize the ScripEngine! Scripting disabled...");
}
SCRIPTING_ENABLED = SCRIPT_ENGINE != null;
if (!SCRIPTING_ENABLED)
throw new IllegalStateException("ScriptEngine is NULL! -> Scripting disabled!");
this.scriptDir = scriptDir;
this.scripts = new ArrayList<>();
for (File file : scriptDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(SCRIPT_EXTENSION);
}
})
) {
// scripts.add(Script.readFromFile(file));
}
}
private static void initializeScriptEngine() throws ScriptException {
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
SCRIPT_ENGINE = scriptEngineManager.getEngineByName(""); // TODO: Settings.SCRIPT_ENGINE.getValue()
if (SCRIPT_ENGINE != null) {
SCRIPT_ENGINE.eval("importPackage(org.bukkit);");
SCRIPT_ENGINE.eval("importPackage(com.dsh105.holoapi);");
}
}
public ScriptEngine getScriptEngine() {
return SCRIPT_ENGINE;
}
public File getScriptDir() {
return this.scriptDir;
}
public Collection<Script> getScripts() {
return Collections.unmodifiableList(this.scripts);
}
} | 3,202 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
ScriptEditor.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/script/ScriptEditor.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.script;
public class ScriptEditor {
}
| 762 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
Script.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/script/Script.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.script;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public abstract class Script<T> {
protected String name;
protected String code;
public Script(String name, String code) {
this.name = name;
this.code = code;
}
public String getName() {
return this.name;
}
public String getCode() {
return this.code;
}
public abstract String getSignature();
public abstract T eval(ScriptEngine engine, Object... args) throws ScriptException;
protected void compile(ScriptEngine engine) throws ScriptException {
if (engine.get(this.name) == null) {
engine.eval("var " + this.name + " = function(hologram, player) {\n" + this.code + "\n}");
}
}
public void cleanup(ScriptEngine engine) {
engine.put(this.name, null);
}
/** public void saveToFile(File file) throws FileNotFoundException {
if (file.isDirectory() || !file.exists())
throw new IllegalArgumentException("File is a directory or doesn't exist!");
if (file.getName().endsWith(ScriptLoader.SCRIPT_EXTENSION))
throw new IllegalArgumentException("File doesn't have the " + ScriptLoader.SCRIPT_EXTENSION + " extension!");
PrintWriter writer = new PrintWriter(file);
writer.print(this.code);
writer.flush();
writer.close();
}
public static Script readFromFile(File file) throws IOException {
byte[] encoded = Files.readAllBytes(file.toPath());
String code = new String(encoded, StandardCharsets.UTF_8);
return new Script(file.getName(), code);
} */
} | 2,437 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
TagFormatScript.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/script/TagFormatScript.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.script;
import com.dsh105.holoapi.api.Hologram;
import com.dsh105.holoapi.api.ITagFormat;
import org.bukkit.entity.Player;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class TagFormatScript extends Script<String> implements ITagFormat {
private ScriptEngine scriptEngine;
public TagFormatScript(String name, String code, ScriptEngine scriptEngine) {
super(name, code);
this.scriptEngine = scriptEngine;
}
@Override
public String getValue(Player observer) {
try {
return eval(scriptEngine, null, observer);
} catch (ScriptException e) {
return null; // TODO: proper error handling maybe?
}
}
@Override
public String getValue(Hologram hologram, Player observer) {
try {
return eval(this.scriptEngine, hologram, observer);
} catch (ScriptException e) {
return null; // TODO: even better error handling?
}
}
@Override
public String getSignature() {
return "hologram,player";
}
@Override
public String eval(ScriptEngine engine, Object... args) throws ScriptException {
this.compile(engine);
try {
Object result = ((Invocable) engine).invokeFunction(this.name, args);
return (String) result;
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Failed to compile " + this.name + " into the ScriptEngine!", e);
}
}
}
| 2,330 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
HoloCommand.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/HoloCommand.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.command;
import com.captainbern.minecraft.reflection.MinecraftReflection;
import com.dsh105.command.*;
import com.dsh105.commodus.GeneralUtil;
import com.dsh105.holoapi.HoloAPI;
import com.dsh105.holoapi.config.Lang;
import org.bukkit.Bukkit;
@Command(
command = "holo",
description = "Manage your own holograms.",
permission = "holoapi.holo",
usage = "Use \"/holo help\" for help."
)
public class HoloCommand implements CommandListener {
private static String[] messages = {"A cow ain't a pig!", "Leave flappy bird alone!", "I don't like this",
"Stop spamming", "Goodmorning America!", "DSH105 is sexy!", "PressHearthToContinue",
"Stay away from my budder!", "Wot", "If HoloAPI works then DSH105 and CaptainBern wrote it, else I have no idea who wrote that crap"};
@ParentCommand
public boolean command(CommandEvent event) {
event.respond(Lang.PLUGIN_INFORMATION.getValue("version", HoloAPI.getCore().getDescription().getVersion()));
return true;
}
@Command(
command = "holodebug",
description = "Smashing bugs and coloring books",
permission = "holo.debug"
)
public boolean debug(CommandEvent event) {
event.respond("Debug results: ");
event.respond("--------------[HoloAPI Stuff]--------------");
event.respond("HoloAPI-Version: " + HoloAPI.getCore().getDescription().getVersion());
event.respond("Message of the day: " + messages[GeneralUtil.random().nextInt(messages.length)]);
event.respond("--------------[CraftBukkit Stuff]--------------");
event.respond("Version tag: " + MinecraftReflection.getVersionTag());
event.respond("NMS-package: " + MinecraftReflection.getMinecraftPackage());
event.respond("CB-package: " + MinecraftReflection.getCraftBukkitPackage());
event.respond("Bukkit version: " + Bukkit.getBukkitVersion());
event.respond("--------------[Minecraft Server Stuff]--------------");
event.respond("Using Netty: " + MinecraftReflection.isUsingNetty());
event.respond("MinecraftServer: " + MinecraftReflection.getMinecraftClass("MinecraftServer").getCanonicalName());
event.respond("Entity: " + MinecraftReflection.getMinecraftClass("Entity"));
event.respond("Is (forge) Modded: " + (MinecraftReflection.getMinecraftClass("Entity").getCanonicalName().startsWith("net.minecraft.entity") ? "Definitely" : "Probably not"));
return true;
}
} | 3,225 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
TeleportCommand.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/TeleportCommand.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.command.sub;
import com.dsh105.command.Command;
import com.dsh105.command.CommandEvent;
import com.dsh105.command.CommandListener;
import com.dsh105.holoapi.HoloAPI;
import com.dsh105.holoapi.api.Hologram;
import com.dsh105.holoapi.config.Lang;
import org.bukkit.entity.Player;
public class TeleportCommand implements CommandListener {
@Command(
command = "teleport <id>",
description = "Teleport to a specific hologram",
permission = "holoapi.holo.teleport"
)
public boolean command(CommandEvent<Player> event) {
Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id"));
if (hologram == null) {
event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id")));
return true;
}
event.sender().teleport(hologram.getDefaultLocation());
event.respond(Lang.HOLOGRAM_TELEPORT_TO.getValue("id", hologram.getSaveId()));
return true;
}
} | 1,686 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
InfoCommand.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/InfoCommand.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.command.sub;
import com.captainbern.minecraft.reflection.MinecraftReflection;
import com.dsh105.command.Command;
import com.dsh105.command.CommandEvent;
import com.dsh105.command.CommandListener;
import com.dsh105.commodus.StringUtil;
import com.dsh105.holoapi.HoloAPI;
import com.dsh105.holoapi.api.AnimatedHologram;
import com.dsh105.holoapi.api.Hologram;
import com.dsh105.holoapi.api.StoredTag;
import com.dsh105.holoapi.config.ConfigType;
import com.dsh105.holoapi.config.Lang;
import com.dsh105.powermessage.core.PowerMessage;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class InfoCommand implements CommandListener {
@Command(
command = "info",
description = "View information on active holograms",
permission = "holoapi.holo.info"
)
public boolean command(CommandEvent event) {
if (HoloAPI.getManager().getAllComplexHolograms().isEmpty()) {
event.respond(Lang.NO_ACTIVE_HOLOGRAMS.getValue());
return true;
}
event.respond(Lang.ACTIVE_DISPLAYS.getValue());
info(event.sender(), HoloAPI.getManager().getAllComplexHolograms().keySet());
if (MinecraftReflection.isUsingNetty() && event.sender() instanceof Player) {
event.respond(Lang.TIP_HOVER_PREVIEW.getValue());
}
return true;
}
protected static void info(CommandSender sender, Collection<Hologram> holograms) {
for (Hologram hologram : holograms) {
ArrayList<String> list = new ArrayList<>();
list.add(ChatColor.GOLD + "" + ChatColor.UNDERLINE + "Hologram Preview:");
if (hologram instanceof AnimatedHologram) {
AnimatedHologram animatedHologram = (AnimatedHologram) hologram;
if (animatedHologram.isImageGenerated() && (HoloAPI.getAnimationLoader().exists(animatedHologram.getAnimationKey())) || HoloAPI.getAnimationLoader().existsAsUnloadedUrl(animatedHologram.getAnimationKey())) {
list.add(ChatColor.YELLOW + "" + ChatColor.ITALIC + animatedHologram.getAnimationKey() + " (ANIMATION)");
} else {
Collections.addAll(list, animatedHologram.getFrames().get(0).getLines());
}
} else {
if (hologram.getLines().length > 1) {
for (StoredTag tag : hologram.serialise()) {
if (tag.isImage()) {
if (HoloAPI.getConfig(ConfigType.MAIN).getBoolean("images." + tag.getContent() + ".requiresBorder", false)) {
for (String s : HoloAPI.getImageLoader().getGenerator(tag.getContent()).getLines()) {
list.add(HoloAPI.getTagFormatter().formatBasic(ChatColor.WHITE + s));
}
} else {
list.add(ChatColor.YELLOW + "" + ChatColor.ITALIC + tag.getContent() + " (IMAGE)");
}
} else {
list.add(HoloAPI.getTagFormatter().formatBasic(ChatColor.WHITE + tag.getContent()));
}
}
} else {
list.add(HoloAPI.getTagFormatter().formatBasic(hologram.getLines()[0]));
}
}
if (list.size() > 1) {
new PowerMessage("•• " + ChatColor.AQUA + hologram.getSaveId() + ChatColor.DARK_AQUA + " at " + (int) hologram.getDefaultX() + ", " + (int) hologram.getDefaultY() + ", " + (int) hologram.getDefaultZ() + ", " + hologram.getWorldName()).tooltip(list.toArray(StringUtil.EMPTY_STRING_ARRAY)).suggest("/holo teleport " + hologram.getSaveId()).send(sender);
}
}
}
} | 4,638 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
HideCommand.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/HideCommand.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.command.sub;
import com.dsh105.command.Command;
import com.dsh105.command.CommandEvent;
import com.dsh105.command.CommandListener;
import com.dsh105.holoapi.HoloAPI;
import com.dsh105.holoapi.api.Hologram;
import com.dsh105.holoapi.config.Lang;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class HideCommand implements CommandListener {
@Command(
command = "hide <id> <player>",
description = "Hide a hologram from a player's view",
permission = "holoapi.holo.hide"
)
public boolean command(CommandEvent event) {
final Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id"));
if (hologram == null) {
event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id")));
return true;
}
Player target = Bukkit.getPlayer(event.variable("player"));
if (target == null) {
event.respond(Lang.NULL_PLAYER.getValue("player", event.variable("player")));
return true;
}
if (!hologram.canBeSeenBy(target)) {
event.respond(Lang.HOLOGRAM_ALREADY_NOT_SEE.getValue("id", event.variable("id"), "player", event.variable("player")));
return true;
}
hologram.clear(target);
event.respond(Lang.HOLOGRAM_HIDE.getValue("id", event.variable("id"), "player", event.variable("player")));
return true;
}
} | 2,146 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
NearbyCommand.java | /FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/NearbyCommand.java | /*
* This file is part of HoloAPI.
*
* HoloAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoloAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoloAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.holoapi.command.sub;
import com.captainbern.minecraft.reflection.MinecraftReflection;
import com.dsh105.command.Command;
import com.dsh105.command.CommandEvent;
import com.dsh105.command.CommandListener;
import com.dsh105.commodus.GeneralUtil;
import com.dsh105.commodus.GeometryUtil;
import com.dsh105.holoapi.HoloAPI;
import com.dsh105.holoapi.api.Hologram;
import com.dsh105.holoapi.config.Lang;
import org.bukkit.entity.Player;
import java.util.ArrayList;
public class NearbyCommand implements CommandListener {
@Command(
command = "nearby <radius>",
description = "View information on all nearby holograms within the specified radius",
permission = "holoapi.holo.nearby"
)
public boolean command(CommandEvent<Player> event) {
int radius;
try {
radius = GeneralUtil.toInteger(event.variable("radius"));
} catch (NumberFormatException e) {
event.respond(Lang.INT_ONLY.getValue("string", event.variable("radius")));
return true;
}
ArrayList<Hologram> nearby = new ArrayList<Hologram>();
for (Hologram hologram : HoloAPI.getManager().getAllComplexHolograms().keySet()) {
if (GeometryUtil.getNearbyEntities(hologram.getDefaultLocation(), radius).contains(event.sender())) {
nearby.add(hologram);
}
}
if (nearby.isEmpty()) {
event.respond(Lang.NO_NEARBY_HOLOGRAMS.getValue("radius", radius));
return true;
}
event.respond(Lang.HOLOGRAM_NEARBY.getValue("radius", radius));
InfoCommand.info(event.sender(), nearby);
if (MinecraftReflection.isUsingNetty()) {
event.respond(Lang.TIP_HOVER_PREVIEW.getValue());
}
return true;
}
} | 2,500 | Java | .java | DSH105/HoloAPI | 31 | 16 | 21 | 2014-02-21T21:30:11Z | 2014-12-24T12:52:54Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.