repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
netmelody/ci-eye
src/main/java/org/netmelody/cieye/spies/teamcity/TeamCityCommunicator.java
// Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/BuildDetail.java // public final class BuildDetail { // public long id; // public String number; // public String status; // public String href; // public String webUrl; // public boolean personal; // public boolean history; // public boolean pinned; // public String statusText; // //buildType // public Date startDate; // public Date finishDate; // //agent // public Comment comment; // //tags // //properties // //revisions // public ChangesHref changes; // //relatedIssues // // public Status status() { // if (status == null || "SUCCESS".equals(status)) { // return Status.GREEN; // } // if (comment != null && comment.text != null && !comment.text.isEmpty()) { // return Status.UNDER_INVESTIGATION; // } // return Status.BROKEN; // } // // public long startDateTime() { // return (null == startDate) ? 0L : startDate.getTime(); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/Investigation.java // public final class Investigation { // public String id; // public String state; // public User responsible; // public Assignment assignment; // // scope; // // public long startDateTime() { // if (null == assignment) { // return 0L; // } // return (null == assignment.timestamp) ? 0L : assignment.timestamp.getTime(); // } // // public boolean underInvestigation() { // return "TAKEN".equals(state) || "FIXED".equals(state); // } // }
import static com.google.common.collect.Iterables.find; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.netmelody.cieye.core.domain.Feature; import org.netmelody.cieye.core.observation.Contact; import org.netmelody.cieye.spies.teamcity.jsondomain.Build; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildType; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypes; import org.netmelody.cieye.spies.teamcity.jsondomain.Builds; import org.netmelody.cieye.spies.teamcity.jsondomain.Change; import org.netmelody.cieye.spies.teamcity.jsondomain.ChangeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigation; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigations; import org.netmelody.cieye.spies.teamcity.jsondomain.Project; import org.netmelody.cieye.spies.teamcity.jsondomain.ProjectDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.TeamCityProjects; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonNull;
} public Collection<Project> projects() { return makeTeamCityRestCall(endpoint + prefix + "/projects", TeamCityProjects.class).project(); } public Collection<BuildType> buildTypes() { return makeTeamCityRestCall(endpoint + prefix + "/buildTypes", BuildTypes.class).buildType(); } public Collection<BuildType> buildTypesFor(Project projectDigest) { return makeTeamCityRestCall(endpoint + projectDigest.href, ProjectDetail.class).buildTypes.buildType(); } public BuildTypeDetail detailsFor(BuildType buildType) { return makeTeamCityRestCall(endpoint + buildType.href, BuildTypeDetail.class); } public Build lastCompletedBuildFor(BuildTypeDetail buildTypeDetail) { final Builds completedBuilds = makeTeamCityRestCall(endpoint + buildTypeDetail.builds.href, Builds.class); if (null == completedBuilds.build() || completedBuilds.build().isEmpty()) { return null; } return find(completedBuilds.build(), primaryBranchBuilds); } public List<Build> runningBuildsFor(BuildType buildType) { return makeTeamCityRestCall(endpoint + prefix + "/builds/?locator=running:true,buildType:id:" + buildType.id, Builds.class).build(); }
// Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/BuildDetail.java // public final class BuildDetail { // public long id; // public String number; // public String status; // public String href; // public String webUrl; // public boolean personal; // public boolean history; // public boolean pinned; // public String statusText; // //buildType // public Date startDate; // public Date finishDate; // //agent // public Comment comment; // //tags // //properties // //revisions // public ChangesHref changes; // //relatedIssues // // public Status status() { // if (status == null || "SUCCESS".equals(status)) { // return Status.GREEN; // } // if (comment != null && comment.text != null && !comment.text.isEmpty()) { // return Status.UNDER_INVESTIGATION; // } // return Status.BROKEN; // } // // public long startDateTime() { // return (null == startDate) ? 0L : startDate.getTime(); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/Investigation.java // public final class Investigation { // public String id; // public String state; // public User responsible; // public Assignment assignment; // // scope; // // public long startDateTime() { // if (null == assignment) { // return 0L; // } // return (null == assignment.timestamp) ? 0L : assignment.timestamp.getTime(); // } // // public boolean underInvestigation() { // return "TAKEN".equals(state) || "FIXED".equals(state); // } // } // Path: src/main/java/org/netmelody/cieye/spies/teamcity/TeamCityCommunicator.java import static com.google.common.collect.Iterables.find; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.netmelody.cieye.core.domain.Feature; import org.netmelody.cieye.core.observation.Contact; import org.netmelody.cieye.spies.teamcity.jsondomain.Build; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildType; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypes; import org.netmelody.cieye.spies.teamcity.jsondomain.Builds; import org.netmelody.cieye.spies.teamcity.jsondomain.Change; import org.netmelody.cieye.spies.teamcity.jsondomain.ChangeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigation; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigations; import org.netmelody.cieye.spies.teamcity.jsondomain.Project; import org.netmelody.cieye.spies.teamcity.jsondomain.ProjectDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.TeamCityProjects; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonNull; } public Collection<Project> projects() { return makeTeamCityRestCall(endpoint + prefix + "/projects", TeamCityProjects.class).project(); } public Collection<BuildType> buildTypes() { return makeTeamCityRestCall(endpoint + prefix + "/buildTypes", BuildTypes.class).buildType(); } public Collection<BuildType> buildTypesFor(Project projectDigest) { return makeTeamCityRestCall(endpoint + projectDigest.href, ProjectDetail.class).buildTypes.buildType(); } public BuildTypeDetail detailsFor(BuildType buildType) { return makeTeamCityRestCall(endpoint + buildType.href, BuildTypeDetail.class); } public Build lastCompletedBuildFor(BuildTypeDetail buildTypeDetail) { final Builds completedBuilds = makeTeamCityRestCall(endpoint + buildTypeDetail.builds.href, Builds.class); if (null == completedBuilds.build() || completedBuilds.build().isEmpty()) { return null; } return find(completedBuilds.build(), primaryBranchBuilds); } public List<Build> runningBuildsFor(BuildType buildType) { return makeTeamCityRestCall(endpoint + prefix + "/builds/?locator=running:true,buildType:id:" + buildType.id, Builds.class).build(); }
public List<Investigation> investigationsOf(BuildType buildType) {
netmelody/ci-eye
src/main/java/org/netmelody/cieye/spies/teamcity/TeamCityCommunicator.java
// Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/BuildDetail.java // public final class BuildDetail { // public long id; // public String number; // public String status; // public String href; // public String webUrl; // public boolean personal; // public boolean history; // public boolean pinned; // public String statusText; // //buildType // public Date startDate; // public Date finishDate; // //agent // public Comment comment; // //tags // //properties // //revisions // public ChangesHref changes; // //relatedIssues // // public Status status() { // if (status == null || "SUCCESS".equals(status)) { // return Status.GREEN; // } // if (comment != null && comment.text != null && !comment.text.isEmpty()) { // return Status.UNDER_INVESTIGATION; // } // return Status.BROKEN; // } // // public long startDateTime() { // return (null == startDate) ? 0L : startDate.getTime(); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/Investigation.java // public final class Investigation { // public String id; // public String state; // public User responsible; // public Assignment assignment; // // scope; // // public long startDateTime() { // if (null == assignment) { // return 0L; // } // return (null == assignment.timestamp) ? 0L : assignment.timestamp.getTime(); // } // // public boolean underInvestigation() { // return "TAKEN".equals(state) || "FIXED".equals(state); // } // }
import static com.google.common.collect.Iterables.find; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.netmelody.cieye.core.domain.Feature; import org.netmelody.cieye.core.observation.Contact; import org.netmelody.cieye.spies.teamcity.jsondomain.Build; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildType; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypes; import org.netmelody.cieye.spies.teamcity.jsondomain.Builds; import org.netmelody.cieye.spies.teamcity.jsondomain.Change; import org.netmelody.cieye.spies.teamcity.jsondomain.ChangeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigation; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigations; import org.netmelody.cieye.spies.teamcity.jsondomain.Project; import org.netmelody.cieye.spies.teamcity.jsondomain.ProjectDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.TeamCityProjects; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonNull;
} public Collection<BuildType> buildTypes() { return makeTeamCityRestCall(endpoint + prefix + "/buildTypes", BuildTypes.class).buildType(); } public Collection<BuildType> buildTypesFor(Project projectDigest) { return makeTeamCityRestCall(endpoint + projectDigest.href, ProjectDetail.class).buildTypes.buildType(); } public BuildTypeDetail detailsFor(BuildType buildType) { return makeTeamCityRestCall(endpoint + buildType.href, BuildTypeDetail.class); } public Build lastCompletedBuildFor(BuildTypeDetail buildTypeDetail) { final Builds completedBuilds = makeTeamCityRestCall(endpoint + buildTypeDetail.builds.href, Builds.class); if (null == completedBuilds.build() || completedBuilds.build().isEmpty()) { return null; } return find(completedBuilds.build(), primaryBranchBuilds); } public List<Build> runningBuildsFor(BuildType buildType) { return makeTeamCityRestCall(endpoint + prefix + "/builds/?locator=running:true,buildType:id:" + buildType.id, Builds.class).build(); } public List<Investigation> investigationsOf(BuildType buildType) { return makeTeamCityRestCall(endpoint + buildType.href + "/investigations", Investigations.class).investigation(); }
// Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/BuildDetail.java // public final class BuildDetail { // public long id; // public String number; // public String status; // public String href; // public String webUrl; // public boolean personal; // public boolean history; // public boolean pinned; // public String statusText; // //buildType // public Date startDate; // public Date finishDate; // //agent // public Comment comment; // //tags // //properties // //revisions // public ChangesHref changes; // //relatedIssues // // public Status status() { // if (status == null || "SUCCESS".equals(status)) { // return Status.GREEN; // } // if (comment != null && comment.text != null && !comment.text.isEmpty()) { // return Status.UNDER_INVESTIGATION; // } // return Status.BROKEN; // } // // public long startDateTime() { // return (null == startDate) ? 0L : startDate.getTime(); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/Investigation.java // public final class Investigation { // public String id; // public String state; // public User responsible; // public Assignment assignment; // // scope; // // public long startDateTime() { // if (null == assignment) { // return 0L; // } // return (null == assignment.timestamp) ? 0L : assignment.timestamp.getTime(); // } // // public boolean underInvestigation() { // return "TAKEN".equals(state) || "FIXED".equals(state); // } // } // Path: src/main/java/org/netmelody/cieye/spies/teamcity/TeamCityCommunicator.java import static com.google.common.collect.Iterables.find; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.netmelody.cieye.core.domain.Feature; import org.netmelody.cieye.core.observation.Contact; import org.netmelody.cieye.spies.teamcity.jsondomain.Build; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildType; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypes; import org.netmelody.cieye.spies.teamcity.jsondomain.Builds; import org.netmelody.cieye.spies.teamcity.jsondomain.Change; import org.netmelody.cieye.spies.teamcity.jsondomain.ChangeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigation; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigations; import org.netmelody.cieye.spies.teamcity.jsondomain.Project; import org.netmelody.cieye.spies.teamcity.jsondomain.ProjectDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.TeamCityProjects; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonNull; } public Collection<BuildType> buildTypes() { return makeTeamCityRestCall(endpoint + prefix + "/buildTypes", BuildTypes.class).buildType(); } public Collection<BuildType> buildTypesFor(Project projectDigest) { return makeTeamCityRestCall(endpoint + projectDigest.href, ProjectDetail.class).buildTypes.buildType(); } public BuildTypeDetail detailsFor(BuildType buildType) { return makeTeamCityRestCall(endpoint + buildType.href, BuildTypeDetail.class); } public Build lastCompletedBuildFor(BuildTypeDetail buildTypeDetail) { final Builds completedBuilds = makeTeamCityRestCall(endpoint + buildTypeDetail.builds.href, Builds.class); if (null == completedBuilds.build() || completedBuilds.build().isEmpty()) { return null; } return find(completedBuilds.build(), primaryBranchBuilds); } public List<Build> runningBuildsFor(BuildType buildType) { return makeTeamCityRestCall(endpoint + prefix + "/builds/?locator=running:true,buildType:id:" + buildType.id, Builds.class).build(); } public List<Investigation> investigationsOf(BuildType buildType) { return makeTeamCityRestCall(endpoint + buildType.href + "/investigations", Investigations.class).investigation(); }
public BuildDetail detailsOf(Build build) {
netmelody/ci-eye
src/main/java/org/netmelody/cieye/spies/teamcity/BuildTypeAnalyser.java
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/BuildDetail.java // public final class BuildDetail { // public long id; // public String number; // public String status; // public String href; // public String webUrl; // public boolean personal; // public boolean history; // public boolean pinned; // public String statusText; // //buildType // public Date startDate; // public Date finishDate; // //agent // public Comment comment; // //tags // //properties // //revisions // public ChangesHref changes; // //relatedIssues // // public Status status() { // if (status == null || "SUCCESS".equals(status)) { // return Status.GREEN; // } // if (comment != null && comment.text != null && !comment.text.isEmpty()) { // return Status.UNDER_INVESTIGATION; // } // return Status.BROKEN; // } // // public long startDateTime() { // return (null == startDate) ? 0L : startDate.getTime(); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/Investigation.java // public final class Investigation { // public String id; // public String state; // public User responsible; // public Assignment assignment; // // scope; // // public long startDateTime() { // if (null == assignment) { // return 0L; // } // return (null == assignment.timestamp) ? 0L : assignment.timestamp.getTime(); // } // // public boolean underInvestigation() { // return "TAKEN".equals(state) || "FIXED".equals(state); // } // }
import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.teamcity.jsondomain.Build; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildType; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Change; import org.netmelody.cieye.spies.teamcity.jsondomain.ChangeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigation;
package org.netmelody.cieye.spies.teamcity; public final class BuildTypeAnalyser { private final TeamCityCommunicator communicator; private final KnownOffendersDirectory detective; public BuildTypeAnalyser(TeamCityCommunicator communicator, KnownOffendersDirectory detective) { this.communicator = communicator; this.detective = detective; } public TargetDetail targetFrom(BuildType buildType) { final BuildTypeDetail buildTypeDetail = communicator.detailsFor(buildType); if (buildTypeDetail.paused) { return new TargetDetail(communicator.endpoint() + buildType.href, buildType.webUrl(), buildType.name, Status.DISABLED, 0L); } final Set<Sponsor> sponsors = new HashSet<Sponsor>();
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/BuildDetail.java // public final class BuildDetail { // public long id; // public String number; // public String status; // public String href; // public String webUrl; // public boolean personal; // public boolean history; // public boolean pinned; // public String statusText; // //buildType // public Date startDate; // public Date finishDate; // //agent // public Comment comment; // //tags // //properties // //revisions // public ChangesHref changes; // //relatedIssues // // public Status status() { // if (status == null || "SUCCESS".equals(status)) { // return Status.GREEN; // } // if (comment != null && comment.text != null && !comment.text.isEmpty()) { // return Status.UNDER_INVESTIGATION; // } // return Status.BROKEN; // } // // public long startDateTime() { // return (null == startDate) ? 0L : startDate.getTime(); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/Investigation.java // public final class Investigation { // public String id; // public String state; // public User responsible; // public Assignment assignment; // // scope; // // public long startDateTime() { // if (null == assignment) { // return 0L; // } // return (null == assignment.timestamp) ? 0L : assignment.timestamp.getTime(); // } // // public boolean underInvestigation() { // return "TAKEN".equals(state) || "FIXED".equals(state); // } // } // Path: src/main/java/org/netmelody/cieye/spies/teamcity/BuildTypeAnalyser.java import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.teamcity.jsondomain.Build; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildType; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Change; import org.netmelody.cieye.spies.teamcity.jsondomain.ChangeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigation; package org.netmelody.cieye.spies.teamcity; public final class BuildTypeAnalyser { private final TeamCityCommunicator communicator; private final KnownOffendersDirectory detective; public BuildTypeAnalyser(TeamCityCommunicator communicator, KnownOffendersDirectory detective) { this.communicator = communicator; this.detective = detective; } public TargetDetail targetFrom(BuildType buildType) { final BuildTypeDetail buildTypeDetail = communicator.detailsFor(buildType); if (buildTypeDetail.paused) { return new TargetDetail(communicator.endpoint() + buildType.href, buildType.webUrl(), buildType.name, Status.DISABLED, 0L); } final Set<Sponsor> sponsors = new HashSet<Sponsor>();
final List<RunningBuild> runningBuilds = new ArrayList<RunningBuild>();
netmelody/ci-eye
src/main/java/org/netmelody/cieye/spies/teamcity/BuildTypeAnalyser.java
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/BuildDetail.java // public final class BuildDetail { // public long id; // public String number; // public String status; // public String href; // public String webUrl; // public boolean personal; // public boolean history; // public boolean pinned; // public String statusText; // //buildType // public Date startDate; // public Date finishDate; // //agent // public Comment comment; // //tags // //properties // //revisions // public ChangesHref changes; // //relatedIssues // // public Status status() { // if (status == null || "SUCCESS".equals(status)) { // return Status.GREEN; // } // if (comment != null && comment.text != null && !comment.text.isEmpty()) { // return Status.UNDER_INVESTIGATION; // } // return Status.BROKEN; // } // // public long startDateTime() { // return (null == startDate) ? 0L : startDate.getTime(); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/Investigation.java // public final class Investigation { // public String id; // public String state; // public User responsible; // public Assignment assignment; // // scope; // // public long startDateTime() { // if (null == assignment) { // return 0L; // } // return (null == assignment.timestamp) ? 0L : assignment.timestamp.getTime(); // } // // public boolean underInvestigation() { // return "TAKEN".equals(state) || "FIXED".equals(state); // } // }
import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.teamcity.jsondomain.Build; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildType; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Change; import org.netmelody.cieye.spies.teamcity.jsondomain.ChangeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigation;
package org.netmelody.cieye.spies.teamcity; public final class BuildTypeAnalyser { private final TeamCityCommunicator communicator; private final KnownOffendersDirectory detective; public BuildTypeAnalyser(TeamCityCommunicator communicator, KnownOffendersDirectory detective) { this.communicator = communicator; this.detective = detective; } public TargetDetail targetFrom(BuildType buildType) { final BuildTypeDetail buildTypeDetail = communicator.detailsFor(buildType); if (buildTypeDetail.paused) { return new TargetDetail(communicator.endpoint() + buildType.href, buildType.webUrl(), buildType.name, Status.DISABLED, 0L); } final Set<Sponsor> sponsors = new HashSet<Sponsor>(); final List<RunningBuild> runningBuilds = new ArrayList<RunningBuild>(); long startTime = 0L; for(Build build : communicator.runningBuildsFor(buildType)) {
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/BuildDetail.java // public final class BuildDetail { // public long id; // public String number; // public String status; // public String href; // public String webUrl; // public boolean personal; // public boolean history; // public boolean pinned; // public String statusText; // //buildType // public Date startDate; // public Date finishDate; // //agent // public Comment comment; // //tags // //properties // //revisions // public ChangesHref changes; // //relatedIssues // // public Status status() { // if (status == null || "SUCCESS".equals(status)) { // return Status.GREEN; // } // if (comment != null && comment.text != null && !comment.text.isEmpty()) { // return Status.UNDER_INVESTIGATION; // } // return Status.BROKEN; // } // // public long startDateTime() { // return (null == startDate) ? 0L : startDate.getTime(); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/Investigation.java // public final class Investigation { // public String id; // public String state; // public User responsible; // public Assignment assignment; // // scope; // // public long startDateTime() { // if (null == assignment) { // return 0L; // } // return (null == assignment.timestamp) ? 0L : assignment.timestamp.getTime(); // } // // public boolean underInvestigation() { // return "TAKEN".equals(state) || "FIXED".equals(state); // } // } // Path: src/main/java/org/netmelody/cieye/spies/teamcity/BuildTypeAnalyser.java import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.teamcity.jsondomain.Build; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildType; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Change; import org.netmelody.cieye.spies.teamcity.jsondomain.ChangeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigation; package org.netmelody.cieye.spies.teamcity; public final class BuildTypeAnalyser { private final TeamCityCommunicator communicator; private final KnownOffendersDirectory detective; public BuildTypeAnalyser(TeamCityCommunicator communicator, KnownOffendersDirectory detective) { this.communicator = communicator; this.detective = detective; } public TargetDetail targetFrom(BuildType buildType) { final BuildTypeDetail buildTypeDetail = communicator.detailsFor(buildType); if (buildTypeDetail.paused) { return new TargetDetail(communicator.endpoint() + buildType.href, buildType.webUrl(), buildType.name, Status.DISABLED, 0L); } final Set<Sponsor> sponsors = new HashSet<Sponsor>(); final List<RunningBuild> runningBuilds = new ArrayList<RunningBuild>(); long startTime = 0L; for(Build build : communicator.runningBuildsFor(buildType)) {
final BuildDetail buildDetail = communicator.detailsOf(build);
netmelody/ci-eye
src/main/java/org/netmelody/cieye/spies/teamcity/BuildTypeAnalyser.java
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/BuildDetail.java // public final class BuildDetail { // public long id; // public String number; // public String status; // public String href; // public String webUrl; // public boolean personal; // public boolean history; // public boolean pinned; // public String statusText; // //buildType // public Date startDate; // public Date finishDate; // //agent // public Comment comment; // //tags // //properties // //revisions // public ChangesHref changes; // //relatedIssues // // public Status status() { // if (status == null || "SUCCESS".equals(status)) { // return Status.GREEN; // } // if (comment != null && comment.text != null && !comment.text.isEmpty()) { // return Status.UNDER_INVESTIGATION; // } // return Status.BROKEN; // } // // public long startDateTime() { // return (null == startDate) ? 0L : startDate.getTime(); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/Investigation.java // public final class Investigation { // public String id; // public String state; // public User responsible; // public Assignment assignment; // // scope; // // public long startDateTime() { // if (null == assignment) { // return 0L; // } // return (null == assignment.timestamp) ? 0L : assignment.timestamp.getTime(); // } // // public boolean underInvestigation() { // return "TAKEN".equals(state) || "FIXED".equals(state); // } // }
import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.teamcity.jsondomain.Build; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildType; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Change; import org.netmelody.cieye.spies.teamcity.jsondomain.ChangeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigation;
final BuildTypeDetail buildTypeDetail = communicator.detailsFor(buildType); if (buildTypeDetail.paused) { return new TargetDetail(communicator.endpoint() + buildType.href, buildType.webUrl(), buildType.name, Status.DISABLED, 0L); } final Set<Sponsor> sponsors = new HashSet<Sponsor>(); final List<RunningBuild> runningBuilds = new ArrayList<RunningBuild>(); long startTime = 0L; for(Build build : communicator.runningBuildsFor(buildType)) { final BuildDetail buildDetail = communicator.detailsOf(build); startTime = Math.max(buildDetail.startDateTime(), startTime); sponsors.addAll(sponsorsOf(buildDetail)); runningBuilds.add(new RunningBuild(percentageOf(build.percentageComplete), buildDetail.status())); } Status currentStatus = Status.UNKNOWN; final Build lastCompletedBuild = communicator.lastCompletedBuildFor(buildTypeDetail); if (null != lastCompletedBuild) { currentStatus = lastCompletedBuild.status(); if (runningBuilds.isEmpty() || Status.BROKEN.equals(currentStatus)) { final BuildDetail buildDetail = communicator.detailsOf(lastCompletedBuild); startTime = Math.max(buildDetail.startDateTime(), startTime); sponsors.addAll(sponsorsOf(buildDetail)); currentStatus = buildDetail.status(); } } if (Status.BROKEN.equals(currentStatus)) {
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/BuildDetail.java // public final class BuildDetail { // public long id; // public String number; // public String status; // public String href; // public String webUrl; // public boolean personal; // public boolean history; // public boolean pinned; // public String statusText; // //buildType // public Date startDate; // public Date finishDate; // //agent // public Comment comment; // //tags // //properties // //revisions // public ChangesHref changes; // //relatedIssues // // public Status status() { // if (status == null || "SUCCESS".equals(status)) { // return Status.GREEN; // } // if (comment != null && comment.text != null && !comment.text.isEmpty()) { // return Status.UNDER_INVESTIGATION; // } // return Status.BROKEN; // } // // public long startDateTime() { // return (null == startDate) ? 0L : startDate.getTime(); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/teamcity/jsondomain/Investigation.java // public final class Investigation { // public String id; // public String state; // public User responsible; // public Assignment assignment; // // scope; // // public long startDateTime() { // if (null == assignment) { // return 0L; // } // return (null == assignment.timestamp) ? 0L : assignment.timestamp.getTime(); // } // // public boolean underInvestigation() { // return "TAKEN".equals(state) || "FIXED".equals(state); // } // } // Path: src/main/java/org/netmelody/cieye/spies/teamcity/BuildTypeAnalyser.java import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.teamcity.jsondomain.Build; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildType; import org.netmelody.cieye.spies.teamcity.jsondomain.BuildTypeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Change; import org.netmelody.cieye.spies.teamcity.jsondomain.ChangeDetail; import org.netmelody.cieye.spies.teamcity.jsondomain.Investigation; final BuildTypeDetail buildTypeDetail = communicator.detailsFor(buildType); if (buildTypeDetail.paused) { return new TargetDetail(communicator.endpoint() + buildType.href, buildType.webUrl(), buildType.name, Status.DISABLED, 0L); } final Set<Sponsor> sponsors = new HashSet<Sponsor>(); final List<RunningBuild> runningBuilds = new ArrayList<RunningBuild>(); long startTime = 0L; for(Build build : communicator.runningBuildsFor(buildType)) { final BuildDetail buildDetail = communicator.detailsOf(build); startTime = Math.max(buildDetail.startDateTime(), startTime); sponsors.addAll(sponsorsOf(buildDetail)); runningBuilds.add(new RunningBuild(percentageOf(build.percentageComplete), buildDetail.status())); } Status currentStatus = Status.UNKNOWN; final Build lastCompletedBuild = communicator.lastCompletedBuildFor(buildTypeDetail); if (null != lastCompletedBuild) { currentStatus = lastCompletedBuild.status(); if (runningBuilds.isEmpty() || Status.BROKEN.equals(currentStatus)) { final BuildDetail buildDetail = communicator.detailsOf(lastCompletedBuild); startTime = Math.max(buildDetail.startDateTime(), startTime); sponsors.addAll(sponsorsOf(buildDetail)); currentStatus = buildDetail.status(); } } if (Status.BROKEN.equals(currentStatus)) {
final List<Investigation> investigations = communicator.investigationsOf(buildType);
netmelody/ci-eye
src/main/java/org/netmelody/cieye/spies/jenkins/JenkinsCommunicator.java
// Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/Server.java // public final class Server { // public List<Label> assignedLabels; // public String mode; // public String nodeName; // public String nodeDescription; // public int numExecutors; // public String description; // public List<Job> jobs; // public Load overallLoad; // public View primaryView; // public int slaveAgentPort; // public boolean useCrumbs; // public boolean useSecurity; // public List<View> views; // // public List<View> views() { // return (views == null) ? new ArrayList<View>() : views; // } // }
import java.util.Collection; import org.netmelody.cieye.core.domain.Feature; import org.netmelody.cieye.core.observation.Contact; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.Job; import org.netmelody.cieye.spies.jenkins.jsondomain.JobDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.Server; import org.netmelody.cieye.spies.jenkins.jsondomain.View; import org.netmelody.cieye.spies.jenkins.jsondomain.ViewDetail;
package org.netmelody.cieye.spies.jenkins; public final class JenkinsCommunicator { private final Contact contact; private final String endpoint; public JenkinsCommunicator(String endpoint, Contact contact) { this.endpoint = endpoint; this.contact = contact; } public String endpoint() { return endpoint; } public boolean canSpeakFor(Feature feature) { return endpoint.equals(feature.endpoint()); } public void doJenkinsPost(String url) { contact.doPost(url); } public BuildDetail buildDetailsFor(String buildUrl) { return makeJenkinsRestCall(buildUrl, BuildDetail.class); } public JobDetail jobDetailFor(String jobEndpoint) { return makeJenkinsRestCall(jobEndpoint, JobDetail.class); } public String lastBadBuildFor(String jobEndpoint) { return jobDetailFor(jobEndpoint).lastBadBuildUrl(); } public Collection<Job> jobsFor(View viewDigest) { return makeJenkinsRestCall(viewDigest.url, ViewDetail.class).jobs(); } public Collection<View> views() {
// Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/Server.java // public final class Server { // public List<Label> assignedLabels; // public String mode; // public String nodeName; // public String nodeDescription; // public int numExecutors; // public String description; // public List<Job> jobs; // public Load overallLoad; // public View primaryView; // public int slaveAgentPort; // public boolean useCrumbs; // public boolean useSecurity; // public List<View> views; // // public List<View> views() { // return (views == null) ? new ArrayList<View>() : views; // } // } // Path: src/main/java/org/netmelody/cieye/spies/jenkins/JenkinsCommunicator.java import java.util.Collection; import org.netmelody.cieye.core.domain.Feature; import org.netmelody.cieye.core.observation.Contact; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.Job; import org.netmelody.cieye.spies.jenkins.jsondomain.JobDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.Server; import org.netmelody.cieye.spies.jenkins.jsondomain.View; import org.netmelody.cieye.spies.jenkins.jsondomain.ViewDetail; package org.netmelody.cieye.spies.jenkins; public final class JenkinsCommunicator { private final Contact contact; private final String endpoint; public JenkinsCommunicator(String endpoint, Contact contact) { this.endpoint = endpoint; this.contact = contact; } public String endpoint() { return endpoint; } public boolean canSpeakFor(Feature feature) { return endpoint.equals(feature.endpoint()); } public void doJenkinsPost(String url) { contact.doPost(url); } public BuildDetail buildDetailsFor(String buildUrl) { return makeJenkinsRestCall(buildUrl, BuildDetail.class); } public JobDetail jobDetailFor(String jobEndpoint) { return makeJenkinsRestCall(jobEndpoint, JobDetail.class); } public String lastBadBuildFor(String jobEndpoint) { return jobDetailFor(jobEndpoint).lastBadBuildUrl(); } public Collection<Job> jobsFor(View viewDigest) { return makeJenkinsRestCall(viewDigest.url, ViewDetail.class).jobs(); } public Collection<View> views() {
return makeJenkinsRestCallWithSuffix("", Server.class).views();
netmelody/ci-eye
src/main/java/org/netmelody/cieye/spies/jenkins/JobAnalyser.java
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/ChangeSetItem.java // public final class ChangeSetItem { // //Date date; // public String msg; // public String comment; // public long revision; // public String user; // //paths // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/User.java // public final class User { // public String absoluteUrl; // public String fullName; // } // // Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // }
import com.google.common.base.Function; import com.google.common.base.Predicate; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.jenkins.jsondomain.Build; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.ChangeSetItem; import org.netmelody.cieye.spies.jenkins.jsondomain.Job; import org.netmelody.cieye.spies.jenkins.jsondomain.JobDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.User; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.collect.Collections2.filter; import static com.google.common.collect.Collections2.transform; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.unmodifiableSet; import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import static org.netmelody.cieye.core.domain.RunningBuild.buildAt;
return sponsorCache.get(buildUrl); } final BuildDetail buildData = this.buildDetailFetcher.detailsOf(buildUrl); if (null == buildData) { return new HashSet<Sponsor>(); } final Set<Sponsor> sponsors = new HashSet<Sponsor>(detective.search(commitMessagesOf(buildData))); if (sponsors.isEmpty()) { for (String upstreamBuildUrl : buildData.upstreamBuildUrls()) { sponsors.addAll(sponsorsOf(communicator.endpoint() + "/" + upstreamBuildUrl)); } } final Set<Sponsor> result = unmodifiableSet(sponsors); if (!buildData.building) { sponsorCache.put(buildUrl, result); } return result; } private String commitMessagesOf(BuildDetail build) { if (null == build.changeSet || null == build.changeSet.items) { return ""; } final StringBuilder result = new StringBuilder();
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/ChangeSetItem.java // public final class ChangeSetItem { // //Date date; // public String msg; // public String comment; // public long revision; // public String user; // //paths // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/User.java // public final class User { // public String absoluteUrl; // public String fullName; // } // // Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // Path: src/main/java/org/netmelody/cieye/spies/jenkins/JobAnalyser.java import com.google.common.base.Function; import com.google.common.base.Predicate; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.jenkins.jsondomain.Build; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.ChangeSetItem; import org.netmelody.cieye.spies.jenkins.jsondomain.Job; import org.netmelody.cieye.spies.jenkins.jsondomain.JobDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.User; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.collect.Collections2.filter; import static com.google.common.collect.Collections2.transform; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.unmodifiableSet; import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import static org.netmelody.cieye.core.domain.RunningBuild.buildAt; return sponsorCache.get(buildUrl); } final BuildDetail buildData = this.buildDetailFetcher.detailsOf(buildUrl); if (null == buildData) { return new HashSet<Sponsor>(); } final Set<Sponsor> sponsors = new HashSet<Sponsor>(detective.search(commitMessagesOf(buildData))); if (sponsors.isEmpty()) { for (String upstreamBuildUrl : buildData.upstreamBuildUrls()) { sponsors.addAll(sponsorsOf(communicator.endpoint() + "/" + upstreamBuildUrl)); } } final Set<Sponsor> result = unmodifiableSet(sponsors); if (!buildData.building) { sponsorCache.put(buildUrl, result); } return result; } private String commitMessagesOf(BuildDetail build) { if (null == build.changeSet || null == build.changeSet.items) { return ""; } final StringBuilder result = new StringBuilder();
for (ChangeSetItem changeSetItem : build.changeSet.items) {
netmelody/ci-eye
src/main/java/org/netmelody/cieye/spies/jenkins/JobAnalyser.java
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/ChangeSetItem.java // public final class ChangeSetItem { // //Date date; // public String msg; // public String comment; // public long revision; // public String user; // //paths // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/User.java // public final class User { // public String absoluteUrl; // public String fullName; // } // // Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // }
import com.google.common.base.Function; import com.google.common.base.Predicate; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.jenkins.jsondomain.Build; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.ChangeSetItem; import org.netmelody.cieye.spies.jenkins.jsondomain.Job; import org.netmelody.cieye.spies.jenkins.jsondomain.JobDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.User; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.collect.Collections2.filter; import static com.google.common.collect.Collections2.transform; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.unmodifiableSet; import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import static org.netmelody.cieye.core.domain.RunningBuild.buildAt;
} final Set<Sponsor> sponsors = new HashSet<Sponsor>(detective.search(commitMessagesOf(buildData))); if (sponsors.isEmpty()) { for (String upstreamBuildUrl : buildData.upstreamBuildUrls()) { sponsors.addAll(sponsorsOf(communicator.endpoint() + "/" + upstreamBuildUrl)); } } final Set<Sponsor> result = unmodifiableSet(sponsors); if (!buildData.building) { sponsorCache.put(buildUrl, result); } return result; } private String commitMessagesOf(BuildDetail build) { if (null == build.changeSet || null == build.changeSet.items) { return ""; } final StringBuilder result = new StringBuilder(); for (ChangeSetItem changeSetItem : build.changeSet.items) { appendIfNotNull(result, changeSetItem.user); appendIfNotNull(result, changeSetItem.msg); appendIfNotNull(result, changeSetItem.comment); }
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/ChangeSetItem.java // public final class ChangeSetItem { // //Date date; // public String msg; // public String comment; // public long revision; // public String user; // //paths // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/User.java // public final class User { // public String absoluteUrl; // public String fullName; // } // // Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // Path: src/main/java/org/netmelody/cieye/spies/jenkins/JobAnalyser.java import com.google.common.base.Function; import com.google.common.base.Predicate; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.jenkins.jsondomain.Build; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.ChangeSetItem; import org.netmelody.cieye.spies.jenkins.jsondomain.Job; import org.netmelody.cieye.spies.jenkins.jsondomain.JobDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.User; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.collect.Collections2.filter; import static com.google.common.collect.Collections2.transform; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.unmodifiableSet; import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import static org.netmelody.cieye.core.domain.RunningBuild.buildAt; } final Set<Sponsor> sponsors = new HashSet<Sponsor>(detective.search(commitMessagesOf(buildData))); if (sponsors.isEmpty()) { for (String upstreamBuildUrl : buildData.upstreamBuildUrls()) { sponsors.addAll(sponsorsOf(communicator.endpoint() + "/" + upstreamBuildUrl)); } } final Set<Sponsor> result = unmodifiableSet(sponsors); if (!buildData.building) { sponsorCache.put(buildUrl, result); } return result; } private String commitMessagesOf(BuildDetail build) { if (null == build.changeSet || null == build.changeSet.items) { return ""; } final StringBuilder result = new StringBuilder(); for (ChangeSetItem changeSetItem : build.changeSet.items) { appendIfNotNull(result, changeSetItem.user); appendIfNotNull(result, changeSetItem.msg); appendIfNotNull(result, changeSetItem.comment); }
for (User user : build.culprits()) {
netmelody/ci-eye
src/main/java/org/netmelody/cieye/spies/jenkins/JobAnalyser.java
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/ChangeSetItem.java // public final class ChangeSetItem { // //Date date; // public String msg; // public String comment; // public long revision; // public String user; // //paths // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/User.java // public final class User { // public String absoluteUrl; // public String fullName; // } // // Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // }
import com.google.common.base.Function; import com.google.common.base.Predicate; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.jenkins.jsondomain.Build; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.ChangeSetItem; import org.netmelody.cieye.spies.jenkins.jsondomain.Job; import org.netmelody.cieye.spies.jenkins.jsondomain.JobDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.User; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.collect.Collections2.filter; import static com.google.common.collect.Collections2.transform; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.unmodifiableSet; import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import static org.netmelody.cieye.core.domain.RunningBuild.buildAt;
return result; } private String commitMessagesOf(BuildDetail build) { if (null == build.changeSet || null == build.changeSet.items) { return ""; } final StringBuilder result = new StringBuilder(); for (ChangeSetItem changeSetItem : build.changeSet.items) { appendIfNotNull(result, changeSetItem.user); appendIfNotNull(result, changeSetItem.msg); appendIfNotNull(result, changeSetItem.comment); } for (User user : build.culprits()) { appendIfNotNull(result, user.fullName); } return result.toString(); } private static void appendIfNotNull(StringBuilder buffer, String string) { if (string != null) { buffer.append(string); buffer.append(' '); } }
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/ChangeSetItem.java // public final class ChangeSetItem { // //Date date; // public String msg; // public String comment; // public long revision; // public String user; // //paths // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/User.java // public final class User { // public String absoluteUrl; // public String fullName; // } // // Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // Path: src/main/java/org/netmelody/cieye/spies/jenkins/JobAnalyser.java import com.google.common.base.Function; import com.google.common.base.Predicate; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.jenkins.jsondomain.Build; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.ChangeSetItem; import org.netmelody.cieye.spies.jenkins.jsondomain.Job; import org.netmelody.cieye.spies.jenkins.jsondomain.JobDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.User; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.collect.Collections2.filter; import static com.google.common.collect.Collections2.transform; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.unmodifiableSet; import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import static org.netmelody.cieye.core.domain.RunningBuild.buildAt; return result; } private String commitMessagesOf(BuildDetail build) { if (null == build.changeSet || null == build.changeSet.items) { return ""; } final StringBuilder result = new StringBuilder(); for (ChangeSetItem changeSetItem : build.changeSet.items) { appendIfNotNull(result, changeSetItem.user); appendIfNotNull(result, changeSetItem.msg); appendIfNotNull(result, changeSetItem.comment); } for (User user : build.culprits()) { appendIfNotNull(result, user.fullName); } return result.toString(); } private static void appendIfNotNull(StringBuilder buffer, String string) { if (string != null) { buffer.append(string); buffer.append(' '); } }
private List<RunningBuild> buildsFor(final JobDetail job) {
netmelody/ci-eye
src/main/java/org/netmelody/cieye/spies/jenkins/JobAnalyser.java
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/ChangeSetItem.java // public final class ChangeSetItem { // //Date date; // public String msg; // public String comment; // public long revision; // public String user; // //paths // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/User.java // public final class User { // public String absoluteUrl; // public String fullName; // } // // Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // }
import com.google.common.base.Function; import com.google.common.base.Predicate; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.jenkins.jsondomain.Build; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.ChangeSetItem; import org.netmelody.cieye.spies.jenkins.jsondomain.Job; import org.netmelody.cieye.spies.jenkins.jsondomain.JobDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.User; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.collect.Collections2.filter; import static com.google.common.collect.Collections2.transform; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.unmodifiableSet; import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import static org.netmelody.cieye.core.domain.RunningBuild.buildAt;
builds.add(job.lastBuild); } final long duration = this.buildDurationFetcher.lastGoodDurationOf(job); return newArrayList(transform(filter(transform(builds, toBuildDetail()), building()), toRunningBuild(duration))); } private Predicate<Build> after(final long lastCompletedJobNumber) { return new Predicate<Build>() { @Override public boolean apply(Build build) { return build.number > lastCompletedJobNumber; } }; } private Function<Build, BuildDetail> toBuildDetail() { return new Function<Build, BuildDetail>() { @Override public BuildDetail apply(Build build) { return buildDetailFetcher.detailsOf(build.url); } }; } private Predicate<BuildDetail> building() { return new Predicate<BuildDetail>() { @Override public boolean apply(BuildDetail build) { return build.building; } }; } private Function<BuildDetail, RunningBuild> toRunningBuild(final long duration) { return new Function<BuildDetail, RunningBuild>() { @Override public RunningBuild apply(BuildDetail buildDetail) {
// Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public final class RunningBuild { // // private final Percentage progress; // private final Status status; // // public RunningBuild() { // this(percentageOf(100), Status.GREEN); // } // // public RunningBuild(Percentage progress, Status status) { // this.progress = progress; // this.status = status; // } // // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // // public static RunningBuild buildAt(Percentage progress, Status status) { // return new RunningBuild(progress, status); // } // // public Percentage progress() { // return progress; // } // // public Status status() { // return status; // } // // public RunningBuild advancedBy(int percentageIncrement) { // return new RunningBuild(percentageOf(Math.min(progress.value() + percentageIncrement, 100)), status); // } // // public RunningBuild withStatus(Status status) { // return new RunningBuild(progress, status); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/ChangeSetItem.java // public final class ChangeSetItem { // //Date date; // public String msg; // public String comment; // public long revision; // public String user; // //paths // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/User.java // public final class User { // public String absoluteUrl; // public String fullName; // } // // Path: src/main/java/org/netmelody/cieye/core/domain/RunningBuild.java // public static RunningBuild buildAt(Percentage progress) { // return buildAt(progress, Status.UNKNOWN); // } // Path: src/main/java/org/netmelody/cieye/spies/jenkins/JobAnalyser.java import com.google.common.base.Function; import com.google.common.base.Predicate; import org.netmelody.cieye.core.domain.RunningBuild; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.core.domain.Status; import org.netmelody.cieye.core.domain.TargetDetail; import org.netmelody.cieye.core.observation.KnownOffendersDirectory; import org.netmelody.cieye.spies.jenkins.jsondomain.Build; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.ChangeSetItem; import org.netmelody.cieye.spies.jenkins.jsondomain.Job; import org.netmelody.cieye.spies.jenkins.jsondomain.JobDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.User; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.collect.Collections2.filter; import static com.google.common.collect.Collections2.transform; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.unmodifiableSet; import static org.netmelody.cieye.core.domain.Percentage.percentageOf; import static org.netmelody.cieye.core.domain.RunningBuild.buildAt; builds.add(job.lastBuild); } final long duration = this.buildDurationFetcher.lastGoodDurationOf(job); return newArrayList(transform(filter(transform(builds, toBuildDetail()), building()), toRunningBuild(duration))); } private Predicate<Build> after(final long lastCompletedJobNumber) { return new Predicate<Build>() { @Override public boolean apply(Build build) { return build.number > lastCompletedJobNumber; } }; } private Function<Build, BuildDetail> toBuildDetail() { return new Function<Build, BuildDetail>() { @Override public BuildDetail apply(Build build) { return buildDetailFetcher.detailsOf(build.url); } }; } private Predicate<BuildDetail> building() { return new Predicate<BuildDetail>() { @Override public boolean apply(BuildDetail build) { return build.building; } }; } private Function<BuildDetail, RunningBuild> toRunningBuild(final long duration) { return new Function<BuildDetail, RunningBuild>() { @Override public RunningBuild apply(BuildDetail buildDetail) {
return buildAt(percentageOf(new Date().getTime() - buildDetail.timestamp, duration));
netmelody/ci-eye
src/test/java/org/netmelody/cieye/spies/jenkins/test/JenkinsCommunicatorTest.java
// Path: src/main/java/org/netmelody/cieye/spies/jenkins/JenkinsCommunicator.java // public final class JenkinsCommunicator { // // private final Contact contact; // private final String endpoint; // // public JenkinsCommunicator(String endpoint, Contact contact) { // this.endpoint = endpoint; // this.contact = contact; // } // // public String endpoint() { // return endpoint; // } // // public boolean canSpeakFor(Feature feature) { // return endpoint.equals(feature.endpoint()); // } // // public void doJenkinsPost(String url) { // contact.doPost(url); // } // // public BuildDetail buildDetailsFor(String buildUrl) { // return makeJenkinsRestCall(buildUrl, BuildDetail.class); // } // // public JobDetail jobDetailFor(String jobEndpoint) { // return makeJenkinsRestCall(jobEndpoint, JobDetail.class); // } // // public String lastBadBuildFor(String jobEndpoint) { // return jobDetailFor(jobEndpoint).lastBadBuildUrl(); // } // // public Collection<Job> jobsFor(View viewDigest) { // return makeJenkinsRestCall(viewDigest.url, ViewDetail.class).jobs(); // } // // public Collection<View> views() { // return makeJenkinsRestCallWithSuffix("", Server.class).views(); // } // // private <T> T makeJenkinsRestCallWithSuffix(String urlSuffix, Class<T> type) { // return makeJenkinsRestCall(endpoint + ((urlSuffix.length() == 0) ? "" : ("/" + urlSuffix)), type); // } // // private <T> T makeJenkinsRestCall(String url, Class<T> type) { // final String reqUrl = url + (url.endsWith("/") ? "" : "/") + "api/json"; // return contact.makeJsonRestCall(reqUrl, type); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/ChangeSetItem.java // public final class ChangeSetItem { // //Date date; // public String msg; // public String comment; // public long revision; // public String user; // //paths // }
import com.google.common.base.Functions; import com.google.gson.Gson; import org.apache.commons.io.IOUtils; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.netmelody.cieye.server.observation.protocol.JsonRestRequester; import org.netmelody.cieye.server.observation.test.StubGrapeVine; import org.netmelody.cieye.spies.jenkins.JenkinsCommunicator; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.ChangeSetItem; import java.io.IOException; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue;
package org.netmelody.cieye.spies.jenkins.test; public final class JenkinsCommunicatorTest { private final StubGrapeVine channel = new StubGrapeVine();
// Path: src/main/java/org/netmelody/cieye/spies/jenkins/JenkinsCommunicator.java // public final class JenkinsCommunicator { // // private final Contact contact; // private final String endpoint; // // public JenkinsCommunicator(String endpoint, Contact contact) { // this.endpoint = endpoint; // this.contact = contact; // } // // public String endpoint() { // return endpoint; // } // // public boolean canSpeakFor(Feature feature) { // return endpoint.equals(feature.endpoint()); // } // // public void doJenkinsPost(String url) { // contact.doPost(url); // } // // public BuildDetail buildDetailsFor(String buildUrl) { // return makeJenkinsRestCall(buildUrl, BuildDetail.class); // } // // public JobDetail jobDetailFor(String jobEndpoint) { // return makeJenkinsRestCall(jobEndpoint, JobDetail.class); // } // // public String lastBadBuildFor(String jobEndpoint) { // return jobDetailFor(jobEndpoint).lastBadBuildUrl(); // } // // public Collection<Job> jobsFor(View viewDigest) { // return makeJenkinsRestCall(viewDigest.url, ViewDetail.class).jobs(); // } // // public Collection<View> views() { // return makeJenkinsRestCallWithSuffix("", Server.class).views(); // } // // private <T> T makeJenkinsRestCallWithSuffix(String urlSuffix, Class<T> type) { // return makeJenkinsRestCall(endpoint + ((urlSuffix.length() == 0) ? "" : ("/" + urlSuffix)), type); // } // // private <T> T makeJenkinsRestCall(String url, Class<T> type) { // final String reqUrl = url + (url.endsWith("/") ? "" : "/") + "api/json"; // return contact.makeJsonRestCall(reqUrl, type); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/ChangeSetItem.java // public final class ChangeSetItem { // //Date date; // public String msg; // public String comment; // public long revision; // public String user; // //paths // } // Path: src/test/java/org/netmelody/cieye/spies/jenkins/test/JenkinsCommunicatorTest.java import com.google.common.base.Functions; import com.google.gson.Gson; import org.apache.commons.io.IOUtils; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.netmelody.cieye.server.observation.protocol.JsonRestRequester; import org.netmelody.cieye.server.observation.test.StubGrapeVine; import org.netmelody.cieye.spies.jenkins.JenkinsCommunicator; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.ChangeSetItem; import java.io.IOException; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; package org.netmelody.cieye.spies.jenkins.test; public final class JenkinsCommunicatorTest { private final StubGrapeVine channel = new StubGrapeVine();
private JenkinsCommunicator communicator;
netmelody/ci-eye
src/test/java/org/netmelody/cieye/spies/jenkins/test/JenkinsCommunicatorTest.java
// Path: src/main/java/org/netmelody/cieye/spies/jenkins/JenkinsCommunicator.java // public final class JenkinsCommunicator { // // private final Contact contact; // private final String endpoint; // // public JenkinsCommunicator(String endpoint, Contact contact) { // this.endpoint = endpoint; // this.contact = contact; // } // // public String endpoint() { // return endpoint; // } // // public boolean canSpeakFor(Feature feature) { // return endpoint.equals(feature.endpoint()); // } // // public void doJenkinsPost(String url) { // contact.doPost(url); // } // // public BuildDetail buildDetailsFor(String buildUrl) { // return makeJenkinsRestCall(buildUrl, BuildDetail.class); // } // // public JobDetail jobDetailFor(String jobEndpoint) { // return makeJenkinsRestCall(jobEndpoint, JobDetail.class); // } // // public String lastBadBuildFor(String jobEndpoint) { // return jobDetailFor(jobEndpoint).lastBadBuildUrl(); // } // // public Collection<Job> jobsFor(View viewDigest) { // return makeJenkinsRestCall(viewDigest.url, ViewDetail.class).jobs(); // } // // public Collection<View> views() { // return makeJenkinsRestCallWithSuffix("", Server.class).views(); // } // // private <T> T makeJenkinsRestCallWithSuffix(String urlSuffix, Class<T> type) { // return makeJenkinsRestCall(endpoint + ((urlSuffix.length() == 0) ? "" : ("/" + urlSuffix)), type); // } // // private <T> T makeJenkinsRestCall(String url, Class<T> type) { // final String reqUrl = url + (url.endsWith("/") ? "" : "/") + "api/json"; // return contact.makeJsonRestCall(reqUrl, type); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/ChangeSetItem.java // public final class ChangeSetItem { // //Date date; // public String msg; // public String comment; // public long revision; // public String user; // //paths // }
import com.google.common.base.Functions; import com.google.gson.Gson; import org.apache.commons.io.IOUtils; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.netmelody.cieye.server.observation.protocol.JsonRestRequester; import org.netmelody.cieye.server.observation.test.StubGrapeVine; import org.netmelody.cieye.spies.jenkins.JenkinsCommunicator; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.ChangeSetItem; import java.io.IOException; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue;
package org.netmelody.cieye.spies.jenkins.test; public final class JenkinsCommunicatorTest { private final StubGrapeVine channel = new StubGrapeVine(); private JenkinsCommunicator communicator; @Before public void setup() { communicator = new JenkinsCommunicator("http://jenkins", new JsonRestRequester(new Gson(), Functions.<String>identity(), channel)); } @Test public void requestsSingularBuildChangesForJenkinsSvnBuild() { channel.respondingWith("http://jenkins/job/foo/2/api/json", contentFrom("jenkins_1.625.3_builddetail_2.json")); final BuildDetail buildDetail = communicator.buildDetailsFor("http://jenkins/job/foo/2");
// Path: src/main/java/org/netmelody/cieye/spies/jenkins/JenkinsCommunicator.java // public final class JenkinsCommunicator { // // private final Contact contact; // private final String endpoint; // // public JenkinsCommunicator(String endpoint, Contact contact) { // this.endpoint = endpoint; // this.contact = contact; // } // // public String endpoint() { // return endpoint; // } // // public boolean canSpeakFor(Feature feature) { // return endpoint.equals(feature.endpoint()); // } // // public void doJenkinsPost(String url) { // contact.doPost(url); // } // // public BuildDetail buildDetailsFor(String buildUrl) { // return makeJenkinsRestCall(buildUrl, BuildDetail.class); // } // // public JobDetail jobDetailFor(String jobEndpoint) { // return makeJenkinsRestCall(jobEndpoint, JobDetail.class); // } // // public String lastBadBuildFor(String jobEndpoint) { // return jobDetailFor(jobEndpoint).lastBadBuildUrl(); // } // // public Collection<Job> jobsFor(View viewDigest) { // return makeJenkinsRestCall(viewDigest.url, ViewDetail.class).jobs(); // } // // public Collection<View> views() { // return makeJenkinsRestCallWithSuffix("", Server.class).views(); // } // // private <T> T makeJenkinsRestCallWithSuffix(String urlSuffix, Class<T> type) { // return makeJenkinsRestCall(endpoint + ((urlSuffix.length() == 0) ? "" : ("/" + urlSuffix)), type); // } // // private <T> T makeJenkinsRestCall(String url, Class<T> type) { // final String reqUrl = url + (url.endsWith("/") ? "" : "/") + "api/json"; // return contact.makeJsonRestCall(reqUrl, type); // } // } // // Path: src/main/java/org/netmelody/cieye/spies/jenkins/jsondomain/ChangeSetItem.java // public final class ChangeSetItem { // //Date date; // public String msg; // public String comment; // public long revision; // public String user; // //paths // } // Path: src/test/java/org/netmelody/cieye/spies/jenkins/test/JenkinsCommunicatorTest.java import com.google.common.base.Functions; import com.google.gson.Gson; import org.apache.commons.io.IOUtils; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.netmelody.cieye.server.observation.protocol.JsonRestRequester; import org.netmelody.cieye.server.observation.test.StubGrapeVine; import org.netmelody.cieye.spies.jenkins.JenkinsCommunicator; import org.netmelody.cieye.spies.jenkins.jsondomain.BuildDetail; import org.netmelody.cieye.spies.jenkins.jsondomain.ChangeSetItem; import java.io.IOException; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; package org.netmelody.cieye.spies.jenkins.test; public final class JenkinsCommunicatorTest { private final StubGrapeVine channel = new StubGrapeVine(); private JenkinsCommunicator communicator; @Before public void setup() { communicator = new JenkinsCommunicator("http://jenkins", new JsonRestRequester(new Gson(), Functions.<String>identity(), channel)); } @Test public void requestsSingularBuildChangesForJenkinsSvnBuild() { channel.respondingWith("http://jenkins/job/foo/2/api/json", contentFrom("jenkins_1.625.3_builddetail_2.json")); final BuildDetail buildDetail = communicator.buildDetailsFor("http://jenkins/job/foo/2");
List<ChangeSetItem> changes = buildDetail.changeSet.items;
netmelody/ci-eye
src/main/java/org/netmelody/cieye/server/response/responder/LandscapeObservationResponder.java
// Path: src/main/java/org/netmelody/cieye/core/domain/LandscapeObservation.java // public final class LandscapeObservation { // // private final List<TargetDetail> targets = new ArrayList<TargetDetail>(); // private final Set<Sponsor> dohGroup; // // public LandscapeObservation() { // this(new TargetDetailGroup()); // } // // public LandscapeObservation(TargetDetailGroup targets) { // this(newArrayList(targets.targets()), null); // } // // private LandscapeObservation(Collection<TargetDetail> targets, Set<Sponsor> dohGroup) { // this.targets.addAll(targets); // this.dohGroup = (null == dohGroup) ? null : new HashSet<Sponsor>(dohGroup); // } // // public LandscapeObservation add(TargetDetailGroup group) { // if (null == group) { // return this; // } // final LandscapeObservation result = new LandscapeObservation(targets, dohGroup); // result.targets.addAll(newArrayList(group.targets())); // return result; // } // // public List<TargetDetail> targets() { // return new ArrayList<TargetDetail>(targets); // } // // public Set<Sponsor> dohGroup() { // return (null == dohGroup) ? new HashSet<Sponsor>() : new HashSet<Sponsor>(dohGroup); // } // // public LandscapeObservation withDoh(Set<Sponsor> dohGroup) { // return new LandscapeObservation(this.targets, dohGroup); // } // // public LandscapeObservation forSponsor(final Sponsor sponsor) { // return new LandscapeObservation(filter(targets, onSponsor(sponsor)), dohGroup); // } // // private Predicate<TargetDetail> onSponsor(final Sponsor sponsor) { // return new Predicate<TargetDetail>() { // @Override // public boolean apply(TargetDetail input) { // return input.sponsors().contains(sponsor); // } // }; // } // // }
import static java.lang.Math.min; import java.io.IOException; import com.google.common.base.Function; import com.google.common.base.Functions; import org.netmelody.cieye.core.domain.Feature; import org.netmelody.cieye.core.domain.Landscape; import org.netmelody.cieye.core.domain.LandscapeObservation; import org.netmelody.cieye.server.CiSpyIntermediary; import org.netmelody.cieye.server.TargetGroupBriefing; import org.netmelody.cieye.server.response.CiEyeResponder; import org.netmelody.cieye.server.response.CiEyeResponse; import org.netmelody.cieye.server.response.JsonTranslator; import org.netmelody.cieye.server.response.Prison; import org.simpleframework.http.Request;
package org.netmelody.cieye.server.response.responder; public final class LandscapeObservationResponder implements CiEyeResponder { private final CiSpyIntermediary spyIntermediary; private final Landscape landscape; private final Prison prison;
// Path: src/main/java/org/netmelody/cieye/core/domain/LandscapeObservation.java // public final class LandscapeObservation { // // private final List<TargetDetail> targets = new ArrayList<TargetDetail>(); // private final Set<Sponsor> dohGroup; // // public LandscapeObservation() { // this(new TargetDetailGroup()); // } // // public LandscapeObservation(TargetDetailGroup targets) { // this(newArrayList(targets.targets()), null); // } // // private LandscapeObservation(Collection<TargetDetail> targets, Set<Sponsor> dohGroup) { // this.targets.addAll(targets); // this.dohGroup = (null == dohGroup) ? null : new HashSet<Sponsor>(dohGroup); // } // // public LandscapeObservation add(TargetDetailGroup group) { // if (null == group) { // return this; // } // final LandscapeObservation result = new LandscapeObservation(targets, dohGroup); // result.targets.addAll(newArrayList(group.targets())); // return result; // } // // public List<TargetDetail> targets() { // return new ArrayList<TargetDetail>(targets); // } // // public Set<Sponsor> dohGroup() { // return (null == dohGroup) ? new HashSet<Sponsor>() : new HashSet<Sponsor>(dohGroup); // } // // public LandscapeObservation withDoh(Set<Sponsor> dohGroup) { // return new LandscapeObservation(this.targets, dohGroup); // } // // public LandscapeObservation forSponsor(final Sponsor sponsor) { // return new LandscapeObservation(filter(targets, onSponsor(sponsor)), dohGroup); // } // // private Predicate<TargetDetail> onSponsor(final Sponsor sponsor) { // return new Predicate<TargetDetail>() { // @Override // public boolean apply(TargetDetail input) { // return input.sponsors().contains(sponsor); // } // }; // } // // } // Path: src/main/java/org/netmelody/cieye/server/response/responder/LandscapeObservationResponder.java import static java.lang.Math.min; import java.io.IOException; import com.google.common.base.Function; import com.google.common.base.Functions; import org.netmelody.cieye.core.domain.Feature; import org.netmelody.cieye.core.domain.Landscape; import org.netmelody.cieye.core.domain.LandscapeObservation; import org.netmelody.cieye.server.CiSpyIntermediary; import org.netmelody.cieye.server.TargetGroupBriefing; import org.netmelody.cieye.server.response.CiEyeResponder; import org.netmelody.cieye.server.response.CiEyeResponse; import org.netmelody.cieye.server.response.JsonTranslator; import org.netmelody.cieye.server.response.Prison; import org.simpleframework.http.Request; package org.netmelody.cieye.server.response.responder; public final class LandscapeObservationResponder implements CiEyeResponder { private final CiSpyIntermediary spyIntermediary; private final Landscape landscape; private final Prison prison;
private final Function<LandscapeObservation, LandscapeObservation> converter;
Ordina-JTech/hack-a-drone
hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/io/Heartbeat.java
// Path: hackadrone-utils/src/main/java/nl/ordina/jtech/hackadrone/utils/ByteUtils.java // public final class ByteUtils { // // /** // * Generates bytes from numbers. // * // * @param values the values containing the numbers // * @return bytes containing the numbers // */ // public static byte[] asUnsigned(int... values) { // byte[] bytes = new byte[values.length]; // // for (int i = 0; i < values.length; i++) { // int value = values[i]; // // if (value > Byte.MAX_VALUE) { // bytes[i] = (byte) value; // } else { // bytes[i] = (byte) (value & 0xff); // } // } // // return bytes; // } // // /** // * Loads message from a file. // * // * @param fileName the file name containing the message // * @return a bytes array containing the message // * @throws IOException if loading the message from the file failed // */ // public static byte[] loadMessageFromFile(String fileName) throws IOException { // InputStream inputStream = ByteUtils.class.getResourceAsStream("/" + fileName); // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // // int read; // byte[] data = new byte[4096]; // // while ((read = inputStream.read(data, 0, data.length)) > 0) { // byteArrayOutputStream.write(data, 0, read); // } // // byteArrayOutputStream.flush(); // // return byteArrayOutputStream.toByteArray(); // } // // }
import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import nl.ordina.jtech.hackadrone.utils.ByteUtils;
socket = new Socket(host, port); super.start(); } catch (IOException e) { System.err.println("Connection failed!"); } } /** * Starts running the heartbeat. */ @Override public void run() { while (!isInterrupted()) { try { sendHeartBeat(); Thread.sleep(5000); } catch (IOException e) { System.err.println("Unable to send heartbeat"); } catch (InterruptedException e) { System.err.println("Heartbeat interrupted"); } } } /** * Sends a heartbeat to the drone. * * @throws IOException if sending the heartbeat to the drone failed */ private void sendHeartBeat() throws IOException {
// Path: hackadrone-utils/src/main/java/nl/ordina/jtech/hackadrone/utils/ByteUtils.java // public final class ByteUtils { // // /** // * Generates bytes from numbers. // * // * @param values the values containing the numbers // * @return bytes containing the numbers // */ // public static byte[] asUnsigned(int... values) { // byte[] bytes = new byte[values.length]; // // for (int i = 0; i < values.length; i++) { // int value = values[i]; // // if (value > Byte.MAX_VALUE) { // bytes[i] = (byte) value; // } else { // bytes[i] = (byte) (value & 0xff); // } // } // // return bytes; // } // // /** // * Loads message from a file. // * // * @param fileName the file name containing the message // * @return a bytes array containing the message // * @throws IOException if loading the message from the file failed // */ // public static byte[] loadMessageFromFile(String fileName) throws IOException { // InputStream inputStream = ByteUtils.class.getResourceAsStream("/" + fileName); // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // // int read; // byte[] data = new byte[4096]; // // while ((read = inputStream.read(data, 0, data.length)) > 0) { // byteArrayOutputStream.write(data, 0, read); // } // // byteArrayOutputStream.flush(); // // return byteArrayOutputStream.toByteArray(); // } // // } // Path: hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/io/Heartbeat.java import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import nl.ordina.jtech.hackadrone.utils.ByteUtils; socket = new Socket(host, port); super.start(); } catch (IOException e) { System.err.println("Connection failed!"); } } /** * Starts running the heartbeat. */ @Override public void run() { while (!isInterrupted()) { try { sendHeartBeat(); Thread.sleep(5000); } catch (IOException e) { System.err.println("Unable to send heartbeat"); } catch (InterruptedException e) { System.err.println("Heartbeat interrupted"); } } } /** * Sends a heartbeat to the drone. * * @throws IOException if sending the heartbeat to the drone failed */ private void sendHeartBeat() throws IOException {
byte[] heartbeatData = ByteUtils.loadMessageFromFile("bin/heartbeat.bin");
Ordina-JTech/hack-a-drone
hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/io/VideoFrame.java
// Path: hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/io/recognition/Prediction.java // public class Prediction { // // private String label; // private double percentage; // // public Prediction(String label, double percentage) { // this.label = label; // this.percentage = percentage; // } // // public void setLabel(final String label) { // this.label = label; // } // // public void setPercentage(final double percentage) { // this.percentage = percentage; // } // // public String toString() { // return String.format("%s: %.2f ", this.label, this.percentage); // } // // }
import java.awt.image.BufferedImage; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import nl.ordina.jtech.hackadrone.io.recognition.Prediction;
package nl.ordina.jtech.hackadrone.io; public class VideoFrame { private static final int FRAME_WIDTH = 720; private static final int FRAME_HEIGHT = 676; private JFrame frame; private JLabel label; private BufferedImage bufferedImage; public VideoFrame() { frame = new JFrame("Video Frame"); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); label = new JLabel(); frame.add(label); } public void showFrame() { frame.setVisible(true); } public void hideFrame() { frame.setVisible(false); } public void updateVideoFrame(BufferedImage bufferedImage) { setBufferedImage(bufferedImage); label.setIcon(new ImageIcon(bufferedImage)); }
// Path: hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/io/recognition/Prediction.java // public class Prediction { // // private String label; // private double percentage; // // public Prediction(String label, double percentage) { // this.label = label; // this.percentage = percentage; // } // // public void setLabel(final String label) { // this.label = label; // } // // public void setPercentage(final double percentage) { // this.percentage = percentage; // } // // public String toString() { // return String.format("%s: %.2f ", this.label, this.percentage); // } // // } // Path: hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/io/VideoFrame.java import java.awt.image.BufferedImage; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import nl.ordina.jtech.hackadrone.io.recognition.Prediction; package nl.ordina.jtech.hackadrone.io; public class VideoFrame { private static final int FRAME_WIDTH = 720; private static final int FRAME_HEIGHT = 676; private JFrame frame; private JLabel label; private BufferedImage bufferedImage; public VideoFrame() { frame = new JFrame("Video Frame"); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); label = new JLabel(); frame.add(label); } public void showFrame() { frame.setVisible(true); } public void hideFrame() { frame.setVisible(false); } public void updateVideoFrame(BufferedImage bufferedImage) { setBufferedImage(bufferedImage); label.setIcon(new ImageIcon(bufferedImage)); }
public void setFrameLabel(List<Prediction> predictionList) {
Ordina-JTech/hack-a-drone
hackadrone-api/src/main/java/nl/ordina/jtech/hackadrone/Drone.java
// Path: hackadrone-api/src/main/java/nl/ordina/jtech/hackadrone/io/Device.java // public interface Device extends Handler { // // /** // * Sets the listener. // * // * @param commandListener the command listener to set // */ // void setListener(CommandListener commandListener); // // } // // Path: hackadrone-api/src/main/java/nl/ordina/jtech/hackadrone/net/Connection.java // public interface Connection { // // /** // * Connects. // * // * @throws IOException if the connection failed // */ // void connect() throws IOException; // // /** // * Disconnects. // * // * @throws IOException if the disconnection failed // */ // void disconnect() throws IOException; // // }
import nl.ordina.jtech.hackadrone.io.Device; import nl.ordina.jtech.hackadrone.net.Connection;
/* * Copyright (C) 2017 Ordina * * 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 nl.ordina.jtech.hackadrone; /** * Interface representing a drone. */ public interface Drone extends Connection { /** * Connects. * * @throws DroneException if the connection failed */ @Override void connect() throws DroneException; /** * Disconnects. * * @throws DroneException if the disconnection failed */ @Override void disconnect() throws DroneException; /** * Sends messages. * * @throws DroneException if sending the messages failed */ void sendMessages() throws DroneException; /** * Starts the heartbeat. * * @throws DroneException if starting the heartbeat failed */ void startHeartbeat() throws DroneException; /** * Stops the heartbeat. * * @throws DroneException if stopping the heartbeat failed */ void stopHeartbeat() throws DroneException; /** * Starts the controls. * * @param device the device to use the controls from * @throws DroneException if starting the controls failed */
// Path: hackadrone-api/src/main/java/nl/ordina/jtech/hackadrone/io/Device.java // public interface Device extends Handler { // // /** // * Sets the listener. // * // * @param commandListener the command listener to set // */ // void setListener(CommandListener commandListener); // // } // // Path: hackadrone-api/src/main/java/nl/ordina/jtech/hackadrone/net/Connection.java // public interface Connection { // // /** // * Connects. // * // * @throws IOException if the connection failed // */ // void connect() throws IOException; // // /** // * Disconnects. // * // * @throws IOException if the disconnection failed // */ // void disconnect() throws IOException; // // } // Path: hackadrone-api/src/main/java/nl/ordina/jtech/hackadrone/Drone.java import nl.ordina.jtech.hackadrone.io.Device; import nl.ordina.jtech.hackadrone.net.Connection; /* * Copyright (C) 2017 Ordina * * 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 nl.ordina.jtech.hackadrone; /** * Interface representing a drone. */ public interface Drone extends Connection { /** * Connects. * * @throws DroneException if the connection failed */ @Override void connect() throws DroneException; /** * Disconnects. * * @throws DroneException if the disconnection failed */ @Override void disconnect() throws DroneException; /** * Sends messages. * * @throws DroneException if sending the messages failed */ void sendMessages() throws DroneException; /** * Starts the heartbeat. * * @throws DroneException if starting the heartbeat failed */ void startHeartbeat() throws DroneException; /** * Stops the heartbeat. * * @throws DroneException if stopping the heartbeat failed */ void stopHeartbeat() throws DroneException; /** * Starts the controls. * * @param device the device to use the controls from * @throws DroneException if starting the controls failed */
void startControls(Device device) throws DroneException;
Ordina-JTech/hack-a-drone
hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/io/DeepLearning.java
// Path: hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/io/recognition/Prediction.java // public class Prediction { // // private String label; // private double percentage; // // public Prediction(String label, double percentage) { // this.label = label; // this.percentage = percentage; // } // // public void setLabel(final String label) { // this.label = label; // } // // public void setPercentage(final double percentage) { // this.percentage = percentage; // } // // public String toString() { // return String.format("%s: %.2f ", this.label, this.percentage); // } // // }
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import nl.ordina.jtech.hackadrone.io.recognition.Prediction; import org.datavec.image.loader.NativeImageLoader; import org.deeplearning4j.nn.graph.ComputationGraph; import org.deeplearning4j.util.ModelSerializer; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization; import org.nd4j.linalg.dataset.api.preprocessor.VGG16ImagePreProcessor; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.shade.jackson.databind.ObjectMapper;
package nl.ordina.jtech.hackadrone.io; public class DeepLearning { private static final int HEIGHT = 224; private static final int WIDTH = 224; private static final int CHANNELS = 3; /** * Reference to Video Frame */ private VideoFrame videoFrame; /** * Computational graph for deep learning */ private ComputationGraph computationGraphVGG16; private NativeImageLoader nativeImageLoader; public DeepLearning() { this.nativeImageLoader = new NativeImageLoader(HEIGHT, WIDTH, CHANNELS); loadDataModel(); } /** * Load the dataset and the computational graph for deep learning */ private void loadDataModel() { //TODO Deep Learning Challenge Part 1: load existing data model computationGraphVGG16 = null; } /** * Pre process the image to create a matrix */ private INDArray processImage(BufferedImage bufferedImage) { //TODO Deep Learning Challenge Part 2: Normalize the Image INDArray imageMatrix = null; normalizeImage(imageMatrix); return imageMatrix; } /** * Classify images */
// Path: hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/io/recognition/Prediction.java // public class Prediction { // // private String label; // private double percentage; // // public Prediction(String label, double percentage) { // this.label = label; // this.percentage = percentage; // } // // public void setLabel(final String label) { // this.label = label; // } // // public void setPercentage(final double percentage) { // this.percentage = percentage; // } // // public String toString() { // return String.format("%s: %.2f ", this.label, this.percentage); // } // // } // Path: hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/io/DeepLearning.java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import nl.ordina.jtech.hackadrone.io.recognition.Prediction; import org.datavec.image.loader.NativeImageLoader; import org.deeplearning4j.nn.graph.ComputationGraph; import org.deeplearning4j.util.ModelSerializer; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization; import org.nd4j.linalg.dataset.api.preprocessor.VGG16ImagePreProcessor; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.shade.jackson.databind.ObjectMapper; package nl.ordina.jtech.hackadrone.io; public class DeepLearning { private static final int HEIGHT = 224; private static final int WIDTH = 224; private static final int CHANNELS = 3; /** * Reference to Video Frame */ private VideoFrame videoFrame; /** * Computational graph for deep learning */ private ComputationGraph computationGraphVGG16; private NativeImageLoader nativeImageLoader; public DeepLearning() { this.nativeImageLoader = new NativeImageLoader(HEIGHT, WIDTH, CHANNELS); loadDataModel(); } /** * Load the dataset and the computational graph for deep learning */ private void loadDataModel() { //TODO Deep Learning Challenge Part 1: load existing data model computationGraphVGG16 = null; } /** * Pre process the image to create a matrix */ private INDArray processImage(BufferedImage bufferedImage) { //TODO Deep Learning Challenge Part 2: Normalize the Image INDArray imageMatrix = null; normalizeImage(imageMatrix); return imageMatrix; } /** * Classify images */
private List<Prediction> classify(BufferedImage bufferedImage) {
Ordina-JTech/hack-a-drone
hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/io/Controller.java
// Path: hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/net/CommandConnection.java // public final class CommandConnection implements Execute { // // /** // * The socket of the command connection. // */ // private final DatagramSocket socket = new DatagramSocket(); // // /** // * The host of the command connection. // */ // private final InetAddress host; // // /** // * The port of the command connection. // */ // private final int port; // // /** // * A command connection constructor. // * // * @param host the host of the command connection // * @param port the port of the command connection // * @throws IOException if the connection failed // */ // public CommandConnection(String host, int port) throws IOException { // this.host = InetAddress.getByName(host); // this.port = port; // } // // /** // * Sends a command. // * // * @param command the command to send // * @throws IOException if sending the command failed // */ // @Override // public void sendCommand(Command command) throws IOException { // byte[] data = asByteArray(command); // DatagramPacket packet = new DatagramPacket(data, 0, data.length, host, port); // socket.send(packet); // } // // /** // * Converts a command into bytes. // * // * @param command the command to convert into bytes // * @return bytes containing the command // */ // private byte[] asByteArray(Command command) { // int pitch = command.getPitch() + 128; // int yaw = command.getYaw() + 128; // int roll = command.getRoll() + 128; // int throttle = command.getThrottle() + 128; // boolean takeOff = command.isTakeOff(); // boolean land = command.isLand(); // // byte[] data = new byte[8]; // data[0] = (byte) 0xCC; // data[1] = (byte) roll; // data[2] = (byte) pitch; // data[3] = (byte) throttle; // data[4] = (byte) yaw; // // if (takeOff) { // data[5] = (byte) 0x01; // } else if (land) { // data[5] = (byte) 0x02; // } else { // data[5] = (byte) 0x00; // } // // data[6] = checksum(ByteUtils.asUnsigned(data[1], data[2], data[3], data[4], data[5])); // data[7] = (byte) 0x33; // // return data; // } // // /** // * Generates a digit representing the sum of the correct digits in a piece of transmitted digital data. // * // * @param bytes the bytes to check // * @return the sum // */ // private static byte checksum(byte[] bytes) { // byte sum = 0; // // for (byte b : bytes) { // sum ^= b; // } // // return sum; // } // // }
import nl.ordina.jtech.hackadrone.net.CommandConnection;
/* * Copyright (C) 2017 Ordina * * 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 nl.ordina.jtech.hackadrone.io; /** * Class representing the controller for a drone. */ public abstract class Controller extends Thread implements CommandListener { /** * The device to control the drone with. */ protected final Device device; /** * The command connection with the drone. */
// Path: hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/net/CommandConnection.java // public final class CommandConnection implements Execute { // // /** // * The socket of the command connection. // */ // private final DatagramSocket socket = new DatagramSocket(); // // /** // * The host of the command connection. // */ // private final InetAddress host; // // /** // * The port of the command connection. // */ // private final int port; // // /** // * A command connection constructor. // * // * @param host the host of the command connection // * @param port the port of the command connection // * @throws IOException if the connection failed // */ // public CommandConnection(String host, int port) throws IOException { // this.host = InetAddress.getByName(host); // this.port = port; // } // // /** // * Sends a command. // * // * @param command the command to send // * @throws IOException if sending the command failed // */ // @Override // public void sendCommand(Command command) throws IOException { // byte[] data = asByteArray(command); // DatagramPacket packet = new DatagramPacket(data, 0, data.length, host, port); // socket.send(packet); // } // // /** // * Converts a command into bytes. // * // * @param command the command to convert into bytes // * @return bytes containing the command // */ // private byte[] asByteArray(Command command) { // int pitch = command.getPitch() + 128; // int yaw = command.getYaw() + 128; // int roll = command.getRoll() + 128; // int throttle = command.getThrottle() + 128; // boolean takeOff = command.isTakeOff(); // boolean land = command.isLand(); // // byte[] data = new byte[8]; // data[0] = (byte) 0xCC; // data[1] = (byte) roll; // data[2] = (byte) pitch; // data[3] = (byte) throttle; // data[4] = (byte) yaw; // // if (takeOff) { // data[5] = (byte) 0x01; // } else if (land) { // data[5] = (byte) 0x02; // } else { // data[5] = (byte) 0x00; // } // // data[6] = checksum(ByteUtils.asUnsigned(data[1], data[2], data[3], data[4], data[5])); // data[7] = (byte) 0x33; // // return data; // } // // /** // * Generates a digit representing the sum of the correct digits in a piece of transmitted digital data. // * // * @param bytes the bytes to check // * @return the sum // */ // private static byte checksum(byte[] bytes) { // byte sum = 0; // // for (byte b : bytes) { // sum ^= b; // } // // return sum; // } // // } // Path: hackadrone-core/src/main/java/nl/ordina/jtech/hackadrone/io/Controller.java import nl.ordina.jtech.hackadrone.net.CommandConnection; /* * Copyright (C) 2017 Ordina * * 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 nl.ordina.jtech.hackadrone.io; /** * Class representing the controller for a drone. */ public abstract class Controller extends Thread implements CommandListener { /** * The device to control the drone with. */ protected final Device device; /** * The command connection with the drone. */
protected final CommandConnection commandConnection;
OHDSI/MedlineXmlToDatabase
src/org/ohdsi/utilities/files/Row.java
// Path: src/org/ohdsi/utilities/StringUtilities.java // public class StringUtilities { // // public static String join(Collection<?> s, String delimiter) { // StringBuffer buffer = new StringBuffer(); // Iterator<?> iter = s.iterator(); // if (iter.hasNext()) { // buffer.append(iter.next().toString()); // } // while (iter.hasNext()) { // buffer.append(delimiter); // buffer.append(iter.next().toString()); // } // return buffer.toString(); // } // // public static String join(Object[] objects, String delimiter) { // StringBuffer buffer = new StringBuffer(); // if (objects.length != 0) // buffer.append(objects[0].toString()); // for (int i = 1; i < objects.length; i++) { // buffer.append(delimiter); // buffer.append(objects[i].toString()); // } // return buffer.toString(); // } // // public static String now() { // Date d = new Date(); // DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); // return df.format(d); // } // // public static void outputWithTime(String message) { // System.out.println(now() + "\t" + message); // } // // public static String findBetween(String source, String pre, String post) { // int start = source.indexOf(pre); // if (start == -1) // return ""; // int end = source.indexOf(post, start + pre.length()); // if (end == -1) // return ""; // return source.substring(start + pre.length(), end); // } // // public static List<String> multiFindBetween(String source, String pre, String post) { // List<String> result = new ArrayList<String>(); // int start = 0; // int end = 0; // while (start != -1 && end != -1) { // start = source.indexOf(pre, end); // if (start != -1) { // end = source.indexOf(post, start + pre.length()); // if (end != -1) // result.add(source.substring(start + pre.length(), end)); // } // } // return result; // } // // public static boolean isInteger(String string) { // try { // Integer.parseInt(string); // } catch (NumberFormatException e) { // return false; // } // return true; // } // // public static List<String> safeSplit(String string, char delimiter) { // List<String> result = new ArrayList<String>(); // if (string.length() == 0) { // result.add(""); // return result; // } // boolean literal = false; // boolean escape = false; // int startpos = 0; // int i = 0; // char currentchar; // while (i < string.length()) { // currentchar = string.charAt(i); // if (currentchar == '"' && !escape) { // literal = !literal; // } // if (!literal && (currentchar == delimiter && !escape)) { // result.add(string.substring(startpos, i)); // startpos = i + 1; // } // if (currentchar == '\\') { // escape = !escape; // } else { // escape = false; // } // i++; // } // result.add(string.substring(startpos, i)); // return result; // } // // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.ohdsi.utilities.StringUtilities;
cells.set(fieldName2ColumnIndex.get(fieldName), value); } public void set(String fieldName, int value) { set(fieldName, Integer.toString(value)); } public void set(String fieldName, long value) { set(fieldName, Long.toString(value)); } public void set(String fieldName, double value) { set(fieldName, Double.toString(value)); } public List<String> getCells() { return cells; } protected Map<String, Integer> getfieldName2ColumnIndex() { return fieldName2ColumnIndex; } public String toString() { List<String> data = new ArrayList<String>(cells); for (String fieldName : fieldName2ColumnIndex.keySet()) { int index = fieldName2ColumnIndex.get(fieldName); if (data.size() > index) data.set(index, "[" + fieldName + ": " + data.get(index) + "]"); }
// Path: src/org/ohdsi/utilities/StringUtilities.java // public class StringUtilities { // // public static String join(Collection<?> s, String delimiter) { // StringBuffer buffer = new StringBuffer(); // Iterator<?> iter = s.iterator(); // if (iter.hasNext()) { // buffer.append(iter.next().toString()); // } // while (iter.hasNext()) { // buffer.append(delimiter); // buffer.append(iter.next().toString()); // } // return buffer.toString(); // } // // public static String join(Object[] objects, String delimiter) { // StringBuffer buffer = new StringBuffer(); // if (objects.length != 0) // buffer.append(objects[0].toString()); // for (int i = 1; i < objects.length; i++) { // buffer.append(delimiter); // buffer.append(objects[i].toString()); // } // return buffer.toString(); // } // // public static String now() { // Date d = new Date(); // DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); // return df.format(d); // } // // public static void outputWithTime(String message) { // System.out.println(now() + "\t" + message); // } // // public static String findBetween(String source, String pre, String post) { // int start = source.indexOf(pre); // if (start == -1) // return ""; // int end = source.indexOf(post, start + pre.length()); // if (end == -1) // return ""; // return source.substring(start + pre.length(), end); // } // // public static List<String> multiFindBetween(String source, String pre, String post) { // List<String> result = new ArrayList<String>(); // int start = 0; // int end = 0; // while (start != -1 && end != -1) { // start = source.indexOf(pre, end); // if (start != -1) { // end = source.indexOf(post, start + pre.length()); // if (end != -1) // result.add(source.substring(start + pre.length(), end)); // } // } // return result; // } // // public static boolean isInteger(String string) { // try { // Integer.parseInt(string); // } catch (NumberFormatException e) { // return false; // } // return true; // } // // public static List<String> safeSplit(String string, char delimiter) { // List<String> result = new ArrayList<String>(); // if (string.length() == 0) { // result.add(""); // return result; // } // boolean literal = false; // boolean escape = false; // int startpos = 0; // int i = 0; // char currentchar; // while (i < string.length()) { // currentchar = string.charAt(i); // if (currentchar == '"' && !escape) { // literal = !literal; // } // if (!literal && (currentchar == delimiter && !escape)) { // result.add(string.substring(startpos, i)); // startpos = i + 1; // } // if (currentchar == '\\') { // escape = !escape; // } else { // escape = false; // } // i++; // } // result.add(string.substring(startpos, i)); // return result; // } // // } // Path: src/org/ohdsi/utilities/files/Row.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.ohdsi.utilities.StringUtilities; cells.set(fieldName2ColumnIndex.get(fieldName), value); } public void set(String fieldName, int value) { set(fieldName, Integer.toString(value)); } public void set(String fieldName, long value) { set(fieldName, Long.toString(value)); } public void set(String fieldName, double value) { set(fieldName, Double.toString(value)); } public List<String> getCells() { return cells; } protected Map<String, Integer> getfieldName2ColumnIndex() { return fieldName2ColumnIndex; } public String toString() { List<String> data = new ArrayList<String>(cells); for (String fieldName : fieldName2ColumnIndex.keySet()) { int index = fieldName2ColumnIndex.get(fieldName); if (data.size() > index) data.set(index, "[" + fieldName + ": " + data.get(index) + "]"); }
return StringUtilities.join(data, ",");
OHDSI/MedlineXmlToDatabase
src/org/ohdsi/utilities/files/ReadCSVFile.java
// Path: src/org/ohdsi/utilities/StringUtilities.java // public class StringUtilities { // // public static String join(Collection<?> s, String delimiter) { // StringBuffer buffer = new StringBuffer(); // Iterator<?> iter = s.iterator(); // if (iter.hasNext()) { // buffer.append(iter.next().toString()); // } // while (iter.hasNext()) { // buffer.append(delimiter); // buffer.append(iter.next().toString()); // } // return buffer.toString(); // } // // public static String join(Object[] objects, String delimiter) { // StringBuffer buffer = new StringBuffer(); // if (objects.length != 0) // buffer.append(objects[0].toString()); // for (int i = 1; i < objects.length; i++) { // buffer.append(delimiter); // buffer.append(objects[i].toString()); // } // return buffer.toString(); // } // // public static String now() { // Date d = new Date(); // DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); // return df.format(d); // } // // public static void outputWithTime(String message) { // System.out.println(now() + "\t" + message); // } // // public static String findBetween(String source, String pre, String post) { // int start = source.indexOf(pre); // if (start == -1) // return ""; // int end = source.indexOf(post, start + pre.length()); // if (end == -1) // return ""; // return source.substring(start + pre.length(), end); // } // // public static List<String> multiFindBetween(String source, String pre, String post) { // List<String> result = new ArrayList<String>(); // int start = 0; // int end = 0; // while (start != -1 && end != -1) { // start = source.indexOf(pre, end); // if (start != -1) { // end = source.indexOf(post, start + pre.length()); // if (end != -1) // result.add(source.substring(start + pre.length(), end)); // } // } // return result; // } // // public static boolean isInteger(String string) { // try { // Integer.parseInt(string); // } catch (NumberFormatException e) { // return false; // } // return true; // } // // public static List<String> safeSplit(String string, char delimiter) { // List<String> result = new ArrayList<String>(); // if (string.length() == 0) { // result.add(""); // return result; // } // boolean literal = false; // boolean escape = false; // int startpos = 0; // int i = 0; // char currentchar; // while (i < string.length()) { // currentchar = string.charAt(i); // if (currentchar == '"' && !escape) { // literal = !literal; // } // if (!literal && (currentchar == delimiter && !escape)) { // result.add(string.substring(startpos, i)); // startpos = i + 1; // } // if (currentchar == '\\') { // escape = !escape; // } else { // escape = false; // } // i++; // } // result.add(string.substring(startpos, i)); // return result; // } // // }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.List; import org.ohdsi.utilities.StringUtilities;
public boolean hasNext() { return !EOF; } public List<String> next() { String result = buffer; try { buffer = bufferedReader.readLine(); if (buffer == null){ EOF = true; bufferedReader.close(); } } catch (IOException e) { e.printStackTrace(); } return line2columns(result); } public void remove() { System.err.println("Unimplemented method 'remove' called"); } } public Iterator<List<String>> iterator() { return new CSVFileIterator(); } private List<String> line2columns(String line){
// Path: src/org/ohdsi/utilities/StringUtilities.java // public class StringUtilities { // // public static String join(Collection<?> s, String delimiter) { // StringBuffer buffer = new StringBuffer(); // Iterator<?> iter = s.iterator(); // if (iter.hasNext()) { // buffer.append(iter.next().toString()); // } // while (iter.hasNext()) { // buffer.append(delimiter); // buffer.append(iter.next().toString()); // } // return buffer.toString(); // } // // public static String join(Object[] objects, String delimiter) { // StringBuffer buffer = new StringBuffer(); // if (objects.length != 0) // buffer.append(objects[0].toString()); // for (int i = 1; i < objects.length; i++) { // buffer.append(delimiter); // buffer.append(objects[i].toString()); // } // return buffer.toString(); // } // // public static String now() { // Date d = new Date(); // DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); // return df.format(d); // } // // public static void outputWithTime(String message) { // System.out.println(now() + "\t" + message); // } // // public static String findBetween(String source, String pre, String post) { // int start = source.indexOf(pre); // if (start == -1) // return ""; // int end = source.indexOf(post, start + pre.length()); // if (end == -1) // return ""; // return source.substring(start + pre.length(), end); // } // // public static List<String> multiFindBetween(String source, String pre, String post) { // List<String> result = new ArrayList<String>(); // int start = 0; // int end = 0; // while (start != -1 && end != -1) { // start = source.indexOf(pre, end); // if (start != -1) { // end = source.indexOf(post, start + pre.length()); // if (end != -1) // result.add(source.substring(start + pre.length(), end)); // } // } // return result; // } // // public static boolean isInteger(String string) { // try { // Integer.parseInt(string); // } catch (NumberFormatException e) { // return false; // } // return true; // } // // public static List<String> safeSplit(String string, char delimiter) { // List<String> result = new ArrayList<String>(); // if (string.length() == 0) { // result.add(""); // return result; // } // boolean literal = false; // boolean escape = false; // int startpos = 0; // int i = 0; // char currentchar; // while (i < string.length()) { // currentchar = string.charAt(i); // if (currentchar == '"' && !escape) { // literal = !literal; // } // if (!literal && (currentchar == delimiter && !escape)) { // result.add(string.substring(startpos, i)); // startpos = i + 1; // } // if (currentchar == '\\') { // escape = !escape; // } else { // escape = false; // } // i++; // } // result.add(string.substring(startpos, i)); // return result; // } // // } // Path: src/org/ohdsi/utilities/files/ReadCSVFile.java import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.List; import org.ohdsi.utilities.StringUtilities; public boolean hasNext() { return !EOF; } public List<String> next() { String result = buffer; try { buffer = bufferedReader.readLine(); if (buffer == null){ EOF = true; bufferedReader.close(); } } catch (IOException e) { e.printStackTrace(); } return line2columns(result); } public void remove() { System.err.println("Unimplemented method 'remove' called"); } } public Iterator<List<String>> iterator() { return new CSVFileIterator(); } private List<String> line2columns(String line){
List<String> columns = StringUtilities.safeSplit(line, delimiter);
OHDSI/MedlineXmlToDatabase
src/org/ohdsi/medlineXmlToDatabase/XMLFileIterator.java
// Path: src/org/ohdsi/utilities/RandomUtilities.java // public class RandomUtilities { // public static <T> List<T> sampleWithoutReplacement(List<T> items, int sampleSize) { // if (sampleSize > items.size()) { // return items; // } // Random random = new Random(); // List<T> sample = new ArrayList<T>(); // for (int i = 0; i < sampleSize; i++) // sample.add(items.remove(random.nextInt(items.size()))); // return sample; // } // // public static int[] sampleWithoutReplacement(int minValue, int maxValue, int sampleSize) { // if (sampleSize > (maxValue - minValue + 1)) { // int[] sample = new int[maxValue - minValue + 1]; // for (int i = minValue; i <= maxValue; i++) // sample[i - minValue] = i; // return sample; // } else { // Random random = new Random(); // int[] sample = new int[sampleSize]; // for (int i = 0; i < sampleSize; i++) { // int number = random.nextInt(maxValue - minValue + 1); // while (contains(sample, number)) // number = random.nextInt(maxValue - minValue + 1); // sample[i] = number; // } // return sample; // } // // } // // private static boolean contains(int[] sample, int number) { // for (int i : sample) // if (i == number) // return true; // return false; // } // // } // // Path: src/org/ohdsi/utilities/concurrency/BatchProcessingThread.java // public abstract class BatchProcessingThread extends Thread { // private final Semaphore newInputSemaphore = new Semaphore(); // private final Semaphore newOutputSemaphore = new Semaphore(); // private boolean terminated = false; // // public BatchProcessingThread(){ // super(); // this.start(); // // } // // public void run(){ // while (true){ // newInputSemaphore.release(); // if (terminated) // break; // process(); // newOutputSemaphore.take(); // } // } // // protected abstract void process(); // // public void proceed(){ //This method will be run in the other thread! // newInputSemaphore.take(); // } // // public void waitUntilFinished(){ //Runs in other thread! // newOutputSemaphore.release(); // } // // public synchronized void terminate(){//Runs in other thread! // terminated = true; // newInputSemaphore.take(); // } // // // }
import org.ohdsi.utilities.RandomUtilities; import org.ohdsi.utilities.concurrency.BatchProcessingThread; import org.w3c.dom.Document; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.zip.GZIPInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException;
/******************************************************************************* * Copyright 2014 Observational Health Data Sciences and Informatics * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.ohdsi.medlineXmlToDatabase; /** * Iterates over all xml.gz files in a specified folder, decompressing and parsing them in a separate thread. * * @author Schuemie * */ public class XMLFileIterator implements Iterator<Document> { private Iterator<File> fileIterator; private DecompressAndParseThread decompressAndParseThread = new DecompressAndParseThread(); private boolean hasNext = true; /** * @param folder * Specifies the absolute path to the folder containing the xml files */ public XMLFileIterator(String folder) { this(folder, Integer.MAX_VALUE); } /** * * @param folder * Specifies the absolute path to the folder containing the xml files * @param sampleSize * Specifies the maximum number of files that is randomly sampled */ public XMLFileIterator(String folder, int sampleSize) { List<File> files = new ArrayList<File>(); for (File file : new File(folder).listFiles()) if (file.getAbsolutePath().endsWith("xml.gz")) files.add(file);
// Path: src/org/ohdsi/utilities/RandomUtilities.java // public class RandomUtilities { // public static <T> List<T> sampleWithoutReplacement(List<T> items, int sampleSize) { // if (sampleSize > items.size()) { // return items; // } // Random random = new Random(); // List<T> sample = new ArrayList<T>(); // for (int i = 0; i < sampleSize; i++) // sample.add(items.remove(random.nextInt(items.size()))); // return sample; // } // // public static int[] sampleWithoutReplacement(int minValue, int maxValue, int sampleSize) { // if (sampleSize > (maxValue - minValue + 1)) { // int[] sample = new int[maxValue - minValue + 1]; // for (int i = minValue; i <= maxValue; i++) // sample[i - minValue] = i; // return sample; // } else { // Random random = new Random(); // int[] sample = new int[sampleSize]; // for (int i = 0; i < sampleSize; i++) { // int number = random.nextInt(maxValue - minValue + 1); // while (contains(sample, number)) // number = random.nextInt(maxValue - minValue + 1); // sample[i] = number; // } // return sample; // } // // } // // private static boolean contains(int[] sample, int number) { // for (int i : sample) // if (i == number) // return true; // return false; // } // // } // // Path: src/org/ohdsi/utilities/concurrency/BatchProcessingThread.java // public abstract class BatchProcessingThread extends Thread { // private final Semaphore newInputSemaphore = new Semaphore(); // private final Semaphore newOutputSemaphore = new Semaphore(); // private boolean terminated = false; // // public BatchProcessingThread(){ // super(); // this.start(); // // } // // public void run(){ // while (true){ // newInputSemaphore.release(); // if (terminated) // break; // process(); // newOutputSemaphore.take(); // } // } // // protected abstract void process(); // // public void proceed(){ //This method will be run in the other thread! // newInputSemaphore.take(); // } // // public void waitUntilFinished(){ //Runs in other thread! // newOutputSemaphore.release(); // } // // public synchronized void terminate(){//Runs in other thread! // terminated = true; // newInputSemaphore.take(); // } // // // } // Path: src/org/ohdsi/medlineXmlToDatabase/XMLFileIterator.java import org.ohdsi.utilities.RandomUtilities; import org.ohdsi.utilities.concurrency.BatchProcessingThread; import org.w3c.dom.Document; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.zip.GZIPInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; /******************************************************************************* * Copyright 2014 Observational Health Data Sciences and Informatics * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.ohdsi.medlineXmlToDatabase; /** * Iterates over all xml.gz files in a specified folder, decompressing and parsing them in a separate thread. * * @author Schuemie * */ public class XMLFileIterator implements Iterator<Document> { private Iterator<File> fileIterator; private DecompressAndParseThread decompressAndParseThread = new DecompressAndParseThread(); private boolean hasNext = true; /** * @param folder * Specifies the absolute path to the folder containing the xml files */ public XMLFileIterator(String folder) { this(folder, Integer.MAX_VALUE); } /** * * @param folder * Specifies the absolute path to the folder containing the xml files * @param sampleSize * Specifies the maximum number of files that is randomly sampled */ public XMLFileIterator(String folder, int sampleSize) { List<File> files = new ArrayList<File>(); for (File file : new File(folder).listFiles()) if (file.getAbsolutePath().endsWith("xml.gz")) files.add(file);
files = RandomUtilities.sampleWithoutReplacement(files, sampleSize);
OHDSI/MedlineXmlToDatabase
src/org/ohdsi/medlineXmlToDatabase/XMLFileIterator.java
// Path: src/org/ohdsi/utilities/RandomUtilities.java // public class RandomUtilities { // public static <T> List<T> sampleWithoutReplacement(List<T> items, int sampleSize) { // if (sampleSize > items.size()) { // return items; // } // Random random = new Random(); // List<T> sample = new ArrayList<T>(); // for (int i = 0; i < sampleSize; i++) // sample.add(items.remove(random.nextInt(items.size()))); // return sample; // } // // public static int[] sampleWithoutReplacement(int minValue, int maxValue, int sampleSize) { // if (sampleSize > (maxValue - minValue + 1)) { // int[] sample = new int[maxValue - minValue + 1]; // for (int i = minValue; i <= maxValue; i++) // sample[i - minValue] = i; // return sample; // } else { // Random random = new Random(); // int[] sample = new int[sampleSize]; // for (int i = 0; i < sampleSize; i++) { // int number = random.nextInt(maxValue - minValue + 1); // while (contains(sample, number)) // number = random.nextInt(maxValue - minValue + 1); // sample[i] = number; // } // return sample; // } // // } // // private static boolean contains(int[] sample, int number) { // for (int i : sample) // if (i == number) // return true; // return false; // } // // } // // Path: src/org/ohdsi/utilities/concurrency/BatchProcessingThread.java // public abstract class BatchProcessingThread extends Thread { // private final Semaphore newInputSemaphore = new Semaphore(); // private final Semaphore newOutputSemaphore = new Semaphore(); // private boolean terminated = false; // // public BatchProcessingThread(){ // super(); // this.start(); // // } // // public void run(){ // while (true){ // newInputSemaphore.release(); // if (terminated) // break; // process(); // newOutputSemaphore.take(); // } // } // // protected abstract void process(); // // public void proceed(){ //This method will be run in the other thread! // newInputSemaphore.take(); // } // // public void waitUntilFinished(){ //Runs in other thread! // newOutputSemaphore.release(); // } // // public synchronized void terminate(){//Runs in other thread! // terminated = true; // newInputSemaphore.take(); // } // // // }
import org.ohdsi.utilities.RandomUtilities; import org.ohdsi.utilities.concurrency.BatchProcessingThread; import org.w3c.dom.Document; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.zip.GZIPInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException;
decompressAndParseThread.startProcessing(fileIterator.next()); else { hasNext = false; decompressAndParseThread.terminate(); } } @Override public boolean hasNext() { return hasNext; } @Override public Document next() { decompressAndParseThread.waitUntilFinished(); Document document = decompressAndParseThread.getDocument(); if (fileIterator.hasNext()) decompressAndParseThread.startProcessing(fileIterator.next()); else { hasNext = false; decompressAndParseThread.terminate(); } return document; } @Override public void remove() { throw new RuntimeException("Calling unimplemented method remove in " + this.getClass().getName()); }
// Path: src/org/ohdsi/utilities/RandomUtilities.java // public class RandomUtilities { // public static <T> List<T> sampleWithoutReplacement(List<T> items, int sampleSize) { // if (sampleSize > items.size()) { // return items; // } // Random random = new Random(); // List<T> sample = new ArrayList<T>(); // for (int i = 0; i < sampleSize; i++) // sample.add(items.remove(random.nextInt(items.size()))); // return sample; // } // // public static int[] sampleWithoutReplacement(int minValue, int maxValue, int sampleSize) { // if (sampleSize > (maxValue - minValue + 1)) { // int[] sample = new int[maxValue - minValue + 1]; // for (int i = minValue; i <= maxValue; i++) // sample[i - minValue] = i; // return sample; // } else { // Random random = new Random(); // int[] sample = new int[sampleSize]; // for (int i = 0; i < sampleSize; i++) { // int number = random.nextInt(maxValue - minValue + 1); // while (contains(sample, number)) // number = random.nextInt(maxValue - minValue + 1); // sample[i] = number; // } // return sample; // } // // } // // private static boolean contains(int[] sample, int number) { // for (int i : sample) // if (i == number) // return true; // return false; // } // // } // // Path: src/org/ohdsi/utilities/concurrency/BatchProcessingThread.java // public abstract class BatchProcessingThread extends Thread { // private final Semaphore newInputSemaphore = new Semaphore(); // private final Semaphore newOutputSemaphore = new Semaphore(); // private boolean terminated = false; // // public BatchProcessingThread(){ // super(); // this.start(); // // } // // public void run(){ // while (true){ // newInputSemaphore.release(); // if (terminated) // break; // process(); // newOutputSemaphore.take(); // } // } // // protected abstract void process(); // // public void proceed(){ //This method will be run in the other thread! // newInputSemaphore.take(); // } // // public void waitUntilFinished(){ //Runs in other thread! // newOutputSemaphore.release(); // } // // public synchronized void terminate(){//Runs in other thread! // terminated = true; // newInputSemaphore.take(); // } // // // } // Path: src/org/ohdsi/medlineXmlToDatabase/XMLFileIterator.java import org.ohdsi.utilities.RandomUtilities; import org.ohdsi.utilities.concurrency.BatchProcessingThread; import org.w3c.dom.Document; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.zip.GZIPInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; decompressAndParseThread.startProcessing(fileIterator.next()); else { hasNext = false; decompressAndParseThread.terminate(); } } @Override public boolean hasNext() { return hasNext; } @Override public Document next() { decompressAndParseThread.waitUntilFinished(); Document document = decompressAndParseThread.getDocument(); if (fileIterator.hasNext()) decompressAndParseThread.startProcessing(fileIterator.next()); else { hasNext = false; decompressAndParseThread.terminate(); } return document; } @Override public void remove() { throw new RuntimeException("Calling unimplemented method remove in " + this.getClass().getName()); }
private class DecompressAndParseThread extends BatchProcessingThread {
OHDSI/MedlineXmlToDatabase
src/org/ohdsi/databases/InsertableDbTable.java
// Path: src/org/ohdsi/utilities/files/Row.java // public class Row { // private List<String> cells; // private Map<String, Integer> fieldName2ColumnIndex; // // public Row() { // fieldName2ColumnIndex = new HashMap<String, Integer>(); // cells = new ArrayList<String>(); // } // // public Row(List<String> cells, Map<String, Integer> fieldName2ColumnIndex) { // this.cells = cells; // this.fieldName2ColumnIndex = fieldName2ColumnIndex; // } // // public Row(Row row) { // cells = new ArrayList<String>(row.cells); // fieldName2ColumnIndex = new HashMap<String, Integer>(row.fieldName2ColumnIndex); // } // // public String get(String fieldName) { // int index; // try { // index = fieldName2ColumnIndex.get(fieldName); // } catch (NullPointerException e) { // throw new RuntimeException("Field \"" + fieldName + "\" not found"); // } // if (cells.size() <= index) // return null; // else // return cells.get(index); // } // // public List<String> getFieldNames() { // List<String> names = new ArrayList<String>(fieldName2ColumnIndex.size()); // for (int i = 0; i < fieldName2ColumnIndex.size(); i++) // names.add(null); // for (Map.Entry<String, Integer> entry : fieldName2ColumnIndex.entrySet()) // names.set(entry.getValue(), entry.getKey()); // return names; // } // // public int getInt(String fieldName) { // return Integer.parseInt(get(fieldName).trim()); // } // // public long getLong(String fieldName) { // return Long.parseLong(get(fieldName)); // } // // public double getDouble(String fieldName) { // return Double.parseDouble(get(fieldName)); // } // // public void add(String fieldName, String value) { // fieldName2ColumnIndex.put(fieldName, cells.size()); // cells.add(value); // } // // public void add(String fieldName, int value) { // add(fieldName, Integer.toString(value)); // } // // public void add(String fieldName, boolean value) { // add(fieldName, Boolean.toString(value)); // } // // public void add(String fieldName, double value) { // add(fieldName, Double.toString(value)); // } // // public void add(String fieldName, long value) { // add(fieldName, Long.toString(value)); // } // // public void set(String fieldName, String value) { // cells.set(fieldName2ColumnIndex.get(fieldName), value); // } // // public void set(String fieldName, int value) { // set(fieldName, Integer.toString(value)); // } // // public void set(String fieldName, long value) { // set(fieldName, Long.toString(value)); // } // // public void set(String fieldName, double value) { // set(fieldName, Double.toString(value)); // } // // public List<String> getCells() { // return cells; // } // // protected Map<String, Integer> getfieldName2ColumnIndex() { // return fieldName2ColumnIndex; // } // // public String toString() { // List<String> data = new ArrayList<String>(cells); // for (String fieldName : fieldName2ColumnIndex.keySet()) { // int index = fieldName2ColumnIndex.get(fieldName); // if (data.size() > index) // data.set(index, "[" + fieldName + ": " + data.get(index) + "]"); // } // return StringUtilities.join(data, ","); // } // // public void remove(String field) { // Integer index = fieldName2ColumnIndex.remove(field); // cells.remove(index); // Map<String, Integer> tempMap = new HashMap<String, Integer>(); // for (Map.Entry<String, Integer> entry : fieldName2ColumnIndex.entrySet()) // if (entry.getValue() > index) // tempMap.put(entry.getKey(), entry.getValue() - 1); // else // tempMap.put(entry.getKey(), entry.getValue()); // } // // public void upperCaseFieldNames() { // Map<String, Integer> tempMap = new HashMap<String, Integer>(); // for (Map.Entry<String, Integer> entry : fieldName2ColumnIndex.entrySet()) // tempMap.put(entry.getKey().toUpperCase(), entry.getValue()); // fieldName2ColumnIndex = tempMap; // } // // public int size() { // return cells.size(); // } // // public String get(int i) { // return cells.get(i); // } // }
import java.util.ArrayList; import java.util.List; import org.ohdsi.utilities.files.Row;
package org.ohdsi.databases; public class InsertableDbTable { public static int batchSize = 1000;
// Path: src/org/ohdsi/utilities/files/Row.java // public class Row { // private List<String> cells; // private Map<String, Integer> fieldName2ColumnIndex; // // public Row() { // fieldName2ColumnIndex = new HashMap<String, Integer>(); // cells = new ArrayList<String>(); // } // // public Row(List<String> cells, Map<String, Integer> fieldName2ColumnIndex) { // this.cells = cells; // this.fieldName2ColumnIndex = fieldName2ColumnIndex; // } // // public Row(Row row) { // cells = new ArrayList<String>(row.cells); // fieldName2ColumnIndex = new HashMap<String, Integer>(row.fieldName2ColumnIndex); // } // // public String get(String fieldName) { // int index; // try { // index = fieldName2ColumnIndex.get(fieldName); // } catch (NullPointerException e) { // throw new RuntimeException("Field \"" + fieldName + "\" not found"); // } // if (cells.size() <= index) // return null; // else // return cells.get(index); // } // // public List<String> getFieldNames() { // List<String> names = new ArrayList<String>(fieldName2ColumnIndex.size()); // for (int i = 0; i < fieldName2ColumnIndex.size(); i++) // names.add(null); // for (Map.Entry<String, Integer> entry : fieldName2ColumnIndex.entrySet()) // names.set(entry.getValue(), entry.getKey()); // return names; // } // // public int getInt(String fieldName) { // return Integer.parseInt(get(fieldName).trim()); // } // // public long getLong(String fieldName) { // return Long.parseLong(get(fieldName)); // } // // public double getDouble(String fieldName) { // return Double.parseDouble(get(fieldName)); // } // // public void add(String fieldName, String value) { // fieldName2ColumnIndex.put(fieldName, cells.size()); // cells.add(value); // } // // public void add(String fieldName, int value) { // add(fieldName, Integer.toString(value)); // } // // public void add(String fieldName, boolean value) { // add(fieldName, Boolean.toString(value)); // } // // public void add(String fieldName, double value) { // add(fieldName, Double.toString(value)); // } // // public void add(String fieldName, long value) { // add(fieldName, Long.toString(value)); // } // // public void set(String fieldName, String value) { // cells.set(fieldName2ColumnIndex.get(fieldName), value); // } // // public void set(String fieldName, int value) { // set(fieldName, Integer.toString(value)); // } // // public void set(String fieldName, long value) { // set(fieldName, Long.toString(value)); // } // // public void set(String fieldName, double value) { // set(fieldName, Double.toString(value)); // } // // public List<String> getCells() { // return cells; // } // // protected Map<String, Integer> getfieldName2ColumnIndex() { // return fieldName2ColumnIndex; // } // // public String toString() { // List<String> data = new ArrayList<String>(cells); // for (String fieldName : fieldName2ColumnIndex.keySet()) { // int index = fieldName2ColumnIndex.get(fieldName); // if (data.size() > index) // data.set(index, "[" + fieldName + ": " + data.get(index) + "]"); // } // return StringUtilities.join(data, ","); // } // // public void remove(String field) { // Integer index = fieldName2ColumnIndex.remove(field); // cells.remove(index); // Map<String, Integer> tempMap = new HashMap<String, Integer>(); // for (Map.Entry<String, Integer> entry : fieldName2ColumnIndex.entrySet()) // if (entry.getValue() > index) // tempMap.put(entry.getKey(), entry.getValue() - 1); // else // tempMap.put(entry.getKey(), entry.getValue()); // } // // public void upperCaseFieldNames() { // Map<String, Integer> tempMap = new HashMap<String, Integer>(); // for (Map.Entry<String, Integer> entry : fieldName2ColumnIndex.entrySet()) // tempMap.put(entry.getKey().toUpperCase(), entry.getValue()); // fieldName2ColumnIndex = tempMap; // } // // public int size() { // return cells.size(); // } // // public String get(int i) { // return cells.get(i); // } // } // Path: src/org/ohdsi/databases/InsertableDbTable.java import java.util.ArrayList; import java.util.List; import org.ohdsi.utilities.files.Row; package org.ohdsi.databases; public class InsertableDbTable { public static int batchSize = 1000;
private List<Row> batch;
OHDSI/MedlineXmlToDatabase
src/org/ohdsi/medlineXmlToDatabase/MainClass.java
// Path: src/org/ohdsi/meshXmlToDatabase/MeshParserMain.java // public class MeshParserMain { // // private Map<String, String> treeNumberToUi; // // public static void main(String[] args) { // IniFile iniFile = new IniFile(args[0]); // MeshParserMain meshParser = new MeshParserMain(); // meshParser.parseMesh(iniFile.get("MESH_XML_FOLDER"), iniFile.get("SERVER"), iniFile.get("SCHEMA"), iniFile.get("DOMAIN"), iniFile.get("USER"), // iniFile.get("PASSWORD"), iniFile.get("DATA_SOURCE_TYPE")); // // } // // private void parseMesh(String folder, String server, String schema, String domain, String user, String password, String dateSourceType) { // String meshFile = null; // String meshSupplementFile = null; // for (File file : new File(folder).listFiles()) { // String fileName = file.getName(); // if (fileName.startsWith("desc") && fileName.endsWith(".gz")) { // if (meshFile != null) // throw new RuntimeException("Error: Multiple main MeSH files found. Please have only 1 in the folder"); // else // meshFile = file.getAbsolutePath(); // } // if (fileName.startsWith("supp") && fileName.endsWith(".gz")) { // if (meshSupplementFile != null) // throw new RuntimeException("Error: Multiple supplementary MeSH files found. Please have only 1 in the folder"); // else // meshSupplementFile = file.getAbsolutePath(); // } // } // if (meshFile == null) // throw new RuntimeException("Error: No main MeSH file found."); // if (meshSupplementFile == null) // throw new RuntimeException("Error: No supplementary MeSH file found."); // ConnectionWrapper connectionWrapper = new ConnectionWrapper(server, domain, user, password, new DbType(dateSourceType)); // connectionWrapper.use(schema); // // treeNumberToUi = new HashMap<String, String>(); // InsertableDbTable outTerms = new InsertableDbTable(connectionWrapper, "mesh_term"); // InsertableDbTable outRelationship = new InsertableDbTable(connectionWrapper, "mesh_relationship"); // // MainMeshParser.parse(meshFile, outTerms, outRelationship, treeNumberToUi); // SupplementaryMeshParser.parse(meshSupplementFile, outTerms, outRelationship); // outTerms.close(); // outRelationship.close(); // // InsertableDbTable outAncestor = new InsertableDbTable(connectionWrapper, "mesh_ancestor"); // generateAncestorTable(outAncestor); // outAncestor.close(); // } // // private void generateAncestorTable(InsertableDbTable outAncestor) { // Map<String, PairInfo> pairToInfo = new HashMap<String, PairInfo>(); // for (String treeNumber1 : treeNumberToUi.keySet()) { // String parts[] = treeNumber1.split("\\."); // String ui1 = treeNumberToUi.get(treeNumber1); // for (int i = 0; i < parts.length; i++) { // int distance = parts.length - i - 1; // String treeNumber2 = StringUtilities.join(Arrays.copyOfRange(parts, 0, i + 1), "."); // String ui2 = treeNumberToUi.get(treeNumber2); // PairInfo pairInfo = pairToInfo.get(ui1 + "_" + ui2); // if (pairInfo == null) { // pairInfo = new PairInfo(distance, distance); // pairToInfo.put(ui1 + "_" + ui2, pairInfo); // } else { // if (pairInfo.maxDistance < distance) // pairInfo.maxDistance = distance; // if (pairInfo.minDistance > distance) // pairInfo.minDistance = distance; // } // } // } // // for (String pair : pairToInfo.keySet()) { // PairInfo pairInfo = pairToInfo.get(pair); // Row row = new Row(); // row.add("ancestor_ui", pair.split("_")[1]); // row.add("descendant_ui", pair.split("_")[0]); // row.add("max_distance", pairInfo.maxDistance); // row.add("min_distance", pairInfo.minDistance); // outAncestor.write(row); // } // } // // private class PairInfo { // public int minDistance; // public int maxDistance; // // public PairInfo(int minDistance, int maxDistance) { // this.minDistance = minDistance; // this.maxDistance = maxDistance; // } // } // }
import org.ohdsi.meshXmlToDatabase.MeshParserMain;
/******************************************************************************* * Copyright 2014 Observational Health Data Sciences and Informatics * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.ohdsi.medlineXmlToDatabase; /** * The main class that parses the command line arguments, and calls either MedlineAnalyserMain or MedlineParserMain * @author MSCHUEMI * */ public class MainClass { private static enum Action { ANALYSE, PARSE, PARSE_MESH }; private static Action action; private static String pathToIniFile; public static void main(String[] args) { if (args.length == 0) { System.out.println("See https://github.com/OHDSI/MedlineXmlToDatabase for details on how to use"); return; } parseParameters(args); if (action == Action.ANALYSE) MedlineAnalyserMain.main(new String[] { pathToIniFile }); else if (action == Action.PARSE) MedlineParserMain.main(new String[] { pathToIniFile }); if (action == Action.PARSE_MESH)
// Path: src/org/ohdsi/meshXmlToDatabase/MeshParserMain.java // public class MeshParserMain { // // private Map<String, String> treeNumberToUi; // // public static void main(String[] args) { // IniFile iniFile = new IniFile(args[0]); // MeshParserMain meshParser = new MeshParserMain(); // meshParser.parseMesh(iniFile.get("MESH_XML_FOLDER"), iniFile.get("SERVER"), iniFile.get("SCHEMA"), iniFile.get("DOMAIN"), iniFile.get("USER"), // iniFile.get("PASSWORD"), iniFile.get("DATA_SOURCE_TYPE")); // // } // // private void parseMesh(String folder, String server, String schema, String domain, String user, String password, String dateSourceType) { // String meshFile = null; // String meshSupplementFile = null; // for (File file : new File(folder).listFiles()) { // String fileName = file.getName(); // if (fileName.startsWith("desc") && fileName.endsWith(".gz")) { // if (meshFile != null) // throw new RuntimeException("Error: Multiple main MeSH files found. Please have only 1 in the folder"); // else // meshFile = file.getAbsolutePath(); // } // if (fileName.startsWith("supp") && fileName.endsWith(".gz")) { // if (meshSupplementFile != null) // throw new RuntimeException("Error: Multiple supplementary MeSH files found. Please have only 1 in the folder"); // else // meshSupplementFile = file.getAbsolutePath(); // } // } // if (meshFile == null) // throw new RuntimeException("Error: No main MeSH file found."); // if (meshSupplementFile == null) // throw new RuntimeException("Error: No supplementary MeSH file found."); // ConnectionWrapper connectionWrapper = new ConnectionWrapper(server, domain, user, password, new DbType(dateSourceType)); // connectionWrapper.use(schema); // // treeNumberToUi = new HashMap<String, String>(); // InsertableDbTable outTerms = new InsertableDbTable(connectionWrapper, "mesh_term"); // InsertableDbTable outRelationship = new InsertableDbTable(connectionWrapper, "mesh_relationship"); // // MainMeshParser.parse(meshFile, outTerms, outRelationship, treeNumberToUi); // SupplementaryMeshParser.parse(meshSupplementFile, outTerms, outRelationship); // outTerms.close(); // outRelationship.close(); // // InsertableDbTable outAncestor = new InsertableDbTable(connectionWrapper, "mesh_ancestor"); // generateAncestorTable(outAncestor); // outAncestor.close(); // } // // private void generateAncestorTable(InsertableDbTable outAncestor) { // Map<String, PairInfo> pairToInfo = new HashMap<String, PairInfo>(); // for (String treeNumber1 : treeNumberToUi.keySet()) { // String parts[] = treeNumber1.split("\\."); // String ui1 = treeNumberToUi.get(treeNumber1); // for (int i = 0; i < parts.length; i++) { // int distance = parts.length - i - 1; // String treeNumber2 = StringUtilities.join(Arrays.copyOfRange(parts, 0, i + 1), "."); // String ui2 = treeNumberToUi.get(treeNumber2); // PairInfo pairInfo = pairToInfo.get(ui1 + "_" + ui2); // if (pairInfo == null) { // pairInfo = new PairInfo(distance, distance); // pairToInfo.put(ui1 + "_" + ui2, pairInfo); // } else { // if (pairInfo.maxDistance < distance) // pairInfo.maxDistance = distance; // if (pairInfo.minDistance > distance) // pairInfo.minDistance = distance; // } // } // } // // for (String pair : pairToInfo.keySet()) { // PairInfo pairInfo = pairToInfo.get(pair); // Row row = new Row(); // row.add("ancestor_ui", pair.split("_")[1]); // row.add("descendant_ui", pair.split("_")[0]); // row.add("max_distance", pairInfo.maxDistance); // row.add("min_distance", pairInfo.minDistance); // outAncestor.write(row); // } // } // // private class PairInfo { // public int minDistance; // public int maxDistance; // // public PairInfo(int minDistance, int maxDistance) { // this.minDistance = minDistance; // this.maxDistance = maxDistance; // } // } // } // Path: src/org/ohdsi/medlineXmlToDatabase/MainClass.java import org.ohdsi.meshXmlToDatabase.MeshParserMain; /******************************************************************************* * Copyright 2014 Observational Health Data Sciences and Informatics * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.ohdsi.medlineXmlToDatabase; /** * The main class that parses the command line arguments, and calls either MedlineAnalyserMain or MedlineParserMain * @author MSCHUEMI * */ public class MainClass { private static enum Action { ANALYSE, PARSE, PARSE_MESH }; private static Action action; private static String pathToIniFile; public static void main(String[] args) { if (args.length == 0) { System.out.println("See https://github.com/OHDSI/MedlineXmlToDatabase for details on how to use"); return; } parseParameters(args); if (action == Action.ANALYSE) MedlineAnalyserMain.main(new String[] { pathToIniFile }); else if (action == Action.PARSE) MedlineParserMain.main(new String[] { pathToIniFile }); if (action == Action.PARSE_MESH)
MeshParserMain.main(new String[] { pathToIniFile });
aradomski/Navigator
app/src/main/java/pl/edu/radomski/navigator/examples/GroupedParamsForResultActivity.java
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // }
import android.content.Intent; import android.os.Bundle; import android.view.View; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.params.Book;
/* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.examples; /** * Created by adam on 8/24/15. */ @Navigable public class GroupedParamsForResultActivity extends BaseActivity { @Param(forResult = true, group = "group1") Integer integerParam; @Param(forResult = true, group = "group1") String stringParam; @Param(forResult = true, group = "group2")
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // Path: app/src/main/java/pl/edu/radomski/navigator/examples/GroupedParamsForResultActivity.java import android.content.Intent; import android.os.Bundle; import android.view.View; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.params.Book; /* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.examples; /** * Created by adam on 8/24/15. */ @Navigable public class GroupedParamsForResultActivity extends BaseActivity { @Param(forResult = true, group = "group1") Integer integerParam; @Param(forResult = true, group = "group1") String stringParam; @Param(forResult = true, group = "group2")
Book parcelableParam;
aradomski/Navigator
app/src/main/java/pl/edu/radomski/navigator/examples/ForResultActivity.java
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // }
import android.content.Intent; import android.os.Bundle; import android.view.View; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.params.Book;
/* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.examples; /** * Created by adam on 8/24/15. */ @Navigable public class ForResultActivity extends BaseActivity { @Result String stringResult = "abcdefghijk"; @Result
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // Path: app/src/main/java/pl/edu/radomski/navigator/examples/ForResultActivity.java import android.content.Intent; import android.os.Bundle; import android.view.View; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.params.Book; /* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.examples; /** * Created by adam on 8/24/15. */ @Navigable public class ForResultActivity extends BaseActivity { @Result String stringResult = "abcdefghijk"; @Result
Book book;
aradomski/Navigator
app/src/main/java/pl/edu/radomski/navigator/examples/NamedParamsAndResultActivity.java
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // }
import android.content.Intent; import android.os.Bundle; import android.view.View; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.params.Book;
package pl.edu.radomski.navigator.examples; /** * Created by adam on 10.01.16. */ @Navigable(name = "customNameWithParams") public class NamedParamsAndResultActivity extends BaseActivity { @Param(forResult = true) Integer integerParam; @Param(forResult = true) String stringParam; @Param(group = "OtherGroup")
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // Path: app/src/main/java/pl/edu/radomski/navigator/examples/NamedParamsAndResultActivity.java import android.content.Intent; import android.os.Bundle; import android.view.View; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.params.Book; package pl.edu.radomski.navigator.examples; /** * Created by adam on 10.01.16. */ @Navigable(name = "customNameWithParams") public class NamedParamsAndResultActivity extends BaseActivity { @Param(forResult = true) Integer integerParam; @Param(forResult = true) String stringParam; @Param(group = "OtherGroup")
Book parcelableParam;
aradomski/Navigator
compiler/src/test/java/pl/edu/radomski/navigator/NavigatorCodeGeneratorParameterizedTest.java
// Path: compiler/src/main/java/pl/edu/radomski/navigator/exceptions/NotAllFieldsAreAnnotatedForResultException.java // public class NotAllFieldsAreAnnotatedForResultException extends RuntimeException { // public NotAllFieldsAreAnnotatedForResultException(String message) { // super(message); // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/navigable/NavigableAnnotatedClass.java // public class NavigableAnnotatedClass { // // // public static NavigableAnnotatedClass from(TypeElement typeElement) throws VariableElementValidationException { // // Navigable annotation = typeElement.getAnnotation(Navigable.class); // // NavigableAnnotatedClass navigableAnnotatedClass = new NavigableAnnotatedClass(typeElement, annotation.group()); // HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); // HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); // ArrayList<String> errors; // Param paramAnnotation; // Result resultAnnotation; // for (Element element : typeElement.getEnclosedElements()) { // if (!(element instanceof VariableElement)) { // continue; // } // VariableElement variableElement = (VariableElement) element; // if (AnnotationValidator.isAnnotated(variableElement, Param.class)) { // paramAnnotation = variableElement.getAnnotation(Param.class); // errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); // if (errors.size() == 0) { // CollectionUtils.addToHashMapWithList(paramAnnotatedFields, paramAnnotation.group(), variableElement); // } else { // throw new VariableElementValidationException(errors); // } // } // if (AnnotationValidator.isAnnotated(variableElement, Result.class)) { // resultAnnotation = variableElement.getAnnotation(Result.class); // errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); // if (errors.size() == 0) { // CollectionUtils.addToHashMapWithList(resultAnnotatedFields, resultAnnotation.group(), variableElement); // } else { // throw new VariableElementValidationException(errors); // } // } // } // // navigableAnnotatedClass.paramAnnotatedFields = paramAnnotatedFields; // navigableAnnotatedClass.resultAnnotatedFields = resultAnnotatedFields; // navigableAnnotatedClass.navigableAnnotation = annotation; // // return navigableAnnotatedClass; // } // // private HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); // private HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); // private final String annotatedClassName; // private final TypeElement typeElement; // private final String group; // private Navigable navigableAnnotation; // // // public NavigableAnnotatedClass(TypeElement typeElement, String group) { // this.annotatedClassName = typeElement.getSimpleName().toString(); // this.typeElement = typeElement; // this.group = group; // // } // // public HashMap<String, List<VariableElement>> getParamAnnotatedFields() { // return paramAnnotatedFields; // } // // public HashMap<String, List<VariableElement>> getResultAnnotatedFields() { // return resultAnnotatedFields; // } // // public String getAnnotatedClassName() { // return annotatedClassName; // } // // public TypeElement getTypeElement() { // return typeElement; // } // // public String getGroup() { // return group; // } // // public Navigable getNavigableAnnotation() { // return navigableAnnotation; // } // }
import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.Mock; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import pl.edu.radomski.navigator.exceptions.NotAllFieldsAreAnnotatedForResultException; import pl.edu.radomski.navigator.navigable.NavigableAnnotatedClass; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when;
package pl.edu.radomski.navigator; /** * Created by adam on 1/9/16. */ @RunWith(Parameterized.class) public class NavigatorCodeGeneratorParameterizedTest { @Mock
// Path: compiler/src/main/java/pl/edu/radomski/navigator/exceptions/NotAllFieldsAreAnnotatedForResultException.java // public class NotAllFieldsAreAnnotatedForResultException extends RuntimeException { // public NotAllFieldsAreAnnotatedForResultException(String message) { // super(message); // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/navigable/NavigableAnnotatedClass.java // public class NavigableAnnotatedClass { // // // public static NavigableAnnotatedClass from(TypeElement typeElement) throws VariableElementValidationException { // // Navigable annotation = typeElement.getAnnotation(Navigable.class); // // NavigableAnnotatedClass navigableAnnotatedClass = new NavigableAnnotatedClass(typeElement, annotation.group()); // HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); // HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); // ArrayList<String> errors; // Param paramAnnotation; // Result resultAnnotation; // for (Element element : typeElement.getEnclosedElements()) { // if (!(element instanceof VariableElement)) { // continue; // } // VariableElement variableElement = (VariableElement) element; // if (AnnotationValidator.isAnnotated(variableElement, Param.class)) { // paramAnnotation = variableElement.getAnnotation(Param.class); // errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); // if (errors.size() == 0) { // CollectionUtils.addToHashMapWithList(paramAnnotatedFields, paramAnnotation.group(), variableElement); // } else { // throw new VariableElementValidationException(errors); // } // } // if (AnnotationValidator.isAnnotated(variableElement, Result.class)) { // resultAnnotation = variableElement.getAnnotation(Result.class); // errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); // if (errors.size() == 0) { // CollectionUtils.addToHashMapWithList(resultAnnotatedFields, resultAnnotation.group(), variableElement); // } else { // throw new VariableElementValidationException(errors); // } // } // } // // navigableAnnotatedClass.paramAnnotatedFields = paramAnnotatedFields; // navigableAnnotatedClass.resultAnnotatedFields = resultAnnotatedFields; // navigableAnnotatedClass.navigableAnnotation = annotation; // // return navigableAnnotatedClass; // } // // private HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); // private HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); // private final String annotatedClassName; // private final TypeElement typeElement; // private final String group; // private Navigable navigableAnnotation; // // // public NavigableAnnotatedClass(TypeElement typeElement, String group) { // this.annotatedClassName = typeElement.getSimpleName().toString(); // this.typeElement = typeElement; // this.group = group; // // } // // public HashMap<String, List<VariableElement>> getParamAnnotatedFields() { // return paramAnnotatedFields; // } // // public HashMap<String, List<VariableElement>> getResultAnnotatedFields() { // return resultAnnotatedFields; // } // // public String getAnnotatedClassName() { // return annotatedClassName; // } // // public TypeElement getTypeElement() { // return typeElement; // } // // public String getGroup() { // return group; // } // // public Navigable getNavigableAnnotation() { // return navigableAnnotation; // } // } // Path: compiler/src/test/java/pl/edu/radomski/navigator/NavigatorCodeGeneratorParameterizedTest.java import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.Mock; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import pl.edu.radomski.navigator.exceptions.NotAllFieldsAreAnnotatedForResultException; import pl.edu.radomski.navigator.navigable.NavigableAnnotatedClass; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; package pl.edu.radomski.navigator; /** * Created by adam on 1/9/16. */ @RunWith(Parameterized.class) public class NavigatorCodeGeneratorParameterizedTest { @Mock
NavigableAnnotatedClass navigableAnnotatedClass;
aradomski/Navigator
compiler/src/test/java/pl/edu/radomski/navigator/NavigatorCodeGeneratorParameterizedTest.java
// Path: compiler/src/main/java/pl/edu/radomski/navigator/exceptions/NotAllFieldsAreAnnotatedForResultException.java // public class NotAllFieldsAreAnnotatedForResultException extends RuntimeException { // public NotAllFieldsAreAnnotatedForResultException(String message) { // super(message); // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/navigable/NavigableAnnotatedClass.java // public class NavigableAnnotatedClass { // // // public static NavigableAnnotatedClass from(TypeElement typeElement) throws VariableElementValidationException { // // Navigable annotation = typeElement.getAnnotation(Navigable.class); // // NavigableAnnotatedClass navigableAnnotatedClass = new NavigableAnnotatedClass(typeElement, annotation.group()); // HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); // HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); // ArrayList<String> errors; // Param paramAnnotation; // Result resultAnnotation; // for (Element element : typeElement.getEnclosedElements()) { // if (!(element instanceof VariableElement)) { // continue; // } // VariableElement variableElement = (VariableElement) element; // if (AnnotationValidator.isAnnotated(variableElement, Param.class)) { // paramAnnotation = variableElement.getAnnotation(Param.class); // errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); // if (errors.size() == 0) { // CollectionUtils.addToHashMapWithList(paramAnnotatedFields, paramAnnotation.group(), variableElement); // } else { // throw new VariableElementValidationException(errors); // } // } // if (AnnotationValidator.isAnnotated(variableElement, Result.class)) { // resultAnnotation = variableElement.getAnnotation(Result.class); // errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); // if (errors.size() == 0) { // CollectionUtils.addToHashMapWithList(resultAnnotatedFields, resultAnnotation.group(), variableElement); // } else { // throw new VariableElementValidationException(errors); // } // } // } // // navigableAnnotatedClass.paramAnnotatedFields = paramAnnotatedFields; // navigableAnnotatedClass.resultAnnotatedFields = resultAnnotatedFields; // navigableAnnotatedClass.navigableAnnotation = annotation; // // return navigableAnnotatedClass; // } // // private HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); // private HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); // private final String annotatedClassName; // private final TypeElement typeElement; // private final String group; // private Navigable navigableAnnotation; // // // public NavigableAnnotatedClass(TypeElement typeElement, String group) { // this.annotatedClassName = typeElement.getSimpleName().toString(); // this.typeElement = typeElement; // this.group = group; // // } // // public HashMap<String, List<VariableElement>> getParamAnnotatedFields() { // return paramAnnotatedFields; // } // // public HashMap<String, List<VariableElement>> getResultAnnotatedFields() { // return resultAnnotatedFields; // } // // public String getAnnotatedClassName() { // return annotatedClassName; // } // // public TypeElement getTypeElement() { // return typeElement; // } // // public String getGroup() { // return group; // } // // public Navigable getNavigableAnnotation() { // return navigableAnnotation; // } // }
import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.Mock; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import pl.edu.radomski.navigator.exceptions.NotAllFieldsAreAnnotatedForResultException; import pl.edu.radomski.navigator.navigable.NavigableAnnotatedClass; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when;
package pl.edu.radomski.navigator; /** * Created by adam on 1/9/16. */ @RunWith(Parameterized.class) public class NavigatorCodeGeneratorParameterizedTest { @Mock NavigableAnnotatedClass navigableAnnotatedClass; private NavigatorCodeGenerator navigatorCodeGenerator; @Parameterized.Parameters(name = "{index}: {0}, {1}, {2}") public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {0, new ArrayList<VariableElement>() {{ add(generateVariableElementMock(true, "aaaa")); add(generateVariableElementMock(true, "bbbb")); }}, null}, {0, new ArrayList<VariableElement>() {{ add(generateVariableElementMock(true, "aaaa")); add(generateVariableElementMock(false, "bbbb"));
// Path: compiler/src/main/java/pl/edu/radomski/navigator/exceptions/NotAllFieldsAreAnnotatedForResultException.java // public class NotAllFieldsAreAnnotatedForResultException extends RuntimeException { // public NotAllFieldsAreAnnotatedForResultException(String message) { // super(message); // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/navigable/NavigableAnnotatedClass.java // public class NavigableAnnotatedClass { // // // public static NavigableAnnotatedClass from(TypeElement typeElement) throws VariableElementValidationException { // // Navigable annotation = typeElement.getAnnotation(Navigable.class); // // NavigableAnnotatedClass navigableAnnotatedClass = new NavigableAnnotatedClass(typeElement, annotation.group()); // HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); // HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); // ArrayList<String> errors; // Param paramAnnotation; // Result resultAnnotation; // for (Element element : typeElement.getEnclosedElements()) { // if (!(element instanceof VariableElement)) { // continue; // } // VariableElement variableElement = (VariableElement) element; // if (AnnotationValidator.isAnnotated(variableElement, Param.class)) { // paramAnnotation = variableElement.getAnnotation(Param.class); // errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); // if (errors.size() == 0) { // CollectionUtils.addToHashMapWithList(paramAnnotatedFields, paramAnnotation.group(), variableElement); // } else { // throw new VariableElementValidationException(errors); // } // } // if (AnnotationValidator.isAnnotated(variableElement, Result.class)) { // resultAnnotation = variableElement.getAnnotation(Result.class); // errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); // if (errors.size() == 0) { // CollectionUtils.addToHashMapWithList(resultAnnotatedFields, resultAnnotation.group(), variableElement); // } else { // throw new VariableElementValidationException(errors); // } // } // } // // navigableAnnotatedClass.paramAnnotatedFields = paramAnnotatedFields; // navigableAnnotatedClass.resultAnnotatedFields = resultAnnotatedFields; // navigableAnnotatedClass.navigableAnnotation = annotation; // // return navigableAnnotatedClass; // } // // private HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); // private HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); // private final String annotatedClassName; // private final TypeElement typeElement; // private final String group; // private Navigable navigableAnnotation; // // // public NavigableAnnotatedClass(TypeElement typeElement, String group) { // this.annotatedClassName = typeElement.getSimpleName().toString(); // this.typeElement = typeElement; // this.group = group; // // } // // public HashMap<String, List<VariableElement>> getParamAnnotatedFields() { // return paramAnnotatedFields; // } // // public HashMap<String, List<VariableElement>> getResultAnnotatedFields() { // return resultAnnotatedFields; // } // // public String getAnnotatedClassName() { // return annotatedClassName; // } // // public TypeElement getTypeElement() { // return typeElement; // } // // public String getGroup() { // return group; // } // // public Navigable getNavigableAnnotation() { // return navigableAnnotation; // } // } // Path: compiler/src/test/java/pl/edu/radomski/navigator/NavigatorCodeGeneratorParameterizedTest.java import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.Mock; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import pl.edu.radomski.navigator.exceptions.NotAllFieldsAreAnnotatedForResultException; import pl.edu.radomski.navigator.navigable.NavigableAnnotatedClass; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; package pl.edu.radomski.navigator; /** * Created by adam on 1/9/16. */ @RunWith(Parameterized.class) public class NavigatorCodeGeneratorParameterizedTest { @Mock NavigableAnnotatedClass navigableAnnotatedClass; private NavigatorCodeGenerator navigatorCodeGenerator; @Parameterized.Parameters(name = "{index}: {0}, {1}, {2}") public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {0, new ArrayList<VariableElement>() {{ add(generateVariableElementMock(true, "aaaa")); add(generateVariableElementMock(true, "bbbb")); }}, null}, {0, new ArrayList<VariableElement>() {{ add(generateVariableElementMock(true, "aaaa")); add(generateVariableElementMock(false, "bbbb"));
}}, NotAllFieldsAreAnnotatedForResultException.class}
aradomski/Navigator
compiler/src/main/java/pl/edu/radomski/navigator/utils/StringUtils.java
// Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/tuple/Tuple.java // public class Tuple { // // public static <T1, T2> Tuple2<T1, T2> make(T1 first, T2 second) { // return new Tuple2<>(first, second); // } // // public static <T1, T2, T3> Tuple3<T1, T2, T3> make(T1 first, T2 second, T3 third) { // return new Tuple3<>(first, second, third); // } // // public static <T1, T2, T3, T4> Tuple4<T1, T2, T3, T4> make(T1 first, T2 second, T3 third, T4 fourth) { // return new Tuple4<>(first, second, third, fourth); // } // // public static <T1, T2, T3, T4, T5> Tuple5<T1, T2, T3, T4, T5> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth) { // return new Tuple5<>(first, second, third, fourth, fifth); // } // // public static <T1, T2, T3, T4, T5, T6> Tuple6<T1, T2, T3, T4, T5, T6> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth ) { // return new Tuple6<>(first, second, third, fourth, fifth, sixth); // } // // public static <T1, T2, T3, T4, T5, T6, T7> Tuple7<T1, T2, T3, T4, T5, T6, T7> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh) { // return new Tuple7<>(first, second, third, fourth, fifth, sixth, seventh); // } // // public static <T1, T2, T3, T4, T5, T6, T7, T8> Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh, T8 eighth) { // return new Tuple8<>(first, second, third, fourth, fifth, sixth, seventh, eighth); // } // // public static <T1, T2, T3, T4, T5, T6, T7, T8, T9> Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh, T8 eighth, T9 nineth) { // return new Tuple9<>(first, second, third, fourth, fifth, sixth, seventh, eighth, nineth); // } // // private Tuple() { // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/tuple/Tuple2.java // public class Tuple2<T1, T2> extends Tuple1<T1> { // // public final T2 second; // // Tuple2(T1 first, T2 second) { // super(first); // this.second = second; // } // }
import java.util.List; import java.util.Map; import java.util.TreeMap; import pl.edu.radomski.navigator.utils.tuple.Tuple; import pl.edu.radomski.navigator.utils.tuple.Tuple2;
/* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.utils; /** * Created by adam on 8/25/15. */ public final class StringUtils { public static boolean isEmpty(String s) { return s == null || s.trim().length() == 0; } public static String longestCommonSubstring(List<String> values) {
// Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/tuple/Tuple.java // public class Tuple { // // public static <T1, T2> Tuple2<T1, T2> make(T1 first, T2 second) { // return new Tuple2<>(first, second); // } // // public static <T1, T2, T3> Tuple3<T1, T2, T3> make(T1 first, T2 second, T3 third) { // return new Tuple3<>(first, second, third); // } // // public static <T1, T2, T3, T4> Tuple4<T1, T2, T3, T4> make(T1 first, T2 second, T3 third, T4 fourth) { // return new Tuple4<>(first, second, third, fourth); // } // // public static <T1, T2, T3, T4, T5> Tuple5<T1, T2, T3, T4, T5> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth) { // return new Tuple5<>(first, second, third, fourth, fifth); // } // // public static <T1, T2, T3, T4, T5, T6> Tuple6<T1, T2, T3, T4, T5, T6> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth ) { // return new Tuple6<>(first, second, third, fourth, fifth, sixth); // } // // public static <T1, T2, T3, T4, T5, T6, T7> Tuple7<T1, T2, T3, T4, T5, T6, T7> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh) { // return new Tuple7<>(first, second, third, fourth, fifth, sixth, seventh); // } // // public static <T1, T2, T3, T4, T5, T6, T7, T8> Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh, T8 eighth) { // return new Tuple8<>(first, second, third, fourth, fifth, sixth, seventh, eighth); // } // // public static <T1, T2, T3, T4, T5, T6, T7, T8, T9> Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh, T8 eighth, T9 nineth) { // return new Tuple9<>(first, second, third, fourth, fifth, sixth, seventh, eighth, nineth); // } // // private Tuple() { // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/tuple/Tuple2.java // public class Tuple2<T1, T2> extends Tuple1<T1> { // // public final T2 second; // // Tuple2(T1 first, T2 second) { // super(first); // this.second = second; // } // } // Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/StringUtils.java import java.util.List; import java.util.Map; import java.util.TreeMap; import pl.edu.radomski.navigator.utils.tuple.Tuple; import pl.edu.radomski.navigator.utils.tuple.Tuple2; /* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.utils; /** * Created by adam on 8/25/15. */ public final class StringUtils { public static boolean isEmpty(String s) { return s == null || s.trim().length() == 0; } public static String longestCommonSubstring(List<String> values) {
TreeMap<Integer, Tuple2<String, String>> map = new TreeMap<>();
aradomski/Navigator
compiler/src/main/java/pl/edu/radomski/navigator/utils/StringUtils.java
// Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/tuple/Tuple.java // public class Tuple { // // public static <T1, T2> Tuple2<T1, T2> make(T1 first, T2 second) { // return new Tuple2<>(first, second); // } // // public static <T1, T2, T3> Tuple3<T1, T2, T3> make(T1 first, T2 second, T3 third) { // return new Tuple3<>(first, second, third); // } // // public static <T1, T2, T3, T4> Tuple4<T1, T2, T3, T4> make(T1 first, T2 second, T3 third, T4 fourth) { // return new Tuple4<>(first, second, third, fourth); // } // // public static <T1, T2, T3, T4, T5> Tuple5<T1, T2, T3, T4, T5> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth) { // return new Tuple5<>(first, second, third, fourth, fifth); // } // // public static <T1, T2, T3, T4, T5, T6> Tuple6<T1, T2, T3, T4, T5, T6> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth ) { // return new Tuple6<>(first, second, third, fourth, fifth, sixth); // } // // public static <T1, T2, T3, T4, T5, T6, T7> Tuple7<T1, T2, T3, T4, T5, T6, T7> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh) { // return new Tuple7<>(first, second, third, fourth, fifth, sixth, seventh); // } // // public static <T1, T2, T3, T4, T5, T6, T7, T8> Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh, T8 eighth) { // return new Tuple8<>(first, second, third, fourth, fifth, sixth, seventh, eighth); // } // // public static <T1, T2, T3, T4, T5, T6, T7, T8, T9> Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh, T8 eighth, T9 nineth) { // return new Tuple9<>(first, second, third, fourth, fifth, sixth, seventh, eighth, nineth); // } // // private Tuple() { // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/tuple/Tuple2.java // public class Tuple2<T1, T2> extends Tuple1<T1> { // // public final T2 second; // // Tuple2(T1 first, T2 second) { // super(first); // this.second = second; // } // }
import java.util.List; import java.util.Map; import java.util.TreeMap; import pl.edu.radomski.navigator.utils.tuple.Tuple; import pl.edu.radomski.navigator.utils.tuple.Tuple2;
/* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.utils; /** * Created by adam on 8/25/15. */ public final class StringUtils { public static boolean isEmpty(String s) { return s == null || s.trim().length() == 0; } public static String longestCommonSubstring(List<String> values) { TreeMap<Integer, Tuple2<String, String>> map = new TreeMap<>(); if (values.size() == 0) { return ""; } else if (values.size() == 1) { return values.get(0); } for (int i = 0; i < values.size() - 1; i++) { for (int j = i + 1; j < values.size(); j++) {
// Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/tuple/Tuple.java // public class Tuple { // // public static <T1, T2> Tuple2<T1, T2> make(T1 first, T2 second) { // return new Tuple2<>(first, second); // } // // public static <T1, T2, T3> Tuple3<T1, T2, T3> make(T1 first, T2 second, T3 third) { // return new Tuple3<>(first, second, third); // } // // public static <T1, T2, T3, T4> Tuple4<T1, T2, T3, T4> make(T1 first, T2 second, T3 third, T4 fourth) { // return new Tuple4<>(first, second, third, fourth); // } // // public static <T1, T2, T3, T4, T5> Tuple5<T1, T2, T3, T4, T5> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth) { // return new Tuple5<>(first, second, third, fourth, fifth); // } // // public static <T1, T2, T3, T4, T5, T6> Tuple6<T1, T2, T3, T4, T5, T6> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth ) { // return new Tuple6<>(first, second, third, fourth, fifth, sixth); // } // // public static <T1, T2, T3, T4, T5, T6, T7> Tuple7<T1, T2, T3, T4, T5, T6, T7> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh) { // return new Tuple7<>(first, second, third, fourth, fifth, sixth, seventh); // } // // public static <T1, T2, T3, T4, T5, T6, T7, T8> Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh, T8 eighth) { // return new Tuple8<>(first, second, third, fourth, fifth, sixth, seventh, eighth); // } // // public static <T1, T2, T3, T4, T5, T6, T7, T8, T9> Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9> make(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh, T8 eighth, T9 nineth) { // return new Tuple9<>(first, second, third, fourth, fifth, sixth, seventh, eighth, nineth); // } // // private Tuple() { // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/tuple/Tuple2.java // public class Tuple2<T1, T2> extends Tuple1<T1> { // // public final T2 second; // // Tuple2(T1 first, T2 second) { // super(first); // this.second = second; // } // } // Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/StringUtils.java import java.util.List; import java.util.Map; import java.util.TreeMap; import pl.edu.radomski.navigator.utils.tuple.Tuple; import pl.edu.radomski.navigator.utils.tuple.Tuple2; /* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.utils; /** * Created by adam on 8/25/15. */ public final class StringUtils { public static boolean isEmpty(String s) { return s == null || s.trim().length() == 0; } public static String longestCommonSubstring(List<String> values) { TreeMap<Integer, Tuple2<String, String>> map = new TreeMap<>(); if (values.size() == 0) { return ""; } else if (values.size() == 1) { return values.get(0); } for (int i = 0; i < values.size() - 1; i++) { for (int j = i + 1; j < values.size(); j++) {
map.put(longestCommonSubstring(values.get(i), values.get(j)), Tuple.make(values.get(i), values.get(j)));
aradomski/Navigator
app/src/main/java/pl/edu/radomski/navigator/examples/ParamsForResultActivity.java
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // }
import android.content.Intent; import android.os.Bundle; import android.view.View; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.params.Book;
/* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.examples; /** * Created by adam on 8/24/15. */ @Navigable public class ParamsForResultActivity extends BaseActivity { @Param(forResult = true) Integer integerParam; @Param(forResult = true) String stringParam; @Param(forResult = true)
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // Path: app/src/main/java/pl/edu/radomski/navigator/examples/ParamsForResultActivity.java import android.content.Intent; import android.os.Bundle; import android.view.View; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.params.Book; /* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.examples; /** * Created by adam on 8/24/15. */ @Navigable public class ParamsForResultActivity extends BaseActivity { @Param(forResult = true) Integer integerParam; @Param(forResult = true) String stringParam; @Param(forResult = true)
Book parcelableParam;
aradomski/Navigator
compiler/src/main/java/pl/edu/radomski/navigator/navigable/NavigableAnnotatedClass.java
// Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/AnnotationValidator.java // public class AnnotationValidator { // protected static boolean isPublic(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PUBLIC); // } // // protected static boolean isPackage(Element annotatedClass) { // return !isPublic(annotatedClass) && !isProtected(annotatedClass) && !isPrivate(annotatedClass); // } // // protected static boolean isProtected(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PROTECTED); // } // // protected static boolean isPrivate(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PRIVATE); // } // // protected static boolean isAbstract(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.ABSTRACT); // } // // protected static boolean hasOneOfModifiers(Element element, Modifier... modifiers) { // for (Modifier modifier : modifiers) { // if (element.getModifiers().contains(modifier)) { // return true; // } // } // return false; // } // // // public static <T extends Class> boolean isAnnotated(Element variableElement, T t) { // return variableElement.getAnnotation(t) != null; // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/CollectionUtils.java // public class CollectionUtils { // // // public static <K, E> void addToHashMapWithList(Map<K, List<E>> map, K key, E element) { // if (map.get(key) == null) { // map.put(key, new ArrayList<E>()); // } // map.get(key).add(element); // } // // public static <K, E> List<E> getElementFromMapWithList(Map<K, List<E>> map) { // ArrayList<E> list = new ArrayList<>(); // for (List<E> element : map.values()) { // list.addAll(element); // } // return list; // } // // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/exceptions/VariableElementValidationException.java // public class VariableElementValidationException extends Exception { // public ArrayList<String> errors; // // public VariableElementValidationException(ArrayList<String> errors) { // this.errors = errors; // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/param/ParamAnnotatedVariableElementValidator.java // public class ParamAnnotatedVariableElementValidator extends AnnotationValidator { // private static final String ANNOTATION = "@" + Param.class.getCanonicalName(); // // public static ArrayList<String> isValid(VariableElement variableElement) { // ArrayList<String> errors = new ArrayList<>(); // if (isPrivate(variableElement)) { // errors.add(String.format("Fields annotated with %s must NOT be private.", ANNOTATION)); // } // return errors; // } // // }
import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.exceptions.VariableElementValidationException; import pl.edu.radomski.navigator.param.ParamAnnotatedVariableElementValidator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import pl.edu.radomski.navigator.utils.AnnotationValidator; import pl.edu.radomski.navigator.utils.CollectionUtils;
/* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.navigable; /** * Created by adam on 8/18/15. */ public class NavigableAnnotatedClass { public static NavigableAnnotatedClass from(TypeElement typeElement) throws VariableElementValidationException { Navigable annotation = typeElement.getAnnotation(Navigable.class); NavigableAnnotatedClass navigableAnnotatedClass = new NavigableAnnotatedClass(typeElement, annotation.group()); HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); ArrayList<String> errors; Param paramAnnotation; Result resultAnnotation; for (Element element : typeElement.getEnclosedElements()) { if (!(element instanceof VariableElement)) { continue; } VariableElement variableElement = (VariableElement) element;
// Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/AnnotationValidator.java // public class AnnotationValidator { // protected static boolean isPublic(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PUBLIC); // } // // protected static boolean isPackage(Element annotatedClass) { // return !isPublic(annotatedClass) && !isProtected(annotatedClass) && !isPrivate(annotatedClass); // } // // protected static boolean isProtected(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PROTECTED); // } // // protected static boolean isPrivate(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PRIVATE); // } // // protected static boolean isAbstract(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.ABSTRACT); // } // // protected static boolean hasOneOfModifiers(Element element, Modifier... modifiers) { // for (Modifier modifier : modifiers) { // if (element.getModifiers().contains(modifier)) { // return true; // } // } // return false; // } // // // public static <T extends Class> boolean isAnnotated(Element variableElement, T t) { // return variableElement.getAnnotation(t) != null; // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/CollectionUtils.java // public class CollectionUtils { // // // public static <K, E> void addToHashMapWithList(Map<K, List<E>> map, K key, E element) { // if (map.get(key) == null) { // map.put(key, new ArrayList<E>()); // } // map.get(key).add(element); // } // // public static <K, E> List<E> getElementFromMapWithList(Map<K, List<E>> map) { // ArrayList<E> list = new ArrayList<>(); // for (List<E> element : map.values()) { // list.addAll(element); // } // return list; // } // // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/exceptions/VariableElementValidationException.java // public class VariableElementValidationException extends Exception { // public ArrayList<String> errors; // // public VariableElementValidationException(ArrayList<String> errors) { // this.errors = errors; // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/param/ParamAnnotatedVariableElementValidator.java // public class ParamAnnotatedVariableElementValidator extends AnnotationValidator { // private static final String ANNOTATION = "@" + Param.class.getCanonicalName(); // // public static ArrayList<String> isValid(VariableElement variableElement) { // ArrayList<String> errors = new ArrayList<>(); // if (isPrivate(variableElement)) { // errors.add(String.format("Fields annotated with %s must NOT be private.", ANNOTATION)); // } // return errors; // } // // } // Path: compiler/src/main/java/pl/edu/radomski/navigator/navigable/NavigableAnnotatedClass.java import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.exceptions.VariableElementValidationException; import pl.edu.radomski.navigator.param.ParamAnnotatedVariableElementValidator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import pl.edu.radomski.navigator.utils.AnnotationValidator; import pl.edu.radomski.navigator.utils.CollectionUtils; /* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.navigable; /** * Created by adam on 8/18/15. */ public class NavigableAnnotatedClass { public static NavigableAnnotatedClass from(TypeElement typeElement) throws VariableElementValidationException { Navigable annotation = typeElement.getAnnotation(Navigable.class); NavigableAnnotatedClass navigableAnnotatedClass = new NavigableAnnotatedClass(typeElement, annotation.group()); HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); ArrayList<String> errors; Param paramAnnotation; Result resultAnnotation; for (Element element : typeElement.getEnclosedElements()) { if (!(element instanceof VariableElement)) { continue; } VariableElement variableElement = (VariableElement) element;
if (AnnotationValidator.isAnnotated(variableElement, Param.class)) {
aradomski/Navigator
compiler/src/main/java/pl/edu/radomski/navigator/navigable/NavigableAnnotatedClass.java
// Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/AnnotationValidator.java // public class AnnotationValidator { // protected static boolean isPublic(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PUBLIC); // } // // protected static boolean isPackage(Element annotatedClass) { // return !isPublic(annotatedClass) && !isProtected(annotatedClass) && !isPrivate(annotatedClass); // } // // protected static boolean isProtected(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PROTECTED); // } // // protected static boolean isPrivate(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PRIVATE); // } // // protected static boolean isAbstract(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.ABSTRACT); // } // // protected static boolean hasOneOfModifiers(Element element, Modifier... modifiers) { // for (Modifier modifier : modifiers) { // if (element.getModifiers().contains(modifier)) { // return true; // } // } // return false; // } // // // public static <T extends Class> boolean isAnnotated(Element variableElement, T t) { // return variableElement.getAnnotation(t) != null; // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/CollectionUtils.java // public class CollectionUtils { // // // public static <K, E> void addToHashMapWithList(Map<K, List<E>> map, K key, E element) { // if (map.get(key) == null) { // map.put(key, new ArrayList<E>()); // } // map.get(key).add(element); // } // // public static <K, E> List<E> getElementFromMapWithList(Map<K, List<E>> map) { // ArrayList<E> list = new ArrayList<>(); // for (List<E> element : map.values()) { // list.addAll(element); // } // return list; // } // // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/exceptions/VariableElementValidationException.java // public class VariableElementValidationException extends Exception { // public ArrayList<String> errors; // // public VariableElementValidationException(ArrayList<String> errors) { // this.errors = errors; // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/param/ParamAnnotatedVariableElementValidator.java // public class ParamAnnotatedVariableElementValidator extends AnnotationValidator { // private static final String ANNOTATION = "@" + Param.class.getCanonicalName(); // // public static ArrayList<String> isValid(VariableElement variableElement) { // ArrayList<String> errors = new ArrayList<>(); // if (isPrivate(variableElement)) { // errors.add(String.format("Fields annotated with %s must NOT be private.", ANNOTATION)); // } // return errors; // } // // }
import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.exceptions.VariableElementValidationException; import pl.edu.radomski.navigator.param.ParamAnnotatedVariableElementValidator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import pl.edu.radomski.navigator.utils.AnnotationValidator; import pl.edu.radomski.navigator.utils.CollectionUtils;
/* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.navigable; /** * Created by adam on 8/18/15. */ public class NavigableAnnotatedClass { public static NavigableAnnotatedClass from(TypeElement typeElement) throws VariableElementValidationException { Navigable annotation = typeElement.getAnnotation(Navigable.class); NavigableAnnotatedClass navigableAnnotatedClass = new NavigableAnnotatedClass(typeElement, annotation.group()); HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); ArrayList<String> errors; Param paramAnnotation; Result resultAnnotation; for (Element element : typeElement.getEnclosedElements()) { if (!(element instanceof VariableElement)) { continue; } VariableElement variableElement = (VariableElement) element; if (AnnotationValidator.isAnnotated(variableElement, Param.class)) { paramAnnotation = variableElement.getAnnotation(Param.class);
// Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/AnnotationValidator.java // public class AnnotationValidator { // protected static boolean isPublic(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PUBLIC); // } // // protected static boolean isPackage(Element annotatedClass) { // return !isPublic(annotatedClass) && !isProtected(annotatedClass) && !isPrivate(annotatedClass); // } // // protected static boolean isProtected(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PROTECTED); // } // // protected static boolean isPrivate(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PRIVATE); // } // // protected static boolean isAbstract(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.ABSTRACT); // } // // protected static boolean hasOneOfModifiers(Element element, Modifier... modifiers) { // for (Modifier modifier : modifiers) { // if (element.getModifiers().contains(modifier)) { // return true; // } // } // return false; // } // // // public static <T extends Class> boolean isAnnotated(Element variableElement, T t) { // return variableElement.getAnnotation(t) != null; // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/CollectionUtils.java // public class CollectionUtils { // // // public static <K, E> void addToHashMapWithList(Map<K, List<E>> map, K key, E element) { // if (map.get(key) == null) { // map.put(key, new ArrayList<E>()); // } // map.get(key).add(element); // } // // public static <K, E> List<E> getElementFromMapWithList(Map<K, List<E>> map) { // ArrayList<E> list = new ArrayList<>(); // for (List<E> element : map.values()) { // list.addAll(element); // } // return list; // } // // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/exceptions/VariableElementValidationException.java // public class VariableElementValidationException extends Exception { // public ArrayList<String> errors; // // public VariableElementValidationException(ArrayList<String> errors) { // this.errors = errors; // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/param/ParamAnnotatedVariableElementValidator.java // public class ParamAnnotatedVariableElementValidator extends AnnotationValidator { // private static final String ANNOTATION = "@" + Param.class.getCanonicalName(); // // public static ArrayList<String> isValid(VariableElement variableElement) { // ArrayList<String> errors = new ArrayList<>(); // if (isPrivate(variableElement)) { // errors.add(String.format("Fields annotated with %s must NOT be private.", ANNOTATION)); // } // return errors; // } // // } // Path: compiler/src/main/java/pl/edu/radomski/navigator/navigable/NavigableAnnotatedClass.java import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.exceptions.VariableElementValidationException; import pl.edu.radomski.navigator.param.ParamAnnotatedVariableElementValidator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import pl.edu.radomski.navigator.utils.AnnotationValidator; import pl.edu.radomski.navigator.utils.CollectionUtils; /* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.navigable; /** * Created by adam on 8/18/15. */ public class NavigableAnnotatedClass { public static NavigableAnnotatedClass from(TypeElement typeElement) throws VariableElementValidationException { Navigable annotation = typeElement.getAnnotation(Navigable.class); NavigableAnnotatedClass navigableAnnotatedClass = new NavigableAnnotatedClass(typeElement, annotation.group()); HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); ArrayList<String> errors; Param paramAnnotation; Result resultAnnotation; for (Element element : typeElement.getEnclosedElements()) { if (!(element instanceof VariableElement)) { continue; } VariableElement variableElement = (VariableElement) element; if (AnnotationValidator.isAnnotated(variableElement, Param.class)) { paramAnnotation = variableElement.getAnnotation(Param.class);
errors = ParamAnnotatedVariableElementValidator.isValid(variableElement);
aradomski/Navigator
compiler/src/main/java/pl/edu/radomski/navigator/navigable/NavigableAnnotatedClass.java
// Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/AnnotationValidator.java // public class AnnotationValidator { // protected static boolean isPublic(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PUBLIC); // } // // protected static boolean isPackage(Element annotatedClass) { // return !isPublic(annotatedClass) && !isProtected(annotatedClass) && !isPrivate(annotatedClass); // } // // protected static boolean isProtected(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PROTECTED); // } // // protected static boolean isPrivate(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PRIVATE); // } // // protected static boolean isAbstract(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.ABSTRACT); // } // // protected static boolean hasOneOfModifiers(Element element, Modifier... modifiers) { // for (Modifier modifier : modifiers) { // if (element.getModifiers().contains(modifier)) { // return true; // } // } // return false; // } // // // public static <T extends Class> boolean isAnnotated(Element variableElement, T t) { // return variableElement.getAnnotation(t) != null; // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/CollectionUtils.java // public class CollectionUtils { // // // public static <K, E> void addToHashMapWithList(Map<K, List<E>> map, K key, E element) { // if (map.get(key) == null) { // map.put(key, new ArrayList<E>()); // } // map.get(key).add(element); // } // // public static <K, E> List<E> getElementFromMapWithList(Map<K, List<E>> map) { // ArrayList<E> list = new ArrayList<>(); // for (List<E> element : map.values()) { // list.addAll(element); // } // return list; // } // // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/exceptions/VariableElementValidationException.java // public class VariableElementValidationException extends Exception { // public ArrayList<String> errors; // // public VariableElementValidationException(ArrayList<String> errors) { // this.errors = errors; // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/param/ParamAnnotatedVariableElementValidator.java // public class ParamAnnotatedVariableElementValidator extends AnnotationValidator { // private static final String ANNOTATION = "@" + Param.class.getCanonicalName(); // // public static ArrayList<String> isValid(VariableElement variableElement) { // ArrayList<String> errors = new ArrayList<>(); // if (isPrivate(variableElement)) { // errors.add(String.format("Fields annotated with %s must NOT be private.", ANNOTATION)); // } // return errors; // } // // }
import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.exceptions.VariableElementValidationException; import pl.edu.radomski.navigator.param.ParamAnnotatedVariableElementValidator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import pl.edu.radomski.navigator.utils.AnnotationValidator; import pl.edu.radomski.navigator.utils.CollectionUtils;
/* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.navigable; /** * Created by adam on 8/18/15. */ public class NavigableAnnotatedClass { public static NavigableAnnotatedClass from(TypeElement typeElement) throws VariableElementValidationException { Navigable annotation = typeElement.getAnnotation(Navigable.class); NavigableAnnotatedClass navigableAnnotatedClass = new NavigableAnnotatedClass(typeElement, annotation.group()); HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); ArrayList<String> errors; Param paramAnnotation; Result resultAnnotation; for (Element element : typeElement.getEnclosedElements()) { if (!(element instanceof VariableElement)) { continue; } VariableElement variableElement = (VariableElement) element; if (AnnotationValidator.isAnnotated(variableElement, Param.class)) { paramAnnotation = variableElement.getAnnotation(Param.class); errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); if (errors.size() == 0) {
// Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/AnnotationValidator.java // public class AnnotationValidator { // protected static boolean isPublic(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PUBLIC); // } // // protected static boolean isPackage(Element annotatedClass) { // return !isPublic(annotatedClass) && !isProtected(annotatedClass) && !isPrivate(annotatedClass); // } // // protected static boolean isProtected(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PROTECTED); // } // // protected static boolean isPrivate(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.PRIVATE); // } // // protected static boolean isAbstract(Element annotatedClass) { // return annotatedClass.getModifiers().contains(Modifier.ABSTRACT); // } // // protected static boolean hasOneOfModifiers(Element element, Modifier... modifiers) { // for (Modifier modifier : modifiers) { // if (element.getModifiers().contains(modifier)) { // return true; // } // } // return false; // } // // // public static <T extends Class> boolean isAnnotated(Element variableElement, T t) { // return variableElement.getAnnotation(t) != null; // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/utils/CollectionUtils.java // public class CollectionUtils { // // // public static <K, E> void addToHashMapWithList(Map<K, List<E>> map, K key, E element) { // if (map.get(key) == null) { // map.put(key, new ArrayList<E>()); // } // map.get(key).add(element); // } // // public static <K, E> List<E> getElementFromMapWithList(Map<K, List<E>> map) { // ArrayList<E> list = new ArrayList<>(); // for (List<E> element : map.values()) { // list.addAll(element); // } // return list; // } // // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/exceptions/VariableElementValidationException.java // public class VariableElementValidationException extends Exception { // public ArrayList<String> errors; // // public VariableElementValidationException(ArrayList<String> errors) { // this.errors = errors; // } // } // // Path: compiler/src/main/java/pl/edu/radomski/navigator/param/ParamAnnotatedVariableElementValidator.java // public class ParamAnnotatedVariableElementValidator extends AnnotationValidator { // private static final String ANNOTATION = "@" + Param.class.getCanonicalName(); // // public static ArrayList<String> isValid(VariableElement variableElement) { // ArrayList<String> errors = new ArrayList<>(); // if (isPrivate(variableElement)) { // errors.add(String.format("Fields annotated with %s must NOT be private.", ANNOTATION)); // } // return errors; // } // // } // Path: compiler/src/main/java/pl/edu/radomski/navigator/navigable/NavigableAnnotatedClass.java import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.exceptions.VariableElementValidationException; import pl.edu.radomski.navigator.param.ParamAnnotatedVariableElementValidator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import pl.edu.radomski.navigator.utils.AnnotationValidator; import pl.edu.radomski.navigator.utils.CollectionUtils; /* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.navigable; /** * Created by adam on 8/18/15. */ public class NavigableAnnotatedClass { public static NavigableAnnotatedClass from(TypeElement typeElement) throws VariableElementValidationException { Navigable annotation = typeElement.getAnnotation(Navigable.class); NavigableAnnotatedClass navigableAnnotatedClass = new NavigableAnnotatedClass(typeElement, annotation.group()); HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); ArrayList<String> errors; Param paramAnnotation; Result resultAnnotation; for (Element element : typeElement.getEnclosedElements()) { if (!(element instanceof VariableElement)) { continue; } VariableElement variableElement = (VariableElement) element; if (AnnotationValidator.isAnnotated(variableElement, Param.class)) { paramAnnotation = variableElement.getAnnotation(Param.class); errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); if (errors.size() == 0) {
CollectionUtils.addToHashMapWithList(paramAnnotatedFields, paramAnnotation.group(), variableElement);
aradomski/Navigator
app/src/main/java/pl/edu/radomski/navigator/examples/BaseActivity.java
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // // Path: app/src/main/java/pl/edu/radomski/navigator/params/Person.java // public class Person implements Serializable { // private static final long serialVersionUID = -7060210544600464481L; // private String name; // private int age; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // @Override // public String toString() { // return "Person{" + // "name='" + name + '\'' + // ", age=" + age + // '}'; // } // }
import pl.edu.radomski.navigator.Navigator; import pl.edu.radomski.navigator.R; import pl.edu.radomski.navigator.params.Book; import pl.edu.radomski.navigator.params.Person; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.ArrayList; import pl.edu.radomski.navigator.Navigable;
/* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.examples; /** * Created by adam on 8/24/15. */ public class BaseActivity extends Activity { public static final int PARAMS_FOR_RESULT_ACTIVITY = 5000; public static final int GROUPED_FOR_RESULT_ACTIVITY = 5001; public static final int FOR_RESULT_ACTIVITY = 5004; public static final int GROUPED_RESULTS_FOR_RESULT_ACTIVITY1 = 5005; public static final int GROUPED_RESULTS_FOR_RESULT_ACTIVITY2 = 5006; public static final int GROUPED_RESULTS_FOR_RESULT_ACTIVITY3 = 5007; public static final int WITH_RESULT_OPTION_ACTIVITY = 5008; public static final int NAMED_WITH_RESULT = 5009; private View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) {
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // // Path: app/src/main/java/pl/edu/radomski/navigator/params/Person.java // public class Person implements Serializable { // private static final long serialVersionUID = -7060210544600464481L; // private String name; // private int age; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // @Override // public String toString() { // return "Person{" + // "name='" + name + '\'' + // ", age=" + age + // '}'; // } // } // Path: app/src/main/java/pl/edu/radomski/navigator/examples/BaseActivity.java import pl.edu.radomski.navigator.Navigator; import pl.edu.radomski.navigator.R; import pl.edu.radomski.navigator.params.Book; import pl.edu.radomski.navigator.params.Person; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.ArrayList; import pl.edu.radomski.navigator.Navigable; /* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.examples; /** * Created by adam on 8/24/15. */ public class BaseActivity extends Activity { public static final int PARAMS_FOR_RESULT_ACTIVITY = 5000; public static final int GROUPED_FOR_RESULT_ACTIVITY = 5001; public static final int FOR_RESULT_ACTIVITY = 5004; public static final int GROUPED_RESULTS_FOR_RESULT_ACTIVITY1 = 5005; public static final int GROUPED_RESULTS_FOR_RESULT_ACTIVITY2 = 5006; public static final int GROUPED_RESULTS_FOR_RESULT_ACTIVITY3 = 5007; public static final int WITH_RESULT_OPTION_ACTIVITY = 5008; public static final int NAMED_WITH_RESULT = 5009; private View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) {
Book book = new Book();
aradomski/Navigator
app/src/main/java/pl/edu/radomski/navigator/examples/BaseActivity.java
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // // Path: app/src/main/java/pl/edu/radomski/navigator/params/Person.java // public class Person implements Serializable { // private static final long serialVersionUID = -7060210544600464481L; // private String name; // private int age; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // @Override // public String toString() { // return "Person{" + // "name='" + name + '\'' + // ", age=" + age + // '}'; // } // }
import pl.edu.radomski.navigator.Navigator; import pl.edu.radomski.navigator.R; import pl.edu.radomski.navigator.params.Book; import pl.edu.radomski.navigator.params.Person; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.ArrayList; import pl.edu.radomski.navigator.Navigable;
charSequences.add("cccccc"); ArrayList<String> strings = new ArrayList<>(); strings.add("aaaaaaa"); strings.add("bbbbbb"); strings.add("cccccc"); ArrayList<Integer> integers = new ArrayList<>(); integers.add(132); integers.add(123); integers.add(312); Book book1 = new Book(); book1.setAuthor("Adam"); book1.setBookName("navigator"); book1.setPublishTime(21351); Book book2 = new Book(); book2.setAuthor("Adam2"); book2.setBookName("navigator2"); book2.setPublishTime(53235); Book book3 = new Book(); book3.setAuthor("Adam3"); book3.setBookName("navigator3"); book3.setPublishTime(65567); ArrayList<Book> books = new ArrayList<>(); books.add(book1); books.add(book2); books.add(book3);
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // // Path: app/src/main/java/pl/edu/radomski/navigator/params/Person.java // public class Person implements Serializable { // private static final long serialVersionUID = -7060210544600464481L; // private String name; // private int age; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // @Override // public String toString() { // return "Person{" + // "name='" + name + '\'' + // ", age=" + age + // '}'; // } // } // Path: app/src/main/java/pl/edu/radomski/navigator/examples/BaseActivity.java import pl.edu.radomski.navigator.Navigator; import pl.edu.radomski.navigator.R; import pl.edu.radomski.navigator.params.Book; import pl.edu.radomski.navigator.params.Person; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.ArrayList; import pl.edu.radomski.navigator.Navigable; charSequences.add("cccccc"); ArrayList<String> strings = new ArrayList<>(); strings.add("aaaaaaa"); strings.add("bbbbbb"); strings.add("cccccc"); ArrayList<Integer> integers = new ArrayList<>(); integers.add(132); integers.add(123); integers.add(312); Book book1 = new Book(); book1.setAuthor("Adam"); book1.setBookName("navigator"); book1.setPublishTime(21351); Book book2 = new Book(); book2.setAuthor("Adam2"); book2.setBookName("navigator2"); book2.setPublishTime(53235); Book book3 = new Book(); book3.setAuthor("Adam3"); book3.setBookName("navigator3"); book3.setPublishTime(65567); ArrayList<Book> books = new ArrayList<>(); books.add(book1); books.add(book2); books.add(book3);
Person person = new Person();
aradomski/Navigator
app/src/main/java/pl/edu/radomski/navigator/examples/AllParamsActivity.java
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // // Path: app/src/main/java/pl/edu/radomski/navigator/params/Person.java // public class Person implements Serializable { // private static final long serialVersionUID = -7060210544600464481L; // private String name; // private int age; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // @Override // public String toString() { // return "Person{" + // "name='" + name + '\'' + // ", age=" + age + // '}'; // } // }
import android.os.Bundle; import java.util.ArrayList; import java.util.Arrays; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.params.Book; import pl.edu.radomski.navigator.params.Person;
Double doubleObjectParam; @Param double doublePrimitiveParam; @Param float[] floatPrimitiveArray; @Param Float floatObjectParam; @Param float floatPrimitiveParam; @Param int[] intPrimitiveArray; @Param Integer intObjectParam; @Param int intPrimitiveParam; @Param ArrayList<Integer> integerArrayList; @Param long[] longPrimitiveArray; @Param Long longObjectParam; @Param long longPrimitiveParam; @Param
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // // Path: app/src/main/java/pl/edu/radomski/navigator/params/Person.java // public class Person implements Serializable { // private static final long serialVersionUID = -7060210544600464481L; // private String name; // private int age; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // @Override // public String toString() { // return "Person{" + // "name='" + name + '\'' + // ", age=" + age + // '}'; // } // } // Path: app/src/main/java/pl/edu/radomski/navigator/examples/AllParamsActivity.java import android.os.Bundle; import java.util.ArrayList; import java.util.Arrays; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.params.Book; import pl.edu.radomski.navigator.params.Person; Double doubleObjectParam; @Param double doublePrimitiveParam; @Param float[] floatPrimitiveArray; @Param Float floatObjectParam; @Param float floatPrimitiveParam; @Param int[] intPrimitiveArray; @Param Integer intObjectParam; @Param int intPrimitiveParam; @Param ArrayList<Integer> integerArrayList; @Param long[] longPrimitiveArray; @Param Long longObjectParam; @Param long longPrimitiveParam; @Param
Book[] booksArray;
aradomski/Navigator
app/src/main/java/pl/edu/radomski/navigator/examples/AllParamsActivity.java
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // // Path: app/src/main/java/pl/edu/radomski/navigator/params/Person.java // public class Person implements Serializable { // private static final long serialVersionUID = -7060210544600464481L; // private String name; // private int age; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // @Override // public String toString() { // return "Person{" + // "name='" + name + '\'' + // ", age=" + age + // '}'; // } // }
import android.os.Bundle; import java.util.ArrayList; import java.util.Arrays; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.params.Book; import pl.edu.radomski.navigator.params.Person;
Float floatObjectParam; @Param float floatPrimitiveParam; @Param int[] intPrimitiveArray; @Param Integer intObjectParam; @Param int intPrimitiveParam; @Param ArrayList<Integer> integerArrayList; @Param long[] longPrimitiveArray; @Param Long longObjectParam; @Param long longPrimitiveParam; @Param Book[] booksArray; @Param ArrayList<Book> bookArrayList; @Param Book book; @Param
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // // Path: app/src/main/java/pl/edu/radomski/navigator/params/Person.java // public class Person implements Serializable { // private static final long serialVersionUID = -7060210544600464481L; // private String name; // private int age; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // @Override // public String toString() { // return "Person{" + // "name='" + name + '\'' + // ", age=" + age + // '}'; // } // } // Path: app/src/main/java/pl/edu/radomski/navigator/examples/AllParamsActivity.java import android.os.Bundle; import java.util.ArrayList; import java.util.Arrays; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.params.Book; import pl.edu.radomski.navigator.params.Person; Float floatObjectParam; @Param float floatPrimitiveParam; @Param int[] intPrimitiveArray; @Param Integer intObjectParam; @Param int intPrimitiveParam; @Param ArrayList<Integer> integerArrayList; @Param long[] longPrimitiveArray; @Param Long longObjectParam; @Param long longPrimitiveParam; @Param Book[] booksArray; @Param ArrayList<Book> bookArrayList; @Param Book book; @Param
Person person;
aradomski/Navigator
app/src/main/java/pl/edu/radomski/navigator/examples/ParamsActivity.java
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // }
import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.params.Book; import android.os.Bundle;
/* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.examples; /** * Created by adam on 8/24/15. */ @Navigable public class ParamsActivity extends BaseActivity { @Param Integer integerParam; @Param String stringParam; @Param
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // Path: app/src/main/java/pl/edu/radomski/navigator/examples/ParamsActivity.java import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.params.Book; import android.os.Bundle; /* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.examples; /** * Created by adam on 8/24/15. */ @Navigable public class ParamsActivity extends BaseActivity { @Param Integer integerParam; @Param String stringParam; @Param
Book parcelableParam;
aradomski/Navigator
app/src/main/java/pl/edu/radomski/navigator/examples/ActivityWithResultOption.java
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // }
import android.content.Intent; import android.os.Bundle; import android.view.View; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.params.Book;
/* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.examples; /** * Created by adam on 9/3/15. */ @Navigable public class ActivityWithResultOption extends BaseActivity { @Param(group = "firstGroup", forResult = true) String stringParam; @Param(group = "firstGroup", forResult = true) Boolean booleanParam; @Param(group = "secondGroup") Double doubleParam; @Param(group = "secondGroup") Integer integerParam; @Result(group = "firstResultGroup") String stringResult = "abcdefghijk"; @Result(group = "firstResultGroup")
// Path: app/src/main/java/pl/edu/radomski/navigator/params/Book.java // public class Book implements Parcelable { // private String bookName; // private String author; // private int publishTime; // // public String getBookName() { // return bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getPublishTime() { // return publishTime; // } // // public void setPublishTime(int publishTime) { // this.publishTime = publishTime; // } // // public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { // public Book createFromParcel(Parcel source) { // Book mBook = new Book(); // mBook.bookName = source.readString(); // mBook.author = source.readString(); // mBook.publishTime = source.readInt(); // return mBook; // } // // public Book[] newArray(int size) { // return new Book[size]; // } // }; // // public int describeContents() { // return 0; // } // // public void writeToParcel(Parcel parcel, int flags) { // parcel.writeString(bookName); // parcel.writeString(author); // parcel.writeInt(publishTime); // } // // @Override // public String toString() { // return "Book{" + // "bookName='" + bookName + '\'' + // ", author='" + author + '\'' + // ", publishTime=" + publishTime + // '}'; // } // } // Path: app/src/main/java/pl/edu/radomski/navigator/examples/ActivityWithResultOption.java import android.content.Intent; import android.os.Bundle; import android.view.View; import pl.edu.radomski.navigator.Navigable; import pl.edu.radomski.navigator.Param; import pl.edu.radomski.navigator.Result; import pl.edu.radomski.navigator.params.Book; /* * Navigator * Copyright (C) 2015 Adam Radomski * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package pl.edu.radomski.navigator.examples; /** * Created by adam on 9/3/15. */ @Navigable public class ActivityWithResultOption extends BaseActivity { @Param(group = "firstGroup", forResult = true) String stringParam; @Param(group = "firstGroup", forResult = true) Boolean booleanParam; @Param(group = "secondGroup") Double doubleParam; @Param(group = "secondGroup") Integer integerParam; @Result(group = "firstResultGroup") String stringResult = "abcdefghijk"; @Result(group = "firstResultGroup")
Book bookResult;
aradomski/Navigator
compiler/src/test/java/pl/edu/radomski/navigator/NavigatorCodeGeneratorTest.java
// Path: compiler/src/main/java/pl/edu/radomski/navigator/navigable/NavigableAnnotatedClass.java // public class NavigableAnnotatedClass { // // // public static NavigableAnnotatedClass from(TypeElement typeElement) throws VariableElementValidationException { // // Navigable annotation = typeElement.getAnnotation(Navigable.class); // // NavigableAnnotatedClass navigableAnnotatedClass = new NavigableAnnotatedClass(typeElement, annotation.group()); // HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); // HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); // ArrayList<String> errors; // Param paramAnnotation; // Result resultAnnotation; // for (Element element : typeElement.getEnclosedElements()) { // if (!(element instanceof VariableElement)) { // continue; // } // VariableElement variableElement = (VariableElement) element; // if (AnnotationValidator.isAnnotated(variableElement, Param.class)) { // paramAnnotation = variableElement.getAnnotation(Param.class); // errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); // if (errors.size() == 0) { // CollectionUtils.addToHashMapWithList(paramAnnotatedFields, paramAnnotation.group(), variableElement); // } else { // throw new VariableElementValidationException(errors); // } // } // if (AnnotationValidator.isAnnotated(variableElement, Result.class)) { // resultAnnotation = variableElement.getAnnotation(Result.class); // errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); // if (errors.size() == 0) { // CollectionUtils.addToHashMapWithList(resultAnnotatedFields, resultAnnotation.group(), variableElement); // } else { // throw new VariableElementValidationException(errors); // } // } // } // // navigableAnnotatedClass.paramAnnotatedFields = paramAnnotatedFields; // navigableAnnotatedClass.resultAnnotatedFields = resultAnnotatedFields; // navigableAnnotatedClass.navigableAnnotation = annotation; // // return navigableAnnotatedClass; // } // // private HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); // private HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); // private final String annotatedClassName; // private final TypeElement typeElement; // private final String group; // private Navigable navigableAnnotation; // // // public NavigableAnnotatedClass(TypeElement typeElement, String group) { // this.annotatedClassName = typeElement.getSimpleName().toString(); // this.typeElement = typeElement; // this.group = group; // // } // // public HashMap<String, List<VariableElement>> getParamAnnotatedFields() { // return paramAnnotatedFields; // } // // public HashMap<String, List<VariableElement>> getResultAnnotatedFields() { // return resultAnnotatedFields; // } // // public String getAnnotatedClassName() { // return annotatedClassName; // } // // public TypeElement getTypeElement() { // return typeElement; // } // // public String getGroup() { // return group; // } // // public Navigable getNavigableAnnotation() { // return navigableAnnotation; // } // }
import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.sun.org.apache.xpath.internal.operations.Mod; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.runners.Parameterized; import org.mockito.Mock; import org.mockito.Mockito; import java.util.Collection; import java.util.List; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import pl.edu.radomski.navigator.navigable.NavigableAnnotatedClass; import static org.mockito.Mockito.*; import static org.junit.Assert.*;
package pl.edu.radomski.navigator; /** * Created by adam on 1/9/16. */ @RunWith(org.junit.runners.JUnit4.class) public class NavigatorCodeGeneratorTest { @Mock
// Path: compiler/src/main/java/pl/edu/radomski/navigator/navigable/NavigableAnnotatedClass.java // public class NavigableAnnotatedClass { // // // public static NavigableAnnotatedClass from(TypeElement typeElement) throws VariableElementValidationException { // // Navigable annotation = typeElement.getAnnotation(Navigable.class); // // NavigableAnnotatedClass navigableAnnotatedClass = new NavigableAnnotatedClass(typeElement, annotation.group()); // HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); // HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); // ArrayList<String> errors; // Param paramAnnotation; // Result resultAnnotation; // for (Element element : typeElement.getEnclosedElements()) { // if (!(element instanceof VariableElement)) { // continue; // } // VariableElement variableElement = (VariableElement) element; // if (AnnotationValidator.isAnnotated(variableElement, Param.class)) { // paramAnnotation = variableElement.getAnnotation(Param.class); // errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); // if (errors.size() == 0) { // CollectionUtils.addToHashMapWithList(paramAnnotatedFields, paramAnnotation.group(), variableElement); // } else { // throw new VariableElementValidationException(errors); // } // } // if (AnnotationValidator.isAnnotated(variableElement, Result.class)) { // resultAnnotation = variableElement.getAnnotation(Result.class); // errors = ParamAnnotatedVariableElementValidator.isValid(variableElement); // if (errors.size() == 0) { // CollectionUtils.addToHashMapWithList(resultAnnotatedFields, resultAnnotation.group(), variableElement); // } else { // throw new VariableElementValidationException(errors); // } // } // } // // navigableAnnotatedClass.paramAnnotatedFields = paramAnnotatedFields; // navigableAnnotatedClass.resultAnnotatedFields = resultAnnotatedFields; // navigableAnnotatedClass.navigableAnnotation = annotation; // // return navigableAnnotatedClass; // } // // private HashMap<String, List<VariableElement>> paramAnnotatedFields = new HashMap<>(); // private HashMap<String, List<VariableElement>> resultAnnotatedFields = new HashMap<>(); // private final String annotatedClassName; // private final TypeElement typeElement; // private final String group; // private Navigable navigableAnnotation; // // // public NavigableAnnotatedClass(TypeElement typeElement, String group) { // this.annotatedClassName = typeElement.getSimpleName().toString(); // this.typeElement = typeElement; // this.group = group; // // } // // public HashMap<String, List<VariableElement>> getParamAnnotatedFields() { // return paramAnnotatedFields; // } // // public HashMap<String, List<VariableElement>> getResultAnnotatedFields() { // return resultAnnotatedFields; // } // // public String getAnnotatedClassName() { // return annotatedClassName; // } // // public TypeElement getTypeElement() { // return typeElement; // } // // public String getGroup() { // return group; // } // // public Navigable getNavigableAnnotation() { // return navigableAnnotation; // } // } // Path: compiler/src/test/java/pl/edu/radomski/navigator/NavigatorCodeGeneratorTest.java import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.sun.org.apache.xpath.internal.operations.Mod; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.runners.Parameterized; import org.mockito.Mock; import org.mockito.Mockito; import java.util.Collection; import java.util.List; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import pl.edu.radomski.navigator.navigable.NavigableAnnotatedClass; import static org.mockito.Mockito.*; import static org.junit.Assert.*; package pl.edu.radomski.navigator; /** * Created by adam on 1/9/16. */ @RunWith(org.junit.runners.JUnit4.class) public class NavigatorCodeGeneratorTest { @Mock
NavigableAnnotatedClass navigableAnnotatedClass;
twitter/netty-http2
src/main/java/com/twitter/http2/DefaultHttpHeadersFrame.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16;
import io.netty.util.internal.StringUtil; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT;
/* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * The default {@link HttpHeadersFrame} implementation. */ public class DefaultHttpHeadersFrame extends DefaultHttpHeaderBlockFrame implements HttpHeadersFrame { private boolean last; private boolean exclusive = false;
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // Path: src/main/java/com/twitter/http2/DefaultHttpHeadersFrame.java import io.netty.util.internal.StringUtil; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; /* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * The default {@link HttpHeadersFrame} implementation. */ public class DefaultHttpHeadersFrame extends DefaultHttpHeaderBlockFrame implements HttpHeadersFrame { private boolean last; private boolean exclusive = false;
private int dependency = HTTP_DEFAULT_DEPENDENCY;
twitter/netty-http2
src/main/java/com/twitter/http2/DefaultHttpHeadersFrame.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16;
import io.netty.util.internal.StringUtil; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT;
/* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * The default {@link HttpHeadersFrame} implementation. */ public class DefaultHttpHeadersFrame extends DefaultHttpHeaderBlockFrame implements HttpHeadersFrame { private boolean last; private boolean exclusive = false; private int dependency = HTTP_DEFAULT_DEPENDENCY;
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // Path: src/main/java/com/twitter/http2/DefaultHttpHeadersFrame.java import io.netty.util.internal.StringUtil; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; /* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * The default {@link HttpHeadersFrame} implementation. */ public class DefaultHttpHeadersFrame extends DefaultHttpHeaderBlockFrame implements HttpHeadersFrame { private boolean last; private boolean exclusive = false; private int dependency = HTTP_DEFAULT_DEPENDENCY;
private int weight = HTTP_DEFAULT_WEIGHT;
twitter/netty-http2
src/test/java/com/twitter/http2/HttpFrameEncoderTest.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14
import java.util.Random; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Test; import static io.netty.util.ReferenceCountUtil.releaseLater; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH;
int weight = (RANDOM.nextInt() & 0xFF) + 1; ByteBuf headerBlock = Unpooled.buffer(1024); for (int i = 0; i < 256; i++) { headerBlock.writeInt(RANDOM.nextInt()); } ByteBuf frame = releaseLater( ENCODER.encodeHeadersFrame( streamId, false, exclusive, dependency, weight, headerBlock.duplicate()) ); assertHeadersFrame(frame, streamId, exclusive, dependency, weight, false, headerBlock); } @Test public void testEmptyHttpHeadersFrame() throws Exception { int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = RANDOM.nextBoolean(); int dependency = RANDOM.nextInt() & 0x7FFFFFFF; int weight = (RANDOM.nextInt() & 0xFF) + 1; ByteBuf frame = releaseLater( ENCODER.encodeHeadersFrame( streamId, false, exclusive, dependency, weight, Unpooled.EMPTY_BUFFER) ); assertHeadersFrame( frame, streamId, exclusive, dependency, weight, false, Unpooled.EMPTY_BUFFER); } @Test public void testLastHttpHeadersFrame() throws Exception { int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = false;
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // Path: src/test/java/com/twitter/http2/HttpFrameEncoderTest.java import java.util.Random; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Test; import static io.netty.util.ReferenceCountUtil.releaseLater; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; int weight = (RANDOM.nextInt() & 0xFF) + 1; ByteBuf headerBlock = Unpooled.buffer(1024); for (int i = 0; i < 256; i++) { headerBlock.writeInt(RANDOM.nextInt()); } ByteBuf frame = releaseLater( ENCODER.encodeHeadersFrame( streamId, false, exclusive, dependency, weight, headerBlock.duplicate()) ); assertHeadersFrame(frame, streamId, exclusive, dependency, weight, false, headerBlock); } @Test public void testEmptyHttpHeadersFrame() throws Exception { int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = RANDOM.nextBoolean(); int dependency = RANDOM.nextInt() & 0x7FFFFFFF; int weight = (RANDOM.nextInt() & 0xFF) + 1; ByteBuf frame = releaseLater( ENCODER.encodeHeadersFrame( streamId, false, exclusive, dependency, weight, Unpooled.EMPTY_BUFFER) ); assertHeadersFrame( frame, streamId, exclusive, dependency, weight, false, Unpooled.EMPTY_BUFFER); } @Test public void testLastHttpHeadersFrame() throws Exception { int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = false;
int dependency = HTTP_DEFAULT_DEPENDENCY;
twitter/netty-http2
src/test/java/com/twitter/http2/HttpFrameEncoderTest.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14
import java.util.Random; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Test; import static io.netty.util.ReferenceCountUtil.releaseLater; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH;
ByteBuf headerBlock = Unpooled.buffer(1024); for (int i = 0; i < 256; i++) { headerBlock.writeInt(RANDOM.nextInt()); } ByteBuf frame = releaseLater( ENCODER.encodeHeadersFrame( streamId, false, exclusive, dependency, weight, headerBlock.duplicate()) ); assertHeadersFrame(frame, streamId, exclusive, dependency, weight, false, headerBlock); } @Test public void testEmptyHttpHeadersFrame() throws Exception { int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = RANDOM.nextBoolean(); int dependency = RANDOM.nextInt() & 0x7FFFFFFF; int weight = (RANDOM.nextInt() & 0xFF) + 1; ByteBuf frame = releaseLater( ENCODER.encodeHeadersFrame( streamId, false, exclusive, dependency, weight, Unpooled.EMPTY_BUFFER) ); assertHeadersFrame( frame, streamId, exclusive, dependency, weight, false, Unpooled.EMPTY_BUFFER); } @Test public void testLastHttpHeadersFrame() throws Exception { int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = false; int dependency = HTTP_DEFAULT_DEPENDENCY;
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // Path: src/test/java/com/twitter/http2/HttpFrameEncoderTest.java import java.util.Random; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Test; import static io.netty.util.ReferenceCountUtil.releaseLater; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; ByteBuf headerBlock = Unpooled.buffer(1024); for (int i = 0; i < 256; i++) { headerBlock.writeInt(RANDOM.nextInt()); } ByteBuf frame = releaseLater( ENCODER.encodeHeadersFrame( streamId, false, exclusive, dependency, weight, headerBlock.duplicate()) ); assertHeadersFrame(frame, streamId, exclusive, dependency, weight, false, headerBlock); } @Test public void testEmptyHttpHeadersFrame() throws Exception { int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = RANDOM.nextBoolean(); int dependency = RANDOM.nextInt() & 0x7FFFFFFF; int weight = (RANDOM.nextInt() & 0xFF) + 1; ByteBuf frame = releaseLater( ENCODER.encodeHeadersFrame( streamId, false, exclusive, dependency, weight, Unpooled.EMPTY_BUFFER) ); assertHeadersFrame( frame, streamId, exclusive, dependency, weight, false, Unpooled.EMPTY_BUFFER); } @Test public void testLastHttpHeadersFrame() throws Exception { int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = false; int dependency = HTTP_DEFAULT_DEPENDENCY;
int weight = HTTP_DEFAULT_WEIGHT;
twitter/netty-http2
src/test/java/com/twitter/http2/HttpFrameEncoderTest.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14
import java.util.Random; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Test; import static io.netty.util.ReferenceCountUtil.releaseLater; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH;
int dependency = RANDOM.nextInt() & 0x7FFFFFFF; int weight = (RANDOM.nextInt() & 0xFF) + 1; ByteBuf frame = releaseLater( ENCODER.encodeHeadersFrame( streamId, false, exclusive, dependency, weight, Unpooled.EMPTY_BUFFER) ); assertHeadersFrame( frame, streamId, exclusive, dependency, weight, false, Unpooled.EMPTY_BUFFER); } @Test public void testLastHttpHeadersFrame() throws Exception { int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = false; int dependency = HTTP_DEFAULT_DEPENDENCY; int weight = HTTP_DEFAULT_WEIGHT; ByteBuf frame = releaseLater( ENCODER.encodeHeadersFrame( streamId, true, exclusive, dependency, weight, Unpooled.EMPTY_BUFFER) ); assertHeadersFrame( frame, streamId, exclusive, dependency, weight, true, Unpooled.EMPTY_BUFFER); } @Test public void testContinuedHttpHeadersFrame() throws Exception { int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = RANDOM.nextBoolean(); int dependency = RANDOM.nextInt() & 0x7FFFFFFF; int weight = (RANDOM.nextInt() & 0xFF) + 1;
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // Path: src/test/java/com/twitter/http2/HttpFrameEncoderTest.java import java.util.Random; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Test; import static io.netty.util.ReferenceCountUtil.releaseLater; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; int dependency = RANDOM.nextInt() & 0x7FFFFFFF; int weight = (RANDOM.nextInt() & 0xFF) + 1; ByteBuf frame = releaseLater( ENCODER.encodeHeadersFrame( streamId, false, exclusive, dependency, weight, Unpooled.EMPTY_BUFFER) ); assertHeadersFrame( frame, streamId, exclusive, dependency, weight, false, Unpooled.EMPTY_BUFFER); } @Test public void testLastHttpHeadersFrame() throws Exception { int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = false; int dependency = HTTP_DEFAULT_DEPENDENCY; int weight = HTTP_DEFAULT_WEIGHT; ByteBuf frame = releaseLater( ENCODER.encodeHeadersFrame( streamId, true, exclusive, dependency, weight, Unpooled.EMPTY_BUFFER) ); assertHeadersFrame( frame, streamId, exclusive, dependency, weight, true, Unpooled.EMPTY_BUFFER); } @Test public void testContinuedHttpHeadersFrame() throws Exception { int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = RANDOM.nextBoolean(); int dependency = RANDOM.nextInt() & 0x7FFFFFFF; int weight = (RANDOM.nextInt() & 0xFF) + 1;
ByteBuf headerBlock = Unpooled.buffer(2 * HTTP_MAX_LENGTH);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
/* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) {
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; /* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) {
byte flags = endStream ? HTTP_FLAG_END_STREAM : 0;
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
/* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0;
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; /* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0;
ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
/* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE);
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; /* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE);
writeFrameHeader(header, data.readableBytes(), HTTP_DATA_FRAME, flags, streamId);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
/* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, data.readableBytes(), HTTP_DATA_FRAME, flags, streamId); return Unpooled.wrappedBuffer(header, data); } /** * Encode an HTTP/2 HEADERS Frame */ public ByteBuf encodeHeadersFrame( int streamId, boolean endStream, boolean exclusive, int dependency, int weight, ByteBuf headerBlock ) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; boolean hasPriority = exclusive
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; /* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, data.readableBytes(), HTTP_DATA_FRAME, flags, streamId); return Unpooled.wrappedBuffer(header, data); } /** * Encode an HTTP/2 HEADERS Frame */ public ByteBuf encodeHeadersFrame( int streamId, boolean endStream, boolean exclusive, int dependency, int weight, ByteBuf headerBlock ) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; boolean hasPriority = exclusive
|| dependency != HTTP_DEFAULT_DEPENDENCY || weight != HTTP_DEFAULT_WEIGHT;
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
/* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, data.readableBytes(), HTTP_DATA_FRAME, flags, streamId); return Unpooled.wrappedBuffer(header, data); } /** * Encode an HTTP/2 HEADERS Frame */ public ByteBuf encodeHeadersFrame( int streamId, boolean endStream, boolean exclusive, int dependency, int weight, ByteBuf headerBlock ) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; boolean hasPriority = exclusive
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; /* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, data.readableBytes(), HTTP_DATA_FRAME, flags, streamId); return Unpooled.wrappedBuffer(header, data); } /** * Encode an HTTP/2 HEADERS Frame */ public ByteBuf encodeHeadersFrame( int streamId, boolean endStream, boolean exclusive, int dependency, int weight, ByteBuf headerBlock ) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; boolean hasPriority = exclusive
|| dependency != HTTP_DEFAULT_DEPENDENCY || weight != HTTP_DEFAULT_WEIGHT;
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
/* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, data.readableBytes(), HTTP_DATA_FRAME, flags, streamId); return Unpooled.wrappedBuffer(header, data); } /** * Encode an HTTP/2 HEADERS Frame */ public ByteBuf encodeHeadersFrame( int streamId, boolean endStream, boolean exclusive, int dependency, int weight, ByteBuf headerBlock ) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; boolean hasPriority = exclusive || dependency != HTTP_DEFAULT_DEPENDENCY || weight != HTTP_DEFAULT_WEIGHT; if (hasPriority) {
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; /* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, data.readableBytes(), HTTP_DATA_FRAME, flags, streamId); return Unpooled.wrappedBuffer(header, data); } /** * Encode an HTTP/2 HEADERS Frame */ public ByteBuf encodeHeadersFrame( int streamId, boolean endStream, boolean exclusive, int dependency, int weight, ByteBuf headerBlock ) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; boolean hasPriority = exclusive || dependency != HTTP_DEFAULT_DEPENDENCY || weight != HTTP_DEFAULT_WEIGHT; if (hasPriority) {
flags |= HTTP_FLAG_PRIORITY;
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
/* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, data.readableBytes(), HTTP_DATA_FRAME, flags, streamId); return Unpooled.wrappedBuffer(header, data); } /** * Encode an HTTP/2 HEADERS Frame */ public ByteBuf encodeHeadersFrame( int streamId, boolean endStream, boolean exclusive, int dependency, int weight, ByteBuf headerBlock ) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; boolean hasPriority = exclusive || dependency != HTTP_DEFAULT_DEPENDENCY || weight != HTTP_DEFAULT_WEIGHT; if (hasPriority) { flags |= HTTP_FLAG_PRIORITY; }
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; /* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, data.readableBytes(), HTTP_DATA_FRAME, flags, streamId); return Unpooled.wrappedBuffer(header, data); } /** * Encode an HTTP/2 HEADERS Frame */ public ByteBuf encodeHeadersFrame( int streamId, boolean endStream, boolean exclusive, int dependency, int weight, ByteBuf headerBlock ) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; boolean hasPriority = exclusive || dependency != HTTP_DEFAULT_DEPENDENCY || weight != HTTP_DEFAULT_WEIGHT; if (hasPriority) { flags |= HTTP_FLAG_PRIORITY; }
int maxLength = hasPriority ? HTTP_MAX_LENGTH - 5 : HTTP_MAX_LENGTH;
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
/* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, data.readableBytes(), HTTP_DATA_FRAME, flags, streamId); return Unpooled.wrappedBuffer(header, data); } /** * Encode an HTTP/2 HEADERS Frame */ public ByteBuf encodeHeadersFrame( int streamId, boolean endStream, boolean exclusive, int dependency, int weight, ByteBuf headerBlock ) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; boolean hasPriority = exclusive || dependency != HTTP_DEFAULT_DEPENDENCY || weight != HTTP_DEFAULT_WEIGHT; if (hasPriority) { flags |= HTTP_FLAG_PRIORITY; } int maxLength = hasPriority ? HTTP_MAX_LENGTH - 5 : HTTP_MAX_LENGTH; boolean needsContinuations = headerBlock.readableBytes() > maxLength; if (!needsContinuations) {
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; /* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; /** * Encodes an HTTP/2 Frame into a {@link ByteBuf}. */ public class HttpFrameEncoder { /** * Encode an HTTP/2 DATA Frame */ public ByteBuf encodeDataFrame(int streamId, boolean endStream, ByteBuf data) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, data.readableBytes(), HTTP_DATA_FRAME, flags, streamId); return Unpooled.wrappedBuffer(header, data); } /** * Encode an HTTP/2 HEADERS Frame */ public ByteBuf encodeHeadersFrame( int streamId, boolean endStream, boolean exclusive, int dependency, int weight, ByteBuf headerBlock ) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; boolean hasPriority = exclusive || dependency != HTTP_DEFAULT_DEPENDENCY || weight != HTTP_DEFAULT_WEIGHT; if (hasPriority) { flags |= HTTP_FLAG_PRIORITY; } int maxLength = hasPriority ? HTTP_MAX_LENGTH - 5 : HTTP_MAX_LENGTH; boolean needsContinuations = headerBlock.readableBytes() > maxLength; if (!needsContinuations) {
flags |= HTTP_FLAG_END_HEADERS;
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
} /** * Encode an HTTP/2 HEADERS Frame */ public ByteBuf encodeHeadersFrame( int streamId, boolean endStream, boolean exclusive, int dependency, int weight, ByteBuf headerBlock ) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; boolean hasPriority = exclusive || dependency != HTTP_DEFAULT_DEPENDENCY || weight != HTTP_DEFAULT_WEIGHT; if (hasPriority) { flags |= HTTP_FLAG_PRIORITY; } int maxLength = hasPriority ? HTTP_MAX_LENGTH - 5 : HTTP_MAX_LENGTH; boolean needsContinuations = headerBlock.readableBytes() > maxLength; if (!needsContinuations) { flags |= HTTP_FLAG_END_HEADERS; } int length = needsContinuations ? maxLength : headerBlock.readableBytes(); if (hasPriority) { length += 5; } int frameLength = hasPriority ? HTTP_FRAME_HEADER_SIZE + 5 : HTTP_FRAME_HEADER_SIZE; ByteBuf header = Unpooled.buffer(frameLength);
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; } /** * Encode an HTTP/2 HEADERS Frame */ public ByteBuf encodeHeadersFrame( int streamId, boolean endStream, boolean exclusive, int dependency, int weight, ByteBuf headerBlock ) { byte flags = endStream ? HTTP_FLAG_END_STREAM : 0; boolean hasPriority = exclusive || dependency != HTTP_DEFAULT_DEPENDENCY || weight != HTTP_DEFAULT_WEIGHT; if (hasPriority) { flags |= HTTP_FLAG_PRIORITY; } int maxLength = hasPriority ? HTTP_MAX_LENGTH - 5 : HTTP_MAX_LENGTH; boolean needsContinuations = headerBlock.readableBytes() > maxLength; if (!needsContinuations) { flags |= HTTP_FLAG_END_HEADERS; } int length = needsContinuations ? maxLength : headerBlock.readableBytes(); if (hasPriority) { length += 5; } int frameLength = hasPriority ? HTTP_FRAME_HEADER_SIZE + 5 : HTTP_FRAME_HEADER_SIZE; ByteBuf header = Unpooled.buffer(frameLength);
writeFrameHeader(header, length, HTTP_HEADERS_FRAME, flags, streamId);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
boolean hasPriority = exclusive || dependency != HTTP_DEFAULT_DEPENDENCY || weight != HTTP_DEFAULT_WEIGHT; if (hasPriority) { flags |= HTTP_FLAG_PRIORITY; } int maxLength = hasPriority ? HTTP_MAX_LENGTH - 5 : HTTP_MAX_LENGTH; boolean needsContinuations = headerBlock.readableBytes() > maxLength; if (!needsContinuations) { flags |= HTTP_FLAG_END_HEADERS; } int length = needsContinuations ? maxLength : headerBlock.readableBytes(); if (hasPriority) { length += 5; } int frameLength = hasPriority ? HTTP_FRAME_HEADER_SIZE + 5 : HTTP_FRAME_HEADER_SIZE; ByteBuf header = Unpooled.buffer(frameLength); writeFrameHeader(header, length, HTTP_HEADERS_FRAME, flags, streamId); if (hasPriority) { if (exclusive) { header.writeInt(dependency | 0x80000000); } else { header.writeInt(dependency); } header.writeByte(weight - 1); length -= 5; } ByteBuf frame = Unpooled.wrappedBuffer(header, headerBlock.readSlice(length)); if (needsContinuations) { while (headerBlock.readableBytes() > HTTP_MAX_LENGTH) { header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE);
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; boolean hasPriority = exclusive || dependency != HTTP_DEFAULT_DEPENDENCY || weight != HTTP_DEFAULT_WEIGHT; if (hasPriority) { flags |= HTTP_FLAG_PRIORITY; } int maxLength = hasPriority ? HTTP_MAX_LENGTH - 5 : HTTP_MAX_LENGTH; boolean needsContinuations = headerBlock.readableBytes() > maxLength; if (!needsContinuations) { flags |= HTTP_FLAG_END_HEADERS; } int length = needsContinuations ? maxLength : headerBlock.readableBytes(); if (hasPriority) { length += 5; } int frameLength = hasPriority ? HTTP_FRAME_HEADER_SIZE + 5 : HTTP_FRAME_HEADER_SIZE; ByteBuf header = Unpooled.buffer(frameLength); writeFrameHeader(header, length, HTTP_HEADERS_FRAME, flags, streamId); if (hasPriority) { if (exclusive) { header.writeInt(dependency | 0x80000000); } else { header.writeInt(dependency); } header.writeByte(weight - 1); length -= 5; } ByteBuf frame = Unpooled.wrappedBuffer(header, headerBlock.readSlice(length)); if (needsContinuations) { while (headerBlock.readableBytes() > HTTP_MAX_LENGTH) { header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE);
writeFrameHeader(header, HTTP_MAX_LENGTH, HTTP_CONTINUATION_FRAME, (byte) 0, streamId);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
header.writeByte(weight - 1); length -= 5; } ByteBuf frame = Unpooled.wrappedBuffer(header, headerBlock.readSlice(length)); if (needsContinuations) { while (headerBlock.readableBytes() > HTTP_MAX_LENGTH) { header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, HTTP_MAX_LENGTH, HTTP_CONTINUATION_FRAME, (byte) 0, streamId); frame = Unpooled.wrappedBuffer(frame, header, headerBlock.readSlice(HTTP_MAX_LENGTH)); } header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader( header, headerBlock.readableBytes(), HTTP_CONTINUATION_FRAME, HTTP_FLAG_END_HEADERS, streamId ); frame = Unpooled.wrappedBuffer(frame, header, headerBlock); } return frame; } /** * Encode an HTTP/2 PRIORITY Frame */ public ByteBuf encodePriorityFrame(int streamId, boolean exclusive, int dependency, int weight) { int length = 5; byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length);
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; header.writeByte(weight - 1); length -= 5; } ByteBuf frame = Unpooled.wrappedBuffer(header, headerBlock.readSlice(length)); if (needsContinuations) { while (headerBlock.readableBytes() > HTTP_MAX_LENGTH) { header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, HTTP_MAX_LENGTH, HTTP_CONTINUATION_FRAME, (byte) 0, streamId); frame = Unpooled.wrappedBuffer(frame, header, headerBlock.readSlice(HTTP_MAX_LENGTH)); } header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader( header, headerBlock.readableBytes(), HTTP_CONTINUATION_FRAME, HTTP_FLAG_END_HEADERS, streamId ); frame = Unpooled.wrappedBuffer(frame, header, headerBlock); } return frame; } /** * Encode an HTTP/2 PRIORITY Frame */ public ByteBuf encodePriorityFrame(int streamId, boolean exclusive, int dependency, int weight) { int length = 5; byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length);
writeFrameHeader(frame, length, HTTP_PRIORITY_FRAME, flags, streamId);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
); frame = Unpooled.wrappedBuffer(frame, header, headerBlock); } return frame; } /** * Encode an HTTP/2 PRIORITY Frame */ public ByteBuf encodePriorityFrame(int streamId, boolean exclusive, int dependency, int weight) { int length = 5; byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_PRIORITY_FRAME, flags, streamId); if (exclusive) { frame.writeInt(dependency | 0x80000000); } else { frame.writeInt(dependency); } frame.writeByte(weight - 1); return frame; } /** * Encode an HTTP/2 RST_STREAM Frame */ public ByteBuf encodeRstStreamFrame(int streamId, int errorCode) { int length = 4; byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length);
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; ); frame = Unpooled.wrappedBuffer(frame, header, headerBlock); } return frame; } /** * Encode an HTTP/2 PRIORITY Frame */ public ByteBuf encodePriorityFrame(int streamId, boolean exclusive, int dependency, int weight) { int length = 5; byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_PRIORITY_FRAME, flags, streamId); if (exclusive) { frame.writeInt(dependency | 0x80000000); } else { frame.writeInt(dependency); } frame.writeByte(weight - 1); return frame; } /** * Encode an HTTP/2 RST_STREAM Frame */ public ByteBuf encodeRstStreamFrame(int streamId, int errorCode) { int length = 4; byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length);
writeFrameHeader(frame, length, HTTP_RST_STREAM_FRAME, flags, streamId);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_PRIORITY_FRAME, flags, streamId); if (exclusive) { frame.writeInt(dependency | 0x80000000); } else { frame.writeInt(dependency); } frame.writeByte(weight - 1); return frame; } /** * Encode an HTTP/2 RST_STREAM Frame */ public ByteBuf encodeRstStreamFrame(int streamId, int errorCode) { int length = 4; byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_RST_STREAM_FRAME, flags, streamId); frame.writeInt(errorCode); return frame; } /** * Encode an HTTP/2 SETTINGS Frame */ public ByteBuf encodeSettingsFrame(HttpSettingsFrame httpSettingsFrame) { Set<Integer> ids = httpSettingsFrame.getIds(); int length = ids.size() * 6;
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_PRIORITY_FRAME, flags, streamId); if (exclusive) { frame.writeInt(dependency | 0x80000000); } else { frame.writeInt(dependency); } frame.writeByte(weight - 1); return frame; } /** * Encode an HTTP/2 RST_STREAM Frame */ public ByteBuf encodeRstStreamFrame(int streamId, int errorCode) { int length = 4; byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_RST_STREAM_FRAME, flags, streamId); frame.writeInt(errorCode); return frame; } /** * Encode an HTTP/2 SETTINGS Frame */ public ByteBuf encodeSettingsFrame(HttpSettingsFrame httpSettingsFrame) { Set<Integer> ids = httpSettingsFrame.getIds(); int length = ids.size() * 6;
byte flags = httpSettingsFrame.isAck() ? HTTP_FLAG_ACK : 0;
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
if (exclusive) { frame.writeInt(dependency | 0x80000000); } else { frame.writeInt(dependency); } frame.writeByte(weight - 1); return frame; } /** * Encode an HTTP/2 RST_STREAM Frame */ public ByteBuf encodeRstStreamFrame(int streamId, int errorCode) { int length = 4; byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_RST_STREAM_FRAME, flags, streamId); frame.writeInt(errorCode); return frame; } /** * Encode an HTTP/2 SETTINGS Frame */ public ByteBuf encodeSettingsFrame(HttpSettingsFrame httpSettingsFrame) { Set<Integer> ids = httpSettingsFrame.getIds(); int length = ids.size() * 6; byte flags = httpSettingsFrame.isAck() ? HTTP_FLAG_ACK : 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length);
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; if (exclusive) { frame.writeInt(dependency | 0x80000000); } else { frame.writeInt(dependency); } frame.writeByte(weight - 1); return frame; } /** * Encode an HTTP/2 RST_STREAM Frame */ public ByteBuf encodeRstStreamFrame(int streamId, int errorCode) { int length = 4; byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_RST_STREAM_FRAME, flags, streamId); frame.writeInt(errorCode); return frame; } /** * Encode an HTTP/2 SETTINGS Frame */ public ByteBuf encodeSettingsFrame(HttpSettingsFrame httpSettingsFrame) { Set<Integer> ids = httpSettingsFrame.getIds(); int length = ids.size() * 6; byte flags = httpSettingsFrame.isAck() ? HTTP_FLAG_ACK : 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length);
writeFrameHeader(frame, length, HTTP_SETTINGS_FRAME, flags, streamId);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
writeFrameHeader(frame, length, HTTP_RST_STREAM_FRAME, flags, streamId); frame.writeInt(errorCode); return frame; } /** * Encode an HTTP/2 SETTINGS Frame */ public ByteBuf encodeSettingsFrame(HttpSettingsFrame httpSettingsFrame) { Set<Integer> ids = httpSettingsFrame.getIds(); int length = ids.size() * 6; byte flags = httpSettingsFrame.isAck() ? HTTP_FLAG_ACK : 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_SETTINGS_FRAME, flags, streamId); for (int id : ids) { frame.writeShort(id); frame.writeInt(httpSettingsFrame.getValue(id)); } return frame; } /** * Encode an HTTP/2 PUSH_PROMISE Frame */ public ByteBuf encodePushPromiseFrame(int streamId, int promisedStreamId, ByteBuf headerBlock) { boolean needsContinuations = headerBlock.readableBytes() > HTTP_MAX_LENGTH - 4; int length = needsContinuations ? HTTP_MAX_LENGTH - 4 : headerBlock.readableBytes(); byte flags = needsContinuations ? 0 : HTTP_FLAG_END_HEADERS; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + 4);
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; writeFrameHeader(frame, length, HTTP_RST_STREAM_FRAME, flags, streamId); frame.writeInt(errorCode); return frame; } /** * Encode an HTTP/2 SETTINGS Frame */ public ByteBuf encodeSettingsFrame(HttpSettingsFrame httpSettingsFrame) { Set<Integer> ids = httpSettingsFrame.getIds(); int length = ids.size() * 6; byte flags = httpSettingsFrame.isAck() ? HTTP_FLAG_ACK : 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_SETTINGS_FRAME, flags, streamId); for (int id : ids) { frame.writeShort(id); frame.writeInt(httpSettingsFrame.getValue(id)); } return frame; } /** * Encode an HTTP/2 PUSH_PROMISE Frame */ public ByteBuf encodePushPromiseFrame(int streamId, int promisedStreamId, ByteBuf headerBlock) { boolean needsContinuations = headerBlock.readableBytes() > HTTP_MAX_LENGTH - 4; int length = needsContinuations ? HTTP_MAX_LENGTH - 4 : headerBlock.readableBytes(); byte flags = needsContinuations ? 0 : HTTP_FLAG_END_HEADERS; ByteBuf header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + 4);
writeFrameHeader(header, length + 4, HTTP_PUSH_PROMISE_FRAME, flags, streamId);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
writeFrameHeader(header, length + 4, HTTP_PUSH_PROMISE_FRAME, flags, streamId); header.writeInt(promisedStreamId); ByteBuf frame = Unpooled.wrappedBuffer(header, headerBlock.readSlice(length)); if (needsContinuations) { while (headerBlock.readableBytes() > HTTP_MAX_LENGTH) { header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, HTTP_MAX_LENGTH, HTTP_CONTINUATION_FRAME, (byte) 0, streamId); frame = Unpooled.wrappedBuffer(frame, header, headerBlock.readSlice(HTTP_MAX_LENGTH)); } header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader( header, headerBlock.readableBytes(), HTTP_CONTINUATION_FRAME, HTTP_FLAG_END_HEADERS, streamId ); frame = Unpooled.wrappedBuffer(frame, header, headerBlock); } return frame; } /** * Encode an HTTP/2 PING Frame */ public ByteBuf encodePingFrame(long data, boolean ack) { int length = 8; byte flags = ack ? HTTP_FLAG_ACK : 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length);
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; writeFrameHeader(header, length + 4, HTTP_PUSH_PROMISE_FRAME, flags, streamId); header.writeInt(promisedStreamId); ByteBuf frame = Unpooled.wrappedBuffer(header, headerBlock.readSlice(length)); if (needsContinuations) { while (headerBlock.readableBytes() > HTTP_MAX_LENGTH) { header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader(header, HTTP_MAX_LENGTH, HTTP_CONTINUATION_FRAME, (byte) 0, streamId); frame = Unpooled.wrappedBuffer(frame, header, headerBlock.readSlice(HTTP_MAX_LENGTH)); } header = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE); writeFrameHeader( header, headerBlock.readableBytes(), HTTP_CONTINUATION_FRAME, HTTP_FLAG_END_HEADERS, streamId ); frame = Unpooled.wrappedBuffer(frame, header, headerBlock); } return frame; } /** * Encode an HTTP/2 PING Frame */ public ByteBuf encodePingFrame(long data, boolean ack) { int length = 8; byte flags = ack ? HTTP_FLAG_ACK : 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length);
writeFrameHeader(frame, length, HTTP_PING_FRAME, flags, streamId);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
HTTP_CONTINUATION_FRAME, HTTP_FLAG_END_HEADERS, streamId ); frame = Unpooled.wrappedBuffer(frame, header, headerBlock); } return frame; } /** * Encode an HTTP/2 PING Frame */ public ByteBuf encodePingFrame(long data, boolean ack) { int length = 8; byte flags = ack ? HTTP_FLAG_ACK : 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_PING_FRAME, flags, streamId); frame.writeLong(data); return frame; } /** * Encode an HTTP/2 GOAWAY Frame */ public ByteBuf encodeGoAwayFrame(int lastStreamId, int errorCode) { int length = 8; byte flags = 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length);
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; HTTP_CONTINUATION_FRAME, HTTP_FLAG_END_HEADERS, streamId ); frame = Unpooled.wrappedBuffer(frame, header, headerBlock); } return frame; } /** * Encode an HTTP/2 PING Frame */ public ByteBuf encodePingFrame(long data, boolean ack) { int length = 8; byte flags = ack ? HTTP_FLAG_ACK : 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_PING_FRAME, flags, streamId); frame.writeLong(data); return frame; } /** * Encode an HTTP/2 GOAWAY Frame */ public ByteBuf encodeGoAwayFrame(int lastStreamId, int errorCode) { int length = 8; byte flags = 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length);
writeFrameHeader(frame, length, HTTP_GOAWAY_FRAME, flags, streamId);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpFrameEncoder.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08;
import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME;
int length = 8; byte flags = ack ? HTTP_FLAG_ACK : 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_PING_FRAME, flags, streamId); frame.writeLong(data); return frame; } /** * Encode an HTTP/2 GOAWAY Frame */ public ByteBuf encodeGoAwayFrame(int lastStreamId, int errorCode) { int length = 8; byte flags = 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_GOAWAY_FRAME, flags, streamId); frame.writeInt(lastStreamId); frame.writeInt(errorCode); return frame; } /** * Encode an HTTP/2 WINDOW_UPDATE Frame */ public ByteBuf encodeWindowUpdateFrame(int streamId, int windowSizeIncrement) { int length = 4; byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length);
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONTINUATION_FRAME = 0x09; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DATA_FRAME = 0x00; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_ACK = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_HEADERS = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_END_STREAM = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final byte HTTP_FLAG_PRIORITY = 0x20; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_GOAWAY_FRAME = 0x07; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_HEADERS_FRAME = 0x01; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_MAX_LENGTH = 0x4000; // Initial MAX_FRAME_SIZE value is 2^14 // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PING_FRAME = 0x06; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PRIORITY_FRAME = 0x02; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_PUSH_PROMISE_FRAME = 0x05; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_RST_STREAM_FRAME = 0x03; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_SETTINGS_FRAME = 0x04; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_WINDOW_UPDATE_FRAME = 0x08; // Path: src/main/java/com/twitter/http2/HttpFrameEncoder.java import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static com.twitter.http2.HttpCodecUtil.HTTP_CONTINUATION_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DATA_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_ACK; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_HEADERS; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_END_STREAM; import static com.twitter.http2.HttpCodecUtil.HTTP_FLAG_PRIORITY; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import static com.twitter.http2.HttpCodecUtil.HTTP_GOAWAY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_HEADERS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_MAX_LENGTH; import static com.twitter.http2.HttpCodecUtil.HTTP_PING_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PRIORITY_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_PUSH_PROMISE_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_RST_STREAM_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_SETTINGS_FRAME; import static com.twitter.http2.HttpCodecUtil.HTTP_WINDOW_UPDATE_FRAME; int length = 8; byte flags = ack ? HTTP_FLAG_ACK : 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_PING_FRAME, flags, streamId); frame.writeLong(data); return frame; } /** * Encode an HTTP/2 GOAWAY Frame */ public ByteBuf encodeGoAwayFrame(int lastStreamId, int errorCode) { int length = 8; byte flags = 0; int streamId = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length); writeFrameHeader(frame, length, HTTP_GOAWAY_FRAME, flags, streamId); frame.writeInt(lastStreamId); frame.writeInt(errorCode); return frame; } /** * Encode an HTTP/2 WINDOW_UPDATE Frame */ public ByteBuf encodeWindowUpdateFrame(int streamId, int windowSizeIncrement) { int length = 4; byte flags = 0; ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length);
writeFrameHeader(frame, length, HTTP_WINDOW_UPDATE_FRAME, flags, streamId);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpConnectionHandler.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONNECTION_STREAM_ID = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static boolean isServerId(int streamId) { // // Server initiated streams have even stream identifiers // return streamId % 2 == 0; // }
import static com.twitter.http2.HttpCodecUtil.isServerId; import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.ClosedChannelException; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandler; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.util.internal.EmptyArrays; import static com.twitter.http2.HttpCodecUtil.HTTP_CONNECTION_STREAM_ID;
if (connectionReceiveWindowSize < 0) { throw new IllegalArgumentException("connectionReceiveWindowSize"); } // This will not send a window update frame immediately. // If this value increases the allowed receive window size, // a WINDOW_UPDATE frame will be sent when only half of the // session window size remains during data frame processing. // If this value decreases the allowed receive window size, // the window will be reduced as data frames are processed. initialConnectionReceiveWindowSize = connectionReceiveWindowSize; } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { super.handlerAdded(ctx); context = ctx; } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { httpFrameDecoder.decode(in); } /** * {@inheritDoc} */ @Override public void readDataFramePadding(int streamId, boolean endStream, int padding) { int deltaWindowSize = -1 * padding; int newConnectionWindowSize = httpConnection.updateReceiveWindowSize(
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONNECTION_STREAM_ID = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static boolean isServerId(int streamId) { // // Server initiated streams have even stream identifiers // return streamId % 2 == 0; // } // Path: src/main/java/com/twitter/http2/HttpConnectionHandler.java import static com.twitter.http2.HttpCodecUtil.isServerId; import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.ClosedChannelException; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandler; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.util.internal.EmptyArrays; import static com.twitter.http2.HttpCodecUtil.HTTP_CONNECTION_STREAM_ID; if (connectionReceiveWindowSize < 0) { throw new IllegalArgumentException("connectionReceiveWindowSize"); } // This will not send a window update frame immediately. // If this value increases the allowed receive window size, // a WINDOW_UPDATE frame will be sent when only half of the // session window size remains during data frame processing. // If this value decreases the allowed receive window size, // the window will be reduced as data frames are processed. initialConnectionReceiveWindowSize = connectionReceiveWindowSize; } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { super.handlerAdded(ctx); context = ctx; } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { httpFrameDecoder.decode(in); } /** * {@inheritDoc} */ @Override public void readDataFramePadding(int streamId, boolean endStream, int padding) { int deltaWindowSize = -1 * padding; int newConnectionWindowSize = httpConnection.updateReceiveWindowSize(
HTTP_CONNECTION_STREAM_ID, deltaWindowSize);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpConnectionHandler.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONNECTION_STREAM_ID = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static boolean isServerId(int streamId) { // // Server initiated streams have even stream identifiers // return streamId % 2 == 0; // }
import static com.twitter.http2.HttpCodecUtil.isServerId; import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.ClosedChannelException; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandler; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.util.internal.EmptyArrays; import static com.twitter.http2.HttpCodecUtil.HTTP_CONNECTION_STREAM_ID;
ChannelFuture future = sendGoAwayFrame(status); future.addListener(ChannelFutureListener.CLOSE); } // Http/2 Stream Error Handling: // // Upon a stream error, the endpoint must send a RST_STREAM frame which contains // the Stream-ID for the stream where the error occurred and the error status which // caused the error. // // After sending the RST_STREAM, the stream is closed to the sending endpoint. // // Note: this is only called by the worker thread private void issueStreamError(int streamId, HttpErrorCode errorCode) { boolean fireMessageReceived = !httpConnection.isRemoteSideClosed(streamId); ChannelPromise promise = context.channel().newPromise(); removeStream(streamId, promise); ByteBuf frame = httpFrameEncoder.encodeRstStreamFrame(streamId, errorCode.getCode()); context.writeAndFlush(frame, promise); if (fireMessageReceived) { HttpRstStreamFrame httpRstStreamFrame = new DefaultHttpRstStreamFrame(streamId, errorCode); context.fireChannelRead(httpRstStreamFrame); } } // Helper functions private boolean isRemoteInitiatedId(int id) {
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONNECTION_STREAM_ID = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static boolean isServerId(int streamId) { // // Server initiated streams have even stream identifiers // return streamId % 2 == 0; // } // Path: src/main/java/com/twitter/http2/HttpConnectionHandler.java import static com.twitter.http2.HttpCodecUtil.isServerId; import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.ClosedChannelException; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandler; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.util.internal.EmptyArrays; import static com.twitter.http2.HttpCodecUtil.HTTP_CONNECTION_STREAM_ID; ChannelFuture future = sendGoAwayFrame(status); future.addListener(ChannelFutureListener.CLOSE); } // Http/2 Stream Error Handling: // // Upon a stream error, the endpoint must send a RST_STREAM frame which contains // the Stream-ID for the stream where the error occurred and the error status which // caused the error. // // After sending the RST_STREAM, the stream is closed to the sending endpoint. // // Note: this is only called by the worker thread private void issueStreamError(int streamId, HttpErrorCode errorCode) { boolean fireMessageReceived = !httpConnection.isRemoteSideClosed(streamId); ChannelPromise promise = context.channel().newPromise(); removeStream(streamId, promise); ByteBuf frame = httpFrameEncoder.encodeRstStreamFrame(streamId, errorCode.getCode()); context.writeAndFlush(frame, promise); if (fireMessageReceived) { HttpRstStreamFrame httpRstStreamFrame = new DefaultHttpRstStreamFrame(streamId, errorCode); context.fireChannelRead(httpRstStreamFrame); } } // Helper functions private boolean isRemoteInitiatedId(int id) {
boolean serverId = isServerId(id);
twitter/netty-http2
src/main/java/com/twitter/http2/HttpConnection.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONNECTION_STREAM_ID = 0;
import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import io.netty.channel.ChannelPromise; import io.netty.util.internal.EmptyArrays; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_CONNECTION_STREAM_ID;
/* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; final class HttpConnection { private static final HttpProtocolException STREAM_CLOSED = new HttpProtocolException("Stream closed"); static { STREAM_CLOSED.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); } private final AtomicInteger activeLocalStreams = new AtomicInteger(); private final AtomicInteger activeRemoteStreams = new AtomicInteger(); private final Map<Integer, Node> streams = new ConcurrentHashMap<Integer, Node>(); private final AtomicInteger sendWindowSize; private final AtomicInteger receiveWindowSize; public HttpConnection(int sendWindowSize, int receiveWindowSize) {
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONNECTION_STREAM_ID = 0; // Path: src/main/java/com/twitter/http2/HttpConnection.java import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import io.netty.channel.ChannelPromise; import io.netty.util.internal.EmptyArrays; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_CONNECTION_STREAM_ID; /* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.http2; final class HttpConnection { private static final HttpProtocolException STREAM_CLOSED = new HttpProtocolException("Stream closed"); static { STREAM_CLOSED.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); } private final AtomicInteger activeLocalStreams = new AtomicInteger(); private final AtomicInteger activeRemoteStreams = new AtomicInteger(); private final Map<Integer, Node> streams = new ConcurrentHashMap<Integer, Node>(); private final AtomicInteger sendWindowSize; private final AtomicInteger receiveWindowSize; public HttpConnection(int sendWindowSize, int receiveWindowSize) {
streams.put(HTTP_CONNECTION_STREAM_ID, new Node(null));
twitter/netty-http2
src/main/java/com/twitter/http2/HttpConnection.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONNECTION_STREAM_ID = 0;
import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import io.netty.channel.ChannelPromise; import io.netty.util.internal.EmptyArrays; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_CONNECTION_STREAM_ID;
} } } return e; } PendingWrite removePendingWrite(int streamId) { Node stream = streams.get(streamId); StreamState state = stream == null ? null : stream.state; return state != null ? state.removePendingWrite() : null; } /** * Set the priority of the stream. */ boolean setPriority(int streamId, boolean exclusive, int dependency, int weight) { Node stream = streams.get(streamId); if (stream == null) { // stream closed? return false; } Node parent = streams.get(dependency); if (parent == null) { // garbage collected? stream.parent.removeDependent(stream); // set to default priority Node root = streams.get(HTTP_CONNECTION_STREAM_ID); root.addDependent(false, stream);
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_CONNECTION_STREAM_ID = 0; // Path: src/main/java/com/twitter/http2/HttpConnection.java import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import io.netty.channel.ChannelPromise; import io.netty.util.internal.EmptyArrays; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_CONNECTION_STREAM_ID; } } } return e; } PendingWrite removePendingWrite(int streamId) { Node stream = streams.get(streamId); StreamState state = stream == null ? null : stream.state; return state != null ? state.removePendingWrite() : null; } /** * Set the priority of the stream. */ boolean setPriority(int streamId, boolean exclusive, int dependency, int weight) { Node stream = streams.get(streamId); if (stream == null) { // stream closed? return false; } Node parent = streams.get(dependency); if (parent == null) { // garbage collected? stream.parent.removeDependent(stream); // set to default priority Node root = streams.get(HTTP_CONNECTION_STREAM_ID); root.addDependent(false, stream);
stream.setWeight(HTTP_DEFAULT_WEIGHT);
twitter/netty-http2
src/test/java/com/twitter/http2/HttpFrameDecoderTest.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9;
import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import java.util.Random; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import static io.netty.util.ReferenceCountUtil.releaseLater; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions;
} @Test public void testInvalidClientConnectionPreface() throws Exception { decoder = new HttpFrameDecoder(true, delegate); // Only write SETTINGS frame int length = 0; byte flags = 0; int streamId = 0; // connection identifier ByteBuf frame = settingsFrame(length, flags, streamId); decoder.decode(frame); verify(delegate).readFrameError(anyString()); verifyNoMoreInteractions(delegate); } @Test public void testHttpDataFrame() throws Exception { int length = RANDOM.nextInt() & 0x3FFF; byte flags = 0; int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; ByteBuf frame = dataFrame(length, flags, streamId); writeRandomData(frame, length); decoder.decode(frame); InOrder inOrder = inOrder(delegate); for (int i = 0; i < length; i += 8192) { // data frames do not exceed maxChunkSize
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // Path: src/test/java/com/twitter/http2/HttpFrameDecoderTest.java import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import java.util.Random; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import static io.netty.util.ReferenceCountUtil.releaseLater; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; } @Test public void testInvalidClientConnectionPreface() throws Exception { decoder = new HttpFrameDecoder(true, delegate); // Only write SETTINGS frame int length = 0; byte flags = 0; int streamId = 0; // connection identifier ByteBuf frame = settingsFrame(length, flags, streamId); decoder.decode(frame); verify(delegate).readFrameError(anyString()); verifyNoMoreInteractions(delegate); } @Test public void testHttpDataFrame() throws Exception { int length = RANDOM.nextInt() & 0x3FFF; byte flags = 0; int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; ByteBuf frame = dataFrame(length, flags, streamId); writeRandomData(frame, length); decoder.decode(frame); InOrder inOrder = inOrder(delegate); for (int i = 0; i < length; i += 8192) { // data frames do not exceed maxChunkSize
int off = HTTP_FRAME_HEADER_SIZE + i;
twitter/netty-http2
src/test/java/com/twitter/http2/HttpFrameDecoderTest.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9;
import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import java.util.Random; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import static io.netty.util.ReferenceCountUtil.releaseLater; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = RANDOM.nextBoolean(); int dependency = RANDOM.nextInt() & 0x7FFFFFFF; int weight = RANDOM.nextInt() & 0xFF; ByteBuf frame = headersFrame(length, flags, streamId); writePriorityFields(frame, exclusive, dependency, weight); writeRandomData(frame, headerBlockLength); decoder.decode(frame); InOrder inOrder = inOrder(delegate); inOrder.verify(delegate).readHeadersFrame( streamId, false, false, exclusive, dependency, weight + 1); inOrder.verify(delegate).readHeaderBlock( frame.slice(HTTP_FRAME_HEADER_SIZE + 5, headerBlockLength)); inOrder.verify(delegate).readHeaderBlockEnd(); verifyNoMoreInteractions(delegate); } @Test public void testLastHttpHeadersFrame() throws Exception { int length = 0; byte flags = 0x01 | 0x04; // END_STREAM | END_HEADERS int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; ByteBuf frame = headersFrame(length, flags, streamId); decoder.decode(frame); InOrder inOrder = inOrder(delegate); inOrder.verify(delegate).readHeadersFrame(
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // Path: src/test/java/com/twitter/http2/HttpFrameDecoderTest.java import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import java.util.Random; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import static io.netty.util.ReferenceCountUtil.releaseLater; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = RANDOM.nextBoolean(); int dependency = RANDOM.nextInt() & 0x7FFFFFFF; int weight = RANDOM.nextInt() & 0xFF; ByteBuf frame = headersFrame(length, flags, streamId); writePriorityFields(frame, exclusive, dependency, weight); writeRandomData(frame, headerBlockLength); decoder.decode(frame); InOrder inOrder = inOrder(delegate); inOrder.verify(delegate).readHeadersFrame( streamId, false, false, exclusive, dependency, weight + 1); inOrder.verify(delegate).readHeaderBlock( frame.slice(HTTP_FRAME_HEADER_SIZE + 5, headerBlockLength)); inOrder.verify(delegate).readHeaderBlockEnd(); verifyNoMoreInteractions(delegate); } @Test public void testLastHttpHeadersFrame() throws Exception { int length = 0; byte flags = 0x01 | 0x04; // END_STREAM | END_HEADERS int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; ByteBuf frame = headersFrame(length, flags, streamId); decoder.decode(frame); InOrder inOrder = inOrder(delegate); inOrder.verify(delegate).readHeadersFrame(
streamId, true, false, false, HTTP_DEFAULT_DEPENDENCY, HTTP_DEFAULT_WEIGHT);
twitter/netty-http2
src/test/java/com/twitter/http2/HttpFrameDecoderTest.java
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9;
import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import java.util.Random; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import static io.netty.util.ReferenceCountUtil.releaseLater; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = RANDOM.nextBoolean(); int dependency = RANDOM.nextInt() & 0x7FFFFFFF; int weight = RANDOM.nextInt() & 0xFF; ByteBuf frame = headersFrame(length, flags, streamId); writePriorityFields(frame, exclusive, dependency, weight); writeRandomData(frame, headerBlockLength); decoder.decode(frame); InOrder inOrder = inOrder(delegate); inOrder.verify(delegate).readHeadersFrame( streamId, false, false, exclusive, dependency, weight + 1); inOrder.verify(delegate).readHeaderBlock( frame.slice(HTTP_FRAME_HEADER_SIZE + 5, headerBlockLength)); inOrder.verify(delegate).readHeaderBlockEnd(); verifyNoMoreInteractions(delegate); } @Test public void testLastHttpHeadersFrame() throws Exception { int length = 0; byte flags = 0x01 | 0x04; // END_STREAM | END_HEADERS int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; ByteBuf frame = headersFrame(length, flags, streamId); decoder.decode(frame); InOrder inOrder = inOrder(delegate); inOrder.verify(delegate).readHeadersFrame(
// Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_DEPENDENCY = 0; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_DEFAULT_WEIGHT = 16; // // Path: src/main/java/com/twitter/http2/HttpCodecUtil.java // static final int HTTP_FRAME_HEADER_SIZE = 9; // Path: src/test/java/com/twitter/http2/HttpFrameDecoderTest.java import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_DEPENDENCY; import static com.twitter.http2.HttpCodecUtil.HTTP_DEFAULT_WEIGHT; import static com.twitter.http2.HttpCodecUtil.HTTP_FRAME_HEADER_SIZE; import java.util.Random; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import static io.netty.util.ReferenceCountUtil.releaseLater; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = RANDOM.nextBoolean(); int dependency = RANDOM.nextInt() & 0x7FFFFFFF; int weight = RANDOM.nextInt() & 0xFF; ByteBuf frame = headersFrame(length, flags, streamId); writePriorityFields(frame, exclusive, dependency, weight); writeRandomData(frame, headerBlockLength); decoder.decode(frame); InOrder inOrder = inOrder(delegate); inOrder.verify(delegate).readHeadersFrame( streamId, false, false, exclusive, dependency, weight + 1); inOrder.verify(delegate).readHeaderBlock( frame.slice(HTTP_FRAME_HEADER_SIZE + 5, headerBlockLength)); inOrder.verify(delegate).readHeaderBlockEnd(); verifyNoMoreInteractions(delegate); } @Test public void testLastHttpHeadersFrame() throws Exception { int length = 0; byte flags = 0x01 | 0x04; // END_STREAM | END_HEADERS int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; ByteBuf frame = headersFrame(length, flags, streamId); decoder.decode(frame); InOrder inOrder = inOrder(delegate); inOrder.verify(delegate).readHeadersFrame(
streamId, true, false, false, HTTP_DEFAULT_DEPENDENCY, HTTP_DEFAULT_WEIGHT);
undertow-io/jastow
test/org/apache/el/TestELInJsp.java
// Path: src/test/java/org/apache/tomcat/util/buf/ByteChunk.java // public final class ByteChunk { // // private final StringBuilder content; // // // public ByteChunk(String content) { // this.content = new StringBuilder(content); // } // // public ByteChunk() { // this.content = new StringBuilder(); // } // // @Override // public String toString() { // return content.toString(); // } // // public void write(String content) { // this.content.append(content); // } // // public void recycle() { // content.setLength(0); // } // // public String toStringInternal() { // return toString(); // } // // }
import org.apache.tomcat.util.buf.ByteChunk; import java.io.File; import java.math.RoundingMode; import java.util.Collections; import javax.servlet.DispatcherType; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.Wrapper; import org.apache.catalina.core.StandardContext; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.jasper.servlet.JasperInitializer;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.el; /** * Tests EL with an without JSP attributes using a test web application. Similar * tests may be found in {@link TestELEvaluation} and * {@link org.apache.jasper.compiler.TestAttributeParser}. */ public class TestELInJsp extends TomcatBaseTest { @Test public void testBug36923() throws Exception { getTomcatInstanceTestWebapp(false, true);
// Path: src/test/java/org/apache/tomcat/util/buf/ByteChunk.java // public final class ByteChunk { // // private final StringBuilder content; // // // public ByteChunk(String content) { // this.content = new StringBuilder(content); // } // // public ByteChunk() { // this.content = new StringBuilder(); // } // // @Override // public String toString() { // return content.toString(); // } // // public void write(String content) { // this.content.append(content); // } // // public void recycle() { // content.setLength(0); // } // // public String toStringInternal() { // return toString(); // } // // } // Path: test/org/apache/el/TestELInJsp.java import org.apache.tomcat.util.buf.ByteChunk; import java.io.File; import java.math.RoundingMode; import java.util.Collections; import javax.servlet.DispatcherType; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.Wrapper; import org.apache.catalina.core.StandardContext; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.jasper.servlet.JasperInitializer; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.el; /** * Tests EL with an without JSP attributes using a test web application. Similar * tests may be found in {@link TestELEvaluation} and * {@link org.apache.jasper.compiler.TestAttributeParser}. */ public class TestELInJsp extends TomcatBaseTest { @Test public void testBug36923() throws Exception { getTomcatInstanceTestWebapp(false, true);
ByteChunk res = getUrl("http://localhost:" + getPort() + "/test/bug36923.jsp");
undertow-io/jastow
src/test/java/io/undertow/test/jsp/expression/ExpressionJspTestCase.java
// Path: src/main/java/io/undertow/jsp/JspServletBuilder.java // public class JspServletBuilder { // // // public static void setupDeployment(final DeploymentInfo deploymentInfo, final Map<String, ? extends JspPropertyGroupDescriptor> propertyGroups, final Map<String, TagLibraryInfo> tagLibraries, final InstanceManager instanceManager) { // deploymentInfo.addServletContextAttribute(SERVLET_VERSION, deploymentInfo.getMajorVersion() + "." + deploymentInfo.getMinorVersion()); // deploymentInfo.addServletContextAttribute(JSP_PROPERTY_GROUPS, propertyGroups); // deploymentInfo.addServletContextAttribute(JSP_TAG_LIBRARIES, tagLibraries); // deploymentInfo.addServletContextAttribute(InstanceManager.class.getName(), instanceManager); // deploymentInfo.setJspConfigDescriptor(new JspConfigDescriptor() { // @Override // public Collection<TaglibDescriptor> getTaglibs() { // return null; // } // // @Override // public Collection<JspPropertyGroupDescriptor> getJspPropertyGroups() { // return (Collection<JspPropertyGroupDescriptor>) propertyGroups.values(); // } // }); // } // // public static ServletInfo createServlet(final String name, final String path) { // ServletInfo servlet = new ServletInfo(name, JspServlet.class); // servlet.addMapping(path); // //if the JSP servlet is mapped to a path that ends in /* // //we want to perform welcome file matches if the directory is requested // servlet.setRequireWelcomeFileMapping(true); // return servlet; // } // // // }
import java.io.IOException; import java.lang.reflect.Method; import java.util.HashMap; import javax.el.CompositeELResolver; import javax.el.ELContext; import javax.servlet.ServletException; import javax.servlet.jsp.JspApplicationContext; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.el.Expression; import javax.servlet.jsp.el.ExpressionEvaluator; import javax.servlet.jsp.el.FunctionMapper; import javax.servlet.jsp.el.VariableResolver; import io.undertow.jsp.HackInstanceManager; import io.undertow.jsp.JspServletBuilder; import io.undertow.server.handlers.PathHandler; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.test.util.TestClassIntrospector; import io.undertow.servlet.test.util.TestResourceLoader; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.HttpClientUtils; import io.undertow.testutils.TestHttpClient; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.jasper.deploy.JspPropertyGroup; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith;
/* * JBoss, Home of Professional Open Source. * Copyright 2012 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.test.jsp.expression; /** * @author Tomaz Cerar */ @RunWith(DefaultServer.class) public class ExpressionJspTestCase { @BeforeClass public static void setup() throws ServletException { final PathHandler servletPath = new PathHandler(); final ServletContainer container = ServletContainer.Factory.newInstance(); DeploymentInfo builder = new DeploymentInfo() .setClassLoader(ExpressionJspTestCase.class.getClassLoader()) .setContextPath("/servletContext") .setClassIntrospecter(TestClassIntrospector.INSTANCE) .setDeploymentName("servletContext.war") .setResourceManager(new TestResourceLoader(ExpressionJspTestCase.class))
// Path: src/main/java/io/undertow/jsp/JspServletBuilder.java // public class JspServletBuilder { // // // public static void setupDeployment(final DeploymentInfo deploymentInfo, final Map<String, ? extends JspPropertyGroupDescriptor> propertyGroups, final Map<String, TagLibraryInfo> tagLibraries, final InstanceManager instanceManager) { // deploymentInfo.addServletContextAttribute(SERVLET_VERSION, deploymentInfo.getMajorVersion() + "." + deploymentInfo.getMinorVersion()); // deploymentInfo.addServletContextAttribute(JSP_PROPERTY_GROUPS, propertyGroups); // deploymentInfo.addServletContextAttribute(JSP_TAG_LIBRARIES, tagLibraries); // deploymentInfo.addServletContextAttribute(InstanceManager.class.getName(), instanceManager); // deploymentInfo.setJspConfigDescriptor(new JspConfigDescriptor() { // @Override // public Collection<TaglibDescriptor> getTaglibs() { // return null; // } // // @Override // public Collection<JspPropertyGroupDescriptor> getJspPropertyGroups() { // return (Collection<JspPropertyGroupDescriptor>) propertyGroups.values(); // } // }); // } // // public static ServletInfo createServlet(final String name, final String path) { // ServletInfo servlet = new ServletInfo(name, JspServlet.class); // servlet.addMapping(path); // //if the JSP servlet is mapped to a path that ends in /* // //we want to perform welcome file matches if the directory is requested // servlet.setRequireWelcomeFileMapping(true); // return servlet; // } // // // } // Path: src/test/java/io/undertow/test/jsp/expression/ExpressionJspTestCase.java import java.io.IOException; import java.lang.reflect.Method; import java.util.HashMap; import javax.el.CompositeELResolver; import javax.el.ELContext; import javax.servlet.ServletException; import javax.servlet.jsp.JspApplicationContext; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.el.Expression; import javax.servlet.jsp.el.ExpressionEvaluator; import javax.servlet.jsp.el.FunctionMapper; import javax.servlet.jsp.el.VariableResolver; import io.undertow.jsp.HackInstanceManager; import io.undertow.jsp.JspServletBuilder; import io.undertow.server.handlers.PathHandler; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.test.util.TestClassIntrospector; import io.undertow.servlet.test.util.TestResourceLoader; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.HttpClientUtils; import io.undertow.testutils.TestHttpClient; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.jasper.deploy.JspPropertyGroup; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /* * JBoss, Home of Professional Open Source. * Copyright 2012 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.test.jsp.expression; /** * @author Tomaz Cerar */ @RunWith(DefaultServer.class) public class ExpressionJspTestCase { @BeforeClass public static void setup() throws ServletException { final PathHandler servletPath = new PathHandler(); final ServletContainer container = ServletContainer.Factory.newInstance(); DeploymentInfo builder = new DeploymentInfo() .setClassLoader(ExpressionJspTestCase.class.getClassLoader()) .setContextPath("/servletContext") .setClassIntrospecter(TestClassIntrospector.INSTANCE) .setDeploymentName("servletContext.war") .setResourceManager(new TestResourceLoader(ExpressionJspTestCase.class))
.addServlet(JspServletBuilder.createServlet("Default Jsp Servlet", "*.jsp").addMapping("*.jspx"));
undertow-io/jastow
src/test/java/io/undertow/test/jsp/lambda/LambdaJspTestCase.java
// Path: src/main/java/io/undertow/jsp/JspServletBuilder.java // public class JspServletBuilder { // // // public static void setupDeployment(final DeploymentInfo deploymentInfo, final Map<String, ? extends JspPropertyGroupDescriptor> propertyGroups, final Map<String, TagLibraryInfo> tagLibraries, final InstanceManager instanceManager) { // deploymentInfo.addServletContextAttribute(SERVLET_VERSION, deploymentInfo.getMajorVersion() + "." + deploymentInfo.getMinorVersion()); // deploymentInfo.addServletContextAttribute(JSP_PROPERTY_GROUPS, propertyGroups); // deploymentInfo.addServletContextAttribute(JSP_TAG_LIBRARIES, tagLibraries); // deploymentInfo.addServletContextAttribute(InstanceManager.class.getName(), instanceManager); // deploymentInfo.setJspConfigDescriptor(new JspConfigDescriptor() { // @Override // public Collection<TaglibDescriptor> getTaglibs() { // return null; // } // // @Override // public Collection<JspPropertyGroupDescriptor> getJspPropertyGroups() { // return (Collection<JspPropertyGroupDescriptor>) propertyGroups.values(); // } // }); // } // // public static ServletInfo createServlet(final String name, final String path) { // ServletInfo servlet = new ServletInfo(name, JspServlet.class); // servlet.addMapping(path); // //if the JSP servlet is mapped to a path that ends in /* // //we want to perform welcome file matches if the directory is requested // servlet.setRequireWelcomeFileMapping(true); // return servlet; // } // // // }
import java.io.IOException; import java.util.HashMap; import javax.servlet.ServletException; import io.undertow.jsp.HackInstanceManager; import io.undertow.jsp.JspServletBuilder; import io.undertow.server.handlers.PathHandler; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.test.util.TestClassIntrospector; import io.undertow.servlet.test.util.TestResourceLoader; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.HttpClientUtils; import io.undertow.testutils.TestHttpClient; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagLibraryInfo; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith;
/* * JBoss, Home of Professional Open Source. * Copyright 2012 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.test.jsp.lambda; /** * @author Stuart Douglas */ @RunWith(DefaultServer.class) public class LambdaJspTestCase { public static final String KEY = "io.undertow.message"; @BeforeClass public static void setup() throws ServletException { final PathHandler servletPath = new PathHandler(); final ServletContainer container = ServletContainer.Factory.newInstance(); DeploymentInfo builder = new DeploymentInfo() .setClassLoader(LambdaJspTestCase.class.getClassLoader()) .setContextPath("/servletContext") .setClassIntrospecter(TestClassIntrospector.INSTANCE) .setDeploymentName("servletContext.war") .setResourceManager(new TestResourceLoader(LambdaJspTestCase.class))
// Path: src/main/java/io/undertow/jsp/JspServletBuilder.java // public class JspServletBuilder { // // // public static void setupDeployment(final DeploymentInfo deploymentInfo, final Map<String, ? extends JspPropertyGroupDescriptor> propertyGroups, final Map<String, TagLibraryInfo> tagLibraries, final InstanceManager instanceManager) { // deploymentInfo.addServletContextAttribute(SERVLET_VERSION, deploymentInfo.getMajorVersion() + "." + deploymentInfo.getMinorVersion()); // deploymentInfo.addServletContextAttribute(JSP_PROPERTY_GROUPS, propertyGroups); // deploymentInfo.addServletContextAttribute(JSP_TAG_LIBRARIES, tagLibraries); // deploymentInfo.addServletContextAttribute(InstanceManager.class.getName(), instanceManager); // deploymentInfo.setJspConfigDescriptor(new JspConfigDescriptor() { // @Override // public Collection<TaglibDescriptor> getTaglibs() { // return null; // } // // @Override // public Collection<JspPropertyGroupDescriptor> getJspPropertyGroups() { // return (Collection<JspPropertyGroupDescriptor>) propertyGroups.values(); // } // }); // } // // public static ServletInfo createServlet(final String name, final String path) { // ServletInfo servlet = new ServletInfo(name, JspServlet.class); // servlet.addMapping(path); // //if the JSP servlet is mapped to a path that ends in /* // //we want to perform welcome file matches if the directory is requested // servlet.setRequireWelcomeFileMapping(true); // return servlet; // } // // // } // Path: src/test/java/io/undertow/test/jsp/lambda/LambdaJspTestCase.java import java.io.IOException; import java.util.HashMap; import javax.servlet.ServletException; import io.undertow.jsp.HackInstanceManager; import io.undertow.jsp.JspServletBuilder; import io.undertow.server.handlers.PathHandler; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.test.util.TestClassIntrospector; import io.undertow.servlet.test.util.TestResourceLoader; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.HttpClientUtils; import io.undertow.testutils.TestHttpClient; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagLibraryInfo; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /* * JBoss, Home of Professional Open Source. * Copyright 2012 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.test.jsp.lambda; /** * @author Stuart Douglas */ @RunWith(DefaultServer.class) public class LambdaJspTestCase { public static final String KEY = "io.undertow.message"; @BeforeClass public static void setup() throws ServletException { final PathHandler servletPath = new PathHandler(); final ServletContainer container = ServletContainer.Factory.newInstance(); DeploymentInfo builder = new DeploymentInfo() .setClassLoader(LambdaJspTestCase.class.getClassLoader()) .setContextPath("/servletContext") .setClassIntrospecter(TestClassIntrospector.INSTANCE) .setDeploymentName("servletContext.war") .setResourceManager(new TestResourceLoader(LambdaJspTestCase.class))
.addServlet(JspServletBuilder.createServlet("Default Jsp Servlet", "*.jsp")
undertow-io/jastow
src/test/java/org/apache/jasper/compiler/TestELParser.java
// Path: src/main/java/org/apache/jasper/compiler/ELParser.java // static class TextBuilder extends ELNode.Visitor { // // protected final boolean isDeferredSyntaxAllowedAsLiteral; // protected final StringBuilder output = new StringBuilder(); // // protected TextBuilder(boolean isDeferredSyntaxAllowedAsLiteral) { // this.isDeferredSyntaxAllowedAsLiteral = isDeferredSyntaxAllowedAsLiteral; // } // // public String getText() { // return output.toString(); // } // // @Override // public void visit(Root n) throws JasperException { // output.append(n.getType()); // output.append('{'); // n.getExpression().visit(this); // output.append('}'); // } // // @Override // public void visit(Function n) throws JasperException { // output.append(escapeLiteralExpression(n.getOriginalText(), isDeferredSyntaxAllowedAsLiteral)); // output.append('('); // } // // @Override // public void visit(Text n) throws JasperException { // output.append(escapeLiteralExpression(n.getText(),isDeferredSyntaxAllowedAsLiteral)); // } // // @Override // public void visit(ELText n) throws JasperException { // output.append(escapeELText(n.getText())); // } // }
import javax.el.ELContext; import javax.el.ELException; import javax.el.ELManager; import javax.el.ExpressionFactory; import javax.el.ValueExpression; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.apache.jasper.JasperException; import org.apache.jasper.compiler.ELNode.Nodes; import org.apache.jasper.compiler.ELParser.TextBuilder;
private void doTestParser(String input, String expectedResult, String expectedBuilderOutput) throws JasperException { ELException elException = null; String elResult = null; // Don't try and evaluate expressions that depend on variables or functions if (expectedResult != null) { try { ELManager manager = new ELManager(); ELContext context = manager.getELContext(); ExpressionFactory factory = ELManager.getExpressionFactory(); ValueExpression ve = factory.createValueExpression(context, input, String.class); elResult = ve.getValue(context).toString(); Assert.assertEquals(expectedResult, elResult); } catch (ELException ele) { elException = ele; } } Nodes nodes = null; try { nodes = ELParser.parse(input, false); Assert.assertNull(elException); } catch (IllegalArgumentException iae) { Assert.assertNotNull(elResult, elException); // Not strictly true but enables us to report both iae.initCause(elException); throw iae; }
// Path: src/main/java/org/apache/jasper/compiler/ELParser.java // static class TextBuilder extends ELNode.Visitor { // // protected final boolean isDeferredSyntaxAllowedAsLiteral; // protected final StringBuilder output = new StringBuilder(); // // protected TextBuilder(boolean isDeferredSyntaxAllowedAsLiteral) { // this.isDeferredSyntaxAllowedAsLiteral = isDeferredSyntaxAllowedAsLiteral; // } // // public String getText() { // return output.toString(); // } // // @Override // public void visit(Root n) throws JasperException { // output.append(n.getType()); // output.append('{'); // n.getExpression().visit(this); // output.append('}'); // } // // @Override // public void visit(Function n) throws JasperException { // output.append(escapeLiteralExpression(n.getOriginalText(), isDeferredSyntaxAllowedAsLiteral)); // output.append('('); // } // // @Override // public void visit(Text n) throws JasperException { // output.append(escapeLiteralExpression(n.getText(),isDeferredSyntaxAllowedAsLiteral)); // } // // @Override // public void visit(ELText n) throws JasperException { // output.append(escapeELText(n.getText())); // } // } // Path: src/test/java/org/apache/jasper/compiler/TestELParser.java import javax.el.ELContext; import javax.el.ELException; import javax.el.ELManager; import javax.el.ExpressionFactory; import javax.el.ValueExpression; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.apache.jasper.JasperException; import org.apache.jasper.compiler.ELNode.Nodes; import org.apache.jasper.compiler.ELParser.TextBuilder; private void doTestParser(String input, String expectedResult, String expectedBuilderOutput) throws JasperException { ELException elException = null; String elResult = null; // Don't try and evaluate expressions that depend on variables or functions if (expectedResult != null) { try { ELManager manager = new ELManager(); ELContext context = manager.getELContext(); ExpressionFactory factory = ELManager.getExpressionFactory(); ValueExpression ve = factory.createValueExpression(context, input, String.class); elResult = ve.getValue(context).toString(); Assert.assertEquals(expectedResult, elResult); } catch (ELException ele) { elException = ele; } } Nodes nodes = null; try { nodes = ELParser.parse(input, false); Assert.assertNull(elException); } catch (IllegalArgumentException iae) { Assert.assertNotNull(elResult, elException); // Not strictly true but enables us to report both iae.initCause(elException); throw iae; }
TextBuilder textBuilder = new TextBuilder(false);
undertow-io/jastow
src/test/java/io/undertow/test/jsp/taglib/TagLibJspTestCase.java
// Path: src/main/java/io/undertow/jsp/JspServletBuilder.java // public class JspServletBuilder { // // // public static void setupDeployment(final DeploymentInfo deploymentInfo, final Map<String, ? extends JspPropertyGroupDescriptor> propertyGroups, final Map<String, TagLibraryInfo> tagLibraries, final InstanceManager instanceManager) { // deploymentInfo.addServletContextAttribute(SERVLET_VERSION, deploymentInfo.getMajorVersion() + "." + deploymentInfo.getMinorVersion()); // deploymentInfo.addServletContextAttribute(JSP_PROPERTY_GROUPS, propertyGroups); // deploymentInfo.addServletContextAttribute(JSP_TAG_LIBRARIES, tagLibraries); // deploymentInfo.addServletContextAttribute(InstanceManager.class.getName(), instanceManager); // deploymentInfo.setJspConfigDescriptor(new JspConfigDescriptor() { // @Override // public Collection<TaglibDescriptor> getTaglibs() { // return null; // } // // @Override // public Collection<JspPropertyGroupDescriptor> getJspPropertyGroups() { // return (Collection<JspPropertyGroupDescriptor>) propertyGroups.values(); // } // }); // } // // public static ServletInfo createServlet(final String name, final String path) { // ServletInfo servlet = new ServletInfo(name, JspServlet.class); // servlet.addMapping(path); // //if the JSP servlet is mapped to a path that ends in /* // //we want to perform welcome file matches if the directory is requested // servlet.setRequireWelcomeFileMapping(true); // return servlet; // } // // // }
import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import io.undertow.jsp.HackInstanceManager; import io.undertow.jsp.JspServletBuilder; import io.undertow.server.handlers.PathHandler; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.test.util.TestClassIntrospector; import io.undertow.servlet.test.util.TestResourceLoader; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.HttpClientUtils; import io.undertow.testutils.TestHttpClient; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.jasper.deploy.FunctionInfo; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagLibraryInfo; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith;
/* * JBoss, Home of Professional Open Source. * Copyright 2012 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.test.jsp.taglib; /** * @author Stuart Douglas */ @RunWith(DefaultServer.class) public class TagLibJspTestCase { @BeforeClass public static void setup() throws ServletException { final PathHandler servletPath = new PathHandler(); final ServletContainer container = ServletContainer.Factory.newInstance(); DeploymentInfo builder = new DeploymentInfo() .setClassLoader(TagLibJspTestCase.class.getClassLoader()) .setContextPath("/servletContext") .setClassIntrospecter(TestClassIntrospector.INSTANCE) .setDeploymentName("servletContext.war") .setResourceManager(new TestResourceLoader(TagLibJspTestCase.class))
// Path: src/main/java/io/undertow/jsp/JspServletBuilder.java // public class JspServletBuilder { // // // public static void setupDeployment(final DeploymentInfo deploymentInfo, final Map<String, ? extends JspPropertyGroupDescriptor> propertyGroups, final Map<String, TagLibraryInfo> tagLibraries, final InstanceManager instanceManager) { // deploymentInfo.addServletContextAttribute(SERVLET_VERSION, deploymentInfo.getMajorVersion() + "." + deploymentInfo.getMinorVersion()); // deploymentInfo.addServletContextAttribute(JSP_PROPERTY_GROUPS, propertyGroups); // deploymentInfo.addServletContextAttribute(JSP_TAG_LIBRARIES, tagLibraries); // deploymentInfo.addServletContextAttribute(InstanceManager.class.getName(), instanceManager); // deploymentInfo.setJspConfigDescriptor(new JspConfigDescriptor() { // @Override // public Collection<TaglibDescriptor> getTaglibs() { // return null; // } // // @Override // public Collection<JspPropertyGroupDescriptor> getJspPropertyGroups() { // return (Collection<JspPropertyGroupDescriptor>) propertyGroups.values(); // } // }); // } // // public static ServletInfo createServlet(final String name, final String path) { // ServletInfo servlet = new ServletInfo(name, JspServlet.class); // servlet.addMapping(path); // //if the JSP servlet is mapped to a path that ends in /* // //we want to perform welcome file matches if the directory is requested // servlet.setRequireWelcomeFileMapping(true); // return servlet; // } // // // } // Path: src/test/java/io/undertow/test/jsp/taglib/TagLibJspTestCase.java import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import io.undertow.jsp.HackInstanceManager; import io.undertow.jsp.JspServletBuilder; import io.undertow.server.handlers.PathHandler; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.test.util.TestClassIntrospector; import io.undertow.servlet.test.util.TestResourceLoader; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.HttpClientUtils; import io.undertow.testutils.TestHttpClient; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.jasper.deploy.FunctionInfo; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagLibraryInfo; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /* * JBoss, Home of Professional Open Source. * Copyright 2012 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.test.jsp.taglib; /** * @author Stuart Douglas */ @RunWith(DefaultServer.class) public class TagLibJspTestCase { @BeforeClass public static void setup() throws ServletException { final PathHandler servletPath = new PathHandler(); final ServletContainer container = ServletContainer.Factory.newInstance(); DeploymentInfo builder = new DeploymentInfo() .setClassLoader(TagLibJspTestCase.class.getClassLoader()) .setContextPath("/servletContext") .setClassIntrospecter(TestClassIntrospector.INSTANCE) .setDeploymentName("servletContext.war") .setResourceManager(new TestResourceLoader(TagLibJspTestCase.class))
.addServlet(JspServletBuilder.createServlet("Default Jsp Servlet", "*.jsp"));
undertow-io/jastow
src/test/java/io/undertow/test/TomcatBaseTest.java
// Path: src/main/java/io/undertow/jsp/JspServletBuilder.java // public class JspServletBuilder { // // // public static void setupDeployment(final DeploymentInfo deploymentInfo, final Map<String, ? extends JspPropertyGroupDescriptor> propertyGroups, final Map<String, TagLibraryInfo> tagLibraries, final InstanceManager instanceManager) { // deploymentInfo.addServletContextAttribute(SERVLET_VERSION, deploymentInfo.getMajorVersion() + "." + deploymentInfo.getMinorVersion()); // deploymentInfo.addServletContextAttribute(JSP_PROPERTY_GROUPS, propertyGroups); // deploymentInfo.addServletContextAttribute(JSP_TAG_LIBRARIES, tagLibraries); // deploymentInfo.addServletContextAttribute(InstanceManager.class.getName(), instanceManager); // deploymentInfo.setJspConfigDescriptor(new JspConfigDescriptor() { // @Override // public Collection<TaglibDescriptor> getTaglibs() { // return null; // } // // @Override // public Collection<JspPropertyGroupDescriptor> getJspPropertyGroups() { // return (Collection<JspPropertyGroupDescriptor>) propertyGroups.values(); // } // }); // } // // public static ServletInfo createServlet(final String name, final String path) { // ServletInfo servlet = new ServletInfo(name, JspServlet.class); // servlet.addMapping(path); // //if the JSP servlet is mapped to a path that ends in /* // //we want to perform welcome file matches if the directory is requested // servlet.setRequireWelcomeFileMapping(true); // return servlet; // } // // // } // // Path: src/test/java/org/apache/tomcat/util/buf/ByteChunk.java // public final class ByteChunk { // // private final StringBuilder content; // // // public ByteChunk(String content) { // this.content = new StringBuilder(content); // } // // public ByteChunk() { // this.content = new StringBuilder(); // } // // @Override // public String toString() { // return content.toString(); // } // // public void write(String content) { // this.content.append(content); // } // // public void recycle() { // content.setLength(0); // } // // public String toStringInternal() { // return toString(); // } // // }
import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.DirectoryStream; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.servlet.descriptor.JspPropertyGroupDescriptor; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import io.undertow.jsp.HackInstanceManager; import io.undertow.jsp.JspServletBuilder; import io.undertow.server.handlers.PathHandler; import io.undertow.server.handlers.resource.PathResourceManager; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.test.util.TestClassIntrospector; import io.undertow.testutils.AjpIgnore; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.HttpClientUtils; import io.undertow.testutils.HttpOneOnly; import io.undertow.testutils.HttpsIgnore; import io.undertow.testutils.TestHttpClient; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.jasper.deploy.FunctionInfo; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagAttributeInfo; import org.apache.jasper.deploy.TagFileInfo; import org.apache.jasper.deploy.TagInfo; import org.apache.jasper.deploy.TagLibraryInfo; import org.apache.jasper.deploy.TagLibraryValidatorInfo; import org.apache.jasper.deploy.TagVariableInfo; import org.apache.tomcat.util.buf.ByteChunk; import org.jboss.annotation.javaee.Icon; import org.jboss.metadata.javaee.spec.DescriptionGroupMetaData; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.parser.jsp.TldMetaDataParser; import org.jboss.metadata.web.spec.AttributeMetaData; import org.jboss.metadata.web.spec.FunctionMetaData; import org.jboss.metadata.web.spec.TagFileMetaData; import org.jboss.metadata.web.spec.TagMetaData; import org.jboss.metadata.web.spec.TldMetaData; import org.jboss.metadata.web.spec.VariableMetaData; import org.junit.BeforeClass; import org.junit.runner.RunWith;
package io.undertow.test; /** * @author Tomaz Cerar (c) 2017 Red Hat Inc. * This class is just a substition class for TomcatBaseTest from tomcat codebase but adapted to work with undertow & jastow. */ @RunWith(DefaultServer.class) @HttpOneOnly @HttpsIgnore @AjpIgnore public abstract class TomcatBaseTest { @BeforeClass public static void setUp() throws Exception { final PathHandler servletPath = new PathHandler(); final ServletContainer container = ServletContainer.Factory.newInstance(); Path root = Paths.get(Thread.currentThread().getContextClassLoader().getResource("webapp").toURI()); DeploymentInfo builder = new DeploymentInfo() .setClassLoader(TomcatBaseTest.class.getClassLoader()) .setContextPath("/test") .setClassIntrospecter(TestClassIntrospector.INSTANCE) .setDeploymentName("test.war") .setResourceManager(new PathResourceManager(root))
// Path: src/main/java/io/undertow/jsp/JspServletBuilder.java // public class JspServletBuilder { // // // public static void setupDeployment(final DeploymentInfo deploymentInfo, final Map<String, ? extends JspPropertyGroupDescriptor> propertyGroups, final Map<String, TagLibraryInfo> tagLibraries, final InstanceManager instanceManager) { // deploymentInfo.addServletContextAttribute(SERVLET_VERSION, deploymentInfo.getMajorVersion() + "." + deploymentInfo.getMinorVersion()); // deploymentInfo.addServletContextAttribute(JSP_PROPERTY_GROUPS, propertyGroups); // deploymentInfo.addServletContextAttribute(JSP_TAG_LIBRARIES, tagLibraries); // deploymentInfo.addServletContextAttribute(InstanceManager.class.getName(), instanceManager); // deploymentInfo.setJspConfigDescriptor(new JspConfigDescriptor() { // @Override // public Collection<TaglibDescriptor> getTaglibs() { // return null; // } // // @Override // public Collection<JspPropertyGroupDescriptor> getJspPropertyGroups() { // return (Collection<JspPropertyGroupDescriptor>) propertyGroups.values(); // } // }); // } // // public static ServletInfo createServlet(final String name, final String path) { // ServletInfo servlet = new ServletInfo(name, JspServlet.class); // servlet.addMapping(path); // //if the JSP servlet is mapped to a path that ends in /* // //we want to perform welcome file matches if the directory is requested // servlet.setRequireWelcomeFileMapping(true); // return servlet; // } // // // } // // Path: src/test/java/org/apache/tomcat/util/buf/ByteChunk.java // public final class ByteChunk { // // private final StringBuilder content; // // // public ByteChunk(String content) { // this.content = new StringBuilder(content); // } // // public ByteChunk() { // this.content = new StringBuilder(); // } // // @Override // public String toString() { // return content.toString(); // } // // public void write(String content) { // this.content.append(content); // } // // public void recycle() { // content.setLength(0); // } // // public String toStringInternal() { // return toString(); // } // // } // Path: src/test/java/io/undertow/test/TomcatBaseTest.java import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.DirectoryStream; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.servlet.descriptor.JspPropertyGroupDescriptor; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import io.undertow.jsp.HackInstanceManager; import io.undertow.jsp.JspServletBuilder; import io.undertow.server.handlers.PathHandler; import io.undertow.server.handlers.resource.PathResourceManager; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.test.util.TestClassIntrospector; import io.undertow.testutils.AjpIgnore; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.HttpClientUtils; import io.undertow.testutils.HttpOneOnly; import io.undertow.testutils.HttpsIgnore; import io.undertow.testutils.TestHttpClient; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.jasper.deploy.FunctionInfo; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagAttributeInfo; import org.apache.jasper.deploy.TagFileInfo; import org.apache.jasper.deploy.TagInfo; import org.apache.jasper.deploy.TagLibraryInfo; import org.apache.jasper.deploy.TagLibraryValidatorInfo; import org.apache.jasper.deploy.TagVariableInfo; import org.apache.tomcat.util.buf.ByteChunk; import org.jboss.annotation.javaee.Icon; import org.jboss.metadata.javaee.spec.DescriptionGroupMetaData; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.parser.jsp.TldMetaDataParser; import org.jboss.metadata.web.spec.AttributeMetaData; import org.jboss.metadata.web.spec.FunctionMetaData; import org.jboss.metadata.web.spec.TagFileMetaData; import org.jboss.metadata.web.spec.TagMetaData; import org.jboss.metadata.web.spec.TldMetaData; import org.jboss.metadata.web.spec.VariableMetaData; import org.junit.BeforeClass; import org.junit.runner.RunWith; package io.undertow.test; /** * @author Tomaz Cerar (c) 2017 Red Hat Inc. * This class is just a substition class for TomcatBaseTest from tomcat codebase but adapted to work with undertow & jastow. */ @RunWith(DefaultServer.class) @HttpOneOnly @HttpsIgnore @AjpIgnore public abstract class TomcatBaseTest { @BeforeClass public static void setUp() throws Exception { final PathHandler servletPath = new PathHandler(); final ServletContainer container = ServletContainer.Factory.newInstance(); Path root = Paths.get(Thread.currentThread().getContextClassLoader().getResource("webapp").toURI()); DeploymentInfo builder = new DeploymentInfo() .setClassLoader(TomcatBaseTest.class.getClassLoader()) .setContextPath("/test") .setClassIntrospecter(TestClassIntrospector.INSTANCE) .setDeploymentName("test.war") .setResourceManager(new PathResourceManager(root))
.addServlet(JspServletBuilder.createServlet("Default Jsp Servlet", "*.jsp").addMapping("*.jspx"));
undertow-io/jastow
src/test/java/io/undertow/test/jsp/classref/ClassRefTestCase.java
// Path: src/main/java/io/undertow/jsp/JspServletBuilder.java // public class JspServletBuilder { // // // public static void setupDeployment(final DeploymentInfo deploymentInfo, final Map<String, ? extends JspPropertyGroupDescriptor> propertyGroups, final Map<String, TagLibraryInfo> tagLibraries, final InstanceManager instanceManager) { // deploymentInfo.addServletContextAttribute(SERVLET_VERSION, deploymentInfo.getMajorVersion() + "." + deploymentInfo.getMinorVersion()); // deploymentInfo.addServletContextAttribute(JSP_PROPERTY_GROUPS, propertyGroups); // deploymentInfo.addServletContextAttribute(JSP_TAG_LIBRARIES, tagLibraries); // deploymentInfo.addServletContextAttribute(InstanceManager.class.getName(), instanceManager); // deploymentInfo.setJspConfigDescriptor(new JspConfigDescriptor() { // @Override // public Collection<TaglibDescriptor> getTaglibs() { // return null; // } // // @Override // public Collection<JspPropertyGroupDescriptor> getJspPropertyGroups() { // return (Collection<JspPropertyGroupDescriptor>) propertyGroups.values(); // } // }); // } // // public static ServletInfo createServlet(final String name, final String path) { // ServletInfo servlet = new ServletInfo(name, JspServlet.class); // servlet.addMapping(path); // //if the JSP servlet is mapped to a path that ends in /* // //we want to perform welcome file matches if the directory is requested // servlet.setRequireWelcomeFileMapping(true); // return servlet; // } // // // }
import io.undertow.jsp.HackInstanceManager; import io.undertow.jsp.JspServletBuilder; import io.undertow.server.handlers.PathHandler; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.test.util.TestClassIntrospector; import io.undertow.servlet.test.util.TestResourceLoader; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.TestHttpClient; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagLibraryInfo; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import java.net.HttpURLConnection; import java.util.HashMap; import javax.servlet.ServletException;
package io.undertow.test.jsp.classref; /** * @tpChapter Class access from jsp */ @RunWith(DefaultServer.class) public class ClassRefTestCase { private static final String CONTEXT_NAME = "classref"; private static final String CONTEXT_PATH = "/" + CONTEXT_NAME; @BeforeClass public static void setup() throws ServletException { final PathHandler servletPath = new PathHandler(); final ServletContainer container = ServletContainer.Factory.newInstance(); DeploymentInfo builder = new DeploymentInfo() .setClassLoader(ClassRefTestCase.class.getClassLoader()) .setContextPath(CONTEXT_PATH) .setClassIntrospecter(TestClassIntrospector.INSTANCE) .setDeploymentName(CONTEXT_NAME + ".war") .setResourceManager(new TestResourceLoader(ClassRefTestCase.class))
// Path: src/main/java/io/undertow/jsp/JspServletBuilder.java // public class JspServletBuilder { // // // public static void setupDeployment(final DeploymentInfo deploymentInfo, final Map<String, ? extends JspPropertyGroupDescriptor> propertyGroups, final Map<String, TagLibraryInfo> tagLibraries, final InstanceManager instanceManager) { // deploymentInfo.addServletContextAttribute(SERVLET_VERSION, deploymentInfo.getMajorVersion() + "." + deploymentInfo.getMinorVersion()); // deploymentInfo.addServletContextAttribute(JSP_PROPERTY_GROUPS, propertyGroups); // deploymentInfo.addServletContextAttribute(JSP_TAG_LIBRARIES, tagLibraries); // deploymentInfo.addServletContextAttribute(InstanceManager.class.getName(), instanceManager); // deploymentInfo.setJspConfigDescriptor(new JspConfigDescriptor() { // @Override // public Collection<TaglibDescriptor> getTaglibs() { // return null; // } // // @Override // public Collection<JspPropertyGroupDescriptor> getJspPropertyGroups() { // return (Collection<JspPropertyGroupDescriptor>) propertyGroups.values(); // } // }); // } // // public static ServletInfo createServlet(final String name, final String path) { // ServletInfo servlet = new ServletInfo(name, JspServlet.class); // servlet.addMapping(path); // //if the JSP servlet is mapped to a path that ends in /* // //we want to perform welcome file matches if the directory is requested // servlet.setRequireWelcomeFileMapping(true); // return servlet; // } // // // } // Path: src/test/java/io/undertow/test/jsp/classref/ClassRefTestCase.java import io.undertow.jsp.HackInstanceManager; import io.undertow.jsp.JspServletBuilder; import io.undertow.server.handlers.PathHandler; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.test.util.TestClassIntrospector; import io.undertow.servlet.test.util.TestResourceLoader; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.TestHttpClient; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagLibraryInfo; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import java.net.HttpURLConnection; import java.util.HashMap; import javax.servlet.ServletException; package io.undertow.test.jsp.classref; /** * @tpChapter Class access from jsp */ @RunWith(DefaultServer.class) public class ClassRefTestCase { private static final String CONTEXT_NAME = "classref"; private static final String CONTEXT_PATH = "/" + CONTEXT_NAME; @BeforeClass public static void setup() throws ServletException { final PathHandler servletPath = new PathHandler(); final ServletContainer container = ServletContainer.Factory.newInstance(); DeploymentInfo builder = new DeploymentInfo() .setClassLoader(ClassRefTestCase.class.getClassLoader()) .setContextPath(CONTEXT_PATH) .setClassIntrospecter(TestClassIntrospector.INSTANCE) .setDeploymentName(CONTEXT_NAME + ".war") .setResourceManager(new TestResourceLoader(ClassRefTestCase.class))
.addServlet(JspServletBuilder.createServlet("Default Jsp Servlet", "*.jsp"));
undertow-io/jastow
src/test/java/io/undertow/test/jsp/classref/Indirect.java
// Path: src/test/java/io/undertow/test/jsp/classref/testname/MyTest.java // public class MyTest { // }
import io.undertow.test.jsp.classref.testname.MyTest;
package io.undertow.test.jsp.classref; public class Indirect { public Indirect() {
// Path: src/test/java/io/undertow/test/jsp/classref/testname/MyTest.java // public class MyTest { // } // Path: src/test/java/io/undertow/test/jsp/classref/Indirect.java import io.undertow.test.jsp.classref.testname.MyTest; package io.undertow.test.jsp.classref; public class Indirect { public Indirect() {
MyTest myTest = new MyTest();
hazelcast/spring-data-hazelcast
src/main/java/org/springframework/data/hazelcast/HazelcastQueryEngine.java
// Path: src/main/java/org/springframework/data/hazelcast/repository/query/HazelcastCriteriaAccessor.java // public class HazelcastCriteriaAccessor // implements CriteriaAccessor<Predicate<?, ?>> { // // /** // * @param A query in Spring form // * @return The same in Hazelcast form // */ // public Predicate<?, ?> resolve(KeyValueQuery<?> query) { // // if (query == null) { // return null; // } // // final Object criteria = query.getCriteria(); // if (criteria == null) { // return null; // } // // if (criteria instanceof PagingPredicateImpl) { // PagingPredicateImpl pagingPredicate = (PagingPredicateImpl) criteria; // query.limit(pagingPredicate.getPageSize()); // return pagingPredicate.getPredicate(); // } // // if (criteria instanceof Predicate) { // return (Predicate<?, ?>) criteria; // } // // throw new UnsupportedOperationException(query.toString()); // } // // } // // Path: src/main/java/org/springframework/data/hazelcast/repository/query/HazelcastSortAccessor.java // public class HazelcastSortAccessor // implements SortAccessor<Comparator<Entry<?, ?>>> { // // /** // * <p> // * Sort on a sequence of fields, possibly none. // * </P> // * // * @param query If not null, will contain one of more {@link Sort.Order} objects. // * @return A sequence of comparators or {@code null} // */ // public Comparator<Entry<?, ?>> resolve(KeyValueQuery<?> query) { // // if (query == null || query.getSort() == Sort.unsorted()) { // return null; // } // // Comparator hazelcastPropertyComparator = null; // // for (Order order : query.getSort()) { // // if (order.getProperty().indexOf('.') > -1) { // throw new UnsupportedOperationException("Embedded fields not implemented: " + order); // } // // if (order.isIgnoreCase()) { // throw new UnsupportedOperationException("Ignore case not implemented: " + order); // } // // if (NullHandling.NATIVE != order.getNullHandling()) { // throw new UnsupportedOperationException("Null handling not implemented: " + order); // } // // if (hazelcastPropertyComparator == null) { // hazelcastPropertyComparator = new HazelcastPropertyComparator(order.getProperty(), // order.isAscending()); // } else { // hazelcastPropertyComparator = hazelcastPropertyComparator.thenComparing( // new HazelcastPropertyComparator(order.getProperty(), // order.isAscending())); // } // } // // return hazelcastPropertyComparator; // } // // }
import com.hazelcast.query.PagingPredicate; import com.hazelcast.query.Predicate; import com.hazelcast.query.impl.predicates.PagingPredicateImpl; import org.springframework.data.hazelcast.repository.query.HazelcastCriteriaAccessor; import org.springframework.data.hazelcast.repository.query.HazelcastSortAccessor; import org.springframework.data.keyvalue.core.QueryEngine; import org.springframework.util.Assert; import java.util.Collection; import java.util.Comparator; import java.util.Map.Entry;
/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast; /** * <p> * Implementation of {@code findBy*()} and {@code countBy*{}} queries. * </P> * * @author Christoph Strobl * @author Neil Stevenson * @author Viacheslav Petriaiev */ public class HazelcastQueryEngine extends QueryEngine<HazelcastKeyValueAdapter, Predicate<?, ?>, Comparator<Entry<?, ?>>> { public HazelcastQueryEngine() {
// Path: src/main/java/org/springframework/data/hazelcast/repository/query/HazelcastCriteriaAccessor.java // public class HazelcastCriteriaAccessor // implements CriteriaAccessor<Predicate<?, ?>> { // // /** // * @param A query in Spring form // * @return The same in Hazelcast form // */ // public Predicate<?, ?> resolve(KeyValueQuery<?> query) { // // if (query == null) { // return null; // } // // final Object criteria = query.getCriteria(); // if (criteria == null) { // return null; // } // // if (criteria instanceof PagingPredicateImpl) { // PagingPredicateImpl pagingPredicate = (PagingPredicateImpl) criteria; // query.limit(pagingPredicate.getPageSize()); // return pagingPredicate.getPredicate(); // } // // if (criteria instanceof Predicate) { // return (Predicate<?, ?>) criteria; // } // // throw new UnsupportedOperationException(query.toString()); // } // // } // // Path: src/main/java/org/springframework/data/hazelcast/repository/query/HazelcastSortAccessor.java // public class HazelcastSortAccessor // implements SortAccessor<Comparator<Entry<?, ?>>> { // // /** // * <p> // * Sort on a sequence of fields, possibly none. // * </P> // * // * @param query If not null, will contain one of more {@link Sort.Order} objects. // * @return A sequence of comparators or {@code null} // */ // public Comparator<Entry<?, ?>> resolve(KeyValueQuery<?> query) { // // if (query == null || query.getSort() == Sort.unsorted()) { // return null; // } // // Comparator hazelcastPropertyComparator = null; // // for (Order order : query.getSort()) { // // if (order.getProperty().indexOf('.') > -1) { // throw new UnsupportedOperationException("Embedded fields not implemented: " + order); // } // // if (order.isIgnoreCase()) { // throw new UnsupportedOperationException("Ignore case not implemented: " + order); // } // // if (NullHandling.NATIVE != order.getNullHandling()) { // throw new UnsupportedOperationException("Null handling not implemented: " + order); // } // // if (hazelcastPropertyComparator == null) { // hazelcastPropertyComparator = new HazelcastPropertyComparator(order.getProperty(), // order.isAscending()); // } else { // hazelcastPropertyComparator = hazelcastPropertyComparator.thenComparing( // new HazelcastPropertyComparator(order.getProperty(), // order.isAscending())); // } // } // // return hazelcastPropertyComparator; // } // // } // Path: src/main/java/org/springframework/data/hazelcast/HazelcastQueryEngine.java import com.hazelcast.query.PagingPredicate; import com.hazelcast.query.Predicate; import com.hazelcast.query.impl.predicates.PagingPredicateImpl; import org.springframework.data.hazelcast.repository.query.HazelcastCriteriaAccessor; import org.springframework.data.hazelcast.repository.query.HazelcastSortAccessor; import org.springframework.data.keyvalue.core.QueryEngine; import org.springframework.util.Assert; import java.util.Collection; import java.util.Comparator; import java.util.Map.Entry; /* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast; /** * <p> * Implementation of {@code findBy*()} and {@code countBy*{}} queries. * </P> * * @author Christoph Strobl * @author Neil Stevenson * @author Viacheslav Petriaiev */ public class HazelcastQueryEngine extends QueryEngine<HazelcastKeyValueAdapter, Predicate<?, ?>, Comparator<Entry<?, ?>>> { public HazelcastQueryEngine() {
super(new HazelcastCriteriaAccessor(), new HazelcastSortAccessor());
hazelcast/spring-data-hazelcast
src/main/java/org/springframework/data/hazelcast/HazelcastQueryEngine.java
// Path: src/main/java/org/springframework/data/hazelcast/repository/query/HazelcastCriteriaAccessor.java // public class HazelcastCriteriaAccessor // implements CriteriaAccessor<Predicate<?, ?>> { // // /** // * @param A query in Spring form // * @return The same in Hazelcast form // */ // public Predicate<?, ?> resolve(KeyValueQuery<?> query) { // // if (query == null) { // return null; // } // // final Object criteria = query.getCriteria(); // if (criteria == null) { // return null; // } // // if (criteria instanceof PagingPredicateImpl) { // PagingPredicateImpl pagingPredicate = (PagingPredicateImpl) criteria; // query.limit(pagingPredicate.getPageSize()); // return pagingPredicate.getPredicate(); // } // // if (criteria instanceof Predicate) { // return (Predicate<?, ?>) criteria; // } // // throw new UnsupportedOperationException(query.toString()); // } // // } // // Path: src/main/java/org/springframework/data/hazelcast/repository/query/HazelcastSortAccessor.java // public class HazelcastSortAccessor // implements SortAccessor<Comparator<Entry<?, ?>>> { // // /** // * <p> // * Sort on a sequence of fields, possibly none. // * </P> // * // * @param query If not null, will contain one of more {@link Sort.Order} objects. // * @return A sequence of comparators or {@code null} // */ // public Comparator<Entry<?, ?>> resolve(KeyValueQuery<?> query) { // // if (query == null || query.getSort() == Sort.unsorted()) { // return null; // } // // Comparator hazelcastPropertyComparator = null; // // for (Order order : query.getSort()) { // // if (order.getProperty().indexOf('.') > -1) { // throw new UnsupportedOperationException("Embedded fields not implemented: " + order); // } // // if (order.isIgnoreCase()) { // throw new UnsupportedOperationException("Ignore case not implemented: " + order); // } // // if (NullHandling.NATIVE != order.getNullHandling()) { // throw new UnsupportedOperationException("Null handling not implemented: " + order); // } // // if (hazelcastPropertyComparator == null) { // hazelcastPropertyComparator = new HazelcastPropertyComparator(order.getProperty(), // order.isAscending()); // } else { // hazelcastPropertyComparator = hazelcastPropertyComparator.thenComparing( // new HazelcastPropertyComparator(order.getProperty(), // order.isAscending())); // } // } // // return hazelcastPropertyComparator; // } // // }
import com.hazelcast.query.PagingPredicate; import com.hazelcast.query.Predicate; import com.hazelcast.query.impl.predicates.PagingPredicateImpl; import org.springframework.data.hazelcast.repository.query.HazelcastCriteriaAccessor; import org.springframework.data.hazelcast.repository.query.HazelcastSortAccessor; import org.springframework.data.keyvalue.core.QueryEngine; import org.springframework.util.Assert; import java.util.Collection; import java.util.Comparator; import java.util.Map.Entry;
/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast; /** * <p> * Implementation of {@code findBy*()} and {@code countBy*{}} queries. * </P> * * @author Christoph Strobl * @author Neil Stevenson * @author Viacheslav Petriaiev */ public class HazelcastQueryEngine extends QueryEngine<HazelcastKeyValueAdapter, Predicate<?, ?>, Comparator<Entry<?, ?>>> { public HazelcastQueryEngine() {
// Path: src/main/java/org/springframework/data/hazelcast/repository/query/HazelcastCriteriaAccessor.java // public class HazelcastCriteriaAccessor // implements CriteriaAccessor<Predicate<?, ?>> { // // /** // * @param A query in Spring form // * @return The same in Hazelcast form // */ // public Predicate<?, ?> resolve(KeyValueQuery<?> query) { // // if (query == null) { // return null; // } // // final Object criteria = query.getCriteria(); // if (criteria == null) { // return null; // } // // if (criteria instanceof PagingPredicateImpl) { // PagingPredicateImpl pagingPredicate = (PagingPredicateImpl) criteria; // query.limit(pagingPredicate.getPageSize()); // return pagingPredicate.getPredicate(); // } // // if (criteria instanceof Predicate) { // return (Predicate<?, ?>) criteria; // } // // throw new UnsupportedOperationException(query.toString()); // } // // } // // Path: src/main/java/org/springframework/data/hazelcast/repository/query/HazelcastSortAccessor.java // public class HazelcastSortAccessor // implements SortAccessor<Comparator<Entry<?, ?>>> { // // /** // * <p> // * Sort on a sequence of fields, possibly none. // * </P> // * // * @param query If not null, will contain one of more {@link Sort.Order} objects. // * @return A sequence of comparators or {@code null} // */ // public Comparator<Entry<?, ?>> resolve(KeyValueQuery<?> query) { // // if (query == null || query.getSort() == Sort.unsorted()) { // return null; // } // // Comparator hazelcastPropertyComparator = null; // // for (Order order : query.getSort()) { // // if (order.getProperty().indexOf('.') > -1) { // throw new UnsupportedOperationException("Embedded fields not implemented: " + order); // } // // if (order.isIgnoreCase()) { // throw new UnsupportedOperationException("Ignore case not implemented: " + order); // } // // if (NullHandling.NATIVE != order.getNullHandling()) { // throw new UnsupportedOperationException("Null handling not implemented: " + order); // } // // if (hazelcastPropertyComparator == null) { // hazelcastPropertyComparator = new HazelcastPropertyComparator(order.getProperty(), // order.isAscending()); // } else { // hazelcastPropertyComparator = hazelcastPropertyComparator.thenComparing( // new HazelcastPropertyComparator(order.getProperty(), // order.isAscending())); // } // } // // return hazelcastPropertyComparator; // } // // } // Path: src/main/java/org/springframework/data/hazelcast/HazelcastQueryEngine.java import com.hazelcast.query.PagingPredicate; import com.hazelcast.query.Predicate; import com.hazelcast.query.impl.predicates.PagingPredicateImpl; import org.springframework.data.hazelcast.repository.query.HazelcastCriteriaAccessor; import org.springframework.data.hazelcast.repository.query.HazelcastSortAccessor; import org.springframework.data.keyvalue.core.QueryEngine; import org.springframework.util.Assert; import java.util.Collection; import java.util.Comparator; import java.util.Map.Entry; /* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast; /** * <p> * Implementation of {@code findBy*()} and {@code countBy*{}} queries. * </P> * * @author Christoph Strobl * @author Neil Stevenson * @author Viacheslav Petriaiev */ public class HazelcastQueryEngine extends QueryEngine<HazelcastKeyValueAdapter, Predicate<?, ?>, Comparator<Entry<?, ?>>> { public HazelcastQueryEngine() {
super(new HazelcastCriteriaAccessor(), new HazelcastSortAccessor());
hazelcast/spring-data-hazelcast
src/main/java/org/springframework/data/hazelcast/repository/config/HazelcastRepositoryConfigurationExtension.java
// Path: src/main/java/org/springframework/data/hazelcast/HazelcastKeyValueAdapter.java // public class HazelcastKeyValueAdapter // extends AbstractKeyValueAdapter { // // private HazelcastInstance hzInstance; // // public HazelcastKeyValueAdapter(HazelcastInstance hzInstance) { // super(new HazelcastQueryEngine()); // Assert.notNull(hzInstance, "hzInstance must not be 'null'."); // this.hzInstance = hzInstance; // } // // public void setHzInstance(HazelcastInstance hzInstance) { // this.hzInstance = hzInstance; // } // // @Override // public Object put(Object id, Object item, String keyspace) { // Assert.notNull(id, "Id must not be 'null' for adding."); // Assert.notNull(item, "Item must not be 'null' for adding."); // // return getMap(keyspace).put(id, item); // } // // @Override // public boolean contains(Object id, String keyspace) { // return getMap(keyspace).containsKey(id); // } // // @Override // public Object get(Object id, String keyspace) { // return getMap(keyspace).get(id); // } // // @Override // public Object delete(Object id, String keyspace) { // return getMap(keyspace).remove(id); // } // // @Override // public Iterable<?> getAllOf(String keyspace) { // return getMap(keyspace).values(); // } // // @Override // public void deleteAllOf(String keyspace) { // getMap(keyspace).clear(); // } // // @Override // public void clear() { // this.hzInstance.shutdown(); // } // // protected IMap<Object, Object> getMap(final String keyspace) { // return hzInstance.getMap(keyspace); // } // // @Override // public void destroy() { // this.clear(); // } // // @Override // public long count(String keyspace) { // return getMap(keyspace).size(); // } // // @Override // public CloseableIterator<Map.Entry<Object, Object>> entries(String keyspace) { // Iterator<Entry<Object, Object>> iterator = this.getMap(keyspace).entrySet().iterator(); // return new ForwardingCloseableIterator<>(iterator); // } // }
import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.data.hazelcast.HazelcastKeyValueAdapter; import org.springframework.data.keyvalue.core.KeyValueTemplate; import org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension; import org.springframework.data.repository.config.RepositoryConfigurationExtension; import org.springframework.data.repository.config.RepositoryConfigurationSource;
/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast.repository.config; /** * Hazelcast-specific {@link RepositoryConfigurationExtension}. * * @author Oliver Gierke * @author Rafal Leszko */ class HazelcastRepositoryConfigurationExtension extends KeyValueRepositoryConfigurationExtension { private static final String HAZELCAST_ADAPTER_BEAN_NAME = "hazelcastKeyValueAdapter"; /* * (non-Javadoc) * @see org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension * #getModuleName() */ @Override public String getModuleName() { return "Hazelcast"; } /* * (non-Javadoc) * @see org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension * #getModulePrefix() */ @Override protected String getModulePrefix() { return "hazelcast"; } /* * (non-Javadoc) * @see org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension * #getDefaultKeyValueTemplateRef() */ @Override protected String getDefaultKeyValueTemplateRef() { return "keyValueTemplate"; } @Override public void registerBeansForRoot(BeanDefinitionRegistry registry, RepositoryConfigurationSource configurationSource) { // register HazelcastKeyValueAdapter String hazelcastInstanceRef = configurationSource.getAttribute("hazelcastInstanceRef").get();
// Path: src/main/java/org/springframework/data/hazelcast/HazelcastKeyValueAdapter.java // public class HazelcastKeyValueAdapter // extends AbstractKeyValueAdapter { // // private HazelcastInstance hzInstance; // // public HazelcastKeyValueAdapter(HazelcastInstance hzInstance) { // super(new HazelcastQueryEngine()); // Assert.notNull(hzInstance, "hzInstance must not be 'null'."); // this.hzInstance = hzInstance; // } // // public void setHzInstance(HazelcastInstance hzInstance) { // this.hzInstance = hzInstance; // } // // @Override // public Object put(Object id, Object item, String keyspace) { // Assert.notNull(id, "Id must not be 'null' for adding."); // Assert.notNull(item, "Item must not be 'null' for adding."); // // return getMap(keyspace).put(id, item); // } // // @Override // public boolean contains(Object id, String keyspace) { // return getMap(keyspace).containsKey(id); // } // // @Override // public Object get(Object id, String keyspace) { // return getMap(keyspace).get(id); // } // // @Override // public Object delete(Object id, String keyspace) { // return getMap(keyspace).remove(id); // } // // @Override // public Iterable<?> getAllOf(String keyspace) { // return getMap(keyspace).values(); // } // // @Override // public void deleteAllOf(String keyspace) { // getMap(keyspace).clear(); // } // // @Override // public void clear() { // this.hzInstance.shutdown(); // } // // protected IMap<Object, Object> getMap(final String keyspace) { // return hzInstance.getMap(keyspace); // } // // @Override // public void destroy() { // this.clear(); // } // // @Override // public long count(String keyspace) { // return getMap(keyspace).size(); // } // // @Override // public CloseableIterator<Map.Entry<Object, Object>> entries(String keyspace) { // Iterator<Entry<Object, Object>> iterator = this.getMap(keyspace).entrySet().iterator(); // return new ForwardingCloseableIterator<>(iterator); // } // } // Path: src/main/java/org/springframework/data/hazelcast/repository/config/HazelcastRepositoryConfigurationExtension.java import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.data.hazelcast.HazelcastKeyValueAdapter; import org.springframework.data.keyvalue.core.KeyValueTemplate; import org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension; import org.springframework.data.repository.config.RepositoryConfigurationExtension; import org.springframework.data.repository.config.RepositoryConfigurationSource; /* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast.repository.config; /** * Hazelcast-specific {@link RepositoryConfigurationExtension}. * * @author Oliver Gierke * @author Rafal Leszko */ class HazelcastRepositoryConfigurationExtension extends KeyValueRepositoryConfigurationExtension { private static final String HAZELCAST_ADAPTER_BEAN_NAME = "hazelcastKeyValueAdapter"; /* * (non-Javadoc) * @see org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension * #getModuleName() */ @Override public String getModuleName() { return "Hazelcast"; } /* * (non-Javadoc) * @see org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension * #getModulePrefix() */ @Override protected String getModulePrefix() { return "hazelcast"; } /* * (non-Javadoc) * @see org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension * #getDefaultKeyValueTemplateRef() */ @Override protected String getDefaultKeyValueTemplateRef() { return "keyValueTemplate"; } @Override public void registerBeansForRoot(BeanDefinitionRegistry registry, RepositoryConfigurationSource configurationSource) { // register HazelcastKeyValueAdapter String hazelcastInstanceRef = configurationSource.getAttribute("hazelcastInstanceRef").get();
RootBeanDefinition hazelcastKeyValueAdapterDefinition = new RootBeanDefinition(HazelcastKeyValueAdapter.class);
hazelcast/spring-data-hazelcast
src/test/java/test/utils/repository/custom/MyTitleRepository.java
// Path: src/main/java/org/springframework/data/hazelcast/repository/HazelcastRepository.java // @NoRepositoryBean // public interface HazelcastRepository<T extends Serializable, ID extends Serializable> // extends KeyValueRepository<T, ID> { // }
import org.springframework.data.hazelcast.repository.HazelcastRepository; import org.springframework.data.repository.NoRepositoryBean; import java.io.Serializable;
/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 test.utils.repository.custom; /** * <P>Define a generic repository bean for extension by other interfaces. * Mark with {@code @NoRepositoryBean} so Spring doesn't try to create one * of these at runtime. * </P> * * @author Neil Stevenson */ @NoRepositoryBean public interface MyTitleRepository<T extends Serializable, ID extends Serializable>
// Path: src/main/java/org/springframework/data/hazelcast/repository/HazelcastRepository.java // @NoRepositoryBean // public interface HazelcastRepository<T extends Serializable, ID extends Serializable> // extends KeyValueRepository<T, ID> { // } // Path: src/test/java/test/utils/repository/custom/MyTitleRepository.java import org.springframework.data.hazelcast.repository.HazelcastRepository; import org.springframework.data.repository.NoRepositoryBean; import java.io.Serializable; /* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 test.utils.repository.custom; /** * <P>Define a generic repository bean for extension by other interfaces. * Mark with {@code @NoRepositoryBean} so Spring doesn't try to create one * of these at runtime. * </P> * * @author Neil Stevenson */ @NoRepositoryBean public interface MyTitleRepository<T extends Serializable, ID extends Serializable>
extends HazelcastRepository<T, ID> {
hazelcast/spring-data-hazelcast
src/test/java/org/springframework/data/hazelcast/repository/support/HazelcastEntityInformationTest.java
// Path: src/test/java/org/springframework/data/hazelcast/HazelcastUtils.java // public class HazelcastUtils { // // static Config hazelcastConfig() { // // Config hazelcastConfig = new Config(); // hazelcastConfig.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); // hazelcastConfig.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false); // hazelcastConfig.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false); // // return hazelcastConfig; // } // // public static HazelcastKeyValueAdapter preconfiguredHazelcastKeyValueAdapter() { // HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(hazelcastConfig()); // HazelcastKeyValueAdapter hazelcastKeyValueAdapter = new HazelcastKeyValueAdapter(hazelcastInstance); // return hazelcastKeyValueAdapter; // } // // } // // Path: src/test/java/test/utils/domain/NoIdEntity.java // @KeySpace // public class NoIdEntity // implements Serializable { // private static final long serialVersionUID = 1L; // // private String name; // }
import com.hazelcast.core.Hazelcast; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.springframework.data.hazelcast.HazelcastUtils; import org.springframework.data.keyvalue.core.KeyValueOperations; import org.springframework.data.keyvalue.core.KeyValueTemplate; import org.springframework.data.mapping.MappingException; import org.springframework.data.mapping.PersistentEntity; import test.utils.domain.NoIdEntity;
/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast.repository.support; public class HazelcastEntityInformationTest { private KeyValueOperations operations; @Before public void setUp() {
// Path: src/test/java/org/springframework/data/hazelcast/HazelcastUtils.java // public class HazelcastUtils { // // static Config hazelcastConfig() { // // Config hazelcastConfig = new Config(); // hazelcastConfig.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); // hazelcastConfig.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false); // hazelcastConfig.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false); // // return hazelcastConfig; // } // // public static HazelcastKeyValueAdapter preconfiguredHazelcastKeyValueAdapter() { // HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(hazelcastConfig()); // HazelcastKeyValueAdapter hazelcastKeyValueAdapter = new HazelcastKeyValueAdapter(hazelcastInstance); // return hazelcastKeyValueAdapter; // } // // } // // Path: src/test/java/test/utils/domain/NoIdEntity.java // @KeySpace // public class NoIdEntity // implements Serializable { // private static final long serialVersionUID = 1L; // // private String name; // } // Path: src/test/java/org/springframework/data/hazelcast/repository/support/HazelcastEntityInformationTest.java import com.hazelcast.core.Hazelcast; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.springframework.data.hazelcast.HazelcastUtils; import org.springframework.data.keyvalue.core.KeyValueOperations; import org.springframework.data.keyvalue.core.KeyValueTemplate; import org.springframework.data.mapping.MappingException; import org.springframework.data.mapping.PersistentEntity; import test.utils.domain.NoIdEntity; /* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast.repository.support; public class HazelcastEntityInformationTest { private KeyValueOperations operations; @Before public void setUp() {
this.operations = new KeyValueTemplate(HazelcastUtils.preconfiguredHazelcastKeyValueAdapter());
hazelcast/spring-data-hazelcast
src/test/java/org/springframework/data/hazelcast/repository/support/HazelcastEntityInformationTest.java
// Path: src/test/java/org/springframework/data/hazelcast/HazelcastUtils.java // public class HazelcastUtils { // // static Config hazelcastConfig() { // // Config hazelcastConfig = new Config(); // hazelcastConfig.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); // hazelcastConfig.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false); // hazelcastConfig.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false); // // return hazelcastConfig; // } // // public static HazelcastKeyValueAdapter preconfiguredHazelcastKeyValueAdapter() { // HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(hazelcastConfig()); // HazelcastKeyValueAdapter hazelcastKeyValueAdapter = new HazelcastKeyValueAdapter(hazelcastInstance); // return hazelcastKeyValueAdapter; // } // // } // // Path: src/test/java/test/utils/domain/NoIdEntity.java // @KeySpace // public class NoIdEntity // implements Serializable { // private static final long serialVersionUID = 1L; // // private String name; // }
import com.hazelcast.core.Hazelcast; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.springframework.data.hazelcast.HazelcastUtils; import org.springframework.data.keyvalue.core.KeyValueOperations; import org.springframework.data.keyvalue.core.KeyValueTemplate; import org.springframework.data.mapping.MappingException; import org.springframework.data.mapping.PersistentEntity; import test.utils.domain.NoIdEntity;
/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast.repository.support; public class HazelcastEntityInformationTest { private KeyValueOperations operations; @Before public void setUp() { this.operations = new KeyValueTemplate(HazelcastUtils.preconfiguredHazelcastKeyValueAdapter()); } @Test(expected = MappingException.class) public void throwsMappingExceptionWhenNoIdPropertyPresent() {
// Path: src/test/java/org/springframework/data/hazelcast/HazelcastUtils.java // public class HazelcastUtils { // // static Config hazelcastConfig() { // // Config hazelcastConfig = new Config(); // hazelcastConfig.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); // hazelcastConfig.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false); // hazelcastConfig.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false); // // return hazelcastConfig; // } // // public static HazelcastKeyValueAdapter preconfiguredHazelcastKeyValueAdapter() { // HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(hazelcastConfig()); // HazelcastKeyValueAdapter hazelcastKeyValueAdapter = new HazelcastKeyValueAdapter(hazelcastInstance); // return hazelcastKeyValueAdapter; // } // // } // // Path: src/test/java/test/utils/domain/NoIdEntity.java // @KeySpace // public class NoIdEntity // implements Serializable { // private static final long serialVersionUID = 1L; // // private String name; // } // Path: src/test/java/org/springframework/data/hazelcast/repository/support/HazelcastEntityInformationTest.java import com.hazelcast.core.Hazelcast; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.springframework.data.hazelcast.HazelcastUtils; import org.springframework.data.keyvalue.core.KeyValueOperations; import org.springframework.data.keyvalue.core.KeyValueTemplate; import org.springframework.data.mapping.MappingException; import org.springframework.data.mapping.PersistentEntity; import test.utils.domain.NoIdEntity; /* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast.repository.support; public class HazelcastEntityInformationTest { private KeyValueOperations operations; @Before public void setUp() { this.operations = new KeyValueTemplate(HazelcastUtils.preconfiguredHazelcastKeyValueAdapter()); } @Test(expected = MappingException.class) public void throwsMappingExceptionWhenNoIdPropertyPresent() {
PersistentEntity<?, ?> persistentEntity = operations.getMappingContext().getPersistentEntity(NoIdEntity.class);
hazelcast/spring-data-hazelcast
src/test/java/org/springframework/data/hazelcast/repository/KeyValueIT.java
// Path: src/test/java/test/utils/domain/Person.java // @KeySpace(TestConstants.PERSON_MAP_NAME) // public class Person // implements Comparable<Person>, Serializable { // // private static final long serialVersionUID = 1L; // // @Id // private String id; // private String firstname; // private String lastname; // private boolean isChild = false; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getFirstname() { // return firstname; // } // // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // public String getLastname() { // return lastname; // } // // public void setLastname(String lastname) { // this.lastname = lastname; // } // // public boolean isChild() { // return isChild; // } // // public void setChild(boolean child) { // isChild = child; // } // // // Sort by lastname then firstname // @Override // public int compareTo(Person that) { // int lastnameCompare = this.lastname.compareTo(that.getLastname()); // return (lastnameCompare != 0 ? lastnameCompare : this.firstname.compareTo(that.getFirstname())); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Person person = (Person) o; // return isChild == person.isChild && Objects.equals(id, person.id) && Objects.equals(firstname, person.firstname) // && Objects.equals(lastname, person.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(id, firstname, lastname, isChild); // } // // @Override // public String toString() { // return "Person{" + "id='" + id + '\'' + ", firstname='" + firstname + '\'' + ", lastname='" + lastname + '\'' // + ", isChild=" + isChild + '}'; // } // }
import org.junit.Test; import org.springframework.data.keyvalue.repository.KeyValueRepository; import org.springframework.data.repository.PagingAndSortingRepository; import test.utils.domain.Person; import javax.annotation.Resource;
/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast.repository; /** * <p> * Downcast a {@link HazelcastRepository} into a {@link KeyValueRepository} to test any Key-Value additions to * {@link PagingAndSortingRepository}. At the moment, there are none so this is empty. * </P> * * @author Neil Stevenson */ public class KeyValueIT { // PersonRepository is really a HazelcastRepository @Resource
// Path: src/test/java/test/utils/domain/Person.java // @KeySpace(TestConstants.PERSON_MAP_NAME) // public class Person // implements Comparable<Person>, Serializable { // // private static final long serialVersionUID = 1L; // // @Id // private String id; // private String firstname; // private String lastname; // private boolean isChild = false; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getFirstname() { // return firstname; // } // // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // public String getLastname() { // return lastname; // } // // public void setLastname(String lastname) { // this.lastname = lastname; // } // // public boolean isChild() { // return isChild; // } // // public void setChild(boolean child) { // isChild = child; // } // // // Sort by lastname then firstname // @Override // public int compareTo(Person that) { // int lastnameCompare = this.lastname.compareTo(that.getLastname()); // return (lastnameCompare != 0 ? lastnameCompare : this.firstname.compareTo(that.getFirstname())); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Person person = (Person) o; // return isChild == person.isChild && Objects.equals(id, person.id) && Objects.equals(firstname, person.firstname) // && Objects.equals(lastname, person.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(id, firstname, lastname, isChild); // } // // @Override // public String toString() { // return "Person{" + "id='" + id + '\'' + ", firstname='" + firstname + '\'' + ", lastname='" + lastname + '\'' // + ", isChild=" + isChild + '}'; // } // } // Path: src/test/java/org/springframework/data/hazelcast/repository/KeyValueIT.java import org.junit.Test; import org.springframework.data.keyvalue.repository.KeyValueRepository; import org.springframework.data.repository.PagingAndSortingRepository; import test.utils.domain.Person; import javax.annotation.Resource; /* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast.repository; /** * <p> * Downcast a {@link HazelcastRepository} into a {@link KeyValueRepository} to test any Key-Value additions to * {@link PagingAndSortingRepository}. At the moment, there are none so this is empty. * </P> * * @author Neil Stevenson */ public class KeyValueIT { // PersonRepository is really a HazelcastRepository @Resource
private KeyValueRepository<Person, String> personRepository;
hazelcast/spring-data-hazelcast
src/test/java/org/springframework/data/hazelcast/topology/ClientServerIT.java
// Path: src/test/java/test/utils/TestConstants.java // public class TestConstants { // // public static final String CLIENT_INSTANCE_NAME = "hazelcast-instance-client"; // public static final String SERVER_INSTANCE_NAME = "hazelcast-instance-server"; // // public static final String SPRING_TEST_PROFILE_CLIENT_SERVER = "client-server"; // public static final String SPRING_TEST_PROFILE_CLUSTER = "cluster"; // public static final String SPRING_TEST_PROFILE_SINGLETON = "singleton"; // // public static final String MAKEUP_MAP_NAME = "Make-up"; // public static final String MOVIE_MAP_NAME = "Movie"; // public static final String PERSON_MAP_NAME = "Actors"; // public static final String SONG_MAP_NAME = Song.class.getCanonicalName(); // public static final String CITY_MAP_NAME = "Cities"; // // public static final String[] OSCAR_MAP_NAMES = {MAKEUP_MAP_NAME, MOVIE_MAP_NAME, PERSON_MAP_NAME, SONG_MAP_NAME, CITY_MAP_NAME}; // } // // Path: src/test/java/test/utils/domain/Person.java // @KeySpace(TestConstants.PERSON_MAP_NAME) // public class Person // implements Comparable<Person>, Serializable { // // private static final long serialVersionUID = 1L; // // @Id // private String id; // private String firstname; // private String lastname; // private boolean isChild = false; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getFirstname() { // return firstname; // } // // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // public String getLastname() { // return lastname; // } // // public void setLastname(String lastname) { // this.lastname = lastname; // } // // public boolean isChild() { // return isChild; // } // // public void setChild(boolean child) { // isChild = child; // } // // // Sort by lastname then firstname // @Override // public int compareTo(Person that) { // int lastnameCompare = this.lastname.compareTo(that.getLastname()); // return (lastnameCompare != 0 ? lastnameCompare : this.firstname.compareTo(that.getFirstname())); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Person person = (Person) o; // return isChild == person.isChild && Objects.equals(id, person.id) && Objects.equals(firstname, person.firstname) // && Objects.equals(lastname, person.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(id, firstname, lastname, isChild); // } // // @Override // public String toString() { // return "Person{" + "id='" + id + '\'' + ", firstname='" + firstname + '\'' + ", lastname='" + lastname + '\'' // + ", isChild=" + isChild + '}'; // } // }
import com.hazelcast.query.Predicate; import com.hazelcast.query.Predicates; import org.junit.Test; import org.springframework.test.context.ActiveProfiles; import test.utils.TestConstants; import test.utils.domain.Person; import java.util.Set; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat;
/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast.topology; /** * <p> * Run the {@link AbstractTopologyIT} tests with the client-server profile. * </P> * <p> * Spring Data Hazelcast uses the client, so the tests examine the server content to confirm client operations are sent * there. * </P> * * @author Neil Stevenson */ @ActiveProfiles(TestConstants.SPRING_TEST_PROFILE_CLIENT_SERVER) public class ClientServerIT extends AbstractTopologyIT { /* Test data loaded into the client should exist on the * server. */ @Test public void notJavaDuke() { String FIRST_NAME_IS_JOHN = "John"; String LAST_NAME_IS_WAYNE = "Wayne"; String NINETEEN_SIXTY_NINE = "1969"; Predicate<?, ?> predicate = Predicates .and(Predicates.equal("firstname", FIRST_NAME_IS_JOHN), Predicates.equal("lastname", LAST_NAME_IS_WAYNE)); // Force operation to server's content, not remote
// Path: src/test/java/test/utils/TestConstants.java // public class TestConstants { // // public static final String CLIENT_INSTANCE_NAME = "hazelcast-instance-client"; // public static final String SERVER_INSTANCE_NAME = "hazelcast-instance-server"; // // public static final String SPRING_TEST_PROFILE_CLIENT_SERVER = "client-server"; // public static final String SPRING_TEST_PROFILE_CLUSTER = "cluster"; // public static final String SPRING_TEST_PROFILE_SINGLETON = "singleton"; // // public static final String MAKEUP_MAP_NAME = "Make-up"; // public static final String MOVIE_MAP_NAME = "Movie"; // public static final String PERSON_MAP_NAME = "Actors"; // public static final String SONG_MAP_NAME = Song.class.getCanonicalName(); // public static final String CITY_MAP_NAME = "Cities"; // // public static final String[] OSCAR_MAP_NAMES = {MAKEUP_MAP_NAME, MOVIE_MAP_NAME, PERSON_MAP_NAME, SONG_MAP_NAME, CITY_MAP_NAME}; // } // // Path: src/test/java/test/utils/domain/Person.java // @KeySpace(TestConstants.PERSON_MAP_NAME) // public class Person // implements Comparable<Person>, Serializable { // // private static final long serialVersionUID = 1L; // // @Id // private String id; // private String firstname; // private String lastname; // private boolean isChild = false; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getFirstname() { // return firstname; // } // // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // public String getLastname() { // return lastname; // } // // public void setLastname(String lastname) { // this.lastname = lastname; // } // // public boolean isChild() { // return isChild; // } // // public void setChild(boolean child) { // isChild = child; // } // // // Sort by lastname then firstname // @Override // public int compareTo(Person that) { // int lastnameCompare = this.lastname.compareTo(that.getLastname()); // return (lastnameCompare != 0 ? lastnameCompare : this.firstname.compareTo(that.getFirstname())); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Person person = (Person) o; // return isChild == person.isChild && Objects.equals(id, person.id) && Objects.equals(firstname, person.firstname) // && Objects.equals(lastname, person.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(id, firstname, lastname, isChild); // } // // @Override // public String toString() { // return "Person{" + "id='" + id + '\'' + ", firstname='" + firstname + '\'' + ", lastname='" + lastname + '\'' // + ", isChild=" + isChild + '}'; // } // } // Path: src/test/java/org/springframework/data/hazelcast/topology/ClientServerIT.java import com.hazelcast.query.Predicate; import com.hazelcast.query.Predicates; import org.junit.Test; import org.springframework.test.context.ActiveProfiles; import test.utils.TestConstants; import test.utils.domain.Person; import java.util.Set; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; /* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast.topology; /** * <p> * Run the {@link AbstractTopologyIT} tests with the client-server profile. * </P> * <p> * Spring Data Hazelcast uses the client, so the tests examine the server content to confirm client operations are sent * there. * </P> * * @author Neil Stevenson */ @ActiveProfiles(TestConstants.SPRING_TEST_PROFILE_CLIENT_SERVER) public class ClientServerIT extends AbstractTopologyIT { /* Test data loaded into the client should exist on the * server. */ @Test public void notJavaDuke() { String FIRST_NAME_IS_JOHN = "John"; String LAST_NAME_IS_WAYNE = "Wayne"; String NINETEEN_SIXTY_NINE = "1969"; Predicate<?, ?> predicate = Predicates .and(Predicates.equal("firstname", FIRST_NAME_IS_JOHN), Predicates.equal("lastname", LAST_NAME_IS_WAYNE)); // Force operation to server's content, not remote
Set<String> localKeySet = super.server_personMap.localKeySet((Predicate<String, Person>) predicate);
hazelcast/spring-data-hazelcast
src/test/java/test/utils/TestConstants.java
// Path: src/test/java/test/utils/domain/Song.java // @KeySpace // public class Song // extends MyTitle { // private static final long serialVersionUID = 1L; // // @Override // public String toString() { // return "Song [id=" + super.getId() + ", title=" + super.getTitle() + "]"; // } // // }
import test.utils.domain.Song;
/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 test.utils; /** * @author Neil Stevenson */ public class TestConstants { public static final String CLIENT_INSTANCE_NAME = "hazelcast-instance-client"; public static final String SERVER_INSTANCE_NAME = "hazelcast-instance-server"; public static final String SPRING_TEST_PROFILE_CLIENT_SERVER = "client-server"; public static final String SPRING_TEST_PROFILE_CLUSTER = "cluster"; public static final String SPRING_TEST_PROFILE_SINGLETON = "singleton"; public static final String MAKEUP_MAP_NAME = "Make-up"; public static final String MOVIE_MAP_NAME = "Movie"; public static final String PERSON_MAP_NAME = "Actors";
// Path: src/test/java/test/utils/domain/Song.java // @KeySpace // public class Song // extends MyTitle { // private static final long serialVersionUID = 1L; // // @Override // public String toString() { // return "Song [id=" + super.getId() + ", title=" + super.getTitle() + "]"; // } // // } // Path: src/test/java/test/utils/TestConstants.java import test.utils.domain.Song; /* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 test.utils; /** * @author Neil Stevenson */ public class TestConstants { public static final String CLIENT_INSTANCE_NAME = "hazelcast-instance-client"; public static final String SERVER_INSTANCE_NAME = "hazelcast-instance-server"; public static final String SPRING_TEST_PROFILE_CLIENT_SERVER = "client-server"; public static final String SPRING_TEST_PROFILE_CLUSTER = "cluster"; public static final String SPRING_TEST_PROFILE_SINGLETON = "singleton"; public static final String MAKEUP_MAP_NAME = "Make-up"; public static final String MOVIE_MAP_NAME = "Movie"; public static final String PERSON_MAP_NAME = "Actors";
public static final String SONG_MAP_NAME = Song.class.getCanonicalName();
hazelcast/spring-data-hazelcast
src/main/java/org/springframework/data/hazelcast/repository/support/SimpleHazelcastRepository.java
// Path: src/main/java/org/springframework/data/hazelcast/repository/HazelcastRepository.java // @NoRepositoryBean // public interface HazelcastRepository<T extends Serializable, ID extends Serializable> // extends KeyValueRepository<T, ID> { // }
import org.springframework.data.hazelcast.repository.HazelcastRepository; import org.springframework.data.keyvalue.core.KeyValueOperations; import org.springframework.data.keyvalue.repository.support.SimpleKeyValueRepository; import org.springframework.data.repository.core.EntityInformation; import java.io.Serializable;
/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast.repository.support; /** * <P>A concrete implementation to instantiate directly rather than allow * Spring to generate. * </P> * * @param <T> The domain object * @param <ID> The key of the domain object * @author Neil Stevenson */ public class SimpleHazelcastRepository<T extends Serializable, ID extends Serializable> extends SimpleKeyValueRepository<T, ID>
// Path: src/main/java/org/springframework/data/hazelcast/repository/HazelcastRepository.java // @NoRepositoryBean // public interface HazelcastRepository<T extends Serializable, ID extends Serializable> // extends KeyValueRepository<T, ID> { // } // Path: src/main/java/org/springframework/data/hazelcast/repository/support/SimpleHazelcastRepository.java import org.springframework.data.hazelcast.repository.HazelcastRepository; import org.springframework.data.keyvalue.core.KeyValueOperations; import org.springframework.data.keyvalue.repository.support.SimpleKeyValueRepository; import org.springframework.data.repository.core.EntityInformation; import java.io.Serializable; /* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 org.springframework.data.hazelcast.repository.support; /** * <P>A concrete implementation to instantiate directly rather than allow * Spring to generate. * </P> * * @param <T> The domain object * @param <ID> The key of the domain object * @author Neil Stevenson */ public class SimpleHazelcastRepository<T extends Serializable, ID extends Serializable> extends SimpleKeyValueRepository<T, ID>
implements HazelcastRepository<T, ID> {
hazelcast/spring-data-hazelcast
src/test/java/test/utils/InstanceHelper.java
// Path: src/test/java/test/utils/repository/custom/MyTitleRepositoryFactoryBean.java // public class MyTitleRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> // extends HazelcastRepositoryFactoryBean<T, S, ID> { // @Resource // private HazelcastInstance hazelcastInstance; // // /* // * Creates a new {@link MyTitleRepositoryFactoryBean} for the given repository interface. // */ // public MyTitleRepositoryFactoryBean(Class<? extends T> repositoryInterface) { // super(repositoryInterface); // } // // /* Create a specialised repository factory. // * // * (non-Javadoc) // * @see org.springframework.data.hazelcast.repository.support.HazelcastRepositoryFactoryBean#createRepositoryFactory(org // * .springframework.data.keyvalue.core.KeyValueOperations, java.lang.Class, java.lang.Class) // */ // @Override // protected MyTitleRepositoryFactory createRepositoryFactory(KeyValueOperations operations, // Class<? extends AbstractQueryCreator<?, ?>> queryCreator, // Class<? extends RepositoryQuery> repositoryQueryType) { // // return new MyTitleRepositoryFactory(operations, queryCreator, hazelcastInstance); // } // // }
import javax.annotation.PreDestroy; import javax.annotation.Resource; import java.util.Arrays; import java.util.Set; import com.hazelcast.client.HazelcastClient; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.config.Config; import com.hazelcast.config.TcpIpConfig; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.data.hazelcast.repository.config.EnableHazelcastRepositories; import test.utils.repository.custom.MyTitleRepositoryFactoryBean;
* </P> */ @PreDestroy public void preDestroy() { boolean testInstanceWasRunning = false; Set<HazelcastInstance> hazelcastInstances = Hazelcast.getAllHazelcastInstances(); if (hazelcastInstances.size() != 0) { for (HazelcastInstance hazelcastInstance : hazelcastInstances) { if (TestConstants.CLIENT_INSTANCE_NAME.equals(hazelcastInstance.getName())) { testInstanceWasRunning = true; } LOG.debug("Closing '{}'", hazelcastInstance); hazelcastInstance.shutdown(); } } ; if (testInstanceWasRunning) { LOG.error("'{}' was still running", TestConstants.CLIENT_INSTANCE_NAME); } else { LOG.debug("'{}' already closed by Spring", TestConstants.CLIENT_INSTANCE_NAME); } } /** * <P>The {@code @EnableHazelcastRepositories} annotation is not repeatable, * so use an inner class to scan a second package. * </P> */
// Path: src/test/java/test/utils/repository/custom/MyTitleRepositoryFactoryBean.java // public class MyTitleRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> // extends HazelcastRepositoryFactoryBean<T, S, ID> { // @Resource // private HazelcastInstance hazelcastInstance; // // /* // * Creates a new {@link MyTitleRepositoryFactoryBean} for the given repository interface. // */ // public MyTitleRepositoryFactoryBean(Class<? extends T> repositoryInterface) { // super(repositoryInterface); // } // // /* Create a specialised repository factory. // * // * (non-Javadoc) // * @see org.springframework.data.hazelcast.repository.support.HazelcastRepositoryFactoryBean#createRepositoryFactory(org // * .springframework.data.keyvalue.core.KeyValueOperations, java.lang.Class, java.lang.Class) // */ // @Override // protected MyTitleRepositoryFactory createRepositoryFactory(KeyValueOperations operations, // Class<? extends AbstractQueryCreator<?, ?>> queryCreator, // Class<? extends RepositoryQuery> repositoryQueryType) { // // return new MyTitleRepositoryFactory(operations, queryCreator, hazelcastInstance); // } // // } // Path: src/test/java/test/utils/InstanceHelper.java import javax.annotation.PreDestroy; import javax.annotation.Resource; import java.util.Arrays; import java.util.Set; import com.hazelcast.client.HazelcastClient; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.config.Config; import com.hazelcast.config.TcpIpConfig; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.data.hazelcast.repository.config.EnableHazelcastRepositories; import test.utils.repository.custom.MyTitleRepositoryFactoryBean; * </P> */ @PreDestroy public void preDestroy() { boolean testInstanceWasRunning = false; Set<HazelcastInstance> hazelcastInstances = Hazelcast.getAllHazelcastInstances(); if (hazelcastInstances.size() != 0) { for (HazelcastInstance hazelcastInstance : hazelcastInstances) { if (TestConstants.CLIENT_INSTANCE_NAME.equals(hazelcastInstance.getName())) { testInstanceWasRunning = true; } LOG.debug("Closing '{}'", hazelcastInstance); hazelcastInstance.shutdown(); } } ; if (testInstanceWasRunning) { LOG.error("'{}' was still running", TestConstants.CLIENT_INSTANCE_NAME); } else { LOG.debug("'{}' already closed by Spring", TestConstants.CLIENT_INSTANCE_NAME); } } /** * <P>The {@code @EnableHazelcastRepositories} annotation is not repeatable, * so use an inner class to scan a second package. * </P> */
@EnableHazelcastRepositories(basePackages = "test.utils.repository.custom", repositoryFactoryBeanClass = MyTitleRepositoryFactoryBean.class, hazelcastInstanceRef = TestConstants.CLIENT_INSTANCE_NAME)
hazelcast/spring-data-hazelcast
src/test/java/test/utils/repository/custom/MyTitleRepositoryImpl.java
// Path: src/main/java/org/springframework/data/hazelcast/repository/support/SimpleHazelcastRepository.java // public class SimpleHazelcastRepository<T extends Serializable, ID extends Serializable> // extends SimpleKeyValueRepository<T, ID> // implements HazelcastRepository<T, ID> { // // public SimpleHazelcastRepository(EntityInformation<T, ID> metadata, KeyValueOperations operations) { // super(metadata, operations); // } // // } // // Path: src/test/java/test/utils/domain/MyTitle.java // public abstract class MyTitle // implements Comparable<MyTitle>, Serializable { // private static final long serialVersionUID = 1L; // // @Id // private String id; // private String title; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // result = prime * result + ((title == null) ? 0 : title.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // MyTitle other = (MyTitle) obj; // if (id == null) { // if (other.id != null) { // return false; // } // } else if (!id.equals(other.id)) { // return false; // } // if (title == null) { // if (other.title != null) { // return false; // } // } else if (!title.equals(other.title)) { // return false; // } // return true; // } // // // Sort by title only // @Override // public int compareTo(MyTitle that) { // return this.title.compareTo(that.getTitle()); // } // // }
import org.springframework.data.hazelcast.repository.support.SimpleHazelcastRepository; import org.springframework.data.keyvalue.core.KeyValueOperations; import org.springframework.data.repository.core.EntityInformation; import test.utils.domain.MyTitle; import java.io.Serializable;
/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 test.utils.repository.custom; /** * <P>Implement a custom repository for {@link MyTitleRepository}, but * inherit most of the behaviour from {@link SimpleHazelcastRepository}. * </P> * * @param <T> The domain object * @param <ID> The key of the domain object * @author Neil Stevenson */ public class MyTitleRepositoryImpl<T extends Serializable, ID extends Serializable> extends SimpleHazelcastRepository<T, ID> implements MyTitleRepository<T, ID> { public MyTitleRepositoryImpl(EntityInformation<T, ID> metadata, KeyValueOperations keyValueOperations) { super(metadata, keyValueOperations); } /** * <p> * Count the words in a particular title. * </P> * * @param Key to lookup * @return Tokens in string, -1 if not found */ public int wordsInTitle(String year) {
// Path: src/main/java/org/springframework/data/hazelcast/repository/support/SimpleHazelcastRepository.java // public class SimpleHazelcastRepository<T extends Serializable, ID extends Serializable> // extends SimpleKeyValueRepository<T, ID> // implements HazelcastRepository<T, ID> { // // public SimpleHazelcastRepository(EntityInformation<T, ID> metadata, KeyValueOperations operations) { // super(metadata, operations); // } // // } // // Path: src/test/java/test/utils/domain/MyTitle.java // public abstract class MyTitle // implements Comparable<MyTitle>, Serializable { // private static final long serialVersionUID = 1L; // // @Id // private String id; // private String title; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // result = prime * result + ((title == null) ? 0 : title.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // MyTitle other = (MyTitle) obj; // if (id == null) { // if (other.id != null) { // return false; // } // } else if (!id.equals(other.id)) { // return false; // } // if (title == null) { // if (other.title != null) { // return false; // } // } else if (!title.equals(other.title)) { // return false; // } // return true; // } // // // Sort by title only // @Override // public int compareTo(MyTitle that) { // return this.title.compareTo(that.getTitle()); // } // // } // Path: src/test/java/test/utils/repository/custom/MyTitleRepositoryImpl.java import org.springframework.data.hazelcast.repository.support.SimpleHazelcastRepository; import org.springframework.data.keyvalue.core.KeyValueOperations; import org.springframework.data.repository.core.EntityInformation; import test.utils.domain.MyTitle; import java.io.Serializable; /* * Copyright (c) 2008-2018, Hazelcast, Inc. 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 test.utils.repository.custom; /** * <P>Implement a custom repository for {@link MyTitleRepository}, but * inherit most of the behaviour from {@link SimpleHazelcastRepository}. * </P> * * @param <T> The domain object * @param <ID> The key of the domain object * @author Neil Stevenson */ public class MyTitleRepositoryImpl<T extends Serializable, ID extends Serializable> extends SimpleHazelcastRepository<T, ID> implements MyTitleRepository<T, ID> { public MyTitleRepositoryImpl(EntityInformation<T, ID> metadata, KeyValueOperations keyValueOperations) { super(metadata, keyValueOperations); } /** * <p> * Count the words in a particular title. * </P> * * @param Key to lookup * @return Tokens in string, -1 if not found */ public int wordsInTitle(String year) {
@SuppressWarnings("unchecked") MyTitle myTitle = (MyTitle) super.findById((ID) year).orElse(null);
grahamedgecombe/android-ssl
analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/util/PointsToUtils.java
// Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/VulnerabilityState.java // public enum VulnerabilityState { // VULNERABLE, // SAFE, // UNKNOWN // } // // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/tag/VulnerabilityTag.java // public abstract class VulnerabilityTag implements Tag { // private final String name; // private final VulnerabilityState state; // // public VulnerabilityTag(String name, VulnerabilityState state) { // this.name = name; // this.state = state; // } // // @Override // public String getName() { // return name; // } // // public VulnerabilityState getState() { // return state; // } // // @Override // public byte[] getValue() { // return new byte[] { // (byte) state.ordinal() // }; // } // }
import soot.*; import uk.ac.cam.gpe21.droidssl.analysis.VulnerabilityState; import uk.ac.cam.gpe21.droidssl.analysis.tag.VulnerabilityTag;
/* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.analysis.util; public final class PointsToUtils { public static boolean anyTypeVulnerable(PointsToSet set, final String tagName) { final boolean[] box = new boolean[1]; // TODO this is hacky for (Type type : set.possibleTypes()) { type.apply(new TypeSwitch() { @Override public void caseRefType(RefType type) {
// Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/VulnerabilityState.java // public enum VulnerabilityState { // VULNERABLE, // SAFE, // UNKNOWN // } // // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/tag/VulnerabilityTag.java // public abstract class VulnerabilityTag implements Tag { // private final String name; // private final VulnerabilityState state; // // public VulnerabilityTag(String name, VulnerabilityState state) { // this.name = name; // this.state = state; // } // // @Override // public String getName() { // return name; // } // // public VulnerabilityState getState() { // return state; // } // // @Override // public byte[] getValue() { // return new byte[] { // (byte) state.ordinal() // }; // } // } // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/util/PointsToUtils.java import soot.*; import uk.ac.cam.gpe21.droidssl.analysis.VulnerabilityState; import uk.ac.cam.gpe21.droidssl.analysis.tag.VulnerabilityTag; /* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.analysis.util; public final class PointsToUtils { public static boolean anyTypeVulnerable(PointsToSet set, final String tagName) { final boolean[] box = new boolean[1]; // TODO this is hacky for (Type type : set.possibleTypes()) { type.apply(new TypeSwitch() { @Override public void caseRefType(RefType type) {
VulnerabilityTag tag = (VulnerabilityTag) type.getSootClass().getTag(tagName);
grahamedgecombe/android-ssl
analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/util/PointsToUtils.java
// Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/VulnerabilityState.java // public enum VulnerabilityState { // VULNERABLE, // SAFE, // UNKNOWN // } // // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/tag/VulnerabilityTag.java // public abstract class VulnerabilityTag implements Tag { // private final String name; // private final VulnerabilityState state; // // public VulnerabilityTag(String name, VulnerabilityState state) { // this.name = name; // this.state = state; // } // // @Override // public String getName() { // return name; // } // // public VulnerabilityState getState() { // return state; // } // // @Override // public byte[] getValue() { // return new byte[] { // (byte) state.ordinal() // }; // } // }
import soot.*; import uk.ac.cam.gpe21.droidssl.analysis.VulnerabilityState; import uk.ac.cam.gpe21.droidssl.analysis.tag.VulnerabilityTag;
/* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.analysis.util; public final class PointsToUtils { public static boolean anyTypeVulnerable(PointsToSet set, final String tagName) { final boolean[] box = new boolean[1]; // TODO this is hacky for (Type type : set.possibleTypes()) { type.apply(new TypeSwitch() { @Override public void caseRefType(RefType type) { VulnerabilityTag tag = (VulnerabilityTag) type.getSootClass().getTag(tagName);
// Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/VulnerabilityState.java // public enum VulnerabilityState { // VULNERABLE, // SAFE, // UNKNOWN // } // // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/tag/VulnerabilityTag.java // public abstract class VulnerabilityTag implements Tag { // private final String name; // private final VulnerabilityState state; // // public VulnerabilityTag(String name, VulnerabilityState state) { // this.name = name; // this.state = state; // } // // @Override // public String getName() { // return name; // } // // public VulnerabilityState getState() { // return state; // } // // @Override // public byte[] getValue() { // return new byte[] { // (byte) state.ordinal() // }; // } // } // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/util/PointsToUtils.java import soot.*; import uk.ac.cam.gpe21.droidssl.analysis.VulnerabilityState; import uk.ac.cam.gpe21.droidssl.analysis.tag.VulnerabilityTag; /* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.analysis.util; public final class PointsToUtils { public static boolean anyTypeVulnerable(PointsToSet set, final String tagName) { final boolean[] box = new boolean[1]; // TODO this is hacky for (Type type : set.possibleTypes()) { type.apply(new TypeSwitch() { @Override public void caseRefType(RefType type) { VulnerabilityTag tag = (VulnerabilityTag) type.getSootClass().getTag(tagName);
if (tag != null && tag.getState() == VulnerabilityState.VULNERABLE)
grahamedgecombe/android-ssl
mitm/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/IoCopyRunnable.java
// Path: mitm/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/ui/Session.java // public final class Session { // public enum State { // OPEN(Color.GREEN, "Open"), // CLOSED(Color.GRAY, "Closed"), // FAILED(Color.RED, "Failed"), // MAYBE_FAILED(Color.ORANGE, "Maybe Failed"); /* means connection closed without sending data */ // // private final Color color; // private final String description; // // private State(Color color, String description) { // this.color = color; // this.description = description; // } // // public Color getColor() { // return color; // } // // @Override // public String toString() { // return description; // } // } // // private final InetSocketAddress source, destination; // private State state = State.OPEN; // private Throwable failureReason; // private CertificateKey realKey, key; // private String cipherSuite; // private String protocol; // // public Session(InetSocketAddress source, InetSocketAddress destination) { // this.source = source; // this.destination = destination; // } // // public InetSocketAddress getSource() { // return source; // } // // public InetSocketAddress getDestination() { // return destination; // } // // public boolean isSsl() { // return key != null; // } // // public CertificateKey getRealKey() { // return realKey; // } // // public void setRealKey(CertificateKey realKey) { // this.realKey = realKey; // } // // public CertificateKey getKey() { // return key; // } // // public void setKey(CertificateKey key) { // this.key = key; // } // // public String getCipherSuite() { // return cipherSuite; // } // // public void setCipherSuite(String cipherSuite) { // this.cipherSuite = cipherSuite; // } // // public String getProtocol() { // return protocol; // } // // public void setProtocol(String protocol) { // this.protocol = protocol; // } // // public State getState() { // synchronized (this) { // return state; // } // } // // public void setState(State state) { // synchronized (this) { // /* // * Only allow open->closed or open->failed transitions (or the fact // * two threads run I/O can cause e.g. a failed to connection to // * transition to closed, which stops the GUI from displaying the // * exception). // */ // if (this.state != State.OPEN) // return; // // this.state = state; // } // } // // public Throwable getFailureReason() { // synchronized (this) { // return failureReason; // } // } // // public void setFailureReason(Throwable failureReason) { // synchronized (this) { // this.failureReason = failureReason; // } // } // // @Override // public String toString() { // return destination.getHostName() + ":" + destination.getPort(); // } // } // // Path: mitm/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/ui/UserInterface.java // public abstract class UserInterface { // public abstract void init(String title, String caPrefix, String hostnameFinder); // public abstract void onOpen(Session session); // public abstract void onData(Session session, boolean receive, byte[] buf, int len); // public abstract void onClose(Session session); // public abstract void onFailure(Session session, IOException reason); // }
import uk.ac.cam.gpe21.droidssl.mitm.ui.Session; import uk.ac.cam.gpe21.droidssl.mitm.ui.UserInterface; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
/* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.mitm; public final class IoCopyRunnable implements Runnable { private final Session session; private final boolean receive; private final InputStream in; private final OutputStream out;
// Path: mitm/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/ui/Session.java // public final class Session { // public enum State { // OPEN(Color.GREEN, "Open"), // CLOSED(Color.GRAY, "Closed"), // FAILED(Color.RED, "Failed"), // MAYBE_FAILED(Color.ORANGE, "Maybe Failed"); /* means connection closed without sending data */ // // private final Color color; // private final String description; // // private State(Color color, String description) { // this.color = color; // this.description = description; // } // // public Color getColor() { // return color; // } // // @Override // public String toString() { // return description; // } // } // // private final InetSocketAddress source, destination; // private State state = State.OPEN; // private Throwable failureReason; // private CertificateKey realKey, key; // private String cipherSuite; // private String protocol; // // public Session(InetSocketAddress source, InetSocketAddress destination) { // this.source = source; // this.destination = destination; // } // // public InetSocketAddress getSource() { // return source; // } // // public InetSocketAddress getDestination() { // return destination; // } // // public boolean isSsl() { // return key != null; // } // // public CertificateKey getRealKey() { // return realKey; // } // // public void setRealKey(CertificateKey realKey) { // this.realKey = realKey; // } // // public CertificateKey getKey() { // return key; // } // // public void setKey(CertificateKey key) { // this.key = key; // } // // public String getCipherSuite() { // return cipherSuite; // } // // public void setCipherSuite(String cipherSuite) { // this.cipherSuite = cipherSuite; // } // // public String getProtocol() { // return protocol; // } // // public void setProtocol(String protocol) { // this.protocol = protocol; // } // // public State getState() { // synchronized (this) { // return state; // } // } // // public void setState(State state) { // synchronized (this) { // /* // * Only allow open->closed or open->failed transitions (or the fact // * two threads run I/O can cause e.g. a failed to connection to // * transition to closed, which stops the GUI from displaying the // * exception). // */ // if (this.state != State.OPEN) // return; // // this.state = state; // } // } // // public Throwable getFailureReason() { // synchronized (this) { // return failureReason; // } // } // // public void setFailureReason(Throwable failureReason) { // synchronized (this) { // this.failureReason = failureReason; // } // } // // @Override // public String toString() { // return destination.getHostName() + ":" + destination.getPort(); // } // } // // Path: mitm/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/ui/UserInterface.java // public abstract class UserInterface { // public abstract void init(String title, String caPrefix, String hostnameFinder); // public abstract void onOpen(Session session); // public abstract void onData(Session session, boolean receive, byte[] buf, int len); // public abstract void onClose(Session session); // public abstract void onFailure(Session session, IOException reason); // } // Path: mitm/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/IoCopyRunnable.java import uk.ac.cam.gpe21.droidssl.mitm.ui.Session; import uk.ac.cam.gpe21.droidssl.mitm.ui.UserInterface; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.mitm; public final class IoCopyRunnable implements Runnable { private final Session session; private final boolean receive; private final InputStream in; private final OutputStream out;
private final UserInterface ui;
grahamedgecombe/android-ssl
analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/tag/HostnameVerifierTag.java
// Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/VulnerabilityState.java // public enum VulnerabilityState { // VULNERABLE, // SAFE, // UNKNOWN // }
import uk.ac.cam.gpe21.droidssl.analysis.VulnerabilityState;
/* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.analysis.tag; public final class HostnameVerifierTag extends VulnerabilityTag { public static final String NAME = "hostname_verifier";
// Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/VulnerabilityState.java // public enum VulnerabilityState { // VULNERABLE, // SAFE, // UNKNOWN // } // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/tag/HostnameVerifierTag.java import uk.ac.cam.gpe21.droidssl.analysis.VulnerabilityState; /* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.analysis.tag; public final class HostnameVerifierTag extends VulnerabilityTag { public static final String NAME = "hostname_verifier";
public HostnameVerifierTag(VulnerabilityState state) {
grahamedgecombe/android-ssl
analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/trans/InitTrustManagerAnalyser.java
// Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/Vulnerability.java // public final class Vulnerability { // private final SootClass clazz; // private final SootMethod method; // private final VulnerabilityType type; // private final VulnerabilityState state; // // public Vulnerability(SootClass clazz, VulnerabilityType type, VulnerabilityState state) { // this.clazz = clazz; // this.method = null; // this.type = type; // this.state = state; // } // // public Vulnerability(SootMethod method, VulnerabilityType type, VulnerabilityState state) { // this.clazz = method.getDeclaringClass(); // this.method = method; // this.type = type; // this.state = state; // } // // public SootClass getClazz() { // return clazz; // } // // public SootMethod getMethod() { // return method; // } // // public VulnerabilityType getType() { // return type; // } // // public VulnerabilityState getState() { // return state; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Vulnerability that = (Vulnerability) o; // // if (!clazz.equals(that.clazz)) return false; // if (method != null ? !method.equals(that.method) : that.method != null) return false; // if (state != that.state) return false; // if (type != that.type) return false; // // return true; // } // // @Override // public int hashCode() { // int result = clazz.hashCode(); // result = 31 * result + (method != null ? method.hashCode() : 0); // result = 31 * result + type.hashCode(); // result = 31 * result + state.hashCode(); // return result; // } // // @Override // public String toString() { // if (method == null) { // return clazz.getName() + "\t" + type + "\t" + state; // } else { // return clazz.getName() + "::" + method.getName() + "\t" + type + "\t" + state; // } // } // } // // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/VulnerabilityType.java // public enum VulnerabilityType { // PERMISSIVE_HOSTNAME_VERIFIER, // PERMISSIVE_TRUST_MANAGER, // INIT_HOSTNAME_VERIFIER, // INIT_TRUST_MANAGER, // HTTPS_CONNECTION_DEFAULT_HOSTNAME_VERIFIER, // HTTPS_CONNECTION_USES_HOSTNAME_VERIFIER, // SOCKET_USES_PERMISSIVE_TRUST_MANAGER // } // // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/tag/TrustManagerTag.java // public final class TrustManagerTag extends VulnerabilityTag { // public static final String NAME = "trust_manager"; // // public TrustManagerTag(VulnerabilityState state) { // super(NAME, state); // } // }
import soot.*; import soot.jimple.AbstractJimpleValueSwitch; import soot.jimple.NewExpr; import uk.ac.cam.gpe21.droidssl.analysis.Vulnerability; import uk.ac.cam.gpe21.droidssl.analysis.VulnerabilityType; import uk.ac.cam.gpe21.droidssl.analysis.tag.TrustManagerTag; import java.util.Set;
/* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.analysis.trans; public final class InitTrustManagerAnalyser extends IntraProceduralAnalyser { public InitTrustManagerAnalyser(Set<Vulnerability> vulnerabilities) { super(vulnerabilities); } @Override protected void analyse(SootClass clazz, final SootMethod method, Body body) { for (Unit unit : body.getUnits()) { for (ValueBox valueBox : unit.getUseBoxes()) { valueBox.getValue().apply(new AbstractJimpleValueSwitch() { @Override public void caseNewExpr(NewExpr value) { SootClass type = value.getBaseType().getSootClass();
// Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/Vulnerability.java // public final class Vulnerability { // private final SootClass clazz; // private final SootMethod method; // private final VulnerabilityType type; // private final VulnerabilityState state; // // public Vulnerability(SootClass clazz, VulnerabilityType type, VulnerabilityState state) { // this.clazz = clazz; // this.method = null; // this.type = type; // this.state = state; // } // // public Vulnerability(SootMethod method, VulnerabilityType type, VulnerabilityState state) { // this.clazz = method.getDeclaringClass(); // this.method = method; // this.type = type; // this.state = state; // } // // public SootClass getClazz() { // return clazz; // } // // public SootMethod getMethod() { // return method; // } // // public VulnerabilityType getType() { // return type; // } // // public VulnerabilityState getState() { // return state; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Vulnerability that = (Vulnerability) o; // // if (!clazz.equals(that.clazz)) return false; // if (method != null ? !method.equals(that.method) : that.method != null) return false; // if (state != that.state) return false; // if (type != that.type) return false; // // return true; // } // // @Override // public int hashCode() { // int result = clazz.hashCode(); // result = 31 * result + (method != null ? method.hashCode() : 0); // result = 31 * result + type.hashCode(); // result = 31 * result + state.hashCode(); // return result; // } // // @Override // public String toString() { // if (method == null) { // return clazz.getName() + "\t" + type + "\t" + state; // } else { // return clazz.getName() + "::" + method.getName() + "\t" + type + "\t" + state; // } // } // } // // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/VulnerabilityType.java // public enum VulnerabilityType { // PERMISSIVE_HOSTNAME_VERIFIER, // PERMISSIVE_TRUST_MANAGER, // INIT_HOSTNAME_VERIFIER, // INIT_TRUST_MANAGER, // HTTPS_CONNECTION_DEFAULT_HOSTNAME_VERIFIER, // HTTPS_CONNECTION_USES_HOSTNAME_VERIFIER, // SOCKET_USES_PERMISSIVE_TRUST_MANAGER // } // // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/tag/TrustManagerTag.java // public final class TrustManagerTag extends VulnerabilityTag { // public static final String NAME = "trust_manager"; // // public TrustManagerTag(VulnerabilityState state) { // super(NAME, state); // } // } // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/trans/InitTrustManagerAnalyser.java import soot.*; import soot.jimple.AbstractJimpleValueSwitch; import soot.jimple.NewExpr; import uk.ac.cam.gpe21.droidssl.analysis.Vulnerability; import uk.ac.cam.gpe21.droidssl.analysis.VulnerabilityType; import uk.ac.cam.gpe21.droidssl.analysis.tag.TrustManagerTag; import java.util.Set; /* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.analysis.trans; public final class InitTrustManagerAnalyser extends IntraProceduralAnalyser { public InitTrustManagerAnalyser(Set<Vulnerability> vulnerabilities) { super(vulnerabilities); } @Override protected void analyse(SootClass clazz, final SootMethod method, Body body) { for (Unit unit : body.getUnits()) { for (ValueBox valueBox : unit.getUseBoxes()) { valueBox.getValue().apply(new AbstractJimpleValueSwitch() { @Override public void caseNewExpr(NewExpr value) { SootClass type = value.getBaseType().getSootClass();
if (type.hasTag(TrustManagerTag.NAME)) {
grahamedgecombe/android-ssl
analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/trans/InitTrustManagerAnalyser.java
// Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/Vulnerability.java // public final class Vulnerability { // private final SootClass clazz; // private final SootMethod method; // private final VulnerabilityType type; // private final VulnerabilityState state; // // public Vulnerability(SootClass clazz, VulnerabilityType type, VulnerabilityState state) { // this.clazz = clazz; // this.method = null; // this.type = type; // this.state = state; // } // // public Vulnerability(SootMethod method, VulnerabilityType type, VulnerabilityState state) { // this.clazz = method.getDeclaringClass(); // this.method = method; // this.type = type; // this.state = state; // } // // public SootClass getClazz() { // return clazz; // } // // public SootMethod getMethod() { // return method; // } // // public VulnerabilityType getType() { // return type; // } // // public VulnerabilityState getState() { // return state; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Vulnerability that = (Vulnerability) o; // // if (!clazz.equals(that.clazz)) return false; // if (method != null ? !method.equals(that.method) : that.method != null) return false; // if (state != that.state) return false; // if (type != that.type) return false; // // return true; // } // // @Override // public int hashCode() { // int result = clazz.hashCode(); // result = 31 * result + (method != null ? method.hashCode() : 0); // result = 31 * result + type.hashCode(); // result = 31 * result + state.hashCode(); // return result; // } // // @Override // public String toString() { // if (method == null) { // return clazz.getName() + "\t" + type + "\t" + state; // } else { // return clazz.getName() + "::" + method.getName() + "\t" + type + "\t" + state; // } // } // } // // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/VulnerabilityType.java // public enum VulnerabilityType { // PERMISSIVE_HOSTNAME_VERIFIER, // PERMISSIVE_TRUST_MANAGER, // INIT_HOSTNAME_VERIFIER, // INIT_TRUST_MANAGER, // HTTPS_CONNECTION_DEFAULT_HOSTNAME_VERIFIER, // HTTPS_CONNECTION_USES_HOSTNAME_VERIFIER, // SOCKET_USES_PERMISSIVE_TRUST_MANAGER // } // // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/tag/TrustManagerTag.java // public final class TrustManagerTag extends VulnerabilityTag { // public static final String NAME = "trust_manager"; // // public TrustManagerTag(VulnerabilityState state) { // super(NAME, state); // } // }
import soot.*; import soot.jimple.AbstractJimpleValueSwitch; import soot.jimple.NewExpr; import uk.ac.cam.gpe21.droidssl.analysis.Vulnerability; import uk.ac.cam.gpe21.droidssl.analysis.VulnerabilityType; import uk.ac.cam.gpe21.droidssl.analysis.tag.TrustManagerTag; import java.util.Set;
/* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.analysis.trans; public final class InitTrustManagerAnalyser extends IntraProceduralAnalyser { public InitTrustManagerAnalyser(Set<Vulnerability> vulnerabilities) { super(vulnerabilities); } @Override protected void analyse(SootClass clazz, final SootMethod method, Body body) { for (Unit unit : body.getUnits()) { for (ValueBox valueBox : unit.getUseBoxes()) { valueBox.getValue().apply(new AbstractJimpleValueSwitch() { @Override public void caseNewExpr(NewExpr value) { SootClass type = value.getBaseType().getSootClass(); if (type.hasTag(TrustManagerTag.NAME)) { TrustManagerTag tag = (TrustManagerTag) type.getTag(TrustManagerTag.NAME);
// Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/Vulnerability.java // public final class Vulnerability { // private final SootClass clazz; // private final SootMethod method; // private final VulnerabilityType type; // private final VulnerabilityState state; // // public Vulnerability(SootClass clazz, VulnerabilityType type, VulnerabilityState state) { // this.clazz = clazz; // this.method = null; // this.type = type; // this.state = state; // } // // public Vulnerability(SootMethod method, VulnerabilityType type, VulnerabilityState state) { // this.clazz = method.getDeclaringClass(); // this.method = method; // this.type = type; // this.state = state; // } // // public SootClass getClazz() { // return clazz; // } // // public SootMethod getMethod() { // return method; // } // // public VulnerabilityType getType() { // return type; // } // // public VulnerabilityState getState() { // return state; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Vulnerability that = (Vulnerability) o; // // if (!clazz.equals(that.clazz)) return false; // if (method != null ? !method.equals(that.method) : that.method != null) return false; // if (state != that.state) return false; // if (type != that.type) return false; // // return true; // } // // @Override // public int hashCode() { // int result = clazz.hashCode(); // result = 31 * result + (method != null ? method.hashCode() : 0); // result = 31 * result + type.hashCode(); // result = 31 * result + state.hashCode(); // return result; // } // // @Override // public String toString() { // if (method == null) { // return clazz.getName() + "\t" + type + "\t" + state; // } else { // return clazz.getName() + "::" + method.getName() + "\t" + type + "\t" + state; // } // } // } // // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/VulnerabilityType.java // public enum VulnerabilityType { // PERMISSIVE_HOSTNAME_VERIFIER, // PERMISSIVE_TRUST_MANAGER, // INIT_HOSTNAME_VERIFIER, // INIT_TRUST_MANAGER, // HTTPS_CONNECTION_DEFAULT_HOSTNAME_VERIFIER, // HTTPS_CONNECTION_USES_HOSTNAME_VERIFIER, // SOCKET_USES_PERMISSIVE_TRUST_MANAGER // } // // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/tag/TrustManagerTag.java // public final class TrustManagerTag extends VulnerabilityTag { // public static final String NAME = "trust_manager"; // // public TrustManagerTag(VulnerabilityState state) { // super(NAME, state); // } // } // Path: analysis/src/main/java/uk/ac/cam/gpe21/droidssl/analysis/trans/InitTrustManagerAnalyser.java import soot.*; import soot.jimple.AbstractJimpleValueSwitch; import soot.jimple.NewExpr; import uk.ac.cam.gpe21.droidssl.analysis.Vulnerability; import uk.ac.cam.gpe21.droidssl.analysis.VulnerabilityType; import uk.ac.cam.gpe21.droidssl.analysis.tag.TrustManagerTag; import java.util.Set; /* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.analysis.trans; public final class InitTrustManagerAnalyser extends IntraProceduralAnalyser { public InitTrustManagerAnalyser(Set<Vulnerability> vulnerabilities) { super(vulnerabilities); } @Override protected void analyse(SootClass clazz, final SootMethod method, Body body) { for (Unit unit : body.getUnits()) { for (ValueBox valueBox : unit.getUseBoxes()) { valueBox.getValue().apply(new AbstractJimpleValueSwitch() { @Override public void caseNewExpr(NewExpr value) { SootClass type = value.getBaseType().getSootClass(); if (type.hasTag(TrustManagerTag.NAME)) { TrustManagerTag tag = (TrustManagerTag) type.getTag(TrustManagerTag.NAME);
vulnerabilities.add(new Vulnerability(method, VulnerabilityType.INIT_TRUST_MANAGER, tag.getState()));
grahamedgecombe/android-ssl
mitm/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/socket/SocketUtils.java
// Path: mitm/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/util/CLibrary.java // public interface CLibrary extends Library { // public final CLibrary INSTANCE = (CLibrary) Native.loadLibrary("c", CLibrary.class); // // /* from /usr/include/bits/socket.h */ // public final int PF_INET = 2; // public final int PF_INET6 = 10; // // /* from /usr/include/bits/in.h */ // public final int SOL_IP = 0; // public final int SOL_IPV6 = 41; // public final int IP_TRANSPARENT = 19; // // /* from /usr/include/linux/netfilter_ipv4.h */ // public final int SO_ORIGINAL_DST = 80; // // /* from /usr/include/linux/netfilter_ipv6/ip6_tables.h */ // public final int IP6T_SO_ORIGINAL_DST = 80; // // /* from /usr/include/linux/in.h */ // public final class sockaddr_in extends Structure { // public short sin_family; // public byte[] sin_port = new byte[2]; // public byte[] sin_addr = new byte[4]; // public byte[] sin_zero = new byte[8]; // // @Override // protected List getFieldOrder() { // return Arrays.asList("sin_family", "sin_port", "sin_addr", "sin_zero"); // } // } // // /* from /usr/include/linux/in6.h */ // public final class sockaddr_in6 extends Structure { // public short sin6_family; // public byte[] sin6_port = new byte[2]; // public byte[] sin6_flowinfo = new byte[4]; // public byte[] sin6_addr = new byte[16]; // public int sin6_scope_id; // // @Override // protected List getFieldOrder() { // return Arrays.asList("sin6_family", "sin6_port", "sin6_flowinfo", "sin6_addr", "sin6_scope_id"); // } // } // // /* from /usr/include/sys/socket.h */ // public int getsockopt(int socket, int level, int option_name, Pointer option_value, IntByReference option_len) throws LastErrorException; // public int setsockopt(int socket, int level, int option_name, Pointer option_value, int option_len) throws LastErrorException; // // /* from /usr/include/string.h */ // public String strerror(int errnum); // }
import com.sun.jna.LastErrorException; import com.sun.jna.ptr.IntByReference; import uk.ac.cam.gpe21.droidssl.mitm.util.CLibrary; import javax.net.ssl.SSLSocket; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Field; import java.net.*; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel;
/* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.mitm.socket; public final class SocketUtils { private static final Class<?> SERVER_SOCKET_CHANNEL_IMPL; private static final Field SERVER_SOCKET_CHANNEL_FD; private static final Class<?> SOCKET_CHANNEL_IMPL; private static final Field SOCKET_CHANNEL_FD; private static final Class<?> SSL_SOCKET_IMPL; private static final Field SSL_SOCKET_INPUT; private static final Field FD; static { try { SERVER_SOCKET_CHANNEL_IMPL = Class.forName("sun.nio.ch.ServerSocketChannelImpl"); SERVER_SOCKET_CHANNEL_FD = SERVER_SOCKET_CHANNEL_IMPL.getDeclaredField("fd"); SERVER_SOCKET_CHANNEL_FD.setAccessible(true); SOCKET_CHANNEL_IMPL = Class.forName("sun.nio.ch.SocketChannelImpl"); SOCKET_CHANNEL_FD = SOCKET_CHANNEL_IMPL.getDeclaredField("fd"); SOCKET_CHANNEL_FD.setAccessible(true); SSL_SOCKET_IMPL = Class.forName("sun.security.ssl.SSLSocketImpl"); SSL_SOCKET_INPUT = SSL_SOCKET_IMPL.getDeclaredField("sockInput"); SSL_SOCKET_INPUT.setAccessible(true); FD = FileDescriptor.class.getDeclaredField("fd"); FD.setAccessible(true); } catch (NoSuchFieldException | ClassNotFoundException ex) { throw new ExceptionInInitializerError(ex); } } /** * Opens an unbound {@link ServerSocket} with the {@code IP_TRANSPARENT} * option enabled. * @return The {@link ServerSocket}. * @throws IOException if an I/O error occurs opening the socket or if the * {@code IP_TRANSPARENT} option could not be set. */ public static ServerSocket openTproxyServerSocket() throws IOException { /* * The old IO ServerSocket class obtains an FD and binds to the socket * in one go in a single native call, making it impossible to set the * IP_TRANSPARENT option prior to binding. * * However, the NIO ServerSocketChannel class obtains an FD upon * creation and allows the bind to be delayed, allowing us to insert * the setsockopt() call between these two events. * * It also has a method to return an object which appears like a * ServerSocket but actually translates all method calls into * operations on the underlying ServerSocketChannel instead. This is * useful so we don't have to convert the entire MITM server to use * NIO. (Notably, SSL code is trickier in NIO as you have to implement * it yourself with the SSLEngine class.) */ ServerSocketChannel ch = ServerSocketChannel.open(); int fd = getFileDescriptor(ch); IntByReference yes = new IntByReference(1); /* sizeof(int) = 4 */ try {
// Path: mitm/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/util/CLibrary.java // public interface CLibrary extends Library { // public final CLibrary INSTANCE = (CLibrary) Native.loadLibrary("c", CLibrary.class); // // /* from /usr/include/bits/socket.h */ // public final int PF_INET = 2; // public final int PF_INET6 = 10; // // /* from /usr/include/bits/in.h */ // public final int SOL_IP = 0; // public final int SOL_IPV6 = 41; // public final int IP_TRANSPARENT = 19; // // /* from /usr/include/linux/netfilter_ipv4.h */ // public final int SO_ORIGINAL_DST = 80; // // /* from /usr/include/linux/netfilter_ipv6/ip6_tables.h */ // public final int IP6T_SO_ORIGINAL_DST = 80; // // /* from /usr/include/linux/in.h */ // public final class sockaddr_in extends Structure { // public short sin_family; // public byte[] sin_port = new byte[2]; // public byte[] sin_addr = new byte[4]; // public byte[] sin_zero = new byte[8]; // // @Override // protected List getFieldOrder() { // return Arrays.asList("sin_family", "sin_port", "sin_addr", "sin_zero"); // } // } // // /* from /usr/include/linux/in6.h */ // public final class sockaddr_in6 extends Structure { // public short sin6_family; // public byte[] sin6_port = new byte[2]; // public byte[] sin6_flowinfo = new byte[4]; // public byte[] sin6_addr = new byte[16]; // public int sin6_scope_id; // // @Override // protected List getFieldOrder() { // return Arrays.asList("sin6_family", "sin6_port", "sin6_flowinfo", "sin6_addr", "sin6_scope_id"); // } // } // // /* from /usr/include/sys/socket.h */ // public int getsockopt(int socket, int level, int option_name, Pointer option_value, IntByReference option_len) throws LastErrorException; // public int setsockopt(int socket, int level, int option_name, Pointer option_value, int option_len) throws LastErrorException; // // /* from /usr/include/string.h */ // public String strerror(int errnum); // } // Path: mitm/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/socket/SocketUtils.java import com.sun.jna.LastErrorException; import com.sun.jna.ptr.IntByReference; import uk.ac.cam.gpe21.droidssl.mitm.util.CLibrary; import javax.net.ssl.SSLSocket; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Field; import java.net.*; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; /* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.mitm.socket; public final class SocketUtils { private static final Class<?> SERVER_SOCKET_CHANNEL_IMPL; private static final Field SERVER_SOCKET_CHANNEL_FD; private static final Class<?> SOCKET_CHANNEL_IMPL; private static final Field SOCKET_CHANNEL_FD; private static final Class<?> SSL_SOCKET_IMPL; private static final Field SSL_SOCKET_INPUT; private static final Field FD; static { try { SERVER_SOCKET_CHANNEL_IMPL = Class.forName("sun.nio.ch.ServerSocketChannelImpl"); SERVER_SOCKET_CHANNEL_FD = SERVER_SOCKET_CHANNEL_IMPL.getDeclaredField("fd"); SERVER_SOCKET_CHANNEL_FD.setAccessible(true); SOCKET_CHANNEL_IMPL = Class.forName("sun.nio.ch.SocketChannelImpl"); SOCKET_CHANNEL_FD = SOCKET_CHANNEL_IMPL.getDeclaredField("fd"); SOCKET_CHANNEL_FD.setAccessible(true); SSL_SOCKET_IMPL = Class.forName("sun.security.ssl.SSLSocketImpl"); SSL_SOCKET_INPUT = SSL_SOCKET_IMPL.getDeclaredField("sockInput"); SSL_SOCKET_INPUT.setAccessible(true); FD = FileDescriptor.class.getDeclaredField("fd"); FD.setAccessible(true); } catch (NoSuchFieldException | ClassNotFoundException ex) { throw new ExceptionInInitializerError(ex); } } /** * Opens an unbound {@link ServerSocket} with the {@code IP_TRANSPARENT} * option enabled. * @return The {@link ServerSocket}. * @throws IOException if an I/O error occurs opening the socket or if the * {@code IP_TRANSPARENT} option could not be set. */ public static ServerSocket openTproxyServerSocket() throws IOException { /* * The old IO ServerSocket class obtains an FD and binds to the socket * in one go in a single native call, making it impossible to set the * IP_TRANSPARENT option prior to binding. * * However, the NIO ServerSocketChannel class obtains an FD upon * creation and allows the bind to be delayed, allowing us to insert * the setsockopt() call between these two events. * * It also has a method to return an object which appears like a * ServerSocket but actually translates all method calls into * operations on the underlying ServerSocketChannel instead. This is * useful so we don't have to convert the entire MITM server to use * NIO. (Notably, SSL code is trickier in NIO as you have to implement * it yourself with the SSLEngine class.) */ ServerSocketChannel ch = ServerSocketChannel.open(); int fd = getFileDescriptor(ch); IntByReference yes = new IntByReference(1); /* sizeof(int) = 4 */ try {
CLibrary.INSTANCE.setsockopt(fd, CLibrary.SOL_IP, CLibrary.IP_TRANSPARENT, yes.getPointer(), 4);
grahamedgecombe/android-ssl
mitm-test-client/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/testclient/SecureHostnameVerifier.java
// Path: mitm-common/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/crypto/cert/CertificateUtils.java // public final class CertificateUtils { // private static final String[] EMPTY_STRING_ARRAY = new String[0]; // // public static X509Certificate readCertificate(Path path) throws IOException { // try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { // return readCertificate(reader); // } // } // // public static X509Certificate readCertificate(Reader reader) throws IOException { // // TODO share with CertificateAuthority's own implementation // try (PEMParser parser = new PEMParser(reader)) { // Object object = parser.readObject(); // if (!(object instanceof X509CertificateHolder)) // throw new IOException("File does not contain a certificate"); // // X509CertificateHolder certificate = (X509CertificateHolder) object; // return new JcaX509CertificateConverter().getCertificate(certificate); // } catch (CertificateException ex) { // throw new IOException(ex); // } // } // // public static String extractCn(X509Certificate certificate) { // X500Name dn = JcaX500NameUtil.getSubject(certificate); // for (RDN rdn : dn.getRDNs()) { // AttributeTypeAndValue first = rdn.getFirst(); // if (first.getType().equals(BCStyle.CN)) { // return first.getValue().toString(); // } // } // // throw new IllegalArgumentException("certificate subject has no common name (CN)"); // } // // public static String[] extractSans(X509Certificate certificate) { // try { // Collection<List<?>> pairs = certificate.getSubjectAlternativeNames(); // if (pairs == null) // return EMPTY_STRING_ARRAY; // // List<String> sans = new ArrayList<>(); // for (List<?> pair : pairs) { // int type = (Integer) pair.get(0); // if (type == 2) { // TODO fix magic number! // String san = (String) pair.get(1); // sans.add(san); // } // } // return sans.toArray(EMPTY_STRING_ARRAY); // } catch (CertificateParsingException ex) { // throw new IllegalArgumentException(ex); // TODO ideal? // } // } // // private CertificateUtils() { // /* to prevent instantiation */ // } // }
import uk.ac.cam.gpe21.droidssl.mitm.crypto.cert.CertificateUtils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import java.security.cert.Certificate; import java.security.cert.X509Certificate;
/* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.mitm.testclient; public final class SecureHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String hostname, SSLSession session) { try { Certificate[] chain = session.getPeerCertificates(); X509Certificate leaf = (X509Certificate) chain[0];
// Path: mitm-common/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/crypto/cert/CertificateUtils.java // public final class CertificateUtils { // private static final String[] EMPTY_STRING_ARRAY = new String[0]; // // public static X509Certificate readCertificate(Path path) throws IOException { // try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { // return readCertificate(reader); // } // } // // public static X509Certificate readCertificate(Reader reader) throws IOException { // // TODO share with CertificateAuthority's own implementation // try (PEMParser parser = new PEMParser(reader)) { // Object object = parser.readObject(); // if (!(object instanceof X509CertificateHolder)) // throw new IOException("File does not contain a certificate"); // // X509CertificateHolder certificate = (X509CertificateHolder) object; // return new JcaX509CertificateConverter().getCertificate(certificate); // } catch (CertificateException ex) { // throw new IOException(ex); // } // } // // public static String extractCn(X509Certificate certificate) { // X500Name dn = JcaX500NameUtil.getSubject(certificate); // for (RDN rdn : dn.getRDNs()) { // AttributeTypeAndValue first = rdn.getFirst(); // if (first.getType().equals(BCStyle.CN)) { // return first.getValue().toString(); // } // } // // throw new IllegalArgumentException("certificate subject has no common name (CN)"); // } // // public static String[] extractSans(X509Certificate certificate) { // try { // Collection<List<?>> pairs = certificate.getSubjectAlternativeNames(); // if (pairs == null) // return EMPTY_STRING_ARRAY; // // List<String> sans = new ArrayList<>(); // for (List<?> pair : pairs) { // int type = (Integer) pair.get(0); // if (type == 2) { // TODO fix magic number! // String san = (String) pair.get(1); // sans.add(san); // } // } // return sans.toArray(EMPTY_STRING_ARRAY); // } catch (CertificateParsingException ex) { // throw new IllegalArgumentException(ex); // TODO ideal? // } // } // // private CertificateUtils() { // /* to prevent instantiation */ // } // } // Path: mitm-test-client/src/main/java/uk/ac/cam/gpe21/droidssl/mitm/testclient/SecureHostnameVerifier.java import uk.ac.cam.gpe21.droidssl.mitm.crypto.cert.CertificateUtils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import java.security.cert.Certificate; import java.security.cert.X509Certificate; /* * Copyright 2013-2014 Graham Edgecombe * * 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 uk.ac.cam.gpe21.droidssl.mitm.testclient; public final class SecureHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String hostname, SSLSession session) { try { Certificate[] chain = session.getPeerCertificates(); X509Certificate leaf = (X509Certificate) chain[0];
return hostname.equals(CertificateUtils.extractCn(leaf));