gt stringclasses 1 value | context stringlengths 2.05k 161k |
|---|---|
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Martin Eigenbrodt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.tasks;
import hudson.Extension;
import hudson.Launcher;
import hudson.Util;
import hudson.console.ModelHyperlinkNote;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AutoCompletionCandidates;
import hudson.model.BuildListener;
import hudson.model.Cause.UpstreamCause;
import hudson.model.DependencyGraph;
import hudson.model.DependencyGraph.Dependency;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Items;
import hudson.model.Job;
import hudson.model.Project;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.ItemListener;
import hudson.model.queue.Tasks;
import hudson.security.ACL;
import hudson.security.ACLContext;
import hudson.util.FormValidation;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import jenkins.model.DependencyDeclarer;
import jenkins.model.Jenkins;
import jenkins.model.ParameterizedJobMixIn;
import jenkins.triggers.ReverseBuildTrigger;
import net.sf.json.JSONObject;
import org.acegisecurity.Authentication;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
/**
* Triggers builds of other projects.
*
* <p>
* Despite what the name suggests, this class doesn't actually trigger other jobs
* as a part of {@link #perform} method. Its main job is to simply augment
* {@link DependencyGraph}. Jobs are responsible for triggering downstream jobs
* on its own, because dependencies may come from other sources.
*
* <p>
* This class, however, does provide the {@link #execute(AbstractBuild, BuildListener, BuildTrigger)}
* method as a convenience method to invoke downstream builds.
*
* <p>Its counterpart is {@link ReverseBuildTrigger}.
*
* @author Kohsuke Kawaguchi
*/
public class BuildTrigger extends Recorder implements DependencyDeclarer {
/**
* Comma-separated list of other projects to be scheduled.
*/
private String childProjects;
/**
* Threshold status to trigger other builds.
*
* For compatibility reasons, this field could be null, in which case
* it should read as "SUCCESS".
*/
private final Result threshold;
public BuildTrigger(String childProjects, boolean evenIfUnstable) {
this(childProjects,evenIfUnstable ? Result.UNSTABLE : Result.SUCCESS);
}
@DataBoundConstructor
public BuildTrigger(String childProjects, String threshold) {
this(childProjects, Result.fromString(StringUtils.defaultString(threshold, Result.SUCCESS.toString())));
}
public BuildTrigger(String childProjects, Result threshold) {
if(childProjects==null)
throw new IllegalArgumentException();
this.childProjects = childProjects;
this.threshold = threshold;
}
public BuildTrigger(List<AbstractProject> childProjects, Result threshold) {
this((Collection<AbstractProject>)childProjects,threshold);
}
public BuildTrigger(Collection<? extends AbstractProject> childProjects, Result threshold) {
this(Items.toNameList(childProjects),threshold);
}
public String getChildProjectsValue() {
return childProjects;
}
public Result getThreshold() {
if(threshold==null)
return Result.SUCCESS;
else
return threshold;
}
/**
* @deprecated as of 1.406
* Use {@link #getChildProjects(ItemGroup)}
*/
@Deprecated
public List<AbstractProject> getChildProjects() {
return getChildProjects(Jenkins.get());
}
/** @deprecated use {@link #getChildJobs} */
@Deprecated
public List<AbstractProject> getChildProjects(AbstractProject owner) {
return getChildProjects(owner==null?null:owner.getParent());
}
@Deprecated
public List<AbstractProject> getChildProjects(ItemGroup base) {
return Items.fromNameList(base,childProjects,AbstractProject.class);
}
@SuppressWarnings("unchecked")
@NonNull
public List<Job<?, ?>> getChildJobs(@NonNull AbstractProject<?, ?> owner) {
return Items.fromNameList(owner.getParent(), childProjects, (Class<Job<?, ?>>) (Class) Job.class);
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
/**
* @deprecated apparently unused
*/
@Deprecated
public boolean hasSame(AbstractProject owner, Collection<? extends AbstractProject> projects) {
List<AbstractProject> children = getChildProjects(owner);
return children.size()==projects.size() && children.containsAll(projects);
}
/**
* @deprecated as of 1.406
* Use {@link #hasSame(AbstractProject, Collection)}
*/
@Deprecated
public boolean hasSame(Collection<? extends AbstractProject> projects) {
return hasSame(null,projects);
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
List<Job<?, ?>> jobs = new ArrayList<>();
for (Job<?, ?> job : getChildJobs(build.getProject())) {
if (job instanceof AbstractProject) {
continue; // taken care of by DependencyGraph
}
jobs.add(job);
}
if (!jobs.isEmpty() && build.getResult().isBetterOrEqualTo(threshold)) {
PrintStream logger = listener.getLogger();
for (Job<?, ?> downstream : jobs) {
if (Jenkins.get().getItemByFullName(downstream.getFullName()) != downstream) {
LOGGER.log(Level.WARNING, "Running as {0} cannot even see {1} for trigger from {2}", new Object[] {Jenkins.getAuthentication().getName(), downstream, build.getParent()});
continue;
}
if (!downstream.hasPermission(Item.BUILD)) {
listener.getLogger().println(Messages.BuildTrigger_you_have_no_permission_to_build_(ModelHyperlinkNote.encodeTo(downstream)));
continue;
}
if (!(downstream instanceof ParameterizedJobMixIn.ParameterizedJob)) {
logger.println(Messages.BuildTrigger_NotBuildable(ModelHyperlinkNote.encodeTo(downstream)));
continue;
}
ParameterizedJobMixIn.ParameterizedJob<?, ?> pj = (ParameterizedJobMixIn.ParameterizedJob) downstream;
if (pj.isDisabled()) {
logger.println(Messages.BuildTrigger_Disabled(ModelHyperlinkNote.encodeTo(downstream)));
continue;
}
if (!downstream.isBuildable()) { // some other reason; no API to retrieve cause
logger.println(Messages.BuildTrigger_NotBuildable(ModelHyperlinkNote.encodeTo(downstream)));
continue;
}
boolean scheduled = pj.scheduleBuild(pj.getQuietPeriod(), new UpstreamCause((Run) build));
if (Jenkins.get().getItemByFullName(downstream.getFullName()) == downstream) {
String name = ModelHyperlinkNote.encodeTo(downstream);
if (scheduled) {
logger.println(Messages.BuildTrigger_Triggering(name));
} else {
logger.println(Messages.BuildTrigger_InQueue(name));
}
}
}
}
return true;
}
/**
* @deprecated since 1.341; use {@link #execute(AbstractBuild,BuildListener)}
*/
@Deprecated
public static boolean execute(AbstractBuild build, BuildListener listener, BuildTrigger trigger) {
return execute(build, listener);
}
/**
* Convenience method to trigger downstream builds.
*
* @param build
* The current build. Its downstreams will be triggered.
* @param listener
* Receives the progress report.
*/
public static boolean execute(AbstractBuild build, BuildListener listener) {
PrintStream logger = listener.getLogger();
// Check all downstream Project of the project, not just those defined by BuildTrigger
// TODO this may not yet be up to date if rebuildDependencyGraphAsync has been used; need a method to wait for the last call made before now to finish
final DependencyGraph graph = Jenkins.get().getDependencyGraph();
List<Dependency> downstreamProjects = new ArrayList<>(
graph.getDownstreamDependencies(build.getProject()));
// Sort topologically
downstreamProjects.sort(new Comparator<Dependency>() {
public int compare(Dependency lhs, Dependency rhs) {
// Swapping lhs/rhs to get reverse sort:
return graph.compare(rhs.getDownstreamProject(), lhs.getDownstreamProject());
}
});
for (Dependency dep : downstreamProjects) {
List<Action> buildActions = new ArrayList<>();
if (dep.shouldTriggerBuild(build, listener, buildActions)) {
AbstractProject p = dep.getDownstreamProject();
// Allow shouldTriggerBuild to return false first, in case it is skipping because of a lack of Item.READ/DISCOVER permission:
if (p.isDisabled()) {
logger.println(Messages.BuildTrigger_Disabled(ModelHyperlinkNote.encodeTo(p)));
continue;
}
boolean scheduled = p.scheduleBuild(p.getQuietPeriod(), new UpstreamCause((Run)build), buildActions.toArray(new Action[0]));
if (Jenkins.get().getItemByFullName(p.getFullName()) == p) {
String name = ModelHyperlinkNote.encodeTo(p);
if (scheduled) {
logger.println(Messages.BuildTrigger_Triggering(name));
} else {
logger.println(Messages.BuildTrigger_InQueue(name));
}
} // otherwise upstream users should not know that it happened
}
}
return true;
}
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) {
for (AbstractProject p : getChildProjects(owner)) // only care about AbstractProject here
graph.addDependency(new Dependency(owner, p) {
@Override
public boolean shouldTriggerBuild(AbstractBuild build, TaskListener listener,
List<Action> actions) {
AbstractProject downstream = getDownstreamProject();
if (Jenkins.get().getItemByFullName(downstream.getFullName()) != downstream) { // this checks Item.READ also on parent folders
LOGGER.log(Level.WARNING, "Running as {0} cannot even see {1} for trigger from {2}", new Object[] {Jenkins.getAuthentication().getName(), downstream, getUpstreamProject()});
return false; // do not even issue a warning to build log
}
if (!downstream.hasPermission(Item.BUILD)) {
listener.getLogger().println(Messages.BuildTrigger_you_have_no_permission_to_build_(ModelHyperlinkNote.encodeTo(downstream)));
return false;
}
return build.getResult().isBetterOrEqualTo(threshold);
}
});
}
@Override
public boolean needsToRunAfterFinalized() {
return true;
}
/** @deprecated Does not handle folder moves. */
@Deprecated
public boolean onJobRenamed(String oldName, String newName) {
// quick test
if(!childProjects.contains(oldName))
return false;
boolean changed = false;
// we need to do this per string, since old Project object is already gone.
String[] projects = childProjects.split(",");
for( int i=0; i<projects.length; i++ ) {
if(projects[i].trim().equals(oldName)) {
projects[i] = newName;
changed = true;
}
}
if(changed) {
StringBuilder b = new StringBuilder();
for (String p : projects) {
if(b.length()>0) b.append(',');
b.append(p);
}
childProjects = b.toString();
}
return changed;
}
/**
* Correct broken data gracefully (#1537)
*/
private Object readResolve() {
if(childProjects==null)
return childProjects="";
return this;
}
@Extension @Symbol("downstream")
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public String getDisplayName() {
return Messages.BuildTrigger_DisplayName();
}
@Override
public String getHelpFile() {
return "/help/project-config/downstream.html";
}
@Override
public BuildTrigger newInstance(StaplerRequest req, JSONObject formData) throws FormException {
String childProjectsString = formData.getString("childProjects").trim();
if (childProjectsString.endsWith(",")) {
childProjectsString = childProjectsString.substring(0, childProjectsString.length() - 1).trim();
}
return new BuildTrigger(
childProjectsString,
formData.optString("threshold", Result.SUCCESS.toString()));
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
public boolean showEvenIfUnstableOption(@CheckForNull Class<? extends AbstractProject<?,?>> jobType) {
// UGLY: for promotion process, this option doesn't make sense.
return jobType == null || !jobType.getName().contains("PromotionProcess");
}
/**
* Form validation method.
*/
public FormValidation doCheck(@AncestorInPath AbstractProject project, @QueryParameter String value) {
// JENKINS-32525: Check that it behaves gracefully for an unknown context
if (project == null) return FormValidation.ok(Messages.BuildTrigger_ok_ancestor_is_null());
// Require CONFIGURE permission on this project
if(!project.hasPermission(Item.CONFIGURE)) return FormValidation.ok();
StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),",");
boolean hasProjects = false;
while(tokens.hasMoreTokens()) {
String projectName = tokens.nextToken().trim();
if (StringUtils.isNotBlank(projectName)) {
Item item = Jenkins.get().getItem(projectName,project,Item.class);
if (item == null) {
Job<?, ?> nearest = Items.findNearest(Job.class, projectName, project.getParent());
String alternative = nearest != null ? nearest.getRelativeNameFrom(project) : "?";
return FormValidation.error(Messages.BuildTrigger_NoSuchProject(projectName, alternative));
}
if(!(item instanceof ParameterizedJobMixIn.ParameterizedJob))
return FormValidation.error(Messages.BuildTrigger_NotBuildable(projectName));
// check whether the supposed user is expected to be able to build
Authentication auth = Tasks.getAuthenticationOf(project);
if (!item.hasPermission(auth, Item.BUILD)) {
return FormValidation.error(Messages.BuildTrigger_you_have_no_permission_to_build_(projectName));
}
hasProjects = true;
}
}
if (!hasProjects) {
return FormValidation.error(Messages.BuildTrigger_NoProjectSpecified());
}
return FormValidation.ok();
}
public AutoCompletionCandidates doAutoCompleteChildProjects(@QueryParameter String value, @AncestorInPath Item self, @AncestorInPath ItemGroup container) {
return AutoCompletionCandidates.ofJobNames(Job.class,value,self,container);
}
@Extension
public static class ItemListenerImpl extends ItemListener {
@Override
public void onLocationChanged(final Item item, final String oldFullName, final String newFullName) {
try (ACLContext acl = ACL.as(ACL.SYSTEM)) {
locationChanged(item, oldFullName, newFullName);
}
}
private void locationChanged(Item item, String oldFullName, String newFullName) {
// update BuildTrigger of other projects that point to this object.
// can't we generalize this?
for( Project<?,?> p : Jenkins.get().allItems(Project.class) ) {
BuildTrigger t = p.getPublishersList().get(BuildTrigger.class);
if(t!=null) {
String cp2 = Items.computeRelativeNamesAfterRenaming(oldFullName, newFullName, t.childProjects, p.getParent());
if (!cp2.equals(t.childProjects)) {
t.childProjects = cp2;
try {
p.save();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to persist project setting during rename from "+oldFullName+" to "+newFullName,e);
}
}
}
}
}
}
}
private static final Logger LOGGER = Logger.getLogger(BuildTrigger.class.getName());
}
| |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This file has been modified from the original.
*
* The original file can be found at:
* https://code.google.com/p/replicaisland/
*/
package com.replica.core;
import java.util.Comparator;
import com.replica.core.factory.GameObjectFactory;
import com.replica.core.systems.CameraSystem;
import com.replica.utility.FixedSizeArray;
import com.replica.utility.Vector2;
/**
* A node in the game graph that manages the activation status of its children.
* The GameObjectManager moves the objects it manages in and out of the active
* list (that is, in and out of the game tree, causing them to be updated or
* ignored, respectively) each frame based on the distance of that object to the
* camera. Objects may specify an "activation radius" to define an area around
* themselves so that the position of the camera can be used to determine which
* objects should receive processing time and which should be ignored. Objects
* that do not move should have an activation radius that defines a sphere
* similar to the size of the screen; they only need processing when they are
* visible. Objects that move around will probably need larger regions so that
* they can leave the visible area of the game world and not be immediately
* deactivated.
*/
public class GameObjectManager extends ObjectManager {
private static final int MAX_GAME_OBJECTS = 384;
private float mMaxActivationRadius;
private final static HorizontalPositionComparator sGameObjectComparator = new HorizontalPositionComparator();
private FixedSizeArray<BaseObject> mInactiveObjects;
private FixedSizeArray<GameObject> mMarkedForDeathObjects;
private GameObject mPlayer;
private boolean mVisitingGraph;
private Vector2 mCameraFocus;
public GameObjectManager(float maxActivationRadius) {
super(MAX_GAME_OBJECTS);
mMaxActivationRadius = maxActivationRadius;
mInactiveObjects = new FixedSizeArray<BaseObject>(MAX_GAME_OBJECTS);
mInactiveObjects.setComparator(sGameObjectComparator);
mMarkedForDeathObjects = new FixedSizeArray<GameObject>(
MAX_GAME_OBJECTS);
mVisitingGraph = false;
mCameraFocus = new Vector2();
}
@Override
public void commitUpdates() {
super.commitUpdates();
GameObjectFactory factory = sSystemRegistry.gameObjectFactory;
final int objectsToKillCount = mMarkedForDeathObjects.getCount();
if (factory != null && objectsToKillCount > 0) {
final Object[] deathArray = mMarkedForDeathObjects.getArray();
for (int x = 0; x < objectsToKillCount; x++) {
factory.destroy((GameObject) deathArray[x]);
}
mMarkedForDeathObjects.clear();
}
}
@Override
public void update(float timeDelta, BaseObject parent) {
commitUpdates();
CameraSystem camera = sSystemRegistry.cameraSystem;
mCameraFocus
.set(camera.getFocusPositionX(), camera.getFocusPositionY());
mVisitingGraph = true;
FixedSizeArray<BaseObject> objects = getObjects();
final int count = objects.getCount();
if (count > 0) {
final Object[] objectArray = objects.getArray();
for (int i = count - 1; i >= 0; i--) {
GameObject gameObject = (GameObject) objectArray[i];
final float distance2 = mCameraFocus.distance2(gameObject
.getPosition());
if (distance2 < (gameObject.activationRadius * gameObject.activationRadius)
|| gameObject.activationRadius == -1) {
gameObject.update(timeDelta, this);
} else {
// Remove the object from the list.
// It's safe to just swap the current object with the last
// object because this list is being iterated backwards, so
// the last object in the list has already been processed.
objects.swapWithLast(i);
objects.removeLast();
if (gameObject.destroyOnDeactivation) {
mMarkedForDeathObjects.add(gameObject);
} else {
mInactiveObjects.add((BaseObject) gameObject);
}
}
}
}
mInactiveObjects.sort(false);
final int inactiveCount = mInactiveObjects.getCount();
if (inactiveCount > 0) {
final Object[] inactiveArray = mInactiveObjects.getArray();
for (int i = inactiveCount - 1; i >= 0; i--) {
GameObject gameObject = (GameObject) inactiveArray[i];
final Vector2 position = gameObject.getPosition();
final float distance2 = mCameraFocus.distance2(position);
final float xDistance = position.x - mCameraFocus.x;
if (distance2 < (gameObject.activationRadius * gameObject.activationRadius)
|| gameObject.activationRadius == -1) {
gameObject.update(timeDelta, this);
mInactiveObjects.swapWithLast(i);
mInactiveObjects.removeLast();
objects.add(gameObject);
} else if (xDistance < -mMaxActivationRadius) {
// We've passed the focus, we can stop processing now
break;
}
}
}
mVisitingGraph = false;
}
@Override
public void add(BaseObject object) {
if (object instanceof GameObject) {
super.add(object);
}
}
@Override
public void remove(BaseObject object) {
super.remove(object);
if (object == mPlayer) {
mPlayer = null;
}
}
public void destroy(GameObject object) {
mMarkedForDeathObjects.add(object);
remove(object);
}
public void destroyAll() {
assert mVisitingGraph == false;
commitUpdates();
FixedSizeArray<BaseObject> objects = getObjects();
final int count = objects.getCount();
for (int i = count - 1; i >= 0; i--) {
mMarkedForDeathObjects.add((GameObject) objects.get(i));
objects.remove(i);
}
final int inactiveObjectCount = mInactiveObjects.getCount();
for (int j = inactiveObjectCount - 1; j >= 0; j--) {
mMarkedForDeathObjects.add((GameObject) mInactiveObjects.get(j));
mInactiveObjects.remove(j);
}
mPlayer = null;
}
public void setPlayer(GameObject player) {
mPlayer = player;
}
public GameObject getPlayer() {
return mPlayer;
}
/** Comparator for game objects objects. */
private final static class HorizontalPositionComparator implements
Comparator<BaseObject> {
public int compare(BaseObject object1, BaseObject object2) {
int result = 0;
if (object1 == null && object2 != null) {
result = 1;
} else if (object1 != null && object2 == null) {
result = -1;
} else if (object1 != null && object2 != null) {
float delta = ((GameObject) object1).getPosition().x
- ((GameObject) object2).getPosition().x;
if (delta < 0) {
result = -1;
} else if (delta > 0) {
result = 1;
}
}
return result;
}
}
}
| |
/*
* Copyright 2008 The Closure Compiler Authors.
*
* 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.google.javascript.jscomp;
import com.google.javascript.jscomp.NodeTraversal.AbstractShallowCallback;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.util.LinkedList;
import java.util.List;
/**
* When there are multiple prototype member declarations to the same class,
* use a temp variable to alias the prototype object.
*
* Example:
*
* <pre>
* function B() { ... } \
* B.prototype.foo = function() { ... } \___ {@link ExtractionInstance}
* ... /
* B.prototype.bar = function() { ... } /
* ^---------------------------------{@link PrototypeMemberDeclaration}
* </pre>
* <p>becomes
* <pre>
* function B() { ... }
* x = B.prototype;
* x.foo = function() { ... }
* ...
* x.bar = function() { ... }
* </pre>
*
* <p> Works almost like a redundant load elimination but limited to only
* recognizing the class prototype declaration idiom. First it only works within
* a basic block because we avoided {@link DataFlowAnalysis} for compilation
* performance. Secondly, we can avoid having to compute how long to
* sub-expressing has to be. Example:
* <pre>
* a.b.c.d = ...
* a.b.c = ...
* a.b = ...
* a.b.c = ...
* </pre>
* <p> Further more, we only introduce one temp variable to hold a single
* prototype at a time. So all the {@link PrototypeMemberDeclaration}
* to be extracted must be in a single line. We call this a single
* {@link ExtractionInstance}.
*
* <p>Alternatively, for users who do not want a global variable to be
* introduced, we will create an anonymous function instead.
* <pre>
* function B() { ... }
* (function (x) {
* x.foo = function() { ... }
* ...
* x.bar = function() { ... }
* )(B.prototype)
* </pre>
*
* The RHS of the declarations can have side effects, however, one good way to
* break this is the following:
* <pre>
* function B() { ... }
* B.prototype.foo = (function() { B.prototype = somethingElse(); return 0 })();
* ...
* </pre>
* Such logic is highly unlikely and we will assume that it never occurs.
*
*/
class ExtractPrototypeMemberDeclarations implements CompilerPass {
// The name of variable that will temporary hold the pointer to the prototype
// object. Of cause, we assume that it'll be renamed by RenameVars.
private String prototypeAlias = "JSCompiler_prototypeAlias";
private final AbstractCompiler compiler;
private final Pattern pattern;
enum Pattern {
USE_GLOBAL_TEMP(
// Global Overhead.
// We need a temp variable to hold all the prototype.
"var t;".length(),
// Per Extract overhead:
// Every extraction instance must first use the temp variable to point
// to the prototype object.
"t=y.prototype;".length(),
// TODO(user): Check to to see if AliasExterns is on
// The gain we get per prototype declaration. Assuming it can be
// aliased.
"t.y=".length() - "x[p].y=".length()),
USE_IIFE(
// Global Overhead:
0,
// Per-extraction overhead:
// This is the cost of a single anoynmous function.
"(function(t){})(y.prototype);".length(),
// Per-prototype member declaration overhead:
// Here we assumes that they don't have AliasExterns on (in SIMPLE mode).
"t.y=".length() - "x.prototype.y=".length());
private final int globalOverhead;
private final int perExtractionOverhead;
private final int perMemberOverhead;
Pattern(int globalOverHead, int perExtractionOverhead, int perMemberOverhead) {
this.globalOverhead = globalOverHead;
this.perExtractionOverhead = perExtractionOverhead;
this.perMemberOverhead = perMemberOverhead;
}
}
ExtractPrototypeMemberDeclarations(AbstractCompiler compiler, Pattern pattern) {
this.compiler = compiler;
this.pattern = pattern;
}
@Override
public void process(Node externs, Node root) {
GatherExtractionInfo extractionInfo = new GatherExtractionInfo();
NodeTraversal.traverseEs6(compiler, root, extractionInfo);
if (extractionInfo.shouldExtract()) {
doExtraction(extractionInfo);
}
}
/**
* Declares the temp variable to point to prototype objects and iterates
* through all ExtractInstance and performs extraction there.
*/
private void doExtraction(GatherExtractionInfo info) {
// Insert a global temp if we are using the USE_GLOBAL_TEMP pattern.
if (pattern == Pattern.USE_GLOBAL_TEMP) {
Node injectionPoint = compiler.getNodeForCodeInsertion(null);
Node var = NodeUtil.newVarNode(prototypeAlias, null)
.useSourceInfoIfMissingFromForTree(injectionPoint);
injectionPoint.addChildToFront(var);
compiler.reportChangeToEnclosingScope(var);
}
// Go through all extraction instances and extract each of them.
for (ExtractionInstance instance : info.instances) {
extractInstance(instance);
}
}
/**
* At a given ExtractionInstance, stores and prototype object in the temp
* variable and rewrite each member declaration to assign to the temp variable
* instead.
*/
private void extractInstance(ExtractionInstance instance) {
PrototypeMemberDeclaration first = instance.declarations.getFirst();
String className = first.qualifiedClassName;
if (pattern == Pattern.USE_GLOBAL_TEMP) {
// Use the temp variable to hold the prototype.
Node stmt =
new Node(
first.node.getToken(),
IR.assign(
IR.name(prototypeAlias),
NodeUtil.newQName(
compiler,
className + ".prototype",
instance.parent,
className + ".prototype")))
.useSourceInfoIfMissingFromForTree(first.node);
instance.parent.addChildBefore(stmt, first.node);
compiler.reportChangeToEnclosingScope(stmt);
} else if (pattern == Pattern.USE_IIFE){
Node block = IR.block();
Node func = IR.function(
IR.name(""),
IR.paramList(IR.name(prototypeAlias)),
block);
Node call = IR.call(func,
NodeUtil.newQName(
compiler, className + ".prototype",
instance.parent, className + ".prototype"));
call.putIntProp(Node.FREE_CALL, 1);
Node stmt = new Node(first.node.getToken(), call);
stmt.useSourceInfoIfMissingFromForTree(first.node);
instance.parent.addChildBefore(stmt, first.node);
compiler.reportChangeToEnclosingScope(stmt);
for (PrototypeMemberDeclaration declar : instance.declarations) {
compiler.reportChangeToEnclosingScope(declar.node);
block.addChildToBack(declar.node.detach());
}
}
// Go thought each member declaration and replace it with an assignment
// to the prototype variable.
for (PrototypeMemberDeclaration declar : instance.declarations) {
replacePrototypeMemberDeclaration(declar);
}
}
/**
* Replaces a member declaration to an assignment to the temp prototype
* object.
*/
private void replacePrototypeMemberDeclaration(
PrototypeMemberDeclaration declar) {
// x.prototype.y = ... -> t.y = ...
Node assignment = declar.node.getFirstChild();
Node lhs = assignment.getFirstChild();
Node name = NodeUtil.newQName(
compiler,
prototypeAlias + "." + declar.memberName, declar.node,
declar.memberName);
// Save the full prototype path on the left hand side of the assignment
// for debugging purposes.
// declar.lhs = x.prototype.y so first child of the first child
// is 'x'.
Node accessNode = declar.lhs.getFirstFirstChild();
String originalName = accessNode.getOriginalName();
String className = originalName != null ? originalName : "?";
name.getFirstChild().useSourceInfoFromForTree(lhs);
name.getFirstChild().setOriginalName(className + ".prototype");
assignment.replaceChild(lhs, name);
compiler.reportChangeToEnclosingScope(name);
}
/**
* Collects all the possible extraction instances in a node traversal.
*/
private class GatherExtractionInfo extends AbstractShallowCallback {
private List<ExtractionInstance> instances = new LinkedList<>();
private int totalDelta = pattern.globalOverhead;
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (!n.isScript() && !n.isNormalBlock()) {
return;
}
for (Node cur = n.getFirstChild(); cur != null; cur = cur.getNext()) {
PrototypeMemberDeclaration prototypeMember =
PrototypeMemberDeclaration.extractDeclaration(cur);
if (prototypeMember == null) {
continue;
}
// Found a good site here. The constructor will computes the chain of
// declarations that is qualified for extraction.
ExtractionInstance instance =
new ExtractionInstance(prototypeMember, n);
cur = instance.declarations.getLast().node;
// Only add it to our work list if the extraction at this instance
// makes the code smaller.
if (instance.isFavorable()) {
instances.add(instance);
totalDelta += instance.delta;
}
}
}
/**
* @return <@code true> if the sum of all the extraction instance gain
* outweighs the overhead of the temp variable declaration.
*/
private boolean shouldExtract() {
return totalDelta < 0;
}
}
private class ExtractionInstance {
LinkedList<PrototypeMemberDeclaration> declarations = new LinkedList<>();
private int delta = 0;
private final Node parent;
private ExtractionInstance(PrototypeMemberDeclaration head, Node parent) {
this.parent = parent;
declarations.add(head);
delta = pattern.perExtractionOverhead + pattern.perMemberOverhead;
for (Node cur = head.node.getNext(); cur != null; cur = cur.getNext()) {
// We can skip over any named functions because they have no effect on
// the control flow. In fact, they are lifted to the beginning of the
// block. This happens a lot when devirtualization breaks the whole
// chain.
if (cur.isFunction()) {
continue;
}
PrototypeMemberDeclaration prototypeMember =
PrototypeMemberDeclaration.extractDeclaration(cur);
if (prototypeMember == null || !head.isSameClass(prototypeMember)) {
break;
}
declarations.add(prototypeMember);
delta += pattern.perMemberOverhead;
}
}
/**
* @return {@code true} if extracting all the declarations at this instance
* will overweight the overhead of aliasing the prototype object.
*/
boolean isFavorable() {
return delta <= 0;
}
}
/**
* Abstraction for a prototype member declaration.
*
* <p>{@code a.b.c.prototype.d = ....}
*/
private static class PrototypeMemberDeclaration {
final String memberName;
final Node node;
final String qualifiedClassName;
final Node lhs;
private PrototypeMemberDeclaration(Node lhs, Node node) {
this.lhs = lhs;
this.memberName = NodeUtil.getPrototypePropertyName(lhs);
this.node = node;
this.qualifiedClassName = getPrototypeClassName(lhs).getQualifiedName();
}
private boolean isSameClass(PrototypeMemberDeclaration other) {
return qualifiedClassName.equals(other.qualifiedClassName);
}
private static Node getPrototypeClassName(Node qName) {
Node cur = qName;
while (cur.isGetProp()) {
if (cur.getLastChild().getString().equals("prototype")) {
return cur.getFirstChild();
} else {
cur = cur.getFirstChild();
}
}
return null;
}
private static boolean isPrototypePropertyDeclaration(Node n) {
if (!NodeUtil.isExprAssign(n)) {
return false;
}
Node lvalue = n.getFirstFirstChild();
if (lvalue.isGetProp()) {
Node cur = lvalue.getFirstChild();
while (cur.isGetProp()) {
if (cur.getLastChild().getString().equals("prototype")) {
return cur.isQualifiedName();
}
cur = cur.getFirstChild();
}
}
return false;
}
/**
* @return A prototype member declaration representation if there is one
* else it returns {@code null}.
*/
private static PrototypeMemberDeclaration extractDeclaration(Node n) {
if (!isPrototypePropertyDeclaration(n)) {
return null;
}
Node lhs = n.getFirstFirstChild();
return new PrototypeMemberDeclaration(lhs, n);
}
}
}
| |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 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
*
* https://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.quarkus.vertx.http.runtime.security;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import javax.inject.Singleton;
import org.jboss.logging.Logger;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.quarkus.security.AuthenticationFailedException;
import io.quarkus.security.credential.PasswordCredential;
import io.quarkus.security.identity.IdentityProviderManager;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.request.AuthenticationRequest;
import io.quarkus.security.identity.request.UsernamePasswordAuthenticationRequest;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;
/**
* The authentication handler responsible for BASIC authentication as described by RFC2617
*
*/
@Singleton
public class BasicAuthenticationMechanism implements HttpAuthenticationMechanism {
private static final Logger log = Logger.getLogger(BasicAuthenticationMechanism.class);
public static final String SILENT = "silent";
public static final String CHARSET = "charset";
/**
* A comma separated list of patterns and charsets. The pattern is a regular expression.
*
* Because different browsers user different encodings this allows for the correct encoding to be selected based
* on the current browser. In general though it is recommended that BASIC auth not be used when passwords contain
* characters outside ASCII, as some browsers use the current locate to determine encoding.
*
* This list must have an even number of elements, as it is interpreted as pattern,charset,pattern,charset,...
*/
public static final String USER_AGENT_CHARSETS = "user-agent-charsets";
private final String challenge;
private static final String BASIC = "basic";
private static final String BASIC_PREFIX = BASIC + " ";
private static final String LOWERCASE_BASIC_PREFIX = BASIC_PREFIX.toLowerCase(Locale.ENGLISH);
private static final int PREFIX_LENGTH = BASIC_PREFIX.length();
private static final String COLON = ":";
/**
* If silent is true then this mechanism will only take effect if there is an Authorization header.
*
* This allows you to combine basic auth with form auth, so human users will use form based auth, but allows
* programmatic clients to login using basic auth.
*/
private final boolean silent;
private final Charset charset;
private final Map<Pattern, Charset> userAgentCharsets;
public BasicAuthenticationMechanism(final String realmName) {
this(realmName, false);
}
public BasicAuthenticationMechanism(final String realmName, final boolean silent) {
this(realmName, silent, StandardCharsets.UTF_8, Collections.emptyMap());
}
public BasicAuthenticationMechanism(final String realmName, final boolean silent,
Charset charset, Map<Pattern, Charset> userAgentCharsets) {
this.challenge = BASIC_PREFIX + "realm=\"" + realmName + "\"";
this.silent = silent;
this.charset = charset;
this.userAgentCharsets = Collections.unmodifiableMap(new LinkedHashMap<>(userAgentCharsets));
}
@Deprecated
public BasicAuthenticationMechanism(final String realmName, final String mechanismName) {
this(realmName, mechanismName, false);
}
@Deprecated
public BasicAuthenticationMechanism(final String realmName, final String mechanismName, final boolean silent) {
this(realmName, mechanismName, silent, StandardCharsets.UTF_8, Collections.emptyMap());
}
@Deprecated
public BasicAuthenticationMechanism(final String realmName, final String mechanismName, final boolean silent,
Charset charset, Map<Pattern, Charset> userAgentCharsets) {
this.challenge = BASIC_PREFIX + "realm=\"" + realmName + "\"";
this.silent = silent;
this.charset = charset;
this.userAgentCharsets = Collections.unmodifiableMap(new LinkedHashMap<>(userAgentCharsets));
}
@Override
public Uni<SecurityIdentity> authenticate(RoutingContext context,
IdentityProviderManager identityProviderManager) {
List<String> authHeaders = context.request().headers().getAll(HttpHeaderNames.AUTHORIZATION);
if (authHeaders != null) {
for (String current : authHeaders) {
if (current.toLowerCase(Locale.ENGLISH).startsWith(LOWERCASE_BASIC_PREFIX)) {
String base64Challenge = current.substring(PREFIX_LENGTH);
String plainChallenge = null;
byte[] decode = Base64.getDecoder().decode(base64Challenge);
Charset charset = this.charset;
if (!userAgentCharsets.isEmpty()) {
String ua = context.request().headers().get(HttpHeaderNames.USER_AGENT);
if (ua != null) {
for (Map.Entry<Pattern, Charset> entry : userAgentCharsets.entrySet()) {
if (entry.getKey().matcher(ua).find()) {
charset = entry.getValue();
break;
}
}
}
}
plainChallenge = new String(decode, charset);
int colonPos;
if ((colonPos = plainChallenge.indexOf(COLON)) > -1) {
String userName = plainChallenge.substring(0, colonPos);
char[] password = plainChallenge.substring(colonPos + 1).toCharArray();
log.debugf("Found basic auth header %s:***** (decoded using charset %s)", userName, charset);
UsernamePasswordAuthenticationRequest credential = new UsernamePasswordAuthenticationRequest(userName,
new PasswordCredential(password));
HttpSecurityUtils.setRoutingContextAttribute(credential, context);
context.put(HttpAuthenticationMechanism.class.getName(), this);
return identityProviderManager.authenticate(credential);
}
// By this point we had a header we should have been able to verify but for some reason
// it was not correctly structured.
return Uni.createFrom().failure(new AuthenticationFailedException());
}
}
}
// No suitable header has been found in this request,
return Uni.createFrom().optional(Optional.empty());
}
@Override
public Uni<ChallengeData> getChallenge(RoutingContext context) {
if (silent) {
//if this is silent we only send a challenge if the request contained auth headers
//otherwise we assume another method will send the challenge
String authHeader = context.request().headers().get(HttpHeaderNames.AUTHORIZATION);
if (authHeader == null) {
return Uni.createFrom().optional(Optional.empty());
}
}
ChallengeData result = new ChallengeData(
HttpResponseStatus.UNAUTHORIZED.code(),
HttpHeaderNames.WWW_AUTHENTICATE,
challenge);
return Uni.createFrom().item(result);
}
@Override
public Set<Class<? extends AuthenticationRequest>> getCredentialTypes() {
return Collections.singleton(UsernamePasswordAuthenticationRequest.class);
}
@Override
public Uni<HttpCredentialTransport> getCredentialTransport(RoutingContext context) {
return Uni.createFrom().item(new HttpCredentialTransport(HttpCredentialTransport.Type.AUTHORIZATION, BASIC));
}
@Override
public int getPriority() {
return 2000;
}
}
| |
/*
* Copyright 2010-2013 Coda Hale and Yammer, Inc., 2014-2017 Dropwizard Team
*
* 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.dropwizard.metrics;
import io.dropwizard.metrics.Counter;
import io.dropwizard.metrics.ExponentiallyDecayingReservoir;
import io.dropwizard.metrics.Gauge;
import io.dropwizard.metrics.Histogram;
import io.dropwizard.metrics.Meter;
import io.dropwizard.metrics.Metric;
import io.dropwizard.metrics.MetricFilter;
import io.dropwizard.metrics.MetricRegistry;
import io.dropwizard.metrics.MetricRegistryListener;
import io.dropwizard.metrics.MetricSet;
import io.dropwizard.metrics.Timer;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* A registry of metric instances.
*/
public class MetricRegistry implements MetricSet {
/**
* @param klass klass
* @param names names
* @return MetricName
* @see #name(String, String...)
*/
public static MetricName name(Class<?> klass, String... names) {
return name(klass.getName(), names);
}
/**
* Shorthand method for backwards compatibility in creating metric names.
*
* Uses {@link MetricName#build(String...)} for its
* heavy lifting.
*
* @see MetricName#build(String...)
* @param name The first element of the name
* @param names The remaining elements of the name
* @return A metric name matching the specified components.
*/
public static MetricName name(String name, String... names) {
final int length;
if (names == null) {
length = 0;
} else {
length = names.length;
}
final String[] parts = new String[length + 1];
parts[0] = name;
System.arraycopy(names, 0, parts, 1, length);
return MetricName.build(parts);
}
private final ConcurrentMap<MetricName, Metric> metrics;
private final List<MetricRegistryListener> listeners;
/**
* Creates a new {@link MetricRegistry}.
*/
public MetricRegistry() {
this(new ConcurrentHashMap<>());
}
/**
* Creates a {@link MetricRegistry} with a custom {@link ConcurrentMap} implementation for use
* inside the registry. Call as the super-constructor to create a {@link MetricRegistry} with
* space- or time-bounded metric lifecycles, for example.
* @param metricsMap metricsMap
*/
protected MetricRegistry(ConcurrentMap<MetricName, Metric> metricsMap) {
this.metrics = metricsMap;
this.listeners = new CopyOnWriteArrayList<>();
}
/**
* @param name name
* @param metric metric
* @param <T> type of metrics
* @return T git s{@code metric}
* @see #register(MetricName, Metric)
*/
@SuppressWarnings("unchecked")
public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException {
return register(MetricName.build(name), metric);
}
/**
* Given a {@link Metric}, registers it under the given name.
*
* @param name the name of the metric
* @param metric the metric
* @param <T> the type of the metric
* @return {@code metric}
* @throws IllegalArgumentException if the name is already registered
*/
@SuppressWarnings("unchecked")
public <T extends Metric> T register(MetricName name, T metric) throws IllegalArgumentException {
if (metric instanceof MetricSet) {
registerAll(name, (MetricSet) metric);
} else {
final Metric existing = metrics.putIfAbsent(name, metric);
if (existing == null) {
onMetricAdded(name, metric);
} else {
throw new IllegalArgumentException("A metric named " + name + " already exists");
}
}
return metric;
}
/**
* Given a metric set, registers them.
*
* @param metrics a set of metrics
* @throws IllegalArgumentException if any of the names are already registered
*/
public void registerAll(MetricSet metrics) throws IllegalArgumentException {
registerAll(null, metrics);
}
/**
* @param name name
* @return Counter counter
* @see #counter(MetricName)
*/
public Counter counter(String name) {
return counter(MetricName.build(name));
}
/**
* Return the {@link Counter} registered under this name; or create and register
* a new {@link Counter} if none is registered.
*
* @param name the name of the metric
* @return a new or pre-existing {@link Counter}
*/
public Counter counter(MetricName name) {
return getOrAdd(name, MetricBuilder.COUNTERS);
}
/**
* @param name name
* @return Histogram Histogram
* @see #histogram(MetricName)
*/
public Histogram histogram(String name) {
return histogram(MetricName.build(name));
}
/**
* Return the {@link Histogram} registered under this name; or create and register
* a new {@link Histogram} if none is registered.
*
* @param name the name of the metric
* @return a new or pre-existing {@link Histogram}
*/
public Histogram histogram(MetricName name) {
return getOrAdd(name, MetricBuilder.HISTOGRAMS);
}
/**
* @param name name
* @return Meter Meter
* @see #meter(MetricName)
*/
public Meter meter(String name) {
return meter(MetricName.build(name));
}
/**
* Return the {@link Meter} registered under this name; or create and register
* a new {@link Meter} if none is registered.
*
* @param name the name of the metric
* @return a new or pre-existing {@link Meter}
*/
public Meter meter(MetricName name) {
return getOrAdd(name, MetricBuilder.METERS);
}
/**
* @param name name
* @return Timer Timer
* @see #timer(MetricName)
*/
public Timer timer(String name) {
return timer(MetricName.build(name));
}
/**
* Return the {@link Timer} registered under this name; or create and register
* a new {@link Timer} if none is registered.
*
* @param name the name of the metric
* @return a new or pre-existing {@link Timer}
*/
public Timer timer(MetricName name) {
return getOrAdd(name, MetricBuilder.TIMERS);
}
/**
* Removes the metric with the given name.
*
* @param name the name of the metric
* @return whether or not the metric was removed
*/
public boolean remove(MetricName name) {
final Metric metric = metrics.remove(name);
if (metric != null) {
onMetricRemoved(name, metric);
return true;
}
return false;
}
/**
* Removes all the metrics in registry.
*/
public void removeAll() {
for(Iterator<Map.Entry<MetricName, Metric>> it = metrics.entrySet().iterator(); it.hasNext();) {
Map.Entry<MetricName, Metric> entry = it.next();
Metric metric = entry.getValue();
if(metric != null) {
onMetricRemoved(entry.getKey(), metric);
}
it.remove();
}
}
/**
* Removes all metrics which match the given filter.
*
* @param filter a filter
*/
public void removeMatching(MetricFilter filter) {
metrics.entrySet().stream().filter(entry -> filter.matches(entry.getKey(), entry.getValue())).forEachOrdered(entry -> remove(entry.getKey()));
}
/**
* Adds a {@link MetricRegistryListener} to a collection of listeners that will be notified on
* metric creation. Listeners will be notified in the order in which they are added.
*
* <b>N.B.:</b> The listener will be notified of all existing metrics when it first registers.
*
* @param listener the listener that will be notified
*/
public void addListener(MetricRegistryListener listener) {
listeners.add(listener);
for (Map.Entry<MetricName, Metric> entry : metrics.entrySet()) {
notifyListenerOfAddedMetric(listener, entry.getValue(), entry.getKey());
}
}
/**
* Removes a {@link MetricRegistryListener} from this registry's collection of listeners.
*
* @param listener the listener that will be removed
*/
public void removeListener(MetricRegistryListener listener) {
listeners.remove(listener);
}
/**
* Returns a set of the names of all the metrics in the registry.
*
* @return the names of all the metrics
*/
public SortedSet<MetricName> getNames() {
return Collections.unmodifiableSortedSet(new TreeSet<>(metrics.keySet()));
}
/**
* Returns a map of all the gauges in the registry and their names.
*
* @return all the gauges in the registry
*/
public SortedMap<MetricName, Gauge> getGauges() {
return getGauges(MetricFilter.ALL);
}
/**
* Returns a map of all the gauges in the registry and their names which match the given filter.
*
* @param filter the metric filter to match
* @return all the gauges in the registry
*/
public SortedMap<MetricName, Gauge> getGauges(MetricFilter filter) {
return getMetrics(Gauge.class, filter);
}
/**
* Returns a map of all the counters in the registry and their names.
*
* @return all the counters in the registry
*/
public SortedMap<MetricName, Counter> getCounters() {
return getCounters(MetricFilter.ALL);
}
/**
* Returns a map of all the counters in the registry and their names which match the given
* filter.
*
* @param filter the metric filter to match
* @return all the counters in the registry
*/
public SortedMap<MetricName, Counter> getCounters(MetricFilter filter) {
return getMetrics(Counter.class, filter);
}
/**
* Returns a map of all the histograms in the registry and their names.
*
* @return all the histograms in the registry
*/
public SortedMap<MetricName, Histogram> getHistograms() {
return getHistograms(MetricFilter.ALL);
}
/**
* Returns a map of all the histograms in the registry and their names which match the given
* filter.
*
* @param filter the metric filter to match
* @return all the histograms in the registry
*/
public SortedMap<MetricName, Histogram> getHistograms(MetricFilter filter) {
return getMetrics(Histogram.class, filter);
}
/**
* Returns a map of all the meters in the registry and their names.
*
* @return all the meters in the registry
*/
public SortedMap<MetricName, Meter> getMeters() {
return getMeters(MetricFilter.ALL);
}
/**
* Returns a map of all the meters in the registry and their names which match the given filter.
*
* @param filter the metric filter to match
* @return all the meters in the registry
*/
public SortedMap<MetricName, Meter> getMeters(MetricFilter filter) {
return getMetrics(Meter.class, filter);
}
/**
* Returns a map of all the timers in the registry and their names.
*
* @return all the timers in the registry
*/
public SortedMap<MetricName, Timer> getTimers() {
return getTimers(MetricFilter.ALL);
}
/**
* Returns a map of all the timers in the registry and their names which match the given filter.
*
* @param filter the metric filter to match
* @return all the timers in the registry
*/
public SortedMap<MetricName, Timer> getTimers(MetricFilter filter) {
return getMetrics(Timer.class, filter);
}
@SuppressWarnings("unchecked")
public <T extends Metric> T getOrAdd(MetricName name, MetricBuilder<T> builder) {
final Metric metric = metrics.get(name);
if (builder.isInstance(metric)) {
return (T) metric;
} else if (metric == null) {
try {
return register(name, builder.newMetric());
} catch (IllegalArgumentException e) {
final Metric added = metrics.get(name);
if (builder.isInstance(added)) {
return (T) added;
}
}
}
throw new IllegalArgumentException(name + " is already used for a different type of metric");
}
@SuppressWarnings("unchecked")
private <T extends Metric> SortedMap<MetricName, T> getMetrics(Class<T> klass, MetricFilter filter) {
final TreeMap<MetricName, T> timers = new TreeMap<>();
metrics.entrySet().stream().filter(entry -> klass.isInstance(entry.getValue()) && filter.matches(entry.getKey(),
entry.getValue())).forEachOrdered(entry -> timers.put(entry.getKey(), (T) entry.getValue()));
return Collections.unmodifiableSortedMap(timers);
}
private void onMetricAdded(MetricName name, Metric metric) {
for (MetricRegistryListener listener : listeners) {
notifyListenerOfAddedMetric(listener, metric, name);
}
}
private void notifyListenerOfAddedMetric(MetricRegistryListener listener, Metric metric, MetricName name) {
if (metric instanceof Gauge) {
listener.onGaugeAdded(name, (Gauge<?>) metric);
} else if (metric instanceof Counter) {
listener.onCounterAdded(name, (Counter) metric);
} else if (metric instanceof Histogram) {
listener.onHistogramAdded(name, (Histogram) metric);
} else if (metric instanceof Meter) {
listener.onMeterAdded(name, (Meter) metric);
} else if (metric instanceof Timer) {
listener.onTimerAdded(name, (Timer) metric);
} else {
throw new IllegalArgumentException("Unknown metric type: " + metric.getClass());
}
}
private void onMetricRemoved(MetricName name, Metric metric) {
for (MetricRegistryListener listener : listeners) {
notifyListenerOfRemovedMetric(name, metric, listener);
}
}
private void notifyListenerOfRemovedMetric(MetricName name, Metric metric, MetricRegistryListener listener) {
if (metric instanceof Gauge) {
listener.onGaugeRemoved(name);
} else if (metric instanceof Counter) {
listener.onCounterRemoved(name);
} else if (metric instanceof Histogram) {
listener.onHistogramRemoved(name);
} else if (metric instanceof Meter) {
listener.onMeterRemoved(name);
} else if (metric instanceof Timer) {
listener.onTimerRemoved(name);
} else {
throw new IllegalArgumentException("Unknown metric type: " + metric.getClass());
}
}
private void registerAll(MetricName prefix, MetricSet metrics) throws IllegalArgumentException {
if (prefix == null)
prefix = MetricName.EMPTY;
for (Map.Entry<MetricName, Metric> entry : metrics.getMetrics().entrySet()) {
if (entry.getValue() instanceof MetricSet) {
registerAll(MetricName.join(prefix, entry.getKey()), (MetricSet) entry.getValue());
} else {
register(MetricName.join(prefix, entry.getKey()), entry.getValue());
}
}
}
@Override
public Map<MetricName, Metric> getMetrics() {
return Collections.unmodifiableMap(metrics);
}
/**
* A quick and easy way of capturing the notion of default metrics.
*/
public interface MetricBuilder<T extends Metric> {
MetricBuilder<Counter> COUNTERS = new MetricBuilder<Counter>() {
@Override
public Counter newMetric() {
return new Counter();
}
@Override
public boolean isInstance(Metric metric) {
return Counter.class.isInstance(metric);
}
};
MetricBuilder<Histogram> HISTOGRAMS = new MetricBuilder<Histogram>() {
@Override
public Histogram newMetric() {
return new Histogram(new ExponentiallyDecayingReservoir());
}
@Override
public boolean isInstance(Metric metric) {
return Histogram.class.isInstance(metric);
}
};
MetricBuilder<Meter> METERS = new MetricBuilder<Meter>() {
@Override
public Meter newMetric() {
return new Meter();
}
@Override
public boolean isInstance(Metric metric) {
return Meter.class.isInstance(metric);
}
};
MetricBuilder<Timer> TIMERS = new MetricBuilder<Timer>() {
@Override
public Timer newMetric() {
return new Timer();
}
@Override
public boolean isInstance(Metric metric) {
return Timer.class.isInstance(metric);
}
};
T newMetric();
boolean isInstance(Metric metric);
}
}
| |
/*
* Copyright 2014 The Netty Project
*
* The Netty Project 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 io.netty.channel.epoll;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import io.netty.channel.MessageSizeEstimator;
import io.netty.channel.RecvByteBufAllocator;
import io.netty.channel.socket.SocketChannelConfig;
import io.netty.util.internal.PlatformDependent;
import java.net.InetAddress;
import java.util.Map;
import static io.netty.channel.ChannelOption.*;
public final class EpollSocketChannelConfig extends EpollChannelConfig implements SocketChannelConfig {
private static final long MAX_UINT32_T = 0xFFFFFFFFL;
private final EpollSocketChannel channel;
private volatile boolean allowHalfClosure;
/**
* Creates a new instance.
*/
EpollSocketChannelConfig(EpollSocketChannel channel) {
super(channel);
this.channel = channel;
if (PlatformDependent.canEnableTcpNoDelayByDefault()) {
setTcpNoDelay(true);
}
}
@Override
public Map<ChannelOption<?>, Object> getOptions() {
return getOptions(
super.getOptions(),
SO_RCVBUF, SO_SNDBUF, TCP_NODELAY, SO_KEEPALIVE, SO_REUSEADDR, SO_LINGER, IP_TOS,
ALLOW_HALF_CLOSURE, EpollChannelOption.TCP_CORK, EpollChannelOption.TCP_NOTSENT_LOWAT,
EpollChannelOption.TCP_KEEPCNT, EpollChannelOption.TCP_KEEPIDLE, EpollChannelOption.TCP_KEEPINTVL,
EpollChannelOption.TCP_MD5SIG);
}
@SuppressWarnings("unchecked")
@Override
public <T> T getOption(ChannelOption<T> option) {
if (option == SO_RCVBUF) {
return (T) Integer.valueOf(getReceiveBufferSize());
}
if (option == SO_SNDBUF) {
return (T) Integer.valueOf(getSendBufferSize());
}
if (option == TCP_NODELAY) {
return (T) Boolean.valueOf(isTcpNoDelay());
}
if (option == SO_KEEPALIVE) {
return (T) Boolean.valueOf(isKeepAlive());
}
if (option == SO_REUSEADDR) {
return (T) Boolean.valueOf(isReuseAddress());
}
if (option == SO_LINGER) {
return (T) Integer.valueOf(getSoLinger());
}
if (option == IP_TOS) {
return (T) Integer.valueOf(getTrafficClass());
}
if (option == ALLOW_HALF_CLOSURE) {
return (T) Boolean.valueOf(isAllowHalfClosure());
}
if (option == EpollChannelOption.TCP_CORK) {
return (T) Boolean.valueOf(isTcpCork());
}
if (option == EpollChannelOption.TCP_NOTSENT_LOWAT) {
return (T) Long.valueOf(getTcpNotSentLowAt());
}
if (option == EpollChannelOption.TCP_KEEPIDLE) {
return (T) Integer.valueOf(getTcpKeepIdle());
}
if (option == EpollChannelOption.TCP_KEEPINTVL) {
return (T) Integer.valueOf(getTcpKeepIntvl());
}
if (option == EpollChannelOption.TCP_KEEPCNT) {
return (T) Integer.valueOf(getTcpKeepCnt());
}
if (option == EpollChannelOption.TCP_USER_TIMEOUT) {
return (T) Integer.valueOf(getTcpUserTimeout());
}
return super.getOption(option);
}
@Override
public <T> boolean setOption(ChannelOption<T> option, T value) {
validate(option, value);
if (option == SO_RCVBUF) {
setReceiveBufferSize((Integer) value);
} else if (option == SO_SNDBUF) {
setSendBufferSize((Integer) value);
} else if (option == TCP_NODELAY) {
setTcpNoDelay((Boolean) value);
} else if (option == SO_KEEPALIVE) {
setKeepAlive((Boolean) value);
} else if (option == SO_REUSEADDR) {
setReuseAddress((Boolean) value);
} else if (option == SO_LINGER) {
setSoLinger((Integer) value);
} else if (option == IP_TOS) {
setTrafficClass((Integer) value);
} else if (option == ALLOW_HALF_CLOSURE) {
setAllowHalfClosure((Boolean) value);
} else if (option == EpollChannelOption.TCP_CORK) {
setTcpCork((Boolean) value);
} else if (option == EpollChannelOption.TCP_NOTSENT_LOWAT) {
setTcpNotSentLowAt((Long) value);
} else if (option == EpollChannelOption.TCP_KEEPIDLE) {
setTcpKeepIdle((Integer) value);
} else if (option == EpollChannelOption.TCP_KEEPCNT) {
setTcpKeepCntl((Integer) value);
} else if (option == EpollChannelOption.TCP_KEEPINTVL) {
setTcpKeepIntvl((Integer) value);
} else if (option == EpollChannelOption.TCP_USER_TIMEOUT) {
setTcpUserTimeout((Integer) value);
} else if (option == EpollChannelOption.TCP_MD5SIG) {
@SuppressWarnings("unchecked")
final Map<InetAddress, byte[]> m = (Map<InetAddress, byte[]>) value;
setTcpMd5Sig(m);
} else {
return super.setOption(option, value);
}
return true;
}
@Override
public int getReceiveBufferSize() {
return channel.fd().getReceiveBufferSize();
}
@Override
public int getSendBufferSize() {
return channel.fd().getSendBufferSize();
}
@Override
public int getSoLinger() {
return channel.fd().getSoLinger();
}
@Override
public int getTrafficClass() {
return Native.getTrafficClass(channel.fd().intValue());
}
@Override
public boolean isKeepAlive() {
return channel.fd().isKeepAlive();
}
@Override
public boolean isReuseAddress() {
return Native.isReuseAddress(channel.fd().intValue()) == 1;
}
@Override
public boolean isTcpNoDelay() {
return channel.fd().isTcpNoDelay();
}
/**
* Get the {@code TCP_CORK} option on the socket. See {@code man 7 tcp} for more details.
*/
public boolean isTcpCork() {
return channel.fd().isTcpCork();
}
/**
* Get the {@code TCP_NOTSENT_LOWAT} option on the socket. See {@code man 7 tcp} for more details.
* @return value is a uint32_t
*/
public long getTcpNotSentLowAt() {
return Native.getTcpNotSentLowAt(channel.fd().intValue()) & MAX_UINT32_T;
}
/**
* Get the {@code TCP_KEEPIDLE} option on the socket. See {@code man 7 tcp} for more details.
*/
public int getTcpKeepIdle() {
return Native.getTcpKeepIdle(channel.fd().intValue());
}
/**
* Get the {@code TCP_KEEPINTVL} option on the socket. See {@code man 7 tcp} for more details.
*/
public int getTcpKeepIntvl() {
return Native.getTcpKeepIntvl(channel.fd().intValue());
}
/**
* Get the {@code TCP_KEEPCNT} option on the socket. See {@code man 7 tcp} for more details.
*/
public int getTcpKeepCnt() {
return Native.getTcpKeepCnt(channel.fd().intValue());
}
/**
* Get the {@code TCP_USER_TIMEOUT} option on the socket. See {@code man 7 tcp} for more details.
*/
public int getTcpUserTimeout() {
return Native.getTcpUserTimeout(channel.fd().intValue());
}
@Override
public EpollSocketChannelConfig setKeepAlive(boolean keepAlive) {
channel.fd().setKeepAlive(keepAlive);
return this;
}
@Override
public EpollSocketChannelConfig setPerformancePreferences(
int connectionTime, int latency, int bandwidth) {
return this;
}
@Override
public EpollSocketChannelConfig setReceiveBufferSize(int receiveBufferSize) {
channel.fd().setReceiveBufferSize(receiveBufferSize);
return this;
}
@Override
public EpollSocketChannelConfig setReuseAddress(boolean reuseAddress) {
Native.setReuseAddress(channel.fd().intValue(), reuseAddress ? 1 : 0);
return this;
}
@Override
public EpollSocketChannelConfig setSendBufferSize(int sendBufferSize) {
channel.fd().setSendBufferSize(sendBufferSize);
return this;
}
@Override
public EpollSocketChannelConfig setSoLinger(int soLinger) {
channel.fd().setSoLinger(soLinger);
return this;
}
@Override
public EpollSocketChannelConfig setTcpNoDelay(boolean tcpNoDelay) {
channel.fd().setTcpNoDelay(tcpNoDelay);
return this;
}
/**
* Set the {@code TCP_CORK} option on the socket. See {@code man 7 tcp} for more details.
*/
public EpollSocketChannelConfig setTcpCork(boolean tcpCork) {
channel.fd().setTcpCork(tcpCork);
return this;
}
/**
* Set the {@code TCP_NOTSENT_LOWAT} option on the socket. See {@code man 7 tcp} for more details.
* @param tcpNotSentLowAt is a uint32_t
*/
public EpollSocketChannelConfig setTcpNotSentLowAt(long tcpNotSentLowAt) {
if (tcpNotSentLowAt < 0 || tcpNotSentLowAt > MAX_UINT32_T) {
throw new IllegalArgumentException("tcpNotSentLowAt must be a uint32_t");
}
Native.setTcpNotSentLowAt(channel.fd().intValue(), (int) tcpNotSentLowAt);
return this;
}
@Override
public EpollSocketChannelConfig setTrafficClass(int trafficClass) {
Native.setTrafficClass(channel.fd().intValue(), trafficClass);
return this;
}
/**
* Set the {@code TCP_KEEPIDLE} option on the socket. See {@code man 7 tcp} for more details.
*/
public EpollSocketChannelConfig setTcpKeepIdle(int seconds) {
Native.setTcpKeepIdle(channel.fd().intValue(), seconds);
return this;
}
/**
* Set the {@code TCP_KEEPINTVL} option on the socket. See {@code man 7 tcp} for more details.
*/
public EpollSocketChannelConfig setTcpKeepIntvl(int seconds) {
Native.setTcpKeepIntvl(channel.fd().intValue(), seconds);
return this;
}
/**
* Set the {@code TCP_KEEPCNT} option on the socket. See {@code man 7 tcp} for more details.
*/
public EpollSocketChannelConfig setTcpKeepCntl(int probes) {
Native.setTcpKeepCnt(channel.fd().intValue(), probes);
return this;
}
/**
* Set the {@code TCP_USER_TIMEOUT} option on the socket. See {@code man 7 tcp} for more details.
*/
public EpollSocketChannelConfig setTcpUserTimeout(int milliseconds) {
Native.setTcpUserTimeout(channel.fd().intValue(), milliseconds);
return this;
}
/*
* Set the {@code TCP_MD5SIG} option on the socket. See {@code linux/tcp.h} for more details.
* Keys can only be set on, not read to prevent a potential leak, as they are confidential.
* Allowing them being read would mean anyone with access to the channel could get them.
*/
public EpollSocketChannelConfig setTcpMd5Sig(Map<InetAddress, byte[]> keys) {
channel.setTcpMd5Sig(keys);
return this;
}
@Override
public boolean isAllowHalfClosure() {
return allowHalfClosure;
}
@Override
public EpollSocketChannelConfig setAllowHalfClosure(boolean allowHalfClosure) {
this.allowHalfClosure = allowHalfClosure;
return this;
}
@Override
public EpollSocketChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis) {
super.setConnectTimeoutMillis(connectTimeoutMillis);
return this;
}
@Override
@Deprecated
public EpollSocketChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead) {
super.setMaxMessagesPerRead(maxMessagesPerRead);
return this;
}
@Override
public EpollSocketChannelConfig setWriteSpinCount(int writeSpinCount) {
super.setWriteSpinCount(writeSpinCount);
return this;
}
@Override
public EpollSocketChannelConfig setAllocator(ByteBufAllocator allocator) {
super.setAllocator(allocator);
return this;
}
@Override
public EpollSocketChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator) {
super.setRecvByteBufAllocator(allocator);
return this;
}
@Override
public EpollSocketChannelConfig setAutoRead(boolean autoRead) {
super.setAutoRead(autoRead);
return this;
}
@Override
public EpollSocketChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark) {
super.setWriteBufferHighWaterMark(writeBufferHighWaterMark);
return this;
}
@Override
public EpollSocketChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark) {
super.setWriteBufferLowWaterMark(writeBufferLowWaterMark);
return this;
}
@Override
public EpollSocketChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator) {
super.setMessageSizeEstimator(estimator);
return this;
}
@Override
public EpollSocketChannelConfig setEpollMode(EpollMode mode) {
super.setEpollMode(mode);
return this;
}
}
| |
/**
* generated by Xtext 2.12.0
*/
package fire.fire.impl;
import fire.fire.BuiltInType;
import fire.fire.FirePackage;
import fire.fire.IdElement;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Id Element</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link fire.fire.impl.IdElementImpl#getName <em>Name</em>}</li>
* <li>{@link fire.fire.impl.IdElementImpl#getType <em>Type</em>}</li>
* </ul>
*
* @generated
*/
public class IdElementImpl extends MinimalEObjectImpl.Container implements IdElement
{
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The default value of the '{@link #getType() <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getType()
* @generated
* @ordered
*/
protected static final BuiltInType TYPE_EDEFAULT = BuiltInType.STRING;
/**
* The cached value of the '{@link #getType() <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getType()
* @generated
* @ordered
*/
protected BuiltInType type = TYPE_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IdElementImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return FirePackage.Literals.ID_ELEMENT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName()
{
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName)
{
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FirePackage.ID_ELEMENT__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BuiltInType getType()
{
return type;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setType(BuiltInType newType)
{
BuiltInType oldType = type;
type = newType == null ? TYPE_EDEFAULT : newType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FirePackage.ID_ELEMENT__TYPE, oldType, type));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case FirePackage.ID_ELEMENT__NAME:
return getName();
case FirePackage.ID_ELEMENT__TYPE:
return getType();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case FirePackage.ID_ELEMENT__NAME:
setName((String)newValue);
return;
case FirePackage.ID_ELEMENT__TYPE:
setType((BuiltInType)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case FirePackage.ID_ELEMENT__NAME:
setName(NAME_EDEFAULT);
return;
case FirePackage.ID_ELEMENT__TYPE:
setType(TYPE_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case FirePackage.ID_ELEMENT__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case FirePackage.ID_ELEMENT__TYPE:
return type != TYPE_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
result.append(name);
result.append(", type: ");
result.append(type);
result.append(')');
return result.toString();
}
} //IdElementImpl
| |
/*
* Copyright 2014 The Closure Compiler Authors.
*
* 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.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import com.google.javascript.jscomp.NodeUtil.Visitor;
import com.google.javascript.jscomp.parsing.parser.FeatureSet;
import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfoBuilder;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.FunctionType;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import java.util.ArrayList;
import java.util.List;
/** Converts REST parameters and SPREAD expressions. */
public final class Es6RewriteRestAndSpread extends NodeTraversal.AbstractPostOrderCallback
implements HotSwapCompilerPass {
static final DiagnosticType BAD_REST_PARAMETER_ANNOTATION =
DiagnosticType.warning(
"BAD_REST_PARAMETER_ANNOTATION",
"Missing \"...\" in type annotation for rest parameter.");
// The name of the index variable for populating the rest parameter array.
private static final String REST_INDEX = "$jscomp$restIndex";
// The name of the placeholder for the rest parameters.
private static final String REST_PARAMS = "$jscomp$restParams";
private static final String FRESH_SPREAD_VAR = "$jscomp$spread$args";
private static final FeatureSet transpiledFeatures =
FeatureSet.BARE_MINIMUM.with(Feature.REST_PARAMETERS, Feature.SPREAD_EXPRESSIONS);
private final AbstractCompiler compiler;
private final JSType arrayType;
private final JSType boolType;
private final JSType concatFnType;
private final JSType nullType;
private final JSType numberType;
private final JSType u2uFunctionType;
private final JSType functionFunctionType;
public Es6RewriteRestAndSpread(AbstractCompiler compiler) {
this.compiler = compiler;
if (compiler.hasTypeCheckingRun()) {
JSTypeRegistry registry = compiler.getTypeRegistry();
this.arrayType = registry.getNativeType(JSTypeNative.ARRAY_TYPE);
this.boolType = registry.getNativeType(JSTypeNative.BOOLEAN_TYPE);
this.concatFnType = arrayType.findPropertyType("concat");
this.nullType = registry.getNativeType(JSTypeNative.NULL_TYPE);
this.numberType = registry.getNativeType(JSTypeNative.NUMBER_TYPE);
this.u2uFunctionType = registry.getNativeType(JSTypeNative.U2U_FUNCTION_TYPE);
this.functionFunctionType = registry.getNativeType(JSTypeNative.FUNCTION_FUNCTION_TYPE);
} else {
this.arrayType = null;
this.boolType = null;
this.concatFnType = null;
this.nullType = null;
this.numberType = null;
this.u2uFunctionType = null;
this.functionFunctionType = null;
}
}
@Override
public void process(Node externs, Node root) {
TranspilationPasses.processTranspile(compiler, externs, transpiledFeatures, this);
TranspilationPasses.processTranspile(compiler, root, transpiledFeatures, this);
TranspilationPasses.markFeaturesAsTranspiledAway(compiler, transpiledFeatures);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
TranspilationPasses.hotSwapTranspile(compiler, scriptRoot, transpiledFeatures, this);
TranspilationPasses.markFeaturesAsTranspiledAway(compiler, transpiledFeatures);
}
@Override
public void visit(NodeTraversal traversal, Node current, Node parent) {
switch (current.getToken()) {
case REST:
visitRestParam(traversal, current, parent);
break;
case ARRAYLIT:
case NEW:
case CALL:
for (Node child : current.children()) {
if (child.isSpread()) {
visitArrayLitOrCallWithSpread(current);
break;
}
}
break;
default:
break;
}
}
/** Processes a rest parameter */
private void visitRestParam(NodeTraversal t, Node restParam, Node paramList) {
Node functionBody = paramList.getNext();
int restIndex = paramList.getIndexOfChild(restParam);
String paramName = restParam.getFirstChild().getString();
// Swap a vararg param into the parameter list.
Node nameNode = IR.name(paramName);
nameNode.setVarArgs(true);
nameNode.setJSDocInfo(restParam.getJSDocInfo());
paramList.replaceChild(restParam, nameNode);
// Make sure rest parameters are typechecked.
JSDocInfo inlineInfo = restParam.getJSDocInfo();
JSDocInfo functionInfo = NodeUtil.getBestJSDocInfo(paramList.getParent());
final JSTypeExpression paramTypeAnnotation;
if (inlineInfo != null) {
paramTypeAnnotation = inlineInfo.getType();
} else if (functionInfo != null) {
paramTypeAnnotation = functionInfo.getParameterType(paramName);
} else {
paramTypeAnnotation = null;
}
if (paramTypeAnnotation != null && paramTypeAnnotation.getRoot().getToken() != Token.ELLIPSIS) {
compiler.report(JSError.make(restParam, BAD_REST_PARAMETER_ANNOTATION));
}
if (!functionBody.hasChildren()) {
// If function has no body, we are done!
t.reportCodeChange();
return;
}
// Don't insert these directly, just clone them.
Node newArrayName = IR.name(REST_PARAMS).setJSType(arrayType);
Node cursorName = IR.name(REST_INDEX).setJSType(numberType);
Node newBlock = IR.block().useSourceInfoFrom(functionBody);
Node name = IR.name(paramName);
Node let = IR.let(name, newArrayName).useSourceInfoIfMissingFromForTree(functionBody);
newBlock.addChildToFront(let);
for (Node child : functionBody.children()) {
newBlock.addChildToBack(child.detach());
}
// `let $jscomp$restParams` => `let /** !Array<T> */ $jscomp$restParams`
if (paramTypeAnnotation != null) {
Node arrayTypeName = IR.string("Array");
Node typeNode = paramTypeAnnotation.getRoot();
Node memberType =
typeNode.getToken() == Token.ELLIPSIS
? typeNode.getFirstChild().cloneTree()
: typeNode.cloneTree();
if (functionInfo != null) {
memberType = replaceTypeVariablesWithUnknown(functionInfo, memberType);
}
arrayTypeName.addChildToFront(
new Node(Token.BLOCK, memberType).useSourceInfoIfMissingFrom(typeNode));
JSDocInfoBuilder builder = new JSDocInfoBuilder(false);
builder.recordType(
new JSTypeExpression(new Node(Token.BANG, arrayTypeName), restParam.getSourceFileName()));
name.setJSDocInfo(builder.build());
}
Node newArrayDeclaration = IR.var(newArrayName.cloneTree(), arrayLitWithJSType());
functionBody.addChildToFront(newArrayDeclaration.useSourceInfoIfMissingFromForTree(restParam));
// TODO(b/74074478): Use a general utility method instead of an inlined loop.
Node copyLoop =
IR.forNode(
IR.var(cursorName.cloneTree(), IR.number(restIndex).setJSType(numberType)),
IR.lt(
cursorName.cloneTree(),
IR.getprop(IR.name("arguments"), IR.string("length")).setJSType(numberType))
.setJSType(boolType),
IR.inc(cursorName.cloneTree(), false).setJSType(numberType),
IR.block(
IR.exprResult(
IR.assign(
IR.getelem(
newArrayName.cloneTree(),
IR.sub(
cursorName.cloneTree(),
IR.number(restIndex).setJSType(numberType))
.setJSType(numberType)),
IR.getelem(IR.name("arguments"), cursorName.cloneTree())
.setJSType(numberType))
.setJSType(numberType))))
.useSourceInfoIfMissingFromForTree(restParam);
functionBody.addChildAfter(copyLoop, newArrayDeclaration);
functionBody.addChildToBack(newBlock);
compiler.reportChangeToEnclosingScope(newBlock);
// For now, we are running transpilation before type-checking, so we'll
// need to make sure changes don't invalidate the JSDoc annotations.
// Therefore we keep the parameter list the same length and only initialize
// the values if they are set to undefined.
}
private Node replaceTypeVariablesWithUnknown(JSDocInfo functionJsdoc, Node typeAst) {
final List<String> typeVars = functionJsdoc.getTemplateTypeNames();
if (typeVars.isEmpty()) {
return typeAst;
}
NodeUtil.visitPreOrder(
typeAst,
new Visitor() {
@Override
public void visit(Node n) {
if (n.isString() && n.getParent() != null && typeVars.contains(n.getString())) {
n.replaceWith(new Node(Token.QMARK));
}
}
});
return typeAst;
}
/**
* Processes array literals or calls to eliminate spreads.
*
* <p>Examples:
*
* <ul>
* <li>[1, 2, ...x, 4, 5] => [].concat([1, 2], $jscomp.arrayFromIterable(x), [4, 5])
* <li>f(1, ...arr) => f.apply(null, [1].concat($jscomp.arrayFromIterable(arr)))
* <li>new F(...args) => new Function.prototype.bind.apply(F,
* [null].concat($jscomp.arrayFromIterable(args)))
* </ul>
*/
private void visitArrayLitOrCallWithSpread(Node spreadParent) {
if (spreadParent.isArrayLit()) {
visitArrayLitContainingSpread(spreadParent);
} else if (spreadParent.isCall()) {
visitCallContainingSpread(spreadParent);
} else {
checkArgument(spreadParent.isNew(), spreadParent);
visitNewWithSpread(spreadParent);
}
}
/**
* Extracts child nodes from an ARRAYLIT, CALL or NEW node that may contain spread operators into
* a list of nodes that may be concatenated with Array.concat() to get an array.
*
* <p>Example: [a, b, ...x, c, ...arguments] returns a list containing [ [a, b],
* $jscomp.arrayFromIterable(x), [c], $jscomp.arrayFromIterable(arguments) ]
*
* <p>IMPORTANT: CALL and NEW nodes must have the first, callee, child removed already.
*
* <p>Note that all elements of the returned list will be one of:
*
* <ul>
* <li>array literal
* <li>$jscomp.arrayFromIterable(spreadExpression)
* </ul>
*
* TODO(bradfordcsmith): When this pass moves after type checking, we can use type information to
* avoid unnecessary calls to $jscomp.arrayFromIterable().
*
* <p>TODO(nickreid): Stop mutating `spreadParent`.
*/
private List<Node> extractSpreadGroups(Node spreadParent) {
checkArgument(spreadParent.isCall() || spreadParent.isArrayLit() || spreadParent.isNew());
List<Node> groups = new ArrayList<>();
Node currGroup = null;
for (Node currElement = spreadParent.removeFirstChild();
currElement != null;
currElement = spreadParent.removeFirstChild()) {
if (currElement.isSpread()) {
Node spreadExpression = currElement.removeFirstChild();
if (spreadExpression.isArrayLit()) {
// We can expand an array literal spread in place.
if (currGroup == null) {
// [...[spread, contents], a, b]
// we can use this array lit itself as a group and append following elements to it
currGroup = spreadExpression;
} else {
// [ a, b, ...[spread, contents], c]
// Just add contents of this array lit to the group we were already collecting.
currGroup.addChildrenToBack(spreadExpression.removeChildren());
}
} else {
// We need to treat the spread expression as a separate group
if (currGroup != null) {
// finish off and add the group we were collecting before
groups.add(currGroup);
currGroup = null;
}
groups.add(Es6ToEs3Util.arrayFromIterable(compiler, spreadExpression));
}
} else {
if (currGroup == null) {
currGroup = arrayLitWithJSType();
}
currGroup.addChildToBack(currElement);
}
}
if (currGroup != null) {
groups.add(currGroup);
}
return groups;
}
/**
* Processes array literals containing spreads.
*
* <p>Example:
*
* <pre><code>
* [1, 2, ...x, 4, 5] => [1, 2].concat($jscomp.arrayFromIterable(x), [4, 5])
* </code></pre>
*/
private void visitArrayLitContainingSpread(Node spreadParent) {
checkArgument(spreadParent.isArrayLit());
List<Node> groups = extractSpreadGroups(spreadParent);
final Node baseArrayLit;
if (groups.get(0).isArrayLit()) {
// g0.concat(g1, g2, ..., gn)
baseArrayLit = groups.remove(0);
} else {
// [].concat(g0, g1, g2, ..., gn)
baseArrayLit = arrayLitWithJSType();
}
final Node joinedGroups;
if (groups.isEmpty()) {
joinedGroups = baseArrayLit;
} else {
Node concat = IR.getprop(baseArrayLit, IR.string("concat")).setJSType(concatFnType);
joinedGroups = IR.call(concat, groups.toArray(new Node[0]));
}
joinedGroups.useSourceInfoIfMissingFromForTree(spreadParent);
joinedGroups.setJSType(arrayType);
spreadParent.replaceWith(joinedGroups);
compiler.reportChangeToEnclosingScope(joinedGroups);
}
/**
* Processes calls containing spreads.
*
* <p>Examples:
*
* <pre><code>
* f(...arr) => f.apply(null, $jscomp.arrayFromIterable(arr))
* f(a, ...arr) => f.apply(null, [a].concat($jscomp.arrayFromIterable(arr)))
* f(...arr, b) => f.apply(null, [].concat($jscomp.arrayFromIterable(arr), [b]))
* </code></pre>
*/
private void visitCallContainingSpread(Node spreadParent) {
checkArgument(spreadParent.isCall());
Node callee = spreadParent.getFirstChild();
// Check if the callee has side effects before removing it from the AST (since some NodeUtil
// methods assume the node they are passed has a non-null parent).
boolean calleeMayHaveSideEffects = NodeUtil.mayHaveSideEffects(callee);
// Must remove callee before extracting argument groups.
spreadParent.removeChild(callee);
final Node joinedGroups;
if (spreadParent.hasOneChild() && isSpreadOfArguments(spreadParent.getOnlyChild())) {
// Check for special case of `foo(...arguments)` and pass `arguments` directly to
// `foo.apply(null, arguments)`. We want to avoid calling $jscomp.arrayFromIterable(arguments)
// for this case, because it can have side effects, which prevents code removal.
//
// TODO(b/74074478): Generalize this to avoid ever calling $jscomp.arrayFromIterable() for
// `arguments`.
joinedGroups = spreadParent.removeFirstChild().removeFirstChild();
} else {
List<Node> groups = extractSpreadGroups(spreadParent);
checkState(!groups.isEmpty());
if (groups.size() == 1) {
// A single group can just be passed to `apply()` as-is
// It could be `arguments`, an array literal, or $jscomp.arrayFromIterable(someExpression).
joinedGroups = groups.remove(0);
} else {
// If the first group is an array literal, we can just use that for concatenation,
// otherwise use an empty array literal.
//
// TODO(nickreid): Stop distringuishing between array literals and variables when this pass
// is moved after type-checking.
Node baseArrayLit = groups.get(0).isArrayLit() ? groups.remove(0) : arrayLitWithJSType();
Node concat = IR.getprop(baseArrayLit, IR.string("concat")).setJSType(concatFnType);
joinedGroups = IR.call(concat, groups.toArray(new Node[0])).setJSType(arrayType);
}
joinedGroups.setJSType(arrayType);
}
final Node callToApply;
if (calleeMayHaveSideEffects && callee.isGetProp()) {
JSType receiverType = callee.getFirstChild().getJSType(); // Type of `foo()`.
// foo().method(...[a, b, c])
// must convert to
// var freshVar;
// (freshVar = foo()).method.apply(freshVar, [a, b, c])
Node freshVar =
IR.name(FRESH_SPREAD_VAR + compiler.getUniqueNameIdSupplier().get())
.setJSType(receiverType);
Node freshVarDeclaration = IR.var(freshVar.cloneTree());
Node statementContainingSpread = NodeUtil.getEnclosingStatement(spreadParent);
freshVarDeclaration.useSourceInfoIfMissingFromForTree(statementContainingSpread);
statementContainingSpread
.getParent()
.addChildBefore(freshVarDeclaration, statementContainingSpread);
callee.addChildToFront(
IR.assign(freshVar.cloneTree(), callee.removeFirstChild()).setJSType(receiverType));
callToApply =
IR.call(getpropInferringJSType(callee, "apply"), freshVar.cloneTree(), joinedGroups);
} else {
// foo.method(...[a, b, c]) -> foo.method.apply(foo, [a, b, c]
// or
// foo(...[a, b, c]) -> foo.apply(null, [a, b, c])
Node context = callee.isGetProp() ? callee.getFirstChild().cloneTree() : nullWithJSType();
callToApply = IR.call(getpropInferringJSType(callee, "apply"), context, joinedGroups);
}
callToApply.setJSType(spreadParent.getJSType());
callToApply.useSourceInfoIfMissingFromForTree(spreadParent);
spreadParent.replaceWith(callToApply);
compiler.reportChangeToEnclosingScope(callToApply);
}
private boolean isSpreadOfArguments(Node n) {
return n.isSpread() && n.getOnlyChild().matchesQualifiedName("arguments");
}
/**
* Processes new calls containing spreads.
*
* <p>Example:
*
* <pre><code>
* new F(...args) =>
* new Function.prototype.bind.apply(F, [].concat($jscomp.arrayFromIterable(args)))
* </code></pre>
*/
private void visitNewWithSpread(Node spreadParent) {
checkArgument(spreadParent.isNew());
// Must remove callee before extracting argument groups.
Node callee = spreadParent.removeFirstChild();
List<Node> groups = extractSpreadGroups(spreadParent);
// We need to generate
// `new (Function.prototype.bind.apply(callee, [null].concat(other, args))();`.
// `null` stands in for the 'this' arg to the contructor.
final Node baseArrayLit;
if (groups.get(0).isArrayLit()) {
baseArrayLit = groups.remove(0);
} else {
baseArrayLit = arrayLitWithJSType();
}
baseArrayLit.addChildToFront(nullWithJSType());
Node joinedGroups =
groups.isEmpty()
? baseArrayLit
: IR.call(
IR.getprop(baseArrayLit, IR.string("concat")).setJSType(concatFnType),
groups.toArray(new Node[0]))
.setJSType(arrayType);
if (FeatureSet.ES3.contains(compiler.getOptions().getOutputFeatureSet())) {
// TODO(tbreisacher): Support this in ES3 too by not relying on Function.bind.
Es6ToEs3Util.cannotConvert(
compiler,
spreadParent,
"\"...\" passed to a constructor (consider using --language_out=ES5)");
}
// Function.prototype.bind =>
// function(this:function(new:[spreadParent], ...?), ...?):function(new:[spreadParent])
// Function.prototype.bind.apply =>
// function(function(new:[spreadParent], ...?), !Array<?>):function(new:[spreadParent])
Node bindApply =
getpropInferringJSType(
IR.getprop(
getpropInferringJSType(
IR.name("Function").setJSType(functionFunctionType), "prototype"),
"bind")
.setJSType(u2uFunctionType),
"apply");
Node result =
IR.newNode(
callInferringJSType(
bindApply, callee, joinedGroups /* function(new:[spreadParent]) */))
.setJSType(spreadParent.getJSType());
result.useSourceInfoIfMissingFromForTree(spreadParent);
spreadParent.replaceWith(result);
compiler.reportChangeToEnclosingScope(result);
}
private Node arrayLitWithJSType() {
return IR.arraylit().setJSType(arrayType);
}
private Node nullWithJSType() {
return IR.nullNode().setJSType(nullType);
}
private Node getpropInferringJSType(Node receiver, String propName) {
Node getprop = IR.getprop(receiver, propName);
JSType receiverType = receiver.getJSType();
if (receiverType == null) {
return getprop;
}
JSType getpropType = receiverType.findPropertyType(propName);
if (getpropType == null && receiverType instanceof FunctionType) {
getpropType = ((FunctionType) receiverType).getPropertyType(propName);
}
return getprop.setJSType(getpropType);
}
private Node callInferringJSType(Node callee, Node... args) {
Node call = IR.call(callee, args);
JSType calleeType = callee.getJSType();
if (calleeType == null || !(calleeType instanceof FunctionType)) {
return call;
}
JSType returnType = ((FunctionType) calleeType).getReturnType();
return call.setJSType(returnType);
}
}
| |
package com.udacity.gradle.multidex;
public class Methods96 {
public void method_0() {}
public void method_1() {}
public void method_2() {}
public void method_3() {}
public void method_4() {}
public void method_5() {}
public void method_6() {}
public void method_7() {}
public void method_8() {}
public void method_9() {}
public void method_10() {}
public void method_11() {}
public void method_12() {}
public void method_13() {}
public void method_14() {}
public void method_15() {}
public void method_16() {}
public void method_17() {}
public void method_18() {}
public void method_19() {}
public void method_20() {}
public void method_21() {}
public void method_22() {}
public void method_23() {}
public void method_24() {}
public void method_25() {}
public void method_26() {}
public void method_27() {}
public void method_28() {}
public void method_29() {}
public void method_30() {}
public void method_31() {}
public void method_32() {}
public void method_33() {}
public void method_34() {}
public void method_35() {}
public void method_36() {}
public void method_37() {}
public void method_38() {}
public void method_39() {}
public void method_40() {}
public void method_41() {}
public void method_42() {}
public void method_43() {}
public void method_44() {}
public void method_45() {}
public void method_46() {}
public void method_47() {}
public void method_48() {}
public void method_49() {}
public void method_50() {}
public void method_51() {}
public void method_52() {}
public void method_53() {}
public void method_54() {}
public void method_55() {}
public void method_56() {}
public void method_57() {}
public void method_58() {}
public void method_59() {}
public void method_60() {}
public void method_61() {}
public void method_62() {}
public void method_63() {}
public void method_64() {}
public void method_65() {}
public void method_66() {}
public void method_67() {}
public void method_68() {}
public void method_69() {}
public void method_70() {}
public void method_71() {}
public void method_72() {}
public void method_73() {}
public void method_74() {}
public void method_75() {}
public void method_76() {}
public void method_77() {}
public void method_78() {}
public void method_79() {}
public void method_80() {}
public void method_81() {}
public void method_82() {}
public void method_83() {}
public void method_84() {}
public void method_85() {}
public void method_86() {}
public void method_87() {}
public void method_88() {}
public void method_89() {}
public void method_90() {}
public void method_91() {}
public void method_92() {}
public void method_93() {}
public void method_94() {}
public void method_95() {}
public void method_96() {}
public void method_97() {}
public void method_98() {}
public void method_99() {}
public void method_100() {}
public void method_101() {}
public void method_102() {}
public void method_103() {}
public void method_104() {}
public void method_105() {}
public void method_106() {}
public void method_107() {}
public void method_108() {}
public void method_109() {}
public void method_110() {}
public void method_111() {}
public void method_112() {}
public void method_113() {}
public void method_114() {}
public void method_115() {}
public void method_116() {}
public void method_117() {}
public void method_118() {}
public void method_119() {}
public void method_120() {}
public void method_121() {}
public void method_122() {}
public void method_123() {}
public void method_124() {}
public void method_125() {}
public void method_126() {}
public void method_127() {}
public void method_128() {}
public void method_129() {}
public void method_130() {}
public void method_131() {}
public void method_132() {}
public void method_133() {}
public void method_134() {}
public void method_135() {}
public void method_136() {}
public void method_137() {}
public void method_138() {}
public void method_139() {}
public void method_140() {}
public void method_141() {}
public void method_142() {}
public void method_143() {}
public void method_144() {}
public void method_145() {}
public void method_146() {}
public void method_147() {}
public void method_148() {}
public void method_149() {}
public void method_150() {}
public void method_151() {}
public void method_152() {}
public void method_153() {}
public void method_154() {}
public void method_155() {}
public void method_156() {}
public void method_157() {}
public void method_158() {}
public void method_159() {}
public void method_160() {}
public void method_161() {}
public void method_162() {}
public void method_163() {}
public void method_164() {}
public void method_165() {}
public void method_166() {}
public void method_167() {}
public void method_168() {}
public void method_169() {}
public void method_170() {}
public void method_171() {}
public void method_172() {}
public void method_173() {}
public void method_174() {}
public void method_175() {}
public void method_176() {}
public void method_177() {}
public void method_178() {}
public void method_179() {}
public void method_180() {}
public void method_181() {}
public void method_182() {}
public void method_183() {}
public void method_184() {}
public void method_185() {}
public void method_186() {}
public void method_187() {}
public void method_188() {}
public void method_189() {}
public void method_190() {}
public void method_191() {}
public void method_192() {}
public void method_193() {}
public void method_194() {}
public void method_195() {}
public void method_196() {}
public void method_197() {}
public void method_198() {}
public void method_199() {}
public void method_200() {}
public void method_201() {}
public void method_202() {}
public void method_203() {}
public void method_204() {}
public void method_205() {}
public void method_206() {}
public void method_207() {}
public void method_208() {}
public void method_209() {}
public void method_210() {}
public void method_211() {}
public void method_212() {}
public void method_213() {}
public void method_214() {}
public void method_215() {}
public void method_216() {}
public void method_217() {}
public void method_218() {}
public void method_219() {}
public void method_220() {}
public void method_221() {}
public void method_222() {}
public void method_223() {}
public void method_224() {}
public void method_225() {}
public void method_226() {}
public void method_227() {}
public void method_228() {}
public void method_229() {}
public void method_230() {}
public void method_231() {}
public void method_232() {}
public void method_233() {}
public void method_234() {}
public void method_235() {}
public void method_236() {}
public void method_237() {}
public void method_238() {}
public void method_239() {}
public void method_240() {}
public void method_241() {}
public void method_242() {}
public void method_243() {}
public void method_244() {}
public void method_245() {}
public void method_246() {}
public void method_247() {}
public void method_248() {}
public void method_249() {}
public void method_250() {}
public void method_251() {}
public void method_252() {}
public void method_253() {}
public void method_254() {}
public void method_255() {}
public void method_256() {}
public void method_257() {}
public void method_258() {}
public void method_259() {}
public void method_260() {}
public void method_261() {}
public void method_262() {}
public void method_263() {}
public void method_264() {}
public void method_265() {}
public void method_266() {}
public void method_267() {}
public void method_268() {}
public void method_269() {}
public void method_270() {}
public void method_271() {}
public void method_272() {}
public void method_273() {}
public void method_274() {}
public void method_275() {}
public void method_276() {}
public void method_277() {}
public void method_278() {}
public void method_279() {}
public void method_280() {}
public void method_281() {}
public void method_282() {}
public void method_283() {}
public void method_284() {}
public void method_285() {}
public void method_286() {}
public void method_287() {}
public void method_288() {}
public void method_289() {}
public void method_290() {}
public void method_291() {}
public void method_292() {}
public void method_293() {}
public void method_294() {}
public void method_295() {}
public void method_296() {}
public void method_297() {}
public void method_298() {}
public void method_299() {}
public void method_300() {}
public void method_301() {}
public void method_302() {}
public void method_303() {}
public void method_304() {}
public void method_305() {}
public void method_306() {}
public void method_307() {}
public void method_308() {}
public void method_309() {}
public void method_310() {}
public void method_311() {}
public void method_312() {}
public void method_313() {}
public void method_314() {}
public void method_315() {}
public void method_316() {}
public void method_317() {}
public void method_318() {}
public void method_319() {}
public void method_320() {}
public void method_321() {}
public void method_322() {}
public void method_323() {}
public void method_324() {}
public void method_325() {}
public void method_326() {}
public void method_327() {}
public void method_328() {}
public void method_329() {}
public void method_330() {}
public void method_331() {}
public void method_332() {}
public void method_333() {}
public void method_334() {}
public void method_335() {}
public void method_336() {}
public void method_337() {}
public void method_338() {}
public void method_339() {}
public void method_340() {}
public void method_341() {}
public void method_342() {}
public void method_343() {}
public void method_344() {}
public void method_345() {}
public void method_346() {}
public void method_347() {}
public void method_348() {}
public void method_349() {}
public void method_350() {}
public void method_351() {}
public void method_352() {}
public void method_353() {}
public void method_354() {}
public void method_355() {}
public void method_356() {}
public void method_357() {}
public void method_358() {}
public void method_359() {}
public void method_360() {}
public void method_361() {}
public void method_362() {}
public void method_363() {}
public void method_364() {}
public void method_365() {}
public void method_366() {}
public void method_367() {}
public void method_368() {}
public void method_369() {}
public void method_370() {}
public void method_371() {}
public void method_372() {}
public void method_373() {}
public void method_374() {}
public void method_375() {}
public void method_376() {}
public void method_377() {}
public void method_378() {}
public void method_379() {}
public void method_380() {}
public void method_381() {}
public void method_382() {}
public void method_383() {}
public void method_384() {}
public void method_385() {}
public void method_386() {}
public void method_387() {}
public void method_388() {}
public void method_389() {}
public void method_390() {}
public void method_391() {}
public void method_392() {}
public void method_393() {}
public void method_394() {}
public void method_395() {}
public void method_396() {}
public void method_397() {}
public void method_398() {}
public void method_399() {}
public void method_400() {}
public void method_401() {}
public void method_402() {}
public void method_403() {}
public void method_404() {}
public void method_405() {}
public void method_406() {}
public void method_407() {}
public void method_408() {}
public void method_409() {}
public void method_410() {}
public void method_411() {}
public void method_412() {}
public void method_413() {}
public void method_414() {}
public void method_415() {}
public void method_416() {}
public void method_417() {}
public void method_418() {}
public void method_419() {}
public void method_420() {}
public void method_421() {}
public void method_422() {}
public void method_423() {}
public void method_424() {}
public void method_425() {}
public void method_426() {}
public void method_427() {}
public void method_428() {}
public void method_429() {}
public void method_430() {}
public void method_431() {}
public void method_432() {}
public void method_433() {}
public void method_434() {}
public void method_435() {}
public void method_436() {}
public void method_437() {}
public void method_438() {}
public void method_439() {}
public void method_440() {}
public void method_441() {}
public void method_442() {}
public void method_443() {}
public void method_444() {}
public void method_445() {}
public void method_446() {}
public void method_447() {}
public void method_448() {}
public void method_449() {}
public void method_450() {}
public void method_451() {}
public void method_452() {}
public void method_453() {}
public void method_454() {}
public void method_455() {}
public void method_456() {}
public void method_457() {}
public void method_458() {}
public void method_459() {}
public void method_460() {}
public void method_461() {}
public void method_462() {}
public void method_463() {}
public void method_464() {}
public void method_465() {}
public void method_466() {}
public void method_467() {}
public void method_468() {}
public void method_469() {}
public void method_470() {}
public void method_471() {}
public void method_472() {}
public void method_473() {}
public void method_474() {}
public void method_475() {}
public void method_476() {}
public void method_477() {}
public void method_478() {}
public void method_479() {}
public void method_480() {}
public void method_481() {}
public void method_482() {}
public void method_483() {}
public void method_484() {}
public void method_485() {}
public void method_486() {}
public void method_487() {}
public void method_488() {}
public void method_489() {}
public void method_490() {}
public void method_491() {}
public void method_492() {}
public void method_493() {}
public void method_494() {}
public void method_495() {}
public void method_496() {}
public void method_497() {}
public void method_498() {}
public void method_499() {}
public void method_500() {}
public void method_501() {}
public void method_502() {}
public void method_503() {}
public void method_504() {}
public void method_505() {}
public void method_506() {}
public void method_507() {}
public void method_508() {}
public void method_509() {}
public void method_510() {}
public void method_511() {}
public void method_512() {}
public void method_513() {}
public void method_514() {}
public void method_515() {}
public void method_516() {}
public void method_517() {}
public void method_518() {}
public void method_519() {}
public void method_520() {}
public void method_521() {}
public void method_522() {}
public void method_523() {}
public void method_524() {}
public void method_525() {}
public void method_526() {}
public void method_527() {}
public void method_528() {}
public void method_529() {}
public void method_530() {}
public void method_531() {}
public void method_532() {}
public void method_533() {}
public void method_534() {}
public void method_535() {}
public void method_536() {}
public void method_537() {}
public void method_538() {}
public void method_539() {}
public void method_540() {}
public void method_541() {}
public void method_542() {}
public void method_543() {}
public void method_544() {}
public void method_545() {}
public void method_546() {}
public void method_547() {}
public void method_548() {}
public void method_549() {}
public void method_550() {}
public void method_551() {}
public void method_552() {}
public void method_553() {}
public void method_554() {}
public void method_555() {}
public void method_556() {}
public void method_557() {}
public void method_558() {}
public void method_559() {}
public void method_560() {}
public void method_561() {}
public void method_562() {}
public void method_563() {}
public void method_564() {}
public void method_565() {}
public void method_566() {}
public void method_567() {}
public void method_568() {}
public void method_569() {}
public void method_570() {}
public void method_571() {}
public void method_572() {}
public void method_573() {}
public void method_574() {}
public void method_575() {}
public void method_576() {}
public void method_577() {}
public void method_578() {}
public void method_579() {}
public void method_580() {}
public void method_581() {}
public void method_582() {}
public void method_583() {}
public void method_584() {}
public void method_585() {}
public void method_586() {}
public void method_587() {}
public void method_588() {}
public void method_589() {}
public void method_590() {}
public void method_591() {}
public void method_592() {}
public void method_593() {}
public void method_594() {}
public void method_595() {}
public void method_596() {}
public void method_597() {}
public void method_598() {}
public void method_599() {}
public void method_600() {}
public void method_601() {}
public void method_602() {}
public void method_603() {}
public void method_604() {}
public void method_605() {}
public void method_606() {}
public void method_607() {}
public void method_608() {}
public void method_609() {}
public void method_610() {}
public void method_611() {}
public void method_612() {}
public void method_613() {}
public void method_614() {}
public void method_615() {}
public void method_616() {}
public void method_617() {}
public void method_618() {}
public void method_619() {}
public void method_620() {}
public void method_621() {}
public void method_622() {}
public void method_623() {}
public void method_624() {}
public void method_625() {}
public void method_626() {}
public void method_627() {}
public void method_628() {}
public void method_629() {}
public void method_630() {}
public void method_631() {}
public void method_632() {}
public void method_633() {}
public void method_634() {}
public void method_635() {}
public void method_636() {}
public void method_637() {}
public void method_638() {}
public void method_639() {}
public void method_640() {}
public void method_641() {}
public void method_642() {}
public void method_643() {}
public void method_644() {}
public void method_645() {}
public void method_646() {}
public void method_647() {}
public void method_648() {}
public void method_649() {}
public void method_650() {}
public void method_651() {}
public void method_652() {}
public void method_653() {}
public void method_654() {}
public void method_655() {}
public void method_656() {}
public void method_657() {}
public void method_658() {}
public void method_659() {}
public void method_660() {}
public void method_661() {}
public void method_662() {}
public void method_663() {}
public void method_664() {}
public void method_665() {}
public void method_666() {}
public void method_667() {}
public void method_668() {}
public void method_669() {}
public void method_670() {}
public void method_671() {}
public void method_672() {}
public void method_673() {}
public void method_674() {}
public void method_675() {}
public void method_676() {}
public void method_677() {}
public void method_678() {}
public void method_679() {}
public void method_680() {}
public void method_681() {}
public void method_682() {}
public void method_683() {}
public void method_684() {}
public void method_685() {}
public void method_686() {}
public void method_687() {}
public void method_688() {}
public void method_689() {}
public void method_690() {}
public void method_691() {}
public void method_692() {}
public void method_693() {}
public void method_694() {}
public void method_695() {}
public void method_696() {}
public void method_697() {}
public void method_698() {}
public void method_699() {}
public void method_700() {}
}
| |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.platform.templates;
import com.intellij.CommonBundle;
import com.intellij.configurationStore.StoreUtil;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.FileTemplateUtil;
import com.intellij.ide.fileTemplates.impl.FileTemplateBase;
import com.intellij.ide.util.projectWizard.ProjectTemplateFileProcessor;
import com.intellij.ide.util.projectWizard.ProjectTemplateParameterFactory;
import com.intellij.idea.ActionsBundle;
import com.intellij.lang.LangBundle;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.components.PathMacroManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentIterator;
import com.intellij.openapi.roots.FileIndex;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.project.ProjectKt;
import com.intellij.util.PlatformUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.Compressor;
import com.intellij.util.io.PathKt;
import com.intellij.util.ui.UIUtil;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.serialization.PathMacroUtil;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Dmitry Avdeev
*/
public class SaveProjectAsTemplateAction extends AnAction implements DumbAware {
private static final Logger LOG = Logger.getInstance(SaveProjectAsTemplateAction.class);
private static final @NonNls String PROJECT_TEMPLATE_XML = "project-template.xml";
static final @NonNls String FILE_HEADER_TEMPLATE_PLACEHOLDER = "<IntelliJ_File_Header>";
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
final Project project = getEventProject(e);
assert project != null;
if (!ProjectKt.isDirectoryBased(project)) {
Messages.showErrorDialog(project, LangBundle.message("dialog.message.project.templates.do.support.old.ipr.file"), CommonBundle.getErrorTitle());
return;
}
final VirtualFile descriptionFile = getDescriptionFile(project, LocalArchivedTemplate.DESCRIPTION_PATH);
final SaveProjectAsTemplateDialog dialog = new SaveProjectAsTemplateDialog(project, descriptionFile);
if (dialog.showAndGet()) {
final Module moduleToSave = dialog.getModuleToSave();
final Path file = dialog.getTemplateFile();
final String description = dialog.getDescription();
FileDocumentManager.getInstance().saveAllDocuments();
ProgressManager.getInstance().run(new Task.Backgroundable(project, LangBundle.message("progress.title.saving.project.as.template"), true) {
@Override
public void run(@NotNull final ProgressIndicator indicator) {
saveProject(project, file, moduleToSave, description, dialog.isReplaceParameters(), indicator, shouldEscape());
}
@Override
public void onSuccess() {
AnAction newProjectAction = ActionManager.getInstance().getAction(getNewProjectActionId());
newProjectAction.getTemplatePresentation().setText(ActionsBundle.actionText("NewDirectoryProject"));
AnAction manageAction = ActionManager.getInstance().getAction("ManageProjectTemplates");
Notification notification = new Notification("Project Template",
LangBundle.message("notification.title.template.created"),
LangBundle.message("notification.content.was.successfully.created",
FileUtilRt.getNameWithoutExtension(file.getFileName().toString())),
NotificationType.INFORMATION);
notification.addAction(newProjectAction);
if (manageAction != null) {
notification.addAction(manageAction);
}
notification.notify(getProject());
}
@Override
public void onCancel() {
PathKt.delete(file);
}
});
}
}
public static VirtualFile getDescriptionFile(Project project, String path) {
VirtualFile baseDir = project.getBaseDir();
return baseDir != null ? baseDir.findFileByRelativePath(path) : null;
}
public static void saveProject(Project project,
@NotNull Path zipFile,
Module moduleToSave,
String description,
boolean replaceParameters,
ProgressIndicator indicator,
boolean shouldEscape) {
Map<String, String> parameters = computeParameters(project, replaceParameters);
indicator.setText(LangBundle.message("progress.text.saving.project"));
StoreUtil.saveSettings(project, true);
indicator.setText(LangBundle.message("progress.text.processing.project.files"));
VirtualFile dir = getDirectoryToSave(project, moduleToSave);
List<LocalArchivedTemplate.RootDescription> roots = collectStructure(project, moduleToSave);
LocalArchivedTemplate.RootDescription basePathRoot = findOrAddBaseRoot(roots, dir);
PathKt.createDirectories(zipFile.getParent());
try (Compressor stream = new Compressor.Zip(zipFile.toFile())) {
writeFile(LocalArchivedTemplate.DESCRIPTION_PATH, description, project, basePathRoot.myRelativePath, stream, true);
if (replaceParameters) {
String text = getInputFieldsText(parameters);
writeFile(LocalArchivedTemplate.TEMPLATE_DESCRIPTOR, text, project, basePathRoot.myRelativePath, stream, false);
}
String metaDescription = getTemplateMetaText(shouldEscape, roots);
writeFile(LocalArchivedTemplate.META_TEMPLATE_DESCRIPTOR_PATH, metaDescription, project, basePathRoot.myRelativePath, stream, true);
FileIndex index = moduleToSave == null
? ProjectRootManager.getInstance(project).getFileIndex()
: ModuleRootManager.getInstance(moduleToSave).getFileIndex();
MyContentIterator iterator = new MyContentIterator(indicator, stream, project, parameters, shouldEscape);
for (LocalArchivedTemplate.RootDescription root : roots) {
String prefix = LocalArchivedTemplate.ROOT_FILE_NAME + root.myIndex;
VirtualFile rootFile = root.myFile;
iterator.setRootAndPrefix(rootFile, prefix);
index.iterateContentUnderDirectory(rootFile, iterator);
}
}
catch (ProcessCanceledException ignored) { }
catch (Exception ex) {
LOG.error(ex);
UIUtil.invokeLaterIfNeeded(() -> Messages.showErrorDialog(project,
LangBundle.message("dialog.message.can.t.save.project.as.template"),
LangBundle.message("dialog.message.internal.error")));
}
}
private static LocalArchivedTemplate.RootDescription findOrAddBaseRoot(List<LocalArchivedTemplate.RootDescription> roots, VirtualFile dirToSave) {
for (LocalArchivedTemplate.RootDescription root : roots) {
if(root.myRelativePath.isEmpty()){
return root;
}
}
LocalArchivedTemplate.RootDescription root = new LocalArchivedTemplate.RootDescription(dirToSave, "", roots.size());
roots.add(root);
return root;
}
static String getFileHeaderTemplateName() {
if (PlatformUtils.isIntelliJ()) {
return FileTemplateBase.getQualifiedName(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME, "java");
}
if (PlatformUtils.isPhpStorm()) {
return FileTemplateBase.getQualifiedName("PHP File Header", "php");
}
if (PlatformUtils.isWebStorm()) {
return FileTemplateBase.getQualifiedName("JavaScript File", "js");
}
if (PlatformUtils.isGoIde()) {
return FileTemplateBase.getQualifiedName("Go File", "go");
}
throw new IllegalStateException("Provide file header template for your IDE");
}
static String getNewProjectActionId() {
if (PlatformUtils.isIntelliJ() || PlatformUtils.isWebStorm()) {
return "NewProject";
}
if (PlatformUtils.isPhpStorm()) {
return "NewDirectoryProject";
}
if (PlatformUtils.isGoIde()) {
return "GoIdeNewProjectAction";
}
throw new IllegalStateException("Provide new project action id for your IDE");
}
private static void writeFile(String path, String text, Project project, String prefix, Compressor zip, boolean overwrite) throws IOException {
VirtualFile descriptionFile = getDescriptionFile(project, path);
if (descriptionFile == null) {
zip.addFile(prefix + '/' + path, text.getBytes(StandardCharsets.UTF_8));
}
else if (overwrite) {
Ref<IOException> exceptionRef = Ref.create();
ApplicationManager.getApplication().invokeAndWait(() -> {
try {
WriteAction.run(() -> VfsUtil.saveText(descriptionFile, text));
}
catch (IOException e) {
exceptionRef.set(e);
}
});
IOException e = exceptionRef.get();
if (e != null) throw e;
}
}
public static Map<String, String> computeParameters(final Project project, boolean replaceParameters) {
final Map<String, String> parameters = new HashMap<>();
if (replaceParameters) {
ApplicationManager.getApplication().runReadAction(() -> {
for (ProjectTemplateParameterFactory extension : ProjectTemplateParameterFactory.EP_NAME.getExtensionList()) {
String value = extension.detectParameterValue(project);
if (value != null) {
parameters.put(value, extension.getParameterId());
}
}
});
}
return parameters;
}
public static String getEncodedContent(VirtualFile virtualFile,
Project project,
Map<String, String> parameters) throws IOException {
return getEncodedContent(virtualFile, project, parameters,
FileTemplateBase.getQualifiedName(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME, "java"), true);
}
private static String getEncodedContent(VirtualFile virtualFile,
Project project,
Map<String, String> parameters,
String fileHeaderTemplateName,
boolean shouldEscape) throws IOException {
String text = VfsUtilCore.loadText(virtualFile);
final FileTemplate template = FileTemplateManager.getInstance(project).getDefaultTemplate(fileHeaderTemplateName);
final String templateText = template.getText();
final Pattern pattern = FileTemplateUtil.getTemplatePattern(template, project, new Int2ObjectOpenHashMap<>());
String result = convertTemplates(text, pattern, templateText, shouldEscape);
result = ProjectTemplateFileProcessor.encodeFile(result, virtualFile, project);
for (Map.Entry<String, String> entry : parameters.entrySet()) {
result = result.replace(entry.getKey(), "${" + entry.getValue() + "}");
}
return result;
}
private static VirtualFile getDirectoryToSave(Project project, @Nullable Module module) {
if (module == null) {
return project.getBaseDir();
}
else {
VirtualFile moduleFile = module.getModuleFile();
assert moduleFile != null;
return moduleFile.getParent();
}
}
@NotNull
private static List<LocalArchivedTemplate.RootDescription> collectStructure(Project project, Module moduleToSave) {
List<LocalArchivedTemplate.RootDescription> result = new ArrayList<>();
if (moduleToSave != null) {
PathMacroManager macroManager = PathMacroManager.getInstance(moduleToSave);
ModuleRootManager rootManager = ModuleRootManager.getInstance(moduleToSave);
int i = 0;
for (VirtualFile file : rootManager.getContentRoots()) {
result.add(i, describeRoot(file, i, macroManager));
i++;
}
}
else {
PathMacroManager macroManager = PathMacroManager.getInstance(project);
ProjectRootManager rootManager = ProjectRootManager.getInstance(project);
int i = 0;
for (VirtualFile file : rootManager.getContentRoots()) {
result.add(i, describeRoot(file, i, macroManager));
i++;
}
}
return result;
}
private static LocalArchivedTemplate.RootDescription describeRoot(VirtualFile root, int rootIndex, PathMacroManager pathMacroManager) {
return new LocalArchivedTemplate.RootDescription(root, getRelativePath(pathMacroManager, root), rootIndex);
}
private static String getRelativePath(PathMacroManager pathMacroManager, VirtualFile moduleRoot) {
String path = pathMacroManager.collapsePath(moduleRoot.getPath());
path = StringUtil.trimStart(path, "$" + PathMacroUtil.PROJECT_DIR_MACRO_NAME + "$");
path = StringUtil.trimStart(path, PathMacroUtil.DEPRECATED_MODULE_DIR);
path = StringUtil.trimStart(path, "/");
return path;
}
public static String convertTemplates(String input, Pattern pattern, String template, boolean shouldEscape) {
Matcher matcher = pattern.matcher(input);
int start = matcher.matches() ? matcher.start(1) : -1;
if(!shouldEscape){
if(start == -1){
return input;
} else {
return input.substring(0, start) + FILE_HEADER_TEMPLATE_PLACEHOLDER + input.substring(matcher.end(1));
}
}
StringBuilder builder = new StringBuilder(input.length() + 10);
for (int i = 0; i < input.length(); i++) {
if (start == i) {
builder.append(template);
//noinspection AssignmentToForLoopParameter
i = matcher.end(1);
}
char c = input.charAt(i);
if (c == '$') {
builder.append("#[[\\$]]#");
continue;
}
if (c == '#') {
builder.append('\\');
}
builder.append(c);
}
return builder.toString();
}
private static String getInputFieldsText(Map<String, String> parameters) {
Element element = new Element(ArchivedProjectTemplate.TEMPLATE);
for (Map.Entry<String, String> entry : parameters.entrySet()) {
Element field = new Element(ArchivedProjectTemplate.INPUT_FIELD);
field.setText(entry.getValue());
field.setAttribute(ArchivedProjectTemplate.INPUT_DEFAULT, entry.getKey());
element.addContent(field);
}
return JDOMUtil.writeElement(element);
}
private static String getTemplateMetaText(boolean shouldEncode, List<LocalArchivedTemplate.RootDescription> roots) {
Element element = new Element(ArchivedProjectTemplate.TEMPLATE);
element.setAttribute(LocalArchivedTemplate.UNENCODED_ATTRIBUTE, String.valueOf(!shouldEncode));
LocalArchivedTemplate.RootDescription.writeRoots(element, roots);
return JDOMUtil.writeElement(element);
}
private static boolean shouldEscape() {
return !PlatformUtils.isPhpStorm();
}
@Override
public void update(@NotNull AnActionEvent e) {
Project project = getEventProject(e);
e.getPresentation().setEnabled(project != null && !project.isDefault());
}
private static class MyContentIterator implements ContentIterator {
private static final Set<String> ALLOWED_FILES = ContainerUtil.newHashSet(
"description.html", PROJECT_TEMPLATE_XML, LocalArchivedTemplate.TEMPLATE_META_XML, "misc.xml", "modules.xml", "workspace.xml");
private final ProgressIndicator myIndicator;
private final Compressor myStream;
private final Project myProject;
private final Map<String, String> myParameters;
private final boolean myShouldEscape;
private VirtualFile myRootDir;
private String myPrefix;
MyContentIterator(ProgressIndicator indicator, Compressor stream, Project project, Map<String, String> parameters, boolean shouldEscape) {
myIndicator = indicator;
myStream = stream;
myProject = project;
myParameters = parameters;
myShouldEscape = shouldEscape;
}
public void setRootAndPrefix(VirtualFile root, String prefix) {
myRootDir = root;
myPrefix = prefix;
}
@Override
public boolean processFile(@NotNull VirtualFile virtualFile) {
myIndicator.checkCanceled();
if (!virtualFile.isDirectory()) {
String fileName = virtualFile.getName();
myIndicator.setText2(fileName);
String relativePath = VfsUtilCore.getRelativePath(virtualFile, myRootDir, '/');
if (relativePath == null) {
throw new RuntimeException("Can't find relative path for " + virtualFile + " in " + myRootDir);
}
boolean system = Project.DIRECTORY_STORE_FOLDER.equals(virtualFile.getParent().getName());
if (!system || ALLOWED_FILES.contains(fileName) || fileName.endsWith(".iml")) {
String entryName = myPrefix + '/' + relativePath;
try {
if (virtualFile.getFileType().isBinary() || PROJECT_TEMPLATE_XML.equals(virtualFile.getName())) {
myStream.addFile(entryName, new File(virtualFile.getPath()));
}
else {
String result = getEncodedContent(virtualFile, myProject, myParameters, getFileHeaderTemplateName(), myShouldEscape);
myStream.addFile(entryName, result.getBytes(StandardCharsets.UTF_8));
}
}
catch (IOException e) {
LOG.error(e);
}
}
}
return true;
}
}
}
| |
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.gradle.model;
import static com.android.build.gradle.model.AndroidComponentModelPlugin.COMPONENT_NAME;
import static com.android.build.gradle.model.ModelConstants.ANDROID_BUILDER;
import static com.android.build.gradle.model.ModelConstants.ANDROID_CONFIG_ADAPTOR;
import static com.android.build.gradle.model.ModelConstants.EXTRA_MODEL_INFO;
import static com.android.builder.core.BuilderConstants.DEBUG;
import static com.android.builder.model.AndroidProject.FD_INTERMEDIATES;
import com.android.annotations.NonNull;
import com.android.build.gradle.internal.AndroidConfigHelper;
import com.android.build.gradle.internal.ExecutionConfigurationUtil;
import com.android.build.gradle.internal.ExtraModelInfo;
import com.android.build.gradle.internal.LibraryCache;
import com.android.build.gradle.internal.LoggerWrapper;
import com.android.build.gradle.internal.NdkOptionsHelper;
import com.android.build.gradle.internal.SdkHandler;
import com.android.build.gradle.internal.TaskManager;
import com.android.build.gradle.internal.VariantManager;
import com.android.build.gradle.internal.coverage.JacocoPlugin;
import com.android.build.gradle.internal.process.GradleJavaProcessExecutor;
import com.android.build.gradle.internal.process.GradleProcessExecutor;
import com.android.build.gradle.internal.profile.RecordingBuildListener;
import com.android.build.gradle.internal.tasks.DependencyReportTask;
import com.android.build.gradle.internal.tasks.SigningReportTask;
import com.android.build.gradle.internal.variant.VariantFactory;
import com.android.build.gradle.managed.AndroidConfig;
import com.android.build.gradle.managed.BuildType;
import com.android.build.gradle.managed.ClassField;
import com.android.build.gradle.managed.NdkConfig;
import com.android.build.gradle.managed.NdkOptions;
import com.android.build.gradle.managed.ProductFlavor;
import com.android.build.gradle.managed.SigningConfig;
import com.android.build.gradle.managed.adaptor.AndroidConfigAdaptor;
import com.android.build.gradle.managed.adaptor.BuildTypeAdaptor;
import com.android.build.gradle.managed.adaptor.ProductFlavorAdaptor;
import com.android.build.gradle.tasks.JillTask;
import com.android.build.gradle.tasks.PreDex;
import com.android.builder.core.AndroidBuilder;
import com.android.builder.internal.compiler.JackConversionCache;
import com.android.builder.internal.compiler.PreDexCache;
import com.android.builder.profile.ProcessRecorderFactory;
import com.android.builder.profile.ThreadRecorder;
import com.android.builder.sdk.TargetInfo;
import com.android.builder.signing.DefaultSigningConfig;
import com.android.ide.common.internal.ExecutorSingleton;
import com.android.ide.common.process.LoggedProcessOutputHandler;
import com.android.ide.common.signing.KeystoreHelper;
import com.android.prefs.AndroidLocation;
import com.android.utils.ILogger;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.artifacts.repositories.MavenArtifactRepository;
import org.gradle.api.execution.TaskExecutionGraph;
import org.gradle.api.logging.LogLevel;
import org.gradle.api.plugins.JavaBasePlugin;
import org.gradle.internal.reflect.Instantiator;
import org.gradle.internal.service.ServiceRegistry;
import org.gradle.language.base.FunctionalSourceSet;
import org.gradle.language.base.LanguageSourceSet;
import org.gradle.model.Defaults;
import org.gradle.model.Model;
import org.gradle.model.ModelMap;
import org.gradle.model.Mutate;
import org.gradle.model.Path;
import org.gradle.model.RuleSource;
import org.gradle.model.internal.core.ModelCreators;
import org.gradle.model.internal.core.ModelReference;
import org.gradle.model.internal.registry.ModelRegistry;
import org.gradle.platform.base.BinaryContainer;
import org.gradle.platform.base.ComponentSpecContainer;
import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry;
import java.io.File;
import java.io.IOException;
import java.security.KeyStore;
import java.util.List;
import javax.inject.Inject;
import groovy.lang.Closure;
public class BaseComponentModelPlugin implements Plugin<Project> {
private ToolingModelBuilderRegistry toolingRegistry;
private ModelRegistry modelRegistry;
@Inject
protected BaseComponentModelPlugin(ToolingModelBuilderRegistry toolingRegistry,
ModelRegistry modelRegistry) {
this.toolingRegistry = toolingRegistry;
this.modelRegistry = modelRegistry;
}
/**
* Replace BasePlugin's apply method for component model.
*/
@Override
public void apply(Project project) {
ExecutionConfigurationUtil.setThreadPoolSize(project);
try {
ProcessRecorderFactory.initialize(
new LoggerWrapper(project.getLogger()),
project.getRootProject()
.file("profiler" + System.currentTimeMillis() + ".json"));
} catch (IOException e) {
throw new RuntimeException("Unable to initialize ProcessRecorderFactory");
}
project.getGradle().addListener(new RecordingBuildListener(ThreadRecorder.get()));
project.getPlugins().apply(AndroidComponentModelPlugin.class);
project.getPlugins().apply(JavaBasePlugin.class);
project.getPlugins().apply(JacocoPlugin.class);
// TODO: Create configurations for build types and flavors, or migrate to new dependency
// management if it's ready.
ConfigurationContainer configurations = project.getConfigurations();
createConfiguration(configurations, "compile", "Classpath for default sources.");
createConfiguration(configurations, "default-metadata", "Metadata for published APKs");
createConfiguration(configurations, "default-mapping", "Metadata for published APKs");
project.getPlugins().apply(NdkComponentModelPlugin.class);
// Remove this when our models no longer depends on Project.
modelRegistry.create(ModelCreators
.bridgedInstance(ModelReference.of("projectModel", Project.class), project)
.descriptor("Model of project.").build());
toolingRegistry.register(new ComponentModelBuilder(modelRegistry));
// Inserting the ToolingModelBuilderRegistry into the model so that it can be use to create
// TaskManager in child classes.
modelRegistry.create(ModelCreators.bridgedInstance(
ModelReference.of("toolingRegistry", ToolingModelBuilderRegistry.class),
toolingRegistry).descriptor("Tooling model builder model registry.").build());
}
private static void createConfiguration(@NonNull ConfigurationContainer configurations,
@NonNull String configurationName, @NonNull String configurationDescription) {
Configuration configuration = configurations.findByName(configurationName);
if (configuration == null) {
configuration = configurations.create(configurationName);
}
configuration.setVisible(false);
configuration.setDescription(configurationDescription);
}
@SuppressWarnings("MethodMayBeStatic")
public static class Rules extends RuleSource {
@Defaults
public void configureAndroidModel(
AndroidConfig androidModel,
ServiceRegistry serviceRegistry) {
Instantiator instantiator = serviceRegistry.get(Instantiator.class);
AndroidConfigHelper.configure(androidModel, instantiator);
androidModel.getSigningConfigs().create(DEBUG, new Action<SigningConfig>() {
@Override
public void execute(SigningConfig signingConfig) {
try {
signingConfig.setStoreFile(KeystoreHelper.defaultDebugKeystoreLocation());
signingConfig.setStorePassword(DefaultSigningConfig.DEFAULT_PASSWORD);
signingConfig.setKeyAlias(DefaultSigningConfig.DEFAULT_ALIAS);
signingConfig.setKeyPassword(DefaultSigningConfig.DEFAULT_PASSWORD);
signingConfig.setStoreType(KeyStore.getDefaultType());
} catch (AndroidLocation.AndroidLocationException e) {
throw new RuntimeException(e);
}
}
});
}
// com.android.build.gradle.AndroidConfig do not contain an NdkConfig. Copy it to the
// defaultConfig for now.
@Defaults
public void copyNdkConfig(
@Path("android.defaultConfig.ndk") NdkOptions defaultNdkConfig,
@Path("android.ndk") NdkConfig pluginNdkConfig) {
NdkOptionsHelper.init(defaultNdkConfig);
NdkOptionsHelper.merge(defaultNdkConfig, pluginNdkConfig);
}
// TODO: Remove code duplicated from BasePlugin.
@Model(EXTRA_MODEL_INFO)
public ExtraModelInfo createExtraModelInfo(
Project project,
@NonNull @Path("isApplication") Boolean isApplication) {
return new ExtraModelInfo(project, isApplication);
}
@Model
public SdkHandler createSdkHandler(final Project project) {
final ILogger logger = new LoggerWrapper(project.getLogger());
final SdkHandler sdkHandler = new SdkHandler(project, logger);
// call back on execution. This is called after the whole build is done (not
// after the current project is done).
// This is will be called for each (android) projects though, so this should support
// being called 2+ times.
project.getGradle().buildFinished(new Closure<Object>(this, this) {
public void doCall(Object it) {
ExecutorSingleton.shutdown();
sdkHandler.unload();
try {
PreDexCache.getCache().clear(project.getRootProject()
.file(String.valueOf(project.getRootProject().getBuildDir()) + "/"
+ FD_INTERMEDIATES + "/dex-cache/cache.xml"), logger);
JackConversionCache.getCache().clear(project.getRootProject()
.file(String.valueOf(project.getRootProject().getBuildDir()) + "/"
+ FD_INTERMEDIATES + "/jack-cache/cache.xml"), logger);
} catch (IOException e) {
throw new RuntimeException(e);
}
LibraryCache.getCache().unload();
}
public void doCall() {
doCall(null);
}
});
project.getGradle().getTaskGraph().whenReady(new Closure<Void>(this, this) {
public void doCall(TaskExecutionGraph taskGraph) {
for (Task task : taskGraph.getAllTasks()) {
if (task instanceof PreDex) {
PreDexCache.getCache().load(project.getRootProject()
.file(String.valueOf(project.getRootProject().getBuildDir())
+ "/" + FD_INTERMEDIATES + "/dex-cache/cache.xml"));
break;
} else if (task instanceof JillTask) {
JackConversionCache.getCache().load(project.getRootProject()
.file(String.valueOf(project.getRootProject().getBuildDir())
+ "/" + FD_INTERMEDIATES + "/jack-cache/cache.xml"));
break;
}
}
}
});
// setup SDK repositories.
for (final File file : sdkHandler.getSdkLoader().getRepositories()) {
project.getRepositories().maven(new Action<MavenArtifactRepository>() {
@Override
public void execute(MavenArtifactRepository repo) {
repo.setUrl(file.toURI());
}
});
}
return sdkHandler;
}
@Model(ANDROID_BUILDER)
public AndroidBuilder createAndroidBuilder(Project project, ExtraModelInfo extraModelInfo) {
String creator = "Android Gradle";
ILogger logger = new LoggerWrapper(project.getLogger());
return new AndroidBuilder(project.equals(project.getRootProject()) ? project.getName()
: project.getPath(), creator, new GradleProcessExecutor(project),
new GradleJavaProcessExecutor(project), new LoggedProcessOutputHandler(logger),
extraModelInfo, logger, project.getLogger().isEnabled(LogLevel.INFO));
}
@Mutate
public void initDebugBuildTypes(
@Path("android.buildTypes") ModelMap<BuildType> buildTypes,
@Path("android.signingConfigs") final ModelMap<SigningConfig> signingConfigs) {
buildTypes.beforeEach(new Action<BuildType>() {
@Override
public void execute(BuildType buildType) {
initBuildType(buildType);
}
});
buildTypes.named(DEBUG, new Action<BuildType>() {
@Override
public void execute(BuildType buildType) {
buildType.setSigningConfig(signingConfigs.get(DEBUG));
}
});
}
private static void initBuildType(@NonNull BuildType buildType) {
buildType.setDebuggable(false);
buildType.setTestCoverageEnabled(false);
buildType.setPseudoLocalesEnabled(false);
buildType.setRenderscriptDebuggable(false);
buildType.setRenderscriptOptimLevel(3);
buildType.setMinifyEnabled(false);
buildType.setZipAlignEnabled(true);
buildType.setEmbedMicroApp(true);
buildType.setUseJack(false);
buildType.setShrinkResources(false);
buildType.setProguardFiles(Sets.<File>newHashSet());
buildType.setConsumerProguardFiles(Sets.<File>newHashSet());
buildType.setTestProguardFiles(Sets.<File>newHashSet());
}
@Mutate
public void initDefaultConfig(@Path("android.defaultConfig") ProductFlavor defaultConfig) {
initProductFlavor(defaultConfig);
}
@Mutate
public void initProductFlavors(
@Path("android.productFlavors") final ModelMap<ProductFlavor> productFlavors) {
productFlavors.beforeEach(new Action<ProductFlavor>() {
@Override
public void execute(ProductFlavor productFlavor) {
initProductFlavor(productFlavor);
}
});
}
private void initProductFlavor(ProductFlavor productFlavor) {
productFlavor.setProguardFiles(Sets.<File>newHashSet());
productFlavor.setConsumerProguardFiles(Sets.<File>newHashSet());
productFlavor.setTestProguardFiles(Sets.<File>newHashSet());
productFlavor.setResourceConfigurations(Sets.<String>newHashSet());
productFlavor.setJarJarRuleFiles(Lists.<File>newArrayList());
productFlavor.getBuildConfigFields().beforeEach(new Action<ClassField>() {
@Override
public void execute(ClassField classField) {
classField.setAnnotations(Sets.<String>newHashSet());
}
});
productFlavor.getResValues().beforeEach(new Action<ClassField>() {
@Override
public void execute(ClassField classField) {
classField.setAnnotations(Sets.<String>newHashSet());
}
});
}
@Mutate
public void addDefaultAndroidSourceSet(
@Path("android.sources") AndroidComponentModelSourceSet sources) {
sources.addDefaultSourceSet("resources", AndroidLanguageSourceSet.class);
sources.addDefaultSourceSet("java", AndroidLanguageSourceSet.class);
sources.addDefaultSourceSet("manifest", AndroidLanguageSourceSet.class);
sources.addDefaultSourceSet("res", AndroidLanguageSourceSet.class);
sources.addDefaultSourceSet("assets", AndroidLanguageSourceSet.class);
sources.addDefaultSourceSet("aidl", AndroidLanguageSourceSet.class);
sources.addDefaultSourceSet("renderscript", AndroidLanguageSourceSet.class);
sources.addDefaultSourceSet("jniLibs", AndroidLanguageSourceSet.class);
sources.all(new Action<FunctionalSourceSet>() {
@Override
public void execute(FunctionalSourceSet functionalSourceSet) {
LanguageSourceSet manifest = functionalSourceSet.getByName("manifest");
manifest.getSource().setIncludes(ImmutableList.of("AndroidManifest.xml"));
}
});
}
@Model(ANDROID_CONFIG_ADAPTOR)
public com.android.build.gradle.AndroidConfig createModelAdaptor(
ServiceRegistry serviceRegistry,
AndroidConfig androidExtension,
Project project,
@Path("isApplication") Boolean isApplication) {
Instantiator instantiator = serviceRegistry.get(Instantiator.class);
return new AndroidConfigAdaptor(androidExtension, AndroidConfigHelper
.createSourceSetsContainer(project, instantiator, !isApplication));
}
@Mutate
public void createAndroidComponents(
ComponentSpecContainer androidSpecs,
ServiceRegistry serviceRegistry, AndroidConfig androidExtension,
com.android.build.gradle.AndroidConfig adaptedModel,
@Path("android.buildTypes") ModelMap<BuildType> buildTypes,
@Path("android.productFlavors") ModelMap<ProductFlavor> productFlavors,
@Path("android.signingConfigs") ModelMap<SigningConfig> signingConfigs,
VariantFactory variantFactory,
TaskManager taskManager,
Project project,
AndroidBuilder androidBuilder,
SdkHandler sdkHandler,
ExtraModelInfo extraModelInfo,
@Path("isApplication") Boolean isApplication) {
Instantiator instantiator = serviceRegistry.get(Instantiator.class);
// check if the target has been set.
TargetInfo targetInfo = androidBuilder.getTargetInfo();
if (targetInfo == null) {
sdkHandler.initTarget(androidExtension.getCompileSdkVersion(),
androidExtension.getBuildToolsRevision(),
androidExtension.getLibraryRequests(), androidBuilder);
}
VariantManager variantManager = new VariantManager(project, androidBuilder,
adaptedModel, variantFactory, taskManager, instantiator);
for (BuildType buildType : buildTypes.values()) {
variantManager.addBuildType(new BuildTypeAdaptor(buildType));
}
for (ProductFlavor productFlavor : productFlavors.values()) {
variantManager.addProductFlavor(new ProductFlavorAdaptor(productFlavor));
}
DefaultAndroidComponentSpec spec =
(DefaultAndroidComponentSpec) androidSpecs.get(COMPONENT_NAME);
spec.setExtension(androidExtension);
spec.setVariantManager(variantManager);
}
@Mutate
public void createVariantData(
ModelMap<AndroidBinary> binaries,
ModelMap<AndroidComponentSpec> specs,
TaskManager taskManager) {
final VariantManager variantManager =
((DefaultAndroidComponentSpec) specs.get(COMPONENT_NAME)).getVariantManager();
binaries.afterEach(new Action<AndroidBinary>() {
@Override
public void execute(AndroidBinary androidBinary) {
DefaultAndroidBinary binary = (DefaultAndroidBinary) androidBinary;
List<ProductFlavorAdaptor> adaptedFlavors = Lists.newArrayList();
for (ProductFlavor flavor : binary.getProductFlavors()) {
adaptedFlavors.add(new ProductFlavorAdaptor(flavor));
}
binary.setVariantData(
variantManager.createVariantData(
new BuildTypeAdaptor(binary.getBuildType()),
adaptedFlavors));
variantManager.getVariantDataList().add(binary.getVariantData());
}
});
}
@Mutate
public void createLifeCycleTasks(ModelMap<Task> tasks, TaskManager taskManager) {
taskManager.createTasksBeforeEvaluate(new TaskModelMapAdaptor(tasks));
}
@Mutate
public void createAndroidTasks(
ModelMap<Task> tasks,
ModelMap<AndroidComponentSpec> androidSpecs,
TaskManager taskManager,
SdkHandler sdkHandler,
Project project, AndroidComponentModelSourceSet androidSources) {
// setup SDK repositories.
for (final File file : sdkHandler.getSdkLoader().getRepositories()) {
project.getRepositories().maven(new Action<MavenArtifactRepository>() {
@Override
public void execute(MavenArtifactRepository repo) {
repo.setUrl(file.toURI());
}
});
}
// TODO: determine how to provide functionalities of variant API objects.
}
// TODO: Use @BinaryTasks after figuring how to configure non-binary specific tasks.
@Mutate
public void createBinaryTasks(
final ModelMap<Task> tasks,
BinaryContainer binaries,
ModelMap<AndroidComponentSpec> specs,
TaskManager taskManager) {
final VariantManager variantManager =
((DefaultAndroidComponentSpec) specs.get(COMPONENT_NAME)).getVariantManager();
binaries.withType(AndroidBinary.class, new Action<AndroidBinary>() {
@Override
public void execute(AndroidBinary androidBinary) {
DefaultAndroidBinary binary = (DefaultAndroidBinary) androidBinary;
variantManager.createTasksForVariantData(
new TaskModelMapAdaptor(tasks),
binary.getVariantData());
}
});
}
/**
* Create tasks that must be created after other tasks for variants are created.
*/
@Mutate
public void createRemainingTasks(
ModelMap<Task> tasks,
TaskManager taskManager,
ModelMap<AndroidComponentSpec> spec) {
VariantManager variantManager =
((DefaultAndroidComponentSpec)spec.get(COMPONENT_NAME)).getVariantManager();
// create the test tasks.
taskManager.createTopLevelTestTasks(new TaskModelMapAdaptor(tasks),
!variantManager.getProductFlavors().isEmpty());
}
@Mutate
public void createReportTasks(
ModelMap<Task> tasks,
ModelMap<AndroidComponentSpec> specs) {
final VariantManager variantManager =
((DefaultAndroidComponentSpec)specs.get(COMPONENT_NAME)).getVariantManager();
tasks.create("androidDependencies", DependencyReportTask.class,
new Action<DependencyReportTask>() {
@Override
public void execute(DependencyReportTask dependencyReportTask) {
dependencyReportTask.setDescription(
"Displays the Android dependencies of the project");
dependencyReportTask.setVariants(variantManager.getVariantDataList());
dependencyReportTask.setGroup("Android");
}
});
tasks.create("signingReport", SigningReportTask.class,
new Action<SigningReportTask>() {
@Override
public void execute(SigningReportTask signingReportTask) {
signingReportTask
.setDescription("Displays the signing info for each variant");
signingReportTask.setVariants(variantManager.getVariantDataList());
signingReportTask.setGroup("Android");
}
});
}
@Mutate
public void modifyAssembleTaskDescription(@Path("tasks.assemble") Task assembleTask) {
assembleTask.setDescription(
"Assembles all variants of all applications and secondary packages.");
}
}
}
| |
/* 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.flowable.dmn.editor.converter;
import java.awt.Shape;
import java.awt.geom.Area;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.flowable.dmn.editor.constants.DmnStencilConstants;
import org.flowable.dmn.editor.constants.EditorJsonConstants;
import org.flowable.dmn.model.GraphicInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* @author Yvo Swillens
*/
public class DmnJsonConverterUtil implements EditorJsonConstants, DmnStencilConstants {
protected static final Logger LOGGER = LoggerFactory.getLogger(DmnJsonConverterUtil.class);
protected static final ObjectMapper objectMapper = new ObjectMapper();
protected static double lineWidth = 0.05d;
public static String getValueAsString(String name, JsonNode objectNode) {
String propertyValue = null;
JsonNode jsonNode = objectNode.get(name);
if (jsonNode != null && !jsonNode.isNull()) {
propertyValue = jsonNode.asText();
}
return propertyValue;
}
public static boolean migrateModel(JsonNode decisionTableNode, ObjectMapper objectMapper) {
boolean wasMigrated = false;
// check if model is version 1
if ((decisionTableNode.get("modelVersion") == null || decisionTableNode.get("modelVersion").isNull()) && decisionTableNode.has("name")) {
wasMigrated = true;
String modelName = decisionTableNode.get("name").asText();
LOGGER.info("Decision table model with name {} found with version < v2; migrating to v3", modelName);
ObjectNode decisionTableObjectNode = (ObjectNode) decisionTableNode;
decisionTableObjectNode.put("modelVersion", "3");
// split input rule nodes into operator and expression nodes
//
// determine input node ids
JsonNode inputExpressionNodes = decisionTableNode.get("inputExpressions");
Map<String, String> inputExpressionIds = new HashMap<>();
if (inputExpressionNodes != null && !inputExpressionNodes.isNull()) {
for (JsonNode inputExpressionNode : inputExpressionNodes) {
if (inputExpressionNode.get("id") != null && !inputExpressionNode.get("id").isNull()) {
String inputId = inputExpressionNode.get("id").asText();
String inputType = null;
if (inputExpressionNode.get("type") != null && !inputExpressionNode.get("type").isNull()) {
inputType = inputExpressionNode.get("type").asText();
}
inputExpressionIds.put(inputId, inputType);
}
}
}
// split input rule nodes
JsonNode ruleNodes = decisionTableNode.get("rules");
ArrayNode newRuleNodes = objectMapper.createArrayNode();
if (ruleNodes != null && !ruleNodes.isNull()) {
for (JsonNode ruleNode : ruleNodes) {
ObjectNode newRuleNode = objectMapper.createObjectNode();
for (String inputExpressionId : inputExpressionIds.keySet()) {
if (ruleNode.has(inputExpressionId)) {
String operatorId = inputExpressionId + "_operator";
String expressionId = inputExpressionId + "_expression";
String operatorValue = null;
String expressionValue = null;
if (ruleNode.get(inputExpressionId) != null && !ruleNode.get(inputExpressionId).isNull()) {
String oldExpression = ruleNode.get(inputExpressionId).asText();
if (StringUtils.isNotEmpty(oldExpression)) {
if (oldExpression.indexOf(' ') != -1) {
operatorValue = oldExpression.substring(0, oldExpression.indexOf(' '));
expressionValue = oldExpression.substring(oldExpression.indexOf(' ') + 1);
} else { // no prefixed operator
expressionValue = oldExpression;
}
// remove outer escape quotes
if (expressionValue.startsWith("\"") && expressionValue.endsWith("\"")) {
expressionValue = expressionValue.substring(1, expressionValue.length() - 1);
}
// if build in date function
if (expressionValue.startsWith("fn_date(")) {
expressionValue = expressionValue.substring(9, expressionValue.lastIndexOf('\''));
} else if (expressionValue.startsWith("date:toDate(")) {
expressionValue = expressionValue.substring(13, expressionValue.lastIndexOf('\''));
}
// determine type is null
if (StringUtils.isEmpty(inputExpressionIds.get(inputExpressionId))) {
String expressionType = determineExpressionType(expressionValue);
inputExpressionIds.put(inputExpressionId, expressionType);
}
}
}
// add new operator kv
if (StringUtils.isNotEmpty(operatorValue)) {
newRuleNode.put(operatorId, operatorValue);
} else { // default value
newRuleNode.put(operatorId, "==");
}
// add new expression kv
if (StringUtils.isNotEmpty(expressionValue)) {
newRuleNode.put(expressionId, expressionValue);
} else { // default value
newRuleNode.put(expressionId, "-");
}
}
}
Iterator<String> ruleProperty = ruleNode.fieldNames();
while (ruleProperty.hasNext()) {
String expressionId = ruleProperty.next();
if (!inputExpressionIds.containsKey(expressionId)) {
if (ruleNode.hasNonNull(expressionId)) {
String expressionValue = ruleNode.get(expressionId).asText();
// remove outer escape quotes
if (StringUtils.isNotEmpty(expressionValue) && expressionValue.startsWith("\"") && expressionValue
.endsWith("\"")) {
expressionValue = expressionValue.substring(1, expressionValue.length() - 1);
}
// if build in date function
if (expressionValue.startsWith("fn_date(")) {
expressionValue = expressionValue.substring(9, expressionValue.lastIndexOf('\''));
} else if (expressionValue.startsWith("date:toDate(")) {
expressionValue = expressionValue.substring(13, expressionValue.lastIndexOf('\''));
}
newRuleNode.put(expressionId, expressionValue);
}
}
}
newRuleNodes.add(newRuleNode);
}
// set input expression nodes types
if (inputExpressionNodes != null && !inputExpressionNodes.isNull()) {
for (JsonNode inputExpressionNode : inputExpressionNodes) {
if (inputExpressionNode.get("id") != null && !inputExpressionNode.get("id").isNull()) {
String inputId = inputExpressionNode.get("id").asText();
((ObjectNode) inputExpressionNode).put("type", inputExpressionIds.get(inputId));
}
}
}
// replace rules node
decisionTableObjectNode.replace("rules", newRuleNodes);
}
LOGGER.info("Decision table model {} migrated to v3", modelName);
}
return wasMigrated;
}
public static boolean migrateModelV3(JsonNode decisionTableNode, ObjectMapper objectMapper) {
// migrate to v2
boolean wasMigrated = migrateModel(decisionTableNode, objectMapper);
// migrate to v3
if (decisionTableNode.has("modelVersion") && "2".equals(decisionTableNode.get("modelVersion").asText()) && decisionTableNode.has("name")) {
wasMigrated = true;
String modelName = decisionTableNode.get("name").asText();
LOGGER.info("Decision table model {} found with version v2; migrating to v3", modelName);
ObjectNode decisionTableObjectNode = (ObjectNode) decisionTableNode;
decisionTableObjectNode.put("modelVersion", "3");
JsonNode inputExpressionNodes = decisionTableNode.get("inputExpressions");
Map<String, String> inputExpressionIds = new HashMap<>();
if (inputExpressionNodes != null && !inputExpressionNodes.isNull()) {
for (JsonNode inputExpressionNode : inputExpressionNodes) {
if (inputExpressionNode.get("id") != null && !inputExpressionNode.get("id").isNull()) {
String inputId = inputExpressionNode.get("id").asText();
String inputType = null;
if (inputExpressionNode.get("type") != null && !inputExpressionNode.get("type").isNull()) {
inputType = inputExpressionNode.get("type").asText();
}
inputExpressionIds.put(inputId, inputType);
}
}
}
// split input rule nodes
JsonNode ruleNodes = decisionTableNode.get("rules");
if (ruleNodes != null && !ruleNodes.isNull()) {
for (JsonNode ruleNode : ruleNodes) {
for (String inputExpressionId : inputExpressionIds.keySet()) {
// get operator
String inputExpressionOperatorId = inputExpressionId + "_operator";
if (ruleNode.has(inputExpressionOperatorId)) {
if (ruleNode.get(inputExpressionOperatorId) != null && !ruleNode.get(inputExpressionOperatorId).isNull()) {
String oldInputExpressionOperatorValue = ruleNode.get(inputExpressionOperatorId).asText();
String inputType = inputExpressionIds.get(inputExpressionId);
try {
String newInputExpressionOperatorValue = transformCollectionOperation(oldInputExpressionOperatorValue, inputType);
// replace operator value
((ObjectNode) ruleNode).put(inputExpressionOperatorId, newInputExpressionOperatorValue);
} catch (IllegalArgumentException iae) {
LOGGER.warn("Skipping model migration; could not transform collection operator for model name: {}", modelName, iae);
}
}
}
}
}
}
LOGGER.info("Decision table model {} migrated to v3", modelName);
}
return wasMigrated;
}
public static String determineExpressionType(String expressionValue) {
String expressionType = null;
if (!"-".equals(expressionValue)) {
expressionType = "string";
if (NumberUtils.isCreatable(expressionValue)) {
expressionType = "number";
} else {
try {
new SimpleDateFormat("yyyy-MM-dd").parse(expressionValue);
expressionType = "date";
} catch (ParseException pe) {
if ("true".equalsIgnoreCase(expressionValue) || "false".equalsIgnoreCase(expressionValue)) {
expressionType = "boolean";
}
}
}
}
return expressionType;
}
public static String formatCollectionExpression(String containsOperator, String inputVariable, String expressionValue) {
String containsPrefixAndMethod = getDMNContainsExpressionMethod(containsOperator);
StringBuilder stringBuilder = new StringBuilder();
if (containsPrefixAndMethod != null) {
stringBuilder.append("${");
stringBuilder.append(containsPrefixAndMethod);
stringBuilder.append("(");
stringBuilder.append(formatCollectionExpressionValue(inputVariable));
stringBuilder.append(", ");
String formattedExpressionValue = formatCollectionExpressionValue(expressionValue);
stringBuilder.append(formattedExpressionValue);
stringBuilder.append(")}");
} else {
stringBuilder.append(containsOperator);
stringBuilder.append(" ");
stringBuilder.append(formatCollectionExpressionValue(expressionValue));
}
return stringBuilder.toString();
}
public static boolean isCollectionOperator(String operator) {
return "IN".equals(operator) || "NOT IN".equals(operator) || "ANY".equals(operator) || "NOT ANY".equals(operator) ||
"IS IN".equals(operator) || "IS NOT IN".equals(operator) ||
"NONE OF".equals(operator) || "NOT ALL OF".equals(operator) || "ALL OF".equals(operator);
}
public static boolean isDRD(JsonNode definitionNode) {
return definitionNode.has("childShapes");
}
public static String getStencilId(JsonNode objectNode) {
String stencilId = null;
JsonNode stencilNode = objectNode.get(EDITOR_STENCIL);
if (stencilNode != null && stencilNode.get(EDITOR_STENCIL_ID) != null) {
stencilId = stencilNode.get(EDITOR_STENCIL_ID).asText();
}
return stencilId;
}
public static String getElementId(JsonNode objectNode) {
String elementId = null;
if (StringUtils.isNotEmpty(getPropertyValueAsString(PROPERTY_OVERRIDE_ID, objectNode))) {
elementId = getPropertyValueAsString(PROPERTY_OVERRIDE_ID, objectNode).trim();
} else {
elementId = objectNode.get(EDITOR_SHAPE_ID).asText();
}
return elementId;
}
public static String getUniqueElementId() {
return getUniqueElementId(null);
}
public static String getUniqueElementId(String prefix) {
UUID uuid = UUID.randomUUID();
if (StringUtils.isEmpty(prefix)) {
return uuid.toString();
} else {
return String.format("%s_%s", prefix, uuid);
}
}
public static String getPropertyValueAsString(String name, JsonNode objectNode) {
String propertyValue = null;
JsonNode propertyNode = getProperty(name, objectNode);
if (propertyNode != null && !propertyNode.isNull()) {
propertyValue = propertyNode.asText();
}
return propertyValue;
}
public static JsonNode getProperty(String name, JsonNode objectNode) {
JsonNode propertyNode = null;
if (objectNode.get(EDITOR_SHAPE_PROPERTIES) != null) {
JsonNode propertiesNode = objectNode.get(EDITOR_SHAPE_PROPERTIES);
propertyNode = propertiesNode.get(name);
}
return propertyNode;
}
public static ObjectNode createChildShape(String id, String type, double lowerRightX, double lowerRightY, double upperLeftX, double upperLeftY) {
ObjectNode shapeNode = objectMapper.createObjectNode();
shapeNode.set(EDITOR_BOUNDS, createBoundsNode(lowerRightX, lowerRightY, upperLeftX, upperLeftY));
shapeNode.put(EDITOR_SHAPE_ID, id);
ArrayNode shapesArrayNode = objectMapper.createArrayNode();
shapeNode.set(EDITOR_CHILD_SHAPES, shapesArrayNode);
ObjectNode stencilNode = objectMapper.createObjectNode();
stencilNode.put(EDITOR_STENCIL_ID, type);
shapeNode.set(EDITOR_STENCIL, stencilNode);
shapeNode.putArray(EDITOR_OUTGOING);
shapeNode.putArray(EDITOR_DOCKERS);
return shapeNode;
}
public static ObjectNode createBoundsNode(double lowerRightX, double lowerRightY, double upperLeftX, double upperLeftY) {
ObjectNode boundsNode = objectMapper.createObjectNode();
boundsNode.set(EDITOR_BOUNDS_LOWER_RIGHT, createPositionNode(lowerRightX, lowerRightY));
boundsNode.set(EDITOR_BOUNDS_UPPER_LEFT, createPositionNode(upperLeftX, upperLeftY));
return boundsNode;
}
public static ObjectNode createPositionNode(double x, double y) {
ObjectNode positionNode = objectMapper.createObjectNode();
positionNode.put(EDITOR_BOUNDS_X, x);
positionNode.put(EDITOR_BOUNDS_Y, y);
return positionNode;
}
public static Area createRectangle(GraphicInfo graphicInfo) {
Area outerRectangle = new Area(new Rectangle2D.Double(
graphicInfo.getX(), graphicInfo.getY(),
graphicInfo.getWidth(), graphicInfo.getHeight()
));
Area innerRectangle = new Area(new Rectangle2D.Double(
graphicInfo.getX() + lineWidth, graphicInfo.getY() + lineWidth,
graphicInfo.getWidth() - 2*lineWidth, graphicInfo.getHeight() - 2*lineWidth
));
outerRectangle.subtract(innerRectangle);
return outerRectangle;
}
public static GraphicInfo createGraphicInfo(double x, double y) {
GraphicInfo graphicInfo = new GraphicInfo();
graphicInfo.setX(x);
graphicInfo.setY(y);
return graphicInfo;
}
public static Collection<Point2D> getIntersections(java.awt.geom.Line2D line, Area shape) {
Area intersectionArea = new Area(getLineShape(line));
intersectionArea.intersect(shape);
if (!intersectionArea.isEmpty()) {
Rectangle2D bounds2D = intersectionArea.getBounds2D();
HashSet<Point2D> intersections = new HashSet<>(1);
intersections.add(new java.awt.geom.Point2D.Double(bounds2D.getX(), bounds2D.getY()));
return intersections;
}
return Collections.EMPTY_SET;
}
public static Shape getLineShape(java.awt.geom.Line2D line2D) {
Path2D line = new Path2D.Double(Path2D.WIND_NON_ZERO, 4);
line.moveTo(line2D.getX1(), line2D.getY1());
line.lineTo(line2D.getX2(), line2D.getY2());
line.lineTo(line2D.getX2() + lineWidth, line2D.getY2() + lineWidth);
line.closePath();
return line;
}
public static List<JsonLookupResult> getDmnModelChildShapesPropertyValues(JsonNode editorJsonNode, String propertyName, List<String> allowedStencilTypes) {
List<JsonLookupResult> result = new ArrayList<>();
internalGetDmnChildShapePropertyValues(editorJsonNode, propertyName, allowedStencilTypes, result);
return result;
}
public static List<JsonNode> filterOutJsonNodes(List<JsonLookupResult> lookupResults) {
List<JsonNode> jsonNodes = new ArrayList<>(lookupResults.size());
for (JsonLookupResult lookupResult : lookupResults) {
jsonNodes.add(lookupResult.getJsonNode());
}
return jsonNodes;
}
public static List<JsonLookupResult> getDmnModelDecisionTableReferences(ObjectNode editorJsonNode) {
List<String> allowedStencilTypes = new ArrayList<>();
allowedStencilTypes.add(STENCIL_DECISION);
return getDmnModelChildShapesPropertyValues(editorJsonNode, PROPERTY_DECISION_TABLE_REFERENCE, allowedStencilTypes);
}
public static void updateDecisionTableModelReferences(ObjectNode decisionServiceObjectNode, DmnJsonConverterContext converterContext) {
List<JsonNode> decisionTableNodes = DmnJsonConverterUtil.filterOutJsonNodes(DmnJsonConverterUtil.getDmnModelDecisionTableReferences(decisionServiceObjectNode));
decisionTableNodes.forEach(decisionNode -> {
String decisionTableKey = decisionNode.get("key").asText();
Map<String, String> modelInfo = converterContext.getDecisionTableModelInfoForDecisionTableModelKey(decisionTableKey);
if (modelInfo != null) {
((ObjectNode) decisionNode).put("id", modelInfo.get("id"));
}
});
}
protected static void internalGetDmnChildShapePropertyValues(JsonNode editorJsonNode, String propertyName,
List<String> allowedStencilTypes, List<JsonLookupResult> result) {
JsonNode childShapesNode = editorJsonNode.get("childShapes");
if (childShapesNode != null && childShapesNode.isArray()) {
ArrayNode childShapesArrayNode = (ArrayNode) childShapesNode;
Iterator<JsonNode> childShapeNodeIterator = childShapesArrayNode.iterator();
while (childShapeNodeIterator.hasNext()) {
JsonNode childShapeNode = childShapeNodeIterator.next();
String childShapeNodeStencilId = DmnJsonConverterUtil.getStencilId(childShapeNode);
boolean readPropertiesNode = allowedStencilTypes.contains(childShapeNodeStencilId);
if (readPropertiesNode) {
// Properties
JsonNode properties = childShapeNode.get("properties");
if (properties != null && properties.has(propertyName)) {
JsonNode nameNode = properties.get("name");
JsonNode propertyNode = properties.get(propertyName);
result.add(new JsonLookupResult(DmnJsonConverterUtil.getElementId(childShapeNode),
nameNode != null ? nameNode.asText() : null, propertyNode));
}
}
// Potential nested child shapes
if (childShapeNode.has("childShapes")) {
internalGetDmnChildShapePropertyValues(childShapeNode, propertyName, allowedStencilTypes, result);
}
}
}
}
protected static String getDMNContainsExpressionMethod(String containsOperator) {
if (StringUtils.isEmpty(containsOperator)) {
throw new IllegalArgumentException("containsOperator must be provided");
}
String containsPrefixAndMethod;
switch (containsOperator) {
case "IS IN":
case "ALL OF":
case "IN":
containsPrefixAndMethod = "collection:allOf";
break;
case "IS NOT IN":
case "NONE OF":
case "NOT IN":
containsPrefixAndMethod = "collection:noneOf";
break;
case "ANY OF":
case "ANY":
containsPrefixAndMethod = "collection:anyOf";
break;
case "NOT ALL OF":
case "NOT ANY":
containsPrefixAndMethod = "collection:notAllOf";
break;
default:
containsPrefixAndMethod = null;
}
return containsPrefixAndMethod;
}
protected static String formatCollectionExpressionValue(String expressionValue) {
if (StringUtils.isEmpty(expressionValue)) {
return "\"\"";
}
StringBuilder formattedExpressionValue = new StringBuilder();
// if multiple values
if (expressionValue.contains(",")) {
formattedExpressionValue.append("'");
List<String> formattedValues = split(expressionValue);
formattedExpressionValue.append(StringUtils.join(formattedValues, ','));
} else {
String formattedValue = expressionValue;
formattedExpressionValue.append(formattedValue);
}
// if multiple values
if (expressionValue.contains(",")) {
formattedExpressionValue.append("'");
}
return formattedExpressionValue.toString();
}
protected static List<String> split(String str) {
String regex;
if (str.contains("\"")) {
// only split on comma between matching quotes
regex = ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)";
} else {
regex = ",";
}
return Stream.of(str.split(regex))
.map(elem -> elem.trim())
.collect(Collectors.toList());
}
protected static String transformCollectionOperation(String operatorValue, String inputType) {
if (StringUtils.isEmpty(operatorValue) || StringUtils.isEmpty(inputType)) {
throw new IllegalArgumentException("operator value and input type must be present");
}
if ("collection".equalsIgnoreCase(inputType)) {
switch (operatorValue) {
case "IN":
return "ALL OF";
case "NOT IN":
return "NONE OF";
case "ANY":
return "ANY OF";
case "NOT ANY":
return "NOT ALL OF";
default:
return operatorValue;
}
} else {
switch (operatorValue) {
case "IN":
return "IS IN";
case "NOT IN":
return "IS NOT IN";
case "ANY":
return "IS IN";
case "NOT ANY":
return "IS NOT IN";
default:
return operatorValue;
}
}
}
// Helper classes
public static class JsonLookupResult {
private String id;
private String name;
private JsonNode jsonNode;
public JsonLookupResult(String id, String name, JsonNode jsonNode) {
this(name, jsonNode);
this.id = id;
}
public JsonLookupResult(String name, JsonNode jsonNode) {
this.name = name;
this.jsonNode = jsonNode;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public JsonNode getJsonNode() {
return jsonNode;
}
public void setJsonNode(JsonNode jsonNode) {
this.jsonNode = jsonNode;
}
}
}
| |
/**
* 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 fr.ritaly.dungeonmaster;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import fr.ritaly.dungeonmaster.stat.Stats;
/**
* Enumerates the possible champion skills. A {@link Skill} is either "basic" or
* "hidden". There are 4 basic skills ({@link #FIGHTER}, {@link #NINJA},
* {@link #PRIEST} and {@link #WIZARD}) and 16 hidden skills (4 per basic
* skill).<br>
* <br>
* Source: <a href="http://dmweb.free.fr/?q=node/691">Technical Documentation -
* Dungeon Master and Chaos Strikes Back Skills and Statistics</a>
*
* @author <a href="mailto:francois.ritaly@gmail.com">Francois RITALY</a>
*/
public enum Skill {
/** Basic skill */
FIGHTER,
/** Basic skill */
NINJA,
/** Basic skill */
PRIEST,
/** Basic skill */
WIZARD,
/** Hidden fighter skills */
SWING,
/** Hidden fighter skills */
THRUST,
/** Hidden fighter skills */
CLUB,
/** Hidden fighter skills */
PARRY,
/** Hidden ninja skills */
STEAL,
/** Hidden ninja skills */
FIGHT,
/** Hidden ninja skills */
THROW,
/** Hidden ninja skills */
SHOOT,
/** Hidden priest skills */
IDENTIFY,
/** Hidden priest skills */
HEAL,
/** Hidden priest skills */
INFLUENCE,
/** Hidden priest skills */
DEFEND,
/** Hidden wizard skills */
FIRE,
/** Hidden wizard skills */
AIR,
/** Hidden wizard skills */
EARTH,
/** Hidden wizard skills */
WATER;
/**
* Tells whether this {@link Skill} is basic (or hidden).
*
* @return whether this {@link Skill} is basic (or hidden).
*/
public boolean isBasic() {
switch (this) {
case FIGHTER:
case NINJA:
case PRIEST:
case WIZARD:
return true;
default:
return false;
}
}
/**
* Tells whether this {@link Skill} is hidden (or basic).
*
* @return whether this {@link Skill} is hidden (or basic).
*/
public boolean isHidden() {
return !isBasic();
}
/**
* Returns the basic {@link Skill} mapped to this hidden {@link Skill}. This
* method throws an {@link UnsupportedOperationException} if this skill
* isn't basic.
*
* @return a {@link Skill}.
*/
public Skill getRelatedSkill() {
if (isBasic()) {
throw new UnsupportedOperationException();
}
switch (this) {
case SWING:
case THRUST:
case CLUB:
case PARRY:
return FIGHTER;
case STEAL:
case FIGHT:
case THROW:
case SHOOT:
return NINJA;
case IDENTIFY:
case HEAL:
case INFLUENCE:
case DEFEND:
return PRIEST;
case FIRE:
case AIR:
case EARTH:
case WATER:
return WIZARD;
default:
throw new UnsupportedOperationException();
}
}
/**
* Tells whether the champion's strength improves when the champion gains a
* new level of this {@link Skill}.
*
* @return whether the champion's strength improves when the champion gains
* a new level of this {@link Skill}.
*/
boolean improvesStrength() {
return equals(FIGHTER) || equals(NINJA);
}
/**
* Tells whether the champion's dexterity improves when the champion gains a
* new level of this {@link Skill}.
*
* @return whether the champion's dexterity improves when the champion gains
* a new level of this {@link Skill}.
*/
boolean improvesDexterity() {
return equals(FIGHTER) || equals(NINJA);
}
/**
* Tells whether the champion's mana improves when the champion gains a new
* level of this {@link Skill}.
*
* @return whether the champion's mana improves when the champion gains a
* new level of this {@link Skill}.
*/
boolean improvesMana() {
return equals(PRIEST) || equals(WIZARD);
}
/**
* Tells whether the champion's wisdom improves when the champion gains a
* new level of this {@link Skill}.
*
* @return whether the champion's wisdom improves when the champion gains a
* new level of this {@link Skill}.
*/
boolean improvesWisdom() {
return equals(PRIEST) || equals(WIZARD);
}
/**
* Tells whether the champion's anti-magic improves when the champion gains
* a new level of this {@link Skill}.
*
* @return whether the champion's anti-magic improves when the champion
* gains a new level of this {@link Skill}.
*/
boolean improvesAntiMagic() {
return equals(PRIEST) || equals(WIZARD);
}
/**
* Tells whether the champion's health improves when the champion gains a
* new level of this {@link Skill}.
*
* @return whether the champion's health improves when the champion gains a
* new level of this {@link Skill}.
*/
boolean improvesHealth() {
return true;
}
/**
* Tells whether the champion's stamina improves when the champion gains a
* new level of this {@link Skill}.
*
* @return whether the champion's stamina improves when the champion gains a
* new level of this {@link Skill}.
*/
boolean improvesStamina() {
return true;
}
/**
* Tells whether the champion's vitality improves when the champion gains a
* new level of this {@link Skill}.
*
* @return whether the champion's vitality improves when the champion gains
* a new level of this {@link Skill}.
*/
boolean improvesVitality() {
return true;
}
/**
* Tells whether the champion's anti-fire improves when the champion gains a
* new level of this {@link Skill}.
*
* @return whether the champion's anti-fire improves when the champion gains
* a new level of this {@link Skill}.
*/
boolean improvesAntiFire() {
return true;
}
/**
* Returns this {@link Skill}'s label. Example: Returns "Ninja" for the
* {@link #NINJA} skill.
*
* @return a {@link String}.
*/
public String getLabel() {
return StringUtils.capitalize(name().toLowerCase());
}
/**
* Randomly improves the given stats. The stats improved depend on the
* skill.
*
* @param stats
* the stats to improve. Can't be null.
*/
public void improve(Stats stats) {
Validate.notNull(stats, "The given stats is null");
if (improvesHealth()) {
final int healthBonus = Utils.random(5, 15);
stats.getHealth().incMax(healthBonus);
stats.getHealth().inc(healthBonus);
}
if (improvesStamina()) {
final int staminaBonus = Utils.random(5, 15);
stats.getStamina().incMax(staminaBonus);
stats.getStamina().inc(staminaBonus);
}
if (improvesVitality()) {
final int vitalityBonus = Utils.random(5, 15);
stats.getVitality().incMax(vitalityBonus);
stats.getVitality().inc(vitalityBonus);
}
if (improvesAntiFire()) {
final int antiFireBonus = Utils.random(5, 15);
stats.getAntiFire().incMax(antiFireBonus);
stats.getAntiFire().inc(antiFireBonus);
}
if (improvesStrength()) {
final int strengthBonus = Utils.random(5, 15);
stats.getStrength().incMax(strengthBonus);
stats.getStrength().inc(strengthBonus);
}
if (improvesDexterity()) {
final int dexterityBonus = Utils.random(5, 15);
stats.getDexterity().incMax(dexterityBonus);
stats.getDexterity().inc(dexterityBonus);
}
if (improvesMana()) {
final int manaBonus = Utils.random(5, 15);
stats.getMana().incMax(manaBonus);
stats.getMana().inc(manaBonus);
}
if (improvesWisdom()) {
final int wisdomBonus = Utils.random(5, 15);
stats.getWisdom().incMax(wisdomBonus);
stats.getWisdom().inc(wisdomBonus);
}
if (improvesAntiMagic()) {
final int antiMagicBonus = Utils.random(5, 15);
stats.getAntiMagic().incMax(antiMagicBonus);
stats.getAntiMagic().inc(antiMagicBonus);
}
}
}
| |
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.android;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ResourceSet;
import com.google.devtools.build.lib.analysis.AnalysisUtils;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.OutputGroupProvider;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.analysis.actions.FileWriteAction;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.collect.IterablesChain;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.packages.AggregatingAttributeMapper;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.rules.android.AndroidRuleClasses.MultidexMode;
import com.google.devtools.build.lib.rules.android.ResourceContainer.ResourceType;
import com.google.devtools.build.lib.rules.cpp.CcLinkParams;
import com.google.devtools.build.lib.rules.cpp.CcLinkParamsProvider;
import com.google.devtools.build.lib.rules.cpp.CcLinkParamsStore;
import com.google.devtools.build.lib.rules.java.ClasspathConfiguredFragment;
import com.google.devtools.build.lib.rules.java.JavaCcLinkParamsProvider;
import com.google.devtools.build.lib.rules.java.JavaCommon;
import com.google.devtools.build.lib.rules.java.JavaCompilationArgs;
import com.google.devtools.build.lib.rules.java.JavaCompilationArgs.ClasspathType;
import com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider;
import com.google.devtools.build.lib.rules.java.JavaCompilationArtifacts;
import com.google.devtools.build.lib.rules.java.JavaCompilationHelper;
import com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider;
import com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider.OutputJar;
import com.google.devtools.build.lib.rules.java.JavaRuntimeJarProvider;
import com.google.devtools.build.lib.rules.java.JavaSemantics;
import com.google.devtools.build.lib.rules.java.JavaSkylarkApiProvider;
import com.google.devtools.build.lib.rules.java.JavaSourceJarsProvider;
import com.google.devtools.build.lib.rules.java.JavaTargetAttributes;
import com.google.devtools.build.lib.rules.java.JavaUtil;
import com.google.devtools.build.lib.rules.java.proto.GeneratedExtensionRegistryProvider;
import com.google.devtools.build.lib.rules.test.InstrumentedFilesCollector.InstrumentationSpec;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A helper class for android rules.
*
* <p>Helps create the java compilation as well as handling the exporting of the java compilation
* artifacts to the other rules.
*/
public class AndroidCommon {
public static final InstrumentationSpec ANDROID_COLLECTION_SPEC = JavaCommon.JAVA_COLLECTION_SPEC
.withDependencyAttributes("deps", "data", "exports", "runtime_deps", "binary_under_test");
public static final Set<String> TRANSITIVE_ATTRIBUTES = ImmutableSet.of(
"deps",
"exports"
);
public static final <T extends TransitiveInfoProvider> Iterable<T> getTransitivePrerequisites(
RuleContext ruleContext, Mode mode, final Class<T> classType) {
IterablesChain.Builder<T> builder = IterablesChain.builder();
AttributeMap attributes = ruleContext.attributes();
for (String attr : TRANSITIVE_ATTRIBUTES) {
if (attributes.has(attr, BuildType.LABEL_LIST)) {
builder.add(ruleContext.getPrerequisites(attr, mode, classType));
}
}
return builder.build();
}
public static final Iterable<TransitiveInfoCollection> collectTransitiveInfo(
RuleContext ruleContext, Mode mode) {
ImmutableList.Builder<TransitiveInfoCollection> builder = ImmutableList.builder();
for (String attr : TRANSITIVE_ATTRIBUTES) {
if (ruleContext.attributes().has(attr, BuildType.LABEL_LIST)) {
builder.addAll(ruleContext.getPrerequisites(attr, mode));
}
}
return builder.build();
}
private final RuleContext ruleContext;
private final JavaCommon javaCommon;
private final boolean asNeverLink;
private final boolean exportDeps;
private NestedSet<Artifact> compileTimeDependencyArtifacts;
private NestedSet<Artifact> filesToBuild;
private NestedSet<Artifact> transitiveNeverlinkLibraries =
NestedSetBuilder.emptySet(Order.STABLE_ORDER);
private JavaCompilationArgs javaCompilationArgs = JavaCompilationArgs.EMPTY_ARGS;
private JavaCompilationArgs recursiveJavaCompilationArgs = JavaCompilationArgs.EMPTY_ARGS;
private JackCompilationHelper jackCompilationHelper;
private NestedSet<Artifact> jarsProducedForRuntime;
private Artifact classJar;
private Artifact iJar;
private Artifact srcJar;
private Artifact genClassJar;
private Artifact genSourceJar;
private Artifact resourceClassJar;
private Artifact resourceSourceJar;
private Artifact outputDepsProto;
private GeneratedExtensionRegistryProvider generatedExtensionRegistryProvider;
private final JavaSourceJarsProvider.Builder javaSourceJarsProviderBuilder =
JavaSourceJarsProvider.builder();
private final JavaRuleOutputJarsProvider.Builder javaRuleOutputJarsProviderBuilder =
JavaRuleOutputJarsProvider.builder();
private Artifact manifestProtoOutput;
private AndroidIdlHelper idlHelper;
public AndroidCommon(JavaCommon javaCommon) {
this(javaCommon, JavaCommon.isNeverLink(javaCommon.getRuleContext()), false);
}
/**
* Creates a new AndroidCommon.
* @param common the JavaCommon instance
* @param asNeverLink Boolean to indicate if this rule should be treated as a compile time dep
* by consuming rules.
* @param exportDeps Boolean to indicate if the dependencies should be treated as "exported" deps.
*/
public AndroidCommon(JavaCommon common, boolean asNeverLink, boolean exportDeps) {
this.ruleContext = common.getRuleContext();
this.asNeverLink = asNeverLink;
this.exportDeps = exportDeps;
this.javaCommon = common;
}
/**
* Collects the transitive neverlink dependencies.
*
* @param ruleContext the context of the rule neverlink deps are to be computed for
* @param deps the targets to be treated as dependencies
* @param runtimeJars the runtime jars produced by the rule (non-transitive)
*
* @return a nested set of the neverlink deps.
*/
public static NestedSet<Artifact> collectTransitiveNeverlinkLibraries(
RuleContext ruleContext, Iterable<? extends TransitiveInfoCollection> deps,
ImmutableList<Artifact> runtimeJars) {
NestedSetBuilder<Artifact> builder = NestedSetBuilder.naiveLinkOrder();
for (AndroidNeverLinkLibrariesProvider provider : AnalysisUtils.getProviders(deps,
AndroidNeverLinkLibrariesProvider.class)) {
builder.addTransitive(provider.getTransitiveNeverLinkLibraries());
}
if (JavaCommon.isNeverLink(ruleContext)) {
builder.addAll(runtimeJars);
for (JavaCompilationArgsProvider provider : AnalysisUtils.getProviders(
deps, JavaCompilationArgsProvider.class)) {
builder.addTransitive(provider.getRecursiveJavaCompilationArgs().getRuntimeJars());
}
}
return builder.build();
}
/**
* Creates an action that converts {@code jarToDex} to a dex file. The output will be stored in
* the {@link com.google.devtools.build.lib.actions.Artifact} {@code dxJar}.
*/
public static void createDexAction(
RuleContext ruleContext,
Artifact jarToDex, Artifact classesDex, List<String> dexOptions, boolean multidex,
Artifact mainDexList) {
List<String> args = new ArrayList<>();
args.add("--dex");
// Multithreaded dex does not work when using --multi-dex.
if (!multidex) {
// Multithreaded dex tends to run faster, but only up to about 5 threads (at which point the
// law of diminishing returns kicks in). This was determined experimentally, with 5-thread dex
// performing about 25% faster than 1-thread dex.
args.add("--num-threads=5");
}
args.addAll(dexOptions);
if (multidex) {
args.add("--multi-dex");
if (mainDexList != null) {
args.add("--main-dex-list=" + mainDexList.getExecPathString());
}
}
args.add("--output=" + classesDex.getExecPathString());
args.add(jarToDex.getExecPathString());
SpawnAction.Builder builder = new SpawnAction.Builder()
.setExecutable(AndroidSdkProvider.fromRuleContext(ruleContext).getDx())
.addInput(jarToDex)
.addOutput(classesDex)
.addArguments(args)
.setProgressMessage("Converting " + jarToDex.getExecPathString() + " to dex format")
.setMnemonic("AndroidDexer")
.setResources(ResourceSet.createWithRamCpuIo(4096.0, 5.0, 0.0));
if (mainDexList != null) {
builder.addInput(mainDexList);
}
ruleContext.registerAction(builder.build(ruleContext));
}
public static AndroidIdeInfoProvider createAndroidIdeInfoProvider(
RuleContext ruleContext,
AndroidSemantics semantics,
AndroidIdlHelper idlHelper,
OutputJar resourceJar,
Artifact aar,
ResourceApk resourceApk,
Artifact zipAlignedApk,
Iterable<Artifact> apksUnderTest) {
AndroidIdeInfoProvider.Builder ideInfoProviderBuilder =
new AndroidIdeInfoProvider.Builder()
.setIdlClassJar(idlHelper.getIdlClassJar())
.setIdlSourceJar(idlHelper.getIdlSourceJar())
.setResourceJar(resourceJar)
.setAar(aar)
.addIdlImportRoot(idlHelper.getIdlImportRoot())
.addIdlParcelables(idlHelper.getIdlParcelables())
.addIdlSrcs(idlHelper.getIdlSources())
.addIdlGeneratedJavaFiles(idlHelper.getIdlGeneratedJavaSources())
.addAllApksUnderTest(apksUnderTest);
if (zipAlignedApk != null) {
ideInfoProviderBuilder.setApk(zipAlignedApk);
}
// If the rule defines resources, put those in the IDE info. Otherwise, proxy the data coming
// from the android_resources rule in its direct dependencies, if such a thing exists.
if (LocalResourceContainer.definesAndroidResources(ruleContext.attributes())) {
ideInfoProviderBuilder
.setDefinesAndroidResources(true)
.addResourceSources(resourceApk.getPrimaryResource().getArtifacts(ResourceType.RESOURCES))
.addAssetSources(
resourceApk.getPrimaryResource().getArtifacts(ResourceType.ASSETS),
getAssetDir(ruleContext))
// Sets the possibly merged manifest and the raw manifest.
.setGeneratedManifest(resourceApk.getPrimaryResource().getManifest())
.setManifest(ruleContext.getPrerequisiteArtifact("manifest", Mode.TARGET))
.setJavaPackage(getJavaPackage(ruleContext));
} else {
semantics.addNonLocalResources(ruleContext, resourceApk, ideInfoProviderBuilder);
}
return ideInfoProviderBuilder.build();
}
public static String getJavaPackage(RuleContext ruleContext) {
AttributeMap attributes = ruleContext.attributes();
if (attributes.isAttributeValueExplicitlySpecified("custom_package")) {
return attributes.get("custom_package", Type.STRING);
}
return getDefaultJavaPackage(ruleContext.getRule());
}
public static Iterable<String> getPossibleJavaPackages(Rule rule) {
AggregatingAttributeMapper attributes = AggregatingAttributeMapper.of(rule);
if (attributes.isAttributeValueExplicitlySpecified("custom_package")) {
return attributes.visitAttribute("custom_package", Type.STRING);
}
return ImmutableList.of(getDefaultJavaPackage(rule));
}
private static String getDefaultJavaPackage(Rule rule) {
PathFragment nameFragment = rule.getPackage().getNameFragment();
String packageName = JavaUtil.getJavaFullClassname(nameFragment);
if (packageName != null) {
return packageName;
} else {
// This is a workaround for libraries that don't follow the standard Bazel package format
return nameFragment.getPathString().replace('/', '.');
}
}
static PathFragment getSourceDirectoryRelativePathFromResource(Artifact resource) {
PathFragment resourceDir = LocalResourceContainer.Builder.findResourceDir(resource);
if (resourceDir == null) {
return null;
}
return trimTo(resource.getRootRelativePath(), resourceDir);
}
/**
* Finds the rightmost occurrence of the needle and returns subfragment of the haystack from
* left to the end of the occurrence inclusive of the needle.
*
* <pre>
* `Example:
* Given the haystack:
* res/research/handwriting/res/values/strings.xml
* And the needle:
* res
* Returns:
* res/research/handwriting/res
* </pre>
*/
static PathFragment trimTo(PathFragment haystack, PathFragment needle) {
if (needle.equals(PathFragment.EMPTY_FRAGMENT)) {
return haystack;
}
// Compute the overlap offset for duplicated parts of the needle.
int[] overlap = new int[needle.segmentCount() + 1];
// Start overlap at -1, as it will cancel out the increment in the search.
// See http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm for the
// details.
overlap[0] = -1;
for (int i = 0, j = -1; i < needle.segmentCount(); j++, i++, overlap[i] = j) {
while (j >= 0 && !needle.getSegment(i).equals(needle.getSegment(j))) {
// Walk the overlap until the bound is found.
j = overlap[j];
}
}
// TODO(corysmith): reverse the search algorithm.
// Keep the index of the found so that the rightmost index is taken.
int found = -1;
for (int i = 0, j = 0; i < haystack.segmentCount(); i++) {
while (j >= 0 && !haystack.getSegment(i).equals(needle.getSegment(j))) {
// Not matching, walk the needle index to attempt another match.
j = overlap[j];
}
j++;
// Needle index is exhausted, so the needle must match.
if (j == needle.segmentCount()) {
// Record the found index + 1 to be inclusive of the end index.
found = i + 1;
// Subtract one from the needle index to restart the search process
j = j - 1;
}
}
if (found != -1) {
// Return the subsection of the haystack.
return haystack.subFragment(0, found);
}
throw new IllegalArgumentException(String.format("%s was not found in %s", needle, haystack));
}
public static NestedSetBuilder<Artifact> collectTransitiveNativeLibsZips(
RuleContext ruleContext) {
NestedSetBuilder<Artifact> transitiveAarNativeLibs = NestedSetBuilder.naiveLinkOrder();
Iterable<NativeLibsZipsProvider> providers = getTransitivePrerequisites(
ruleContext, Mode.TARGET, NativeLibsZipsProvider.class);
for (NativeLibsZipsProvider nativeLibsZipsProvider : providers) {
transitiveAarNativeLibs.addTransitive(nativeLibsZipsProvider.getAarNativeLibs());
}
return transitiveAarNativeLibs;
}
Artifact compileDexWithJack(
MultidexMode mode, Optional<Artifact> mainDexList, Collection<Artifact> proguardSpecs) {
return jackCompilationHelper.compileAsDex(mode, mainDexList, proguardSpecs);
}
private void compileResources(
JavaSemantics javaSemantics,
ResourceApk resourceApk,
Artifact resourcesJar,
JavaCompilationArtifacts.Builder artifactsBuilder,
JavaTargetAttributes.Builder attributes,
NestedSetBuilder<Artifact> filesBuilder,
NestedSetBuilder<Artifact> jarsProducedForRuntime,
boolean useRClassGenerator) throws InterruptedException {
compileResourceJar(javaSemantics, resourceApk, resourcesJar, useRClassGenerator);
// Add the compiled resource jar to the classpath of the main compilation.
attributes.addDirectJars(NestedSetBuilder.create(Order.STABLE_ORDER, resourceClassJar));
// Add the compiled resource jar to the classpath of consuming targets.
// We don't actually use the ijar. That is almost the same as the resource class jar
// except for <clinit>, but it takes time to build and waiting for that to build would
// just delay building the rest of the library.
artifactsBuilder.addCompileTimeJar(resourceClassJar);
// Combined resource constants needs to come even before our own classes that may contain
// local resource constants.
artifactsBuilder.addRuntimeJar(resourceClassJar);
jarsProducedForRuntime.add(resourceClassJar);
// Add the compiled resource jar as a declared output of the rule.
filesBuilder.add(resourceSourceJar);
filesBuilder.add(resourceClassJar);
}
private void compileResourceJar(
JavaSemantics javaSemantics, ResourceApk resourceApk, Artifact resourcesJar,
boolean useRClassGenerator)
throws InterruptedException {
resourceSourceJar = ruleContext.getImplicitOutputArtifact(
AndroidRuleClasses.ANDROID_RESOURCES_SOURCE_JAR);
resourceClassJar = ruleContext.getImplicitOutputArtifact(
AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR);
JavaCompilationArtifacts.Builder javaArtifactsBuilder = new JavaCompilationArtifacts.Builder();
JavaTargetAttributes.Builder javacAttributes = new JavaTargetAttributes.Builder(javaSemantics)
.addSourceJar(resourcesJar);
JavaCompilationHelper javacHelper = new JavaCompilationHelper(
ruleContext, javaSemantics, getJavacOpts(), javacAttributes);
// Only build the class jar if it's not already generated internally by resource processing.
if (resourceApk.getResourceJavaClassJar() == null) {
if (useRClassGenerator) {
RClassGeneratorActionBuilder actionBuilder =
new RClassGeneratorActionBuilder(ruleContext)
.withPrimary(resourceApk.getPrimaryResource())
.withDependencies(resourceApk.getResourceDependencies())
.setClassJarOut(resourceClassJar);
actionBuilder.build();
} else {
Artifact outputDepsProto =
javacHelper.createOutputDepsProtoArtifact(resourceClassJar, javaArtifactsBuilder);
javacHelper.createCompileActionWithInstrumentation(
resourceClassJar,
null /* manifestProtoOutput */,
null /* genSourceJar */,
outputDepsProto,
javaArtifactsBuilder);
}
} else {
// Otherwise, it should have been the AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR.
Preconditions.checkArgument(
resourceApk.getResourceJavaClassJar().equals(
ruleContext.getImplicitOutputArtifact(
AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR)));
}
javacHelper.createSourceJarAction(resourceSourceJar, null);
}
private void createJarJarActions(
JavaTargetAttributes.Builder attributes,
NestedSetBuilder<Artifact> jarsProducedForRuntime,
Iterable<ResourceContainer> resourceContainers,
String originalPackage,
Artifact binaryResourcesJar) {
// Now use jarjar for the rest of the resources. We need to make a copy
// of the final generated resources for each of the targets included in
// the transitive closure of this binary.
for (ResourceContainer otherContainer : resourceContainers) {
if (otherContainer.getLabel().equals(ruleContext.getLabel())) {
continue;
}
Artifact resourcesJar = createResourceJarArtifact(ruleContext, otherContainer, ".jar");
// combined resource constants copy needs to come before library classes that may contain
// their local resource constants
attributes.addRuntimeClassPathEntry(resourcesJar);
Artifact jarJarRuleFile = createResourceJarArtifact(
ruleContext, otherContainer, ".jar_jarjar_rules.txt");
String jarJarRule = String.format("rule %s.* %s.@1",
originalPackage, otherContainer.getJavaPackage());
ruleContext.registerAction(
FileWriteAction.create(ruleContext, jarJarRuleFile, jarJarRule, false));
FilesToRunProvider jarjar =
ruleContext.getExecutablePrerequisite("$jarjar_bin", Mode.HOST);
ruleContext.registerAction(new SpawnAction.Builder()
.setExecutable(jarjar)
.addArgument("process")
.addInputArgument(jarJarRuleFile)
.addInputArgument(binaryResourcesJar)
.addOutputArgument(resourcesJar)
.setProgressMessage("Repackaging jar")
.setMnemonic("AndroidRepackageJar")
.build(ruleContext));
jarsProducedForRuntime.add(resourcesJar);
}
}
private static Artifact createResourceJarArtifact(RuleContext ruleContext,
ResourceContainer container, String fileNameSuffix) {
String artifactName = container.getLabel().getName() + fileNameSuffix;
// Since the Java sources are generated by combining all resources with the
// ones included in the binary, the path of the artifact has to be unique
// per binary and per library (not only per library).
Artifact artifact = ruleContext.getUniqueDirectoryArtifact("resource_jars",
container.getLabel().getPackageIdentifier().getSourceRoot().getRelative(artifactName),
ruleContext.getBinOrGenfilesDirectory());
return artifact;
}
public JavaTargetAttributes init(
JavaSemantics javaSemantics,
AndroidSemantics androidSemantics,
ResourceApk resourceApk,
boolean addCoverageSupport,
boolean collectJavaCompilationArgs,
boolean isBinary)
throws InterruptedException {
classJar = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_CLASS_JAR);
idlHelper = new AndroidIdlHelper(ruleContext, classJar);
ImmutableList<Artifact> bootclasspath;
if (getAndroidConfig(ruleContext).desugarJava8()) {
bootclasspath = ImmutableList.<Artifact>builder()
.addAll(ruleContext.getPrerequisite("$desugar_java8_extra_bootclasspath", Mode.HOST)
.getProvider(FileProvider.class)
.getFilesToBuild())
.add(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar())
.build();
} else {
bootclasspath =
ImmutableList.of(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar());
}
JavaTargetAttributes.Builder attributes =
javaCommon
.initCommon(
idlHelper.getIdlGeneratedJavaSources(),
androidSemantics.getJavacArguments(ruleContext))
.setBootClassPath(bootclasspath);
if (DataBinding.isEnabled(ruleContext)) {
DataBinding.addAnnotationProcessor(ruleContext, attributes);
}
JavaCompilationArtifacts.Builder artifactsBuilder = new JavaCompilationArtifacts.Builder();
NestedSetBuilder<Artifact> jarsProducedForRuntime = NestedSetBuilder.<Artifact>stableOrder();
NestedSetBuilder<Artifact> filesBuilder = NestedSetBuilder.<Artifact>stableOrder();
Artifact resourcesJar = resourceApk.getResourceJavaSrcJar();
if (resourcesJar != null) {
filesBuilder.add(resourcesJar);
// Use a fast-path R class generator for android_binary with local resources, where there is
// a bottleneck. For legacy resources, the srcjar and R class compiler don't match up
// (the legacy srcjar requires the createJarJar step below).
boolean useRClassGenerator = isBinary && !resourceApk.isLegacy();
compileResources(javaSemantics, resourceApk, resourcesJar, artifactsBuilder, attributes,
filesBuilder, jarsProducedForRuntime, useRClassGenerator);
if (resourceApk.isLegacy()) {
// Repackages the R.java for each dependency package and places the resultant jars before
// the dependency libraries to ensure that the generated resource ids are correct.
createJarJarActions(attributes, jarsProducedForRuntime,
resourceApk.getResourceDependencies().getResources(),
resourceApk.getPrimaryResource().getJavaPackage(), resourceClassJar);
}
}
JavaCompilationHelper helper = initAttributes(attributes, javaSemantics);
if (ruleContext.hasErrors()) {
return null;
}
if (addCoverageSupport) {
androidSemantics.addCoverageSupport(ruleContext, this, javaSemantics, true,
attributes, artifactsBuilder);
if (ruleContext.hasErrors()) {
return null;
}
}
jackCompilationHelper = initJack(helper.getAttributes());
if (ruleContext.hasErrors()) {
return null;
}
initJava(
javaSemantics,
helper,
artifactsBuilder,
collectJavaCompilationArgs,
filesBuilder,
isBinary);
if (ruleContext.hasErrors()) {
return null;
}
this.jarsProducedForRuntime = jarsProducedForRuntime.add(classJar).build();
return helper.getAttributes();
}
private JavaCompilationHelper initAttributes(
JavaTargetAttributes.Builder attributes, JavaSemantics semantics) {
JavaCompilationHelper helper = new JavaCompilationHelper(ruleContext, semantics,
javaCommon.getJavacOpts(), attributes,
DataBinding.isEnabled(ruleContext)
? DataBinding.processDeps(ruleContext, attributes) : ImmutableList.<Artifact>of());
helper.addLibrariesToAttributes(javaCommon.targetsTreatedAsDeps(ClasspathType.COMPILE_ONLY));
attributes.setRuleKind(ruleContext.getRule().getRuleClass());
attributes.setTargetLabel(ruleContext.getLabel());
JavaCommon.validateConstraint(ruleContext, "android",
javaCommon.targetsTreatedAsDeps(ClasspathType.BOTH));
ruleContext.checkSrcsSamePackage(true);
return helper;
}
JackCompilationHelper initJack(JavaTargetAttributes attributes) throws InterruptedException {
AndroidSdkProvider sdk = AndroidSdkProvider.fromRuleContext(ruleContext);
return new JackCompilationHelper.Builder()
// blaze infrastructure
.setRuleContext(ruleContext)
// configuration
.setOutputArtifact(
ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_JACK_FILE))
// tools
.setJackBinary(sdk.getJack())
.setJillBinary(sdk.getJill())
.setResourceExtractorBinary(sdk.getResourceExtractor())
.setJackBaseClasspath(sdk.getAndroidBaseClasspathForJack())
// sources
.addJavaSources(attributes.getSourceFiles())
.addSourceJars(attributes.getSourceJars())
.addResources(attributes.getResources())
.addResourceJars(attributes.getResourceJars())
.addProcessorNames(attributes.getProcessorNames())
.addProcessorClasspathJars(attributes.getProcessorPath())
.addExports(JavaCommon.getExports(ruleContext))
.addClasspathDeps(javaCommon.targetsTreatedAsDeps(ClasspathType.COMPILE_ONLY))
.addRuntimeDeps(javaCommon.targetsTreatedAsDeps(ClasspathType.RUNTIME_ONLY))
.build();
}
private void initJava(
JavaSemantics javaSemantics,
JavaCompilationHelper helper,
JavaCompilationArtifacts.Builder javaArtifactsBuilder,
boolean collectJavaCompilationArgs,
NestedSetBuilder<Artifact> filesBuilder,
boolean isBinary)
throws InterruptedException {
JavaTargetAttributes attributes = helper.getAttributes();
if (ruleContext.hasErrors()) {
// Avoid leaving filesToBuild set to null, otherwise we'll get a NullPointerException masking
// the real error.
filesToBuild = filesBuilder.build();
return;
}
Artifact jar = null;
if (attributes.hasSourceFiles() || attributes.hasSourceJars() || attributes.hasResources()) {
// We only want to add a jar to the classpath of a dependent rule if it has content.
javaArtifactsBuilder.addRuntimeJar(classJar);
jar = classJar;
}
filesBuilder.add(classJar);
manifestProtoOutput = helper.createManifestProtoOutput(classJar);
// The gensrc jar is created only if the target uses annotation processing. Otherwise,
// it is null, and the source jar action will not depend on the compile action.
if (helper.usesAnnotationProcessing()) {
genClassJar = helper.createGenJar(classJar);
genSourceJar = helper.createGensrcJar(classJar);
helper.createGenJarAction(classJar, manifestProtoOutput, genClassJar);
}
srcJar = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_SOURCE_JAR);
javaSourceJarsProviderBuilder
.addSourceJar(srcJar)
.addAllTransitiveSourceJars(javaCommon.collectTransitiveSourceJars(srcJar));
helper.createSourceJarAction(srcJar, genSourceJar);
outputDepsProto = helper.createOutputDepsProtoArtifact(classJar, javaArtifactsBuilder);
helper.createCompileActionWithInstrumentation(classJar, manifestProtoOutput, genSourceJar,
outputDepsProto, javaArtifactsBuilder);
if (isBinary) {
generatedExtensionRegistryProvider =
javaSemantics.createGeneratedExtensionRegistry(
ruleContext,
javaCommon,
filesBuilder,
javaArtifactsBuilder,
javaRuleOutputJarsProviderBuilder,
javaSourceJarsProviderBuilder);
}
filesToBuild = filesBuilder.build();
if ((attributes.hasSourceFiles() || attributes.hasSourceJars()) && jar != null) {
iJar = helper.createCompileTimeJarAction(jar, javaArtifactsBuilder);
}
JavaCompilationArtifacts javaArtifacts = javaArtifactsBuilder.build();
compileTimeDependencyArtifacts =
javaCommon.collectCompileTimeDependencyArtifacts(
javaArtifacts.getCompileTimeDependencyArtifact());
javaCommon.setJavaCompilationArtifacts(javaArtifacts);
javaCommon.setClassPathFragment(
new ClasspathConfiguredFragment(
javaCommon.getJavaCompilationArtifacts(),
attributes,
asNeverLink,
helper.getBootclasspathOrDefault()));
transitiveNeverlinkLibraries = collectTransitiveNeverlinkLibraries(
ruleContext,
javaCommon.getDependencies(),
javaCommon.getJavaCompilationArtifacts().getRuntimeJars());
if (collectJavaCompilationArgs) {
boolean hasSources = attributes.hasSourceFiles() || attributes.hasSourceJars();
this.javaCompilationArgs =
collectJavaCompilationArgs(exportDeps, asNeverLink, hasSources);
this.recursiveJavaCompilationArgs = collectJavaCompilationArgs(
true, asNeverLink, /* hasSources */ true);
}
}
public RuleConfiguredTargetBuilder addTransitiveInfoProviders(
RuleConfiguredTargetBuilder builder,
AndroidSemantics androidSemantics,
Artifact aar,
ResourceApk resourceApk,
Artifact zipAlignedApk,
Iterable<Artifact> apksUnderTest) {
idlHelper.addTransitiveInfoProviders(builder, classJar, manifestProtoOutput);
if (generatedExtensionRegistryProvider != null) {
builder.add(GeneratedExtensionRegistryProvider.class, generatedExtensionRegistryProvider);
}
OutputJar resourceJar = null;
if (resourceClassJar != null && resourceSourceJar != null) {
resourceJar = new OutputJar(resourceClassJar, null, resourceSourceJar);
javaRuleOutputJarsProviderBuilder.addOutputJar(resourceJar);
}
JavaRuleOutputJarsProvider ruleOutputJarsProvider =
javaRuleOutputJarsProviderBuilder
.addOutputJar(classJar, iJar, srcJar)
.setJdeps(outputDepsProto)
.build();
JavaSourceJarsProvider sourceJarsProvider = javaSourceJarsProviderBuilder.build();
JavaCompilationArgsProvider compilationArgsProvider =
JavaCompilationArgsProvider.create(
javaCompilationArgs,
recursiveJavaCompilationArgs,
compileTimeDependencyArtifacts,
NestedSetBuilder.<Artifact>emptySet(Order.STABLE_ORDER));
JavaSkylarkApiProvider.Builder skylarkApiProvider =
JavaSkylarkApiProvider.builder()
.setRuleOutputJarsProvider(ruleOutputJarsProvider)
.setSourceJarsProvider(sourceJarsProvider)
.setCompilationArgsProvider(compilationArgsProvider);
javaCommon.addTransitiveInfoProviders(
builder, skylarkApiProvider, filesToBuild, classJar, ANDROID_COLLECTION_SPEC);
javaCommon.addGenJarsProvider(builder, skylarkApiProvider, genClassJar, genSourceJar);
return builder
.setFilesToBuild(filesToBuild)
.addSkylarkTransitiveInfo(JavaSkylarkApiProvider.NAME, skylarkApiProvider.build())
.add(JavaRuleOutputJarsProvider.class, ruleOutputJarsProvider)
.add(JavaSourceJarsProvider.class, sourceJarsProvider)
.add(
JavaRuntimeJarProvider.class,
new JavaRuntimeJarProvider(javaCommon.getJavaCompilationArtifacts().getRuntimeJars()))
.add(RunfilesProvider.class, RunfilesProvider.simple(getRunfiles()))
.add(AndroidResourcesProvider.class, resourceApk.toResourceProvider(ruleContext.getLabel()))
.add(
AndroidIdeInfoProvider.class,
createAndroidIdeInfoProvider(
ruleContext,
androidSemantics,
idlHelper,
resourceJar,
aar,
resourceApk,
zipAlignedApk,
apksUnderTest))
.add(JavaCompilationArgsProvider.class, compilationArgsProvider)
.add(
JackLibraryProvider.class,
asNeverLink
? jackCompilationHelper.compileAsNeverlinkLibrary()
: jackCompilationHelper.compileAsLibrary())
.addSkylarkTransitiveInfo(AndroidSkylarkApiProvider.NAME, new AndroidSkylarkApiProvider())
.addOutputGroup(
OutputGroupProvider.HIDDEN_TOP_LEVEL, collectHiddenTopLevelArtifacts(ruleContext))
.addOutputGroup(
JavaSemantics.SOURCE_JARS_OUTPUT_GROUP, sourceJarsProvider.getTransitiveSourceJars());
}
private Runfiles getRunfiles() {
// TODO(bazel-team): why return any Runfiles in the neverlink case?
if (asNeverLink) {
return new Runfiles.Builder(
ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles())
.addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES)
.build();
}
return JavaCommon.getRunfiles(
ruleContext, javaCommon.getJavaSemantics(), javaCommon.getJavaCompilationArtifacts(),
asNeverLink);
}
public static PathFragment getAssetDir(RuleContext ruleContext) {
return new PathFragment(ruleContext.attributes().get(
ResourceType.ASSETS.getAttribute() + "_dir",
Type.STRING));
}
public static AndroidResourcesProvider getAndroidResources(RuleContext ruleContext) {
if (!ruleContext.attributes().has("resources", BuildType.LABEL)) {
return null;
}
TransitiveInfoCollection prerequisite = ruleContext.getPrerequisite("resources", Mode.TARGET);
if (prerequisite == null) {
return null;
}
ruleContext.ruleWarning(
"The use of the android_resources rule and the resources attribute is deprecated. "
+ "Please use the resource_files, assets, and manifest attributes of android_library.");
return prerequisite.getProvider(AndroidResourcesProvider.class);
}
/**
* Collects Java compilation arguments for this target.
*
* @param recursive Whether to scan dependencies recursively.
* @param isNeverLink Whether the target has the 'neverlink' attr.
* @param hasSrcs If false, deps are exported (deprecated behaviour)
*/
private JavaCompilationArgs collectJavaCompilationArgs(boolean recursive, boolean isNeverLink,
boolean hasSrcs) {
boolean exportDeps = !hasSrcs
&& ruleContext.getFragment(AndroidConfiguration.class).allowSrcsLessAndroidLibraryDeps();
return javaCommon.collectJavaCompilationArgs(recursive, isNeverLink, exportDeps);
}
public ImmutableList<String> getJavacOpts() {
return javaCommon.getJavacOpts();
}
public Artifact getGenClassJar() {
return genClassJar;
}
@Nullable public Artifact getGenSourceJar() {
return genSourceJar;
}
public ImmutableList<Artifact> getRuntimeJars() {
return javaCommon.getJavaCompilationArtifacts().getRuntimeJars();
}
public Artifact getResourceClassJar() {
return resourceClassJar;
}
/**
* Returns Jars produced by this rule that may go into the runtime classpath. By contrast
* {@link #getRuntimeJars()} returns the complete runtime classpath needed by this rule, including
* dependencies.
*/
public NestedSet<Artifact> getJarsProducedForRuntime() {
return jarsProducedForRuntime;
}
public Artifact getInstrumentedJar() {
return javaCommon.getJavaCompilationArtifacts().getInstrumentedJar();
}
public NestedSet<Artifact> getTransitiveNeverLinkLibraries() {
return transitiveNeverlinkLibraries;
}
public boolean isNeverLink() {
return asNeverLink;
}
public CcLinkParamsStore getCcLinkParamsStore() {
return getCcLinkParamsStore(
javaCommon.targetsTreatedAsDeps(ClasspathType.BOTH), ImmutableList.<String>of());
}
public static CcLinkParamsStore getCcLinkParamsStore(
final Iterable<? extends TransitiveInfoCollection> deps, final Collection<String> linkOpts) {
return new CcLinkParamsStore() {
@Override
protected void collect(
CcLinkParams.Builder builder, boolean linkingStatically, boolean linkShared) {
builder.addTransitiveTargets(
deps,
// Link in Java-specific C++ code in the transitive closure
JavaCcLinkParamsProvider.TO_LINK_PARAMS,
// Link in Android-specific C++ code (e.g., android_libraries) in the transitive closure
AndroidCcLinkParamsProvider.TO_LINK_PARAMS,
// Link in non-language-specific C++ code in the transitive closure
CcLinkParamsProvider.TO_LINK_PARAMS);
builder.addLinkOpts(linkOpts);
}
};
}
/**
* Returns {@link AndroidConfiguration} in given context.
*/
static AndroidConfiguration getAndroidConfig(RuleContext context) {
return context.getConfiguration().getFragment(AndroidConfiguration.class);
}
private NestedSet<Artifact> collectHiddenTopLevelArtifacts(RuleContext ruleContext) {
NestedSetBuilder<Artifact> builder = NestedSetBuilder.stableOrder();
for (OutputGroupProvider provider :
getTransitivePrerequisites(ruleContext, Mode.TARGET, OutputGroupProvider.class)) {
builder.addTransitive(provider.getOutputGroup(OutputGroupProvider.HIDDEN_TOP_LEVEL));
}
return builder.build();
}
/**
* Returns a {@link JavaCommon} instance with Android data binding support.
*
* <p>Binaries need both compile-time and runtime support, while libraries only need compile-time
* support.
*
* <p>No rule needs <i>any</i> support if data binding is disabled.
*/
static JavaCommon createJavaCommonWithAndroidDataBinding(RuleContext ruleContext,
JavaSemantics semantics, boolean isLibrary) {
boolean useDataBinding = DataBinding.isEnabled(ruleContext);
ImmutableList<Artifact> srcs =
ruleContext.getPrerequisiteArtifacts("srcs", RuleConfiguredTarget.Mode.TARGET).list();
if (useDataBinding) {
srcs = ImmutableList.<Artifact>builder().addAll(srcs)
.add(DataBinding.createAnnotationFile(ruleContext, isLibrary)).build();
}
ImmutableList<TransitiveInfoCollection> compileDeps;
ImmutableList<TransitiveInfoCollection> runtimeDeps;
ImmutableList<TransitiveInfoCollection> bothDeps;
if (isLibrary) {
compileDeps = JavaCommon.defaultDeps(ruleContext, semantics, ClasspathType.COMPILE_ONLY);
if (useDataBinding) {
compileDeps = DataBinding.addSupportLibs(ruleContext, compileDeps);
}
if (AndroidIdlHelper.hasIdlSrcs(ruleContext)) {
compileDeps = AndroidIdlHelper.addSupportLibs(ruleContext, compileDeps);
}
runtimeDeps = JavaCommon.defaultDeps(ruleContext, semantics, ClasspathType.RUNTIME_ONLY);
bothDeps = JavaCommon.defaultDeps(ruleContext, semantics, ClasspathType.BOTH);
} else {
// Binary:
List<? extends TransitiveInfoCollection> ruleDeps =
ruleContext.getPrerequisites("deps", RuleConfiguredTarget.Mode.TARGET);
compileDeps = useDataBinding
? DataBinding.addSupportLibs(ruleContext, ruleDeps)
: ImmutableList.<TransitiveInfoCollection>copyOf(ruleDeps);
runtimeDeps = compileDeps;
bothDeps = compileDeps;
}
return new JavaCommon(ruleContext, semantics, srcs, compileDeps, runtimeDeps, bothDeps);
}
}
| |
package JavaChatServer.Controller;
import JavaChatServer.Model.Message;
import JavaChatServer.Model.MessageQueue;
import JavaChatServer.Model.NickRegistrar;
import java.util.*;
/**
* Keeps track of all the client handler threads and broadcasts new messages to them
* Created by david on 4/1/17.
*/
public class MessageBroadcaster implements Runnable {
private final int timeout = 100; // time to wait between attempted broadcasts, in ms
private final MessageQueue queue;
private final List<ClientHandler> handlerList; // list of client handlers
private final Map<String, List<ClientHandler>> channelMembers; // list of the channels subscribed to by each client
public MessageBroadcaster(MessageQueue q) {
this.queue = q;
handlerList = Collections.synchronizedList(new ArrayList<ClientHandler>());
channelMembers = Collections.synchronizedMap(new HashMap<String, List<ClientHandler>>());
}
public void addHandlder(ClientHandler h) {
handlerList.add(h);
}
public void joinChannel(ClientHandler h, String channel) {
System.out.println("Client wants to join " + channel);
List<ClientHandler> memberList = channelMembers.get(channel);
if (memberList == null) {
System.out.println("First member for " + channel + " has joined!");
channelMembers.put(channel, new ArrayList<>());
memberList = channelMembers.get(channel);
}
memberList.add(h);
}
public void removeHandler(ClientHandler clientHandler) {
System.out.println("Removing client " + clientHandler.getClientID() + " from broadcaster");
// remove from all channels subscribed to
for (List<ClientHandler> l : channelMembers.values()) {
l.remove(clientHandler);
}
// remove from server wide handler list
handlerList.remove(clientHandler);
}
public void broadcast(Message m) {
queue.broadcast(m);
}
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
Message message = queue.consume();
// if there are no new messages... wait
if (message == null) {
try {
Thread.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
// give each client handler a copy of the message
List<ClientHandler> closedClients = new ArrayList<>();
List<ClientHandler> recipients = new ArrayList();
if (message.getRecipient() == null) {
// broadcast to all users
synchronized (handlerList) { // make sure another thread does not change the list while we iterate over it
for (ClientHandler h : handlerList) {
if (h.closed()) {
// ignore closed connections and remove them from the queue
System.out.println("Removed old client " + h.getClientID());
NickRegistrar.getInstance().removeNick(h.getNick());
closedClients.add(h);
continue;
}
// don't broadcast back to sender
if (h.getClientID() != message.getClientID() || message.isEcho()) {
recipients.add(h);
}
}
}
} else if (message.getRecipient().startsWith("#")) {
// send to all users in the channel
String channel = message.getRecipient();
List<ClientHandler> members = channelMembers.get(channel);
if (members == null) {
// there are no members...
System.err.println(channel + " has no memebers...");
} else {
synchronized (members) {
for (ClientHandler h : members) {
if (h.closed()) {
// ignore closed connections and remove them from the queue
NickRegistrar.getInstance().removeNick(h.getNick());
closedClients.add(h);
continue;
}
// don't broadcast back to sender
if (h.getClientID() != message.getClientID() || message.isEcho()) {
recipients.add(h);
}
}
}
}
} else {
// send to the particular user
// find the recipient message handler
synchronized (handlerList) {
for (ClientHandler h : handlerList) {
if (h.getUser().getNick().equalsIgnoreCase(message.getRecipient())) {
recipients.add(h);
}
}
}
}
// remove the closed clients
for (ClientHandler h : closedClients) {
removeHandler(h);
}
for (ClientHandler h : recipients) {
System.out.println("Broadcasting message to " + h.getClientID());
h.receive(message);
}
}
}
}
}).start();
}
public List<String> getMembers(String channel) {
List<String> memebers = new ArrayList<>();
List<ClientHandler> memberList = channelMembers.get(channel);
synchronized (memberList) {
if (memberList == null) {
return new ArrayList<>();
} else {
for (ClientHandler h : memberList) {
memebers.add(h.getNick());
}
}
}
return memebers;
}
// Get all channels a particular client is in
public List<String> getChannels(ClientHandler client) {
List<String> channels = new ArrayList<String>();
synchronized (channelMembers) {
for (String channel : channelMembers.keySet()) {
Collection<ClientHandler> clients = channelMembers.get(channel);
if (clients.contains(client)) {
channels.add(channel);
}
}
}
return channels;
}
public void partChannel(ClientHandler client, String channel) {
synchronized (channelMembers) {
List<ClientHandler> members = channelMembers.get(channel);
members.remove(client);
}
}
public boolean isMember(ClientHandler handler, String channel) {
if (channelMembers.get(channel) != null) {
return channelMembers.get(channel).contains(handler);
} else {
return false;
}
}
}
| |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.webapi.service;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.hisp.dhis.common.cache.CacheStrategy.CACHE_10_MINUTES;
import static org.hisp.dhis.common.cache.CacheStrategy.CACHE_15_MINUTES;
import static org.hisp.dhis.common.cache.CacheStrategy.CACHE_1_HOUR;
import static org.hisp.dhis.common.cache.CacheStrategy.CACHE_1_MINUTE;
import static org.hisp.dhis.common.cache.CacheStrategy.CACHE_30_MINUTES;
import static org.hisp.dhis.common.cache.CacheStrategy.CACHE_5_MINUTES;
import static org.hisp.dhis.common.cache.CacheStrategy.CACHE_TWO_WEEKS;
import static org.hisp.dhis.common.cache.CacheStrategy.NO_CACHE;
import static org.hisp.dhis.common.cache.CacheStrategy.RESPECT_SYSTEM_SETTING;
import static org.hisp.dhis.common.cache.Cacheability.PRIVATE;
import static org.hisp.dhis.common.cache.Cacheability.PUBLIC;
import static org.hisp.dhis.setting.SettingKey.CACHEABILITY;
import static org.hisp.dhis.setting.SettingKey.CACHE_STRATEGY;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
import static org.springframework.http.CacheControl.maxAge;
import static org.springframework.http.CacheControl.noCache;
import java.util.Date;
import org.hisp.dhis.analytics.cache.AnalyticsCacheSettings;
import org.hisp.dhis.common.cache.CacheStrategy;
import org.hisp.dhis.common.cache.Cacheability;
import org.hisp.dhis.setting.SystemSettingManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.CacheControl;
@ExtendWith( MockitoExtension.class )
class WebCacheTest
{
@Mock
private SystemSettingManager systemSettingManager;
@Mock
private AnalyticsCacheSettings analyticsCacheSettings;
private WebCache webCache;
@BeforeEach
public void setUp()
{
webCache = new WebCache( systemSettingManager, analyticsCacheSettings );
}
@Test
void testGetCacheControlForWhenCacheStrategyIsNoCache()
{
// Given
final CacheControl expectedCacheControl = noCache();
// When
final CacheControl actualCacheControl = webCache.getCacheControlFor( NO_CACHE );
// Then
assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
@Test
void testGetCacheControlForWhenCacheStrategyIsRespectSystemSetting()
{
// Given
final CacheStrategy strategy = CACHE_5_MINUTES;
final CacheControl expectedCacheControl = stubPublicCacheControl( strategy );
givenCacheabilityPublic();
givenCacheStartegy( strategy );
// When
final CacheControl actualCacheControl = webCache.getCacheControlFor( RESPECT_SYSTEM_SETTING );
// Then
assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
@Test
void testGetAnalyticsCacheControlForWhenTimeToLiveIsZero()
{
// Given
final long zeroTimeToLive = 0;
final Date aDate = new Date();
final CacheControl expectedCacheControl = noCache();
// When
when( analyticsCacheSettings.progressiveExpirationTimeOrDefault( aDate ) ).thenReturn( zeroTimeToLive );
final CacheControl actualCacheControl = webCache.getCacheControlFor( aDate );
// Then
assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
@Test
void testGetAnalyticsCacheControlForWhenTimeToLiveIsNegative()
{
// Given
final long zeroTimeToLive = -1;
final Date aDate = new Date();
final CacheControl expectedCacheControl = noCache();
// When
when( analyticsCacheSettings.progressiveExpirationTimeOrDefault( aDate ) ).thenReturn( zeroTimeToLive );
final CacheControl actualCacheControl = webCache.getCacheControlFor( aDate );
// Then
assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
@Test
void testGetAnalyticsCacheControlForWhenTimeToLiveIsPositive()
{
// Given
final long positiveTimeToLive = 60;
final Date aDate = new Date();
final CacheControl expectedCacheControl = stubPublicCacheControl( positiveTimeToLive );
givenCacheability( PUBLIC );
when( analyticsCacheSettings.progressiveExpirationTimeOrDefault( aDate ) ).thenReturn( positiveTimeToLive );
final CacheControl actualCacheControl = webCache.getCacheControlFor( aDate );
// Then
assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
@Test
void testGetCacheControlForWhenCacheStrategyIsRespectSystemSettingNotUsedInObjectBasis()
{
// Given
givenCacheStartegy( RESPECT_SYSTEM_SETTING );
assertThrows( UnsupportedOperationException.class,
() -> webCache.getCacheControlFor( RESPECT_SYSTEM_SETTING ) );
}
@Test
void testGetCacheControlForWhenCacheStrategyIsCache1Minute()
{
// Given
final CacheStrategy strategy = CACHE_1_MINUTE;
final CacheControl expectedCacheControl = stubPublicCacheControl( strategy );
givenCacheabilityPublic();
// When
final CacheControl actualCacheControl = webCache.getCacheControlFor( strategy );
// Then
assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
@Test
void testGetCacheControlForWhenCacheStrategyIsCache5Minutes()
{
// Given
final CacheStrategy strategy = CACHE_5_MINUTES;
final CacheControl expectedCacheControl = stubPublicCacheControl( strategy );
givenCacheabilityPublic();
// When
final CacheControl actualCacheControl = webCache.getCacheControlFor( strategy );
// Then
assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
@Test
void testGetCacheControlForWhenCacheStrategyIsCache10Minutes()
{
// Given
final CacheStrategy strategy = CACHE_10_MINUTES;
final CacheControl expectedCacheControl = stubPublicCacheControl( strategy );
givenCacheabilityPublic();
// When
final CacheControl actualCacheControl = webCache.getCacheControlFor( strategy );
// Then
assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
@Test
void testGetCacheControlForWhenCacheStrategyIsCache15Minutes()
{
// Given
final CacheStrategy strategy = CACHE_15_MINUTES;
final CacheControl expectedCacheControl = stubPublicCacheControl( strategy );
givenCacheabilityPublic();
// When
final CacheControl actualCacheControl = webCache.getCacheControlFor( strategy );
// Then
assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
@Test
void testGetCacheControlForWhenCacheStrategyIsCache30Minutes()
{
// Given
final CacheStrategy strategy = CACHE_30_MINUTES;
final CacheControl expectedCacheControl = stubPublicCacheControl( strategy );
givenCacheabilityPublic();
// When
final CacheControl actualCacheControl = webCache.getCacheControlFor( strategy );
// Then
assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
@Test
void testGetCacheControlForWhenCacheStrategyIsCache1Hour()
{
// Given
final CacheStrategy strategy = CACHE_1_HOUR;
final CacheControl expectedCacheControl = stubPublicCacheControl( strategy );
givenCacheabilityPublic();
// When
final CacheControl actualCacheControl = webCache.getCacheControlFor( strategy );
// Then
assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
@Test
void testGetCacheControlForWhenCacheStrategyIsCache2Weeks()
{
// Given
final CacheStrategy strategy = CACHE_TWO_WEEKS;
final CacheControl expectedCacheControl = stubPublicCacheControl( strategy );
givenCacheabilityPublic();
// When
final CacheControl actualCacheControl = webCache.getCacheControlFor( strategy );
// Then
assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
@Test
void testSetCacheabilityWhenCacheabilityIsSetToPublic()
{
// Given
givenCacheability( PUBLIC );
final CacheControl actualCacheControl = webCache.getCacheControlFor( CACHE_5_MINUTES );
// Then
assertThat( actualCacheControl.toString().toLowerCase(), containsString( "public" ) );
}
@Test
void testSetCacheabilityWhenCacheabilityIsSetToPrivate()
{
// Given
givenCacheability( PRIVATE );
final CacheControl actualCacheControl = webCache.getCacheControlFor( CACHE_5_MINUTES );
// Then
assertThat( actualCacheControl.toString().toLowerCase(), containsString( "private" ) );
}
@Test
void testSetCacheabilityWhenCacheabilityIsSetToNull()
{
// Given
givenCacheability( null );
final CacheControl actualCacheControl = webCache.getCacheControlFor( CACHE_5_MINUTES );
// Then
assertThat( actualCacheControl.toString().toLowerCase(), not( containsString( "private" ) ) );
assertThat( actualCacheControl.toString().toLowerCase(), not( containsString( "public" ) ) );
}
private CacheControl stubPublicCacheControl( final CacheStrategy cacheStrategy )
{
return stubPublicCacheControl( cacheStrategy.toSeconds() );
}
private CacheControl stubPublicCacheControl( final long seconds )
{
return maxAge( seconds, SECONDS ).cachePublic();
}
private void givenCacheStartegy( CacheStrategy theCacheStrategySet )
{
when( systemSettingManager.getSystemSetting( CACHE_STRATEGY, CacheStrategy.class ) )
.thenReturn( theCacheStrategySet );
}
private void givenCacheabilityPublic()
{
givenCacheability( PUBLIC );
}
private void givenCacheability( Cacheability cacheability )
{
when( systemSettingManager.getSystemSetting( CACHEABILITY, Cacheability.class ) )
.thenReturn( cacheability );
}
}
| |
/*
* ImageOJ.java
* fully documented 8.3.2010
*/
package oj.project;
import ij.ImagePlus;
import ij.WindowManager;
import oj.OJ;
import oj.processor.events.ImageChangedEventOJ;
/**
* ImageOJ holds information about a linked image, such as width, height,
* slices, hyperstack structure, scaling and name.
*/
public class ImageOJ extends BaseAdapterOJ {
private static final long serialVersionUID = 556257904296924117L;
//image info
private String name;
private String description = "";
private transient boolean fileExists = true;
private int nrSlices = 1;
private int nrFrames = 1;
private int nrChannels = 1;
//image size
private int width = 0;
private int height = 0;
//image calibration
private double voxelSizeX = 1.0;
private double voxelSizeY = 1.0;
private double voxelSizeZ = 1.0;
private String voxelUnitX = "";
private String voxelUnitY = "";
private String voxelUnitZ = "";
//image stack
private int frameInterval = 1;//30.7.2013 put this back to int: was this the mistake?
private double frameIntervalD = 1;//30.7.2013 put this back to int: was this the mistake?
private String frameRateUnit = "sec";
//private transient int ID = 0;//negative if image is open, zero if closed
private transient ImagePlus imagePlus = null;
public ImageOJ() {
name = "";
//ID = 0;
}
public ImageOJ(String name, ImagePlus imp) {//30.6.2012
// if (imp != null) {//5.4.2013
// this.ID = imp.getID();
// }
this.imagePlus = imp;
this.name = name;
}
public int[] getDimensions() {
int[] dimensions = {width, height, nrChannels, nrSlices, nrFrames};
return dimensions;
}
// public int getID() {
// return ID;
// }
//
// public void setID(int ID) {
// this.ID = ID;
// }
public void setImagePlus(ImagePlus imp) {
imagePlus = imp;
}
//returns imageOJ's ImagePlus, or null if it is not open
public ImagePlus getImagePlus() {
if (imagePlus != null) {
int id = imagePlus.getID();//verify if still open
imagePlus = WindowManager.getImage(id);
}
return imagePlus;
}
public String getName() {
return name;
}
public String getFilename() {
//return filename;
return name;
}
public String getDescription() {
return description;
}
public void setDescription(String s) {
description = s;
}
/**
* @return index of first cell (0-based) in this image, or -1 if unmarked
*/
public int getFirstCell() {
return OJ.getData().getCells().getFirstCellOnImage(name);
}
/**
* @return index of last cell (0-based) in this image, or -1 if unmarked
*/
public int getLastCell() {
return OJ.getData().getCells().getLastCellOnImage(name);
}
/**
* @return number of cells in this image
*/
public int getCellCount() {
if (getFirstCell() >= 0) {
return getLastCell() - getFirstCell() + 1;
} else {
return 0;
}
}
/**
* @return array of cells in this image not tested yet
*/
public CellOJ[] getCells() {
int count = getCellCount();
CellOJ[] cells = new CellOJ[count];
int kk = 0;
for (int cc = getFirstCell(); cc < getFirstCell() + count; cc++) {
cells[kk++] = OJ.getData().getCells().getCellByIndex(cc);
}
return cells;
}
/**
* rename image
*/
public void setName(String name) {
if (!this.name.equals(name)) {
String oldName = this.name;
this.name = name;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, oldName, ImageChangedEventOJ.IMAGE_EDITED);
}
}
/**
* rename image - obsolete
*/
public void setFilename(String filename) {
if (!this.name.equals(filename)) {
this.name = filename;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
/**
* ObjectJ stores the image width and height of a linked image - this is not
* really used
*/
public int getWidth() {
return width;
}
/**
* ObjectJ stores the image width and height of a linked image - this is not
* really used
*/
public void setWidth(int width) {
if (this.width != width) {
this.width = width;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
/**
* ObjectJ stores the image width and height of a linked image - this is not
* really used
*/
public int getHeight() {
return height;
}
/**
* ojj file stores the image width and height of a linked image - this is
* not really used
*/
public void setHeight(int height) {
if (this.height != height) {
this.height = height;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
/**
* ojj file stores voxel size
*/
public double getVoxelSizeX() {
return voxelSizeX;
}
public void setVoxelSizeX(double voxelSizeX) {
if (this.voxelSizeX != voxelSizeX) {
this.voxelSizeX = voxelSizeX;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
public double getVoxelSizeY() {
return voxelSizeY;
}
public void setVoxelSizeY(double voxelSizeY) {
if (this.voxelSizeY != voxelSizeY) {
this.voxelSizeY = voxelSizeY;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
public double getVoxelSizeZ() {
return voxelSizeZ;
}
public void setVoxelSizeZ(double voxelSizeZ) {
if (this.voxelSizeZ != voxelSizeZ) {
this.voxelSizeZ = voxelSizeZ;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
public String getVoxelUnitX() {
return voxelUnitX;
}
public void setVoxelUnitX(String voxelUnitX) {
if (!this.voxelUnitX.equals(voxelUnitX)) {
this.voxelUnitX = voxelUnitX;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
public String getVoxelUnitY() {
return voxelUnitY;
}
public void setVoxelUnitY(String voxelUnitY) {
if (!this.voxelUnitY.equals(voxelUnitY)) {
this.voxelUnitY = voxelUnitY;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
public String getVoxelUnitZ() {
return voxelUnitZ;
}
public void setVoxelUnitZ(String voxelUnitZ) {
if (!this.voxelUnitZ.equals(voxelUnitZ)) {
this.voxelUnitZ = voxelUnitZ;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
/**
* ojj file stores frame interval
*/
public double getFrameInterval() {
return frameIntervalD;
}
public void setFrameInterval(double frameInterval) {
if (this.frameIntervalD != frameInterval) {
this.frameIntervalD = frameInterval;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
public String getFrameRateUnit() {
return frameRateUnit;
}
public void setFrameRateUnit(String frameRateUnit) {
if (!this.frameRateUnit.equals(frameRateUnit)) {
this.frameRateUnit = frameRateUnit;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
/**
* fill default values if incomplete
*/
public void initAfterUnmarshalling(IBaseOJ parent) {
super.initAfterUnmarshalling(parent);
if (width < 0) {
width = 0;
}
if (height < 0) {
height = 0;
}
if (nrSlices < 1) {
nrSlices = 1;
}
if (nrFrames < 1) {
nrFrames = 1;
}
if (nrChannels < 1) {
nrChannels = 1;
}
if (voxelSizeX <= 0) {
voxelSizeX = 1.0;
}
if (voxelSizeY <= 0) {
voxelSizeY = 1.0;
}
if (voxelSizeZ <= 0) {
voxelSizeZ = 1.0;
}
if ((voxelUnitX == null) || (voxelUnitX.equals(""))) {
voxelUnitX = "um";
}
if ((voxelUnitY == null) || (voxelUnitY.equals(""))) {
voxelUnitY = "um";
}
if ((voxelUnitZ == null) || (voxelUnitZ.equals(""))) {
voxelUnitZ = "um";
}
if (frameIntervalD < 0) {
frameIntervalD = 1;
}
if ((frameRateUnit == null) || (frameRateUnit.equals(""))) {
frameRateUnit = "s";
}
}
/**
* @return true if image is saved in project folder
*/
public boolean isFileExists() {
return fileExists;
}
public void setFileExists(boolean fileExists) {
this.fileExists = fileExists;
}
public int getNumberOfSlices() {
return nrSlices;
}
public int getStackSize() {
return nrSlices * nrFrames * nrChannels;
}
public void setNumberOfSlices(int nrSlices) {
if (this.nrSlices != nrSlices) {
this.nrSlices = nrSlices;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
public int getNumberOfFrames() {
return nrFrames;
}
public void setNumberOfFrames(int nrFrames) {
if (this.nrFrames != nrFrames) {
this.nrFrames = nrFrames;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
public int getNumberOfChannels() {
return nrChannels;
}
public void setNumberOfChannels(int nrChannels) {
if (this.nrChannels != nrChannels) {
this.nrChannels = nrChannels;
setChanged(true);
OJ.getEventProcessor().fireImageChangedEvent(name, ImageChangedEventOJ.IMAGE_EDITED);
}
}
}
| |
/*
* Licensed to DuraSpace under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* DuraSpace 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.fcrepo.persistence.ocfl.impl;
import static edu.wisc.library.ocfl.api.OcflOption.MOVE_SOURCE;
import static java.lang.String.format;
import static org.fcrepo.persistence.api.CommitOption.NEW_VERSION;
import static org.fcrepo.persistence.api.CommitOption.UNVERSIONED;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import edu.wisc.library.ocfl.core.storage.filesystem.FileSystemOcflStorage;
import org.apache.commons.io.IOUtils;
import org.fcrepo.persistence.api.exceptions.PersistentItemNotFoundException;
import org.fcrepo.persistence.api.exceptions.PersistentSessionClosedException;
import org.fcrepo.persistence.api.exceptions.PersistentStorageException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import edu.wisc.library.ocfl.api.MutableOcflRepository;
import edu.wisc.library.ocfl.api.OcflObjectVersion;
import edu.wisc.library.ocfl.api.model.ObjectDetails;
import edu.wisc.library.ocfl.api.model.ObjectVersionId;
import edu.wisc.library.ocfl.api.model.VersionDetails;
import edu.wisc.library.ocfl.api.model.VersionId;
import edu.wisc.library.ocfl.core.OcflRepositoryBuilder;
import edu.wisc.library.ocfl.core.extension.layout.config.DefaultLayoutConfig;
/**
* @author bbpennel
*
*/
public class DefaultOCFLObjectSessionTest {
private final static String OBJ_ID = "obj1";
private final static String FILE1_SUBPATH = "test_file1.txt";
private final static String FILE2_SUBPATH = "test_file2.txt";
private final static String FILE_CONTENT1 = "Some content";
private final static String FILE_CONTENT2 = "Content, 6.0";
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
private Path stagingPath;
private DefaultOCFLObjectSession session;
private MutableOcflRepository ocflRepository;
@Before
public void setup() throws Exception {
tempFolder.create();
final var repoDir = tempFolder.newFolder("ocfl-repo").toPath();
final var workDir = tempFolder.newFolder("ocfl-work").toPath();
ocflRepository = new OcflRepositoryBuilder()
.layoutConfig(DefaultLayoutConfig.flatPairTreeConfig())
.workDir(workDir)
.storage(FileSystemOcflStorage.builder().repositoryRoot(repoDir).build())
.buildMutable();
session = makeNewSession();
}
private DefaultOCFLObjectSession makeNewSession() throws Exception {
if (stagingPath == null || !stagingPath.toFile().exists()) {
stagingPath = tempFolder.newFolder("obj1-staging").toPath();
}
return new DefaultOCFLObjectSession(OBJ_ID, stagingPath, ocflRepository);
}
@Test
public void writeNewFile_ToNewVersion_NewObject() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
final String versionId = session.commit(NEW_VERSION);
assertEquals("v1", versionId);
assertNoMutableHead(OBJ_ID);
assertFileInHeadVersion(OBJ_ID, FILE1_SUBPATH, FILE_CONTENT1);
}
@Test
public void writeNewFile_ToMHead_NewObject() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(UNVERSIONED);
assertMutableHeadPopulated(OBJ_ID);
assertFileInHeadVersion(OBJ_ID, FILE1_SUBPATH, FILE_CONTENT1);
}
@Test
public void write_OverwriteStagedFile_NewVersion_NewObject() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
// Change the same file again
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT2));
final String versionId = session.commit(NEW_VERSION);
assertEquals("v1", versionId);
assertNoMutableHead(OBJ_ID);
assertFileInHeadVersion(OBJ_ID, FILE1_SUBPATH, FILE_CONTENT2);
}
@Test
public void write_ReplaceFile_NewVersion_ExistingObject() throws Exception {
final var preStagingPath = tempFolder.newFolder("prestage").toPath();
Files.writeString(preStagingPath.resolve(FILE1_SUBPATH), FILE_CONTENT1);
ocflRepository.putObject(ObjectVersionId.head(OBJ_ID), preStagingPath, null);
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT2));
final String versionId = session.commit(NEW_VERSION);
assertEquals("v2", versionId);
assertNoMutableHead(OBJ_ID);
assertFileInHeadVersion(OBJ_ID, FILE1_SUBPATH, FILE_CONTENT2);
assertFileInVersion(OBJ_ID, "v1", FILE1_SUBPATH, FILE_CONTENT1);
}
@Test
public void write_ReplaceFileInMHead_ExistingObject() throws Exception {
final var preStagingPath = tempFolder.newFolder("prestage").toPath();
Files.writeString(preStagingPath.resolve(FILE1_SUBPATH), FILE_CONTENT1);
ocflRepository.stageChanges(ObjectVersionId.head(OBJ_ID), null, updater -> {
updater.addPath(preStagingPath, "", MOVE_SOURCE);
});
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT2));
final String versionId = session.commit(UNVERSIONED);
assertEquals("Multiple commits to head should stay on version", "v2", versionId);
assertMutableHeadPopulated(OBJ_ID);
assertFileInHeadVersion(OBJ_ID, FILE1_SUBPATH, FILE_CONTENT2);
}
@Test
public void writeToMHeadThenNewVersion() throws Exception {
// Write first file to mutable head
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(UNVERSIONED);
assertMutableHeadPopulated(OBJ_ID);
session = new DefaultOCFLObjectSession(OBJ_ID, stagingPath, ocflRepository);
// Commit changes to new version in second commit
session.write(FILE2_SUBPATH, fileStream(FILE_CONTENT2));
final String versionId = session.commit(NEW_VERSION);
assertEquals("v2", versionId);
assertNoMutableHead(OBJ_ID);
assertFileInHeadVersion(OBJ_ID, FILE1_SUBPATH, FILE_CONTENT1);
assertFileInHeadVersion(OBJ_ID, FILE2_SUBPATH, FILE_CONTENT2);
// Initial version is empty since created with mutable head
assertFileNotInVersion(OBJ_ID, "v1", FILE1_SUBPATH);
assertFileNotInVersion(OBJ_ID, "v1", FILE2_SUBPATH);
}
@Test(expected = PersistentSessionClosedException.class)
public void write_CommittedSession() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
session.write(FILE2_SUBPATH, fileStream(FILE_CONTENT1));
}
@Test(expected = PersistentItemNotFoundException.class)
public void read_ObjectNotExist() throws Exception {
session.read(FILE1_SUBPATH);
}
@Test(expected = PersistentItemNotFoundException.class)
public void read_FileNotExist() throws Exception {
Files.writeString(stagingPath.resolve(FILE1_SUBPATH), FILE_CONTENT1);
ocflRepository.putObject(ObjectVersionId.head(OBJ_ID), stagingPath, null);
session.read(FILE2_SUBPATH);
}
@Test
public void read_FromStaged_NewObject() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
assertStreamMatches(FILE_CONTENT1, session.read(FILE1_SUBPATH));
}
@Test
public void read_FromMHead() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(UNVERSIONED);
final var session2 = makeNewSession();
assertStreamMatches(FILE_CONTENT1, session2.read(FILE1_SUBPATH));
}
@Test
public void read_FromVersion() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
assertStreamMatches(FILE_CONTENT1, session2.read(FILE1_SUBPATH));
}
@Test
public void read_FromStagedAndVersion() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
session2.write(FILE1_SUBPATH, fileStream(FILE_CONTENT2));
assertStreamMatches(FILE_CONTENT2, session2.read(FILE1_SUBPATH));
assertStreamMatches(FILE_CONTENT1, session2.read(FILE1_SUBPATH, "v1"));
}
@Test
public void read_FromStagedAndMHead() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(UNVERSIONED);
final var session2 = makeNewSession();
session2.write(FILE1_SUBPATH, fileStream(FILE_CONTENT2));
assertStreamMatches(FILE_CONTENT2, session2.read(FILE1_SUBPATH));
// initial version when creating with mutable head is version 2
assertStreamMatches(FILE_CONTENT1, session2.read(FILE1_SUBPATH, "v2"));
}
@Test(expected = PersistentItemNotFoundException.class)
public void read_FromVersion_NotExist() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
// Try a path that doesn't exist
session2.read(FILE2_SUBPATH, "v1");
}
@Test(expected = PersistentItemNotFoundException.class)
public void read_FromVersion_ObjectNotExist() throws Exception {
// No object created
session.read(FILE2_SUBPATH, "v1");
}
@Test(expected = PersistentItemNotFoundException.class)
public void read_FromNonExistentVersion() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
// version that hasn't been created yet
session2.read(FILE2_SUBPATH, "v99");
}
@Test
public void read_CommittedSession() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
assertStreamMatches(FILE_CONTENT1, session2.read(FILE1_SUBPATH));
}
// Verify that subpaths with parent directories are created and readable
@Test
public void nestedPath_NewVersion_NewObject() throws Exception {
final String nestedSubpath = "path/to/the/file.txt";
session.write(nestedSubpath, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
assertStreamMatches(FILE_CONTENT1, session2.read(nestedSubpath));
}
@Test(expected = PersistentItemNotFoundException.class)
public void delete_FileNotExist() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
// Try a path that doesn't exist
session2.delete(FILE2_SUBPATH);
}
@Test(expected = PersistentItemNotFoundException.class)
public void delete_ObjectNotExist() throws Exception {
// Object not created or populated yet
session.delete(FILE1_SUBPATH);
}
@Test
public void delete_FromStaged_InitialVersion() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
assertEquals(1, stagingPath.toFile().listFiles().length);
assertEquals(1, stagingPath.resolve(OBJ_ID).toFile().listFiles().length);
session.delete(FILE1_SUBPATH);
assertEquals(1, stagingPath.toFile().listFiles().length);
assertEquals(0, stagingPath.resolve(OBJ_ID).toFile().listFiles().length);
}
@Test
public void delete_FromStaged_OtherFilesVersioned() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
session2.write(FILE2_SUBPATH, fileStream(FILE_CONTENT2));
// Try a path that doesn't exist
session2.delete(FILE2_SUBPATH);
session2.commit(NEW_VERSION);
assertFileNotInHeadVersion(OBJ_ID, FILE2_SUBPATH);
assertFileInHeadVersion(OBJ_ID, FILE1_SUBPATH, FILE_CONTENT1);
}
@Test
public void delete_FromMHead() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(UNVERSIONED);
final var session2 = makeNewSession();
session2.delete(FILE1_SUBPATH);
session2.commit(UNVERSIONED);
assertFileNotInHeadVersion(OBJ_ID, FILE1_SUBPATH);
}
@Test
public void delete_FromVersion() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
session2.delete(FILE1_SUBPATH);
session2.commit(NEW_VERSION);
assertFileNotInHeadVersion(OBJ_ID, FILE1_SUBPATH);
assertFileInVersion(OBJ_ID, "v1", FILE1_SUBPATH, FILE_CONTENT1);
}
@Test
public void delete_FromStagedAndVersion() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
session2.write(FILE1_SUBPATH, fileStream(FILE_CONTENT2));
session2.delete(FILE1_SUBPATH);
session2.commit(NEW_VERSION);
assertFileNotInHeadVersion(OBJ_ID, FILE1_SUBPATH);
assertFileInVersion(OBJ_ID, "v1", FILE1_SUBPATH, FILE_CONTENT1);
}
@Test
public void delete_FromStagedAndMHead() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(UNVERSIONED);
final var session2 = makeNewSession();
session2.write(FILE1_SUBPATH, fileStream(FILE_CONTENT2));
session2.delete(FILE1_SUBPATH);
session2.commit(UNVERSIONED);
assertFileNotInHeadVersion(OBJ_ID, FILE1_SUBPATH);
assertFileNotInVersion(OBJ_ID, "v1", FILE1_SUBPATH);
}
@Test(expected = PersistentItemNotFoundException.class)
public void delete_FromDeletedObject() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
// Try to delete a file from an object that was just deleted
session2.deleteObject();
session2.delete(FILE1_SUBPATH);
session2.commit(NEW_VERSION);
assertFileNotInHeadVersion(OBJ_ID, FILE1_SUBPATH);
assertFileNotInVersion(OBJ_ID, "v1", FILE1_SUBPATH);
}
@Test
public void delete_FileAddedAfterObjectDeleted() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
// Try to delete a file from an object that was just deleted
session2.deleteObject();
// Adding 2 files so that staging won't be empty when committing
session2.write(FILE1_SUBPATH, fileStream(FILE_CONTENT2));
session2.write(FILE2_SUBPATH, fileStream(FILE_CONTENT2));
session2.delete(FILE1_SUBPATH);
session2.commit(NEW_VERSION);
assertFileNotInHeadVersion(OBJ_ID, FILE1_SUBPATH);
assertFileInHeadVersion(OBJ_ID, FILE2_SUBPATH, FILE_CONTENT2);
assertOnlyFirstVersionExists();
}
@Test(expected = PersistentSessionClosedException.class)
public void delete_CommittedSession() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
session.delete(FILE1_SUBPATH);
}
@Test
public void deleteObject_ObjectExists() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
session2.deleteObject();
session2.commit(NEW_VERSION);
assertFalse("Deleted object must not exist",
ocflRepository.containsObject(OBJ_ID));
}
@Test(expected = PersistentItemNotFoundException.class)
public void deleteObject_NotExists() throws Exception {
session.deleteObject();
}
@Test
public void deleteObject_StagedChanges_ObjectNotCreated() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.deleteObject();
session.commit(NEW_VERSION);
assertFalse("Deleted object must not exist",
ocflRepository.containsObject(OBJ_ID));
}
@Test
public void deleteObject_CreateAndRecreateSameSession() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.deleteObject();
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT2));
session.commit(NEW_VERSION);
// State of object should reflect post-delete object state
assertFileInHeadVersion(OBJ_ID, FILE1_SUBPATH, FILE_CONTENT2);
}
@Test
public void deleteObject_Recreate() throws Exception {
// Create object
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
// Delete object
final var session2 = makeNewSession();
session2.deleteObject();
session2.commit(NEW_VERSION);
// Recreate object
final var session3 = makeNewSession();
session3.write(FILE1_SUBPATH, fileStream(FILE_CONTENT2));
session3.commit(NEW_VERSION);
assertFileInHeadVersion(OBJ_ID, FILE1_SUBPATH, FILE_CONTENT2);
assertOnlyFirstVersionExists();
}
@Test(expected = PersistentItemNotFoundException.class)
public void read_FromDeletedObject() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
session2.deleteObject();
session2.read(FILE1_SUBPATH);
}
@Test(expected = PersistentSessionClosedException.class)
public void deleteObject_CommittedSession() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
session.deleteObject();
}
@Test(expected = PersistentItemNotFoundException.class)
public void readVersion_FromDeletedObject() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
session2.deleteObject();
session2.read(FILE1_SUBPATH, "v1");
}
@Test(expected = IllegalArgumentException.class)
public void commit_WithoutOption() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(null);
}
@Test(expected = PersistentStorageException.class)
public void commit_NewObject_NoContents() throws Exception {
session.commit(NEW_VERSION);
}
@Test
public void commit_NewVersion_NoChanges() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
session2.commit(NEW_VERSION);
final ObjectDetails objDetails = ocflRepository.describeObject(OBJ_ID);
final var versionMap = objDetails.getVersionMap();
assertEquals("Two versions should exist", 2, versionMap.size());
assertFileInVersion(OBJ_ID, "v1", FILE1_SUBPATH, FILE_CONTENT1);
assertFileInVersion(OBJ_ID, "v2", FILE1_SUBPATH, FILE_CONTENT1);
}
@Test
public void commit_MHead_NoChanges() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(UNVERSIONED);
final var session2 = makeNewSession();
session2.commit(UNVERSIONED);
final ObjectDetails objDetails = ocflRepository.describeObject(OBJ_ID);
final var versionMap = objDetails.getVersionMap();
assertEquals("Only the mutable head and initial version exist", 2, versionMap.size());
assertFileInVersion(OBJ_ID, "v2", FILE1_SUBPATH, FILE_CONTENT1);
assertFileNotInVersion(OBJ_ID, "v1", FILE1_SUBPATH);
}
@Test(expected = PersistentSessionClosedException.class)
public void commit_CommittedSession() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
session.commit(NEW_VERSION);
}
@Test
public void close_SessionWithChanges() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
final var session2 = makeNewSession();
session2.write(FILE2_SUBPATH, fileStream(FILE_CONTENT2));
session2.close();
assertOnlyFirstVersionExists();
assertFileInHeadVersion(OBJ_ID, FILE1_SUBPATH, FILE_CONTENT1);
assertFileNotInHeadVersion(OBJ_ID, FILE2_SUBPATH);
}
@Test
public void close_CommittedSession() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
session.close();
}
@Test
public void listVersions() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.commit(NEW_VERSION);
session.close();
final var session1 = makeNewSession();
session1.commit(NEW_VERSION);
session1.close();
final var session2 = makeNewSession();
session2.commit(UNVERSIONED);
session2.close();
final var session3 = makeNewSession();
final List<VersionDetails> versions = session3.listVersions();
session3.close();
assertEquals("First version in list is not \"v1\"", "v1", versions.get(0).getVersionId().toString());
assertEquals("Second version in list is not \"v2\"", "v2", versions.get(1).getVersionId().toString());
assertEquals("There should be exactly two versions",2, versions.size());
}
@Test
public void listHeadSubpaths() throws Exception {
session.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session.write(FILE2_SUBPATH, fileStream(FILE_CONTENT2));
session.commit(NEW_VERSION);
session.close();
final var session2 = makeNewSession();
final List<String> subpaths = session2.listHeadSubpaths().collect(Collectors.toList());
session2.close();
assertEquals("Expected 2 subpaths", 2, subpaths.size());
Arrays.asList(FILE1_SUBPATH, FILE2_SUBPATH).stream().forEach(subpath -> {
assertTrue(format("Expected subpath %s to be presented", subpath), subpaths.contains(subpath));
});
}
@Test
public void ensureFilesDontStageTogether() throws Exception {
final String obj1ID = UUID.randomUUID().toString();
final String obj2ID = UUID.randomUUID().toString();
final var session1 = new DefaultOCFLObjectSession(obj1ID, stagingPath, ocflRepository);
final var session2 = new DefaultOCFLObjectSession(obj2ID, stagingPath, ocflRepository);
session1.write(FILE1_SUBPATH, fileStream(FILE_CONTENT1));
session2.write(FILE2_SUBPATH, fileStream(FILE_CONTENT2));
session1.commit(NEW_VERSION);
session2.commit(NEW_VERSION);
assertFileInVersion(obj1ID, "v1", FILE1_SUBPATH, FILE_CONTENT1);
assertFileNotInVersion(obj1ID, "v1", FILE2_SUBPATH);
assertFileInVersion(obj2ID, "v1", FILE2_SUBPATH, FILE_CONTENT2);
assertFileNotInVersion(obj2ID, "v1", FILE1_SUBPATH);
}
private static InputStream fileStream(final String content) {
return new ByteArrayInputStream(content.getBytes());
}
private void assertOnlyFirstVersionExists() {
final ObjectDetails objDetails = ocflRepository.describeObject(OBJ_ID);
final var versionMap = objDetails.getVersionMap();
assertEquals("Only a single version should remain", 1, versionMap.size());
assertTrue("First version must be present",
versionMap.containsKey(VersionId.fromString("v1")));
}
private void assertFileInHeadVersion(final String objId, final String subpath, final String content) {
final OcflObjectVersion objVersion = ocflRepository.getObject(ObjectVersionId.head(objId));
assertFileContents(subpath, objVersion, content);
}
private void assertFileInVersion(final String objId, final String versionId, final String subpath,
final String content) {
final OcflObjectVersion objVersion = ocflRepository.getObject(ObjectVersionId.version(objId, versionId));
assertFileContents(subpath, objVersion, content);
}
private void assertFileNotInHeadVersion(final String objId, final String subpath) {
final OcflObjectVersion objVersion = ocflRepository.getObject(ObjectVersionId.head(objId));
assertFalse(String.format("File %s must not be in %s head version", subpath, objId),
objVersion.containsFile(subpath));
}
private void assertFileNotInVersion(final String objId, final String versionId, final String subpath) {
final OcflObjectVersion objVersion = ocflRepository.getObject(ObjectVersionId.version(objId, versionId));
assertFalse(String.format("File %s must not be in %s version %s", subpath, objId, versionId),
objVersion.containsFile(subpath));
}
private void assertFileContents(final String subpath, final OcflObjectVersion objVersion, final String content) {
assertStreamMatches(content, objVersion.getFile(subpath).getStream());
}
private void assertStreamMatches(final String expectedContent, final InputStream contentStream) {
try {
assertEquals(expectedContent, IOUtils.toString(contentStream, "UTF-8"));
} catch (final IOException e) {
fail(format("Failed to read stream due to %s", e.getMessage()));
}
}
private void assertMutableHeadPopulated(final String objId) {
assertTrue("Mutable head must be populated for " + objId, ocflRepository.hasStagedChanges(objId));
}
private void assertNoMutableHead(final String objId) {
assertFalse("No mutable head should be present for " + objId, ocflRepository.hasStagedChanges(objId));
}
}
| |
package de.tum.in.schlichter.shoprx.algorithm.model;
import java.math.BigDecimal;
import java.util.Arrays;
import de.tum.in.schlichter.shoprx.Explanations.Model.Explanation;
import de.tum.in.schlichter.shoprx.context.model.ItemSelectedContext;
/**
* Represents a item (e.g. clothing item), or one case in the case-base.
*/
public class Item {
private int id;
private String name;
private BigDecimal price;
private String image_url;
private int shop_id;
private Attributes attrs;
private double querySimilarity;
private double quality;
private Sex sex;
private boolean isTrendy;
private double proximityToStereotype;
private int mItemsInStock;
private ItemSelectedContext mItemContext;
private double mDistanceToContext;//Stores the calculated distance between the context and the item
private int mTimesSelected; // How often was this item part of a context?
private double mTemporaryQuality;
private String[] mNameParts;
private Explanation explanation;
private boolean inFashion;
public int id() {
return id;
}
public Item id(int id) {
explanation = new Explanation();
this.id = id;
return this;
}
public Explanation getExplanation(){
return explanation;
}
public void setExplanation(Explanation explanation){
this.explanation = explanation;
}
public String name() {
return name;
}
public Item name(String name) {
explanation = new Explanation();
this.name = name;
mNameParts = name.split("-");
for (int i = 0; i < mNameParts.length; i++){
mNameParts[i] = mNameParts[i].trim().toLowerCase();
if (mNameParts[i].length() > 1) {
mNameParts[i] = Character.toUpperCase(mNameParts[i].charAt(0)) + mNameParts[i].substring(1);
} else {
mNameParts[i] = "";
}
}
return this;
}
/**
* Gets an array with the parts of the name (strings that are part of the description)
* @return an array with the parts of the name.
*/
public String[] getNameParts(){
String[] strings = Arrays.copyOf(mNameParts, mNameParts.length + 1);
strings[strings.length -1 ] = attributes().getAttributeById(Color.ID).currentValue().descriptor();
return strings;
}
public BigDecimal price() {
return price;
}
public Item price(BigDecimal price) {
explanation = new Explanation();
this.price = price;
return this;
}
public boolean isInFashion() {
return inFashion;
}
public void setInFashion(boolean inFashion) {
this.inFashion = inFashion;
}
public String image() {
return image_url;
}
public Item image(String image_url) {
explanation = new Explanation();
this.image_url = image_url;
return this;
}
public int shopId() {
return shop_id;
}
public Item shopId(int shop_id) {
this.shop_id = shop_id;
return this;
}
public Attributes attributes() {
return attrs;
}
public Item attributes(Attributes attrs) {
explanation = new Explanation();
this.attrs = attrs;
return this;
}
public double querySimilarity() {
return querySimilarity;
}
public Item querySimilarity(double querySimilarity) {
this.querySimilarity = querySimilarity;
return this;
}
public double quality() {
return quality;
}
public Item quality(double quality) {
explanation = new Explanation();
this.quality = quality;
return this;
}
public void setTrendy(boolean isTrendy){
this.isTrendy = isTrendy;
}
public boolean isTrendy(){return isTrendy;}
public void setSex(Sex sex){
this.sex = sex;
}
public Sex getSex(){
return sex;
}
/**
* Gets the proximity to the stereotype, meaning how similar this item and the stereotype are.
* @return the proximity based on a previous calculation
*/
public double getProximityToStereotype() {
return proximityToStereotype;
}
/**
* Sets the proximity to a stereotype of the user.
* @param proximityToStereotype the proximity to the stereotype
*/
public void setProximityToStereotype(double proximityToStereotype) {
this.proximityToStereotype = proximityToStereotype;
}
/**
* Method that sets the amount of items that are currently available in the given shop.
* @param numberOfItems the number of items in stock.
*/
public void setItemsInStock(int numberOfItems){
mItemsInStock = numberOfItems;
}
public int getItemsInStock(){
return mItemsInStock;
}
/**
* Gets the context object, that states in which contexts the item has been selected how often.
* @return The context object.
*/
public ItemSelectedContext getItemContext() {
return mItemContext;
}
/**
* Sets a new Context Object which states in which contexts the item has been selected how often.
* @param itemContext An item Context object that contains information about in which contexts the given item has been selected.
*/
public void setItemContext(ItemSelectedContext itemContext) {
this.mItemContext = itemContext;
}
/**
* Get the distance to the active scenario context.
* @return the distance
*/
public double getDistanceToContext() {
return mDistanceToContext;
}
/**
* Sets the calculated distance to the currently active scenario.
* @param mDistanceToContext the calculated distance
*/
public void setDistanceToContext(double mDistanceToContext) {
this.mDistanceToContext = mDistanceToContext;
}
/**
* Get how often this item was selected in ANY context
* @return times Selected.
*/
public int getTimesSelected() {
return mTimesSelected;
}
/**
* Set how many times this item was selected in any context.
* @param mTimesSelected how many times was the item selected.
*/
public void setTimesSelected(int mTimesSelected) {
this.mTimesSelected = mTimesSelected;
}
@Override
public String toString() {
return "Item{" +
"id=" + id +
", name='" + name + '\'' +
", sex=" + sex.currentValue() +
'}';
}
/**
* This method sets a temporary parameter used in the calculation of the bounded greedy algorithm.
* @param i the similarity
*/
public void setTemporaryQuality(double i) {
mTemporaryQuality = i;
}
/**
* Gets the temporarily stored value.
* @return the similarity for this recommendation cycle
*/
public double getTemporaryQuality(){
return mTemporaryQuality;
}
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.core.ml.job.results;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ObjectParser.ValueType;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.xpack.core.ml.job.config.Job;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
/**
* Model ForecastRequestStats POJO.
*
* This information is produced by the autodetect process and contains
* information about errors, progress and counters. There is exactly 1 document
* per forecast request, getting updated while the request is processed.
*/
public class ForecastRequestStats implements ToXContentObject, Writeable {
/**
* Result type
*/
public static final String RESULT_TYPE_VALUE = "model_forecast_request_stats";
public static final ParseField RESULTS_FIELD = new ParseField(RESULT_TYPE_VALUE);
public static final ParseField FORECAST_ID = new ParseField("forecast_id");
public static final ParseField START_TIME = new ParseField("forecast_start_timestamp");
public static final ParseField END_TIME = new ParseField("forecast_end_timestamp");
public static final ParseField CREATE_TIME = new ParseField("forecast_create_timestamp");
public static final ParseField EXPIRY_TIME = new ParseField("forecast_expiry_timestamp");
public static final ParseField MESSAGES = new ParseField("forecast_messages");
public static final ParseField PROCESSING_TIME_MS = new ParseField("processing_time_ms");
public static final ParseField PROGRESS = new ParseField("forecast_progress");
public static final ParseField PROCESSED_RECORD_COUNT = new ParseField("processed_record_count");
public static final ParseField STATUS = new ParseField("forecast_status");
public static final ParseField MEMORY_USAGE = new ParseField("forecast_memory_bytes");
public static final ConstructingObjectParser<ForecastRequestStats, Void> STRICT_PARSER = createParser(false);
public static final ConstructingObjectParser<ForecastRequestStats, Void> LENIENT_PARSER = createParser(true);
private static ConstructingObjectParser<ForecastRequestStats, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<ForecastRequestStats, Void> parser = new ConstructingObjectParser<>(RESULT_TYPE_VALUE, ignoreUnknownFields,
a -> new ForecastRequestStats((String) a[0], (String) a[1]));
parser.declareString(ConstructingObjectParser.constructorArg(), Job.ID);
parser.declareString(ConstructingObjectParser.constructorArg(), FORECAST_ID);
parser.declareString((modelForecastRequestStats, s) -> {}, Result.RESULT_TYPE);
parser.declareLong(ForecastRequestStats::setRecordCount, PROCESSED_RECORD_COUNT);
parser.declareStringArray(ForecastRequestStats::setMessages, MESSAGES);
parser.declareField(ForecastRequestStats::setTimeStamp,
p -> Instant.ofEpochMilli(p.longValue()), Result.TIMESTAMP, ValueType.LONG);
parser.declareField(ForecastRequestStats::setStartTime,
p -> Instant.ofEpochMilli(p.longValue()), START_TIME, ValueType.LONG);
parser.declareField(ForecastRequestStats::setEndTime,
p -> Instant.ofEpochMilli(p.longValue()), END_TIME, ValueType.LONG);
parser.declareField(ForecastRequestStats::setCreateTime,
p -> Instant.ofEpochMilli(p.longValue()), CREATE_TIME, ValueType.LONG);
parser.declareField(ForecastRequestStats::setExpiryTime,
p -> Instant.ofEpochMilli(p.longValue()), EXPIRY_TIME, ValueType.LONG);
parser.declareDouble(ForecastRequestStats::setProgress, PROGRESS);
parser.declareLong(ForecastRequestStats::setProcessingTime, PROCESSING_TIME_MS);
parser.declareField(ForecastRequestStats::setStatus, p -> ForecastRequestStatus.fromString(p.text()), STATUS, ValueType.STRING);
parser.declareLong(ForecastRequestStats::setMemoryUsage, MEMORY_USAGE);
return parser;
}
public enum ForecastRequestStatus implements Writeable {
OK, FAILED, STOPPED, STARTED, FINISHED, SCHEDULED;
public static ForecastRequestStatus fromString(String statusName) {
return valueOf(statusName.trim().toUpperCase(Locale.ROOT));
}
public static ForecastRequestStatus readFromStream(StreamInput in) throws IOException {
return in.readEnum(ForecastRequestStatus.class);
}
/**
* @return {@code true} if state matches any of the given {@code candidates}
*/
public boolean isAnyOf(ForecastRequestStatus... candidates) {
return Arrays.stream(candidates).anyMatch(candidate -> this == candidate);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeEnum(this);
}
@Override
public String toString() {
return name().toLowerCase(Locale.ROOT);
}
}
private final String jobId;
private final String forecastId;
private long recordCount;
private List<String> messages;
private Instant timestamp = Instant.EPOCH;
private Instant startTime = Instant.EPOCH;
private Instant endTime = Instant.EPOCH;
private Instant createTime = Instant.EPOCH;
private Instant expiryTime = Instant.EPOCH;
private double progress;
private long processingTime;
private long memoryUsage;
private ForecastRequestStatus status = ForecastRequestStatus.OK;
public ForecastRequestStats(String jobId, String forecastId) {
this.jobId = Objects.requireNonNull(jobId);
this.forecastId = Objects.requireNonNull(forecastId);
}
public ForecastRequestStats(ForecastRequestStats forecastRequestStats) {
this.jobId = forecastRequestStats.jobId;
this.forecastId = forecastRequestStats.forecastId;
this.recordCount = forecastRequestStats.recordCount;
this.messages = forecastRequestStats.messages;
this.timestamp = forecastRequestStats.timestamp;
this.startTime = forecastRequestStats.startTime;
this.endTime = forecastRequestStats.endTime;
this.createTime = forecastRequestStats.createTime;
this.expiryTime = forecastRequestStats.expiryTime;
this.progress = forecastRequestStats.progress;
this.processingTime = forecastRequestStats.processingTime;
this.memoryUsage = forecastRequestStats.memoryUsage;
this.status = forecastRequestStats.status;
}
public ForecastRequestStats(StreamInput in) throws IOException {
jobId = in.readString();
forecastId = in.readString();
recordCount = in.readLong();
if (in.readBoolean()) {
messages = in.readStringList();
} else {
messages = null;
}
timestamp = in.readInstant();
startTime = in.readInstant();
endTime = in.readInstant();
createTime = in.readInstant();
expiryTime = in.readInstant();
progress = in.readDouble();
processingTime = in.readLong();
setMemoryUsage(in.readLong());
status = ForecastRequestStatus.readFromStream(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(jobId);
out.writeString(forecastId);
out.writeLong(recordCount);
if (messages != null) {
out.writeBoolean(true);
out.writeStringCollection(messages);
} else {
out.writeBoolean(false);
}
out.writeInstant(timestamp);
out.writeInstant(startTime);
out.writeInstant(endTime);
out.writeInstant(createTime);
out.writeInstant(expiryTime);
out.writeDouble(progress);
out.writeLong(processingTime);
out.writeLong(getMemoryUsage());
status.writeTo(out);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(Job.ID.getPreferredName(), jobId);
builder.field(Result.RESULT_TYPE.getPreferredName(), RESULT_TYPE_VALUE);
builder.field(FORECAST_ID.getPreferredName(), forecastId);
builder.field(PROCESSED_RECORD_COUNT.getPreferredName(), recordCount);
if (messages != null) {
builder.field(MESSAGES.getPreferredName(), messages);
}
if (timestamp.equals(Instant.EPOCH) == false) {
builder.field(Result.TIMESTAMP.getPreferredName(), timestamp.toEpochMilli());
}
if (startTime.equals(Instant.EPOCH) == false) {
builder.field(START_TIME.getPreferredName(), startTime.toEpochMilli());
}
if (endTime.equals(Instant.EPOCH) == false) {
builder.field(END_TIME.getPreferredName(), endTime.toEpochMilli());
}
if (createTime.equals(Instant.EPOCH) == false) {
builder.field(CREATE_TIME.getPreferredName(), createTime.toEpochMilli());
}
if (expiryTime.equals(Instant.EPOCH) == false) {
builder.field(EXPIRY_TIME.getPreferredName(), expiryTime.toEpochMilli());
}
builder.field(PROGRESS.getPreferredName(), progress);
builder.field(PROCESSING_TIME_MS.getPreferredName(), processingTime);
builder.field(MEMORY_USAGE.getPreferredName(), getMemoryUsage());
builder.field(STATUS.getPreferredName(), status);
builder.endObject();
return builder;
}
public String getJobId() {
return jobId;
}
public String getForecastId() {
return forecastId;
}
public static String documentId(String jobId, String forecastId) {
return jobId + "_model_forecast_request_stats_" + forecastId;
}
/**
* Return the document ID used for indexing. As there is 1 and only 1 document
* per forecast request, the id has no dynamic parts.
*
* @return id
*/
public String getId() {
return documentId(jobId, forecastId);
}
public void setRecordCount(long recordCount) {
this.recordCount = recordCount;
}
public long getRecordCount() {
return recordCount;
}
public List<String> getMessages() {
return messages;
}
public void setMessages(List<String> messages) {
this.messages = messages;
}
public void setTimeStamp(Instant timestamp) {
this.timestamp = Instant.ofEpochMilli(timestamp.toEpochMilli());
}
public Instant getTimestamp() {
return timestamp;
}
public void setStartTime(Instant startTime) {
this.startTime = Instant.ofEpochMilli(startTime.toEpochMilli());
}
public Instant getStartTime() {
return startTime;
}
public Instant getEndTime() {
return endTime;
}
public void setEndTime(Instant endTime) {
this.endTime = Instant.ofEpochMilli(endTime.toEpochMilli());
}
public void setCreateTime(Instant createTime) {
this.createTime = Instant.ofEpochMilli(createTime.toEpochMilli());
}
public Instant getCreateTime() {
return createTime;
}
public void setExpiryTime(Instant expiryTime) {
this.expiryTime = Instant.ofEpochMilli(expiryTime.toEpochMilli());
}
public Instant getExpiryTime() {
return expiryTime;
}
/**
* Progress information of the ForecastRequest in the range 0 to 1,
* while 1 means finished
*
* @return progress value
*/
public double getProgress() {
return progress;
}
public void setProgress(double progress) {
this.progress = progress;
}
public long getProcessingTime() {
return processingTime;
}
public void setProcessingTime(long processingTime) {
this.processingTime = processingTime;
}
public long getMemoryUsage() {
return memoryUsage;
}
public void setMemoryUsage(long memoryUsage) {
this.memoryUsage = memoryUsage;
}
public ForecastRequestStatus getStatus() {
return status;
}
public void setStatus(ForecastRequestStatus jobStatus) {
Objects.requireNonNull(jobStatus, "[" + STATUS.getPreferredName() + "] must not be null");
this.status = jobStatus;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other instanceof ForecastRequestStats == false) {
return false;
}
ForecastRequestStats that = (ForecastRequestStats) other;
return Objects.equals(this.jobId, that.jobId) &&
Objects.equals(this.forecastId, that.forecastId) &&
this.recordCount == that.recordCount &&
Objects.equals(this.messages, that.messages) &&
Objects.equals(this.timestamp, that.timestamp) &&
Objects.equals(this.startTime, that.startTime) &&
Objects.equals(this.endTime, that.endTime) &&
Objects.equals(this.createTime, that.createTime) &&
Objects.equals(this.expiryTime, that.expiryTime) &&
this.progress == that.progress &&
this.processingTime == that.processingTime &&
this.memoryUsage == that.memoryUsage &&
Objects.equals(this.status, that.status);
}
@Override
public int hashCode() {
return Objects.hash(jobId, forecastId, recordCount, messages, timestamp, startTime, endTime, createTime, expiryTime,
progress, processingTime, memoryUsage, status);
}
}
| |
package com.github.ltsopensource.store.jdbc.builder;
import com.github.ltsopensource.core.commons.utils.StringUtils;
import com.github.ltsopensource.core.logger.Logger;
import com.github.ltsopensource.core.logger.LoggerFactory;
import com.github.ltsopensource.store.jdbc.SQLFormatter;
import com.github.ltsopensource.store.jdbc.SqlTemplate;
import com.github.ltsopensource.store.jdbc.dbutils.ResultSetHandler;
import com.github.ltsopensource.store.jdbc.exception.JdbcException;
import java.util.LinkedList;
import java.util.List;
/**
* @author Robert HG (254963746@qq.com) on 3/8/16.
*/
public class SelectSql {
private static final Logger LOGGER = LoggerFactory.getLogger(SelectSql.class);
private SqlTemplate sqlTemplate;
private StringBuilder sql = new StringBuilder();
private List<Object> params = new LinkedList<Object>();
private int curOrderByColumnSize = 0;
private static final String ORDER_BY = " ORDER BY ";
public SelectSql(SqlTemplate sqlTemplate) {
this.sqlTemplate = sqlTemplate;
}
public SelectSql select() {
sql.append(" SELECT ");
return this;
}
public SelectSql all() {
sql.append(" * ");
return this;
}
public SelectSql columns(String... columns) {
if (columns == null || columns.length == 0) {
throw new JdbcException("columns must have length");
}
String split = "";
for (String column : columns) {
sql.append(split);
split = ",";
sql.append(column.trim()).append(" ");
}
return this;
}
public SelectSql from() {
sql.append(" FROM ");
return this;
}
public SelectSql table(String table) {
sql.append("`").append(table).append("`");
return this;
}
public SelectSql tables(String... tables) {
String split = "";
for (String table : tables) {
sql.append(split);
split = ",";
sql.append(table.trim()).append(" ");
}
return this;
}
public SelectSql where(){
sql.append(" WHERE ");
return this;
}
public SelectSql whereSql(WhereSql whereSql) {
sql.append(whereSql.getSQL());
params.addAll(whereSql.params());
return this;
}
public SelectSql where(String condition, Object value) {
sql.append(" WHERE ").append(condition);
params.add(value);
return this;
}
public SelectSql and(String condition, Object value) {
sql.append(" AND ").append(condition);
params.add(value);
return this;
}
public SelectSql or(String condition, Object value) {
sql.append(" OR ").append(condition);
params.add(value);
return this;
}
public SelectSql orderBy() {
curOrderByColumnSize = 0;
return this;
}
public SelectSql column(String column, OrderByType order) {
if (StringUtils.isEmpty(column) || order == null) {
return this;
}
if (curOrderByColumnSize == 0) {
sql.append(ORDER_BY);
} else if (curOrderByColumnSize > 0) {
sql.append(" , ");
}
sql.append(" ").append(column).append(" ").append(order);
curOrderByColumnSize++;
return this;
}
public SelectSql and(String condition) {
sql.append(" AND ").append(condition);
return this;
}
public SelectSql or(String condition) {
sql.append(" OR ").append(condition);
return this;
}
public SelectSql andOnNotNull(String condition, Object value) {
if (value == null) {
return this;
}
return and(condition, value);
}
public SelectSql orOnNotNull(String condition, Object value) {
if (value == null) {
return this;
}
return or(condition, value);
}
public SelectSql andOnNotEmpty(String condition, String value) {
if (StringUtils.isEmpty(value)) {
return this;
}
return and(condition, value);
}
public SelectSql orOnNotEmpty(String condition, String value) {
if (StringUtils.isEmpty(value)) {
return this;
}
return or(condition, value);
}
public SelectSql andBetween(String column, Object start, Object end) {
if (start == null && end == null) {
return this;
}
if (start != null && end != null) {
sql.append(" AND (").append(column).append(" BETWEEN ? AND ? ").append(")");
params.add(start);
params.add(end);
return this;
}
if (start == null) {
sql.append(" ").append(column).append(" <= ? ");
params.add(end);
return this;
}
sql.append("").append(column).append(" >= ? ");
params.add(start);
return this;
}
public SelectSql orBetween(String column, Object start, Object end) {
if (start == null && end == null) {
return this;
}
if (start != null && end != null) {
sql.append(" OR (").append(column).append(" BETWEEN ? AND ? ").append(")");
params.add(start);
params.add(end);
return this;
}
if (start == null) {
sql.append(column).append(" <= ? ");
params.add(end);
return this;
}
sql.append(column).append(" >= ? ");
params.add(start);
return this;
}
public SelectSql limit(int start, int size) {
sql.append(" LIMIT ").append(start).append(",").append(size);
return this;
}
public SelectSql groupBy(String... columns) {
sql.append(" GROUP BY ");
String split = "";
for (String column : columns) {
sql.append(split);
split = ",";
sql.append(column.trim()).append(" ");
}
return this;
}
public SelectSql having(String condition) {
sql.append(" HAVING ").append(condition);
return this;
}
public SelectSql innerJoin(String condition) {
sql.append(" INNER JOIN ").append(condition);
return this;
}
public SelectSql rightOuterJoin(String condition) {
sql.append(" RIGHT OUTER JOIN ").append(condition);
return this;
}
public SelectSql leftOuterJoin(String condition) {
sql.append(" LEFT OUTER JOIN ").append(condition);
return this;
}
public <T> List<T> list(ResultSetHandler<List<T>> handler) {
try {
return sqlTemplate.query(getSQL(), handler, params.toArray());
} catch (Exception e) {
throw new JdbcException("Select SQL Error:" + getSQL(), e);
}
}
public <T> T single(ResultSetHandler<T> handler) {
try {
return sqlTemplate.query(getSQL(), handler, params.toArray());
} catch (Exception e) {
throw new JdbcException("Select SQL Error:" + getSQL(), e);
}
}
public <T> T single() {
String finalSQL = getSQL();
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(SQLFormatter.format(finalSQL));
}
return sqlTemplate.queryForValue(finalSQL, params.toArray());
} catch (Exception e) {
throw new JdbcException("Select SQL Error:" + SQLFormatter.format(finalSQL), e);
}
}
public String getSQL() {
return sql.toString();
}
}
| |
/*******************************************************************************
* /*
* *
* * Copyright 2013 Netflix, 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.netflix.staash.connection;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import com.google.common.collect.ImmutableMap;
import com.netflix.astyanax.AstyanaxContext;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.connectionpool.NodeDiscoveryType;
import com.netflix.astyanax.connectionpool.OperationResult;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolConfigurationImpl;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolType;
import com.netflix.astyanax.connectionpool.impl.CountingConnectionPoolMonitor;
import com.netflix.astyanax.cql.CqlStatementResult;
import com.netflix.astyanax.impl.AstyanaxConfigurationImpl;
import com.netflix.astyanax.recipes.storage.CassandraChunkedStorageProvider;
import com.netflix.astyanax.recipes.storage.ChunkedStorage;
import com.netflix.astyanax.recipes.storage.ChunkedStorageProvider;
import com.netflix.astyanax.recipes.storage.ObjectMetadata;
import com.netflix.astyanax.thrift.ThriftFamilyFactory;
import com.netflix.staash.cassandra.discovery.EurekaAstyanaxHostSupplier;
import com.netflix.staash.common.query.QueryFactory;
import com.netflix.staash.common.query.QueryType;
import com.netflix.staash.common.query.QueryUtils;
import com.netflix.staash.json.JsonObject;
import com.netflix.staash.model.StorageType;
public class AstyanaxCassandraConnection implements PaasConnection {
private Keyspace keyspace;
private static Logger logger = Logger
.getLogger(AstyanaxCassandraConnection.class);
public AstyanaxCassandraConnection(String cluster, String db,
EurekaAstyanaxHostSupplier supplier) {
this.keyspace = createAstyanaxKeyspace(cluster, db, supplier);
}
private Keyspace createAstyanaxKeyspace(String clustername, String db,
EurekaAstyanaxHostSupplier supplier) {
String clusterNameOnly = "localhost";
String clusterPortOnly = "9160";
String[] clusterinfo = clustername.split(":");
if (clusterinfo != null && clusterinfo.length == 2) {
clusterNameOnly = clusterinfo[0];
} else {
clusterNameOnly = clustername;
}
AstyanaxContext<Keyspace> keyspaceContext;
if (supplier!=null) {
keyspaceContext = new AstyanaxContext.Builder()
.forCluster("Casss_Paas")
.forKeyspace(db)
.withAstyanaxConfiguration(
new AstyanaxConfigurationImpl()
.setDiscoveryType(
NodeDiscoveryType.DISCOVERY_SERVICE)
.setConnectionPoolType(
ConnectionPoolType.TOKEN_AWARE)
.setDiscoveryDelayInSeconds(60)
.setTargetCassandraVersion("1.2")
.setCqlVersion("3.0.0"))
.withHostSupplier(supplier.getSupplier(clustername))
.withConnectionPoolConfiguration(
new ConnectionPoolConfigurationImpl(clusterNameOnly
+ "_" + db)
.setSocketTimeout(10000)
.setPort(7102)
.setMaxConnsPerHost(10).setInitConnsPerHost(3)
.setSeeds(null))
.withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
.buildKeyspace(ThriftFamilyFactory.getInstance());
} else {
keyspaceContext = new AstyanaxContext.Builder()
.forCluster(clusterNameOnly)
.forKeyspace(db)
.withAstyanaxConfiguration(
new AstyanaxConfigurationImpl()
.setDiscoveryType(
NodeDiscoveryType.RING_DESCRIBE)
.setConnectionPoolType(
ConnectionPoolType.TOKEN_AWARE)
.setDiscoveryDelayInSeconds(60)
.setTargetCassandraVersion("1.2")
.setCqlVersion("3.0.0"))
//.withHostSupplier(hs.getSupplier(clustername))
.withConnectionPoolConfiguration(
new ConnectionPoolConfigurationImpl(clusterNameOnly
+ "_" + db)
.setSocketTimeout(11000)
.setConnectTimeout(2000)
.setMaxConnsPerHost(10).setInitConnsPerHost(3)
.setSeeds(clusterNameOnly+":"+clusterPortOnly))
.buildKeyspace(ThriftFamilyFactory.getInstance());
}
keyspaceContext.start();
Keyspace keyspace;
keyspace = keyspaceContext.getClient();
return keyspace;
}
public String insert(String db, String table, JsonObject payload) {
try {
// if (payload.getString("type").equals("kv")) {
// String str = Hex.bytesToHex(payload.getBinary("value"));
// String stmt = "insert into " + db + "." + table
// + "(key, value)" + " values('"
// + payload.getString("key") + "' , '" + str + "');";
// keyspace.prepareCqlStatement().withCql(stmt).execute();
// } else {
String query = QueryFactory.BuildQuery(QueryType.INSERT,
StorageType.CASSANDRA);
keyspace.prepareCqlStatement()
.withCql(
String.format(query, db + "." + table,
payload.getString("columns"),
payload.getValue("values"))).execute();
// }
} catch (ConnectionException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
return "{\"message\":\"ok\"}";
}
public String writeChunked(String db, String table, String objectName,
InputStream is) {
ChunkedStorageProvider provider = new CassandraChunkedStorageProvider(
keyspace, table);
ObjectMetadata meta;
try {
// if (is!=null) is.reset();
meta = ChunkedStorage.newWriter(provider, objectName, is)
.withChunkSize(0x40000).withConcurrencyLevel(8)
.withMaxWaitTime(10).call();
if (meta != null && meta.getObjectSize() <= 0)
throw new RuntimeException("Object does not exist");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
return "{\"msg\":\"ok\"}";
}
public ByteArrayOutputStream readChunked(String db, String table, String objName) {
ChunkedStorageProvider provider = new CassandraChunkedStorageProvider(
keyspace, table);
ObjectMetadata meta;
ByteArrayOutputStream os = null;
try {
meta = ChunkedStorage.newInfoReader(provider, objName).call();
os = new ByteArrayOutputStream(meta.getObjectSize().intValue());
meta = ChunkedStorage.newReader(provider, objName, os)
.withConcurrencyLevel(8).withMaxWaitTime(10)
.withBatchSize(10).call();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
return os;
}
public String createDB(String dbInfo) {
JsonObject dbJson = new JsonObject(dbInfo);
try {
String rfString = dbJson.getString("rf");
String strategy = dbJson.getString("strategy");
String[] rfs = rfString.split(",");
Map<String, Object> strategyMap = new HashMap<String, Object>();
for (int i = 0; i < rfs.length; i++) {
String[] rfparams = rfs[i].split(":");
strategyMap.put(rfparams[0], (Object) rfparams[1]);
}
keyspace.createKeyspace(ImmutableMap.<String, Object> builder()
.put("strategy_options", strategyMap)
.put("strategy_class", strategy).build());
} catch (Exception e) {
logger.info("DB Exists, Skipping");
}
return "{\"message\":\"ok\"}";
}
public String createTable(JsonObject payload) {
String sql = String
.format(QueryFactory.BuildQuery(QueryType.CREATETABLE,
StorageType.CASSANDRA), payload.getString("db") + "."
+ payload.getString("name"), QueryUtils.formatColumns(
payload.getString("columns"), StorageType.CASSANDRA),
payload.getString("primarykey"));
try {
keyspace.prepareCqlStatement().withCql(sql + ";").execute();
} catch (ConnectionException e) {
logger.info("Table Exists, Skipping");
}
return "{\"message\":\"ok\"}";
}
public String read(String db, String table, String keycol, String key,
String... keyvals) {
try {
if (keyvals != null && keyvals.length == 2) {
String query = QueryFactory.BuildQuery(QueryType.SELECTEVENT,
StorageType.CASSANDRA);
return QueryUtils.formatQueryResult(
keyspace.prepareCqlStatement()
.withCql(
String.format(query, db + "." + table,
keycol, key, keyvals[0],
keyvals[1])).execute()
.getResult(), table);
} else {
String query = QueryFactory.BuildQuery(QueryType.SELECTALL,
StorageType.CASSANDRA);
OperationResult<CqlStatementResult> rs;
if (keycol != null && !keycol.equals("")) {
rs = keyspace
.prepareCqlStatement()
.withCql(
String.format(query, db + "." + table,
keycol, key)).execute();
} else {
rs = keyspace
.prepareCqlStatement()
.withCql(
String.format("select * from %s", db + "."
+ table)).execute();
}
if (rs != null)
return QueryUtils.formatQueryResult(rs.getResult(), table);
return "{\"msg\":\"Nothing is found\"}";
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public String createRowIndexTable(JsonObject payload) {
return null;
}
public void closeConnection() {
// TODO Auto-generated method stub
// No API exists for this in current implementation todo:investigate
}
}
| |
/**
* Copyright 2014 Netflix, 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 rx.internal.util;
import static org.junit.Assert.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import rx.internal.util.atomic.*;
import rx.internal.util.unsafe.*;
public class JCToolsQueueTests {
static final class IntField {
int value;
}
static void await(CyclicBarrier cb) {
try {
cb.await();
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
} catch (BrokenBarrierException ex) {
throw new RuntimeException(ex);
}
}
@Test
public void casBasedUnsafe() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
long offset = UnsafeAccess.addressOf(IntField.class, "value");
IntField f = new IntField();
assertTrue(UnsafeAccess.compareAndSwapInt(f, offset, 0, 1));
assertFalse(UnsafeAccess.compareAndSwapInt(f, offset, 0, 2));
assertEquals(1, UnsafeAccess.getAndAddInt(f, offset, 2));
assertEquals(3, UnsafeAccess.getAndIncrementInt(f, offset));
assertEquals(4, UnsafeAccess.getAndSetInt(f, offset, 0));
}
@Test
public void powerOfTwo() {
assertTrue(Pow2.isPowerOfTwo(1));
assertTrue(Pow2.isPowerOfTwo(2));
assertFalse(Pow2.isPowerOfTwo(3));
assertTrue(Pow2.isPowerOfTwo(4));
assertFalse(Pow2.isPowerOfTwo(5));
assertTrue(Pow2.isPowerOfTwo(8));
assertFalse(Pow2.isPowerOfTwo(13));
assertTrue(Pow2.isPowerOfTwo(16));
assertFalse(Pow2.isPowerOfTwo(25));
assertFalse(Pow2.isPowerOfTwo(31));
assertTrue(Pow2.isPowerOfTwo(32));
}
@Test(expected = NullPointerException.class)
public void testMpmcArrayQueueNull() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
MpmcArrayQueue<Integer> q = new MpmcArrayQueue<Integer>(16);
q.offer(null);
}
@Test(expected = UnsupportedOperationException.class)
public void testMpmcArrayQueueIterator() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
MpmcArrayQueue<Integer> q = new MpmcArrayQueue<Integer>(16);
q.iterator();
}
@Test
public void testMpmcArrayQueueOfferPoll() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
Queue<Integer> q = new MpmcArrayQueue<Integer>(128);
testOfferPoll(q);
}
@Test
public void testMpmcOfferUpToCapacity() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
int n = 128;
MpmcArrayQueue<Integer> queue = new MpmcArrayQueue<Integer>(n);
for (int i = 0; i < n; i++) {
assertTrue(queue.offer(i));
}
assertFalse(queue.offer(n));
}
@Test(expected = UnsupportedOperationException.class)
public void testMpscLinkedAtomicQueueIterator() {
MpscLinkedAtomicQueue<Integer> q = new MpscLinkedAtomicQueue<Integer>();
q.iterator();
}
@Test(expected = NullPointerException.class)
public void testMpscLinkedAtomicQueueNull() {
MpscLinkedAtomicQueue<Integer> q = new MpscLinkedAtomicQueue<Integer>();
q.offer(null);
}
@Test
public void testMpscLinkedAtomicQueueOfferPoll() {
MpscLinkedAtomicQueue<Integer> q = new MpscLinkedAtomicQueue<Integer>();
testOfferPoll(q);
}
@Test(timeout = 2000)
public void testMpscLinkedAtomicQueuePipelined() throws InterruptedException {
final MpscLinkedAtomicQueue<Integer> q = new MpscLinkedAtomicQueue<Integer>();
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < 1000 * 1000; i++) {
set.add(i);
}
final CyclicBarrier cb = new CyclicBarrier(3);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
await(cb);
for (int i = 0; i < 500 * 1000; i++) {
q.offer(i);
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
await(cb);
for (int i = 500 * 1000; i < 1000 * 1000; i++) {
q.offer(i);
}
}
});
t1.start();
t2.start();
await(cb);
Integer j;
for (int i = 0; i < 1000 * 1000; i++) {
while ((j = q.poll()) == null);
assertTrue("Value " + j + " already removed", set.remove(j));
}
assertTrue("Set is not empty", set.isEmpty());
}
@Test(expected = UnsupportedOperationException.class)
public void testMpscLinkedQueueIterator() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
MpscLinkedQueue<Integer> q = new MpscLinkedQueue<Integer>();
q.iterator();
}
@Test(expected = NullPointerException.class)
public void testMpscLinkedQueueNull() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
MpscLinkedQueue<Integer> q = new MpscLinkedQueue<Integer>();
q.offer(null);
}
@Test
public void testMpscLinkedQueueOfferPoll() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
MpscLinkedQueue<Integer> q = new MpscLinkedQueue<Integer>();
testOfferPoll(q);
}
@Test(timeout = 2000)
public void testMpscLinkedQueuePipelined() throws InterruptedException {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
final MpscLinkedQueue<Integer> q = new MpscLinkedQueue<Integer>();
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < 1000 * 1000; i++) {
set.add(i);
}
final CyclicBarrier cb = new CyclicBarrier(3);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
await(cb);
for (int i = 0; i < 500 * 1000; i++) {
q.offer(i);
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
await(cb);
for (int i = 500 * 1000; i < 1000 * 1000; i++) {
q.offer(i);
}
}
});
t1.start();
t2.start();
await(cb);
Integer j;
for (int i = 0; i < 1000 * 1000; i++) {
while ((j = q.poll()) == null);
assertTrue("Value " + j + " already removed", set.remove(j));
}
assertTrue("Set is not empty", set.isEmpty());
}
protected void testOfferPoll(Queue<Integer> q) {
for (int i = 0; i < 64; i++) {
assertTrue(q.offer(i));
}
assertFalse(q.isEmpty());
for (int i = 0; i < 64; i++) {
assertEquals((Integer)i, q.peek());
assertEquals(64 - i, q.size());
assertEquals((Integer)i, q.poll());
}
assertTrue(q.isEmpty());
for (int i = 0; i < 64; i++) {
assertTrue(q.offer(i));
assertEquals((Integer)i, q.poll());
}
assertTrue(q.isEmpty());
assertNull(q.peek());
assertNull(q.poll());
}
@Test(expected = NullPointerException.class)
public void testSpmcArrayQueueNull() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
SpmcArrayQueue<Integer> q = new SpmcArrayQueue<Integer>(16);
q.offer(null);
}
@Test
public void testSpmcArrayQueueOfferPoll() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
Queue<Integer> q = new SpmcArrayQueue<Integer>(128);
testOfferPoll(q);
}
@Test(expected = UnsupportedOperationException.class)
public void testSpmcArrayQueueIterator() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
SpmcArrayQueue<Integer> q = new SpmcArrayQueue<Integer>(16);
q.iterator();
}
@Test
public void testSpmcOfferUpToCapacity() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
int n = 128;
SpmcArrayQueue<Integer> queue = new SpmcArrayQueue<Integer>(n);
for (int i = 0; i < n; i++) {
assertTrue(queue.offer(i));
}
assertFalse(queue.offer(n));
}
@Test(expected = NullPointerException.class)
public void testSpscArrayQueueNull() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(16);
q.offer(null);
}
@Test
public void testSpscArrayQueueOfferPoll() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
Queue<Integer> q = new SpscArrayQueue<Integer>(128);
testOfferPoll(q);
}
@Test(expected = UnsupportedOperationException.class)
public void testSpscArrayQueueIterator() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(16);
q.iterator();
}
@Test(expected = UnsupportedOperationException.class)
public void testSpscLinkedAtomicQueueIterator() {
SpscLinkedAtomicQueue<Integer> q = new SpscLinkedAtomicQueue<Integer>();
q.iterator();
}
@Test(expected = NullPointerException.class)
public void testSpscLinkedAtomicQueueNull() {
SpscLinkedAtomicQueue<Integer> q = new SpscLinkedAtomicQueue<Integer>();
q.offer(null);
}
@Test
public void testSpscLinkedAtomicQueueOfferPoll() {
SpscLinkedAtomicQueue<Integer> q = new SpscLinkedAtomicQueue<Integer>();
testOfferPoll(q);
}
@Test(timeout = 2000)
public void testSpscLinkedAtomicQueuePipelined() throws InterruptedException {
final SpscLinkedAtomicQueue<Integer> q = new SpscLinkedAtomicQueue<Integer>();
final AtomicInteger count = new AtomicInteger();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Integer j;
for (int i = 0; i < 1000 * 1000; i++) {
while ((j = q.poll()) == null);
if (j == i) {
count.getAndIncrement();
}
}
}
});
t.start();
for (int i = 0; i < 1000 * 1000; i++) {
assertTrue(q.offer(i));
}
t.join();
assertEquals(1000 * 1000, count.get());
}
@Test(expected = UnsupportedOperationException.class)
public void testSpscLinkedQueueIterator() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
SpscLinkedQueue<Integer> q = new SpscLinkedQueue<Integer>();
q.iterator();
}
@Test(expected = NullPointerException.class)
public void testSpscLinkedQueueNull() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
SpscLinkedQueue<Integer> q = new SpscLinkedQueue<Integer>();
q.offer(null);
}
@Test
public void testSpscLinkedQueueOfferPoll() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
SpscLinkedQueue<Integer> q = new SpscLinkedQueue<Integer>();
testOfferPoll(q);
}
@Test(timeout = 2000)
public void testSpscLinkedQueuePipelined() throws InterruptedException {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
final SpscLinkedQueue<Integer> q = new SpscLinkedQueue<Integer>();
final AtomicInteger count = new AtomicInteger();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Integer j;
for (int i = 0; i < 1000 * 1000; i++) {
while ((j = q.poll()) == null);
if (j == i) {
count.getAndIncrement();
}
}
}
});
t.start();
for (int i = 0; i < 1000 * 1000; i++) {
assertTrue(q.offer(i));
}
t.join();
assertEquals(1000 * 1000, count.get());
}
@Test
public void testSpscOfferUpToCapacity() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
int n = 128;
SpscArrayQueue<Integer> queue = new SpscArrayQueue<Integer>(n);
for (int i = 0; i < n; i++) {
assertTrue(queue.offer(i));
}
assertFalse(queue.offer(n));
}
@Test(expected = InternalError.class)
public void testUnsafeAccessAddressOf() {
if (!UnsafeAccess.isUnsafeAvailable()) {
return;
}
UnsafeAccess.addressOf(Object.class, "field");
}
}
| |
/*
Copyright (C) 2001, 2009 United States Government
as represented by the Administrator of the
National Aeronautics and Space Administration.
All Rights Reserved.
*/
package gov.nasa.worldwind.terrain;
import gov.nasa.worldwind.WorldWind;
import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.cache.FileStore;
import gov.nasa.worldwind.event.*;
import gov.nasa.worldwind.geom.*;
import gov.nasa.worldwind.retrieve.*;
import gov.nasa.worldwind.util.*;
import java.io.*;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.*;
/**
* Downloads elevation data not currently available in the World Wind file cache or a specified {@link FileStore}. The
* class derives from {@link Thread} and is meant to operate in its own thread.
* <p/>
* The sector and resolution associated with the downloader are specified during construction and are final.
*
* @author tag
* @version $Id: BasicElevationModelBulkDownloader.java 12958 2009-12-22 05:55:15Z garakl $
*/
public class BasicElevationModelBulkDownloader extends BulkRetrievalThread
{
protected final static int MAX_TILE_COUNT_PER_REGION = 200;
protected final static long DEFAULT_AVERAGE_FILE_SIZE = 45000L;
protected final BasicElevationModel elevationModel;
protected final int level;
protected ArrayList<Tile> missingTiles;
/**
* Constructs a downloader to retrieve elevations not currently available in the World Wind file cache.
* <p/>
* The thread returned is not started during construction, the caller must start the thread.
*
* @param elevationModel the elevation model for which to download elevations.
* @param sector the sector to download data for. This value is final.
* @param resolution the target resolution, provided in radians of latitude per texel. This value is final.
* @param listener an optional retrieval listener. May be null.
*
* @throws IllegalArgumentException if either the elevation model or sector are null, or the resolution is less than
* zero.
*/
public BasicElevationModelBulkDownloader(BasicElevationModel elevationModel, Sector sector, double resolution,
BulkRetrievalListener listener)
{
// Arguments checked in parent constructor
super(elevationModel, sector, resolution, elevationModel.getDataFileStore(), listener);
this.elevationModel = elevationModel;
this.level = computeLevelForResolution(sector, resolution);
}
/**
* Constructs a downloader to retrieve elevations not currently available in a specified file store.
* <p/>
* The thread returned is not started during construction, the caller must start the thread.
*
* @param elevationModel the elevation model for which to download elevations.
* @param sector the sector to download data for. This value is final.
* @param resolution the target resolution, provided in radians of latitude per texel. This value is final.
* @param fileStore the file store in which to place the downloaded elevations.
* @param listener an optional retrieval listener. May be null.
*
* @throws IllegalArgumentException if either the elevation model, the sector or file store are null, or the
* resolution is less than zero.
*/
public BasicElevationModelBulkDownloader(BasicElevationModel elevationModel, Sector sector, double resolution,
FileStore fileStore, BulkRetrievalListener listener)
{
// Arguments checked in parent constructor
super(elevationModel, sector, resolution, fileStore, listener);
this.elevationModel = elevationModel;
this.level = computeLevelForResolution(sector, resolution);
}
public void run()
{
try
{
// Init progress with missing tiles count estimate
this.progress.setTotalCount(this.estimateMissingTilesCount(20));
this.progress.setTotalSize(this.progress.getTotalCount() * estimateAverageTileSize());
// Determine and request missing tiles by level/region
for (int levelNumber = 0; levelNumber <= this.level; levelNumber++)
{
if (elevationModel.getLevels().isLevelEmpty(levelNumber))
continue;
int div = this.computeRegionDivisions(this.sector, levelNumber, MAX_TILE_COUNT_PER_REGION);
Iterator<Sector> regionsIterator = this.getRegionIterator(this.sector, div);
Sector region;
while (regionsIterator.hasNext())
{
region = regionsIterator.next();
// Determine missing tiles
this.missingTiles = getMissingTilesInSector(region, levelNumber);
// Submit missing tiles requests at intervals
while (this.missingTiles.size() > 0)
{
submitMissingTilesRequests();
if (this.missingTiles.size() > 0)
Thread.sleep(RETRIEVAL_SERVICE_POLL_DELAY);
}
}
}
// Set progress to 100%
this.progress.setTotalCount(this.progress.getCurrentCount());
this.progress.setTotalSize(this.progress.getCurrentSize());
}
catch (InterruptedException e)
{
String message = Logging.getMessage("generic.BulkRetrievalInterrupted", elevationModel.getName());
Logging.logger().log(java.util.logging.Level.WARNING, message, e);
}
catch (Exception e)
{
String message = Logging.getMessage("generic.ExceptionDuringBulkRetrieval", elevationModel.getName());
Logging.logger().severe(message);
throw new RuntimeException(message);
}
}
// protected int countMissingTiles() throws InterruptedException
// {
// int count = 0;
// for (int levelNumber = 0; levelNumber <= this.level; levelNumber++)
// {
// if (this.elevationModel.getLevels().isLevelEmpty(levelNumber))
// continue;
//
// count += getMissingTilesInSector(this.sector, levelNumber).size();
// }
//
// return count;
// }
protected synchronized void submitMissingTilesRequests() throws InterruptedException
{
RetrievalService rs = WorldWind.getRetrievalService();
int i = 0;
while (this.missingTiles.size() > i && rs.isAvailable())
{
Thread.sleep(1); // generates InterruptedException if thread has been interrupted
Tile tile = this.missingTiles.get(i);
if (this.elevationModel.getLevels().isResourceAbsent(tile))
{
removeAbsentTile(tile); // tile is absent, count it off.
continue;
}
URL url = this.fileStore.findFile(tile.getPath(), false);
if (url != null)
{
// tile has been retrieved and is local now, count it as retrieved.
removeRetrievedTile(tile);
continue;
}
this.elevationModel.downloadElevations(tile,
new BulkDownloadPostProcessor(tile, this.elevationModel, this.fileStore));
i++;
}
}
protected class BulkDownloadPostProcessor extends BasicElevationModel.DownloadPostProcessor
{
public BulkDownloadPostProcessor(Tile tile, BasicElevationModel elevationModel, FileStore fileStore)
{
super(tile, elevationModel, fileStore);
}
public ByteBuffer run(Retriever retriever)
{
ByteBuffer buffer = super.run(retriever);
if (retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL))
removeRetrievedTile(this.tile);
if (hasRetrievalListeners())
callRetrievalListeners(retriever, this.tile);
return buffer;
}
}
protected void callRetrievalListeners(Retriever retriever, Tile tile)
{
String eventType = (retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL))
? BulkRetrievalEvent.RETRIEVAL_SUCCEEDED : BulkRetrievalEvent.RETRIEVAL_FAILED;
super.callRetrievalListeners(new BulkRetrievalEvent(this.elevationModel, eventType, tile.getPath()));
}
protected synchronized void removeRetrievedTile(Tile tile)
{
this.missingTiles.remove(tile);
// Update progress
this.progress.setCurrentCount(this.progress.getCurrentCount() + 1);
this.progress.setCurrentSize(this.progress.getCurrentSize() + estimateAverageTileSize());
this.progress.setLastUpdateTime(System.currentTimeMillis());
this.normalizeProgress();
}
protected synchronized void removeAbsentTile(Tile tile)
{
this.missingTiles.remove(tile);
// Decrease progress expected total count and size
this.progress.setTotalCount(this.progress.getTotalCount() - 1);
this.progress.setTotalSize(this.progress.getTotalSize() - estimateAverageTileSize());
this.progress.setLastUpdateTime(System.currentTimeMillis());
this.normalizeProgress();
}
protected void normalizeProgress()
{
if (this.progress.getTotalCount() < this.progress.getCurrentCount())
{
this.progress.setTotalCount(this.progress.getCurrentCount());
this.progress.setTotalSize(this.progress.getCurrentSize());
}
}
protected long getEstimatedMissingDataSize()
{
// Get missing tiles count estimate
long totMissing = estimateMissingTilesCount(6);
// Get average tile size estimate
long averageTileSize = estimateAverageTileSize();
return totMissing * averageTileSize;
}
protected long estimateMissingTilesCount(int numSamples)
{
int maxLevel = computeLevelForResolution(sector, resolution);
// Total expected tiles
long totCount = 0;
for (int levelNumber = 0; levelNumber <= maxLevel; levelNumber++)
{
if (!this.elevationModel.getLevels().isLevelEmpty(levelNumber))
totCount += this.countTilesInSector(sector, levelNumber);
}
// Sample random small sized sectors at finest level
int div = this.computeRegionDivisions(this.sector, maxLevel, 36); // max 6x6 tiles per region
Sector[] regions = computeRandomRegions(this.sector, div, numSamples);
long regionMissing = 0;
long regionCount = 0;
try
{
if (regions.length < numSamples)
{
regionCount = this.countTilesInSector(this.sector, maxLevel);
regionMissing = getMissingTilesInSector(this.sector, maxLevel).size();
}
else
{
for (Sector region : regions)
{
// Count how many tiles are missing in each sample region
regionCount += this.countTilesInSector(region, maxLevel);
regionMissing += getMissingTilesInSector(region, maxLevel).size();
}
}
}
catch (InterruptedException e)
{
return 0;
}
catch (Exception e)
{
String message = Logging.getMessage("generic.ExceptionDuringDataSizeEstimate", this.getName());
Logging.logger().severe(message);
throw new RuntimeException(message);
}
// Extrapolate total missing count
return (long)(totCount * ((double)regionMissing / regionCount));
}
protected long estimateAverageTileSize()
{
Long previouslyComputedSize = (Long) this.elevationModel.getValue(AVKey.AVERAGE_TILE_SIZE);
if (previouslyComputedSize != null)
return previouslyComputedSize;
long size = 0;
int count = 0;
// Average cached tile files size in a few directories from first non empty level
Level targetLevel = this.elevationModel.getLevels().getFirstLevel();
while (targetLevel.isEmpty() && !targetLevel.equals(this.elevationModel.getLevels().getLastLevel()))
{
targetLevel = this.elevationModel.getLevels().getLevel(targetLevel.getLevelNumber() + 1);
}
File cacheRoot = new File(this.fileStore.getWriteLocation(), targetLevel.getPath());
if (cacheRoot.exists())
{
File[] rowDirs = cacheRoot.listFiles(new FileFilter()
{
public boolean accept(File file)
{
return file.isDirectory();
}
});
for (File dir : rowDirs)
{
long averageSize = computeAverageTileSize(dir);
if (averageSize > 0)
{
size += averageSize;
count++;
}
if (count >= 2) // average content from up to 2 cache folders
break;
}
}
Long averageTileSize = DEFAULT_AVERAGE_FILE_SIZE;
if (count > 0 && size > 0)
{
averageTileSize = size / count;
this.elevationModel.setValue(AVKey.AVERAGE_TILE_SIZE, averageTileSize);
}
return averageTileSize;
}
protected static long computeAverageTileSize(File dir)
{
long size = 0;
int count = 0;
File[] files = dir.listFiles();
for (File file : files)
{
try
{
FileInputStream fis = new FileInputStream(file);
size += fis.available();
fis.close();
count++;
}
catch (IOException e)
{
count += 0;
}
}
return count > 0 ? size / count : 0;
}
protected int computeLevelForResolution(Sector sector, double resolution)
{
if (sector == null)
{
String message = Logging.getMessage("nullValue.SectorIsNull");
Logging.logger().severe(message);
throw new IllegalStateException(message);
}
// Find the first level exceeding the desired resolution
double texelSize;
Level targetLevel = this.elevationModel.getLevels().getLastLevel();
for (int i = 0; i < this.elevationModel.getLevels().getLastLevel().getLevelNumber(); i++)
{
if (this.elevationModel.getLevels().isLevelEmpty(i))
continue;
texelSize = this.elevationModel.getLevels().getLevel(i).getTexelSize();
if (texelSize > resolution)
continue;
targetLevel = this.elevationModel.getLevels().getLevel(i);
break;
}
// Choose the level closest to the resolution desired
if (targetLevel.getLevelNumber() != 0 && !this.elevationModel.getLevels().isLevelEmpty(
targetLevel.getLevelNumber() - 1))
{
Level nextLowerLevel = this.elevationModel.getLevels().getLevel(targetLevel.getLevelNumber() - 1);
double dless = Math.abs(nextLowerLevel.getTexelSize() - resolution);
double dmore = Math.abs(targetLevel.getTexelSize() - resolution);
if (dless < dmore)
targetLevel = nextLowerLevel;
}
return targetLevel.getLevelNumber();
}
protected long countTilesInSector(Sector sector, int levelNumber)
{
if (sector == null)
{
String msg = Logging.getMessage("nullValue.SectorIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
Level targetLevel = this.elevationModel.getLevels().getLastLevel();
if (levelNumber >= 0)
{
for (int i = levelNumber; i < this.elevationModel.getLevels().getLastLevel().getLevelNumber(); i++)
{
if (this.elevationModel.getLevels().isLevelEmpty(i))
continue;
targetLevel = this.elevationModel.getLevels().getLevel(i);
break;
}
}
// Collect all the tiles intersecting the input sector.
LatLon delta = targetLevel.getTileDelta();
LatLon origin = this.elevationModel.getLevels().getTileOrigin();
final int nwRow = Tile.computeRow(delta.getLatitude(), sector.getMaxLatitude(), origin.getLatitude());
final int nwCol = Tile.computeColumn(delta.getLongitude(), sector.getMinLongitude(), origin.getLongitude());
final int seRow = Tile.computeRow(delta.getLatitude(), sector.getMinLatitude(), origin.getLatitude());
final int seCol = Tile.computeColumn(delta.getLongitude(), sector.getMaxLongitude(), origin.getLongitude());
long numRows = nwRow - seRow + 1;
long numCols = seCol - nwCol + 1;
return numRows * numCols;
}
protected Tile[][] getTilesInSector(Sector sector, int levelNumber)
{
if (sector == null)
{
String msg = Logging.getMessage("nullValue.SectorIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
Level targetLevel = this.elevationModel.getLevels().getLastLevel();
if (levelNumber >= 0)
{
for (int i = levelNumber; i < this.elevationModel.getLevels().getLastLevel().getLevelNumber(); i++)
{
if (this.elevationModel.getLevels().isLevelEmpty(i))
continue;
targetLevel = this.elevationModel.getLevels().getLevel(i);
break;
}
}
// Collect all the tiles intersecting the input sector.
LatLon delta = targetLevel.getTileDelta();
LatLon origin = this.elevationModel.getLevels().getTileOrigin();
final int nwRow = Tile.computeRow(delta.getLatitude(), sector.getMaxLatitude(), origin.getLatitude());
final int nwCol = Tile.computeColumn(delta.getLongitude(), sector.getMinLongitude(), origin.getLongitude());
final int seRow = Tile.computeRow(delta.getLatitude(), sector.getMinLatitude(), origin.getLatitude());
final int seCol = Tile.computeColumn(delta.getLongitude(), sector.getMaxLongitude(), origin.getLongitude());
int numRows = nwRow - seRow + 1;
int numCols = seCol - nwCol + 1;
Tile[][] sectorTiles = new Tile[numRows][numCols];
for (int row = nwRow; row >= seRow; row--)
{
for (int col = nwCol; col <= seCol; col++)
{
TileKey key = new TileKey(targetLevel.getLevelNumber(), row, col, targetLevel.getCacheName());
Sector tileSector = this.elevationModel.getLevels().computeSectorForKey(key);
sectorTiles[nwRow - row][col - nwCol] = new Tile(tileSector, targetLevel, row, col);
}
}
return sectorTiles;
}
protected ArrayList<Tile> getMissingTilesInSector(Sector sector, int levelNumber) throws InterruptedException
{
ArrayList<Tile> tiles = new ArrayList<Tile>();
Tile[][] tileArray = getTilesInSector(sector, levelNumber);
for (Tile[] row : tileArray)
{
for (Tile tile : row)
{
Thread.sleep(1); // generates InterruptedException if thread has been interrupted
if (tile == null)
continue;
if (isTileLocalOrAbsent(tile))
continue; // tile is local or absent
tiles.add(tile);
}
}
return tiles;
}
protected int computeRegionDivisions(Sector sector, int levelNumber, int maxCount)
{
long tileCount = countTilesInSector(sector, levelNumber);
if (tileCount <= maxCount)
return 1;
// Divide sector in regions that will contain no more tiles then maxCount
return (int) Math.ceil(Math.sqrt((float) tileCount / maxCount));
}
protected Sector[] computeRandomRegions(Sector sector, int div, int numRegions)
{
if (numRegions > div * div)
return sector.subdivide(div);
final double dLat = sector.getDeltaLat().degrees / div;
final double dLon = sector.getDeltaLon().degrees / div;
ArrayList<Sector> regions = new ArrayList<Sector>(numRegions);
Random rand = new Random();
while (regions.size() < numRegions)
{
int row = rand.nextInt(div);
int col = rand.nextInt(div);
double maxLat = (row+1 < div) ? sector.getMinLatitude().degrees + dLat * row + dLat
: sector.getMaxLatitude().degrees;
double maxLon = (col+1 < div) ? sector.getMinLongitude().degrees + dLon * col + dLon
: sector.getMaxLongitude().degrees;
Sector s = Sector.fromDegrees(
sector.getMinLatitude().degrees + dLat * row, maxLat,
sector.getMinLongitude().degrees + dLon * col, maxLon );
if (!regions.contains(s))
regions.add(s);
}
return regions.toArray(new Sector[numRegions]);
}
protected Iterator<Sector> getRegionIterator(final Sector sector, final int div)
{
final double dLat = sector.getDeltaLat().degrees / div;
final double dLon = sector.getDeltaLon().degrees / div;
return new Iterator<Sector>()
{
int row = 0;
int col = 0;
public boolean hasNext()
{
return row < div;
}
public Sector next()
{
double maxLat = (row+1 < div) ? sector.getMinLatitude().degrees + dLat * row + dLat
: sector.getMaxLatitude().degrees;
double maxLon = (col+1 < div) ? sector.getMinLongitude().degrees + dLon * col + dLon
: sector.getMaxLongitude().degrees;
Sector s = Sector.fromDegrees(
sector.getMinLatitude().degrees + dLat * row, maxLat,
sector.getMinLongitude().degrees + dLon * col, maxLon );
col++;
if (col >= div)
{
col = 0;
row++;
}
return s;
}
public void remove()
{
}
};
}
protected boolean isTileLocalOrAbsent(Tile tile)
{
if (this.elevationModel.getLevels().isResourceAbsent(tile))
return true; // tile is absent
URL url = this.fileStore.findFile(tile.getPath(), false);
return url != null && !this.elevationModel.isFileExpired(tile, url, this.fileStore);
}
}
| |
/*
* Copyright 2015 The SageTV Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sage;
public class Java2DSageRenderer extends SageRenderer
{
public static final boolean CACHE_SHAPES = false;
public static final java.awt.Color TRANSPARENT_BLACK = new java.awt.Color(0, 0, 0, 0);
public static final String OSD_RENDERING_PLUGIN_CLASS = "osd_rendering_plugin_class";
public Java2DSageRenderer(ZRoot inMaster)
{
super(inMaster);
vf = uiMgr.getVideoFrame();
enable2DScaleCache = !uiMgr.getBoolean("ui/disable_2d_scaling_cache", false);
}
public boolean allocateBuffers(int width, int height)
{
return true;
}
public void preprocessNextDisplayList(java.util.ArrayList v)
{
cullDisplayList(v);
for (int i = 0; i < v.size(); i++)
{
RenderingOp op = (RenderingOp) v.get(i);
if (!op.isAnimationOp() && !op.isEffectOp() && op.srcRect != null && (op.srcRect.width <= 0 || op.srcRect.height <= 0))
{
v.remove(i);
i--;
}
if (op.isImageOp())
{
// Cache the image if its going to be scaled, otherwise just ensure that cached image stays alive
if (enable2DScaleCache &&
(Math.round(op.copyImageRect.width) != op.texture.getWidth(op.textureIndex) ||
Math.round(op.copyImageRect.height) != op.texture.getHeight(op.textureIndex)))
{
int targetW, targetH;
if (true/*MathUtils.isTranslateScaleOnlyMatrix(op.renderXform) &&
MathUtils.getScaleX(op.renderXform) >= 0 && MathUtils.getScaleY(op.renderXform) >= 0*/)
{
float scaleX = op.texture.getWidth(op.textureIndex) / op.copyImageRect.width;
float scaleY = op.texture.getHeight(op.textureIndex) / op.copyImageRect.height;
// Removing the scaling from the transformation and leave just the translation
float transX = op.copyImageRect.x;//MathUtils.getTranslateX(op.renderXform);
float transY = op.copyImageRect.y;//MathUtils.getTranslateY(op.renderXform);
//op.renderXform = MathUtils.createTranslateMatrix(transX, transY);
op.scaleSrc(1/scaleX, 1/scaleY);
// op.srcRect.x /= scaleX;
// op.srcRect.width /= scaleX;
// op.srcRect.height /= scaleY;
// op.srcRect.y /= scaleY;
targetW = Math.round(op.copyImageRect.width);
targetH = Math.round(op.copyImageRect.height);
}
else
{
targetW = op.texture.getWidth(op.textureIndex);
targetH = op.texture.getHeight(op.textureIndex);
}
if (op.primitive != null && op.primitive.cornerArc > 0)
op.textureIndex = op.texture.getImageIndex(targetW,
targetH, new java.awt.geom.RoundRectangle2D.Float(0, 0,
targetW, targetH,
op.primitive.cornerArc, op.primitive.cornerArc));
else if (op.privateData instanceof java.awt.Insets[])
{
op.textureIndex =
op.texture.getImageIndex(
targetW,
targetH,
(java.awt.Insets[]) op.privateData);
}
else
op.textureIndex = op.texture.getImageIndex(targetW, targetH);
}
}
/*else if (op.isPrimitiveOp() && CACHE_SHAPES)
{
// Convert the primitive to an image
op.texture = getAcceleratedShape(op.primitive);
op.primitive = null;
}*/
else if (op.isTextOp() && !(op.text.font instanceof MetaFont.JavaFont))
{
convertGlyphsToCachedImages(op);
if (op.text.fontImage != null && op.text.renderImageNumCache != null)
{
for (int j = 0; j < op.text.renderImageNumCache.length; j++)
{
if (op.text.renderImageNumCache[j] != -1)
{
op.text.fontImage.getJavaImage(op.text.renderImageNumCache[j]);
op.text.fontImage.removeJavaRef(op.text.renderImageNumCache[j]);
}
}
}
continue;
}
}
}
protected boolean compositeSurfaces(Object targetSurface, Object srcSurface, float alphaFactor, java.awt.geom.Rectangle2D region)
{
java.awt.image.BufferedImage target = (java.awt.image.BufferedImage) targetSurface;
java.awt.image.BufferedImage src = (java.awt.image.BufferedImage) srcSurface;
if (src != null && target != null)
{
java.awt.Graphics2D g2 = target.createGraphics();
g2.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, alphaFactor));
int x = (int)Math.round(region.getX());
int y = (int)Math.round(region.getY());
int x2 = (int)Math.round(region.getX() + region.getWidth());
int y2 = (int)Math.round(region.getY() + region.getHeight());
g2.drawImage(src, x, y, x2, y2, x, y, x2, y2, null);
g2.dispose();
return true;
}
return false;
}
public boolean executeDisplayList(java.awt.Rectangle clipRect)
{
// if (Sage.DBG) System.out.println("Java2DSageRenderer is executing displayList=" + currDisplayList);
if (ANIM_DEBUG) System.out.println("Executing display list now");
if (currDisplayList == null)
return true; // should be false???
boolean setVideoRegion = false;
boolean usedVideoOp = false;
refreshVideo = false;
// NOW EXECUTE THE DISPLAY LIST
java.awt.Graphics2D g2;
if (uiMgr.getBoolean("ui/disable_2d_double_buffering", false) && !hasOSDRenderer())
{
if (primary != null)
{
primary.flush();
primary = null;
}
g2 = (java.awt.Graphics2D) master.getGraphics();
}
else
{
if (primary == null || primary.getWidth() < master.getRoot().getWidth() ||
primary.getHeight() < master.getRoot().getHeight())
{
if (primary != null)
{
primary.flush();
primary = null;
}
Sage.gc();
primary = new java.awt.image.BufferedImage(master.getRoot().getWidth(),
master.getRoot().getHeight(), java.awt.image.BufferedImage.TYPE_INT_ARGB);
if (Sage.DBG) System.out.println("Allocated primary buffer: " + primary);
}
g2 = primary.createGraphics();
}
//g2.setBackground(TRANSPARENT_BLACK);
boolean hqRender = uiMgr.getBoolean("java2d_render_higher_quality", true);
if (hqRender)
{
// g2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
// g2.setRenderingHint(java.awt.RenderingHints.KEY_DITHERING, java.awt.RenderingHints.VALUE_DITHER_ENABLE);
g2.setRenderingHint(java.awt.RenderingHints.KEY_INTERPOLATION, java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.setRenderingHint(java.awt.RenderingHints.KEY_ALPHA_INTERPOLATION, java.awt.RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
// g2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_PURE);
}
else
{
// g2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_SPEED);
// g2.setRenderingHint(java.awt.RenderingHints.KEY_DITHERING, java.awt.RenderingHints.VALUE_DITHER_DISABLE);
g2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_OFF);
g2.setRenderingHint(java.awt.RenderingHints.KEY_INTERPOLATION, java.awt.RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g2.setRenderingHint(java.awt.RenderingHints.KEY_ALPHA_INTERPOLATION, java.awt.RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
}
//g2.clearRect(clipRect.x, clipRect.y, clipRect.width, clipRect.height);
// NOTE: Update on 12/8/04
// I changed the clipping to be done in the destination space. This was due to rounding errors when filling
// shapes. This caused the edge artifact in OSD rendering where there'd be horizontal lines left sometimes in the UI.
// So now the clipping happens before we set the new transformation matrix. We also must intersect the destRect
// with the clipRect to fix the problem...not exactly sure why we have to do that, but without it, it's not fixed.
currSurface = primary;
// These should be empty; but just in case there's an exception
surfStack.clear();
g2Stack.clear();
animsThatGoAfterSurfPop.clear();
java.awt.geom.AffineTransform baseXform = g2.getTransform();
java.awt.geom.AffineTransform tempXform = new java.awt.geom.AffineTransform();
java.util.Stack matrixStack = new java.util.Stack();
long renderStartTime = Sage.eventTime();
boolean effectAnimationsActive = false;
boolean effectAnimationsLocked = false;
java.util.Stack alphaStack = new java.util.Stack();
float currEffectAlpha = 1.0f;
java.util.Stack effectClipStack = new java.util.Stack();
java.awt.geom.Rectangle2D.Float currEffectClip = null;
matrixStack.push(baseXform);
if (dlThatWasComposited != currDisplayList || !uiMgr.areLayersEnabled())
{
boolean freshDL = dlThatWasComposited != currDisplayList;
dlThatWasComposited = null;
// This is all of the surface names that have been used in Out animation operations. Therefore
// they should NOT also be used for any In operation. If they are we should duplicate
// the surface and use that for the Out operation.
if (uiMgr.areLayersEnabled())
fixDuplicateAnimSurfs(currDisplayList, clipRect);
compositeOps.clear();
java.util.Set clearedSurfs = new java.util.HashSet();
javax.vecmath.Matrix4f tempMat = new javax.vecmath.Matrix4f();
//java.awt.geom.AffineTransform myXform = new java.awt.geom.AffineTransform();
java.awt.geom.Rectangle2D.Float tempClipRect = new java.awt.geom.Rectangle2D.Float();
for (int i = 0; i <= currDisplayList.size(); i++)
{
RenderingOp op;
if (i == currDisplayList.size())
{
if (waitIndicatorState && waitIndicatorRops != null)
{
op = (RenderingOp) waitIndicatorRops.get((++waitIndicatorRopsIndex) % waitIndicatorRops.size());
}
else
break;
}
else
op = (RenderingOp) currDisplayList.get(i);
// Skip transparent rendering ops
if (!op.isEffectOp() && currEffectAlpha == 0)
continue;
if (op.isEffectOp())
{
if (op.effectTracker != null)
{
op.effectTracker.processEffectState(renderStartTime, freshDL);
alphaStack.push(new Float(currEffectAlpha));
effectClipStack.push(currEffectClip);
if (op.effectTracker.hasFade())
{
float nextFade = op.effectTracker.getCurrentFade();
currEffectAlpha *= nextFade;
}
if (op.effectTracker.isKiller())
currEffectAlpha = 0;
if (op.effectTracker.getCurrentTransform(tempMat, op.srcRect))
{
if (op.destRect != null)
{
// Now apply the effect to the clipping rectangle to account for the actual effect; and then
// reclip against what the rect actually is
currEffectClip = MathUtils.transformRectCoords(op.destRect, MathUtils.createInverse(tempMat));
currEffectClip.intersect(currEffectClip, op.destRect, currEffectClip);
// currEffectClip.intersect(currEffectClip, clipRect, currEffectClip);
}
MathUtils.convertToAffineTransform(tempMat, tempXform);
tempXform.preConcatenate((java.awt.geom.AffineTransform) matrixStack.peek());
matrixStack.push(tempXform.clone());
}
else
{
// So we match the pop() below
matrixStack.push(matrixStack.peek());
}
if (op.effectTracker.isActive())
{
effectAnimationsActive = true;
if (op.effectTracker.requiresCompletion())
effectAnimationsLocked = true;
}
}
else
{
matrixStack.pop();
currEffectAlpha = ((Float) alphaStack.pop()).floatValue();
currEffectClip = (java.awt.geom.Rectangle2D.Float) effectClipStack.pop();
}
}
else if (op.isImageOp())
{
g2.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, Math.min(1.0f, op.alphaFactor * currEffectAlpha)));
// java.awt.geom.AffineTransform currXform = op.renderXform;
// myXform.setToTranslation(op.copyImageRect.x, op.copyImageRect.y);
// Workaround for JDK Bug# 4916948 to get floating point translation
// BUT it causes a big performance hit because it reallocates everything it draws so don't do it
//at.shear(0.0000001, 0.0000001);
g2.setTransform((java.awt.geom.AffineTransform) matrixStack.peek());
/* if (op.destRect.width < 0)
{
op.destRect.x += op.destRect.width;
op.destRect.width *= -1;
}
if (op.destRect.height < 0)
{
op.destRect.y += op.destRect.height;
op.destRect.height *= -1;
}*/
g2.setClip(op.destRect.createIntersection(currEffectClip != null ? (java.awt.geom.Rectangle2D)currEffectClip : (java.awt.geom.Rectangle2D)clipRect));
/* if ((op.opFlags & RenderingOp.RENDER_FLAG_FLIP_X) != 0 && (op.opFlags & RenderingOp.RENDER_FLAG_FLIP_Y) != 0)
{
g2.scale(-1, -1);
g2.translate(-1*(2*op.destRect.x + op.destRect.width), -1*(2*op.destRect.y + op.destRect.height));
}
else if ((op.opFlags & RenderingOp.RENDER_FLAG_FLIP_X) != 0)
{
g2.scale(-1, 1);
g2.translate(-1*(2*op.destRect.x + op.destRect.width), 0);
}
else if ((op.opFlags & RenderingOp.RENDER_FLAG_FLIP_Y) != 0)
{
g2.scale(1, -1);
g2.translate(0, -1*(2*op.destRect.y + op.destRect.height));
}
*/ java.awt.Image bi = op.texture.getJavaImage(op.textureIndex);
ImageUtils.fixAlphaInconsistency(bi);
boolean deallocBi = false;
if (op.renderColor != null && bi instanceof java.awt.image.BufferedImage)
{
float currAlpha = op.renderColor.getAlpha() / 255.0f;
java.awt.Color textColor = new java.awt.Color((int)(op.renderColor.getRed() * currAlpha), (int)(op.renderColor.getGreen() * currAlpha),
(int)(op.renderColor.getBlue() * currAlpha), (int)(currAlpha*255));
java.awt.image.RescaleOp colorScaler = new java.awt.image.RescaleOp(
textColor.getRGBComponents(null), new float[] { 0f, 0f, 0f, 0f }, null);
bi = colorScaler.filter((java.awt.image.BufferedImage)bi, null);
deallocBi = true;
}
// g2.setTransform(op.renderXform);
// MathUtils.convertToAffineTransform(op.renderXform, tempXform);
// g2.drawImage(bi, tempXform, null);
g2.drawImage(bi, Math.round(op.destRect.x), Math.round(op.destRect.y),
Math.round(op.destRect.x + op.destRect.width), Math.round(op.destRect.y + op.destRect.height),
Math.round(op.srcRect.x), Math.round(op.srcRect.y), Math.round(op.srcRect.x + op.srcRect.width),
Math.round(op.srcRect.y + op.srcRect.height), null);
op.texture.removeJavaRef(op.textureIndex);
if (deallocBi)
{
bi.flush();
bi = null;
}
}
else if (op.isPrimitiveOp())
{
g2.setTransform((java.awt.geom.AffineTransform)matrixStack.peek());
g2.setClip(op.destRect.createIntersection(currEffectClip != null ? (java.awt.geom.Rectangle2D)currEffectClip : (java.awt.geom.Rectangle2D)clipRect));
//MathUtils.convertToAffineTransform(op.renderXform, tempXform);
//g2.transform(tempXform);
g2.translate(op.copyImageRect.x, op.copyImageRect.y);
java.awt.Paint oldPaint = g2.getPaint();
java.awt.Stroke oldStroke = g2.getStroke();
g2.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, Math.min(1.0f, op.alphaFactor * currEffectAlpha)));
if (op.primitive.gradc1 != null)
g2.setPaint(new java.awt.GradientPaint(op.primitive.fx1, op.primitive.fy1, op.primitive.gradc1,
op.primitive.fx2, op.primitive.fy2, op.primitive.gradc2));
else
g2.setColor(op.primitive.color);
// We need to disable AA or it won't use accelerated drawing (and we want to cache shapes that
// we DO want rendered w/ AA, just like text & scaled images)
float thicky = op.primitive.strokeSize;
int cornerArc = op.primitive.cornerArc;
if (!op.primitive.fill)
g2.setStroke(new java.awt.BasicStroke(thicky));
/* if (op.primitive.fill)
myXform.setToTranslation(op.destRect.x-op.srcRect.x, op.destRect.y-op.srcRect.y);
else
myXform.setToTranslation(op.destRect.x-op.srcRect.x+thicky/2, op.destRect.y-op.srcRect.y+thicky/2);
if (op.renderXform != null)
{
myXform.concatenate(op.renderXform);
}
g2.setTransform(myXform);
*/ //if (op.renderXform != null)
// g2.setClip(null);
//else
{
// tempClipRect.setFrame(op.srcRect.x, op.srcRect.y, op.destRect.width, op.destRect.height);
// g2.setClip(tempClipRect);
}
// g2.setClip(new java.awt.geom.Rectangle2D.Float(op.srcRect.x, op.srcRect.y, op.srcRect.width, op.srcRect.height));
if (op.primitive.shapeType.equals("Circle") || op.primitive.shapeType.equals("Oval"))
{
if (op.primitive.fill)
g2.fill(new java.awt.geom.Ellipse2D.Float(0, 0, op.primitive.shapeWidth, op.primitive.shapeHeight));
else
g2.draw(new java.awt.geom.Ellipse2D.Float(thicky/2, thicky/2,
op.primitive.shapeWidth - thicky, op.primitive.shapeHeight - thicky));
}
else if (op.primitive.shapeType.equals("Square") || op.primitive.shapeType.equals("Rectangle"))
{
if (op.primitive.cornerArc == 0)
{
if (op.primitive.fill)
{
if (i == 0)
{
// SPECIAL CASE where we fill the whole image buffer with this color, otherwise
// we can't get zero transparency w/out using video
g2.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC, op.alphaFactor));
}
g2.fill(new java.awt.geom.Rectangle2D.Float(0, 0,
op.primitive.shapeWidth, op.primitive.shapeHeight));
}
else
g2.draw(new java.awt.geom.Rectangle2D.Float(thicky/2, thicky/2,
op.primitive.shapeWidth - thicky, op.primitive.shapeHeight - thicky));
}
else
{
op.primitive.cornerArc = Math.min(op.primitive.cornerArc, (int)Math.floor(Math.min(
op.primitive.shapeWidth/2, op.primitive.shapeHeight/2)));
// if (hqRender)
// g2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
if (op.primitive.fill)
g2.fill(new java.awt.geom.RoundRectangle2D.Float(0, 0,
op.primitive.shapeWidth, op.primitive.shapeHeight, op.primitive.cornerArc, op.primitive.cornerArc));
else
g2.draw(new java.awt.geom.RoundRectangle2D.Float(thicky/2, thicky/2,
op.primitive.shapeWidth - thicky, op.primitive.shapeHeight - thicky, op.primitive.cornerArc, op.primitive.cornerArc));
// if (hqRender)
// g2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_OFF);
}
}
else if (op.primitive.shapeType.equals("Line"))
{
g2.draw(new java.awt.geom.Line2D.Float(0, 0, op.primitive.shapeWidth, op.primitive.shapeHeight));
}
g2.setPaint(oldPaint);
g2.setStroke(oldStroke);
}
else if (op.isTextOp())
{
g2.setTransform((java.awt.geom.AffineTransform)matrixStack.peek());
/* try
{
MathUtils.transformRectCoords(op.destRect, ((java.awt.geom.AffineTransform) matrixStack.peek()).createInverse(), tempClipRect);
}
catch (Exception e)
{
System.out.println("ERROR inverting matrix:" + e);;
}
tempClipRect.intersect(tempClipRect, clipRect, tempClipRect);*/
g2.setClip(op.destRect.createIntersection(currEffectClip != null ? (java.awt.geom.Rectangle2D)currEffectClip : (java.awt.geom.Rectangle2D)clipRect));
/*g2.setClip(Math.max(0, (int)Math.floor(op.destRect.x) - 1), Math.max(0, (int)Math.floor(op.destRect.y) - 1),
(int)Math.floor(op.destRect.width) + 2, (int)Math.floor(op.destRect.height) + 2);*/
// MathUtils.convertToAffineTransform(op.renderXform, tempXform);
// g2.transform(tempXform);
g2.translate(op.copyImageRect.x, op.copyImageRect.y);
if (op.text.fontImage != null && op.text.renderRectCache != null && op.text.renderImageNumCache.length > 0)
{
g2.setComposite(java.awt.AlphaComposite.SrcOver);
// We have to premultiply the text color since the BufferedImage is using premultiplied alpha as well
float currAlpha = Math.min(1.0f, op.alphaFactor * currEffectAlpha * op.renderColor.getAlpha() / 255.0f);
java.awt.Color textColor = new java.awt.Color((int)(op.renderColor.getRed() * currAlpha), (int)(op.renderColor.getGreen() * currAlpha),
(int)(op.renderColor.getBlue() * currAlpha), (int)(currAlpha*255));
java.awt.image.RescaleOp colorScaler = new java.awt.image.RescaleOp(
textColor.getRGBComponents(null), new float[] { 0f, 0f, 0f, 0f }, null);
for (int k = 0; k < op.text.renderImageNumCache.length; k++)
{
if (op.text.renderImageNumCache[k] == -1 || ((int)op.text.renderGlyphRectCache[k].height) <= 0 || ((int)op.text.renderGlyphRectCache[k].width) <= 0)
continue;
java.awt.image.BufferedImage img = (java.awt.image.BufferedImage)op.text.fontImage.getJavaImage(op.text.renderImageNumCache[k]);
java.awt.image.BufferedImage subImage = img.getSubimage((int)op.text.renderGlyphRectCache[k].x,
(int)op.text.renderGlyphRectCache[k].y, (int)op.text.renderGlyphRectCache[k].width, (int)op.text.renderGlyphRectCache[k].height);
java.awt.image.BufferedImage bi2 = colorScaler.filter(subImage, null);
g2.drawImage(bi2, (int)op.text.renderRectCache[2*k], (int)op.text.renderRectCache[2*k+1],
(int)op.text.renderRectCache[2*k] + (int)op.text.renderGlyphRectCache[k].width, (int)op.text.renderRectCache[2*k+1] + (int)op.text.renderGlyphRectCache[k].height, 0, 0,
(int)op.text.renderGlyphRectCache[k].width, (int)op.text.renderGlyphRectCache[k].height, null);
bi2.flush();
bi2 = null;
op.text.fontImage.removeJavaRef(op.text.renderImageNumCache[k]);
}
}
else
{
g2.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, op.alphaFactor));
g2.setColor(op.renderColor);
if (uiMgr.shouldAntialiasFont(op.text.font.getSize()))
g2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
else
g2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
// Unneeded, the cilp is set above
// g2.setClip(op.srcRect);
java.awt.geom.Rectangle2D glyphBounds = op.text.glyphVector.getLogicalBounds();
g2.drawGlyphVector(((MetaFont.JavaGlyphVector)op.text.glyphVector).getJavaGV(), (float)glyphBounds.getX(), (float)-glyphBounds.getY());
}
}
else if (op.isVideoOp()) // if its first then don't clear anything
{
g2.setTransform(baseXform);
// WE MUST clip here or we'll overwrite other parts of the buffer!!
g2.setClip(clipRect);
/*
* We're always using the color key to clear the video area. If we happen to get extra
* rendering quality because its working and we don't know that, nothing's wrong with that.
*/
//if (DBG) System.out.println("Clearing video rect for OSD: " + op.destRect);
// For some reason if this has zero transparency then it doesn't get drawn
java.awt.Color ckey = vf.getColorKey();
if (ckey == null || !vf.isColorKeyingEnabled())
ckey = new java.awt.Color(1, 1, 1, 1);
g2.setBackground(new java.awt.Color(ckey.getRed(), ckey.getGreen(),
ckey.getBlue(), 1)/*TRANSPARENT_BLACK*/);
// Calculate the actual rectangle that the video will cover
int vw, vh;
java.awt.Dimension vfVidSize = vf.getVideoSize();
vw = vfVidSize != null ? vfVidSize.width : 0;
if (vw <= 0)
vw = 720;
vh = vfVidSize != null ? vfVidSize.height : 0;
if (vh <= 0)
vh = MMC.getInstance().isNTSCVideoFormat() ? 480 : 576;
int assMode = vf.getAspectRatioMode();
float targetX = op.destRect.x;
float targetY = op.destRect.y;
float targetW = op.destRect.width;
float targetH = op.destRect.height;
float forcedRatio = vf.getCurrentAspectRatio();
if (forcedRatio != 0)
{
if (targetW/targetH < forcedRatio)
{
float shrink = targetH - targetW/forcedRatio;
targetH -= shrink;
targetY += shrink/2;
}
else
{
float shrink = targetW - targetH*forcedRatio;
targetW -= shrink;
targetX += shrink/2;
}
}
float zoomX = vf.getVideoZoomX(assMode);
float zoomY = vf.getVideoZoomY(assMode);
float transX = vf.getVideoOffsetX(assMode) * targetW / master.getWidth();
float transY = vf.getVideoOffsetY(assMode) * targetH / master.getHeight();
float widthAdjust = (zoomX - 1.0f)*targetW;
float heightAdjust = (zoomY - 1.0f)*targetH;
targetX -= widthAdjust/2;
targetY -= heightAdjust/2;
targetW += widthAdjust;
targetH += heightAdjust;
targetX += transX;
targetY += transY;
long videoHShiftFreq = vf.getVideoHShiftFreq();
if (videoHShiftFreq != 0)
{
float maxHShift = (op.destRect.width - targetW)/2;
long timeDiff = Sage.eventTime();
timeDiff %= videoHShiftFreq;
if (timeDiff < videoHShiftFreq/2)
{
if (timeDiff < videoHShiftFreq/4)
targetX -= maxHShift*timeDiff*4/videoHShiftFreq;
else
targetX -= maxHShift - (maxHShift*(timeDiff - videoHShiftFreq/4)*4/videoHShiftFreq);
}
else
{
timeDiff -= videoHShiftFreq/2;
if (timeDiff < videoHShiftFreq/4)
targetX += maxHShift*timeDiff*4/videoHShiftFreq;
else
targetX += maxHShift - (maxHShift*(timeDiff - videoHShiftFreq/4)*4/videoHShiftFreq);
}
}
java.awt.geom.Rectangle2D.Float videoSrc = new java.awt.geom.Rectangle2D.Float(0, 0, vw, vh);
java.awt.geom.Rectangle2D.Float videoDest = new java.awt.geom.Rectangle2D.Float(targetX, targetY, targetW, targetH);
Sage.clipSrcDestRects(op.destRect, videoSrc, videoDest);
java.awt.Rectangle usedVideoRect = new java.awt.Rectangle();
java.awt.Rectangle fullVideoRect = new java.awt.Rectangle();
usedVideoRect.setFrame(videoDest);
fullVideoRect.setFrame(op.destRect);
// Clear the video rect area
g2.clearRect(fullVideoRect.x, fullVideoRect.y, fullVideoRect.width, fullVideoRect.height);
g2.setBackground(vf.getVideoBGColor());
// Need to clear the left edge of the video region
if (usedVideoRect.x > fullVideoRect.x)
{
g2.clearRect(fullVideoRect.x, fullVideoRect.y, usedVideoRect.x - fullVideoRect.x,
fullVideoRect.height);
}
// Need to clear the top edge of the video region
if (usedVideoRect.y > fullVideoRect.y)
{
g2.clearRect(fullVideoRect.x, fullVideoRect.y, fullVideoRect.width,
usedVideoRect.y - fullVideoRect.y);
}
// Need to clear the right edge of the video region
if (usedVideoRect.x + usedVideoRect.width < fullVideoRect.x + fullVideoRect.width)
{
int adjust = (fullVideoRect.x + fullVideoRect.width) - (usedVideoRect.x + usedVideoRect.width);
g2.clearRect(fullVideoRect.x + fullVideoRect.width - adjust, fullVideoRect.y, adjust,
fullVideoRect.height);
}
// Need to clear the bottom edge of the video region
if (usedVideoRect.y + usedVideoRect.height < fullVideoRect.y + fullVideoRect.height)
{
int adjust = (fullVideoRect.y + fullVideoRect.height) - (usedVideoRect.y + usedVideoRect.height);
g2.clearRect(fullVideoRect.x, fullVideoRect.y + fullVideoRect.height - adjust, fullVideoRect.width,
adjust);
}
usedVideoOp = true;
if (op.destRect.width == master.getRoot().getWidth() && op.destRect.height == master.getRoot().getHeight())
{
vf.setVideoBounds(null);
refreshVideo = true;
if (!vf.isColorKeyingEnabled() && vf.isNonBlendableVideoPlayerLoaded() && Sage.WINDOWS_OS)
{
if (lastVideoRect == null || !SageRenderer.floatRectEquals(op.destRect, lastVideoRect))
uiMgr.repaintNextRegionChange = true;
java.util.ArrayList convertedRegions = getCoveredRegions(currDisplayList, op);
java.awt.Rectangle[] fixedRects = new java.awt.Rectangle[convertedRegions.size()];
int[] rectRounds = new int[convertedRegions.size()];
for (int j = 0; j < convertedRegions.size(); j++)
{
java.awt.geom.RoundRectangle2D.Float foofer = (java.awt.geom.RoundRectangle2D.Float)
convertedRegions.get(j);
fixedRects[j] = foofer.getBounds();
rectRounds[j] = Math.round(foofer.arcwidth);
}
uiMgr.setCompoundWindowRegion2(master.getHWND(),
fixedRects, rectRounds);
setVideoRegion = true;
}
}
else
{
vf.setVideoBounds(op.destRect);
refreshVideo = true;
if (!vf.isColorKeyingEnabled() && vf.isNonBlendableVideoPlayerLoaded() && Sage.WINDOWS_OS)
{
if (lastVideoRect == null || !SageRenderer.floatRectEquals(op.destRect, lastVideoRect))
uiMgr.repaintNextRegionChange = true;
java.util.ArrayList convertedRegions = getCoveredRegions(currDisplayList, op);
java.awt.Rectangle[] fixedRects = new java.awt.Rectangle[convertedRegions.size() +
op.legacyRegions.size()];
int[] rectRounds = new int[convertedRegions.size() + op.legacyRegions.size()];
for (int j = 0; j < op.legacyRegions.size(); j++)
{
java.awt.Rectangle r = (java.awt.Rectangle) op.legacyRegions.get(j);
fixedRects[j] = r;
rectRounds[j] = 0;
}
for (int j = 0; j < convertedRegions.size(); j++)
{
java.awt.geom.RoundRectangle2D.Float foofer = (java.awt.geom.RoundRectangle2D.Float)
convertedRegions.get(j);
fixedRects[j + op.legacyRegions.size()] = foofer.getBounds();
rectRounds[j + op.legacyRegions.size()] = Math.round(foofer.arcwidth);
}
uiMgr.setCompoundWindowRegion2(master.getHWND(), fixedRects, rectRounds);
setVideoRegion = true;
}
}
lastVideoRect = op.destRect;
}
else if (op.isSurfaceOp() && uiMgr.areLayersEnabled())
{
if (ANIM_DEBUG) System.out.println("Surface Op surf=" + op.surface + " on=" + op.isSurfaceOpOn() + " " + op);
if (op.isSurfaceOpOn())
{
if (currSurface != primary)
{
surfStack.push(currSurface);
g2Stack.push(g2);
}
else
primaryG2 = g2;
currSurface = (java.awt.image.BufferedImage) surfaceCache.get(op.surface);
int primWidth = (primary == null) ? master.getWidth() : primary.getWidth();
int primHeight = (primary == null) ? master.getHeight() : primary.getHeight();
if (currSurface != null)
{
// Check to make sure it's big enough
if (currSurface.getWidth() < primWidth || currSurface.getHeight() < primHeight)
{
currSurface.flush();
currSurface = null;
}
}
if (currSurface == null)
{
currSurface = new java.awt.image.BufferedImage(primWidth, primHeight,
java.awt.image.BufferedImage.TYPE_INT_ARGB);
surfaceCache.put(op.surface, currSurface);
numSurfsCreated++;
}
if (ANIM_DEBUG) System.out.println("Switched rendering surface to " + op.surface + " " + currSurface);
g2 = currSurface.createGraphics();
g2.setTransform(baseXform);
g2.setRenderingHint(java.awt.RenderingHints.KEY_INTERPOLATION, java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.setRenderingHint(java.awt.RenderingHints.KEY_ALPHA_INTERPOLATION, java.awt.RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
// Don't clear the area if this surface was already used
if (clearedSurfs.add(currSurface))
{
// g2.setClip(op.destRect.createIntersection(clipRect));
g2.setBackground(new java.awt.Color(0, 0, 0, 0));
// g2.clearRect(Math.round(op.destRect.x), Math.round(op.destRect.y), Math.round(op.destRect.width), Math.round(op.destRect.height));
g2.clearRect(clipRect.x, clipRect.y, clipRect.width, clipRect.height);
}
}
else
{
g2.dispose();
if (surfStack.isEmpty())
g2 = primaryG2;
else
g2 = (java.awt.Graphics2D) g2Stack.pop();
// Avoid double compositing operations from nested surface usage
if (!surfStack.contains(currSurface))
{
compositeOps.add(op);
java.util.ArrayList remnantAnims = (java.util.ArrayList) animsThatGoAfterSurfPop.remove(currSurface);
if (remnantAnims != null)
{
if (ANIM_DEBUG) System.out.println("Adding animation ops into composite list now from prior nested surfs:" + remnantAnims);
compositeOps.addAll(remnantAnims);
}
}
if (surfStack.isEmpty())
currSurface = primary;
else
currSurface = (java.awt.image.BufferedImage) surfStack.pop();
}
}
else if (op.isAnimationOp() && uiMgr.areLayersEnabled())
{
processAnimOp(op, i, clipRect);
if (currSurface != null && (currSurface.equals(surfaceCache.get(op.surface)) || surfStack.contains(surfaceCache.get(op.surface))))
{
if (ANIM_DEBUG) System.out.println("Putting animation op in surf pop map because we're nested in the current surface");
java.util.ArrayList vecy = (java.util.ArrayList) animsThatGoAfterSurfPop.get(currSurface);
if (vecy == null)
animsThatGoAfterSurfPop.put(currSurface, vecy = new java.util.ArrayList());
vecy.add(compositeOps.remove(compositeOps.size() - 1));
}
}
}
if (uiMgr.areLayersEnabled())
{
java.util.Collections.sort(compositeOps, COMPOSITE_LIST_SORTER);
fixSurfacePostCompositeRegions();
}
}
else
{
if (ANIM_DEBUG) System.out.println("OPTIMIZATION Skip DL render & composite only! dlSize=" + currDisplayList.size() +
" optSize=" + compositeOps.size());
}
// Go back through and composite all of the surfaces that were there (if any)
// Find all the names of the surface and sort those and then render the surfaces in order (which may not
// match the order they appeared in the display list)
dlThatWasComposited = currDisplayList;
if (ANIM_DEBUG) System.out.println("Performing the surface compositing operations now");
for (int i = 0; i <= compositeOps.size(); i++)
{
RenderingOp op;
if (i == compositeOps.size())
{
if (waitIndicatorState && waitIndicatorRops != null)
{
op = (RenderingOp) waitIndicatorRops.get((++waitIndicatorRopsIndex) % waitIndicatorRops.size());
}
else
break;
}
else
op = (RenderingOp) compositeOps.get(i);
if (op.isSurfaceOp())
{
if (ANIM_DEBUG) System.out.println("Surface Op surf=" + op.surface + " on=" + op.isSurfaceOpOn() + " " + op);
if (op.isSurfaceOpOff())
{
currSurface = (java.awt.image.BufferedImage) surfaceCache.get(op.surface);
g2.setTransform(baseXform);
g2.setClip(op.destRect.createIntersection(clipRect));
if (isBackgroundSurface(op.surface))
g2.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC));
else
g2.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, op.alphaFactor));
g2.drawImage(currSurface, Math.round(op.destRect.x), Math.round(op.destRect.y), Math.round(op.destRect.x + op.destRect.width),
Math.round(op.destRect.y + op.destRect.height), Math.round(op.destRect.x), Math.round(op.destRect.y),
Math.round(op.destRect.width + op.destRect.x), Math.round(op.destRect.height + op.destRect.y), null);
if (ANIM_DEBUG) System.out.println("Finished cached surface rendering and re-composited it with the main surface");
}
}
else if (op.isImageOp())
{
g2.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, op.alphaFactor));
// java.awt.geom.AffineTransform currXform = op.renderXform;
// myXform.setToTranslation(op.copyImageRect.x, op.copyImageRect.y);
// Workaround for JDK Bug# 4916948 to get floating point translation
// BUT it causes a big performance hit because it reallocates everything it draws so don't do it
//at.shear(0.0000001, 0.0000001);
g2.setTransform(baseXform);
g2.setClip(op.destRect.createIntersection(clipRect));
g2.drawImage(op.texture.getJavaImage(op.textureIndex), Math.round(op.destRect.x), Math.round(op.destRect.y),
Math.round(op.destRect.x + op.destRect.width), Math.round(op.destRect.y + op.destRect.height),
Math.round(op.srcRect.x), Math.round(op.srcRect.y), Math.round(op.srcRect.x + op.srcRect.width),
Math.round(op.srcRect.y + op.srcRect.height), null);
op.texture.removeJavaRef(op.textureIndex);
}
else if (op.isAnimationOp())
{
RenderingOp.Animation anime = op.anime;
if (ANIM_DEBUG) System.out.println("Animation operation found! ANIMAIL ANIMAIL!!! " + op + " scrollSrcRect=" + anime.altSrcRect +
" scrollDstRect=" + anime.altDestRect);
// Find the cached surface first
java.awt.image.BufferedImage cachedSurface = (java.awt.image.BufferedImage) surfaceCache.get(op.surface);
if (cachedSurface != null)
{
if (ANIM_DEBUG) System.out.println("Cached animation surface found: " + op.surface);
if (ANIM_DEBUG) System.out.println("Rendering Animation " + anime.animation);
g2.setTransform(baseXform);
g2.setClip(op.destRect.createIntersection(clipRect));
g2.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, op.alphaFactor));
g2.drawImage(cachedSurface, Math.round(op.destRect.x), Math.round(op.destRect.y), Math.round(op.destRect.x + op.destRect.width),
Math.round(op.destRect.y + op.destRect.height), Math.round(op.srcRect.x), Math.round(op.srcRect.y),
Math.round(op.srcRect.width + op.srcRect.x), Math.round(op.srcRect.height + op.srcRect.y), null);
if (anime.isDualSurfaceOp())
{
// We need to render the other scrolling position
cachedSurface = (java.awt.image.BufferedImage) surfaceCache.get(op.anime.altSurfName);
if (cachedSurface != null)
{
if (ANIM_DEBUG) System.out.println("Rendering second scroll surface scrollSrcRect=" + anime.altSrcRect +
" scrollDstRect=" + anime.altDestRect);
g2.setClip(op.anime.altDestRect.createIntersection(clipRect));
g2.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, op.anime.altAlphaFactor));
g2.drawImage(cachedSurface, Math.round(anime.altDestRect.x), Math.round(anime.altDestRect.y),
Math.round(anime.altDestRect.x + anime.altDestRect.width),
Math.round(anime.altDestRect.y + anime.altDestRect.height),
Math.round(anime.altSrcRect.x), Math.round(anime.altSrcRect.y),
Math.round(anime.altSrcRect.width + anime.altSrcRect.x),
Math.round(anime.altSrcRect.height + anime.altSrcRect.y), null);
}
}
}
else
{
if (ANIM_DEBUG) System.out.println("ERROR: Could not find cached animation surface:" + op.surface);
}
if (!anime.expired)
master.setActiveAnimation(op);
}
}
if (!usedVideoOp)
lastVideoRect = null;
if (!setVideoRegion && Sage.WINDOWS_OS)
uiMgr.clearWindowRegion2(master.getHWND());
g2.dispose();
if (effectAnimationsActive)
master.effectsNeedProcessing(effectAnimationsLocked);
if (ANIM_DEBUG) System.out.println("Done executing display list cacheSize=" + surfaceCache.size() + " numSurfsCreated=" + numSurfsCreated +
" dlSize=" + currDisplayList.size() + " compSize=" + compositeOps.size());
return true;
}
public void present(java.awt.Rectangle clipRect)
{
if (primary != null)
clipRect = clipRect.intersection(new java.awt.Rectangle(0, 0, primary.getWidth(), primary.getHeight()));
//if (DBG) System.out.println("Java2DSageRenderer present called clip=" + clipRect);
if ((!uiMgr.getBoolean("ui/disable_2d_double_buffering", false) || hasOSDRenderer()) &&
master.isShowing() &&
!uiMgr.getBoolean("disable_desktop_ui_rendering", false) &&
primary != null) // minimizing the window will stop the desktop rendering but keep the osd alive
{
java.awt.Graphics2D myG = (java.awt.Graphics2D) master.getGraphics();
myG.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC));
if (clipRect != null)
myG.setClip(clipRect);
myG.drawImage(primary, 0, 0, null);
myG.dispose();
master.getToolkit().sync();
/*try
{
javax.imageio.ImageIO.write(primary, "png", new java.io.File("screen" + (frameNum++) + ".png"));
}
catch (java.io.IOException e)
{
System.out.println("ERROR with Frame PNG Compression:" + e);
}*/
}
long desiredTime = ZRoot.FRAME_TIME;
// Reload the OSD if we've come out of standby
if (osdRenderer != null && uiMgr.getLastDeepSleepAwakeTime() > osdBuildTime)
{
osdRenderer.closeOSD();
osdRenderer = null;
ignoreOSD = false;
}
if (hasOSDRenderer() && !ignoreOSD)
{
if (osdRenderer == null)
{
osdRenderer = createOSDRenderer();
osdBuildTime = Sage.eventTime();
if (osdRenderer == null)
ignoreOSD = true;
else
{
if (osdRenderer instanceof OSDRenderingPlugin2)
ignoreOSD = !((OSDRenderingPlugin2) osdRenderer).openOSD2(primary.getWidth(), primary.getHeight());
else
ignoreOSD = !osdRenderer.openOSD();
}
}
if (!ignoreOSD)
{
if (MMC.getInstance().isNTSCVideoFormat())
osdVideoHeight = uiMgr.getInt("osd_rendering_height_ntsc", 480);
else
osdVideoHeight = uiMgr.getInt("osd_rendering_height_pal", 576);
//if (DBG) System.out.println("ZRoot OSD rendering from " + primary +
// " w=" + primary.getWidth() + " h=" + primary.getHeight());
// Get the subrect if its less than half of our memory size
java.awt.Rectangle currVideoRect = null;
if (lastVideoRect != null)
{
int assMode = vf.getAspectRatioMode();
float zoomX = vf.getVideoZoomX(assMode);
float zoomY = vf.getVideoZoomY(assMode);
int vw = uiMgr.getInt("osd_rendering_width", 720);
int vh = osdVideoHeight;
float targetX = lastVideoRect.x;
float targetY = lastVideoRect.y;
float targetW = lastVideoRect.width;
float targetH = lastVideoRect.height;
float forcedRatio = 0;
switch (assMode)
{
case BasicVideoFrame.ASPECT_16X9:
forcedRatio = 16.0f/9.0f;
break;
case BasicVideoFrame.ASPECT_4X3:
forcedRatio = 4.0f/3.0f;
break;
case BasicVideoFrame.ASPECT_SOURCE:
forcedRatio = ((float)vw)/vh;
break;
}
if (forcedRatio != 0)
{
if (targetW/targetH < forcedRatio)
{
float shrink = targetH - targetW/forcedRatio;
targetH -= shrink;
targetY += shrink/2;
}
else
{
float shrink = targetW - targetH*forcedRatio;
targetW -= shrink;
targetX += shrink/2;
}
}
float widthAdjust = (zoomX - 1.0f)*targetW;
float heightAdjust = (zoomY - 1.0f)*targetH;
float transX = vf.getVideoOffsetX(assMode) * targetW / vw;
float transY = vf.getVideoOffsetY(assMode) * targetH / vh;
targetX -= widthAdjust/2;
targetY -= heightAdjust/2;
targetW += widthAdjust;
targetH += heightAdjust;
targetX += transX;
targetY += transY;
currVideoRect = new java.awt.Rectangle(Math.max(0, Math.round(targetX)),
Math.max(0, Math.round(targetY)), Math.min(vw, Math.round(targetW)),
Math.min(vh, Math.round(targetH)));
}
boolean renderOSDRes;
if (osdRenderer instanceof OSDRenderingPlugin2)
{
renderOSDRes = ((OSDRenderingPlugin2)osdRenderer).updateOSD2(primary, clipRect, currVideoRect);
}
else if (clipRect.width*clipRect.height <= primary.getWidth()*primary.getHeight()/2 &&
osdRenderer.supportsRegionUpdates())
{
//if (DBG) System.out.println("Getting subimage to optimize 350 OSD blitting to " + clipRect);
if (osdMemBuf == null)
osdMemBuf = new int[primary.getWidth()*primary.getHeight()/2];
primary.getRGB(clipRect.x, clipRect.y, clipRect.width,
clipRect.height, osdMemBuf, 0, clipRect.width);
renderOSDRes = osdRenderer.updateOSD(osdMemBuf, clipRect.width, clipRect.height, clipRect,
currVideoRect);
}
else
{
renderOSDRes = osdRenderer.updateOSD(
((java.awt.image.DataBufferInt)primary.getRaster().getDataBuffer()).getData(),
primary.getWidth(), primary.getHeight(), new java.awt.Rectangle(0, 0, primary.getWidth(),
primary.getHeight()), currVideoRect);
}
//if (DBG) System.out.println("Done with 350 OSD rendering");
if (!renderOSDRes && Sage.eventTime() - last350ResetTime > 15000)
{
if (Sage.DBG) System.out.println("Performing 350 OSD reset...");
// Failure with the rendering, if we haven't reset it in the past 2 minutes, then do it again.
last350ResetTime = Sage.eventTime();
osdRenderer.closeOSD();
if (vf.hasFile())
{
vf.reloadFile();
try{Thread.sleep(1000);}catch (Exception e){}
}
osdRenderer = createOSDRenderer();
osdBuildTime = Sage.eventTime();
if (osdRenderer != null)
{
if (osdRenderer instanceof OSDRenderingPlugin2)
ignoreOSD = !((OSDRenderingPlugin2) osdRenderer).openOSD2(primary.getWidth(), primary.getHeight());
else
ignoreOSD = !osdRenderer.openOSD();
}
}
}
}
else if (osdRenderer != null)
{
osdRenderer.closeOSD();
osdRenderer = null;
ignoreOSD = false;
}
if (refreshVideo)
vf.refreshVideoSizing();
markAnimationStartTimes();
// Don't let the frame rate get out of control
long currTime = Sage.eventTime();
long frameTime = currTime - lastPresentTime;
// This fixes a bug where the UI hangs and then repeats a bunch of events
frameTime = Math.max(0, frameTime);
if (frameTime < desiredTime)
{
try{Thread.sleep(desiredTime - frameTime); }catch(Exception e){}
}
else
{
// So we don't max out the CPU with our rendering because we're highest priority thread
try{Thread.sleep(5); }catch(Exception e){}
}
lastPresentTime = currTime;
}
public void cleanupRenderer()
{
if (primary != null)
{
primary.flush();
primary = null;
}
if (osdRenderer != null)
{
osdRenderer.closeOSD();
osdRenderer = null;
}
super.cleanupRenderer();
}
private static final String ENABLE_PVR350_OSD = "enable_pvr350_osd";
public boolean hasOSDRenderer()
{
return hasOSDRenderer(uiMgr);
}
public static boolean hasOSDRenderer(UIManager uiMgr)
{
if (SageConstants.LITE) return false;
// Check for the old property setting
String oldPref = uiMgr.get("videoframe/" + ENABLE_PVR350_OSD, null);
if (oldPref != null)
{
uiMgr.put("videoframe/" + ENABLE_PVR350_OSD, null);
if (Boolean.valueOf(oldPref).booleanValue())
uiMgr.put(OSD_RENDERING_PLUGIN_CLASS, "sage.PVR350OSDRenderingPlugin");
}
return uiMgr.get(OSD_RENDERING_PLUGIN_CLASS, "").length() > 0;
}
private OSDRenderingPlugin createOSDRenderer()
{
String osdPluginClass = uiMgr.get(OSD_RENDERING_PLUGIN_CLASS, "");
if (osdPluginClass.length() > 0)
{
try
{
Class osdClass = Class.forName(osdPluginClass);
OSDRenderingPlugin rv = (OSDRenderingPlugin) osdClass.newInstance();
return rv;
}
catch (Throwable e)
{
System.out.println("ERROR creating the OSD rendering plugin:" + e);
e.printStackTrace();
}
}
return null;
}
public boolean supportsPartialUIUpdates()
{
return true;
}
public boolean hasHWImageScaling()
{
return false;
}
protected java.awt.image.BufferedImage primary;
protected java.awt.image.BufferedImage secondary;
private VideoFrame vf;
private boolean ignoreOSD;
private int[] osdMemBuf;
private java.awt.geom.Rectangle2D.Float lastVideoRect;
private long last350ResetTime;
private int osdVideoHeight;
private OSDRenderingPlugin osdRenderer;
private long osdBuildTime;
private boolean refreshVideo;
private boolean enable2DScaleCache;
private java.util.Stack surfStack = new java.util.Stack();
private java.util.Stack g2Stack = new java.util.Stack();
private java.awt.image.BufferedImage currSurface;
private java.awt.Graphics2D primaryG2;
private java.util.ArrayList dlThatWasComposited;
private int numSurfsCreated = 0;
private java.util.Map animsThatGoAfterSurfPop = new java.util.HashMap();
}
| |
/**
* 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.hadoop.hbase.wal;
import static org.apache.hadoop.hbase.wal.AbstractFSWALProvider.getWALArchiveDirectoryName;
import static org.apache.hadoop.hbase.wal.AbstractFSWALProvider.getWALDirectoryName;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.function.BiPredicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Abortable;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.regionserver.wal.DualAsyncFSWAL;
import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
import org.apache.hadoop.hbase.replication.ReplicationUtils;
import org.apache.hadoop.hbase.replication.SyncReplicationState;
import org.apache.hadoop.hbase.replication.regionserver.PeerActionListener;
import org.apache.hadoop.hbase.replication.regionserver.SyncReplicationPeerInfoProvider;
import org.apache.hadoop.hbase.util.CommonFSUtils;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.KeyLocker;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.yetus.audience.InterfaceAudience;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hbase.thirdparty.com.google.common.base.Throwables;
import org.apache.hbase.thirdparty.com.google.common.collect.Streams;
import org.apache.hbase.thirdparty.io.netty.channel.Channel;
import org.apache.hbase.thirdparty.io.netty.channel.EventLoopGroup;
/**
* The special {@link WALProvider} for synchronous replication.
* <p>
* It works like an interceptor, when getting WAL, first it will check if the given region should be
* replicated synchronously, if so it will return a special WAL for it, otherwise it will delegate
* the request to the normal {@link WALProvider}.
*/
@InterfaceAudience.Private
public class SyncReplicationWALProvider implements WALProvider, PeerActionListener {
private static final Logger LOG = LoggerFactory.getLogger(SyncReplicationWALProvider.class);
// only for injecting errors for testcase, do not use it for other purpose.
public static final String DUAL_WAL_IMPL = "hbase.wal.sync.impl";
private final WALProvider provider;
private SyncReplicationPeerInfoProvider peerInfoProvider =
new DefaultSyncReplicationPeerInfoProvider();
private WALFactory factory;
private Configuration conf;
private List<WALActionsListener> listeners = new ArrayList<>();
private EventLoopGroup eventLoopGroup;
private Class<? extends Channel> channelClass;
private AtomicBoolean initialized = new AtomicBoolean(false);
// when switching from A to DA, we will put a Optional.empty into this map if there is no WAL for
// the peer yet. When getting WAL from this map the caller should know that it should not use
// DualAsyncFSWAL any more.
private final ConcurrentMap<String, Optional<DualAsyncFSWAL>> peerId2WAL =
new ConcurrentHashMap<>();
private final KeyLocker<String> createLock = new KeyLocker<>();
SyncReplicationWALProvider(WALProvider provider) {
this.provider = provider;
}
public void setPeerInfoProvider(SyncReplicationPeerInfoProvider peerInfoProvider) {
this.peerInfoProvider = peerInfoProvider;
}
@Override
public void init(WALFactory factory, Configuration conf, String providerId, Abortable abortable)
throws IOException {
if (!initialized.compareAndSet(false, true)) {
throw new IllegalStateException("WALProvider.init should only be called once.");
}
provider.init(factory, conf, providerId, abortable);
this.conf = conf;
this.factory = factory;
Pair<EventLoopGroup, Class<? extends Channel>> eventLoopGroupAndChannelClass =
NettyAsyncFSWALConfigHelper.getEventLoopConfig(conf);
eventLoopGroup = eventLoopGroupAndChannelClass.getFirst();
channelClass = eventLoopGroupAndChannelClass.getSecond();
}
// Use a timestamp to make it identical. That means, after we transit the peer to DA/S and then
// back to A, the log prefix will be changed. This is used to simplify the implementation for
// replication source, where we do not need to consider that a terminated shipper could be added
// back.
private String getLogPrefix(String peerId) {
return factory.factoryId + "-" + EnvironmentEdgeManager.currentTime() + "-" + peerId;
}
private DualAsyncFSWAL createWAL(String peerId, String remoteWALDir) throws IOException {
Class<? extends DualAsyncFSWAL> clazz =
conf.getClass(DUAL_WAL_IMPL, DualAsyncFSWAL.class, DualAsyncFSWAL.class);
try {
Constructor<?> constructor = null;
for (Constructor<?> c : clazz.getDeclaredConstructors()) {
if (c.getParameterCount() > 0) {
constructor = c;
break;
}
}
if (constructor == null) {
throw new IllegalArgumentException("No valid constructor provided for class " + clazz);
}
constructor.setAccessible(true);
return (DualAsyncFSWAL) constructor.newInstance(
CommonFSUtils.getWALFileSystem(conf),
ReplicationUtils.getRemoteWALFileSystem(conf, remoteWALDir),
CommonFSUtils.getWALRootDir(conf),
ReplicationUtils.getPeerRemoteWALDir(remoteWALDir, peerId),
getWALDirectoryName(factory.factoryId), getWALArchiveDirectoryName(conf, factory.factoryId),
conf, listeners, true, getLogPrefix(peerId), ReplicationUtils.SYNC_WAL_SUFFIX,
eventLoopGroup, channelClass);
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
Throwable cause = e.getTargetException();
Throwables.propagateIfPossible(cause, IOException.class);
throw new RuntimeException(cause);
}
}
private DualAsyncFSWAL getWAL(String peerId, String remoteWALDir) throws IOException {
Optional<DualAsyncFSWAL> opt = peerId2WAL.get(peerId);
if (opt != null) {
return opt.orElse(null);
}
Lock lock = createLock.acquireLock(peerId);
try {
opt = peerId2WAL.get(peerId);
if (opt != null) {
return opt.orElse(null);
}
DualAsyncFSWAL wal = createWAL(peerId, remoteWALDir);
boolean succ = false;
try {
wal.init();
succ = true;
} finally {
if (!succ) {
wal.close();
}
}
peerId2WAL.put(peerId, Optional.of(wal));
return wal;
} finally {
lock.unlock();
}
}
@Override
public WAL getWAL(RegionInfo region) throws IOException {
if (region == null) {
return provider.getWAL(null);
}
WAL wal = null;
Optional<Pair<String, String>> peerIdAndRemoteWALDir =
peerInfoProvider.getPeerIdAndRemoteWALDir(region.getTable());
if (peerIdAndRemoteWALDir.isPresent()) {
Pair<String, String> pair = peerIdAndRemoteWALDir.get();
wal = getWAL(pair.getFirst(), pair.getSecond());
}
return wal != null ? wal : provider.getWAL(region);
}
private Stream<WAL> getWALStream() {
return Streams.concat(
peerId2WAL.values().stream().filter(Optional::isPresent).map(Optional::get),
provider.getWALs().stream());
}
@Override
public List<WAL> getWALs() {
return getWALStream().collect(Collectors.toList());
}
@Override
public void shutdown() throws IOException {
// save the last exception and rethrow
IOException failure = null;
for (Optional<DualAsyncFSWAL> wal : peerId2WAL.values()) {
if (wal.isPresent()) {
try {
wal.get().shutdown();
} catch (IOException e) {
LOG.error("Shutdown WAL failed", e);
failure = e;
}
}
}
provider.shutdown();
if (failure != null) {
throw failure;
}
}
@Override
public void close() throws IOException {
// save the last exception and rethrow
IOException failure = null;
for (Optional<DualAsyncFSWAL> wal : peerId2WAL.values()) {
if (wal.isPresent()) {
try {
wal.get().close();
} catch (IOException e) {
LOG.error("Close WAL failed", e);
failure = e;
}
}
}
provider.close();
if (failure != null) {
throw failure;
}
}
@Override
public long getNumLogFiles() {
return peerId2WAL.size() + provider.getNumLogFiles();
}
@Override
public long getLogFileSize() {
return peerId2WAL.values().stream().filter(Optional::isPresent).map(Optional::get)
.mapToLong(DualAsyncFSWAL::getLogFileSize).sum() + provider.getLogFileSize();
}
private void safeClose(WAL wal) {
if (wal != null) {
try {
wal.close();
} catch (IOException e) {
LOG.error("Close WAL failed", e);
}
}
}
@Override
public void addWALActionsListener(WALActionsListener listener) {
listeners.add(listener);
provider.addWALActionsListener(listener);
}
@Override
public void peerSyncReplicationStateChange(String peerId, SyncReplicationState from,
SyncReplicationState to, int stage) {
if (from == SyncReplicationState.ACTIVE) {
if (stage == 0) {
Lock lock = createLock.acquireLock(peerId);
try {
Optional<DualAsyncFSWAL> opt = peerId2WAL.get(peerId);
if (opt != null) {
opt.ifPresent(w -> w.skipRemoteWAL(to == SyncReplicationState.STANDBY));
} else {
// add a place holder to tell the getWAL caller do not use DualAsyncFSWAL any more.
peerId2WAL.put(peerId, Optional.empty());
}
} finally {
lock.unlock();
}
} else if (stage == 1) {
peerId2WAL.remove(peerId).ifPresent(this::safeClose);
}
}
}
private static class DefaultSyncReplicationPeerInfoProvider
implements SyncReplicationPeerInfoProvider {
@Override
public Optional<Pair<String, String>> getPeerIdAndRemoteWALDir(TableName table) {
return Optional.empty();
}
@Override
public boolean checkState(TableName table,
BiPredicate<SyncReplicationState, SyncReplicationState> checker) {
return false;
}
}
private static final Pattern LOG_PREFIX_PATTERN = Pattern.compile(".*-\\d+-(.+)");
/**
* <p>
* Returns the peer id if the wal file name is in the special group for a sync replication peer.
* </p>
* <p>
* The prefix format is <factoryId>-<ts>-<peerId>.
* </p>
*/
public static Optional<String> getSyncReplicationPeerIdFromWALName(String name) {
if (!name.endsWith(ReplicationUtils.SYNC_WAL_SUFFIX)) {
// fast path to return earlier if the name is not for a sync replication peer.
return Optional.empty();
}
String logPrefix = AbstractFSWALProvider.getWALPrefixFromWALName(name);
Matcher matcher = LOG_PREFIX_PATTERN.matcher(logPrefix);
if (matcher.matches()) {
return Optional.of(matcher.group(1));
} else {
return Optional.empty();
}
}
WALProvider getWrappedProvider() {
return provider;
}
}
| |
/*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.codeInspection.ui;
import com.intellij.codeInspection.CommonProblemDescriptor;
import com.intellij.codeInspection.SuppressIntentionAction;
import com.intellij.codeInspection.offlineViewer.OfflineProblemDescriptorNode;
import com.intellij.codeInspection.reference.RefEntity;
import com.intellij.concurrency.ConcurrentCollectionFactory;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiManager;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.Interner;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
public abstract class SuppressableInspectionTreeNode extends InspectionTreeNode {
@NotNull
private final InspectionToolPresentation myPresentation;
private volatile Set<SuppressIntentionAction> myAvailableSuppressActions;
private volatile String myPresentableName;
private volatile Boolean myValid;
private volatile NodeState myPreviousState;
SuppressableInspectionTreeNode(@NotNull InspectionToolPresentation presentation, @NotNull InspectionTreeNode parent) {
super(parent);
myPresentation = presentation;
}
void nodeAdded() {
dropProblemCountCaches();
ReadAction.run(() -> myValid = calculateIsValid());
//force calculation
getProblemLevels();
}
@Override
protected boolean doesNeedInternProblemLevels() {
return true;
}
@NotNull
public InspectionToolPresentation getPresentation() {
return myPresentation;
}
public boolean canSuppress() {
return getChildren().isEmpty();
}
public abstract boolean isAlreadySuppressedFromView();
public abstract boolean isQuickFixAppliedFromView();
@Override
protected boolean isProblemCountCacheValid() {
NodeState currentState = calculateState();
if (!currentState.equals(myPreviousState)) {
myPreviousState = currentState;
return false;
}
return true;
}
@NotNull
public synchronized Set<SuppressIntentionAction> getAvailableSuppressActions() {
Set<SuppressIntentionAction> actions = myAvailableSuppressActions;
if (actions == null) {
actions = calculateAvailableSuppressActions();
myAvailableSuppressActions = actions;
}
return actions;
}
public void removeSuppressActionFromAvailable(@NotNull SuppressIntentionAction action) {
myAvailableSuppressActions.remove(action);
}
@Nullable
public abstract RefEntity getElement();
@Override
public final synchronized boolean isValid() {
Boolean valid = myValid;
if (valid == null) {
valid = calculateIsValid();
myValid = valid;
}
return valid;
}
@Override
public final synchronized String getPresentableText() {
String name = myPresentableName;
if (name == null) {
name = calculatePresentableName();
myPresentableName = name;
}
return name;
}
@Override
void uiRequested() {
nodeAdded();
ReadAction.run(() -> {
if (myPresentableName == null) {
myPresentableName = calculatePresentableName();
myValid = calculateIsValid();
myAvailableSuppressActions = calculateAvailableSuppressActions();
}
});
}
@Nullable
@Override
public String getTailText() {
if (isQuickFixAppliedFromView()) {
return "";
}
if (isAlreadySuppressedFromView()) {
return "Suppressed";
}
return !isValid() ? "No longer valid" : null;
}
@NotNull
private Set<SuppressIntentionAction> calculateAvailableSuppressActions() {
return getElement() == null
? Collections.emptySet()
: calculateAvailableSuppressActions(myPresentation.getContext().getProject());
}
@NotNull
public abstract Pair<PsiElement, CommonProblemDescriptor> getSuppressContent();
@NotNull
private Set<SuppressIntentionAction> calculateAvailableSuppressActions(@NotNull Project project) {
if (myPresentation.isDummy()) return Collections.emptySet();
final Pair<PsiElement, CommonProblemDescriptor> suppressContent = getSuppressContent();
PsiElement element = suppressContent.getFirst();
if (element == null) return Collections.emptySet();
InspectionResultsView view = myPresentation.getContext().getView();
if (view == null) return Collections.emptySet();
InspectionViewSuppressActionHolder suppressActionHolder = view.getSuppressActionHolder();
final SuppressIntentionAction[] actions = suppressActionHolder.getSuppressActions(myPresentation.getToolWrapper(), element);
if (actions.length == 0) return Collections.emptySet();
return suppressActionHolder.internSuppressActions(Arrays.stream(actions)
.filter(action -> action.isAvailable(project, null, element))
.collect(Collectors.toCollection(() -> ConcurrentCollectionFactory.createConcurrentSet(ContainerUtil.identityStrategy()))));
}
protected abstract String calculatePresentableName();
protected abstract boolean calculateIsValid();
protected void dropCache() {
ReadAction.run(() -> doDropCache());
}
private void doDropCache() {
myProblemLevels.drop();
if (isQuickFixAppliedFromView() || isAlreadySuppressedFromView()) return;
// calculate all data on background thread
myValid = calculateIsValid();
myPresentableName = calculatePresentableName();
for (InspectionTreeNode child : getChildren()) {
if (child instanceof SuppressableInspectionTreeNode) {
((SuppressableInspectionTreeNode)child).doDropCache();
}
}
}
private static class NodeState {
private static final Interner<NodeState> INTERNER = new Interner<>();
private final boolean isValid;
private final boolean isSuppressed;
private final boolean isFixApplied;
private final boolean isExcluded;
private NodeState(boolean isValid, boolean isSuppressed, boolean isFixApplied, boolean isExcluded) {
this.isValid = isValid;
this.isSuppressed = isSuppressed;
this.isFixApplied = isFixApplied;
this.isExcluded = isExcluded;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof NodeState)) return false;
NodeState state = (NodeState)o;
if (isValid != state.isValid) return false;
if (isSuppressed != state.isSuppressed) return false;
if (isFixApplied != state.isFixApplied) return false;
if (isExcluded != state.isExcluded) return false;
return true;
}
@Override
public int hashCode() {
int result = (isValid ? 1 : 0);
result = 31 * result + (isSuppressed ? 1 : 0);
result = 31 * result + (isFixApplied ? 1 : 0);
result = 31 * result + (isExcluded ? 1 : 0);
return result;
}
}
private NodeState calculateState() {
NodeState state = new NodeState(isValid(), isAlreadySuppressedFromView(), isQuickFixAppliedFromView(), isExcluded());
synchronized (NodeState.INTERNER) {
return NodeState.INTERNER.intern(state);
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.mapper.nested;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.MapperService.MergeReason;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.internal.TypeFieldMapper;
import org.elasticsearch.index.mapper.object.ObjectMapper;
import org.elasticsearch.index.mapper.object.ObjectMapper.Dynamic;
import org.elasticsearch.test.ESSingleNodeTestCase;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.function.Function;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
public class NestedMappingTests extends ESSingleNodeTestCase {
public void testEmptyNested() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties")
.startObject("nested1").field("type", "nested").endObject()
.endObject().endObject().endObject().string();
DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));
ParsedDocument doc = docMapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "value")
.nullField("nested1")
.endObject()
.bytes());
assertThat(doc.docs().size(), equalTo(1));
doc = docMapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "value")
.startArray("nested").endArray()
.endObject()
.bytes());
assertThat(doc.docs().size(), equalTo(1));
}
public void testSingleNested() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties")
.startObject("nested1").field("type", "nested").endObject()
.endObject().endObject().endObject().string();
DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));
assertThat(docMapper.hasNestedObjects(), equalTo(true));
ObjectMapper nested1Mapper = docMapper.objectMappers().get("nested1");
assertThat(nested1Mapper.nested().isNested(), equalTo(true));
ParsedDocument doc = docMapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "value")
.startObject("nested1").field("field1", "1").field("field2", "2").endObject()
.endObject()
.bytes());
assertThat(doc.docs().size(), equalTo(2));
assertThat(doc.docs().get(0).get(TypeFieldMapper.NAME), equalTo(nested1Mapper.nestedTypePathAsString()));
assertThat(doc.docs().get(0).get("nested1.field1"), equalTo("1"));
assertThat(doc.docs().get(0).get("nested1.field2"), equalTo("2"));
assertThat(doc.docs().get(1).get("field"), equalTo("value"));
doc = docMapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "value")
.startArray("nested1")
.startObject().field("field1", "1").field("field2", "2").endObject()
.startObject().field("field1", "3").field("field2", "4").endObject()
.endArray()
.endObject()
.bytes());
assertThat(doc.docs().size(), equalTo(3));
assertThat(doc.docs().get(0).get(TypeFieldMapper.NAME), equalTo(nested1Mapper.nestedTypePathAsString()));
assertThat(doc.docs().get(0).get("nested1.field1"), equalTo("3"));
assertThat(doc.docs().get(0).get("nested1.field2"), equalTo("4"));
assertThat(doc.docs().get(1).get(TypeFieldMapper.NAME), equalTo(nested1Mapper.nestedTypePathAsString()));
assertThat(doc.docs().get(1).get("nested1.field1"), equalTo("1"));
assertThat(doc.docs().get(1).get("nested1.field2"), equalTo("2"));
assertThat(doc.docs().get(2).get("field"), equalTo("value"));
}
public void testMultiNested() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties")
.startObject("nested1").field("type", "nested").startObject("properties")
.startObject("nested2").field("type", "nested")
.endObject().endObject()
.endObject().endObject().endObject().string();
DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));
assertThat(docMapper.hasNestedObjects(), equalTo(true));
ObjectMapper nested1Mapper = docMapper.objectMappers().get("nested1");
assertThat(nested1Mapper.nested().isNested(), equalTo(true));
assertThat(nested1Mapper.nested().isIncludeInParent(), equalTo(false));
assertThat(nested1Mapper.nested().isIncludeInRoot(), equalTo(false));
ObjectMapper nested2Mapper = docMapper.objectMappers().get("nested1.nested2");
assertThat(nested2Mapper.nested().isNested(), equalTo(true));
assertThat(nested2Mapper.nested().isIncludeInParent(), equalTo(false));
assertThat(nested2Mapper.nested().isIncludeInRoot(), equalTo(false));
ParsedDocument doc = docMapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "value")
.startArray("nested1")
.startObject().field("field1", "1").startArray("nested2").startObject().field("field2", "2").endObject().startObject().field("field2", "3").endObject().endArray().endObject()
.startObject().field("field1", "4").startArray("nested2").startObject().field("field2", "5").endObject().startObject().field("field2", "6").endObject().endArray().endObject()
.endArray()
.endObject()
.bytes());
assertThat(doc.docs().size(), equalTo(7));
assertThat(doc.docs().get(0).get("nested1.nested2.field2"), equalTo("6"));
assertThat(doc.docs().get(0).get("nested1.field1"), nullValue());
assertThat(doc.docs().get(0).get("field"), nullValue());
assertThat(doc.docs().get(1).get("nested1.nested2.field2"), equalTo("5"));
assertThat(doc.docs().get(1).get("nested1.field1"), nullValue());
assertThat(doc.docs().get(1).get("field"), nullValue());
assertThat(doc.docs().get(2).get("nested1.field1"), equalTo("4"));
assertThat(doc.docs().get(2).get("nested1.nested2.field2"), nullValue());
assertThat(doc.docs().get(2).get("field"), nullValue());
assertThat(doc.docs().get(3).get("nested1.nested2.field2"), equalTo("3"));
assertThat(doc.docs().get(3).get("field"), nullValue());
assertThat(doc.docs().get(4).get("nested1.nested2.field2"), equalTo("2"));
assertThat(doc.docs().get(4).get("field"), nullValue());
assertThat(doc.docs().get(5).get("nested1.field1"), equalTo("1"));
assertThat(doc.docs().get(5).get("nested1.nested2.field2"), nullValue());
assertThat(doc.docs().get(5).get("field"), nullValue());
assertThat(doc.docs().get(6).get("field"), equalTo("value"));
assertThat(doc.docs().get(6).get("nested1.field1"), nullValue());
assertThat(doc.docs().get(6).get("nested1.nested2.field2"), nullValue());
}
public void testMultiObjectAndNested1() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties")
.startObject("nested1").field("type", "nested").startObject("properties")
.startObject("nested2").field("type", "nested").field("include_in_parent", true)
.endObject().endObject()
.endObject().endObject().endObject().string();
DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));
assertThat(docMapper.hasNestedObjects(), equalTo(true));
ObjectMapper nested1Mapper = docMapper.objectMappers().get("nested1");
assertThat(nested1Mapper.nested().isNested(), equalTo(true));
assertThat(nested1Mapper.nested().isIncludeInParent(), equalTo(false));
assertThat(nested1Mapper.nested().isIncludeInRoot(), equalTo(false));
ObjectMapper nested2Mapper = docMapper.objectMappers().get("nested1.nested2");
assertThat(nested2Mapper.nested().isNested(), equalTo(true));
assertThat(nested2Mapper.nested().isIncludeInParent(), equalTo(true));
assertThat(nested2Mapper.nested().isIncludeInRoot(), equalTo(false));
ParsedDocument doc = docMapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "value")
.startArray("nested1")
.startObject().field("field1", "1").startArray("nested2").startObject().field("field2", "2").endObject().startObject().field("field2", "3").endObject().endArray().endObject()
.startObject().field("field1", "4").startArray("nested2").startObject().field("field2", "5").endObject().startObject().field("field2", "6").endObject().endArray().endObject()
.endArray()
.endObject()
.bytes());
assertThat(doc.docs().size(), equalTo(7));
assertThat(doc.docs().get(0).get("nested1.nested2.field2"), equalTo("6"));
assertThat(doc.docs().get(0).get("nested1.field1"), nullValue());
assertThat(doc.docs().get(0).get("field"), nullValue());
assertThat(doc.docs().get(1).get("nested1.nested2.field2"), equalTo("5"));
assertThat(doc.docs().get(1).get("nested1.field1"), nullValue());
assertThat(doc.docs().get(1).get("field"), nullValue());
assertThat(doc.docs().get(2).get("nested1.field1"), equalTo("4"));
assertThat(doc.docs().get(2).get("nested1.nested2.field2"), equalTo("5"));
assertThat(doc.docs().get(2).get("field"), nullValue());
assertThat(doc.docs().get(3).get("nested1.nested2.field2"), equalTo("3"));
assertThat(doc.docs().get(3).get("field"), nullValue());
assertThat(doc.docs().get(4).get("nested1.nested2.field2"), equalTo("2"));
assertThat(doc.docs().get(4).get("field"), nullValue());
assertThat(doc.docs().get(5).get("nested1.field1"), equalTo("1"));
assertThat(doc.docs().get(5).get("nested1.nested2.field2"), equalTo("2"));
assertThat(doc.docs().get(5).get("field"), nullValue());
assertThat(doc.docs().get(6).get("field"), equalTo("value"));
assertThat(doc.docs().get(6).get("nested1.field1"), nullValue());
assertThat(doc.docs().get(6).get("nested1.nested2.field2"), nullValue());
}
public void testMultiObjectAndNested2() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties")
.startObject("nested1").field("type", "nested").field("include_in_parent", true).startObject("properties")
.startObject("nested2").field("type", "nested").field("include_in_parent", true)
.endObject().endObject()
.endObject().endObject().endObject().string();
DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));
assertThat(docMapper.hasNestedObjects(), equalTo(true));
ObjectMapper nested1Mapper = docMapper.objectMappers().get("nested1");
assertThat(nested1Mapper.nested().isNested(), equalTo(true));
assertThat(nested1Mapper.nested().isIncludeInParent(), equalTo(true));
assertThat(nested1Mapper.nested().isIncludeInRoot(), equalTo(false));
ObjectMapper nested2Mapper = docMapper.objectMappers().get("nested1.nested2");
assertThat(nested2Mapper.nested().isNested(), equalTo(true));
assertThat(nested2Mapper.nested().isIncludeInParent(), equalTo(true));
assertThat(nested2Mapper.nested().isIncludeInRoot(), equalTo(false));
ParsedDocument doc = docMapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "value")
.startArray("nested1")
.startObject().field("field1", "1").startArray("nested2").startObject().field("field2", "2").endObject().startObject().field("field2", "3").endObject().endArray().endObject()
.startObject().field("field1", "4").startArray("nested2").startObject().field("field2", "5").endObject().startObject().field("field2", "6").endObject().endArray().endObject()
.endArray()
.endObject()
.bytes());
assertThat(doc.docs().size(), equalTo(7));
assertThat(doc.docs().get(0).get("nested1.nested2.field2"), equalTo("6"));
assertThat(doc.docs().get(0).get("nested1.field1"), nullValue());
assertThat(doc.docs().get(0).get("field"), nullValue());
assertThat(doc.docs().get(1).get("nested1.nested2.field2"), equalTo("5"));
assertThat(doc.docs().get(1).get("nested1.field1"), nullValue());
assertThat(doc.docs().get(1).get("field"), nullValue());
assertThat(doc.docs().get(2).get("nested1.field1"), equalTo("4"));
assertThat(doc.docs().get(2).get("nested1.nested2.field2"), equalTo("5"));
assertThat(doc.docs().get(2).get("field"), nullValue());
assertThat(doc.docs().get(3).get("nested1.nested2.field2"), equalTo("3"));
assertThat(doc.docs().get(3).get("field"), nullValue());
assertThat(doc.docs().get(4).get("nested1.nested2.field2"), equalTo("2"));
assertThat(doc.docs().get(4).get("field"), nullValue());
assertThat(doc.docs().get(5).get("nested1.field1"), equalTo("1"));
assertThat(doc.docs().get(5).get("nested1.nested2.field2"), equalTo("2"));
assertThat(doc.docs().get(5).get("field"), nullValue());
assertThat(doc.docs().get(6).get("field"), equalTo("value"));
assertThat(doc.docs().get(6).getFields("nested1.field1").length, equalTo(2));
assertThat(doc.docs().get(6).getFields("nested1.nested2.field2").length, equalTo(4));
}
public void testMultiRootAndNested1() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties")
.startObject("nested1").field("type", "nested").startObject("properties")
.startObject("nested2").field("type", "nested").field("include_in_root", true)
.endObject().endObject()
.endObject().endObject().endObject().string();
DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));
assertThat(docMapper.hasNestedObjects(), equalTo(true));
ObjectMapper nested1Mapper = docMapper.objectMappers().get("nested1");
assertThat(nested1Mapper.nested().isNested(), equalTo(true));
assertThat(nested1Mapper.nested().isIncludeInParent(), equalTo(false));
assertThat(nested1Mapper.nested().isIncludeInRoot(), equalTo(false));
ObjectMapper nested2Mapper = docMapper.objectMappers().get("nested1.nested2");
assertThat(nested2Mapper.nested().isNested(), equalTo(true));
assertThat(nested2Mapper.nested().isIncludeInParent(), equalTo(false));
assertThat(nested2Mapper.nested().isIncludeInRoot(), equalTo(true));
ParsedDocument doc = docMapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "value")
.startArray("nested1")
.startObject().field("field1", "1").startArray("nested2").startObject().field("field2", "2").endObject().startObject().field("field2", "3").endObject().endArray().endObject()
.startObject().field("field1", "4").startArray("nested2").startObject().field("field2", "5").endObject().startObject().field("field2", "6").endObject().endArray().endObject()
.endArray()
.endObject()
.bytes());
assertThat(doc.docs().size(), equalTo(7));
assertThat(doc.docs().get(0).get("nested1.nested2.field2"), equalTo("6"));
assertThat(doc.docs().get(0).get("nested1.field1"), nullValue());
assertThat(doc.docs().get(0).get("field"), nullValue());
assertThat(doc.docs().get(1).get("nested1.nested2.field2"), equalTo("5"));
assertThat(doc.docs().get(1).get("nested1.field1"), nullValue());
assertThat(doc.docs().get(1).get("field"), nullValue());
assertThat(doc.docs().get(2).get("nested1.field1"), equalTo("4"));
assertThat(doc.docs().get(2).get("nested1.nested2.field2"), nullValue());
assertThat(doc.docs().get(2).get("field"), nullValue());
assertThat(doc.docs().get(3).get("nested1.nested2.field2"), equalTo("3"));
assertThat(doc.docs().get(3).get("field"), nullValue());
assertThat(doc.docs().get(4).get("nested1.nested2.field2"), equalTo("2"));
assertThat(doc.docs().get(4).get("field"), nullValue());
assertThat(doc.docs().get(5).get("nested1.field1"), equalTo("1"));
assertThat(doc.docs().get(5).get("nested1.nested2.field2"), nullValue());
assertThat(doc.docs().get(5).get("field"), nullValue());
assertThat(doc.docs().get(6).get("field"), equalTo("value"));
assertThat(doc.docs().get(6).get("nested1.field1"), nullValue());
assertThat(doc.docs().get(6).getFields("nested1.nested2.field2").length, equalTo(4));
}
public void testNestedArrayStrict() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties")
.startObject("nested1").field("type", "nested").field("dynamic", "strict").startObject("properties")
.startObject("field1").field("type", "text")
.endObject().endObject()
.endObject().endObject().endObject().string();
DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));
assertThat(docMapper.hasNestedObjects(), equalTo(true));
ObjectMapper nested1Mapper = docMapper.objectMappers().get("nested1");
assertThat(nested1Mapper.nested().isNested(), equalTo(true));
assertThat(nested1Mapper.dynamic(), equalTo(Dynamic.STRICT));
ParsedDocument doc = docMapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "value")
.startArray("nested1")
.startObject().field("field1", "1").endObject()
.startObject().field("field1", "4").endObject()
.endArray()
.endObject()
.bytes());
assertThat(doc.docs().size(), equalTo(3));
assertThat(doc.docs().get(0).get("nested1.field1"), equalTo("4"));
assertThat(doc.docs().get(0).get("field"), nullValue());
assertThat(doc.docs().get(1).get("nested1.field1"), equalTo("1"));
assertThat(doc.docs().get(1).get("field"), nullValue());
assertThat(doc.docs().get(2).get("field"), equalTo("value"));
}
public void testLimitOfNestedFieldsPerIndex() throws Exception {
Function<String, String> mapping = type -> {
try {
return XContentFactory.jsonBuilder().startObject().startObject(type).startObject("properties")
.startObject("nested1").field("type", "nested").startObject("properties")
.startObject("nested2").field("type", "nested")
.endObject().endObject()
.endObject().endObject().endObject().string();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
// default limit allows at least two nested fields
createIndex("test1").mapperService().merge("type", new CompressedXContent(mapping.apply("type")), MergeReason.MAPPING_UPDATE, false);
// explicitly setting limit to 0 prevents nested fields
try {
createIndex("test2", Settings.builder().put(MapperService.INDEX_MAPPING_NESTED_FIELDS_LIMIT_SETTING.getKey(), 0).build())
.mapperService().merge("type", new CompressedXContent(mapping.apply("type")), MergeReason.MAPPING_UPDATE, false);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("Limit of nested fields [0] in index [test2] has been exceeded"));
}
// setting limit to 1 with 2 nested fields fails
try {
createIndex("test3", Settings.builder().put(MapperService.INDEX_MAPPING_NESTED_FIELDS_LIMIT_SETTING.getKey(), 1).build())
.mapperService().merge("type", new CompressedXContent(mapping.apply("type")), MergeReason.MAPPING_UPDATE, false);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("Limit of nested fields [1] in index [test3] has been exceeded"));
}
MapperService mapperService = createIndex("test4", Settings.builder().put(MapperService.INDEX_MAPPING_NESTED_FIELDS_LIMIT_SETTING.getKey(), 2)
.build()).mapperService();
mapperService.merge("type1", new CompressedXContent(mapping.apply("type1")), MergeReason.MAPPING_UPDATE, false);
// merging same fields, but different type is ok
mapperService.merge("type2", new CompressedXContent(mapping.apply("type2")), MergeReason.MAPPING_UPDATE, false);
// adding new fields from different type is not ok
String mapping2 = XContentFactory.jsonBuilder().startObject().startObject("type3").startObject("properties").startObject("nested3")
.field("type", "nested").startObject("properties").endObject().endObject().endObject().endObject().string();
try {
mapperService.merge("type3", new CompressedXContent(mapping2), MergeReason.MAPPING_UPDATE, false);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("Limit of nested fields [2] in index [test4] has been exceeded"));
}
// do not check nested fields limit if mapping is not updated
createIndex("test5", Settings.builder().put(MapperService.INDEX_MAPPING_NESTED_FIELDS_LIMIT_SETTING.getKey(), 0).build())
.mapperService().merge("type", new CompressedXContent(mapping.apply("type")), MergeReason.MAPPING_RECOVERY, false);
}
}
| |
/* 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.activiti.engine.impl.persistence.entity;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder;
import org.activiti.engine.impl.Page;
import org.activiti.engine.impl.TaskQueryImpl;
import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.AbstractManager;
import org.activiti.engine.task.Task;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.engine.delegate.event.FlowableEngineEventType;
/**
* @author Tom Baeyens
*/
public class TaskEntityManager extends AbstractManager {
@SuppressWarnings({ "unchecked", "rawtypes" })
public void deleteTasksByProcessInstanceId(String processInstanceId, String deleteReason, boolean cascade) {
List<TaskEntity> tasks = (List) getDbSqlSession()
.createTaskQuery()
.processInstanceId(processInstanceId)
.list();
String reason = (deleteReason == null || deleteReason.length() == 0) ? TaskEntity.DELETE_REASON_DELETED : deleteReason;
CommandContext commandContext = Context.getCommandContext();
for (TaskEntity task: tasks) {
if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createActivityCancelledEvent(
task.getExecution().getActivityId(),
task.getName(),
task.getExecutionId(),
task.getProcessInstanceId(),
task.getProcessDefinitionId(),
"userTask", UserTaskActivityBehavior.class.getName(), deleteReason));
}
deleteTask(task, reason, cascade);
}
}
public void deleteTask(TaskEntity task, String deleteReason, boolean cascade) {
if (!task.isDeleted()) {
task.fireEvent(TaskListener.EVENTNAME_DELETE);
task.setDeleted(true);
CommandContext commandContext = Context.getCommandContext();
String taskId = task.getId();
List<Task> subTasks = findTasksByParentTaskId(taskId);
for (Task subTask: subTasks) {
deleteTask((TaskEntity) subTask, deleteReason, cascade);
}
commandContext
.getIdentityLinkEntityManager()
.deleteIdentityLinksByTaskId(taskId);
commandContext
.getVariableInstanceEntityManager()
.deleteVariableInstanceByTask(task);
if (cascade) {
commandContext
.getHistoricTaskInstanceEntityManager()
.deleteHistoricTaskInstanceById(taskId);
} else {
commandContext
.getHistoryManager()
.recordTaskEnd(taskId, deleteReason);
}
getDbSqlSession().delete(task);
if(commandContext.getEventDispatcher().isEnabled()) {
commandContext.getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, task));
}
}
}
public TaskEntity findTaskById(String id) {
if (id == null) {
throw new ActivitiIllegalArgumentException("Invalid task id : null");
}
return (TaskEntity) getDbSqlSession().selectById(TaskEntity.class, id);
}
@SuppressWarnings("unchecked")
public List<TaskEntity> findTasksByExecutionId(String executionId) {
return getDbSqlSession().selectList("selectTasksByExecutionId", executionId);
}
@SuppressWarnings("unchecked")
public List<TaskEntity> findTasksByProcessInstanceId(String processInstanceId) {
return getDbSqlSession().selectList("selectTasksByProcessInstanceId", processInstanceId);
}
@Deprecated
public List<Task> findTasksByQueryCriteria(TaskQueryImpl taskQuery, Page page) {
taskQuery.setFirstResult(page.getFirstResult());
taskQuery.setMaxResults(page.getMaxResults());
return findTasksByQueryCriteria(taskQuery);
}
@SuppressWarnings("unchecked")
public List<Task> findTasksByQueryCriteria(TaskQueryImpl taskQuery) {
final String query = "selectTaskByQueryCriteria";
return getDbSqlSession().selectList(query, taskQuery);
}
@SuppressWarnings("unchecked")
public List<Task> findTasksAndVariablesByQueryCriteria(TaskQueryImpl taskQuery) {
final String query = "selectTaskWithVariablesByQueryCriteria";
// paging doesn't work for combining task instances and variables due to an outer join, so doing it in-memory
if (taskQuery.getFirstResult() < 0 || taskQuery.getMaxResults() <= 0) {
return Collections.EMPTY_LIST;
}
int firstResult = taskQuery.getFirstResult();
int maxResults = taskQuery.getMaxResults();
// setting max results, limit to 20000 results for performance reasons
if (taskQuery.getTaskVariablesLimit() != null) {
taskQuery.setMaxResults(taskQuery.getTaskVariablesLimit());
} else {
taskQuery.setMaxResults(Context.getProcessEngineConfiguration().getTaskQueryLimit());
}
taskQuery.setFirstResult(0);
List<Task> instanceList = getDbSqlSession().selectListWithRawParameterWithoutFilter(query, taskQuery, taskQuery.getFirstResult(), taskQuery.getMaxResults());
if (instanceList != null && !instanceList.isEmpty()) {
if (firstResult > 0) {
if (firstResult <= instanceList.size()) {
int toIndex = firstResult + Math.min(maxResults, instanceList.size() - firstResult);
return instanceList.subList(firstResult, toIndex);
} else {
return Collections.EMPTY_LIST;
}
} else {
int toIndex = Math.min(maxResults, instanceList.size());
return instanceList.subList(0, toIndex);
}
}
return Collections.EMPTY_LIST;
}
public long findTaskCountByQueryCriteria(TaskQueryImpl taskQuery) {
return (Long) getDbSqlSession().selectOne("selectTaskCountByQueryCriteria", taskQuery);
}
@SuppressWarnings("unchecked")
public List<Task> findTasksByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return getDbSqlSession().selectListWithRawParameter("selectTaskByNativeQuery", parameterMap, firstResult, maxResults);
}
public long findTaskCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectTaskCountByNativeQuery", parameterMap);
}
@SuppressWarnings("unchecked")
public List<Task> findTasksByParentTaskId(String parentTaskId) {
return getDbSqlSession().selectList("selectTasksByParentTaskId", parentTaskId);
}
public void deleteTask(String taskId, String deleteReason, boolean cascade) {
TaskEntity task = Context
.getCommandContext()
.getTaskEntityManager()
.findTaskById(taskId);
if (task!=null) {
if(task.getExecutionId() != null) {
throw new ActivitiException("The task cannot be deleted because is part of a running process");
}
String reason = (deleteReason == null || deleteReason.length() == 0) ? TaskEntity.DELETE_REASON_DELETED : deleteReason;
deleteTask(task, reason, cascade);
} else if (cascade) {
Context
.getCommandContext()
.getHistoricTaskInstanceEntityManager()
.deleteHistoricTaskInstanceById(taskId);
}
}
public void updateTaskTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateTaskTenantIdForDeployment", params);
}
}
| |
/*
* Copyright (c) 2014 Wael Chatila / Icegreen Technologies. All Rights Reserved.
* This software is released under the Apache license 2.0
* This file has been modified by the copyright holder.
* Original file can be found at http://james.apache.org
*/
package com.icegreen.greenmail.imap;
import com.icegreen.greenmail.store.*;
import com.icegreen.greenmail.user.GreenMailUser;
import java.util.*;
/**
* An initial implementation of an ImapHost. By default, uses,
* the {@link com.icegreen.greenmail.store.InMemoryStore} implementation of {@link com.icegreen.greenmail.store.Store}.
* TODO: Make the underlying store configurable with Phoenix.
*
* @author Darrell DeBoer <darrell@apache.org>
* @version $Revision: 109034 $
*/
public class ImapHostManagerImpl
implements ImapHostManager, ImapConstants {
private Store store;
private MailboxSubscriptions subscriptions;
/**
* Hack constructor which creates an in-memory store, and creates a console logger.
*/
public ImapHostManagerImpl() {
this(new InMemoryStore());
}
public ImapHostManagerImpl(Store store) {
this.store = store;
subscriptions = new MailboxSubscriptions();
}
@Override
public List<StoredMessage> getAllMessages() {
List<StoredMessage> ret = new ArrayList<StoredMessage>();
try {
Collection boxes = store.listMailboxes("*");
for (Object boxe : boxes) {
MailFolder folder = (MailFolder) boxe;
ret.addAll(folder.getMessages());
}
} catch (FolderException e) {
throw new IllegalStateException(e);
}
return ret;
}
@Override
public char getHierarchyDelimiter() {
return HIERARCHY_DELIMITER_CHAR;
}
/**
* @see ImapHostManager#getFolder
*/
@Override
public MailFolder getFolder(GreenMailUser user, String mailboxName) {
String name = getQualifiedMailboxName(user, mailboxName);
MailFolder folder = store.getMailbox(name);
return checkViewable(folder);
}
@Override
public MailFolder getFolder(GreenMailUser user, String mailboxName, boolean mustExist)
throws FolderException {
MailFolder folder = getFolder(user, mailboxName);
if (mustExist && (folder == null)) {
throw new FolderException("No such folder : "+mailboxName);
}
return folder;
}
private MailFolder checkViewable(MailFolder folder) {
// TODO implement this.
return folder;
}
/**
* @see ImapHostManager#getInbox
*/
@Override
public MailFolder getInbox(GreenMailUser user) throws FolderException {
return getFolder(user, INBOX_NAME);
}
/**
* @see ImapHostManager#createPrivateMailAccount
*/
@Override
public void createPrivateMailAccount(GreenMailUser user) throws FolderException {
MailFolder root = store.getMailbox(USER_NAMESPACE);
MailFolder userRoot = store.createMailbox(root, user.getQualifiedMailboxName(), false);
store.createMailbox(userRoot, INBOX_NAME, true);
}
/**
* @see ImapHostManager#createMailbox
*/
@Override
public MailFolder createMailbox(GreenMailUser user, String mailboxName)
throws AuthorizationException, FolderException {
String qualifiedName = getQualifiedMailboxName(user, mailboxName);
if (store.getMailbox(qualifiedName) != null) {
throw new FolderException("Mailbox already exists.");
}
StringTokenizer tokens = new StringTokenizer(qualifiedName,
HIERARCHY_DELIMITER);
if (tokens.countTokens() < 2) {
throw new FolderException("Cannot create store at namespace level.");
}
String namespaceRoot = tokens.nextToken();
MailFolder folder = store.getMailbox(namespaceRoot);
if (folder == null) {
throw new FolderException("Invalid namespace.");
}
while (tokens.hasMoreTokens()) {
// Get the next name from the list, and find the child
String childName = tokens.nextToken();
MailFolder child = store.getMailbox(folder, childName);
// Create if neccessary
if (child == null) {
// TODO check permissions.
boolean makeSelectable = !tokens.hasMoreTokens();
child = store.createMailbox(folder, childName, makeSelectable);
}
folder = child;
}
return folder;
}
/**
* @see ImapHostManager#deleteMailbox
*/
@Override
public void deleteMailbox(GreenMailUser user, String mailboxName)
throws FolderException, AuthorizationException {
MailFolder toDelete = getFolder(user, mailboxName, true);
if (store.getChildren(toDelete).isEmpty()) {
toDelete.deleteAllMessages();
toDelete.signalDeletion();
store.deleteMailbox(toDelete);
} else {
if (toDelete.isSelectable()) {
toDelete.deleteAllMessages();
store.setSelectable(toDelete, false);
} else {
throw new FolderException("Can't delete a non-selectable store with children.");
}
}
}
/**
* @see ImapHostManager#renameMailbox
*/
@Override
public void renameMailbox(GreenMailUser user,
String oldMailboxName,
String newMailboxName)
throws FolderException, AuthorizationException {
MailFolder existingFolder = getFolder(user, oldMailboxName, true);
// TODO: check permissions.
// Handle case where existing is INBOX
// - just create new folder, move all messages,
// and leave INBOX (with children) intact.
String userInboxName = getQualifiedMailboxName(user, INBOX_NAME);
if (userInboxName.equals(existingFolder.getFullName())) {
MailFolder newBox = createMailbox(user, newMailboxName);
long[] uids = existingFolder.getMessageUids();
for (long uid : uids) {
existingFolder.copyMessage(uid, newBox);
}
existingFolder.deleteAllMessages();
return;
}
store.renameMailbox(existingFolder, newMailboxName);
}
/**
* @see ImapHostManager#listSubscribedMailboxes
*/
@Override
public Collection<MailFolder> listSubscribedMailboxes(GreenMailUser user,
String mailboxPattern)
throws FolderException {
return listMailboxes(user, mailboxPattern, true);
}
/**
* @see ImapHostManager#listMailboxes
*/
@Override
public Collection<MailFolder> listMailboxes(GreenMailUser user,
String mailboxPattern)
throws FolderException {
return listMailboxes(user, mailboxPattern, false);
}
/**
* Partial implementation of list functionality.
* TODO: Handle wildcards anywhere in store pattern
* (currently only supported as last character of pattern)
*
* @see com.icegreen.greenmail.imap.ImapHostManager#listMailboxes
*/
private Collection<MailFolder> listMailboxes(GreenMailUser user,
String mailboxPattern,
boolean subscribedOnly)
throws FolderException {
List<MailFolder> mailboxes = new ArrayList<MailFolder>();
String qualifiedPattern = getQualifiedMailboxName(user, mailboxPattern);
for (MailFolder folder : store.listMailboxes(qualifiedPattern)) {
// TODO check subscriptions.
if (subscribedOnly && !subscriptions.isSubscribed(user, folder)) {
// if not subscribed
folder = null;
}
// Sets the store to null if it's not viewable.
folder = checkViewable(folder);
if (folder != null) {
mailboxes.add(folder);
}
}
return mailboxes;
}
/**
* @see ImapHostManager#subscribe
*/
@Override
public void subscribe(GreenMailUser user, String mailboxName)
throws FolderException {
MailFolder folder = getFolder(user, mailboxName, true);
subscriptions.subscribe(user, folder);
}
/**
* @see ImapHostManager#unsubscribe
*/
@Override
public void unsubscribe(GreenMailUser user, String mailboxName)
throws FolderException {
MailFolder folder = getFolder(user, mailboxName, true);
subscriptions.unsubscribe(user, folder);
}
/**
* Convert a user specified store name into a server absolute name.
* If the mailboxName begins with the namespace token,
* return as-is.
* If not, need to resolve the Mailbox name for this user.
* Example:
* <br> Convert "INBOX" for user "Fred.Flinstone" into
* absolute name: "#user.Fred.Flintstone.INBOX"
*
* @return String of absoluteName, null if not valid selection
*/
private String getQualifiedMailboxName(GreenMailUser user, String mailboxName) {
String userNamespace = user.getQualifiedMailboxName();
if ("INBOX".equalsIgnoreCase(mailboxName)) {
return USER_NAMESPACE + HIERARCHY_DELIMITER + userNamespace +
HIERARCHY_DELIMITER + INBOX_NAME;
}
if (mailboxName.startsWith(NAMESPACE_PREFIX)) {
return mailboxName;
} else {
if (mailboxName.length() == 0) {
return USER_NAMESPACE + HIERARCHY_DELIMITER + userNamespace;
} else {
return USER_NAMESPACE + HIERARCHY_DELIMITER + userNamespace +
HIERARCHY_DELIMITER + mailboxName;
}
}
}
public Store getStore() {
return store;
}
/**
* Handles all user subscriptions.
* TODO make this a proper class
* TODO persist
*/
private static class MailboxSubscriptions {
private Map<String, List<String>> userSubs = new HashMap<String, List<String>>();
/**
* Subscribes the user to the store.
* TODO should this fail if already subscribed?
*
* @param user The user making the subscription
* @param folder The store to subscribe
* @throws FolderException ??? doesn't yet.
*/
void subscribe(GreenMailUser user, MailFolder folder)
throws FolderException {
getUserSubs(user).add(folder.getFullName());
}
/**
* Unsubscribes the user from this store.
* TODO should this fail if not already subscribed?
*
* @param user The user making the request.
* @param folder The store to unsubscribe
* @throws FolderException ?? doesn't yet
*/
void unsubscribe(GreenMailUser user, MailFolder folder)
throws FolderException {
getUserSubs(user).remove(folder.getFullName());
}
/**
* Returns whether the user is subscribed to the specified store.
*
* @param user The user to test.
* @param folder The store to test.
* @return <code>true</code> if the user is subscribed.
*/
boolean isSubscribed(GreenMailUser user, MailFolder folder) {
return getUserSubs(user).contains(folder.getFullName());
}
private List<String> getUserSubs(GreenMailUser user) {
List<String> subs = userSubs.get(user.getLogin());
if (subs == null) {
subs = new ArrayList<String>();
userSubs.put(user.getLogin(), subs);
}
return subs;
}
}
}
| |
/*
Copyright 2015 Google 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 com.google.security.zynamics.zylib.gui.zygraph.realizers.KeyBehaviours;
import java.awt.Point;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.zylib.general.ClipboardHelpers;
import com.google.security.zynamics.zylib.gui.zygraph.realizers.ECommentPlacement;
import com.google.security.zynamics.zylib.gui.zygraph.realizers.IZyEditableObject;
import com.google.security.zynamics.zylib.gui.zygraph.realizers.ZyCaret;
import com.google.security.zynamics.zylib.gui.zygraph.realizers.ZyLabelContent;
import com.google.security.zynamics.zylib.gui.zygraph.realizers.ZyLineContent;
import com.google.security.zynamics.zylib.gui.zygraph.realizers.KeyBehaviours.UndoHistroy.CUndoManager;
import com.google.security.zynamics.zylib.strings.StringHelper;
public abstract class CAbstractKeyBehavior {
private ZyLabelContent m_labelContent = null;
private final CUndoManager m_undoManager;
private KeyEvent m_event = null;
private boolean m_alt;
private boolean m_ctrl;
private boolean m_shift;
public CAbstractKeyBehavior(final CUndoManager undoManager) {
m_undoManager = Preconditions.checkNotNull(undoManager, "Error: Undo manager can't be null.");
}
private ZyCaret getCaret() {
return m_labelContent.getCaret();
}
private String getSingleLineCommentText(final ZyLineContent lineContent) {
final StringBuilder commentText = new StringBuilder();
final String lineText = lineContent.getText();
boolean hasDelimiter = false;
for (final IZyEditableObject lineObject : lineContent.getLineFragmentObjectList()) {
if (lineObject.isCommentDelimiter()) {
hasDelimiter = true;
continue;
}
if (hasDelimiter) {
final String subString = lineText.substring(lineObject.getStart(), lineObject.getEnd());
commentText.append(subString);
}
}
return commentText.toString();
}
private void setModifier(final KeyEvent event) {
m_ctrl = false;
m_shift = false;
m_alt = false;
if (event.getModifiersEx() == (InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)) {
m_ctrl = true;
m_shift = true;
} else if (event.getModifiersEx() == (InputEvent.CTRL_DOWN_MASK | InputEvent.ALT_DOWN_MASK)) {
m_ctrl = true;
m_alt = true;
} else if (event.getModifiersEx() == (InputEvent.ALT_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)) {
m_alt = true;
m_shift = true;
} else if (event.isAltDown()) {
m_alt = true;
} else if (event.isControlDown()) {
m_ctrl = true;
} else if (event.isShiftDown()) {
m_shift = true;
}
}
private void updateLabelSize() {
final ZyLabelContent labelContent = getLabelContent();
final IZyEditableObject labelModel = labelContent.getModel();
labelContent.getLineEditor().recreateLabelLines(labelContent, labelModel);
}
protected int correctMouseReleasedX(final int mouseReleased_X, final int mouseReleased_Y,
final int mousePressed_Y) {
final int lastReleasedXPos = getLastLineXPos(mouseReleased_Y);
if ((mouseReleased_X > lastReleasedXPos) && (mouseReleased_Y == mousePressed_Y)) {
return lastReleasedXPos;
}
return mouseReleased_X;
}
protected void deleteSelection() {
if (isSelection() && isDeleteableSelection()) {
int mouseStartX = Math.min(getCaretMousePressedX(), getCaretMouseReleasedX());
final int mouseEndX = Math.max(getCaretMousePressedX(), getCaretMouseReleasedX());
int mouseStartY = Math.min(getCaretMousePressedY(), getCaretMouseReleasedY());
final int mouseEndY = Math.max(getCaretMousePressedY(), getCaretMouseReleasedY());
int caretStartX = Math.min(getCaretStartPosX(), getCaretEndPosX());
final int firstModelLine = m_labelContent.getFirstLineIndexOfModelAt(mouseStartY);
final int noneCommentLine = m_labelContent.getNonPureCommentLineIndexOfModelAt(mouseStartY);
final int lastModelLine = m_labelContent.getLastLineIndexOfModelAt(mouseStartY);
int firstObjectLine = firstModelLine;
int lastObjectLine = lastModelLine;
if (noneCommentLine != -1) // It's is not a label comment.
{
if (mouseStartY < noneCommentLine) // It's a above line comment.
{
lastObjectLine = noneCommentLine - 1;
} else
// Its' a behind line comment.
{
firstObjectLine = noneCommentLine;
}
}
StringBuilder changedText = new StringBuilder();
ZyLineContent lineContent = getLineContent(mouseStartY);
IZyEditableObject editObject = lineContent.getLineFragmentObjectAt(mouseStartX);
if (editObject == null) {
for (int lineIndex = firstObjectLine; lineIndex <= lastObjectLine; ++lineIndex) {
final ZyLineContent curLineContent = getLineContent(lineIndex);
editObject = curLineContent.getLineFragmentObjectAt(mouseStartX);
if (editObject != null) {
break;
}
}
}
if ((firstObjectLine == lastObjectLine) && !isComment(caretStartX, mouseStartY)) {
// It's a single line editable object, but not a comment.
if (editObject.isCommentDelimiter()) {
mouseStartX = editObject.getEnd();
caretStartX = editObject.getEnd();
editObject = lineContent.getLineFragmentObjectAt(caretStartX);
}
final String text = lineContent.getText();
changedText =
new StringBuilder(String.format("%s%s",
text.substring(editObject.getStart(), mouseStartX), text.substring(mouseEndX)));
} else {
// It's multi line editable object.
for (int lineIndex = firstObjectLine; lineIndex <= lastObjectLine; ++lineIndex) {
// Iterates over each line
final ZyLineContent curLineContent = getLineContent(lineIndex);
IZyEditableObject curEditObject = curLineContent.getLineFragmentObjectAt(mouseStartX);
if (curEditObject == null) {
curEditObject = curLineContent.getLineFragmentObjectAt(getLastLineXPos(lineIndex));
}
int tempMouseStartX = mouseStartX;
int tempMouseEndX = mouseEndX;
if (curEditObject.isCommentDelimiter()) {
curEditObject = curLineContent.getLineFragmentObjectAt(curEditObject.getEnd());
tempMouseStartX = curEditObject.getStart();
if (mouseEndX < tempMouseStartX) {
tempMouseEndX = tempMouseStartX;
}
}
final String text = curLineContent.getText();
final int curEndX = Math.min(text.length(), tempMouseEndX);
if ((lineIndex >= mouseStartY) && (lineIndex <= mouseEndY)
&& (text.length() > tempMouseStartX)) {
final String afterDeletion =
String.format("%s%s", text.substring(curEditObject.getStart(), tempMouseStartX),
text.substring(curEndX));
if (!afterDeletion.equals("\n") && !afterDeletion.equals("\r")) {
changedText.append(afterDeletion);
}
} else {
changedText.append(curLineContent.getText(curEditObject));
}
}
}
if (changedText.toString().endsWith("\n")) {
changedText = new StringBuilder(changedText.substring(0, changedText.length() - 1));
}
if (!changedText.toString().endsWith("\r")) {
changedText.append("\r");
}
// Get new valid caret position.
if ((editObject != null) && editObject.isCommentDelimiter()) {
caretStartX = editObject.getEnd();
mouseStartX = editObject.getEnd();
}
for (int lineIndex = firstObjectLine; lineIndex <= lastObjectLine; ++lineIndex) {
lineContent = getLineContent(lineIndex);
if ((lineContent.getText().length() >= mouseStartX) && (mouseStartY <= lineIndex)) {
mouseStartY = lineIndex;
caretStartX = mouseStartX;
break;
}
}
// Update object, recreate lines and set caret.
if (editObject != null) {
editObject.update(changedText.toString());
getLabelContent().getLineEditor().recreateLabelLines(getLabelContent(),
editObject.getPersistentModel());
}
setCaret(caretStartX, mouseStartX, mouseStartY, caretStartX, mouseStartX, mouseStartY);
}
}
protected int getCaretEndPosX() {
return getCaret().getCaretEndPos();
}
protected int getCaretMousePressedX() {
return getCaret().getXmousePressed();
}
protected int getCaretMousePressedY() {
return getCaret().getYmousePressed();
}
protected int getCaretMouseReleasedX() {
return getCaret().getXmouseReleased();
}
protected int getCaretMouseReleasedY() {
return getCaret().getYmouseReleased();
}
protected int getCaretStartPosX() {
return getCaret().getCaretStartPos();
}
protected KeyEvent getEvent() {
return m_event;
}
protected ZyLabelContent getLabelContent() {
return m_labelContent;
}
protected int getLastLineXPos(final int lineYPos) {
final ZyLineContent lineContent = getLineContent(lineYPos);
final String text = lineContent.getText();
if (text.endsWith("\n") || text.endsWith("\r")) {
return text.length() - 1;
}
return text.length();
}
protected ZyLineContent getLineContent(final int line) {
return m_labelContent.getLineContent(line);
}
protected int getMaxLineLength(final int startYIndex, final int endYIndex) {
return getCaret().getMaxLineLength(startYIndex, endYIndex);
}
protected String getMultilineComment(final int lineYPos, final String changedLine) {
final StringBuilder commentText = new StringBuilder();
final int nonCommentLine = m_labelContent.getNonPureCommentLineIndexOfModelAt(lineYPos);
final int firstModelLine = m_labelContent.getFirstLineIndexOfModelAt(lineYPos);
final int lastModelLine = m_labelContent.getLastLineIndexOfModelAt(lineYPos);
int startIndex = isAboveLineComment(lineYPos) ? firstModelLine : nonCommentLine;
int endIndex = isAboveLineComment(lineYPos) ? nonCommentLine - 1 : lastModelLine;
if (nonCommentLine == -1) {
startIndex = firstModelLine;
endIndex = lastModelLine;
}
for (int index = startIndex; index <= endIndex; ++index) {
if (index == lineYPos) {
commentText.append(changedLine);
} else {
final ZyLineContent curLineContent = m_labelContent.getLineContent(index);
final String lineText = getSingleLineCommentText(curLineContent);
commentText.append(lineText);
}
}
return commentText.toString().equals("") ? changedLine : commentText.toString();
}
protected String getMultiLineComment(final int lineYPos) {
final StringBuilder commentText = new StringBuilder();
final int nonCommentLine = m_labelContent.getNonPureCommentLineIndexOfModelAt(lineYPos);
final int firstModelLine = m_labelContent.getFirstLineIndexOfModelAt(lineYPos);
final int lastModelLine = m_labelContent.getLastLineIndexOfModelAt(lineYPos);
int startIndex = isAboveLineComment(lineYPos) ? firstModelLine : nonCommentLine;
int endIndex = isAboveLineComment(lineYPos) ? nonCommentLine - 1 : lastModelLine;
if (nonCommentLine < 0) {
startIndex = firstModelLine;
endIndex = lastModelLine;
}
for (int index = startIndex; index <= endIndex; ++index) {
final ZyLineContent curLineContent = m_labelContent.getLineContent(index);
final String lineText = getSingleLineCommentText(curLineContent);
commentText.append(lineText);
}
return commentText.toString();
}
protected ZyLineContent getNextModelLineContent(final int lineYPos) {
final ZyLineContent lineContent = m_labelContent.getLineContent(lineYPos);
final IZyEditableObject lineObject = lineContent.getLineObject();
for (int index = lineYPos + 1; index < m_labelContent.getLineCount(); ++index) {
final ZyLineContent nextLineContent = m_labelContent.getLineContent(index);
if (nextLineContent == null) {
return null;
}
final IZyEditableObject nextLineObject = nextLineContent.getLineObject();
if ((lineObject != nextLineObject) && !nextLineObject.isPlaceholder()) {
return nextLineContent;
}
}
return null;
}
protected int getNextModelLineIndex(final int lineYPos) {
final ZyLineContent lineContent = getNextModelLineContent(lineYPos);
for (int index = lineYPos + 1; index < m_labelContent.getLineCount(); ++index) {
if ((lineContent != null) && !lineContent.getLineObject().isPlaceholder()) {
return getLabelContent().getLineIndex(lineContent);
}
}
return -1;
}
protected String getSelectedText() {
if (!isSelection()) {
return "";
}
final int yStart = Math.min(getCaretMousePressedY(), getCaretMouseReleasedY());
final int yEnd = Math.max(getCaretMousePressedY(), getCaretMouseReleasedY());
final int xStart = Math.min(getCaretMousePressedX(), getCaretMouseReleasedX());
final int xEnd = Math.max(getCaretMousePressedX(), getCaretMouseReleasedX());
final StringBuilder clipboardText = new StringBuilder();
for (int lineIndex = yStart; lineIndex <= yEnd; ++lineIndex) {
final ZyLineContent lineContent = getLineContent(lineIndex);
final int lineLength = lineContent.getText().length();
if (xStart < lineLength) {
int xTempEnd = xEnd;
if (xEnd > lineLength) {
xTempEnd = lineLength;
}
final String lineText = lineContent.getText();
String fragment = lineText.substring(xStart, xTempEnd);
if (!fragment.endsWith("\n") && (lineIndex != yEnd)) {
fragment += "\n";
}
if (fragment.endsWith("\r") || ((lineIndex == yEnd) && fragment.endsWith("\n"))) {
fragment = fragment.substring(0, fragment.length() - 1);
}
clipboardText.append(fragment);
} else if (lineIndex != yEnd) {
clipboardText.append("\n");
}
}
return clipboardText.toString();
}
protected abstract void initUndoHistory();
protected boolean isAboveLineComment(final int lineYPos) {
final int nonCommentLineYPos = getLabelContent().getNonPureCommentLineIndexOfModelAt(lineYPos);
if (nonCommentLineYPos < 0) {
return false;
}
if (nonCommentLineYPos <= lineYPos) {
return false;
}
return true;
}
protected boolean isAltPressed() {
return m_alt;
}
protected boolean isBehindLineComment(final int lineXPos, final int lineYPos) {
final int nonCommentLineYPos = getLabelContent().getNonPureCommentLineIndexOfModelAt(lineYPos);
if (nonCommentLineYPos < 0) {
return false;
}
if (nonCommentLineYPos < lineYPos) {
return true;
}
if (nonCommentLineYPos == lineYPos) {
final ZyLineContent lineContent = getLabelContent().getLineContent(lineYPos);
if (lineContent == null) {
return false;
}
for (final IZyEditableObject obj : lineContent.getLineFragmentObjectList()) {
if (obj.isCommentDelimiter()) {
return obj.getStart() <= lineXPos;
}
}
}
return false;
}
protected boolean isComment(final int lineXPos, final int lineYPos) {
final ZyLineContent lineContent = getLabelContent().getLineContent(lineYPos);
if (lineContent != null) {
boolean commentDelimiterFound = false;
for (final IZyEditableObject obj : lineContent.getLineFragmentObjectList()) {
if (obj.isCommentDelimiter()) {
commentDelimiterFound = true;
}
if ((lineXPos >= obj.getStart()) && commentDelimiterFound) {
return true;
}
}
}
return false;
}
protected boolean isCtrlPressed() {
return m_ctrl;
}
protected boolean isDeleteableSelection() {
final int mouseStartY = Math.min(getCaretMousePressedY(), getCaretMouseReleasedY());
final int mouseEndY = Math.max(getCaretMousePressedY(), getCaretMouseReleasedY());
final int caretStartX = Math.min(getCaretStartPosX(), getCaretEndPosX());
final int caretEndX = Math.max(getCaretStartPosX(), getCaretEndPosX());
final ZyLineContent firstLineContent = getLineContent(mouseStartY);
final ZyLineContent lastLineContent = getLineContent(mouseEndY);
final IZyEditableObject firstEditObject = firstLineContent.getLineFragmentObjectAt(caretStartX);
final IZyEditableObject lastEditObject = firstLineContent.getLineFragmentObjectAt(caretEndX);
if (firstLineContent.getLineObject() != lastLineContent.getLineObject()) {
return false;
}
if (isComment(caretStartX, mouseStartY)) {
if (mouseEndY > mouseStartY) {
final int noneCommentLine = m_labelContent.getNonPureCommentLineIndexOfModelAt(mouseStartY);
if (noneCommentLine != -1) {
if ((mouseStartY < noneCommentLine) && (mouseEndY >= noneCommentLine)) {
return false;
} else if ((mouseStartY >= noneCommentLine) && (mouseEndY < noneCommentLine)) {
return false;
}
}
}
} else {
if ((firstEditObject != lastEditObject)
|| ((firstEditObject == null) && (lastEditObject == null))) {
return false;
}
}
return true;
}
protected boolean isEditable(final int lineXPos, final int lineYPos) {
final ZyLineContent lineContent = getLabelContent().getLineContent(lineYPos);
return lineContent.isEditable(lineXPos);
}
protected boolean isLabelComment(final int lineYPos) {
return getLabelContent().getNonPureCommentLineIndexOfModelAt(lineYPos) == -1;
}
protected boolean isSelection() {
return getCaret().isSelection();
}
protected boolean isShiftPressed() {
return m_shift;
}
protected Point pasteClipboardText() {
int caretX = getCaretEndPosX();
int caretY = getCaretMouseReleasedY();
boolean isNewComment = false;
final ZyLineContent lineContent = getLineContent(caretY);
IZyEditableObject editObject = lineContent.getLineFragmentObjectAt(caretX);
if ((editObject == null) && (caretX == lineContent.getText().length())) {
final int nonModelLineY = getLabelContent().getNonPureCommentLineIndexOfModelAt(caretY);
if ((nonModelLineY != -1) && (nonModelLineY == caretY)) {
editObject = lineContent.getLineObject();
isNewComment = true;
}
}
if (editObject != null) {
String insertText = ClipboardHelpers.getClipboardString();
if (editObject.isCommentDelimiter()) {
caretX = editObject.getEnd();
editObject = lineContent.getLineFragmentObjectAt(caretX);
if (editObject == null) {
return null;
}
}
if (isComment(caretX, caretY)) {
// Insert into existing comment
final int insertedLineCount = StringHelper.count(insertText, '\n');
final int lastLineBreak = insertText.lastIndexOf("\n");
final int textCursor = caretX - editObject.getStart();
final String lineText =
lineContent.getText().substring(editObject.getStart(), editObject.getEnd());
String changedText =
String.format("%s%s%s", lineText.substring(0, textCursor), insertText,
lineText.substring(textCursor));
changedText = getMultilineComment(caretY, changedText);
editObject.update(changedText);
getLabelContent().getLineEditor().recreateLabelLines(getLabelContent(),
editObject.getPersistentModel());
caretX += insertText.length() - lastLineBreak - 1;
caretY += insertedLineCount;
} else if (isNewComment) {
// Create new comment
editObject.updateComment(insertText, ECommentPlacement.BEHIND_LINE);
if (!isLabelComment(caretY)) {
getLabelContent().getLineEditor().recreateLabelLines(getLabelContent(),
editObject.getPersistentModel());
final int insertedLineCount = StringHelper.count(insertText, '\n');
caretY += insertedLineCount;
final ZyLineContent lastInsertedLineContent = getLineContent(caretY);
caretX += lastInsertedLineContent.getText().length() - 1;
}
} else {
// Insert into non comment editable object
insertText = insertText.replace("\n", "");
insertText = insertText.replace("\r", "");
final int tempCaretX = caretX;
caretX = caretX + insertText.length();
final String lineText = lineContent.getText();
String changedText = lineText.substring(editObject.getStart(), editObject.getEnd());
final int insertXpos = tempCaretX - editObject.getStart();
changedText =
String.format("%s%s%s", lineText.substring(editObject.getStart(), insertXpos),
insertText, lineText.substring(caretX, editObject.getEnd()));
editObject.update(changedText);
}
}
return new Point(caretX, caretY);
}
protected void redo() {
m_undoManager.redo();
}
protected void setCaret(final int caretStartPos_X, final int mousePressed_X,
final int mousePressed_Y, final int caretEndPos_X, final int mouseReleased_X,
final int mouseReleased_Y) {
getCaret().setCaret(caretStartPos_X, mousePressed_X, mousePressed_Y, caretEndPos_X,
mouseReleased_X, mouseReleased_Y);
}
protected void udpateUndolist(final ZyLabelContent labelContent, final Object persistantModel,
final IZyEditableObject editableObject, final String changedText,
final boolean isAboveLineComment, final boolean isBehindLineComment,
final boolean isLabelComment, final int caretStartX, final int caretMousePressedX,
final int caretMousePressedY, final int caretEndX, final int caretMouseReleasedX,
final int caretMouseReleasedY) {
m_undoManager.addUndoState(labelContent, persistantModel, editableObject, changedText,
isAboveLineComment, isBehindLineComment, isLabelComment, caretStartX, caretMousePressedX,
caretMousePressedY, caretEndX, caretMouseReleasedX, caretMouseReleasedY);
}
protected void undo() {
m_undoManager.undo();
}
protected abstract void updateCaret();
protected abstract void updateClipboard();
protected abstract void updateLabelContent();
protected abstract void updateSelection();
protected abstract void updateUndoHistory();
public void keyPressed(final ZyLabelContent labelContent, final KeyEvent event) {
m_labelContent = labelContent;
m_event = event;
setModifier(event);
if (labelContent.isEditable()) {
initUndoHistory();
}
updateClipboard();
updateSelection();
if (labelContent.isEditable()) {
updateLabelContent();
}
updateCaret();
if (labelContent.isEditable()) {
updateUndoHistory();
updateLabelSize();
}
m_alt = false;
m_shift = false;
m_ctrl = false;
}
}
| |
/*
* Copyright 2013 Google Inc.
* Copyright 2014-2016 the libsecp256k1 contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.syscoin;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.math.BigInteger;
import com.google.common.base.Preconditions;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static org.syscoin.NativeSecp256k1Util.*;
/**
* <p>This class holds native methods to handle ECDSA verification.</p>
*
* <p>You can find an example library that can be used for this at https://github.com/syscoin/secp256k1</p>
*
* <p>To build secp256k1 for use with syscoinj, run
* `./configure --enable-jni --enable-experimental --enable-module-ecdh`
* and `make` then copy `.libs/libsecp256k1.so` to your system library path
* or point the JVM to the folder containing it with -Djava.library.path
* </p>
*/
public class NativeSecp256k1 {
private static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private static final Lock r = rwl.readLock();
private static final Lock w = rwl.writeLock();
private static ThreadLocal<ByteBuffer> nativeECDSABuffer = new ThreadLocal<ByteBuffer>();
/**
* Verifies the given secp256k1 signature in native code.
* Calling when enabled == false is undefined (probably library not loaded)
*
* @param data The data which was signed, must be exactly 32 bytes
* @param signature The signature
* @param pub The public key which did the signing
*/
public static boolean verify(byte[] data, byte[] signature, byte[] pub) throws AssertFailException{
Preconditions.checkArgument(data.length == 32 && signature.length <= 520 && pub.length <= 520);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < 520) {
byteBuff = ByteBuffer.allocateDirect(520);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(data);
byteBuff.put(signature);
byteBuff.put(pub);
byte[][] retByteArray;
r.lock();
try {
return secp256k1_ecdsa_verify(byteBuff, Secp256k1Context.getContext(), signature.length, pub.length) == 1;
} finally {
r.unlock();
}
}
/**
* libsecp256k1 Create an ECDSA signature.
*
* @param data Message hash, 32 bytes
* @param key Secret key, 32 bytes
*
* Return values
* @param sig byte array of signature
*/
public static byte[] sign(byte[] data, byte[] sec) throws AssertFailException{
Preconditions.checkArgument(data.length == 32 && sec.length <= 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < 32 + 32) {
byteBuff = ByteBuffer.allocateDirect(32 + 32);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(data);
byteBuff.put(sec);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_ecdsa_sign(byteBuff, Secp256k1Context.getContext());
} finally {
r.unlock();
}
byte[] sigArr = retByteArray[0];
int sigLen = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(sigArr.length, sigLen, "Got bad signature length.");
return retVal == 0 ? new byte[0] : sigArr;
}
/**
* libsecp256k1 Seckey Verify - returns 1 if valid, 0 if invalid
*
* @param seckey ECDSA Secret key, 32 bytes
*/
public static boolean secKeyVerify(byte[] seckey) {
Preconditions.checkArgument(seckey.length == 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < seckey.length) {
byteBuff = ByteBuffer.allocateDirect(seckey.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(seckey);
r.lock();
try {
return secp256k1_ec_seckey_verify(byteBuff,Secp256k1Context.getContext()) == 1;
} finally {
r.unlock();
}
}
/**
* libsecp256k1 Compute Pubkey - computes public key from secret key
*
* @param seckey ECDSA Secret key, 32 bytes
*
* Return values
* @param pubkey ECDSA Public key, 33 or 65 bytes
*/
//TODO add a 'compressed' arg
public static byte[] computePubkey(byte[] seckey) throws AssertFailException{
Preconditions.checkArgument(seckey.length == 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < seckey.length) {
byteBuff = ByteBuffer.allocateDirect(seckey.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(seckey);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_ec_pubkey_create(byteBuff, Secp256k1Context.getContext());
} finally {
r.unlock();
}
byte[] pubArr = retByteArray[0];
int pubLen = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(pubArr.length, pubLen, "Got bad pubkey length.");
return retVal == 0 ? new byte[0]: pubArr;
}
/**
* libsecp256k1 Cleanup - This destroys the secp256k1 context object
* This should be called at the end of the program for proper cleanup of the context.
*/
public static synchronized void cleanup() {
w.lock();
try {
secp256k1_destroy_context(Secp256k1Context.getContext());
} finally {
w.unlock();
}
}
public static long cloneContext() {
r.lock();
try {
return secp256k1_ctx_clone(Secp256k1Context.getContext());
} finally { r.unlock(); }
}
/**
* libsecp256k1 PrivKey Tweak-Mul - Tweak privkey by multiplying to it
*
* @param tweak some bytes to tweak with
* @param seckey 32-byte seckey
*/
public static byte[] privKeyTweakMul(byte[] privkey, byte[] tweak) throws AssertFailException{
Preconditions.checkArgument(privkey.length == 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) {
byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(privkey);
byteBuff.put(tweak);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_privkey_tweak_mul(byteBuff,Secp256k1Context.getContext());
} finally {
r.unlock();
}
byte[] privArr = retByteArray[0];
int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(privArr.length, privLen, "Got bad pubkey length.");
assertEquals(retVal, 1, "Failed return value check.");
return privArr;
}
/**
* libsecp256k1 PrivKey Tweak-Add - Tweak privkey by adding to it
*
* @param tweak some bytes to tweak with
* @param seckey 32-byte seckey
*/
public static byte[] privKeyTweakAdd(byte[] privkey, byte[] tweak) throws AssertFailException{
Preconditions.checkArgument(privkey.length == 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) {
byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(privkey);
byteBuff.put(tweak);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_privkey_tweak_add(byteBuff,Secp256k1Context.getContext());
} finally {
r.unlock();
}
byte[] privArr = retByteArray[0];
int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(privArr.length, privLen, "Got bad pubkey length.");
assertEquals(retVal, 1, "Failed return value check.");
return privArr;
}
/**
* libsecp256k1 PubKey Tweak-Add - Tweak pubkey by adding to it
*
* @param tweak some bytes to tweak with
* @param pubkey 32-byte seckey
*/
public static byte[] pubKeyTweakAdd(byte[] pubkey, byte[] tweak) throws AssertFailException{
Preconditions.checkArgument(pubkey.length == 33 || pubkey.length == 65);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) {
byteBuff = ByteBuffer.allocateDirect(pubkey.length + tweak.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(pubkey);
byteBuff.put(tweak);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_pubkey_tweak_add(byteBuff,Secp256k1Context.getContext(), pubkey.length);
} finally {
r.unlock();
}
byte[] pubArr = retByteArray[0];
int pubLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(pubArr.length, pubLen, "Got bad pubkey length.");
assertEquals(retVal, 1, "Failed return value check.");
return pubArr;
}
/**
* libsecp256k1 PubKey Tweak-Mul - Tweak pubkey by multiplying to it
*
* @param tweak some bytes to tweak with
* @param pubkey 32-byte seckey
*/
public static byte[] pubKeyTweakMul(byte[] pubkey, byte[] tweak) throws AssertFailException{
Preconditions.checkArgument(pubkey.length == 33 || pubkey.length == 65);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) {
byteBuff = ByteBuffer.allocateDirect(pubkey.length + tweak.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(pubkey);
byteBuff.put(tweak);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_pubkey_tweak_mul(byteBuff,Secp256k1Context.getContext(), pubkey.length);
} finally {
r.unlock();
}
byte[] pubArr = retByteArray[0];
int pubLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(pubArr.length, pubLen, "Got bad pubkey length.");
assertEquals(retVal, 1, "Failed return value check.");
return pubArr;
}
/**
* libsecp256k1 create ECDH secret - constant time ECDH calculation
*
* @param seckey byte array of secret key used in exponentiaion
* @param pubkey byte array of public key used in exponentiaion
*/
public static byte[] createECDHSecret(byte[] seckey, byte[] pubkey) throws AssertFailException{
Preconditions.checkArgument(seckey.length <= 32 && pubkey.length <= 65);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < 32 + pubkey.length) {
byteBuff = ByteBuffer.allocateDirect(32 + pubkey.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(seckey);
byteBuff.put(pubkey);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_ecdh(byteBuff, Secp256k1Context.getContext(), pubkey.length);
} finally {
r.unlock();
}
byte[] resArr = retByteArray[0];
int retVal = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();
assertEquals(resArr.length, 32, "Got bad result length.");
assertEquals(retVal, 1, "Failed return value check.");
return resArr;
}
/**
* libsecp256k1 randomize - updates the context randomization
*
* @param seed 32-byte random seed
*/
public static synchronized boolean randomize(byte[] seed) throws AssertFailException{
Preconditions.checkArgument(seed.length == 32 || seed == null);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < seed.length) {
byteBuff = ByteBuffer.allocateDirect(seed.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(seed);
w.lock();
try {
return secp256k1_context_randomize(byteBuff, Secp256k1Context.getContext()) == 1;
} finally {
w.unlock();
}
}
private static native long secp256k1_ctx_clone(long context);
private static native int secp256k1_context_randomize(ByteBuffer byteBuff, long context);
private static native byte[][] secp256k1_privkey_tweak_add(ByteBuffer byteBuff, long context);
private static native byte[][] secp256k1_privkey_tweak_mul(ByteBuffer byteBuff, long context);
private static native byte[][] secp256k1_pubkey_tweak_add(ByteBuffer byteBuff, long context, int pubLen);
private static native byte[][] secp256k1_pubkey_tweak_mul(ByteBuffer byteBuff, long context, int pubLen);
private static native void secp256k1_destroy_context(long context);
private static native int secp256k1_ecdsa_verify(ByteBuffer byteBuff, long context, int sigLen, int pubLen);
private static native byte[][] secp256k1_ecdsa_sign(ByteBuffer byteBuff, long context);
private static native int secp256k1_ec_seckey_verify(ByteBuffer byteBuff, long context);
private static native byte[][] secp256k1_ec_pubkey_create(ByteBuffer byteBuff, long context);
private static native byte[][] secp256k1_ec_pubkey_parse(ByteBuffer byteBuff, long context, int inputLen);
private static native byte[][] secp256k1_ecdh(ByteBuffer byteBuff, long context, int inputLen);
}
| |
/**
* This class is generated by jOOQ
*/
package io.cattle.platform.core.model;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(value = { "http://www.jooq.org", "3.3.0" },
comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
@javax.persistence.Entity
@javax.persistence.Table(name = "instance", schema = "cattle")
public interface Instance extends java.io.Serializable {
/**
* Setter for <code>cattle.instance.id</code>.
*/
public void setId(java.lang.Long value);
/**
* Getter for <code>cattle.instance.id</code>.
*/
@javax.persistence.Id
@javax.persistence.Column(name = "id", unique = true, nullable = false, precision = 19)
public java.lang.Long getId();
/**
* Setter for <code>cattle.instance.name</code>.
*/
public void setName(java.lang.String value);
/**
* Getter for <code>cattle.instance.name</code>.
*/
@javax.persistence.Column(name = "name", length = 255)
public java.lang.String getName();
/**
* Setter for <code>cattle.instance.account_id</code>.
*/
public void setAccountId(java.lang.Long value);
/**
* Getter for <code>cattle.instance.account_id</code>.
*/
@javax.persistence.Column(name = "account_id", precision = 19)
public java.lang.Long getAccountId();
/**
* Setter for <code>cattle.instance.kind</code>.
*/
public void setKind(java.lang.String value);
/**
* Getter for <code>cattle.instance.kind</code>.
*/
@javax.persistence.Column(name = "kind", nullable = false, length = 255)
public java.lang.String getKind();
/**
* Setter for <code>cattle.instance.uuid</code>.
*/
public void setUuid(java.lang.String value);
/**
* Getter for <code>cattle.instance.uuid</code>.
*/
@javax.persistence.Column(name = "uuid", unique = true, nullable = false, length = 128)
public java.lang.String getUuid();
/**
* Setter for <code>cattle.instance.description</code>.
*/
public void setDescription(java.lang.String value);
/**
* Getter for <code>cattle.instance.description</code>.
*/
@javax.persistence.Column(name = "description", length = 1024)
public java.lang.String getDescription();
/**
* Setter for <code>cattle.instance.state</code>.
*/
public void setState(java.lang.String value);
/**
* Getter for <code>cattle.instance.state</code>.
*/
@javax.persistence.Column(name = "state", nullable = false, length = 128)
public java.lang.String getState();
/**
* Setter for <code>cattle.instance.created</code>.
*/
public void setCreated(java.util.Date value);
/**
* Getter for <code>cattle.instance.created</code>.
*/
@javax.persistence.Column(name = "created")
public java.util.Date getCreated();
/**
* Setter for <code>cattle.instance.removed</code>.
*/
public void setRemoved(java.util.Date value);
/**
* Getter for <code>cattle.instance.removed</code>.
*/
@javax.persistence.Column(name = "removed")
public java.util.Date getRemoved();
/**
* Setter for <code>cattle.instance.remove_time</code>.
*/
public void setRemoveTime(java.util.Date value);
/**
* Getter for <code>cattle.instance.remove_time</code>.
*/
@javax.persistence.Column(name = "remove_time")
public java.util.Date getRemoveTime();
/**
* Setter for <code>cattle.instance.data</code>.
*/
public void setData(java.util.Map<String,Object> value);
/**
* Getter for <code>cattle.instance.data</code>.
*/
@javax.persistence.Column(name = "data", length = 16777215)
public java.util.Map<String,Object> getData();
/**
* Setter for <code>cattle.instance.allocation_state</code>.
*/
public void setAllocationState(java.lang.String value);
/**
* Getter for <code>cattle.instance.allocation_state</code>.
*/
@javax.persistence.Column(name = "allocation_state", length = 255)
public java.lang.String getAllocationState();
/**
* Setter for <code>cattle.instance.compute</code>.
*/
public void setCompute(java.lang.Long value);
/**
* Getter for <code>cattle.instance.compute</code>.
*/
@javax.persistence.Column(name = "compute", precision = 19)
public java.lang.Long getCompute();
/**
* Setter for <code>cattle.instance.memory_mb</code>.
*/
public void setMemoryMb(java.lang.Long value);
/**
* Getter for <code>cattle.instance.memory_mb</code>.
*/
@javax.persistence.Column(name = "memory_mb", precision = 19)
public java.lang.Long getMemoryMb();
/**
* Setter for <code>cattle.instance.image_id</code>.
*/
public void setImageId(java.lang.Long value);
/**
* Getter for <code>cattle.instance.image_id</code>.
*/
@javax.persistence.Column(name = "image_id", precision = 19)
public java.lang.Long getImageId();
/**
* Setter for <code>cattle.instance.hostname</code>.
*/
public void setHostname(java.lang.String value);
/**
* Getter for <code>cattle.instance.hostname</code>.
*/
@javax.persistence.Column(name = "hostname", length = 255)
public java.lang.String getHostname();
/**
* Setter for <code>cattle.instance.zone_id</code>.
*/
public void setZoneId(java.lang.Long value);
/**
* Getter for <code>cattle.instance.zone_id</code>.
*/
@javax.persistence.Column(name = "zone_id", precision = 19)
public java.lang.Long getZoneId();
/**
* Setter for <code>cattle.instance.instance_triggered_stop</code>.
*/
public void setInstanceTriggeredStop(java.lang.String value);
/**
* Getter for <code>cattle.instance.instance_triggered_stop</code>.
*/
@javax.persistence.Column(name = "instance_triggered_stop", length = 128)
public java.lang.String getInstanceTriggeredStop();
/**
* Setter for <code>cattle.instance.agent_id</code>.
*/
public void setAgentId(java.lang.Long value);
/**
* Getter for <code>cattle.instance.agent_id</code>.
*/
@javax.persistence.Column(name = "agent_id", precision = 19)
public java.lang.Long getAgentId();
/**
* Setter for <code>cattle.instance.domain</code>.
*/
public void setDomain(java.lang.String value);
/**
* Getter for <code>cattle.instance.domain</code>.
*/
@javax.persistence.Column(name = "domain", length = 128)
public java.lang.String getDomain();
/**
* Setter for <code>cattle.instance.first_running</code>.
*/
public void setFirstRunning(java.util.Date value);
/**
* Getter for <code>cattle.instance.first_running</code>.
*/
@javax.persistence.Column(name = "first_running")
public java.util.Date getFirstRunning();
/**
* Setter for <code>cattle.instance.token</code>.
*/
public void setToken(java.lang.String value);
/**
* Getter for <code>cattle.instance.token</code>.
*/
@javax.persistence.Column(name = "token", length = 255)
public java.lang.String getToken();
/**
* Setter for <code>cattle.instance.userdata</code>.
*/
public void setUserdata(java.lang.String value);
/**
* Getter for <code>cattle.instance.userdata</code>.
*/
@javax.persistence.Column(name = "userdata", length = 65535)
public java.lang.String getUserdata();
/**
* Setter for <code>cattle.instance.registry_credential_id</code>.
*/
public void setRegistryCredentialId(java.lang.Long value);
/**
* Getter for <code>cattle.instance.registry_credential_id</code>.
*/
@javax.persistence.Column(name = "registry_credential_id", precision = 19)
public java.lang.Long getRegistryCredentialId();
/**
* Setter for <code>cattle.instance.external_id</code>.
*/
public void setExternalId(java.lang.String value);
/**
* Getter for <code>cattle.instance.external_id</code>.
*/
@javax.persistence.Column(name = "external_id", length = 128)
public java.lang.String getExternalId();
/**
* Setter for <code>cattle.instance.native_container</code>.
*/
public void setNativeContainer(java.lang.Boolean value);
/**
* Getter for <code>cattle.instance.native_container</code>.
*/
@javax.persistence.Column(name = "native_container", nullable = false, precision = 1)
public java.lang.Boolean getNativeContainer();
/**
* Setter for <code>cattle.instance.network_container_id</code>.
*/
public void setNetworkContainerId(java.lang.Long value);
/**
* Getter for <code>cattle.instance.network_container_id</code>.
*/
@javax.persistence.Column(name = "network_container_id", precision = 19)
public java.lang.Long getNetworkContainerId();
/**
* Setter for <code>cattle.instance.health_state</code>.
*/
public void setHealthState(java.lang.String value);
/**
* Getter for <code>cattle.instance.health_state</code>.
*/
@javax.persistence.Column(name = "health_state", length = 128)
public java.lang.String getHealthState();
/**
* Setter for <code>cattle.instance.start_count</code>.
*/
public void setStartCount(java.lang.Long value);
/**
* Getter for <code>cattle.instance.start_count</code>.
*/
@javax.persistence.Column(name = "start_count", precision = 19)
public java.lang.Long getStartCount();
/**
* Setter for <code>cattle.instance.create_index</code>.
*/
public void setCreateIndex(java.lang.Long value);
/**
* Getter for <code>cattle.instance.create_index</code>.
*/
@javax.persistence.Column(name = "create_index", precision = 19)
public java.lang.Long getCreateIndex();
/**
* Setter for <code>cattle.instance.deployment_unit_uuid</code>.
*/
public void setDeploymentUnitUuid(java.lang.String value);
/**
* Getter for <code>cattle.instance.deployment_unit_uuid</code>.
*/
@javax.persistence.Column(name = "deployment_unit_uuid", length = 128)
public java.lang.String getDeploymentUnitUuid();
/**
* Setter for <code>cattle.instance.version</code>.
*/
public void setVersion(java.lang.String value);
/**
* Getter for <code>cattle.instance.version</code>.
*/
@javax.persistence.Column(name = "version", length = 255)
public java.lang.String getVersion();
/**
* Setter for <code>cattle.instance.health_updated</code>.
*/
public void setHealthUpdated(java.util.Date value);
/**
* Getter for <code>cattle.instance.health_updated</code>.
*/
@javax.persistence.Column(name = "health_updated")
public java.util.Date getHealthUpdated();
/**
* Setter for <code>cattle.instance.service_index_id</code>.
*/
public void setServiceIndexId(java.lang.Long value);
/**
* Getter for <code>cattle.instance.service_index_id</code>.
*/
@javax.persistence.Column(name = "service_index_id", precision = 19)
public java.lang.Long getServiceIndexId();
/**
* Setter for <code>cattle.instance.dns_internal</code>.
*/
public void setDnsInternal(java.lang.String value);
/**
* Getter for <code>cattle.instance.dns_internal</code>.
*/
@javax.persistence.Column(name = "dns_internal", length = 255)
public java.lang.String getDnsInternal();
/**
* Setter for <code>cattle.instance.dns_search_internal</code>.
*/
public void setDnsSearchInternal(java.lang.String value);
/**
* Getter for <code>cattle.instance.dns_search_internal</code>.
*/
@javax.persistence.Column(name = "dns_search_internal", length = 255)
public java.lang.String getDnsSearchInternal();
/**
* Setter for <code>cattle.instance.memory_reservation</code>.
*/
public void setMemoryReservation(java.lang.Long value);
/**
* Getter for <code>cattle.instance.memory_reservation</code>.
*/
@javax.persistence.Column(name = "memory_reservation", precision = 19)
public java.lang.Long getMemoryReservation();
/**
* Setter for <code>cattle.instance.milli_cpu_reservation</code>.
*/
public void setMilliCpuReservation(java.lang.Long value);
/**
* Getter for <code>cattle.instance.milli_cpu_reservation</code>.
*/
@javax.persistence.Column(name = "milli_cpu_reservation", precision = 19)
public java.lang.Long getMilliCpuReservation();
/**
* Setter for <code>cattle.instance.system</code>.
*/
public void setSystem(java.lang.Boolean value);
/**
* Getter for <code>cattle.instance.system</code>.
*/
@javax.persistence.Column(name = "system", nullable = false, precision = 1)
public java.lang.Boolean getSystem();
// -------------------------------------------------------------------------
// FROM and INTO
// -------------------------------------------------------------------------
/**
* Load data from another generated Record/POJO implementing the common interface Instance
*/
public void from(io.cattle.platform.core.model.Instance from);
/**
* Copy data into another generated Record/POJO implementing the common interface Instance
*/
public <E extends io.cattle.platform.core.model.Instance> E into(E into);
}
| |
/*
* Copyright 2015, Barend Garvelink
*
* 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.garvelink.oss.android_iconfont.example;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import nl.garvelink.oss.android_iconfont.IconFontDrawable;
/**
* Sample usage of {@link nl.garvelink.oss.android_iconfont.IconFontDrawable}.
*/
public class DemoActivity extends AppCompatActivity {
private static final boolean HAS_ANIMATOR_API = Build.VERSION.SDK_INT >= 11;
private static Typeface fontAwesome;
private ObjectAnimator menuItemRotator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (fontAwesome == null) {
// You shouldn't assign static fields from an instance method. Ssh!
fontAwesome = Typeface.createFromAsset(getAssets(), "FontAwesome-4.1.0.otf");
}
setContentView(R.layout.activity_demo);
int eight_dp = (int)(getResources().getDisplayMetrics().density * 8);
int twentyfour_dp = 3 * eight_dp;
TextView compoundDrawables = (TextView) findViewById(R.id.compound_drawables);
//
// * The most basic IconFontDrawable can be directly constructed.
//
Drawable down = new IconFontDrawable(fontAwesome, Icons.FA_ANGLE_DOWN, Color.BLUE, eight_dp);
Drawable left = new IconFontDrawable(fontAwesome, Icons.FA_ANGLE_LEFT, Color.BLUE, eight_dp);
Drawable right = new IconFontDrawable(fontAwesome, Icons.FA_ANGLE_RIGHT, Color.BLUE, eight_dp);
Drawable up = new IconFontDrawable(fontAwesome, Icons.FA_ANGLE_UP, Color.BLUE, eight_dp);
compoundDrawables.setCompoundDrawablesWithIntrinsicBounds(left, up, right, down);
ImageView imageNoIntrinsic = (ImageView) findViewById(R.id.image_no_intrinsic);
//
// * You can use setters for the properties that are not exposed in the constructor.
//
IconFontDrawable image = new IconFontDrawable(fontAwesome, Icons.FA_ARROWS_ALT, Color.BLACK);
image.setColor(getResources().getColorStateList(R.color.pressed_color_selector));
image.setPadding(0);
imageNoIntrinsic.setImageDrawable(image);
//
// * For more complex IFD's, the Builder is nicer.
//
ImageView imageCenter = (ImageView) findViewById(R.id.image_center);
image = IconFontDrawable.builder(this)
.setTypeface(fontAwesome)
.setColorResource(android.R.color.black)
.setGlyph(Icons.FA_PAW)
.setIntrinsicSize(60, TypedValue.COMPLEX_UNIT_DIP)
.build();
imageCenter.setImageDrawable(image);
//
// * You'll use dp's a lot, so intrinsicSize and padding can be built directly in dp.
//
ImageView imageFitEnd = (ImageView) findViewById(R.id.image_fit_end);
image = IconFontDrawable.builder(this)
.setTypeface(fontAwesome)
.setColorValue(Color.BLUE)
.setGlyph(Icons.FA_FLOPPY_O)
.setIntrinsicSizeInDip(60)
.setPaddingInDip(0)
.setOpacity(0.2f)
.setRotation(-6f)
.build();
imageFitEnd.setImageDrawable(image);
TextView fontAwesomeLink = (TextView) findViewById(R.id.font_awesome);
IconFontDrawable fontAwesomeIcon = new IconFontDrawable(fontAwesome, Icons.FA_FLAG, Color.BLACK, twentyfour_dp);
createAndStartOpacityAnimation(fontAwesomeIcon);
fontAwesomeLink.setCompoundDrawablesWithIntrinsicBounds(fontAwesomeIcon, null, null, null);
fontAwesomeLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openURL("http://fortawesome.github.io/Font-Awesome/");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//
// * Here we create a Builder with all the common properties for actionbar icons.
//
IconFontDrawable.Builder icons = IconFontDrawable.builder(this)
.setTypeface(fontAwesome)
.setColorResource(R.color.action_bar_color_selector)
.setIntrinsicSizeInDip(32)
.setPaddingInDip(4);
getMenuInflater().inflate(R.menu.demo, menu);
MenuItem menuGithub = menu.findItem(R.id.action_github);
MenuItem menuRotate = menu.findItem(R.id.action_rotate);
//
// * This single Builder can be re-used for many icons, all properties are kept.
//
IconFontDrawable iconGithub = icons.setGlyph(Icons.FA_GITHUB).build();
IconFontDrawable iconRotate = icons.setGlyph(Icons.FA_CIRCLE_O_NOTCH).build();
menuGithub.setIcon(iconGithub);
menuRotate.setIcon(iconRotate);
//
// * The properties that have setters can be animated.
//
createRotationAnimation(iconRotate);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_rotate) {
toggleRotationAnimation();
return true;
} else if (id == R.id.action_github) {
openURL("https://github.com/barend/android-iconfont");
return true;
}
return super.onOptionsItemSelected(item);
}
private void openURL(String url) {
try {
Intent www = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
www.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(www);
} catch (Exception e) {
// Ignored.
}
}
@SuppressLint("NewApi")
private void createAndStartOpacityAnimation(IconFontDrawable icon) {
if (HAS_ANIMATOR_API) {
ObjectAnimator alphaAnim = ObjectAnimator.ofInt(icon, "alpha", 0x0A, 0xFF);
alphaAnim.setRepeatCount(ObjectAnimator.INFINITE);
alphaAnim.setRepeatMode(ObjectAnimator.REVERSE);
alphaAnim.setStartDelay(0L);
alphaAnim.setDuration(2500L);
alphaAnim.setInterpolator(new AccelerateInterpolator());
alphaAnim.start();
}
}
@SuppressLint("NewApi")
private void createRotationAnimation(IconFontDrawable menuItemIcon) {
if (HAS_ANIMATOR_API) {
menuItemRotator = ObjectAnimator.ofFloat(menuItemIcon, "rotation", 0f, 359.99f);
menuItemRotator.setRepeatCount(ObjectAnimator.INFINITE);
menuItemRotator.setRepeatMode(ObjectAnimator.RESTART);
menuItemRotator.setStartDelay(0L);
menuItemRotator.setDuration(1000L);
menuItemRotator.setInterpolator(new LinearInterpolator());
}
}
@SuppressLint("NewApi")
private void toggleRotationAnimation() {
if (HAS_ANIMATOR_API) {
if (menuItemRotator.isPaused()) {
menuItemRotator.resume();
} else if (menuItemRotator.isRunning()) {
menuItemRotator.pause();
} else {
menuItemRotator.start();
}
} else {
Toast.makeText(this, getString(R.string.toast_rotation), Toast.LENGTH_SHORT).show();
}
}
}
| |
package com.ichi2.apisample;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.provider.ContactsContract;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.ichi2.anki.api.AddContentApi;
import java.util.ArrayList;
import java.util.HashMap;
/*
public class Data extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
*/
public class Data extends MainActivity {
public static final String LOG_TAG = "AnkiDroidApiSample";
private static final int AD_PERM_REQUEST = 0;
private ListView mListView;
private ArrayList<HashMap<String, String>> mListData;
private String front = "";
private String back = "";
private String stats = "";
private String recomm = "";
//EditText SharedText1;
int save = 0;
private InputMethodManager imm;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
public static void hideKeyboard(Activity activity) {
InputMethodManager imm1 = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
//Find the currently focused view, so we can grab the correct window token from it.
View view = activity.getCurrentFocus();
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = new View(activity);
}
imm1.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
//personality = sharedText;
SharedText1.setText(sharedText);
// Disable Onscreen Keyboard
View view1 = this.getCurrentFocus(); // not working
if (view1 != null) { // not working
view1.clearFocus(); // not working
imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE); // not working
imm.hideSoftInputFromWindow(view1.getWindowToken(), 0); // not working
}
//Toast.makeText(MainActivity.this, "Disabled Onscreen Keyboard", Toast.LENGTH_LONG).show();
}
}
public void onClick(View v) {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = clipboard.getPrimaryClip();
CharSequence charseq;
//if (clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
ClipData.Item item = clip.getItemAt(0);
charseq = item.getText();
//Toast.makeText(MainActivity.this, "CharSequence : " + charseq + "\n Subsequence: " + charseq.subSequence(16,charseq.length()-2), Toast.LENGTH_LONG).show();
//}
switch (v.getId()) {
case R.id.button:
Button button = (Button) findViewById(R.id.button);
//Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_LONG).show();
front = charseq.toString();
//Toast.makeText(MainActivity.this, "\n Personality : " + personality + "\n Field : " + field + "\n Contribution : " + contribution + "\n Criticism: " + criticism, Toast.LENGTH_LONG).show();
save = 1;
break;
case R.id.button2:
Button button2 = (Button) findViewById(R.id.button2);
//Toast.makeText(MainActivity.this, "Button2 Clicked", Toast.LENGTH_LONG).show();
back = charseq.toString();
save = 1;
break;
case R.id.button3:
Button button3 = (Button) findViewById(R.id.button3);
//Toast.makeText(MainActivity.this, "Button3 Clicked", Toast.LENGTH_LONG).show();
stats = charseq.toString();
save = 1;
break;
case R.id.button4:
Button button4 = (Button) findViewById(R.id.button4);
//Toast.makeText(MainActivity.this, "Button4 Clicked", Toast.LENGTH_LONG).show();
recomm = charseq.toString();
save = 1;
break;
case R.id.button5:
Button button5 = (Button) findViewById(R.id.button5);
//Toast.makeText(MainActivity.this, "Button5 Clicked", Toast.LENGTH_LONG).show();
if (save != 1) {
Toast.makeText(Data.this, "All fields empty!!!", Toast.LENGTH_LONG).show();
break;
}
// Test Code to add basic card
final AddContentApi api = new AddContentApi(Data.this);
// Add new deck if one doesn't already exist
Long did = api.findDeckIdByName("Data");
if (did != null) {
//Toast.makeText(MainActivity.this, "Found Deck PIN!", Toast.LENGTH_LONG).show();
}
Long mid = api.findModelIdByName("Economy", 2);
if (mid != null) {
//Toast.makeText(MainActivity.this, "Found MID PIN!", Toast.LENGTH_LONG).show();
}
api.addNewNote(mid, did, new String[]{front, back, stats, recomm}, "Economy");
Toast.makeText(Data.this, "\n Front : " + front + "\n Back : " + back + "\n Graph/stats : " + stats + "\n Recoomendation: " + recomm , Toast.LENGTH_LONG).show();
break;
case R.id.editText:
imm.hideSoftInputFromWindow(SharedText1.getWindowToken(), 0); // not working
default:
Toast.makeText(Data.this, "Please select some text first!!!", Toast.LENGTH_LONG).show();
}
save = 1;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data);
hideKeyboard(Data.this); // not working
SharedText1 = (EditText) findViewById(R.id.editText);
/* imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE); // not working
imm.hideSoftInputFromWindow(SharedText1.getWindowToken(), 0); // not working
*/
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
handleSendText(intent); // Handle text being sent
/*
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
}
}*/
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.ichi2.apisample/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.ichi2.apisample/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
| |
package org.zstack.compute.host;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.zstack.core.cascade.CascadeConstant;
import org.zstack.core.cascade.CascadeFacade;
import org.zstack.core.cloudbus.*;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.config.GlobalConfigFacade;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.Q;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.core.thread.ChainTask;
import org.zstack.core.thread.SyncTaskChain;
import org.zstack.core.thread.ThreadFacade;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.core.workflow.ShareFlow;
import org.zstack.header.allocator.HostAllocatorConstant;
import org.zstack.header.apimediator.ApiMessageInterceptionException;
import org.zstack.header.core.Completion;
import org.zstack.header.core.NoErrorCompletion;
import org.zstack.header.core.NopeCompletion;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.errorcode.SysErrors;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.host.*;
import org.zstack.header.host.HostCanonicalEvents.HostDeletedData;
import org.zstack.header.host.HostCanonicalEvents.HostStatusChangedData;
import org.zstack.header.host.HostErrors.Opaque;
import org.zstack.header.host.HostMaintenancePolicyExtensionPoint.HostMaintenancePolicy;
import org.zstack.header.message.APIDeleteMessage;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.vm.*;
import org.zstack.utils.CollectionUtils;
import org.zstack.utils.DebugUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.function.ForEachFunction;
import org.zstack.utils.logging.CLogger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.zstack.core.Platform.operr;
@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE)
public abstract class HostBase extends AbstractHost {
protected static final CLogger logger = Utils.getLogger(HostBase.class);
protected HostVO self;
@Autowired
protected CloudBus bus;
@Autowired
protected DatabaseFacade dbf;
@Autowired
protected ThreadFacade thdf;
@Autowired
protected HostExtensionPointEmitter extpEmitter;
@Autowired
protected GlobalConfigFacade gcf;
@Autowired
protected HostManager hostMgr;
@Autowired
protected CascadeFacade casf;
@Autowired
protected ErrorFacade errf;
@Autowired
protected HostTracker tracker;
@Autowired
protected PluginRegistry pluginRgty;
@Autowired
protected EventFacade evtf;
protected final String id;
protected abstract void pingHook(Completion completion);
protected abstract int getVmMigrateQuantity();
protected abstract void changeStateHook(HostState current, HostStateEvent stateEvent, HostState next);
protected abstract void connectHook(ConnectHostInfo info, Completion complete);
protected HostBase(HostVO self) {
this.self = self;
id = "Host-" + self.getUuid();
}
protected void checkStatus() {
if (HostStatus.Connected != self.getStatus()) {
ErrorCode cause = errf.instantiateErrorCode(HostErrors.HOST_IS_DISCONNECTED, String.format("host[uuid:%s, name:%s] is in status[%s], cannot perform required operation", self.getUuid(), self.getName(), self.getStatus()));
throw new OperationFailureException(errf.instantiateErrorCode(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, "unable to do the operation because the host is in status of Disconnected", cause));
}
}
protected void checkState() {
if (HostState.PreMaintenance == self.getState() || HostState.Maintenance == self.getState()) {
throw new OperationFailureException(operr("host[uuid:%s, name:%s] is in state[%s], cannot perform required operation", self.getUuid(), self.getName(), self.getState()));
}
}
protected void checkStateAndStatus() {
checkState();
checkStatus();
}
protected int getHostSyncLevel() {
return 10;
}
protected void handleApiMessage(APIMessage msg) {
if (msg instanceof APIChangeHostStateMsg) {
handle((APIChangeHostStateMsg) msg);
} else if (msg instanceof APIDeleteHostMsg) {
handle((APIDeleteHostMsg) msg);
} else if (msg instanceof APIReconnectHostMsg) {
handle((APIReconnectHostMsg) msg);
} else if (msg instanceof APIUpdateHostMsg) {
handle((APIUpdateHostMsg) msg);
} else {
bus.dealWithUnknownMessage(msg);
}
}
protected HostVO updateHost(APIUpdateHostMsg msg) {
boolean update = false;
if (msg.getName() != null) {
self.setName(msg.getName());
update = true;
}
if (msg.getDescription() != null) {
self.setDescription(msg.getDescription());
update = true;
}
if (msg.getManagementIp() != null) {
self.setManagementIp(msg.getManagementIp());
update = true;
}
return update ? self : null;
}
private void handle(APIUpdateHostMsg msg) {
HostVO vo = updateHost(msg);
if (vo != null) {
self = dbf.updateAndRefresh(vo);
}
APIUpdateHostEvent evt = new APIUpdateHostEvent(msg.getId());
evt.setInventory(getSelfInventory());
bus.publish(evt);
}
protected void maintenanceHook(final Completion completion) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("maintenance-mode-host-%s-ip-%s", self.getUuid(), self.getManagementIp()));
HostMaintenancePolicy policy = HostMaintenancePolicy.MigrateVm;
for (HostMaintenancePolicyExtensionPoint ext : pluginRgty.getExtensionList(HostMaintenancePolicyExtensionPoint.class)) {
HostMaintenancePolicy p = ext.getHostMaintenancePolicy(getSelfInventory());
if (p != null) {
policy = p;
logger.debug(String.format("HostMaintenancePolicyExtensionPoint[%s] set maintenance policy for host[uuid:%s] to %s",
ext.getClass(), self.getUuid(), policy));
}
}
final int quantity = getVmMigrateQuantity();
DebugUtils.Assert(quantity != 0, "getVmMigrateQuantity() cannot return 0");
final HostMaintenancePolicy finalPolicy = policy;
chain.then(new ShareFlow() {
List<String> vmFailedToMigrate = new ArrayList<String>();
@Override
public void setup() {
if (finalPolicy == HostMaintenancePolicy.MigrateVm) {
flow(new NoRollbackFlow() {
String __name__ = "try-migrate-vm";
@Override
public void run(final FlowTrigger trigger, Map data) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.uuid);
q.add(VmInstanceVO_.hostUuid, Op.EQ, self.getUuid());
q.add(VmInstanceVO_.state, Op.NOT_EQ, VmInstanceState.Unknown);
List<String> vmUuids = q.listValue();
if (vmUuids.isEmpty()) {
trigger.next();
return;
}
int migrateQuantity = quantity;
HostInventory host = getSelfInventory();
for (OrderVmBeforeMigrationDuringHostMaintenanceExtensionPoint ext : pluginRgty.getExtensionList(OrderVmBeforeMigrationDuringHostMaintenanceExtensionPoint.class)) {
List<String> ordered = ext.orderVmBeforeMigrationDuringHostMaintenance(host, vmUuids);
if (ordered != null) {
vmUuids = ordered;
logger.debug(String.format("%s ordered VMs for host maintenance, to keep the order, we will migrate VMs one by one",
ext.getClass()));
migrateQuantity = 1;
}
}
final List<MigrateVmMsg> msgs = new ArrayList<MigrateVmMsg>();
for (String uuid : vmUuids) {
MigrateVmMsg msg = new MigrateVmMsg();
msg.setVmInstanceUuid(uuid);
bus.makeTargetServiceIdByResourceUuid(msg, VmInstanceConstant.SERVICE_ID, uuid);
msgs.add(msg);
}
bus.send(msgs, migrateQuantity, new CloudBusListCallBack(trigger) {
@Override
public void run(List<MessageReply> replies) {
for (MessageReply reply : replies) {
if (!reply.isSuccess()) {
MigrateVmMsg msg = msgs.get(replies.indexOf(reply));
logger.warn(String.format("failed to migrate vm[uuid:%s] on host[uuid:%s, name:%s, ip:%s], will try stopping it. %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getName(), self.getManagementIp(), reply.getError()));
vmFailedToMigrate.add(msg.getVmInstanceUuid());
}
}
trigger.next();
}
});
}
});
} else {
// the policy is not to migrate vm
// put all vms in vmFailedToMigrate so the next flow will stop all of them
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.uuid);
q.add(VmInstanceVO_.hostUuid, Op.EQ, self.getUuid());
q.add(VmInstanceVO_.state, Op.NOT_EQ, VmInstanceState.Unknown);
List<String> vmUuids = q.listValue();
vmFailedToMigrate.addAll(vmUuids);
}
flow(new NoRollbackFlow() {
String __name__ = "stop-vm-not-migrated";
@Override
public void run(FlowTrigger trigger, Map data) {
List<String> vmUuids = new ArrayList<String>();
vmUuids.addAll(vmFailedToMigrate);
vmUuids = CollectionUtils.removeDuplicateFromList(vmUuids);
if (vmUuids.isEmpty()) {
trigger.next();
return;
}
stopFailedToMigrateVms(vmUuids, trigger);
}
private void stopFailedToMigrateVms(List<String> vmUuids, final FlowTrigger trigger) {
final List<StopVmInstanceMsg> msgs = new ArrayList<StopVmInstanceMsg>();
for (String vmUuid : vmUuids) {
StopVmInstanceMsg msg = new StopVmInstanceMsg();
msg.setVmInstanceUuid(vmUuid);
bus.makeTargetServiceIdByResourceUuid(msg, VmInstanceConstant.SERVICE_ID, vmUuid);
msgs.add(msg);
}
bus.send(msgs, quantity, new CloudBusListCallBack(trigger) {
@Override
public void run(List<MessageReply> replies) {
StringBuilder sb = new StringBuilder();
boolean success = true;
for (MessageReply r : replies) {
if (!r.isSuccess()) {
StopVmInstanceMsg msg = msgs.get(replies.indexOf(r));
String err = String.format("\nfailed to stop vm[uuid:%s] on host[uuid:%s, name:%s, ip:%s], %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getName(), self.getManagementIp(), r.getError());
sb.append(err);
success = false;
}
}
if (!success) {
logger.warn(sb.toString());
}
if (success || HostGlobalConfig.IGNORE_ERROR_ON_MAINTENANCE_MODE.value(Boolean.class)) {
trigger.next();
} else {
trigger.fail(operr(sb.toString()));
}
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
private void handle(final APIReconnectHostMsg msg) {
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg, new CloudBusCallBack(msg) {
@Override
public void run(MessageReply reply) {
APIReconnectHostEvent evt = new APIReconnectHostEvent(msg.getId());
if (!reply.isSuccess()) {
evt.setError(errf.instantiateErrorCode(HostErrors.UNABLE_TO_RECONNECT_HOST, reply.getError()));
logger.debug(String.format("failed to reconnect host[uuid:%s] because %s", self.getUuid(), reply.getError()));
}else{
self = dbf.reload(self);
evt.setInventory((getSelfInventory()));
}
bus.publish(evt);
}
});
}
private void deleteHostByApiMessage(APIDeleteHostMsg msg) {
final APIDeleteHostEvent evt = new APIDeleteHostEvent(msg.getId());
final String issuer = HostVO.class.getSimpleName();
final List<HostInventory> ctx = Arrays.asList(HostInventory.valueOf(self));
HostInventory hinv = HostInventory.valueOf(self);
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("delete-host-%s", msg.getUuid()));
if (msg.getDeletionMode() == APIDeleteMessage.DeletionMode.Permissive) {
chain.then(new NoRollbackFlow() {
@Override
public void run(final FlowTrigger trigger, Map data) {
casf.asyncCascade(CascadeConstant.DELETION_CHECK_CODE, issuer, ctx, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
}).then(new NoRollbackFlow() {
@Override
public void run(final FlowTrigger trigger, Map data) {
casf.asyncCascade(CascadeConstant.DELETION_DELETE_CODE, issuer, ctx, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
} else {
chain.then(new NoRollbackFlow() {
@Override
public void run(final FlowTrigger trigger, Map data) {
casf.asyncCascade(CascadeConstant.DELETION_FORCE_DELETE_CODE, issuer, ctx, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
}
chain.done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
casf.asyncCascadeFull(CascadeConstant.DELETION_CLEANUP_CODE, issuer, ctx, new NopeCompletion());
bus.publish(evt);
HostDeletedData d = new HostDeletedData();
d.setInventory(HostInventory.valueOf(self));
d.setHostUuid(self.getUuid());
evtf.fire(HostCanonicalEvents.HOST_DELETED_PATH, d);
}
}).error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
evt.setError(errf.instantiateErrorCode(SysErrors.DELETE_RESOURCE_ERROR, errCode));
bus.publish(evt);
}
}).start();
}
private void handle(final APIDeleteHostMsg msg) {
deleteHostByApiMessage(msg);
}
protected HostState changeState(HostStateEvent event) {
HostState currentState = self.getState();
HostState next = currentState.nextState(event);
changeStateHook(currentState, event, next);
extpEmitter.beforeChange(self, event);
self.setState(next);
self = dbf.updateAndRefresh(self);
extpEmitter.afterChange(self, event, currentState);
logger.debug(String.format("Host[%s]'s state changed from %s to %s", self.getUuid(), currentState, self.getState()));
return self.getState();
}
protected void changeStateByApiMessage(final APIChangeHostStateMsg msg, final NoErrorCompletion completion) {
thdf.chainSubmit(new ChainTask(msg, completion) {
@Override
public String getSyncSignature() {
return String.format("change-host-state-%s", self.getUuid());
}
private void done(SyncTaskChain chain) {
completion.done();
chain.next();
}
@Override
public void run(final SyncTaskChain chain) {
final APIChangeHostStateEvent evt = new APIChangeHostStateEvent(msg.getId());
HostStateEvent stateEvent = HostStateEvent.valueOf(msg.getStateEvent());
if (self.getStatus() == HostStatus.Disconnected && stateEvent == HostStateEvent.maintain) {
throw new ApiMessageInterceptionException(operr("cannot change the state of Disconnected host into Maintenance "));
}
stateEvent = stateEvent == HostStateEvent.maintain ? HostStateEvent.preMaintain : stateEvent;
try {
extpEmitter.preChange(self, stateEvent);
} catch (HostException he) {
evt.setError(errf.instantiateErrorCode(SysErrors.CHANGE_RESOURCE_STATE_ERROR, he.getMessage()));
bus.publish(evt);
done(chain);
return;
}
if (HostStateEvent.preMaintain == stateEvent) {
changeState(HostStateEvent.preMaintain);
maintenanceHook(new Completion(msg, chain) {
@Override
public void success() {
changeState(HostStateEvent.maintain);
evt.setInventory(HostInventory.valueOf(self));
bus.publish(evt);
done(chain);
}
@Override
public void fail(ErrorCode errorCode) {
evt.setError(errf.instantiateErrorCode(HostErrors.UNABLE_TO_ENTER_MAINTENANCE_MODE, errorCode.getDetails(), errorCode));
changeState(HostStateEvent.enable);
bus.publish(evt);
done(chain);
}
});
} else {
HostState origState = self.getState();
HostState state = changeState(stateEvent);
if (origState == HostState.Maintenance && state != HostState.Maintenance) {
// host is out of maintenance mode, track and reconnect it.
tracker.trackHost(self.getUuid());
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg);
}
HostInventory inv = HostInventory.valueOf(self);
evt.setInventory(inv);
bus.publish(evt);
done(chain);
}
}
@Override
public String getName() {
return String.format("change-host-state-%s", self.getUuid());
}
});
}
protected void handle(final APIChangeHostStateMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getName() {
return "change-host-state-" + self.getUuid();
}
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
changeStateByApiMessage(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public int getSyncLevel() {
return getHostSyncLevel();
}
});
}
protected void handleLocalMessage(Message msg) {
if (msg instanceof ChangeHostStateMsg) {
handle((ChangeHostStateMsg) msg);
} else if (msg instanceof HostDeletionMsg) {
handle((HostDeletionMsg) msg);
} else if (msg instanceof ConnectHostMsg) {
handle((ConnectHostMsg) msg);
} else if (msg instanceof ReconnectHostMsg) {
handle((ReconnectHostMsg) msg);
} else if (msg instanceof ChangeHostConnectionStateMsg) {
handle((ChangeHostConnectionStateMsg) msg);
} else if (msg instanceof PingHostMsg) {
handle((PingHostMsg) msg);
} else {
HostBaseExtensionFactory ext = hostMgr.getHostBaseExtensionFactory(msg);
if (ext != null) {
Host h = ext.getHost(self);
h.handleMessage(msg);
} else {
bus.dealWithUnknownMessage(msg);
}
}
}
private void handle(final PingHostMsg msg) {
final PingHostReply reply = new PingHostReply();
if (self.getStatus() == HostStatus.Connecting) {
reply.setError(operr("host is connecting"));
bus.reply(msg, reply);
return;
}
pingHook(new Completion(msg) {
@Override
public void success() {
reply.setConnected(true);
reply.setCurrentHostStatus(self.getStatus().toString());
bus.reply(msg, reply);
extpEmitter.hostPingTask(HypervisorType.valueOf(self.getHypervisorType()), getSelfInventory());
}
@Override
public void fail(ErrorCode errorCode) {
reply.setConnected(false);
reply.setCurrentHostStatus(self.getStatus().toString());
reply.setError(errorCode);
reply.setSuccess(true);
Boolean noReconnect = (Boolean) errorCode.getFromOpaque(Opaque.NO_RECONNECT_AFTER_PING_FAILURE.toString());
reply.setNoReconnect(noReconnect != null && noReconnect);
if(!Q.New(HostVO.class).eq(HostVO_.uuid, msg.getHostUuid()).isExists()){
reply.setNoReconnect(true);
bus.reply(msg, reply);
return;
}
changeConnectionState(HostStatusEvent.disconnected);
bus.reply(msg, reply);
}
});
}
private void handle(final HostDeletionMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(SyncTaskChain chain) {
HostInventory hinv = HostInventory.valueOf(self);
extpEmitter.beforeDelete(hinv);
deleteHook();
extpEmitter.afterDelete(hinv);
bus.reply(msg, new HostDeletionReply());
tracker.untrackHost(self.getUuid());
chain.next();
}
@Override
public int getSyncLevel() {
return getHostSyncLevel();
}
@Override
public String getName() {
return String.format("host-deletion-%s", self.getUuid());
}
});
}
private void reconnectHost(final ReconnectHostMsg msg, final NoErrorCompletion completion) {
thdf.chainSubmit(new ChainTask(msg, completion) {
@Override
public String getSyncSignature() {
return String.format("reconnect-host-%s", self.getUuid());
}
private void finish(SyncTaskChain chain) {
chain.next();
completion.done();
}
@Override
public void run(final SyncTaskChain chain) {
checkState();
if (msg.isSkipIfHostConnected() && HostStatus.Connected == self.getStatus()) {
finish(chain);
return;
}
changeConnectionState(HostStatusEvent.disconnected);
ConnectHostMsg connectMsg = new ConnectHostMsg(self.getUuid());
connectMsg.setNewAdd(false);
bus.makeTargetServiceIdByResourceUuid(connectMsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(connectMsg, new CloudBusCallBack(msg, chain, completion) {
@Override
public void run(MessageReply reply) {
ReconnectHostReply r = new ReconnectHostReply();
if (reply.isSuccess()) {
logger.debug(String.format("Successfully reconnect host[uuid:%s]", self.getUuid()));
} else {
r.setError(errf.instantiateErrorCode(HostErrors.UNABLE_TO_RECONNECT_HOST, reply.getError()));
logger.debug(String.format("Failed to reconnect host[uuid:%s] because %s",
self.getUuid(), reply.getError()));
}
bus.reply(msg, r);
}
});
// no need to block the queue, because the ConnectHostMsg will be queued as well
finish(chain);
}
@Override
public String getName() {
return getSyncSignature();
}
});
}
private void handle(final ReconnectHostMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getName() {
return "reconnect-host-" + self.getUuid();
}
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
reconnectHost(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void handle(final ChangeHostConnectionStateMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getName() {
return "change-host-connection-state-" + self.getUuid();
}
private boolean reestablishConnection() {
try {
extpEmitter.connectionReestablished(HypervisorType.valueOf(self.getHypervisorType()), getSelfInventory());
} catch (HostException e) {
logger.warn(String.format("unable to reestablish connection to kvm host[uuid:%s, ip:%s], %s",
self.getUuid(), self.getManagementIp(), e.getMessage()), e);
return false;
}
return true;
}
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(SyncTaskChain chain) {
HostStatusEvent cevt = HostStatusEvent.valueOf(msg.getConnectionStateEvent());
HostStatus next = self.getStatus().nextStatus(cevt);
if (self.getStatus() == HostStatus.Disconnected && next == HostStatus.Connected) {
if (!reestablishConnection()) {
cevt = HostStatusEvent.disconnected;
}
}
changeConnectionState(cevt);
bus.reply(msg, new ChangeHostConnectionStateReply());
chain.next();
}
@Override
public int getSyncLevel() {
return getHostSyncLevel();
}
});
}
protected HostInventory getSelfInventory() {
return HostInventory.valueOf(self);
}
protected boolean changeConnectionState(final HostStatusEvent event) {
if(!Q.New(HostVO.class).eq(HostVO_.uuid, self.getUuid()).isExists()){
throw new CloudRuntimeException(String.format("change host connection state fail, can not find the host[%s]", self.getUuid()));
}
HostStatus before = self.getStatus();
HostStatus next = before.nextStatus(event);
if (before == next) {
return false;
}
self.setStatus(next);
self = dbf.updateAndRefresh(self);
logger.debug(String.format("Host %s [uuid:%s] changed connection state from %s to %s",
self.getName(), self.getUuid(), before, next));
HostStatusChangedData data = new HostStatusChangedData();
data.setHostUuid(self.getUuid());
data.setNewStatus(next.toString());
data.setOldStatus(before.toString());
data.setInventory(HostInventory.valueOf(self));
evtf.fire(HostCanonicalEvents.HOST_STATUS_CHANGED_PATH, data);
CollectionUtils.safeForEach(pluginRgty.getExtensionList(AfterChangeHostStatusExtensionPoint.class),
new ForEachFunction<AfterChangeHostStatusExtensionPoint>() {
@Override
public void run(AfterChangeHostStatusExtensionPoint arg) {
arg.afterChangeHostStatus(self.getUuid(), before, next);
}
});
return true;
}
private void handle(final ConnectHostMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return String.format("connect-host-%s", self.getUuid());
}
@Override
public void run(SyncTaskChain chain) {
checkState();
final ConnectHostReply reply = new ConnectHostReply();
final FlowChain flowChain = FlowChainBuilder.newShareFlowChain();
flowChain.setName(String.format("connect-host-%s", self.getUuid()));
flowChain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "connect-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
changeConnectionState(HostStatusEvent.connecting);
connectHook(ConnectHostInfo.fromConnectHostMsg(msg), new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "call-post-connect-extensions";
@Override
public void run(FlowTrigger trigger, Map data) {
FlowChain postConnectChain = FlowChainBuilder.newSimpleFlowChain();
postConnectChain.allowEmptyFlow();
self = dbf.reload(self);
HostInventory inv = getSelfInventory();
for (PostHostConnectExtensionPoint p : pluginRgty.getExtensionList(PostHostConnectExtensionPoint.class)) {
postConnectChain.then(p.createPostHostConnectFlow(inv));
}
postConnectChain.done(new FlowDoneHandler(trigger) {
@Override
public void handle(Map data) {
trigger.next();
}
}).error(new FlowErrorHandler(trigger) {
@Override
public void handle(ErrorCode errCode, Map data) {
trigger.fail(errCode);
}
}).start();
}
});
flow(new NoRollbackFlow() {
String __name__ = "recalculate-host-capacity";
@Override
public void run(FlowTrigger trigger, Map data) {
RecalculateHostCapacityMsg msg = new RecalculateHostCapacityMsg();
msg.setHostUuid(self.getUuid());
bus.makeLocalServiceId(msg, HostAllocatorConstant.SERVICE_ID);
bus.send(msg);
trigger.next();
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
changeConnectionState(HostStatusEvent.connected);
tracker.trackHost(self.getUuid());
CollectionUtils.safeForEach(pluginRgty.getExtensionList(HostAfterConnectedExtensionPoint.class),
new ForEachFunction<HostAfterConnectedExtensionPoint>() {
@Override
public void run(HostAfterConnectedExtensionPoint ext) {
ext.afterHostConnected(getSelfInventory());
}
});
bus.reply(msg, reply);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
changeConnectionState(HostStatusEvent.disconnected);
if (!msg.isNewAdd()) {
tracker.trackHost(self.getUuid());
}
reply.setError(errCode);
bus.reply(msg, reply);
}
});
Finally(new FlowFinallyHandler(msg) {
@Override
public void Finally() {
chain.next();
}
});
}
}).start();
}
@Override
public String getName() {
return "connect-host";
}
});
}
private void changeStateByLocalMessage(final ChangeHostStateMsg msg, final NoErrorCompletion completion) {
thdf.chainSubmit(new ChainTask(msg, completion) {
@Override
public String getSyncSignature() {
return String.format("change-host-state-%s", self.getUuid());
}
private void done(SyncTaskChain chain) {
completion.done();
chain.next();
}
@Override
public void run(SyncTaskChain chain) {
ChangeHostStateReply reply = new ChangeHostStateReply();
if (self.getState() != HostState.Enabled && self.getState() != HostState.Disabled) {
done(chain);
return;
}
HostStateEvent stateEvent = HostStateEvent.valueOf(msg.getStateEvent());
changeState(stateEvent);
HostInventory inv = HostInventory.valueOf(self);
reply.setInventory(inv);
bus.reply(msg, reply);
done(chain);
}
@Override
public String getName() {
return String.format("change-host-state-%s", self.getUuid());
}
});
}
private void handle(final ChangeHostStateMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getName() {
return "change-host-state-" + self.getUuid();
}
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
changeStateByLocalMessage(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public int getSyncLevel() {
return getHostSyncLevel();
}
});
}
@Override
@MessageSafe
public void handleMessage(Message msg) {
if (msg instanceof APIMessage) {
handleApiMessage((APIMessage) msg);
} else {
handleLocalMessage(msg);
}
}
}
| |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.validation;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.hisp.dhis.expression.Operator.equal_to;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import org.hisp.dhis.TransactionalIntegrationTest;
import org.hisp.dhis.category.Category;
import org.hisp.dhis.category.CategoryCombo;
import org.hisp.dhis.category.CategoryOption;
import org.hisp.dhis.category.CategoryOptionCombo;
import org.hisp.dhis.category.CategoryOptionGroup;
import org.hisp.dhis.category.CategoryOptionGroupSet;
import org.hisp.dhis.category.CategoryService;
import org.hisp.dhis.common.BaseIdentifiableObject;
import org.hisp.dhis.common.CodeGenerator;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.expression.Expression;
import org.hisp.dhis.mock.MockCurrentUserService;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.period.MonthlyPeriodType;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodService;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.user.CurrentUserService;
import org.hisp.dhis.user.CurrentUserServiceTarget;
import org.hisp.dhis.user.User;
import org.hisp.dhis.user.UserAuthorityGroup;
import org.hisp.dhis.user.UserCredentials;
import org.hisp.dhis.user.UserGroup;
import org.hisp.dhis.user.UserGroupAccessService;
import org.hisp.dhis.user.UserGroupService;
import org.hisp.dhis.user.UserService;
import org.hisp.dhis.user.sharing.UserGroupAccess;
import org.hisp.dhis.validation.comparator.ValidationResultQuery;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* @author Jim Grace
*/
class ValidationResultStoreTest extends TransactionalIntegrationTest
{
private static final String ACCESS_NONE = "--------";
private static final String ACCESS_READ = "r-------";
@Autowired
private ValidationRuleStore validationRuleStore;
@Autowired
private ValidationResultStore validationResultStore;
@Autowired
private PeriodService periodService;
@Autowired
private CategoryService categoryService;
@Autowired
private OrganisationUnitService organisationUnitService;
@Autowired
protected UserGroupAccessService userGroupAccessService;
@Autowired
protected UserGroupService userGroupService;
@Autowired
protected IdentifiableObjectManager identifiableObjectManager;
@Autowired
private UserService userService;
@Autowired
private CurrentUserService currentUserService;
// -------------------------------------------------------------------------
// Supporting data
// -------------------------------------------------------------------------
private Expression expressionA;
private Expression expressionB;
private ValidationRule validationRuleA;
private ValidationRule validationRuleB;
private ValidationResult validationResultAA;
private ValidationResult validationResultAB;
private ValidationResult validationResultAC;
private ValidationResult validationResultBA;
private ValidationResult validationResultBB;
private ValidationResult validationResultBC;
private ValidationResult validationResultCA;
private Period periodA;
private Period periodB;
private OrganisationUnit sourceA;
private OrganisationUnit sourceB;
private OrganisationUnit sourceC;
private CurrentUserService superUserService;
private CurrentUserService userAService;
private CurrentUserService userBService;
private CurrentUserService userCService;
private CurrentUserService userDService;
private User userZ;
private CategoryOption optionA;
private CategoryOption optionB;
private Category categoryA;
private CategoryCombo categoryComboA;
private CategoryOptionCombo optionComboA;
private CategoryOptionCombo optionComboB;
private CategoryOptionCombo optionComboC;
private CategoryOptionGroup optionGroupA;
private CategoryOptionGroup optionGroupB;
private CategoryOptionGroupSet optionGroupSetB;
// -------------------------------------------------------------------------
// Set up/tear down helper methods
// -------------------------------------------------------------------------
private CurrentUserService getMockCurrentUserService( String userName, boolean superUserFlag,
OrganisationUnit orgUnit, String... auths )
{
CurrentUserService mockCurrentUserService = new MockCurrentUserService( superUserFlag,
Sets.newHashSet( orgUnit ), Sets.newHashSet( orgUnit ), auths );
User user = mockCurrentUserService.getCurrentUser();
user.setFirstName( "Test" );
user.setSurname( userName );
UserCredentials credentials = user.getUserCredentials();
credentials.setUsername( userName );
for ( UserAuthorityGroup role : credentials.getUserAuthorityGroups() )
{
role.setName( CodeGenerator.generateUid() );
userService.addUserAuthorityGroup( role );
}
userService.addUserCredentials( credentials );
userService.addUser( user );
return mockCurrentUserService;
}
private void setPrivateAccess( BaseIdentifiableObject object, UserGroup... userGroups )
{
object.getSharing().setOwner( userZ );
object.getSharing().setPublicAccess( ACCESS_NONE );
for ( UserGroup group : userGroups )
{
UserGroupAccess userGroupAccess = new UserGroupAccess();
userGroupAccess.setAccess( ACCESS_READ );
userGroupAccess.setUserGroup( group );
object.getSharing().addUserGroupAccess( userGroupAccess );
}
identifiableObjectManager.updateNoAcl( object );
}
// -------------------------------------------------------------------------
// Set up/tear down
// -------------------------------------------------------------------------
@Override
public boolean emptyDatabaseAfterTest()
{
return true;
}
@Override
public void setUpTest()
throws Exception
{
// ---------------------------------------------------------------------
// Add supporting data
// ---------------------------------------------------------------------
PeriodType periodType = PeriodType.getPeriodTypeByName( "Monthly" );
periodA = createPeriod( new MonthlyPeriodType(), getDate( 2017, 1, 1 ), getDate( 2017, 1, 31 ) );
periodB = createPeriod( new MonthlyPeriodType(), getDate( 2017, 2, 1 ), getDate( 2017, 2, 28 ) );
periodService.addPeriod( periodA );
periodService.addPeriod( periodB );
sourceA = createOrganisationUnit( 'A' );
sourceB = createOrganisationUnit( 'B', sourceA );
sourceC = createOrganisationUnit( 'C' );
organisationUnitService.addOrganisationUnit( sourceA );
organisationUnitService.addOrganisationUnit( sourceB );
organisationUnitService.addOrganisationUnit( sourceC );
superUserService = getMockCurrentUserService( "SuperUser", true, sourceA, UserAuthorityGroup.AUTHORITY_ALL );
userAService = getMockCurrentUserService( "UserA", false, sourceA );
userBService = getMockCurrentUserService( "UserB", false, sourceB );
userCService = getMockCurrentUserService( "UserC", false, sourceB );
userDService = getMockCurrentUserService( "UserD", false, sourceB );
userZ = createUser( 'Z' );
userService.addUser( userZ );
UserGroup userGroupC = createUserGroup( 'A', Sets.newHashSet( userCService.getCurrentUser() ) );
UserGroup userGroupD = createUserGroup( 'B', Sets.newHashSet( userDService.getCurrentUser() ) );
userGroupService.addUserGroup( userGroupC );
userGroupService.addUserGroup( userGroupD );
userCService.getCurrentUser().getGroups().add( userGroupC );
userService.updateUser( userCService.getCurrentUser() );
userDService.getCurrentUser().getGroups().add( userGroupD );
userService.updateUser( userDService.getCurrentUser() );
optionA = new CategoryOption( "CategoryOptionA" );
optionB = new CategoryOption( "CategoryOptionB" );
categoryService.addCategoryOption( optionA );
categoryService.addCategoryOption( optionB );
categoryA = createCategory( 'A', optionA, optionB );
categoryService.addCategory( categoryA );
categoryComboA = createCategoryCombo( 'A', categoryA );
categoryService.addCategoryCombo( categoryComboA );
optionComboA = createCategoryOptionCombo( categoryComboA, optionA );
optionComboB = createCategoryOptionCombo( categoryComboA, optionB );
optionComboC = createCategoryOptionCombo( categoryComboA, optionA, optionB );
categoryService.addCategoryOptionCombo( optionComboA );
categoryService.addCategoryOptionCombo( optionComboB );
categoryService.addCategoryOptionCombo( optionComboC );
optionGroupA = createCategoryOptionGroup( 'A', optionA );
optionGroupB = createCategoryOptionGroup( 'B', optionB );
categoryService.saveCategoryOptionGroup( optionGroupA );
categoryService.saveCategoryOptionGroup( optionGroupB );
optionGroupSetB = new CategoryOptionGroupSet( "OptionGroupSetB" );
categoryService.saveCategoryOptionGroupSet( optionGroupSetB );
optionGroupSetB.addCategoryOptionGroup( optionGroupA );
optionGroupSetB.addCategoryOptionGroup( optionGroupB );
optionGroupA.getGroupSets().add( optionGroupSetB );
optionGroupB.getGroupSets().add( optionGroupSetB );
setPrivateAccess( optionA, userGroupC );
setPrivateAccess( optionB );
setPrivateAccess( optionGroupA );
setPrivateAccess( optionGroupB, userGroupD );
categoryService.updateCategoryOptionGroupSet( optionGroupSetB );
categoryService.updateCategoryOptionGroup( optionGroupA );
categoryService.updateCategoryOptionGroup( optionGroupB );
userCService.getCurrentUser().getUserCredentials().getCatDimensionConstraints().add( categoryA );
userDService.getCurrentUser().getUserCredentials().getCogsDimensionConstraints().add( optionGroupSetB );
expressionA = new Expression( "expressionA", "descriptionA" );
expressionB = new Expression( "expressionB", "descriptionB" );
validationRuleA = createValidationRule( 'A', equal_to, expressionA, expressionB, periodType );
validationRuleB = createValidationRule( 'B', equal_to, expressionB, expressionA, periodType );
validationRuleStore.save( validationRuleA );
validationRuleStore.save( validationRuleB );
validationResultAA = new ValidationResult( validationRuleA, periodA, sourceA, optionComboA, 1.0, 2.0, 3 );
validationResultAB = new ValidationResult( validationRuleA, periodA, sourceA, optionComboB, 1.0, 2.0, 3 );
validationResultAC = new ValidationResult( validationRuleA, periodA, sourceA, optionComboC, 1.0, 2.0, 3 );
validationResultBA = new ValidationResult( validationRuleB, periodB, sourceB, optionComboA, 1.0, 2.0, 3 );
validationResultBB = new ValidationResult( validationRuleB, periodB, sourceB, optionComboB, 1.0, 2.0, 3 );
validationResultBC = new ValidationResult( validationRuleB, periodB, sourceB, optionComboC, 1.0, 2.0, 3 );
validationResultCA = new ValidationResult( validationRuleB, periodB, sourceC, optionComboA, 1.0, 2.0, 3 );
validationResultAB.setNotificationSent( true );
}
@Override
public void tearDownTest()
{
setDependency( CurrentUserServiceTarget.class, CurrentUserServiceTarget::setCurrentUserService,
currentUserService, validationResultStore );
}
// -------------------------------------------------------------------------
// Test helper methods
// -------------------------------------------------------------------------
private void setMockUserService( CurrentUserService mockUserService )
{
setDependency( CurrentUserServiceTarget.class, CurrentUserServiceTarget::setCurrentUserService, mockUserService,
validationResultStore );
}
// -------------------------------------------------------------------------
// Test ValidationResultStore
// -------------------------------------------------------------------------
@Test
void testSaveValidationResult()
throws Exception
{
Date beforeSave = new Date();
validationResultStore.save( validationResultAA );
Date afterSave = new Date();
long id = validationResultAA.getId();
ValidationResult validationResult = validationResultStore.get( id );
assertNotNull( validationResult );
assertEquals( validationResult.getValidationRule(), validationRuleA );
assertEquals( validationResult.getPeriod(), periodA );
assertEquals( validationResult.getOrganisationUnit(), sourceA );
assertEquals( validationResult.getAttributeOptionCombo(), optionComboA );
assertEquals( validationResult.getLeftsideValue(), (Double) 1.0 );
assertEquals( validationResult.getRightsideValue(), (Double) 2.0 );
assertEquals( validationResult.getDayInPeriod(), 3L );
assertTrue( validationResult.getCreated().getTime() >= beforeSave.getTime() );
assertTrue( validationResult.getCreated().getTime() <= afterSave.getTime() );
}
@Test
void testDeleteValidationResult()
throws Exception
{
validationResultStore.save( validationResultAA );
long id = validationResultAA.getId();
validationResultStore.delete( validationResultAA );
assertNull( validationResultStore.get( id ) );
}
@Test
void testGetAllUnreportedValidationResults()
throws Exception
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
// Superuser can see all unreported results.
setMockUserService( superUserService );
assertEqualSets( asList( validationResultAA, validationResultAC, validationResultBA, validationResultBB,
validationResultBC ), validationResultStore.getAllUnreportedValidationResults() );
// User A can see all unreported results from sourceA or its children.
setMockUserService( userAService );
assertEqualSets( asList( validationResultAA, validationResultAC, validationResultBA, validationResultBB,
validationResultBC ), validationResultStore.getAllUnreportedValidationResults() );
// User B can see all unreported results from sourceB.
setMockUserService( userBService );
assertEqualSets( asList( validationResultBA, validationResultBB, validationResultBC ),
validationResultStore.getAllUnreportedValidationResults() );
// User C can see only optionA from sourceB.
setMockUserService( userCService );
assertEqualSets( singletonList( validationResultBA ),
validationResultStore.getAllUnreportedValidationResults() );
// User D can see only optionB from sourceB.
setMockUserService( userDService );
assertEqualSets( singletonList( validationResultBB ),
validationResultStore.getAllUnreportedValidationResults() );
}
@Test
void testGetById()
throws Exception
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
setMockUserService( superUserService );
assertEquals( validationResultAA, validationResultStore.getById( validationResultAA.getId() ) );
assertEquals( validationResultAB, validationResultStore.getById( validationResultAB.getId() ) );
assertEquals( validationResultAC, validationResultStore.getById( validationResultAC.getId() ) );
assertEquals( validationResultBA, validationResultStore.getById( validationResultBA.getId() ) );
assertEquals( validationResultBB, validationResultStore.getById( validationResultBB.getId() ) );
assertEquals( validationResultBC, validationResultStore.getById( validationResultBC.getId() ) );
setMockUserService( userAService );
assertEquals( validationResultAA, validationResultStore.getById( validationResultAA.getId() ) );
assertEquals( validationResultAB, validationResultStore.getById( validationResultAB.getId() ) );
assertEquals( validationResultAC, validationResultStore.getById( validationResultAC.getId() ) );
assertEquals( validationResultBA, validationResultStore.getById( validationResultBA.getId() ) );
assertEquals( validationResultBB, validationResultStore.getById( validationResultBB.getId() ) );
assertEquals( validationResultBC, validationResultStore.getById( validationResultBC.getId() ) );
setMockUserService( userBService );
assertNull( validationResultStore.getById( validationResultAA.getId() ) );
assertNull( validationResultStore.getById( validationResultAB.getId() ) );
assertNull( validationResultStore.getById( validationResultAC.getId() ) );
assertEquals( validationResultBA, validationResultStore.getById( validationResultBA.getId() ) );
assertEquals( validationResultBB, validationResultStore.getById( validationResultBB.getId() ) );
assertEquals( validationResultBC, validationResultStore.getById( validationResultBC.getId() ) );
setMockUserService( userCService );
assertNull( validationResultStore.getById( validationResultAA.getId() ) );
assertNull( validationResultStore.getById( validationResultAB.getId() ) );
assertNull( validationResultStore.getById( validationResultAC.getId() ) );
assertEquals( validationResultBA, validationResultStore.getById( validationResultBA.getId() ) );
assertNull( validationResultStore.getById( validationResultBB.getId() ) );
assertNull( validationResultStore.getById( validationResultBC.getId() ) );
setMockUserService( userDService );
assertNull( validationResultStore.getById( validationResultAA.getId() ) );
assertNull( validationResultStore.getById( validationResultAB.getId() ) );
assertNull( validationResultStore.getById( validationResultAC.getId() ) );
assertNull( validationResultStore.getById( validationResultBA.getId() ) );
assertEquals( validationResultBB, validationResultStore.getById( validationResultBB.getId() ) );
assertNull( validationResultStore.getById( validationResultBC.getId() ) );
}
@Test
void testQuery()
throws Exception
{
List<ValidationResult> expected = asList( validationResultAA, validationResultAB, validationResultAC,
validationResultBA, validationResultBB, validationResultBC );
save( expected );
ValidationResultQuery query = new ValidationResultQuery();
setMockUserService( superUserService );
assertEqualSets( expected, validationResultStore.query( query ) );
setMockUserService( userAService );
assertEqualSets( expected, validationResultStore.query( query ) );
setMockUserService( userBService );
assertEqualSets( asList( validationResultBA, validationResultBB, validationResultBC ),
validationResultStore.query( query ) );
setMockUserService( userCService );
assertEqualSets( singletonList( validationResultBA ), validationResultStore.query( query ) );
setMockUserService( userDService );
assertEqualSets( singletonList( validationResultBB ), validationResultStore.query( query ) );
}
@Test
void testQueryWithOrgUnitFilter()
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
// test with superuser so user adds no extra restrictions
setMockUserService( superUserService );
ValidationResultQuery query = new ValidationResultQuery();
// filter on A gives results for A
query.setOu( singletonList( sourceA.getUid() ) );
assertEqualSets( asList( validationResultAA, validationResultAB, validationResultAC ),
validationResultStore.query( query ) );
// filter on B gives results for B
query.setOu( singletonList( sourceB.getUid() ) );
assertEqualSets( asList( validationResultBA, validationResultBB, validationResultBC ),
validationResultStore.query( query ) );
// no match case
query.setOu( singletonList( sourceC.getUid() ) );
assertEqualSets( emptyList(), validationResultStore.query( query ) );
// case with multiple units
query.setOu( asList( sourceB.getUid(), sourceA.getUid() ) );
assertEqualSets( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ), validationResultStore.query( query ) );
// now we restrict user to only be able to see Bs
setMockUserService( userBService );
// so filtering on As should not give any result
query.setOu( singletonList( sourceA.getUid() ) );
assertEqualSets( emptyList(), validationResultStore.query( query ) );
}
@Test
void testQueryWithValidationRuleFilter()
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
// test with superuser so user adds no extra restrictions
setMockUserService( superUserService );
ValidationResultQuery query = new ValidationResultQuery();
// filter on A gives results for A
query.setVr( singletonList( validationRuleA.getUid() ) );
assertEqualSets( asList( validationResultAA, validationResultAB, validationResultAC ),
validationResultStore.query( query ) );
// filter on B gives results for B
query.setVr( singletonList( validationRuleB.getUid() ) );
assertEqualSets( asList( validationResultBA, validationResultBB, validationResultBC ),
validationResultStore.query( query ) );
// case with multiple units
query.setVr( asList( validationRuleA.getUid(), validationRuleB.getUid() ) );
assertEqualSets( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ), validationResultStore.query( query ) );
// now we restrict user to only be able to see Bs
setMockUserService( userBService );
// so filtering on As should not give any result
query.setVr( singletonList( validationRuleA.getUid() ) );
assertEqualSets( emptyList(), validationResultStore.query( query ) );
}
@Test
void testQueryWithIsoPeriodFilter()
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
// test with superuser so user adds no extra restrictions
setMockUserService( superUserService );
ValidationResultQuery query = new ValidationResultQuery();
// periodA is Jan 2017, periodB is Feb 2017
// monthly ISO pattern: YYYY-MM
query.setPe( singletonList( "2017-01" ) );
assertEqualSets( asList( validationResultAA, validationResultAB, validationResultAC ),
validationResultStore.query( query ) );
query.setPe( asList( "2017-01", "2017-02" ) );
assertEqualSets( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ), validationResultStore.query( query ) );
// QUARTERLY
query.setPe( singletonList( "2017Q1" ) );
assertEqualSets( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ), validationResultStore.query( query ) );
// YEARLY
query.setPe( singletonList( "2017" ) );
assertEqualSets( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ), validationResultStore.query( query ) );
// WEEKLY
query.setPe( singletonList( "2017W3" ) );
assertEqualSets( asList( validationResultAA, validationResultAB, validationResultAC ),
validationResultStore.query( query ) );
}
@Test
void testQueryWithCreatedDateFilter()
{
Date beforeA = new Date();
wait1ms();
save( asList( validationResultAA, validationResultAB, validationResultAC ) );
wait1ms();
Date beforeB = new Date();
wait1ms();
save( asList( validationResultBA, validationResultBB, validationResultBC ) );
// B and onwards gives Bs
ValidationResultQuery query = new ValidationResultQuery();
query.setCreatedDate( beforeB );
assertEqualSets( asList( validationResultBA, validationResultBB, validationResultBC ),
validationResultStore.query( query ) );
// A and onwards gives As and Bs
query.setCreatedDate( beforeA );
assertEqualSets( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ), validationResultStore.query( query ) );
// after A and B onwards => none
wait1ms();
query.setCreatedDate( new Date() );
assertEqualSets( emptyList(), validationResultStore.query( query ) );
}
@Test
void testQueryWithMultipleFilters()
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
// test with superuser so user adds no extra restrictions
setMockUserService( superUserService );
// filter on A gives results for A
ValidationResultQuery query = new ValidationResultQuery();
query.setPe( singletonList( "2017" ) );
query.setVr( singletonList( validationRuleA.getUid() ) );
query.setOu( singletonList( sourceA.getUid() ) );
assertEqualSets( asList( validationResultAA, validationResultAB, validationResultAC ),
validationResultStore.query( query ) );
// filter mutual exclusive gives empty result
query.setVr( singletonList( validationRuleA.getUid() ) );
query.setOu( singletonList( sourceB.getUid() ) );
assertEqualSets( emptyList(), validationResultStore.query( query ) );
}
@Test
void testCount()
throws Exception
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
ValidationResultQuery query = new ValidationResultQuery();
setMockUserService( superUserService );
assertEquals( 6, validationResultStore.count( query ) );
setMockUserService( userAService );
assertEquals( 6, validationResultStore.count( query ) );
setMockUserService( userBService );
assertEquals( 3, validationResultStore.count( query ) );
setMockUserService( userCService );
assertEquals( 1, validationResultStore.count( query ) );
setMockUserService( userDService );
assertEquals( 1, validationResultStore.count( query ) );
}
/**
* The exact logic of the filters is tested in depth for the query method
* which shares the filter logic with count. This test should just make sure
* that the count method used with filters has no general issues.
*/
@Test
void testCountWithFilters()
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
ValidationResultQuery query = new ValidationResultQuery();
// org unit filter
query.setOu( singletonList( sourceA.getUid() ) );
assertEquals( 3, validationResultStore.count( query ) );
// period filter
query.setVr( singletonList( validationRuleA.getUid() ) );
assertEquals( 3, validationResultStore.count( query ) );
// period filter
query.setPe( singletonList( "2017-01" ) );
assertEquals( 3, validationResultStore.count( query ) );
}
@Test
void testGetValidationResults()
throws Exception
{
save( asList( validationResultAA, validationResultBA, validationResultCA ) );
List<ValidationRule> rulesA = Lists.newArrayList( validationRuleA );
List<ValidationRule> rulesAB = Lists.newArrayList( validationRuleA, validationRuleB );
List<Period> periodsB = Lists.newArrayList( periodB );
List<Period> periodsAB = Lists.newArrayList( periodA, periodB );
assertEqualSets( singletonList( validationResultAA ),
validationResultStore.getValidationResults( null, false, rulesA, periodsAB ) );
assertEqualSets( asList( validationResultBA, validationResultCA ),
validationResultStore.getValidationResults( null, true, rulesAB, periodsB ) );
assertEqualSets( asList( validationResultAA, validationResultBA, validationResultCA ),
validationResultStore.getValidationResults( null, true, rulesAB, periodsAB ) );
assertEqualSets( asList( validationResultAA, validationResultBA ),
validationResultStore.getValidationResults( sourceA, true, rulesAB, periodsAB ) );
assertEqualSets( singletonList( validationResultAA ),
validationResultStore.getValidationResults( sourceA, false, rulesAB, periodsAB ) );
assertEqualSets( singletonList( validationResultBA ),
validationResultStore.getValidationResults( sourceB, false, rulesAB, periodsAB ) );
}
@Test
void testDeleteObject()
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
validationResultStore.delete( validationResultAA );
assertEqualSets( asList( validationResultAB, validationResultAC, validationResultBA, validationResultBB,
validationResultBC ), validationResultStore.query( new ValidationResultQuery() ) );
}
@Test
void testDeleteByRequestWithOrganisationUnit()
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
ValidationResultsDeletionRequest request = new ValidationResultsDeletionRequest();
request.setOu( singletonList( sourceA.getUid() ) );
validationResultStore.delete( request );
assertEqualSets( asList( validationResultBA, validationResultBB, validationResultBC ),
validationResultStore.query( new ValidationResultQuery() ) );
}
@Test
void testDeleteByRequestWithValidationRule()
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
ValidationResultsDeletionRequest request = new ValidationResultsDeletionRequest();
request.setVr( singletonList( validationRuleA.getUid() ) );
validationResultStore.delete( request );
assertEqualSets( asList( validationResultBA, validationResultBB, validationResultBC ),
validationResultStore.query( new ValidationResultQuery() ) );
}
@Test
void testDeleteByRequestWithPeriod()
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
ValidationResultsDeletionRequest request = new ValidationResultsDeletionRequest();
request.setPe( periodA.getUid() );
validationResultStore.delete( request );
assertEqualSets( asList( validationResultBA, validationResultBB, validationResultBC ),
validationResultStore.query( new ValidationResultQuery() ) );
}
@Test
void testDeleteByRequestWithCreatedPeriod()
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
ValidationResultsDeletionRequest request = new ValidationResultsDeletionRequest();
request.setCreated( "" + LocalDate.now().getYear() );
validationResultStore.delete( request );
assertEqualSets( emptyList(), validationResultStore.query( new ValidationResultQuery() ) );
}
@Test
void testDeleteByRequestWithNotificationSent()
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
ValidationResultsDeletionRequest request = new ValidationResultsDeletionRequest();
// AB is saved with true, others
request.setNotificationSent( true );
// with false
validationResultStore.delete( request );
assertEqualSets( asList( validationResultAA, validationResultAC, validationResultBA, validationResultBB,
validationResultBC ), validationResultStore.query( new ValidationResultQuery() ) );
}
@Test
void testDeleteByRequestWithMultipleCriteria()
{
save( asList( validationResultAA, validationResultAB, validationResultAC, validationResultBA,
validationResultBB, validationResultBC ) );
ValidationResultsDeletionRequest request = new ValidationResultsDeletionRequest();
request.setOu( singletonList( sourceA.getUid() ) );
request.setVr( singletonList( validationRuleA.getUid() ) );
request.setPe( periodA.getUid() );
request.setNotificationSent( true );
validationResultStore.delete( request );
// Ou, Vr and Pe match all As but notificationSent matches only AB
assertEqualSets( asList( validationResultAA, validationResultAC, validationResultBA, validationResultBB,
validationResultBC ), validationResultStore.query( new ValidationResultQuery() ) );
}
private void save( Iterable<ValidationResult> results )
{
for ( ValidationResult r : results )
validationResultStore.save( r );
}
private static <T> void assertEqualSets( Collection<T> expected, Collection<T> actual )
{
assertEquals( expected.size(), actual.size() );
if ( expected.size() == 1 )
{
assertEquals( expected, actual );
}
else
{
assertEquals( new HashSet<>( expected ), new HashSet<>( actual ) );
}
}
private void wait1ms()
{
long now = System.currentTimeMillis();
while ( now >= System.currentTimeMillis() ) // busy wait 1 ms
;
}
}
| |
package org.sagebionetworks.repo.model.dbo.statistics;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.YearMonth;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.sagebionetworks.repo.model.dbo.statistics.StatisticsMonthlyStatusDAO;
import org.sagebionetworks.repo.model.statistics.StatisticsObjectType;
import org.sagebionetworks.repo.model.statistics.StatisticsStatus;
import org.sagebionetworks.repo.model.statistics.monthly.StatisticsMonthlyStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = { "classpath:jdomodels-test-context.xml" })
public class StatisticsMonthlyStatusDAOTest {
private static final StatisticsObjectType OBJECT_TYPE = StatisticsObjectType.PROJECT;
@Autowired
private StatisticsMonthlyStatusDAO dao;
@BeforeEach
public void before() {
dao.clear();
}
@AfterEach
public void after() {
dao.clear();
}
@Test
public void testSetOnCreate() {
int year = 2019;
int month = 8;
YearMonth yearMonth = YearMonth.of(year, month);
// Makes sure that it does not exist
assertFalse(dao.getStatus(OBJECT_TYPE, yearMonth).isPresent());
// Call under test
StatisticsMonthlyStatus status = dao.setAvailable(OBJECT_TYPE, yearMonth);
assertEquals(yearMonth, status.getMonth());
assertEquals(StatisticsStatus.AVAILABLE, status.getStatus());
}
@Test
public void testSetOnUpdate() {
int year = 2019;
int month = 8;
YearMonth yearMonth = YearMonth.of(year, month);
// First set a status
dao.setProcessing(OBJECT_TYPE, yearMonth);
// Makes sure that it does exist
Optional<StatisticsMonthlyStatus> getStatusResult = dao.getStatus(OBJECT_TYPE, yearMonth);
assertTrue(getStatusResult.isPresent());
StatisticsMonthlyStatus status = getStatusResult.get();
assertEquals(StatisticsStatus.PROCESSING, status.getStatus());
// Call under test
StatisticsMonthlyStatus updated = dao.setAvailable(OBJECT_TYPE, yearMonth);
assertEquals(yearMonth, updated.getMonth());
assertEquals(StatisticsStatus.AVAILABLE, updated.getStatus());
}
@Test
public void testSetFailedWithEmptyType() {
assertThrows(IllegalArgumentException.class, () -> {
YearMonth yearMonth = YearMonth.of(2019, 8);
// Call under test
dao.setProcessingFailed(null, yearMonth, "Some error", "Some error details");
});
}
@Test
public void testSetFailedWithEmptyMonth() {
assertThrows(IllegalArgumentException.class, () -> {
YearMonth yearMonth = null;
// Call under test
dao.setProcessingFailed(OBJECT_TYPE, yearMonth, "Some error", "Some error details");
});
}
@Test
public void testSetAvailableWithEmptyType() {
assertThrows(IllegalArgumentException.class, () -> {
YearMonth yearMonth = YearMonth.of(2019, 8);
// Call under test
dao.setAvailable(null, yearMonth);
});
}
@Test
public void testSetAvailableWithEmptyMonth() {
assertThrows(IllegalArgumentException.class, () -> {
YearMonth yearMonth = null;
// Call under test
dao.setAvailable(OBJECT_TYPE, yearMonth);
});
}
@Test
public void testSetProcessingWithEmptyType() {
assertThrows(IllegalArgumentException.class, () -> {
YearMonth yearMonth = YearMonth.of(2019, 8);
// Call under test
dao.setProcessing(null, yearMonth);
});
}
@Test
public void testSetProcessingWithEmptyMonth() {
assertThrows(IllegalArgumentException.class, () -> {
YearMonth yearMonth = null;
// Call under test
dao.setProcessing(OBJECT_TYPE, yearMonth);
});
}
@Test
public void testSetAvailableTimestamp() {
int year = 2019;
int month = 8;
YearMonth yearMonth = YearMonth.of(year, month);
// Call under test
StatisticsMonthlyStatus status = dao.setAvailable(OBJECT_TYPE, yearMonth);
assertEquals(yearMonth, status.getMonth());
assertEquals(StatisticsStatus.AVAILABLE, status.getStatus());
assertNotNull(status.getLastUpdatedOn());
assertNull(status.getLastStartedOn());
}
@Test
public void testSetFailedTimestamp() {
int year = 2019;
int month = 8;
YearMonth yearMonth = YearMonth.of(year, month);
// Call under test
StatisticsMonthlyStatus status = dao.setProcessingFailed(OBJECT_TYPE, yearMonth, "Some error", "Some error details");
assertEquals(yearMonth, status.getMonth());
assertEquals(StatisticsStatus.PROCESSING_FAILED, status.getStatus());
assertNotNull(status.getLastUpdatedOn());
assertNull(status.getLastStartedOn());
}
@Test
public void testSetProcessing() {
int year = 2019;
int month = 8;
YearMonth yearMonth = YearMonth.of(year, month);
// Call under test
StatisticsMonthlyStatus status = dao.setProcessing(OBJECT_TYPE, yearMonth);
assertEquals(yearMonth, status.getMonth());
assertEquals(StatisticsStatus.PROCESSING, status.getStatus());
assertNotNull(status.getLastStartedOn());
assertNotNull(status.getLastUpdatedOn());
}
@Test
public void testSetAvailableAfterProcessing() {
int year = 2019;
int month = 8;
YearMonth yearMonth = YearMonth.of(year, month);
// Set if first as available, this sets the started at timestamp
StatisticsMonthlyStatus status = dao.setProcessing(OBJECT_TYPE, yearMonth);
assertNotNull(status.getLastStartedOn());
assertNotNull(status.getLastUpdatedOn());
// Call under test
StatisticsMonthlyStatus statusUpdated = dao.setAvailable(OBJECT_TYPE, yearMonth);
assertEquals(StatisticsStatus.AVAILABLE, statusUpdated.getStatus());
assertNotNull(statusUpdated.getLastStartedOn());
assertEquals(status.getLastStartedOn(), statusUpdated.getLastStartedOn());
assertNotNull(statusUpdated.getLastUpdatedOn());
assertNotEquals(status.getLastUpdatedOn(), statusUpdated.getLastUpdatedOn());
}
@Test
public void testSetFailedWithNoErrorDetails() {
int year = 2019;
int month = 8;
YearMonth yearMonth = YearMonth.of(year, month);
// Set if first as available, this sets the started at timestamp
StatisticsMonthlyStatus status = dao.setProcessing(OBJECT_TYPE, yearMonth);
assertNotNull(status.getLastStartedOn());
assertNotNull(status.getLastUpdatedOn());
// Call under test
StatisticsMonthlyStatus statusUpdated = dao.setProcessingFailed(OBJECT_TYPE, yearMonth, "Some error", null);
assertNotNull(statusUpdated.getLastStartedOn());
assertEquals(status.getLastStartedOn(), statusUpdated.getLastStartedOn());
assertNotNull(statusUpdated.getLastUpdatedOn());
assertNotEquals(status.getLastUpdatedOn(), statusUpdated.getLastUpdatedOn());
}
@Test
public void testGetStatusWithEmptyType() {
assertThrows(IllegalArgumentException.class, () -> {
YearMonth yearMonth = YearMonth.of(2019, 8);
// Call under test
dao.getStatus(null, yearMonth);
});
}
@Test
public void testGetStatusWithEmptyMonth() {
assertThrows(IllegalArgumentException.class, () -> {
YearMonth yearMonth = null;
// Call under test
dao.getStatus(OBJECT_TYPE, yearMonth);
});
}
@Test
public void testGetStatusEmpty() {
int year = 2019;
int month = 8;
YearMonth yearMonth = YearMonth.of(year, month);
Optional<StatisticsMonthlyStatus> getStatusResult = dao.getStatus(OBJECT_TYPE, yearMonth);
assertFalse(getStatusResult.isPresent());
}
@Test
public void testGetAvailableStatusInRangeWithIllegalRange() {
assertThrows(IllegalArgumentException.class, () -> {
YearMonth from = YearMonth.of(2019, 8);
YearMonth to = YearMonth.of(2019, 8);
// Call under test
dao.getAvailableStatusInRange(OBJECT_TYPE, from, to);
});
assertThrows(IllegalArgumentException.class, () -> {
YearMonth from = YearMonth.of(2019, 9);
YearMonth to = YearMonth.of(2019, 8);
// Call under test
dao.getAvailableStatusInRange(OBJECT_TYPE, from, to);
});
assertThrows(IllegalArgumentException.class, () -> {
YearMonth from = null;
YearMonth to = YearMonth.of(2019, 8);
// Call under test
dao.getAvailableStatusInRange(OBJECT_TYPE, from, to);
});
assertThrows(IllegalArgumentException.class, () -> {
YearMonth from = YearMonth.of(2019, 7);
YearMonth to = null;
// Call under test
dao.getAvailableStatusInRange(OBJECT_TYPE, from, to);
});
}
@Test
public void testGetAvailableStatusInRangeWithEmptyType() {
assertThrows(IllegalArgumentException.class, () -> {
YearMonth from = YearMonth.of(2019, 7);
YearMonth to = YearMonth.of(2019, 8);
// Call under test
dao.getAvailableStatusInRange(null, from, to);
});
}
@Test
public void testGetAvailableStatusInRangeEmpty() {
YearMonth from = YearMonth.of(2019, 7);
YearMonth to = YearMonth.of(2019, 8);
// Call under test
List<StatisticsMonthlyStatus> result = dao.getAvailableStatusInRange(OBJECT_TYPE, from, to);
assertTrue(result.isEmpty());
}
@Test
public void testGetAvailableStatusSameYear() {
int year = 2019;
int minMonth = 1;
int maxMonth = 12;
// Setup some data
for (int month = minMonth; month <= maxMonth; month++) {
dao.setAvailable(OBJECT_TYPE, YearMonth.of(2019, month));
}
YearMonth from = YearMonth.of(year, minMonth);
YearMonth to = YearMonth.of(year, maxMonth);
// Call under test
List<StatisticsMonthlyStatus> result = dao.getAvailableStatusInRange(OBJECT_TYPE, from, to);
assertEquals(from.until(to, ChronoUnit.MONTHS) + 1, result.size());
for (int i = 0; i < result.size(); i++) {
StatisticsMonthlyStatus status = result.get(i);
assertEquals(StatisticsStatus.AVAILABLE, status.getStatus());
assertEquals(YearMonth.of(year, minMonth + i), status.getMonth());
}
}
@Test
public void testGetAvailableStatusSpanYears() {
int startYear = 2018;
int startMonth = 7;
int months = 12;
YearMonth from = YearMonth.of(startYear, startMonth);
YearMonth month = from;
for (int i = 0; i < months; i++) {
dao.setAvailable(OBJECT_TYPE, month);
month = month.plusMonths(1);
}
YearMonth to = month.minusMonths(1);
// Call under test
List<StatisticsMonthlyStatus> result = dao.getAvailableStatusInRange(OBJECT_TYPE, from, to);
assertEquals(from.until(to, ChronoUnit.MONTHS) + 1, result.size());
}
@Test
public void testGetAvailableStatusPartial() {
int year = 2019;
int startMonth = 1;
int months = 12;
YearMonth from = YearMonth.of(year, startMonth);
YearMonth to = from.plusMonths(months);
YearMonth month = from;
// Set half of the months to be available
for (int i = 0; i < months; i++) {
if (i % 2 == 0) {
dao.setAvailable(OBJECT_TYPE, month);
} else {
dao.setProcessing(OBJECT_TYPE, month);
}
month = month.plusMonths(1);
}
// Call under test
List<StatisticsMonthlyStatus> result = dao.getAvailableStatusInRange(OBJECT_TYPE, from, to);
assertEquals(months / 2, result.size());
for (int i = 0; i < result.size(); i++) {
StatisticsMonthlyStatus status = result.get(i);
assertEquals(StatisticsStatus.AVAILABLE, status.getStatus());
}
}
@Test
public void testTouchOnAbsent() {
int year = 2019;
int month = 8;
YearMonth yearMonth = YearMonth.of(year, month);
// Call under test
boolean result = dao.touch(OBJECT_TYPE, yearMonth);
assertFalse(result);
}
@Test
public void testTouchOnExisting() {
int year = 2019;
int month = 8;
YearMonth yearMonth = YearMonth.of(year, month);
StatisticsMonthlyStatus status = dao.setProcessing(OBJECT_TYPE, yearMonth);
// Sleep for some time to make sure the timestamp is different
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Call under test
boolean result = dao.touch(OBJECT_TYPE, yearMonth);
assertTrue(result);
StatisticsMonthlyStatus statusUpdated = dao.getStatus(OBJECT_TYPE, yearMonth).get();
assertNotEquals(status, statusUpdated);
// Everything else should stay the same
statusUpdated.setLastUpdatedOn(status.getLastUpdatedOn());
assertEquals(status, statusUpdated);
}
}
| |
/*
* 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.commons.rdf.impl.utils.graphmatching;
import org.apache.commons.rdf.impl.utils.graphmatching.collections.IntHashMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.rdf.BlankNode;
import org.apache.commons.rdf.Graph;
import org.apache.commons.rdf.BlankNodeOrIri;
import org.apache.commons.rdf.RdfTerm;
import org.apache.commons.rdf.Triple;
import org.apache.commons.rdf.Graph;
import org.apache.commons.rdf.Iri;
import org.apache.commons.rdf.impl.utils.TripleImpl;
import org.apache.commons.rdf.impl.utils.graphmatching.collections.IntIterator;
/**
*
* @author reto
*/
public class HashMatching {
private Map<BlankNode, BlankNode> matchings = new HashMap<BlankNode, BlankNode>();
private Map<Set<BlankNode>, Set<BlankNode>> matchingGroups;
/**
* tc1 and tc2 will be modified: the triples containing no unmatched bnode
* will be removed
*
* @param tc1
* @param tc2
* @throws GraphNotIsomorphicException
*/
HashMatching(Graph tc1, Graph tc2) throws GraphNotIsomorphicException {
int foundMatchings = 0;
int foundMatchingGroups = 0;
Map<BlankNode, Integer> bNodeHashMap = new HashMap<BlankNode, Integer>();
while (true) {
bNodeHashMap = matchByHashes(tc1, tc2, bNodeHashMap);
if (bNodeHashMap == null) {
throw new GraphNotIsomorphicException();
}
if (matchings.size() == foundMatchings) {
if (!(matchingGroups.size() > foundMatchingGroups)) {
break;
}
}
foundMatchings = matchings.size();
foundMatchingGroups = matchingGroups.size();
}
}
/**
*
* @return a map containing set of which each bnodes mappes one of the other set
*/
public Map<Set<BlankNode>, Set<BlankNode>> getMatchingGroups() {
return matchingGroups;
}
public Map<BlankNode, BlankNode> getMatchings() {
return matchings;
}
private static IntHashMap<Set<BlankNode>> getHashNodes(Map<BlankNode,
Set<Property>> bNodePropMap, Map<BlankNode, Integer> bNodeHashMap) {
IntHashMap<Set<BlankNode>> result = new IntHashMap<Set<BlankNode>>();
for (Map.Entry<BlankNode, Set<Property>> entry : bNodePropMap.entrySet()) {
int hash = computeHash(entry.getValue(), bNodeHashMap);
Set<BlankNode> bNodeSet = result.get(hash);
if (bNodeSet == null) {
bNodeSet = new HashSet<BlankNode>();
result.put(hash,bNodeSet);
}
bNodeSet.add(entry.getKey());
}
return result;
}
/*
* returns a Map from bnodes to hash that can be used for future
* refinements, this could be separate for each ImmutableGraph.
*
* triples no longer containing an unmatched bnodes ae removed.
*
* Note that the matched node are not guaranteed to be equals, but only to
* be the correct if the graphs are isomorphic.
*/
private Map<BlankNode, Integer> matchByHashes(Graph g1, Graph g2,
Map<BlankNode, Integer> bNodeHashMap) {
Map<BlankNode, Set<Property>> bNodePropMap1 = getBNodePropMap(g1);
Map<BlankNode, Set<Property>> bNodePropMap2 = getBNodePropMap(g2);
IntHashMap<Set<BlankNode>> hashNodeMap1 = getHashNodes(bNodePropMap1, bNodeHashMap);
IntHashMap<Set<BlankNode>> hashNodeMap2 = getHashNodes(bNodePropMap2, bNodeHashMap);
if (!hashNodeMap1.keySet().equals(hashNodeMap2.keySet())) {
return null;
}
matchingGroups = new HashMap<Set<BlankNode>, Set<BlankNode>>();
IntIterator hashIter = hashNodeMap1.keySet().intIterator();
while (hashIter.hasNext()) {
int hash = hashIter.next();
Set<BlankNode> nodes1 = hashNodeMap1.get(hash);
Set<BlankNode> nodes2 = hashNodeMap2.get(hash);
if (nodes1.size() != nodes2.size()) {
return null;
}
if (nodes1.size() != 1) {
matchingGroups.put(nodes1, nodes2);
continue;
}
final BlankNode bNode1 = nodes1.iterator().next();
final BlankNode bNode2 = nodes2.iterator().next();
matchings.put(bNode1,bNode2);
//in the graphs replace node occurences with grounded node,
BlankNodeOrIri mappedNode = new MappedNode(bNode1, bNode2);
replaceNode(g1,bNode1, mappedNode);
replaceNode(g2, bNode2, mappedNode);
//remove grounded triples
if (!Utils.removeGrounded(g1,g2)) {
return null;
}
}
Map<BlankNode, Integer> result = new HashMap<BlankNode, Integer>();
addInverted(result, hashNodeMap1);
addInverted(result, hashNodeMap2);
return result;
}
private static int computeHash(Set<Property> propertySet, Map<BlankNode, Integer> bNodeHashMap) {
int result = 0;
for (Property property : propertySet) {
result += property.hashCode(bNodeHashMap);
}
return result;
}
private static Map<BlankNode, Set<Property>> getBNodePropMap(Graph g) {
Set<BlankNode> bNodes = Utils.getBNodes(g);
Map<BlankNode, Set<Property>> result = new HashMap<BlankNode, Set<Property>>();
for (BlankNode bNode : bNodes) {
result.put(bNode, getProperties(bNode, g));
}
return result;
}
private static Set<Property> getProperties(BlankNode bNode, Graph g) {
Set<Property> result = new HashSet<Property>();
Iterator<Triple> ti = g.filter(bNode, null, null);
while (ti.hasNext()) {
Triple triple = ti.next();
result.add(new ForwardProperty(triple.getPredicate(), triple.getObject()));
}
ti = g.filter(null, null, bNode);
while (ti.hasNext()) {
Triple triple = ti.next();
result.add(new BackwardProperty(triple.getSubject(), triple.getPredicate()));
}
return result;
}
private static int nodeHash(RdfTerm resource, Map<BlankNode, Integer> bNodeHashMap) {
if (resource instanceof BlankNode) {
Integer mapValue = bNodeHashMap.get((BlankNode)resource);
if (mapValue == null) {
return 0;
} else {
return mapValue;
}
} else {
return resource.hashCode();
}
}
private static void replaceNode(Graph graph, BlankNode bNode, BlankNodeOrIri replacementNode) {
Set<Triple> triplesToRemove = new HashSet<Triple>();
for (Triple triple : graph) {
Triple replacementTriple = getReplacement(triple, bNode, replacementNode);
if (replacementTriple != null) {
triplesToRemove.add(triple);
graph.add(replacementTriple);
}
}
graph.removeAll(triplesToRemove);
}
private static Triple getReplacement(Triple triple, BlankNode bNode, BlankNodeOrIri replacementNode) {
if (triple.getSubject().equals(bNode)) {
if (triple.getObject().equals(bNode)) {
return new TripleImpl(replacementNode, triple.getPredicate(), replacementNode);
} else {
return new TripleImpl(replacementNode, triple.getPredicate(), triple.getObject());
}
} else {
if (triple.getObject().equals(bNode)) {
return new TripleImpl(triple.getSubject(), triple.getPredicate(), replacementNode);
} else {
return null;
}
}
}
private static void addInverted(Map<BlankNode, Integer> result, IntHashMap<Set<BlankNode>> hashNodeMap) {
for (int hash : hashNodeMap.keySet()) {
Set<BlankNode> bNodes = hashNodeMap.get(hash);
for (BlankNode bNode : bNodes) {
result.put(bNode, hash);
}
}
}
private static class BackwardProperty implements Property {
private BlankNodeOrIri subject;
private Iri predicate;
public BackwardProperty(BlankNodeOrIri subject, Iri predicate) {
this.subject = subject;
this.predicate = predicate;
}
@Override
public int hashCode(Map<BlankNode, Integer> bNodeHashMap) {
return 0xFF ^ predicate.hashCode() ^ nodeHash(subject, bNodeHashMap);
}
}
private static class ForwardProperty implements Property {
private Iri predicate;
private RdfTerm object;
public ForwardProperty(Iri predicate, RdfTerm object) {
this.predicate = predicate;
this.object = object;
}
@Override
public int hashCode(Map<BlankNode, Integer> bNodeHashMap) {
return predicate.hashCode() ^ nodeHash(object, bNodeHashMap);
}
}
private static class MappedNode implements BlankNodeOrIri {
private BlankNode bNode1, bNode2;
public MappedNode(BlankNode bNode1, BlankNode bNode2) {
this.bNode1 = bNode1;
this.bNode2 = bNode2;
}
}
private static interface Property {
public int hashCode(Map<BlankNode, Integer> bNodeHashMap);
}
}
| |
package Examples;
//////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001-2022 Aspose Pty Ltd. All Rights Reserved.
//
// This file is part of Aspose.Words. The source code in this file
// is only intended as a supplement to the documentation, and is provided
// "as is", without warranty of any kind, either expressed or implied.
//////////////////////////////////////////////////////////////////////////
import com.aspose.pdf.TextAbsorber;
import com.aspose.words.*;
import org.apache.commons.io.FileUtils;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.ArrayList;
public class ExLoadOptions extends ApiExampleBase {
//ExStart
//ExFor:LoadOptions.ResourceLoadingCallback
//ExSummary:Shows how to handle external resources when loading Html documents.
@Test //ExSkip
public void loadOptionsCallback() throws Exception {
LoadOptions loadOptions = new LoadOptions();
loadOptions.setResourceLoadingCallback(new HtmlLinkedResourceLoadingCallback());
// When we load the document, our callback will handle linked resources such as CSS stylesheets and images.
Document doc = new Document(getMyDir() + "Images.html", loadOptions);
doc.save(getArtifactsDir() + "LoadOptions.LoadOptionsCallback.pdf");
}
/// <summary>
/// Prints the filenames of all external stylesheets and substitutes all images of a loaded html document.
/// </summary>
private static class HtmlLinkedResourceLoadingCallback implements IResourceLoadingCallback {
public int resourceLoading(ResourceLoadingArgs args) throws IOException {
switch (args.getResourceType()) {
case ResourceType.CSS_STYLE_SHEET:
System.out.println(MessageFormat.format("External CSS Stylesheet found upon loading: {0}", args.getOriginalUri()));
return ResourceLoadingAction.DEFAULT;
case ResourceType.IMAGE:
System.out.println(MessageFormat.format("External Image found upon loading: {0}", args.getOriginalUri()));
final String newImageFilename = "Logo.jpg";
System.out.println(MessageFormat.format("\tImage will be substituted with: {0}", newImageFilename));
byte[] imageBytes = FileUtils.readFileToByteArray(new File(getImageDir() + newImageFilename));
args.setData(imageBytes);
return ResourceLoadingAction.USER_PROVIDED;
}
return ResourceLoadingAction.DEFAULT;
}
}
//ExEnd
@Test(dataProvider = "convertShapeToOfficeMathDataProvider")
public void convertShapeToOfficeMath(boolean isConvertShapeToOfficeMath) throws Exception {
//ExStart
//ExFor:LoadOptions.ConvertShapeToOfficeMath
//ExSummary:Shows how to convert EquationXML shapes to Office Math objects.
LoadOptions loadOptions = new LoadOptions();
// Use this flag to specify whether to convert the shapes with EquationXML attributes
// to Office Math objects and then load the document.
loadOptions.setConvertShapeToOfficeMath(isConvertShapeToOfficeMath);
Document doc = new Document(getMyDir() + "Math shapes.docx", loadOptions);
if (isConvertShapeToOfficeMath) {
Assert.assertEquals(16, doc.getChildNodes(NodeType.SHAPE, true).getCount());
Assert.assertEquals(34, doc.getChildNodes(NodeType.OFFICE_MATH, true).getCount());
} else {
Assert.assertEquals(24, doc.getChildNodes(NodeType.SHAPE, true).getCount());
Assert.assertEquals(0, doc.getChildNodes(NodeType.OFFICE_MATH, true).getCount());
}
//ExEnd
}
@DataProvider(name = "convertShapeToOfficeMathDataProvider")
public static Object[][] convertShapeToOfficeMathDataProvider() {
return new Object[][]
{
{true},
{false},
};
}
@Test
public void fontSettings() throws Exception {
//ExStart
//ExFor:LoadOptions.FontSettings
//ExSummary:Shows how to apply font substitution settings while loading a document.
// Create a FontSettings object that will substitute the "Times New Roman" font
// with the font "Arvo" from our "MyFonts" folder.
FontSettings fontSettings = new FontSettings();
fontSettings.setFontsFolder(getFontsDir(), false);
fontSettings.getSubstitutionSettings().getTableSubstitution().addSubstitutes("Times New Roman", "Arvo");
// Set that FontSettings object as a property of a newly created LoadOptions object.
LoadOptions loadOptions = new LoadOptions();
loadOptions.setFontSettings(fontSettings);
// Load the document, then render it as a PDF with the font substitution.
Document doc = new Document(getMyDir() + "Document.docx", loadOptions);
doc.save(getArtifactsDir() + "LoadOptions.FontSettings.pdf");
//ExEnd
}
@Test
public void loadOptionsMswVersion() throws Exception {
//ExStart
//ExFor:LoadOptions.MswVersion
//ExSummary:Shows how to emulate the loading procedure of a specific Microsoft Word version during document loading.
// By default, Aspose.Words load documents according to Microsoft Word 2019 specification.
LoadOptions loadOptions = new LoadOptions();
Assert.assertEquals(MsWordVersion.WORD_2019, loadOptions.getMswVersion());
// This document is missing the default paragraph formatting style.
// This default style will be regenerated when we load the document either with Microsoft Word or Aspose.Words.
loadOptions.setMswVersion(MsWordVersion.WORD_2007);
Document doc = new Document(getMyDir() + "Document.docx", loadOptions);
// The style's line spacing will have this value when loaded by Microsoft Word 2007 specification.
Assert.assertEquals(12.95d, doc.getStyles().getDefaultParagraphFormat().getLineSpacing(), 0.01d);
//ExEnd
}
//ExStart
//ExFor:LoadOptions.WarningCallback
//ExSummary:Shows how to print and store warnings that occur during document loading.
@Test //ExSkip
public void loadOptionsWarningCallback() throws Exception {
// Create a new LoadOptions object and set its WarningCallback attribute
// as an instance of our IWarningCallback implementation.
LoadOptions loadOptions = new LoadOptions();
loadOptions.setWarningCallback(new DocumentLoadingWarningCallback());
// Our callback will print all warnings that come up during the load operation.
Document doc = new Document(getMyDir() + "Document.docx", loadOptions);
ArrayList<WarningInfo> warnings = ((DocumentLoadingWarningCallback) loadOptions.getWarningCallback()).getWarnings();
Assert.assertEquals(3, warnings.size());
testLoadOptionsWarningCallback(warnings); //ExSkip
}
/// <summary>
/// IWarningCallback that prints warnings and their details as they arise during document loading.
/// </summary>
private static class DocumentLoadingWarningCallback implements IWarningCallback {
public void warning(WarningInfo info) {
System.out.println(MessageFormat.format("Warning: {0}", info.getWarningType()));
System.out.println(MessageFormat.format("\tSource: {0}", info.getSource()));
System.out.println(MessageFormat.format("\tDescription: {0}", info.getDescription()));
mWarnings.add(info);
}
public ArrayList<WarningInfo> getWarnings() {
return mWarnings;
}
private final /*final*/ ArrayList<WarningInfo> mWarnings = new ArrayList<WarningInfo>();
}
//ExEnd
private static void testLoadOptionsWarningCallback(ArrayList<WarningInfo> warnings) {
Assert.assertEquals(WarningType.UNEXPECTED_CONTENT, warnings.get(0).getWarningType());
Assert.assertEquals(WarningSource.DOCX, warnings.get(0).getSource());
Assert.assertEquals("3F01", warnings.get(0).getDescription());
Assert.assertEquals(WarningType.MINOR_FORMATTING_LOSS, warnings.get(1).getWarningType());
Assert.assertEquals(WarningSource.DOCX, warnings.get(1).getSource());
Assert.assertEquals("Import of element 'shapedefaults' is not supported in Docx format by Aspose.Words.", warnings.get(1).getDescription());
Assert.assertEquals(WarningType.MINOR_FORMATTING_LOSS, warnings.get(2).getWarningType());
Assert.assertEquals(WarningSource.DOCX, warnings.get(2).getSource());
Assert.assertEquals("Import of element 'extraClrSchemeLst' is not supported in Docx format by Aspose.Words.", warnings.get(2).getDescription());
}
@Test
public void tempFolder() throws Exception {
//ExStart
//ExFor:LoadOptions.TempFolder
//ExSummary:Shows how to use the hard drive instead of memory when loading a document.
// When we load a document, various elements are temporarily stored in memory as the save operation occurs.
// We can use this option to use a temporary folder in the local file system instead,
// which will reduce our application's memory overhead.
LoadOptions options = new LoadOptions();
options.setTempFolder(getArtifactsDir() + "TempFiles");
// The specified temporary folder must exist in the local file system before the load operation.
Files.createDirectory(Paths.get(options.getTempFolder()));
Document doc = new Document(getMyDir() + "Document.docx", options);
// The folder will persist with no residual contents from the load operation.
Assert.assertTrue(DocumentHelper.directoryGetFiles(options.getTempFolder(), "*.*").size() == 0);
//ExEnd
}
@Test
public void addEditingLanguage() throws Exception {
//ExStart
//ExFor:LanguagePreferences
//ExFor:LanguagePreferences.AddEditingLanguage(EditingLanguage)
//ExFor:LoadOptions.LanguagePreferences
//ExFor:EditingLanguage
//ExSummary:Shows how to apply language preferences when loading a document.
LoadOptions loadOptions = new LoadOptions();
loadOptions.getLanguagePreferences().addEditingLanguage(EditingLanguage.JAPANESE);
Document doc = new Document(getMyDir() + "No default editing language.docx", loadOptions);
int localeIdFarEast = doc.getStyles().getDefaultFont().getLocaleIdFarEast();
System.out.println(localeIdFarEast == EditingLanguage.JAPANESE
? "The document either has no any FarEast language set in defaults or it was set to Japanese originally."
: "The document default FarEast language was set to another than Japanese language originally, so it is not overridden.");
//ExEnd
Assert.assertEquals(EditingLanguage.JAPANESE, doc.getStyles().getDefaultFont().getLocaleIdFarEast());
doc = new Document(getMyDir() + "No default editing language.docx");
Assert.assertEquals(EditingLanguage.ENGLISH_US, doc.getStyles().getDefaultFont().getLocaleIdFarEast());
}
@Test
public void setEditingLanguageAsDefault() throws Exception {
//ExStart
//ExFor:LanguagePreferences.DefaultEditingLanguage
//ExSummary:Shows how set a default language when loading a document.
LoadOptions loadOptions = new LoadOptions();
loadOptions.getLanguagePreferences().setDefaultEditingLanguage(EditingLanguage.RUSSIAN);
Document doc = new Document(getMyDir() + "No default editing language.docx", loadOptions);
int localeId = doc.getStyles().getDefaultFont().getLocaleId();
System.out.println(localeId == EditingLanguage.RUSSIAN
? "The document either has no any language set in defaults or it was set to Russian originally."
: "The document default language was set to another than Russian language originally, so it is not overridden.");
//ExEnd
Assert.assertEquals(EditingLanguage.RUSSIAN, doc.getStyles().getDefaultFont().getLocaleId());
doc = new Document(getMyDir() + "No default editing language.docx");
Assert.assertEquals(EditingLanguage.ENGLISH_US, doc.getStyles().getDefaultFont().getLocaleId());
}
@Test
public void convertMetafilesToPng() throws Exception {
//ExStart
//ExFor:LoadOptions.ConvertMetafilesToPng
//ExSummary:Shows how to convert WMF/EMF to PNG during loading document.
Document doc = new Document();
Shape shape = new Shape(doc, ShapeType.IMAGE);
shape.getImageData().setImage(getImageDir() + "Windows MetaFile.wmf");
shape.setWidth(100.0);
shape.setHeight(100.0);
doc.getFirstSection().getBody().getFirstParagraph().appendChild(shape);
doc.save(getArtifactsDir() + "Image.CreateImageDirectly.docx");
shape = (Shape) doc.getChild(NodeType.SHAPE, 0, true);
TestUtil.verifyImageInShape(1600, 1600, ImageType.WMF, shape);
LoadOptions loadOptions = new LoadOptions();
loadOptions.setConvertMetafilesToPng(true);
doc = new Document(getArtifactsDir() + "Image.CreateImageDirectly.docx", loadOptions);
shape = (Shape) doc.getChild(NodeType.SHAPE, 0, true);
//ExEnd
}
@Test
public void openChmFile() throws Exception {
FileFormatInfo info = FileFormatUtil.detectFileFormat(getMyDir() + "HTML help.chm");
Assert.assertEquals(info.getLoadFormat(), LoadFormat.CHM);
LoadOptions loadOptions = new LoadOptions();
loadOptions.setEncoding(Charset.forName("Windows-1251"));
Document doc = new Document(getMyDir() + "HTML help.chm", loadOptions);
}
@Test (dataProvider = "flatOpcXmlMappingOnlyDataProvider")
public void flatOpcXmlMappingOnly(boolean isFlatOpcXmlMappingOnly) throws Exception
{
//ExStart
//ExFor:SaveOptions.FlatOpcXmlMappingOnly
//ExSummary:Shows how to binding structured document tags to any format.
// If true - SDT will contain raw HTML text.
// If false - mapped HTML will parsed and resulting document will be inserted into SDT content.
LoadOptions loadOptions = new LoadOptions(); { loadOptions.setFlatOpcXmlMappingOnly(isFlatOpcXmlMappingOnly); }
Document doc = new Document(getMyDir() + "Structured document tag with HTML content.docx", loadOptions);
SaveOptions saveOptions = SaveOptions.createSaveOptions(SaveFormat.PDF);
saveOptions.setFlatOpcXmlMappingOnly(isFlatOpcXmlMappingOnly);
doc.save(getArtifactsDir() + "LoadOptions.FlatOpcXmlMappingOnly.pdf", saveOptions);
//ExEnd
com.aspose.pdf.Document pdfDocument =
new com.aspose.pdf.Document(getArtifactsDir() + "LoadOptions.FlatOpcXmlMappingOnly.pdf");
TextAbsorber textAbsorber = new TextAbsorber();
pdfDocument.getPages().accept(textAbsorber);
Assert.assertTrue(isFlatOpcXmlMappingOnly
? textAbsorber.getText().contains(
"TCSVerify vData1: <!DOCTYPE html><html><body><h1>My First Heading</h1><p>My first \r\nparagraph.</p></body></html>\r\n\r\n" +
"TCSVerify vData2: <html><body><b>This is BOLD</b><i>This is Italics</i></body></html>\r\n\r\n" +
"TCSVerify vData3: <!DOCTYPE HTML PUBLIC")
: textAbsorber.getText().contains(
"TCSVerify vData1: \r\nMy First Heading\r\n\r\nMy first paragraph.\r\n\r\n\r\n" +
"TCSVerify vData2: This is BOLDThis is Italics\r\n\r\n" +
"TCSVerify vData3: \r\n\r\nDepression Program\r\n\r\nDepression Abuse"));
pdfDocument.close();
}
@DataProvider(name = "flatOpcXmlMappingOnlyDataProvider")
public static Object[][] flatOpcXmlMappingOnlyDataProvider() {
return new Object[][]
{
{true},
{false},
};
}
}
| |
package cs414.a5.nlighth1.ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
/**
*
* @author Nathan Lighthart
*/
public class EditMenuUI {
private UIController controller;
private JFrame frame;
private JComboBox<String> menuComboBox;
private JScrollPane menuItemScrollPane;
private JList<String> menuItemList;
private JPanel buttonPanel;
private JPanel descriptionPanel;
private JButton createButton;
private JButton deleteButton;
private JButton addButton;
private JButton removeButton;
private JButton editButton;
private TextArea menuDescText;
public EditMenuUI(UIController controller) {
this.controller = controller;
}
public void init() {
frame = new JFrame("Edit Menu");
menuComboBox = new JComboBox<>();
menuItemScrollPane = new JScrollPane();
menuItemList = new JList<>();
buttonPanel = new JPanel();
descriptionPanel = new JPanel();
createButton = new JButton("Create Menu");
editButton = new JButton("Edit Menu");
deleteButton = new JButton("Delete Menu");
addButton = new JButton("Add Item");
removeButton = new JButton("Remove Item");
menuDescText = new TextArea((String) menuComboBox.getSelectedItem());
layoutComponents();
addListeners();
frame.setPreferredSize(new Dimension(800, 600));
frame.pack();
}
public void updateMenus() {
setMenus(controller.getMenus());
if(menuComboBox.getModel().getSize() == 0) {
((DefaultListModel<String>) menuItemList.getModel())
.removeAllElements();
}
}
public void setMenus(Iterable<String> menus) {
menuComboBox.removeAllItems();
for(String menu : menus) {
menuComboBox.addItem(menu);
}
}
public void setMenuItems(Iterable<String> items) {
DefaultListModel<String> model = (DefaultListModel<String>) menuItemList
.getModel();
model.removeAllElements();
for(String item : items) {
model.addElement(item);
}
}
public void setVisible(boolean visible) {
frame.setLocationRelativeTo(null);
frame.setVisible(visible);
}
private void layoutComponents() {
frame.setLayout(new BorderLayout());
frame.add(menuComboBox, BorderLayout.NORTH);
frame.add(menuItemScrollPane, BorderLayout.CENTER);
frame.add(descriptionPanel, BorderLayout.LINE_START);
menuItemScrollPane.setViewportView(menuItemList);
menuItemList.setModel(new DefaultListModel<String>());
menuItemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
frame.add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
buttonPanel.add(createButton);
buttonPanel.add(editButton);
buttonPanel.add(deleteButton);
buttonPanel.add(addButton);
buttonPanel.add(removeButton);
menuDescText.setEditable(false);
descriptionPanel.add(menuDescText);
}
private void updateMenuDesc() {
if(menuComboBox.getSelectedItem() == null) {
menuDescText.setText("");
} else {
menuDescText.setText(controller.getMenuDesc((String) menuComboBox
.getSelectedItem()));
}
}
private void addListeners() {
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
controller.closeEditMenu();
}
});
menuComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadItemsAction();
updateMenuDesc();
}
});
createButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
createMenuAction();
updateMenuDesc();
}
});
deleteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteMenuAction();
updateMenuDesc();
}
});
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addItemAction();
}
});
editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
editMenuAction();
}
});
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
removeItemAction();
}
});
}
private void loadItemsAction() {
if(menuComboBox.getModel().getSize() == 0) {
return; // do nothing as nothing to load
}
String menu = (String) menuComboBox.getSelectedItem();
Iterable<String> menuItems = controller.getFullMenuItems(menu);
setMenuItems(menuItems);
}
private void createMenuAction() {
String name = JOptionPane.showInputDialog("Enter menu name:");
String description = JOptionPane
.showInputDialog("Enter menu description:");
boolean success = controller.createMenu(name, description);
if(!success) {
JOptionPane.showMessageDialog(frame,
"Error creating menu. Please try a different name.");
return;
}
updateMenus();
menuComboBox.setSelectedItem(name);
JOptionPane.showMessageDialog(null, "Menu created.");
}
private void editMenuAction() {
String name = JOptionPane.showInputDialog("Enter new menu name:");
String description = JOptionPane
.showInputDialog("Enter new description:");
String menu = (String) menuComboBox.getSelectedItem();
boolean success = controller.editMenu(menu, name, description);
if(!success) {
JOptionPane.showMessageDialog(frame,
"Error editing menu. Please try a different name.");
return;
}
updateMenus();
JOptionPane.showMessageDialog(null, "Menu updated.");
menuComboBox.setSelectedItem(name);
}
private void deleteMenuAction() {
if(menuComboBox.getModel().getSize() == 0) {
return; // do nothing as nothing to load
}
String menu = (String) menuComboBox.getSelectedItem();
controller.deleteMenu(menu);
JOptionPane.showMessageDialog(null, "Menu deleted.");
updateMenus();
}
private void addItemAction() {
if(menuComboBox.getModel().getSize() == 0) {
return; // do nothing as nothing to load
}
String menu = (String) menuComboBox.getSelectedItem();
Iterable<String> menuItems = controller.getMenuItemsNotOnMenu(menu);
List<String> items = new ArrayList<>();
for(String item : menuItems) {
items.add(item);
}
if(items.isEmpty()) {
JOptionPane.showMessageDialog(frame,
"No menu items available to be added.");
return;
}
String selectedItem = (String) JOptionPane.showInputDialog(frame,
"Please select an Item.", "Item Selector",
JOptionPane.PLAIN_MESSAGE, null, items.toArray(), items.get(0));
if(selectedItem == null) {
return; // cancel
}
controller.addMenuItem(menu, selectedItem);
JOptionPane.showMessageDialog(null, "Item added.");
loadItemsAction();
}
private void removeItemAction() {
if(menuComboBox.getModel().getSize() == 0) {
return; // do nothing as nothing to load
}
String menu = (String) menuComboBox.getSelectedItem();
String itemString = menuItemList.getSelectedValue();
if(itemString == null) {
JOptionPane.showMessageDialog(frame,
"Please select an item to remove.");
return;
}
String itemName = controller.getItemName(itemString);
controller.removeMenuItem(menu, itemName);
JOptionPane.showMessageDialog(null, "Item removed.");
loadItemsAction();
}
// Used to view the interface with nothing working
public static void main(String[] args) {
final EditMenuUI view = new EditMenuUI(null);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
view.init();
view.setVisible(true);
view.frame.removeWindowListener(view.frame.getWindowListeners()[0]);
view.frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
});
}
}
| |
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
private static int c;
private static char a;
private static char b;
private static char[] mem = new char[256];
public static void main(String[] args) {
InputStreamReader br = new InputStreamReader(System.in);
try {
while (true) {
c = 0;
Arrays.fill(mem, '0');
br.read(mem, 0, 256);
br.read();
if (mem[0] == '8') {
return;
}
while (c < 256) {
runInstruction();
}
System.out.println(mem);
}
} catch (Exception e) {
} finally {
try {
br.close();
} catch (IOException e) {
}
}
}
private static void runInstruction() {
switch (mem[c]) {
case '0':
a = mem[getAddr(mem[c + 1], mem[c + 2])];
c += 3;
break;
case '1':
mem[getAddr(mem[c + 1], mem[c + 2])] = a;
c += 3;
break;
case '2':
char d = a;
a = b;
b = d;
c++;
break;
case '3':
int total = getDec(a) + getDec(b);
if (total >= 16) {
b = getHex(total / 16);
a = getHex(total % 16);
} else {
b = '0';
a = getHex(total);
}
c++;
break;
case '4':
if (a == '9')
a = 'A';
else if (a == 'F')
a = '0';
else
a++;
c++;
break;
case '5':
if (a == '0')
a = 'F';
else if (a == 'A')
a = '9';
else
a--;
c++;
break;
case '6':
if (a != '0') {
c += 3;
break;
} else {
c = getAddr(mem[c + 1], mem[c + 2]);
runInstruction();
break;
}
case '7':
c = getAddr(mem[c + 1], mem[c + 2]);
runInstruction();
break;
case '8':
c = 256;
break;
default:
break;
}
}
private static int getAddr(char a, char b) {
int addr = 0;
int decA = getDec(a);
addr += (decA == 0 ? 0 : 16 * decA);
addr += getDec(b);
return addr;
}
private static int getDec(char chara) {
switch (chara) {
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'A':
return 10;
case 'B':
return 11;
case 'C':
return 12;
case 'D':
return 13;
case 'E':
return 14;
case 'F':
return 15;
default:
return 0;
}
}
private static char getHex(int dec) {
switch (dec) {
case 0:
return '0';
case 1:
return '1';
case 2:
return '2';
case 3:
return '3';
case 4:
return '4';
case 5:
return '5';
case 6:
return '6';
case 7:
return '7';
case 8:
return '8';
case 9:
return '9';
case 10:
return 'A';
case 11:
return 'B';
case 12:
return 'C';
case 13:
return 'D';
case 14:
return 'E';
case 15:
return 'F';
default:
return '0';
}
}
}
| |
/*
* Copyright (C) 2016 The Dagger Authors.
*
* 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 dagger.internal.codegen.langmodel;
import static androidx.room.compiler.processing.compat.XConverters.toJavac;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.getOnlyElement;
import androidx.room.compiler.processing.XType;
import com.google.auto.common.MoreElements;
import com.google.auto.common.MoreTypes;
import com.google.common.collect.ImmutableSet;
import com.google.common.graph.Traverser;
import com.google.common.util.concurrent.FluentFuture;
import com.google.common.util.concurrent.ListenableFuture;
import com.squareup.javapoet.ArrayTypeName;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.TypeName;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ErrorType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.NoType;
import javax.lang.model.type.NullType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.WildcardType;
import javax.lang.model.util.SimpleTypeVisitor8;
import javax.lang.model.util.Types;
/** Extension of {@link Types} that adds Dagger-specific methods. */
public final class DaggerTypes implements Types {
private final Types types;
private final DaggerElements elements;
public DaggerTypes(Types types, DaggerElements elements) {
this.types = checkNotNull(types);
this.elements = checkNotNull(elements);
}
// Note: This is similar to auto-common's MoreTypes except using ClassName rather than Class.
// TODO(bcorso): Contribute a String version to auto-common's MoreTypes?
/**
* Returns true if the raw type underlying the given {@link TypeMirror} represents the same raw
* type as the given {@link Class} and throws an IllegalArgumentException if the {@link
* TypeMirror} does not represent a type that can be referenced by a {@link Class}
*/
public static boolean isTypeOf(final TypeName typeName, TypeMirror type) {
checkNotNull(typeName);
return type.accept(new IsTypeOf(typeName), null);
}
private static final class IsTypeOf extends SimpleTypeVisitor8<Boolean, Void> {
private final TypeName typeName;
IsTypeOf(TypeName typeName) {
this.typeName = typeName;
}
@Override
protected Boolean defaultAction(TypeMirror type, Void ignored) {
throw new IllegalArgumentException(type + " cannot be represented as a Class<?>.");
}
@Override
public Boolean visitNoType(NoType noType, Void p) {
if (noType.getKind().equals(TypeKind.VOID)) {
return typeName.equals(TypeName.VOID);
}
throw new IllegalArgumentException(noType + " cannot be represented as a Class<?>.");
}
@Override
public Boolean visitError(ErrorType errorType, Void p) {
return false;
}
@Override
public Boolean visitPrimitive(PrimitiveType type, Void p) {
switch (type.getKind()) {
case BOOLEAN:
return typeName.equals(TypeName.BOOLEAN);
case BYTE:
return typeName.equals(TypeName.BYTE);
case CHAR:
return typeName.equals(TypeName.CHAR);
case DOUBLE:
return typeName.equals(TypeName.DOUBLE);
case FLOAT:
return typeName.equals(TypeName.FLOAT);
case INT:
return typeName.equals(TypeName.INT);
case LONG:
return typeName.equals(TypeName.LONG);
case SHORT:
return typeName.equals(TypeName.SHORT);
default:
throw new IllegalArgumentException(type + " cannot be represented as a Class<?>.");
}
}
@Override
public Boolean visitArray(ArrayType array, Void p) {
return (typeName instanceof ArrayTypeName)
&& isTypeOf(((ArrayTypeName) typeName).componentType, array.getComponentType());
}
@Override
public Boolean visitDeclared(DeclaredType type, Void ignored) {
TypeElement typeElement = MoreElements.asType(type.asElement());
return (typeName instanceof ClassName)
&& typeElement.getQualifiedName().contentEquals(((ClassName) typeName).canonicalName());
}
}
/**
* Returns the non-{@link Object} superclass of the type with the proper type parameters. An empty
* {@link Optional} is returned if there is no non-{@link Object} superclass.
*/
public Optional<DeclaredType> nonObjectSuperclass(DeclaredType type) {
return Optional.ofNullable(MoreTypes.nonObjectSuperclass(types, elements, type).orNull());
}
/**
* Returns the {@linkplain #directSupertypes(TypeMirror) supertype}s of a type in breadth-first
* order.
*/
public Iterable<TypeMirror> supertypes(TypeMirror type) {
return Traverser.<TypeMirror>forGraph(this::directSupertypes).breadthFirst(type);
}
/**
* Returns {@code type}'s single type argument.
*
* <p>For example, if {@code type} is {@code List<Number>} this will return {@code Number}.
*
* @throws IllegalArgumentException if {@code type} is not a declared type or has zero or more
* than one type arguments.
*/
public static TypeMirror unwrapType(TypeMirror type) {
TypeMirror unwrapped = unwrapTypeOrDefault(type, null);
checkArgument(unwrapped != null, "%s is a raw type", type);
return unwrapped;
}
private static TypeMirror unwrapTypeOrDefault(TypeMirror type, TypeMirror defaultType) {
DeclaredType declaredType = MoreTypes.asDeclared(type);
TypeElement typeElement = MoreElements.asType(declaredType.asElement());
checkArgument(
!typeElement.getTypeParameters().isEmpty(),
"%s does not have a type parameter",
typeElement.getQualifiedName());
return getOnlyElement(declaredType.getTypeArguments(), defaultType);
}
/**
* Returns {@code type}'s single type argument, if one exists, or {@link Object} if not.
*
* <p>For example, if {@code type} is {@code List<Number>} this will return {@code Number}.
*
* @throws IllegalArgumentException if {@code type} is not a declared type or has more than one
* type argument.
*/
public TypeMirror unwrapTypeOrObject(TypeMirror type) {
return unwrapTypeOrDefault(type, elements.getTypeElement(TypeName.OBJECT).asType());
}
/**
* Returns {@code type} wrapped in {@code wrappingClass}.
*
* <p>For example, if {@code type} is {@code List<Number>} and {@code wrappingClass} is {@code
* Set.class}, this will return {@code Set<List<Number>>}.
*/
public DeclaredType wrapType(XType type, ClassName wrappingClassName) {
return wrapType(toJavac(type), wrappingClassName);
}
/**
* Returns {@code type} wrapped in {@code wrappingClass}.
*
* <p>For example, if {@code type} is {@code List<Number>} and {@code wrappingClass} is {@code
* Set.class}, this will return {@code Set<List<Number>>}.
*/
public DeclaredType wrapType(TypeMirror type, ClassName wrappingClassName) {
return types.getDeclaredType(elements.getTypeElement(wrappingClassName.canonicalName()), type);
}
/**
* Returns {@code type}'s single type argument wrapped in {@code wrappingClass}.
*
* <p>For example, if {@code type} is {@code List<Number>} and {@code wrappingClass} is {@code
* Set.class}, this will return {@code Set<Number>}.
*
* <p>If {@code type} has no type parameters, returns a {@link TypeMirror} for {@code
* wrappingClass} as a raw type.
*
* @throws IllegalArgumentException if {@code} has more than one type argument.
*/
public DeclaredType rewrapType(TypeMirror type, ClassName wrappingClassName) {
List<? extends TypeMirror> typeArguments = MoreTypes.asDeclared(type).getTypeArguments();
TypeElement wrappingType = elements.getTypeElement(wrappingClassName.canonicalName());
switch (typeArguments.size()) {
case 0:
return getDeclaredType(wrappingType);
case 1:
return getDeclaredType(wrappingType, getOnlyElement(typeArguments));
default:
throw new IllegalArgumentException(type + " has more than 1 type argument");
}
}
/**
* Returns an accessible type in {@code requestingClass}'s package based on {@code type}:
*
* <ul>
* <li>If {@code type} is accessible from the package, returns it.
* <li>If not, but {@code type}'s raw type is accessible from the package, returns the raw type.
* <li>Otherwise returns {@link Object}.
* </ul>
*/
public TypeMirror accessibleType(XType type, ClassName requestingClass) {
return accessibleType(toJavac(type), requestingClass);
}
/**
* Returns an accessible type in {@code requestingClass}'s package based on {@code type}:
*
* <ul>
* <li>If {@code type} is accessible from the package, returns it.
* <li>If not, but {@code type}'s raw type is accessible from the package, returns the raw type.
* <li>Otherwise returns {@link Object}.
* </ul>
*/
public TypeMirror accessibleType(TypeMirror type, ClassName requestingClass) {
return accessibleType(
type,
t -> Accessibility.isTypeAccessibleFrom(t, requestingClass.packageName()),
t -> Accessibility.isRawTypeAccessible(t, requestingClass.packageName()));
}
private TypeMirror accessibleType(
TypeMirror type,
Predicate<TypeMirror> accessibilityPredicate,
Predicate<TypeMirror> rawTypeAccessibilityPredicate) {
if (accessibilityPredicate.test(type)) {
return type;
} else if (type.getKind().equals(TypeKind.DECLARED)
&& rawTypeAccessibilityPredicate.test(type)) {
return getDeclaredType(MoreTypes.asTypeElement(type));
} else {
return elements.getTypeElement(TypeName.OBJECT).asType();
}
}
/**
* Throws {@link TypeNotPresentException} if {@code type} is an {@link
* javax.lang.model.type.ErrorType}.
*/
public static void checkTypePresent(TypeMirror type) {
type.accept(
// TODO(ronshapiro): Extract a base class that visits all components of a complex type
// and put it in auto.common
new SimpleTypeVisitor8<Void, Void>() {
@Override
public Void visitArray(ArrayType arrayType, Void p) {
return arrayType.getComponentType().accept(this, p);
}
@Override
public Void visitDeclared(DeclaredType declaredType, Void p) {
declaredType.getTypeArguments().forEach(t -> t.accept(this, p));
return null;
}
@Override
public Void visitError(ErrorType errorType, Void p) {
throw new TypeNotPresentException(type.toString(), null);
}
},
null);
}
private static final ImmutableSet<Class<?>> FUTURE_TYPES =
ImmutableSet.of(ListenableFuture.class, FluentFuture.class);
public static boolean isFutureType(XType type) {
return isFutureType(toJavac(type));
}
public static boolean isFutureType(TypeMirror type) {
return FUTURE_TYPES.stream().anyMatch(t -> MoreTypes.isTypeOf(t, type));
}
// Implementation of Types methods, delegating to types.
@Override
public Element asElement(TypeMirror t) {
return types.asElement(t);
}
@Override
public boolean isSameType(TypeMirror t1, TypeMirror t2) {
return types.isSameType(t1, t2);
}
public boolean isSubtype(XType t1, XType t2) {
return isSubtype(toJavac(t1), toJavac(t2));
}
@Override
public boolean isSubtype(TypeMirror t1, TypeMirror t2) {
return types.isSubtype(t1, t2);
}
@Override
public boolean isAssignable(TypeMirror t1, TypeMirror t2) {
return types.isAssignable(t1, t2);
}
@Override
public boolean contains(TypeMirror t1, TypeMirror t2) {
return types.contains(t1, t2);
}
@Override
public boolean isSubsignature(ExecutableType m1, ExecutableType m2) {
return types.isSubsignature(m1, m2);
}
@Override
public List<? extends TypeMirror> directSupertypes(TypeMirror t) {
return types.directSupertypes(t);
}
@Override
public TypeMirror erasure(TypeMirror t) {
return types.erasure(t);
}
@Override
public TypeElement boxedClass(PrimitiveType p) {
return types.boxedClass(p);
}
@Override
public PrimitiveType unboxedType(TypeMirror t) {
return types.unboxedType(t);
}
@Override
public TypeMirror capture(TypeMirror t) {
return types.capture(t);
}
@Override
public PrimitiveType getPrimitiveType(TypeKind kind) {
return types.getPrimitiveType(kind);
}
@Override
public NullType getNullType() {
return types.getNullType();
}
@Override
public NoType getNoType(TypeKind kind) {
return types.getNoType(kind);
}
@Override
public ArrayType getArrayType(TypeMirror componentType) {
return types.getArrayType(componentType);
}
@Override
public WildcardType getWildcardType(TypeMirror extendsBound, TypeMirror superBound) {
return types.getWildcardType(extendsBound, superBound);
}
@Override
public DeclaredType getDeclaredType(TypeElement typeElem, TypeMirror... typeArgs) {
return types.getDeclaredType(typeElem, typeArgs);
}
@Override
public DeclaredType getDeclaredType(
DeclaredType containing, TypeElement typeElem, TypeMirror... typeArgs) {
return types.getDeclaredType(containing, typeElem, typeArgs);
}
@Override
public TypeMirror asMemberOf(DeclaredType containing, Element element) {
return types.asMemberOf(containing, element);
}
}
| |
/*******************************************************************************
* Copyright (C) 2015 Google 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.google.cloud.dataflow.sdk.runners.worker;
import static com.google.cloud.dataflow.sdk.util.Structs.getBytes;
import com.google.api.services.dataflow.model.FlattenInstruction;
import com.google.api.services.dataflow.model.InstructionInput;
import com.google.api.services.dataflow.model.InstructionOutput;
import com.google.api.services.dataflow.model.MapTask;
import com.google.api.services.dataflow.model.ParDoInstruction;
import com.google.api.services.dataflow.model.ParallelInstruction;
import com.google.api.services.dataflow.model.PartialGroupByKeyInstruction;
import com.google.api.services.dataflow.model.ReadInstruction;
import com.google.api.services.dataflow.model.WriteInstruction;
import com.google.cloud.dataflow.sdk.coders.Coder;
import com.google.cloud.dataflow.sdk.coders.KvCoder;
import com.google.cloud.dataflow.sdk.options.PipelineOptions;
import com.google.cloud.dataflow.sdk.transforms.Combine;
import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow;
import com.google.cloud.dataflow.sdk.util.CloudObject;
import com.google.cloud.dataflow.sdk.util.CoderUtils;
import com.google.cloud.dataflow.sdk.util.ExecutionContext;
import com.google.cloud.dataflow.sdk.util.PropertyNames;
import com.google.cloud.dataflow.sdk.util.SerializableUtils;
import com.google.cloud.dataflow.sdk.util.Serializer;
import com.google.cloud.dataflow.sdk.util.WindowedValue;
import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder;
import com.google.cloud.dataflow.sdk.util.common.CounterSet;
import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObservable;
import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver;
import com.google.cloud.dataflow.sdk.util.common.worker.FlattenOperation;
import com.google.cloud.dataflow.sdk.util.common.worker.MapTaskExecutor;
import com.google.cloud.dataflow.sdk.util.common.worker.Operation;
import com.google.cloud.dataflow.sdk.util.common.worker.OutputReceiver;
import com.google.cloud.dataflow.sdk.util.common.worker.ParDoFn;
import com.google.cloud.dataflow.sdk.util.common.worker.ParDoOperation;
import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation;
import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation.GroupingKeyCreator;
import com.google.cloud.dataflow.sdk.util.common.worker.ReadOperation;
import com.google.cloud.dataflow.sdk.util.common.worker.Reader;
import com.google.cloud.dataflow.sdk.util.common.worker.ReceivingOperation;
import com.google.cloud.dataflow.sdk.util.common.worker.Sink;
import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler;
import com.google.cloud.dataflow.sdk.util.common.worker.WriteOperation;
import com.google.cloud.dataflow.sdk.values.KV;
import org.joda.time.Instant;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
/**
* Creates a MapTaskExecutor from a MapTask definition.
*/
public class MapTaskExecutorFactory {
/**
* Creates a new MapTaskExecutor from the given MapTask definition.
*/
public static MapTaskExecutor create(
PipelineOptions options, MapTask mapTask, ExecutionContext context) throws Exception {
List<Operation> operations = new ArrayList<>();
CounterSet counters = new CounterSet();
String counterPrefix = mapTask.getStageName() + "-";
StateSampler stateSampler = new StateSampler(counterPrefix, counters.getAddCounterMutator());
// Open-ended state.
stateSampler.setState("other");
// Instantiate operations for each instruction in the graph.
for (ParallelInstruction instruction : mapTask.getInstructions()) {
operations.add(createOperation(options, instruction, context, operations, counterPrefix,
counters.getAddCounterMutator(), stateSampler));
}
return new MapTaskExecutor(operations, counters, stateSampler);
}
/**
* Creates an Operation from the given ParallelInstruction definition.
*/
static Operation createOperation(PipelineOptions options, ParallelInstruction instruction,
ExecutionContext executionContext, List<Operation> priorOperations, String counterPrefix,
CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) throws Exception {
if (instruction.getRead() != null) {
return createReadOperation(options, instruction, executionContext, priorOperations,
counterPrefix, addCounterMutator, stateSampler);
} else if (instruction.getWrite() != null) {
return createWriteOperation(options, instruction, executionContext, priorOperations,
counterPrefix, addCounterMutator, stateSampler);
} else if (instruction.getParDo() != null) {
return createParDoOperation(options, instruction, executionContext, priorOperations,
counterPrefix, addCounterMutator, stateSampler);
} else if (instruction.getPartialGroupByKey() != null) {
return createPartialGroupByKeyOperation(options, instruction, executionContext,
priorOperations, counterPrefix, addCounterMutator, stateSampler);
} else if (instruction.getFlatten() != null) {
return createFlattenOperation(options, instruction, executionContext, priorOperations,
counterPrefix, addCounterMutator, stateSampler);
} else {
throw new Exception("Unexpected instruction: " + instruction);
}
}
static ReadOperation createReadOperation(PipelineOptions options, ParallelInstruction instruction,
ExecutionContext executionContext, List<Operation> priorOperations, String counterPrefix,
CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) throws Exception {
ReadInstruction read = instruction.getRead();
Reader<?> reader = ReaderFactory.create(options, read.getSource(), executionContext);
OutputReceiver[] receivers =
createOutputReceivers(instruction, counterPrefix, addCounterMutator, stateSampler, 1);
return new ReadOperation(instruction.getSystemName(), reader, receivers, counterPrefix,
addCounterMutator, stateSampler);
}
static WriteOperation createWriteOperation(PipelineOptions options,
ParallelInstruction instruction, ExecutionContext executionContext,
List<Operation> priorOperations, String counterPrefix,
CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) throws Exception {
WriteInstruction write = instruction.getWrite();
Sink sink = SinkFactory.create(options, write.getSink(), executionContext);
OutputReceiver[] receivers =
createOutputReceivers(instruction, counterPrefix, addCounterMutator, stateSampler, 0);
WriteOperation operation = new WriteOperation(instruction.getSystemName(), sink, receivers,
counterPrefix, addCounterMutator, stateSampler);
attachInput(operation, write.getInput(), priorOperations);
return operation;
}
static ParDoOperation createParDoOperation(PipelineOptions options,
ParallelInstruction instruction, ExecutionContext executionContext,
List<Operation> priorOperations, String counterPrefix,
CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) throws Exception {
ParDoInstruction parDo = instruction.getParDo();
ParDoFn fn = ParDoFnFactory.create(options, CloudObject.fromSpec(parDo.getUserFn()),
instruction.getSystemName(), parDo.getSideInputs(), parDo.getMultiOutputInfos(),
parDo.getNumOutputs(), executionContext, addCounterMutator, stateSampler);
OutputReceiver[] receivers = createOutputReceivers(
instruction, counterPrefix, addCounterMutator, stateSampler, parDo.getNumOutputs());
ParDoOperation operation = new ParDoOperation(
instruction.getSystemName(), fn, receivers, counterPrefix, addCounterMutator, stateSampler);
attachInput(operation, parDo.getInput(), priorOperations);
return operation;
}
static PartialGroupByKeyOperation createPartialGroupByKeyOperation(PipelineOptions options,
ParallelInstruction instruction, ExecutionContext executionContext,
List<Operation> priorOperations, String counterPrefix,
CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) throws Exception {
PartialGroupByKeyInstruction pgbk = instruction.getPartialGroupByKey();
Coder<?> windowedCoder = Serializer.deserialize(pgbk.getInputElementCodec(), Coder.class);
if (!(windowedCoder instanceof WindowedValueCoder)) {
throw new Exception(
"unexpected kind of input coder for PartialGroupByKeyOperation: " + windowedCoder);
}
Coder<?> elemCoder = ((WindowedValueCoder<?>) windowedCoder).getValueCoder();
if (!(elemCoder instanceof KvCoder)) {
throw new Exception(
"unexpected kind of input element coder for PartialGroupByKeyOperation: " + elemCoder);
}
KvCoder<?, ?> kvCoder = (KvCoder<?, ?>) elemCoder;
Coder<?> keyCoder = kvCoder.getKeyCoder();
Coder<?> valueCoder = kvCoder.getValueCoder();
OutputReceiver[] receivers =
createOutputReceivers(instruction, counterPrefix, addCounterMutator, stateSampler, 1);
PartialGroupByKeyOperation.Combiner valueCombiner = createValueCombiner(pgbk);
PartialGroupByKeyOperation operation = new PartialGroupByKeyOperation(
instruction.getSystemName(),
new WindowingCoderGroupingKeyCreator(keyCoder),
new CoderSizeEstimator(WindowedValue.getValueOnlyCoder(keyCoder)),
new CoderSizeEstimator(valueCoder), 0.001 /*sizeEstimatorSampleRate*/, valueCombiner,
PairInfo.create(), receivers, counterPrefix, addCounterMutator, stateSampler);
attachInput(operation, pgbk.getInput(), priorOperations);
return operation;
}
static ValueCombiner createValueCombiner(PartialGroupByKeyInstruction pgbk) throws Exception {
if (pgbk.getValueCombiningFn() == null) {
return null;
}
Object deserializedFn = SerializableUtils.deserializeFromByteArray(
getBytes(CloudObject.fromSpec(pgbk.getValueCombiningFn()), PropertyNames.SERIALIZED_FN),
"serialized combine fn");
return new ValueCombiner((Combine.KeyedCombineFn) deserializedFn);
}
/**
* Implements PGBKOp.Combiner via Combine.KeyedCombineFn.
*/
public static class ValueCombiner<K, VI, VA, VO>
implements PartialGroupByKeyOperation.Combiner<WindowedValue<K>, VI, VA, VO> {
private final Combine.KeyedCombineFn<K, VI, VA, VO> combineFn;
private ValueCombiner(Combine.KeyedCombineFn<K, VI, VA, VO> combineFn) {
this.combineFn = combineFn;
}
@Override
public VA createAccumulator(WindowedValue<K> windowedKey) {
return this.combineFn.createAccumulator(windowedKey.getValue());
}
@Override
public VA add(WindowedValue<K> windowedKey, VA accumulator, VI value) {
return this.combineFn.addInput(windowedKey.getValue(), accumulator, value);
}
@Override
public VA merge(WindowedValue<K> windowedKey, Iterable<VA> accumulators) {
return this.combineFn.mergeAccumulators(windowedKey.getValue(), accumulators);
}
@Override
public VO extract(WindowedValue<K> windowedKey, VA accumulator) {
return this.combineFn.extractOutput(windowedKey.getValue(), accumulator);
}
}
/**
* Implements PGBKOp.PairInfo via KVs.
*/
public static class PairInfo implements PartialGroupByKeyOperation.PairInfo {
private static PairInfo theInstance = new PairInfo();
public static PairInfo create() {
return theInstance;
}
private PairInfo() {}
@Override
public Object getKeyFromInputPair(Object pair) {
@SuppressWarnings("unchecked")
WindowedValue<KV<?, ?>> windowedKv = (WindowedValue<KV<?, ?>>) pair;
return windowedKv.withValue(windowedKv.getValue().getKey());
}
@Override
public Object getValueFromInputPair(Object pair) {
@SuppressWarnings("unchecked")
WindowedValue<KV<?, ?>> windowedKv = (WindowedValue<KV<?, ?>>) pair;
return windowedKv.getValue().getValue();
}
@Override
public Object makeOutputPair(Object key, Object values) {
WindowedValue<?> windowedKey = (WindowedValue<?>) key;
return windowedKey.withValue(KV.of(windowedKey.getValue(), values));
}
}
/**
* Implements PGBKOp.GroupingKeyCreator via Coder.
*/
// TODO: Actually support window merging in the combiner table.
public static class WindowingCoderGroupingKeyCreator
implements GroupingKeyCreator {
private static final Instant ignored = BoundedWindow.TIMESTAMP_MIN_VALUE;
private final Coder coder;
public WindowingCoderGroupingKeyCreator(Coder coder) {
this.coder = coder;
}
@Override
public Object createGroupingKey(Object key) throws Exception {
WindowedValue<?> windowedKey = (WindowedValue<?>) key;
// Ignore timestamp for grouping purposes.
// The PGBK output will inherit the timestamp of one of its inputs.
return WindowedValue.of(
coder.structuralValue(windowedKey.getValue()),
ignored,
windowedKey.getWindows());
}
}
/**
* Implements PGBKOp.SizeEstimator via Coder.
*/
public static class CoderSizeEstimator implements PartialGroupByKeyOperation.SizeEstimator {
final Coder coder;
public CoderSizeEstimator(Coder coder) {
this.coder = coder;
}
@Override
public long estimateSize(Object value) throws Exception {
return CoderUtils.encodeToByteArray(coder, value).length;
}
}
static FlattenOperation createFlattenOperation(PipelineOptions options,
ParallelInstruction instruction, ExecutionContext executionContext,
List<Operation> priorOperations, String counterPrefix,
CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) throws Exception {
FlattenInstruction flatten = instruction.getFlatten();
OutputReceiver[] receivers =
createOutputReceivers(instruction, counterPrefix, addCounterMutator, stateSampler, 1);
FlattenOperation operation = new FlattenOperation(
instruction.getSystemName(), receivers, counterPrefix, addCounterMutator, stateSampler);
for (InstructionInput input : flatten.getInputs()) {
attachInput(operation, input, priorOperations);
}
return operation;
}
/**
* Returns an array of OutputReceivers for the given
* ParallelInstruction definition.
*/
static OutputReceiver[] createOutputReceivers(ParallelInstruction instruction,
String counterPrefix, CounterSet.AddCounterMutator addCounterMutator,
StateSampler stateSampler, int expectedNumOutputs) throws Exception {
int numOutputs = 0;
if (instruction.getOutputs() != null) {
numOutputs = instruction.getOutputs().size();
}
if (numOutputs != expectedNumOutputs) {
throw new AssertionError("ParallelInstruction.Outputs has an unexpected length");
}
OutputReceiver[] receivers = new OutputReceiver[numOutputs];
for (int i = 0; i < numOutputs; i++) {
InstructionOutput cloudOutput = instruction.getOutputs().get(i);
receivers[i] = new OutputReceiver(cloudOutput.getName(),
new ElementByteSizeObservableCoder(Serializer.deserialize(
cloudOutput.getCodec(), Coder.class)),
counterPrefix, addCounterMutator);
}
return receivers;
}
/**
* Adapts a Coder to the ElementByteSizeObservable interface.
*/
public static class ElementByteSizeObservableCoder<T> implements ElementByteSizeObservable<T> {
final Coder<T> coder;
public ElementByteSizeObservableCoder(Coder<T> coder) {
this.coder = coder;
}
@Override
public boolean isRegisterByteSizeObserverCheap(T value) {
return coder.isRegisterByteSizeObserverCheap(value, Coder.Context.OUTER);
}
@Override
public void registerByteSizeObserver(T value, ElementByteSizeObserver observer)
throws Exception {
coder.registerByteSizeObserver(value, observer, Coder.Context.OUTER);
}
}
/**
* Adds an input to the given Operation, coming from the given
* producer instruction output.
*/
static void attachInput(ReceivingOperation operation, @Nullable InstructionInput input,
List<Operation> priorOperations) {
Integer producerInstructionIndex = 0;
Integer outputNum = 0;
if (input != null) {
if (input.getProducerInstructionIndex() != null) {
producerInstructionIndex = input.getProducerInstructionIndex();
}
if (input.getOutputNum() != null) {
outputNum = input.getOutputNum();
}
}
// Input id must refer to an operation that has already been seen.
Operation source = priorOperations.get(producerInstructionIndex);
operation.attachInput(source, outputNum);
}
}
| |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.widget;
import android.os.Build;
import com.actionbarsherlock.R;
import com.actionbarsherlock.internal.widget.IcsLinearLayout;
import com.actionbarsherlock.internal.widget.IcsListPopupWindow;
import com.actionbarsherlock.view.ActionProvider;
import com.actionbarsherlock.widget.ActivityChooserModel.ActivityChooserModelClient;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
/**
* This class is a view for choosing an activity for handling a given {@link Intent}.
* <p>
* The view is composed of two adjacent buttons:
* <ul>
* <li>
* The left button is an immediate action and allows one click activity choosing.
* Tapping this button immediately executes the intent without requiring any further
* user input. Long press on this button shows a popup for changing the default
* activity.
* </li>
* <li>
* The right button is an overflow action and provides an optimized menu
* of additional activities. Tapping this button shows a popup anchored to this
* view, listing the most frequently used activities. This list is initially
* limited to a small number of items in frequency used order. The last item,
* "Show all..." serves as an affordance to display all available activities.
* </li>
* </ul>
* </p>
*
* @hide
*/
class ActivityChooserView extends ViewGroup implements ActivityChooserModelClient {
/**
* An adapter for displaying the activities in an {@link AdapterView}.
*/
private final ActivityChooserViewAdapter mAdapter;
/**
* Implementation of various interfaces to avoid publishing them in the APIs.
*/
private final Callbacks mCallbacks;
/**
* The content of this view.
*/
private final IcsLinearLayout mActivityChooserContent;
/**
* Stores the background drawable to allow hiding and latter showing.
*/
private final Drawable mActivityChooserContentBackground;
/**
* The expand activities action button;
*/
private final FrameLayout mExpandActivityOverflowButton;
/**
* The image for the expand activities action button;
*/
private final ImageView mExpandActivityOverflowButtonImage;
/**
* The default activities action button;
*/
private final FrameLayout mDefaultActivityButton;
/**
* The image for the default activities action button;
*/
private final ImageView mDefaultActivityButtonImage;
/**
* The maximal width of the list popup.
*/
private final int mListPopupMaxWidth;
/**
* The ActionProvider hosting this view, if applicable.
*/
ActionProvider mProvider;
/**
* Observer for the model data.
*/
private final DataSetObserver mModelDataSetOberver = new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
mAdapter.notifyDataSetChanged();
}
@Override
public void onInvalidated() {
super.onInvalidated();
mAdapter.notifyDataSetInvalidated();
}
};
private final OnGlobalLayoutListener mOnGlobalLayoutListener = new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (isShowingPopup()) {
if (!isShown()) {
getListPopupWindow().dismiss();
} else {
getListPopupWindow().show();
if (mProvider != null) {
mProvider.subUiVisibilityChanged(true);
}
}
}
}
};
/**
* Popup window for showing the activity overflow list.
*/
private IcsListPopupWindow mListPopupWindow;
/**
* Listener for the dismissal of the popup/alert.
*/
private PopupWindow.OnDismissListener mOnDismissListener;
/**
* Flag whether a default activity currently being selected.
*/
private boolean mIsSelectingDefaultActivity;
/**
* The count of activities in the popup.
*/
private int mInitialActivityCount = ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_DEFAULT;
/**
* Flag whether this view is attached to a window.
*/
private boolean mIsAttachedToWindow;
/**
* String resource for formatting content description of the default target.
*/
private int mDefaultActionButtonContentDescription;
private final Context mContext;
/**
* Create a new instance.
*
* @param context The application environment.
*/
public ActivityChooserView(Context context) {
this(context, null);
}
/**
* Create a new instance.
*
* @param context The application environment.
* @param attrs A collection of attributes.
*/
public ActivityChooserView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Create a new instance.
*
* @param context The application environment.
* @param attrs A collection of attributes.
* @param defStyle The default style to apply to this view.
*/
public ActivityChooserView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
TypedArray attributesArray = context.obtainStyledAttributes(attrs,
R.styleable.SherlockActivityChooserView, defStyle, 0);
mInitialActivityCount = attributesArray.getInt(
R.styleable.SherlockActivityChooserView_initialActivityCount,
ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_DEFAULT);
Drawable expandActivityOverflowButtonDrawable = attributesArray.getDrawable(
R.styleable.SherlockActivityChooserView_expandActivityOverflowButtonDrawable);
attributesArray.recycle();
LayoutInflater inflater = LayoutInflater.from(mContext);
inflater.inflate(R.layout.abs__activity_chooser_view, this, true);
mCallbacks = new Callbacks();
mActivityChooserContent = (IcsLinearLayout) findViewById(R.id.abs__activity_chooser_view_content);
mActivityChooserContentBackground = mActivityChooserContent.getBackground();
mDefaultActivityButton = (FrameLayout) findViewById(R.id.abs__default_activity_button);
mDefaultActivityButton.setOnClickListener(mCallbacks);
mDefaultActivityButton.setOnLongClickListener(mCallbacks);
mDefaultActivityButtonImage = (ImageView) mDefaultActivityButton.findViewById(R.id.abs__image);
mExpandActivityOverflowButton = (FrameLayout) findViewById(R.id.abs__expand_activities_button);
mExpandActivityOverflowButton.setOnClickListener(mCallbacks);
mExpandActivityOverflowButtonImage =
(ImageView) mExpandActivityOverflowButton.findViewById(R.id.abs__image);
mExpandActivityOverflowButtonImage.setImageDrawable(expandActivityOverflowButtonDrawable);
mAdapter = new ActivityChooserViewAdapter();
mAdapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
updateAppearance();
}
});
Resources resources = context.getResources();
mListPopupMaxWidth = Math.max(resources.getDisplayMetrics().widthPixels / 2,
resources.getDimensionPixelSize(R.dimen.abs__config_prefDialogWidth));
}
/**
* {@inheritDoc}
*/
public void setActivityChooserModel(ActivityChooserModel dataModel) {
mAdapter.setDataModel(dataModel);
if (isShowingPopup()) {
dismissPopup();
showPopup();
}
}
/**
* Sets the background for the button that expands the activity
* overflow list.
*
* <strong>Note:</strong> Clients would like to set this drawable
* as a clue about the action the chosen activity will perform. For
* example, if a share activity is to be chosen the drawable should
* give a clue that sharing is to be performed.
*
* @param drawable The drawable.
*/
public void setExpandActivityOverflowButtonDrawable(Drawable drawable) {
mExpandActivityOverflowButtonImage.setImageDrawable(drawable);
}
/**
* Sets the content description for the button that expands the activity
* overflow list.
*
* description as a clue about the action performed by the button.
* For example, if a share activity is to be chosen the content
* description should be something like "Share with".
*
* @param resourceId The content description resource id.
*/
public void setExpandActivityOverflowButtonContentDescription(int resourceId) {
CharSequence contentDescription = mContext.getString(resourceId);
mExpandActivityOverflowButtonImage.setContentDescription(contentDescription);
}
/**
* Set the provider hosting this view, if applicable.
* @hide Internal use only
*/
public void setProvider(ActionProvider provider) {
mProvider = provider;
}
/**
* Shows the popup window with activities.
*
* @return True if the popup was shown, false if already showing.
*/
public boolean showPopup() {
if (isShowingPopup() || !mIsAttachedToWindow) {
return false;
}
mIsSelectingDefaultActivity = false;
showPopupUnchecked(mInitialActivityCount);
return true;
}
/**
* Shows the popup no matter if it was already showing.
*
* @param maxActivityCount The max number of activities to display.
*/
private void showPopupUnchecked(int maxActivityCount) {
if (mAdapter.getDataModel() == null) {
throw new IllegalStateException("No data model. Did you call #setDataModel?");
}
getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);
final boolean defaultActivityButtonShown =
mDefaultActivityButton.getVisibility() == VISIBLE;
final int activityCount = mAdapter.getActivityCount();
final int maxActivityCountOffset = defaultActivityButtonShown ? 1 : 0;
if (maxActivityCount != ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED
&& activityCount > maxActivityCount + maxActivityCountOffset) {
mAdapter.setShowFooterView(true);
mAdapter.setMaxActivityCount(maxActivityCount - 1);
} else {
mAdapter.setShowFooterView(false);
mAdapter.setMaxActivityCount(maxActivityCount);
}
IcsListPopupWindow popupWindow = getListPopupWindow();
if (!popupWindow.isShowing()) {
if (mIsSelectingDefaultActivity || !defaultActivityButtonShown) {
mAdapter.setShowDefaultActivity(true, defaultActivityButtonShown);
} else {
mAdapter.setShowDefaultActivity(false, false);
}
final int contentWidth = Math.min(mAdapter.measureContentWidth(), mListPopupMaxWidth);
popupWindow.setContentWidth(contentWidth);
popupWindow.show();
if (mProvider != null) {
mProvider.subUiVisibilityChanged(true);
}
popupWindow.getListView().setContentDescription(mContext.getString(
R.string.abs__activitychooserview_choose_application));
}
}
/**
* Dismisses the popup window with activities.
*
* @return True if dismissed, false if already dismissed.
*/
public boolean dismissPopup() {
if (isShowingPopup()) {
getListPopupWindow().dismiss();
ViewTreeObserver viewTreeObserver = getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.removeGlobalOnLayoutListener(mOnGlobalLayoutListener);
}
}
return true;
}
/**
* Gets whether the popup window with activities is shown.
*
* @return True if the popup is shown.
*/
public boolean isShowingPopup() {
return getListPopupWindow().isShowing();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
ActivityChooserModel dataModel = mAdapter.getDataModel();
if (dataModel != null) {
dataModel.registerObserver(mModelDataSetOberver);
}
mIsAttachedToWindow = true;
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
ActivityChooserModel dataModel = mAdapter.getDataModel();
if (dataModel != null) {
dataModel.unregisterObserver(mModelDataSetOberver);
}
ViewTreeObserver viewTreeObserver = getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.removeGlobalOnLayoutListener(mOnGlobalLayoutListener);
}
mIsAttachedToWindow = false;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
View child = mActivityChooserContent;
// If the default action is not visible we want to be as tall as the
// ActionBar so if this widget is used in the latter it will look as
// a normal action button.
if (mDefaultActivityButton.getVisibility() != VISIBLE) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec),
MeasureSpec.EXACTLY);
}
measureChild(child, widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(child.getMeasuredWidth(), child.getMeasuredHeight());
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
mActivityChooserContent.layout(0, 0, right - left, bottom - top);
if (getListPopupWindow().isShowing()) {
showPopupUnchecked(mAdapter.getMaxActivityCount());
} else {
dismissPopup();
}
}
public ActivityChooserModel getDataModel() {
return mAdapter.getDataModel();
}
/**
* Sets a listener to receive a callback when the popup is dismissed.
*
* @param listener The listener to be notified.
*/
public void setOnDismissListener(PopupWindow.OnDismissListener listener) {
mOnDismissListener = listener;
}
/**
* Sets the initial count of items shown in the activities popup
* i.e. the items before the popup is expanded. This is an upper
* bound since it is not guaranteed that such number of intent
* handlers exist.
*
* @param itemCount The initial popup item count.
*/
public void setInitialActivityCount(int itemCount) {
mInitialActivityCount = itemCount;
}
/**
* Sets a content description of the default action button. This
* resource should be a string taking one formatting argument and
* will be used for formatting the content description of the button
* dynamically as the default target changes. For example, a resource
* pointing to the string "share with %1$s" will result in a content
* description "share with Bluetooth" for the Bluetooth activity.
*
* @param resourceId The resource id.
*/
public void setDefaultActionButtonContentDescription(int resourceId) {
mDefaultActionButtonContentDescription = resourceId;
}
/**
* Gets the list popup window which is lazily initialized.
*
* @return The popup.
*/
private IcsListPopupWindow getListPopupWindow() {
if (mListPopupWindow == null) {
mListPopupWindow = new IcsListPopupWindow(getContext());
mListPopupWindow.setAdapter(mAdapter);
mListPopupWindow.setAnchorView(ActivityChooserView.this);
mListPopupWindow.setModal(true);
mListPopupWindow.setOnItemClickListener(mCallbacks);
mListPopupWindow.setOnDismissListener(mCallbacks);
}
return mListPopupWindow;
}
/**
* Updates the buttons state.
*/
private void updateAppearance() {
// Expand overflow button.
if (mAdapter.getCount() > 0) {
mExpandActivityOverflowButton.setEnabled(true);
} else {
mExpandActivityOverflowButton.setEnabled(false);
}
// Default activity button.
final int activityCount = mAdapter.getActivityCount();
final int historySize = mAdapter.getHistorySize();
if (activityCount > 0 && historySize > 0) {
mDefaultActivityButton.setVisibility(VISIBLE);
ResolveInfo activity = mAdapter.getDefaultActivity();
PackageManager packageManager = mContext.getPackageManager();
mDefaultActivityButtonImage.setImageDrawable(activity.loadIcon(packageManager));
if (mDefaultActionButtonContentDescription != 0) {
CharSequence label = activity.loadLabel(packageManager);
String contentDescription = mContext.getString(
mDefaultActionButtonContentDescription, label);
mDefaultActivityButton.setContentDescription(contentDescription);
}
} else {
mDefaultActivityButton.setVisibility(View.GONE);
}
// Activity chooser content.
if (mDefaultActivityButton.getVisibility() == VISIBLE) {
mActivityChooserContent.setBackgroundDrawable(mActivityChooserContentBackground);
} else {
mActivityChooserContent.setBackgroundDrawable(null);
}
}
/**
* Interface implementation to avoid publishing them in the APIs.
*/
private class Callbacks implements AdapterView.OnItemClickListener,
View.OnClickListener, View.OnLongClickListener, PopupWindow.OnDismissListener {
// AdapterView#OnItemClickListener
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ActivityChooserViewAdapter adapter = (ActivityChooserViewAdapter) parent.getAdapter();
final int itemViewType = adapter.getItemViewType(position);
switch (itemViewType) {
case ActivityChooserViewAdapter.ITEM_VIEW_TYPE_FOOTER: {
showPopupUnchecked(ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED);
} break;
case ActivityChooserViewAdapter.ITEM_VIEW_TYPE_ACTIVITY: {
dismissPopup();
if (mIsSelectingDefaultActivity) {
// The item at position zero is the default already.
if (position > 0) {
mAdapter.getDataModel().setDefaultActivity(position);
}
} else {
// If the default target is not shown in the list, the first
// item in the model is default action => adjust index
position = mAdapter.getShowDefaultActivity() ? position : position + 1;
Intent launchIntent = mAdapter.getDataModel().chooseActivity(position);
if (launchIntent != null) {
mContext.startActivity(launchIntent);
}
}
} break;
default:
throw new IllegalArgumentException();
}
}
// View.OnClickListener
public void onClick(View view) {
if (view == mDefaultActivityButton) {
dismissPopup();
ResolveInfo defaultActivity = mAdapter.getDefaultActivity();
final int index = mAdapter.getDataModel().getActivityIndex(defaultActivity);
Intent launchIntent = mAdapter.getDataModel().chooseActivity(index);
if (launchIntent != null) {
mContext.startActivity(launchIntent);
}
} else if (view == mExpandActivityOverflowButton) {
mIsSelectingDefaultActivity = false;
showPopupUnchecked(mInitialActivityCount);
} else {
throw new IllegalArgumentException();
}
}
// OnLongClickListener#onLongClick
@Override
public boolean onLongClick(View view) {
if (view == mDefaultActivityButton) {
if (mAdapter.getCount() > 0) {
mIsSelectingDefaultActivity = true;
showPopupUnchecked(mInitialActivityCount);
}
} else {
throw new IllegalArgumentException();
}
return true;
}
// PopUpWindow.OnDismissListener#onDismiss
public void onDismiss() {
notifyOnDismissListener();
if (mProvider != null) {
mProvider.subUiVisibilityChanged(false);
}
}
private void notifyOnDismissListener() {
if (mOnDismissListener != null) {
mOnDismissListener.onDismiss();
}
}
}
private static class SetActivated {
public static void invoke(View view, boolean activated) {
view.setActivated(activated);
}
}
private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
/**
* Adapter for backing the list of activities shown in the popup.
*/
private class ActivityChooserViewAdapter extends BaseAdapter {
public static final int MAX_ACTIVITY_COUNT_UNLIMITED = Integer.MAX_VALUE;
public static final int MAX_ACTIVITY_COUNT_DEFAULT = 4;
private static final int ITEM_VIEW_TYPE_ACTIVITY = 0;
private static final int ITEM_VIEW_TYPE_FOOTER = 1;
private static final int ITEM_VIEW_TYPE_COUNT = 3;
private ActivityChooserModel mDataModel;
private int mMaxActivityCount = MAX_ACTIVITY_COUNT_DEFAULT;
private boolean mShowDefaultActivity;
private boolean mHighlightDefaultActivity;
private boolean mShowFooterView;
public void setDataModel(ActivityChooserModel dataModel) {
ActivityChooserModel oldDataModel = mAdapter.getDataModel();
if (oldDataModel != null && isShown()) {
oldDataModel.unregisterObserver(mModelDataSetOberver);
}
mDataModel = dataModel;
if (dataModel != null && isShown()) {
dataModel.registerObserver(mModelDataSetOberver);
}
notifyDataSetChanged();
}
@Override
public int getItemViewType(int position) {
if (mShowFooterView && position == getCount() - 1) {
return ITEM_VIEW_TYPE_FOOTER;
} else {
return ITEM_VIEW_TYPE_ACTIVITY;
}
}
@Override
public int getViewTypeCount() {
return ITEM_VIEW_TYPE_COUNT;
}
public int getCount() {
int count = 0;
int activityCount = mDataModel.getActivityCount();
if (!mShowDefaultActivity && mDataModel.getDefaultActivity() != null) {
activityCount--;
}
count = Math.min(activityCount, mMaxActivityCount);
if (mShowFooterView) {
count++;
}
return count;
}
public Object getItem(int position) {
final int itemViewType = getItemViewType(position);
switch (itemViewType) {
case ITEM_VIEW_TYPE_FOOTER:
return null;
case ITEM_VIEW_TYPE_ACTIVITY:
if (!mShowDefaultActivity && mDataModel.getDefaultActivity() != null) {
position++;
}
return mDataModel.getActivity(position);
default:
throw new IllegalArgumentException();
}
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final int itemViewType = getItemViewType(position);
switch (itemViewType) {
case ITEM_VIEW_TYPE_FOOTER:
if (convertView == null || convertView.getId() != ITEM_VIEW_TYPE_FOOTER) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.abs__activity_chooser_view_list_item, parent, false);
convertView.setId(ITEM_VIEW_TYPE_FOOTER);
TextView titleView = (TextView) convertView.findViewById(R.id.abs__title);
titleView.setText(mContext.getString(
R.string.abs__activity_chooser_view_see_all));
}
return convertView;
case ITEM_VIEW_TYPE_ACTIVITY:
if (convertView == null || convertView.getId() != R.id.abs__list_item) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.abs__activity_chooser_view_list_item, parent, false);
}
PackageManager packageManager = mContext.getPackageManager();
// Set the icon
ImageView iconView = (ImageView) convertView.findViewById(R.id.abs__icon);
ResolveInfo activity = (ResolveInfo) getItem(position);
iconView.setImageDrawable(activity.loadIcon(packageManager));
// Set the title.
TextView titleView = (TextView) convertView.findViewById(R.id.abs__title);
titleView.setText(activity.loadLabel(packageManager));
if (IS_HONEYCOMB) {
// Highlight the default.
if (mShowDefaultActivity && position == 0 && mHighlightDefaultActivity) {
SetActivated.invoke(convertView, true);
} else {
SetActivated.invoke(convertView, false);
}
}
return convertView;
default:
throw new IllegalArgumentException();
}
}
public int measureContentWidth() {
// The user may have specified some of the target not to be shown but we
// want to measure all of them since after expansion they should fit.
final int oldMaxActivityCount = mMaxActivityCount;
mMaxActivityCount = MAX_ACTIVITY_COUNT_UNLIMITED;
int contentWidth = 0;
View itemView = null;
final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
final int count = getCount();
for (int i = 0; i < count; i++) {
itemView = getView(i, itemView, null);
itemView.measure(widthMeasureSpec, heightMeasureSpec);
contentWidth = Math.max(contentWidth, itemView.getMeasuredWidth());
}
mMaxActivityCount = oldMaxActivityCount;
return contentWidth;
}
public void setMaxActivityCount(int maxActivityCount) {
if (mMaxActivityCount != maxActivityCount) {
mMaxActivityCount = maxActivityCount;
notifyDataSetChanged();
}
}
public ResolveInfo getDefaultActivity() {
return mDataModel.getDefaultActivity();
}
public void setShowFooterView(boolean showFooterView) {
if (mShowFooterView != showFooterView) {
mShowFooterView = showFooterView;
notifyDataSetChanged();
}
}
public int getActivityCount() {
return mDataModel.getActivityCount();
}
public int getHistorySize() {
return mDataModel.getHistorySize();
}
public int getMaxActivityCount() {
return mMaxActivityCount;
}
public ActivityChooserModel getDataModel() {
return mDataModel;
}
public void setShowDefaultActivity(boolean showDefaultActivity,
boolean highlightDefaultActivity) {
if (mShowDefaultActivity != showDefaultActivity
|| mHighlightDefaultActivity != highlightDefaultActivity) {
mShowDefaultActivity = showDefaultActivity;
mHighlightDefaultActivity = highlightDefaultActivity;
notifyDataSetChanged();
}
}
public boolean getShowDefaultActivity() {
return mShowDefaultActivity;
}
}
}
| |
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* 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.uberfire.backend.vfs.impl;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import org.jboss.errai.common.client.api.annotations.Portable;
import org.jboss.errai.ioc.client.container.IOC;
import org.jboss.errai.security.shared.api.identity.User;
import org.uberfire.backend.vfs.IsVersioned;
import org.uberfire.backend.vfs.ObservablePath;
import org.uberfire.backend.vfs.Path;
import org.uberfire.mvp.Command;
import org.uberfire.mvp.ParameterizedCommand;
import org.uberfire.rpc.SessionInfo;
import org.uberfire.workbench.events.ResourceBatchChangesEvent;
import org.uberfire.workbench.events.ResourceChange;
import org.uberfire.workbench.events.ResourceCopied;
import org.uberfire.workbench.events.ResourceCopiedEvent;
import org.uberfire.workbench.events.ResourceDeletedEvent;
import org.uberfire.workbench.events.ResourceRenamed;
import org.uberfire.workbench.events.ResourceRenamedEvent;
import org.uberfire.workbench.events.ResourceUpdatedEvent;
@Portable
@Dependent
public class ObservablePathImpl implements ObservablePath,
IsVersioned {
private Path path;
private transient Path original;
@Inject
private transient SessionInfo sessionInfo;
private transient List<Command> onRenameCommand = new ArrayList<Command>();
private transient List<Command> onDeleteCommand = new ArrayList<Command>();
private transient List<Command> onUpdateCommand = new ArrayList<Command>();
private transient List<Command> onCopyCommand = new ArrayList<Command>();
private transient List<ParameterizedCommand<OnConcurrentRenameEvent>> onConcurrentRenameCommand = new ArrayList<ParameterizedCommand<OnConcurrentRenameEvent>>();
private transient List<ParameterizedCommand<OnConcurrentDelete>> onConcurrentDeleteCommand = new ArrayList<ParameterizedCommand<OnConcurrentDelete>>();
private transient List<ParameterizedCommand<OnConcurrentUpdateEvent>> onConcurrentUpdateCommand = new ArrayList<ParameterizedCommand<OnConcurrentUpdateEvent>>();
private transient List<ParameterizedCommand<OnConcurrentCopyEvent>> onConcurrentCopyCommand = new ArrayList<ParameterizedCommand<OnConcurrentCopyEvent>>();
public ObservablePathImpl() {
}
@Override
public ObservablePath wrap( final Path path ) {
if ( path instanceof ObservablePathImpl ) {
this.original = ( (ObservablePathImpl) path ).path;
} else {
this.original = path;
}
this.path = this.original;
return this;
}
// Lazy-population of "original" for ObservablePathImpl de-serialized from a serialized PerspectiveDefinition that circumvent the "wrap" feature.
// Renamed resources hold a reference to the old "original" Path which is needed to maintain an immutable hashCode used as part of the compound
// Key for Activity and Place Management). However re-hydration stores the PartDefinition in a HashSet using the incorrect hashCode. By not
// storing the "original" in the serialized form we can guarantee hashCodes in de-serialized PerspectiveDefinitions remain immutable.
// See https://bugzilla.redhat.com/show_bug.cgi?id=1200472 for the re-producer.
public Path getOriginal() {
if ( this.original == null ) {
wrap( this.path );
}
return this.original;
}
@Override
public String getFileName() {
return path.getFileName();
}
public static String removeExtension( final String filename ) {
if ( filename == null ) {
return null;
}
final int index = indexOfExtension( filename );
if ( index == -1 ) {
return filename;
} else {
return filename.substring( 0, index );
}
}
public static int indexOfExtension( final String filename ) {
if ( filename == null ) {
return -1;
}
final int extensionPos = filename.lastIndexOf( "." );
return extensionPos;
}
@Override
public String toURI() {
return path.toURI();
}
@Override
public boolean hasVersionSupport() {
return path instanceof IsVersioned && ( (IsVersioned) path ).hasVersionSupport();
}
@Override
public int compareTo( final Path o ) {
return path.compareTo( o );
}
@Override
public void onRename( final Command command ) {
this.onRenameCommand.add( command );
}
@Override
public void onDelete( final Command command ) {
this.onDeleteCommand.add( command );
}
@Override
public void onUpdate( final Command command ) {
this.onUpdateCommand.add( command );
}
@Override
public void onCopy( final Command command ) {
this.onCopyCommand.add( command );
}
@Override
public void onConcurrentRename( final ParameterizedCommand<OnConcurrentRenameEvent> command ) {
this.onConcurrentRenameCommand.add( command );
}
@Override
public void onConcurrentDelete( final ParameterizedCommand<OnConcurrentDelete> command ) {
this.onConcurrentDeleteCommand.add( command );
}
@Override
public void onConcurrentUpdate( final ParameterizedCommand<OnConcurrentUpdateEvent> command ) {
this.onConcurrentUpdateCommand.add( command );
}
@Override
public void onConcurrentCopy( final ParameterizedCommand<OnConcurrentCopyEvent> command ) {
this.onConcurrentCopyCommand.add( command );
}
@Override
public void dispose() {
onRenameCommand.clear();
onDeleteCommand.clear();
onUpdateCommand.clear();
onCopyCommand.clear();
onConcurrentRenameCommand.clear();
onConcurrentDeleteCommand.clear();
onConcurrentUpdateCommand.clear();
onConcurrentCopyCommand.clear();
if ( IOC.getBeanManager() != null ) {
IOC.getBeanManager().destroyBean( this );
}
}
void onResourceRenamed( @Observes final ResourceRenamedEvent renamedEvent ) {
if ( path != null && path.equals( renamedEvent.getPath() ) ) {
path = renamedEvent.getDestinationPath();
if ( sessionInfo.getId().equals( renamedEvent.getSessionInfo().getId() ) ) {
executeRenameCommands();
} else {
executeConcurrentRenameCommand( renamedEvent.getPath(),
renamedEvent.getDestinationPath(),
renamedEvent.getSessionInfo().getId(),
renamedEvent.getSessionInfo().getIdentity() );
}
}
}
void onResourceDeleted( @Observes final ResourceDeletedEvent deletedEvent ) {
if ( path != null && path.equals( deletedEvent.getPath() ) ) {
if ( sessionInfo.getId().equals( deletedEvent.getSessionInfo().getId() ) ) {
executeDeleteCommands();
} else {
executeConcurrentDeleteCommand( deletedEvent.getPath(),
deletedEvent.getSessionInfo().getId(),
deletedEvent.getSessionInfo().getIdentity() );
}
}
}
void onResourceUpdated( @Observes final ResourceUpdatedEvent updatedEvent ) {
if ( path != null && path.equals( updatedEvent.getPath() ) ) {
if ( sessionInfo.getId().equals( updatedEvent.getSessionInfo().getId() ) ) {
executeUpdateCommands();
} else {
executeConcurrentUpdateCommand( updatedEvent.getPath(),
updatedEvent.getSessionInfo().getId(),
updatedEvent.getSessionInfo().getIdentity() );
}
}
}
void onResourceCopied( @Observes final ResourceCopiedEvent copiedEvent ) {
if ( path != null && path.equals( copiedEvent.getPath() ) ) {
if ( sessionInfo.getId().equals( copiedEvent.getSessionInfo().getId() ) ) {
executeCopyCommands();
} else {
executeConcurrentCopyCommand( copiedEvent.getPath(),
copiedEvent.getDestinationPath(),
copiedEvent.getSessionInfo().getId(),
copiedEvent.getSessionInfo().getIdentity() );
}
}
}
void onResourceBatchEvent( @Observes final ResourceBatchChangesEvent batchEvent ) {
if ( path != null && batchEvent.containPath( path ) ) {
if ( sessionInfo.getId().equals( batchEvent.getSessionInfo().getId() ) ) {
for ( final ResourceChange change : batchEvent.getChanges( path ) ) {
switch ( change.getType() ) {
case COPY:
executeCopyCommands();
break;
case DELETE:
executeDeleteCommands();
break;
case RENAME:
path = ( (ResourceRenamed) change ).getDestinationPath();
executeRenameCommands();
break;
case UPDATE:
executeUpdateCommands();
break;
}
}
} else {
for ( final ResourceChange change : batchEvent.getChanges( path ) ) {
switch ( change.getType() ) {
case COPY:
executeConcurrentCopyCommand( path,
( (ResourceCopied) change ).getDestinationPath(),
batchEvent.getSessionInfo().getId(),
batchEvent.getSessionInfo().getIdentity() );
break;
case DELETE:
executeConcurrentDeleteCommand( path,
batchEvent.getSessionInfo().getId(),
batchEvent.getSessionInfo().getIdentity() );
break;
case RENAME:
path = ( (ResourceRenamed) change ).getDestinationPath();
executeConcurrentRenameCommand( path,
( (ResourceRenamed) change ).getDestinationPath(),
batchEvent.getSessionInfo().getId(),
batchEvent.getSessionInfo().getIdentity() );
break;
case UPDATE:
executeConcurrentUpdateCommand( path,
batchEvent.getSessionInfo().getId(),
batchEvent.getSessionInfo().getIdentity() );
break;
}
}
}
}
}
private void executeRenameCommands() {
if ( !onRenameCommand.isEmpty() ) {
for ( final Command command : onRenameCommand ) {
command.execute();
}
}
}
private void executeConcurrentRenameCommand( final Path path,
final Path destinationPath,
final String sessionId,
final User identity ) {
if ( !onConcurrentRenameCommand.isEmpty() ) {
for ( final ParameterizedCommand<OnConcurrentRenameEvent> command : onConcurrentRenameCommand ) {
final OnConcurrentRenameEvent event = new OnConcurrentRenameEvent() {
@Override
public Path getSource() {
return path;
}
@Override
public Path getTarget() {
return destinationPath;
}
@Override
public String getId() {
return sessionId;
}
@Override
public User getIdentity() {
return identity;
}
};
command.execute( event );
}
}
}
private void executeCopyCommands() {
if ( !onCopyCommand.isEmpty() ) {
for ( final Command command : onCopyCommand ) {
command.execute();
}
}
}
private void executeConcurrentCopyCommand( final Path path,
final Path destinationPath,
final String sessionId,
final User identity ) {
if ( !onConcurrentCopyCommand.isEmpty() ) {
final OnConcurrentCopyEvent copyEvent = new OnConcurrentCopyEvent() {
@Override
public Path getSource() {
return path;
}
@Override
public Path getTarget() {
return destinationPath;
}
@Override
public String getId() {
return sessionId;
}
@Override
public User getIdentity() {
return identity;
}
};
for ( final ParameterizedCommand<OnConcurrentCopyEvent> command : onConcurrentCopyCommand ) {
command.execute( copyEvent );
}
}
}
private void executeUpdateCommands() {
if ( !onUpdateCommand.isEmpty() ) {
for ( final Command command : onUpdateCommand ) {
command.execute();
}
}
}
private void executeConcurrentUpdateCommand( final Path path,
final String sessionId,
final User identity ) {
if ( !onConcurrentUpdateCommand.isEmpty() ) {
final OnConcurrentUpdateEvent event = new OnConcurrentUpdateEvent() {
@Override
public Path getPath() {
return path;
}
@Override
public String getId() {
return sessionId;
}
@Override
public User getIdentity() {
return identity;
}
};
for ( final ParameterizedCommand<OnConcurrentUpdateEvent> command : onConcurrentUpdateCommand ) {
command.execute( event );
}
}
}
private void executeDeleteCommands() {
if ( !onDeleteCommand.isEmpty() ) {
for ( final Command command : onDeleteCommand ) {
command.execute();
}
}
}
private void executeConcurrentDeleteCommand( final Path path,
final String sessionId,
final User identity ) {
if ( !onConcurrentDeleteCommand.isEmpty() ) {
final OnConcurrentDelete event = new OnConcurrentDelete() {
@Override
public Path getPath() {
return path;
}
@Override
public String getId() {
return sessionId;
}
@Override
public User getIdentity() {
return identity;
}
};
for ( final ParameterizedCommand<OnConcurrentDelete> command : onConcurrentDeleteCommand ) {
command.execute( event );
}
}
}
@Override
public boolean equals( Object o ) {
if ( this == o ) {
return true;
}
if ( !( o instanceof Path ) ) {
return false;
}
if ( o instanceof ObservablePathImpl ) {
return this.getOriginal().equals( ( (ObservablePathImpl) o ).getOriginal() );
}
return this.getOriginal().equals( o );
}
@Override
public int hashCode() {
return this.getOriginal().toURI().hashCode();
}
@Override
public String toString() {
return toURI();
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.mapper.core;
import com.carrotsearch.hppc.DoubleArrayList;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.Terms;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.NumericUtils;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.action.fieldstats.FieldStats;
import org.elasticsearch.common.Explicit;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Numbers;
import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.util.ByteUtils;
import org.elasticsearch.common.util.CollectionUtils;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.analysis.NumericDoubleAnalyzer;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.fielddata.IndexNumericFieldData;
import org.elasticsearch.index.mapper.Mapper;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.MergeResult;
import org.elasticsearch.index.mapper.MergeMappingException;
import org.elasticsearch.index.mapper.ParseContext;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.search.NumericRangeFieldDataFilter;
import org.elasticsearch.index.similarity.SimilarityProvider;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeDoubleValue;
import static org.elasticsearch.index.mapper.MapperBuilders.doubleField;
import static org.elasticsearch.index.mapper.core.TypeParsers.parseNumberField;
/**
*
*/
public class DoubleFieldMapper extends NumberFieldMapper<Double> {
public static final String CONTENT_TYPE = "double";
public static class Defaults extends NumberFieldMapper.Defaults {
public static final FieldType FIELD_TYPE = new FieldType(NumberFieldMapper.Defaults.FIELD_TYPE);
static {
FIELD_TYPE.freeze();
}
public static final Double NULL_VALUE = null;
}
public static class Builder extends NumberFieldMapper.Builder<Builder, DoubleFieldMapper> {
protected Double nullValue = Defaults.NULL_VALUE;
public Builder(String name) {
super(name, new FieldType(Defaults.FIELD_TYPE), Defaults.PRECISION_STEP_64_BIT);
builder = this;
}
public Builder nullValue(double nullValue) {
this.nullValue = nullValue;
return this;
}
@Override
public DoubleFieldMapper build(BuilderContext context) {
fieldType.setOmitNorms(fieldType.omitNorms() && boost == 1.0f);
DoubleFieldMapper fieldMapper = new DoubleFieldMapper(buildNames(context),
fieldType.numericPrecisionStep(), boost, fieldType, docValues, nullValue, ignoreMalformed(context), coerce(context),
similarity, normsLoading, fieldDataSettings, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo);
fieldMapper.includeInAll(includeInAll);
return fieldMapper;
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
DoubleFieldMapper.Builder builder = doubleField(name);
parseNumberField(builder, name, node, parserContext);
for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, Object> entry = iterator.next();
String propName = entry.getKey();
Object propNode = entry.getValue();
if (propName.equals("nullValue") || propName.equals("null_value")) {
if (propNode == null) {
throw new MapperParsingException("Property [null_value] cannot be null.");
}
builder.nullValue(nodeDoubleValue(propNode));
iterator.remove();
}
}
return builder;
}
}
private Double nullValue;
private String nullValueAsString;
protected DoubleFieldMapper(Names names, int precisionStep, float boost, FieldType fieldType, Boolean docValues,
Double nullValue, Explicit<Boolean> ignoreMalformed, Explicit<Boolean> coerce,
SimilarityProvider similarity, Loading normsLoading, @Nullable Settings fieldDataSettings,
Settings indexSettings, MultiFields multiFields, CopyTo copyTo) {
super(names, precisionStep, boost, fieldType, docValues, ignoreMalformed, coerce,
NumericDoubleAnalyzer.buildNamedAnalyzer(precisionStep), NumericDoubleAnalyzer.buildNamedAnalyzer(Integer.MAX_VALUE),
similarity, normsLoading, fieldDataSettings, indexSettings, multiFields, copyTo);
this.nullValue = nullValue;
this.nullValueAsString = nullValue == null ? null : nullValue.toString();
}
@Override
public FieldType defaultFieldType() {
return Defaults.FIELD_TYPE;
}
@Override
public FieldDataType defaultFieldDataType() {
return new FieldDataType("double");
}
@Override
protected int maxPrecisionStep() {
return 64;
}
@Override
public Double value(Object value) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).doubleValue();
}
if (value instanceof BytesRef) {
return Numbers.bytesToDouble((BytesRef) value);
}
return Double.parseDouble(value.toString());
}
@Override
public BytesRef indexedValueForSearch(Object value) {
long longValue = NumericUtils.doubleToSortableLong(parseDoubleValue(value));
BytesRefBuilder bytesRef = new BytesRefBuilder();
NumericUtils.longToPrefixCoded(longValue, 0, bytesRef); // 0 because of exact match
return bytesRef.get();
}
@Override
public Query fuzzyQuery(String value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions) {
double iValue = Double.parseDouble(value);
double iSim = fuzziness.asDouble();
return NumericRangeQuery.newDoubleRange(names.indexName(), precisionStep,
iValue - iSim,
iValue + iSim,
true, true);
}
@Override
public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
return NumericRangeQuery.newDoubleRange(names.indexName(), precisionStep,
lowerTerm == null ? null : parseDoubleValue(lowerTerm),
upperTerm == null ? null : parseDoubleValue(upperTerm),
includeLower, includeUpper);
}
@Override
public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
return Queries.wrap(NumericRangeQuery.newDoubleRange(names.indexName(), precisionStep,
lowerTerm == null ? null : parseDoubleValue(lowerTerm),
upperTerm == null ? null : parseDoubleValue(upperTerm),
includeLower, includeUpper));
}
public Filter rangeFilter(Double lowerTerm, Double upperTerm, boolean includeLower, boolean includeUpper) {
return Queries.wrap(NumericRangeQuery.newDoubleRange(names.indexName(), precisionStep, lowerTerm, upperTerm, includeLower, includeUpper));
}
@Override
public Filter rangeFilter(QueryParseContext parseContext, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
return NumericRangeFieldDataFilter.newDoubleRange((IndexNumericFieldData) parseContext.getForField(this),
lowerTerm == null ? null : parseDoubleValue(lowerTerm),
upperTerm == null ? null : parseDoubleValue(upperTerm),
includeLower, includeUpper);
}
@Override
public Filter nullValueFilter() {
if (nullValue == null) {
return null;
}
return Queries.wrap(NumericRangeQuery.newDoubleRange(names.indexName(), precisionStep,
nullValue,
nullValue,
true, true));
}
@Override
protected boolean customBoost() {
return true;
}
@Override
protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException {
double value;
float boost = this.boost;
if (context.externalValueSet()) {
Object externalValue = context.externalValue();
if (externalValue == null) {
if (nullValue == null) {
return;
}
value = nullValue;
} else if (externalValue instanceof String) {
String sExternalValue = (String) externalValue;
if (sExternalValue.length() == 0) {
if (nullValue == null) {
return;
}
value = nullValue;
} else {
value = Double.parseDouble(sExternalValue);
}
} else {
value = ((Number) externalValue).doubleValue();
}
if (context.includeInAll(includeInAll, this)) {
context.allEntries().addText(names.fullName(), Double.toString(value), boost);
}
} else {
XContentParser parser = context.parser();
if (parser.currentToken() == XContentParser.Token.VALUE_NULL ||
(parser.currentToken() == XContentParser.Token.VALUE_STRING && parser.textLength() == 0)) {
if (nullValue == null) {
return;
}
value = nullValue;
if (nullValueAsString != null && (context.includeInAll(includeInAll, this))) {
context.allEntries().addText(names.fullName(), nullValueAsString, boost);
}
} else if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
XContentParser.Token token;
String currentFieldName = null;
Double objValue = nullValue;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else {
if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) {
if (parser.currentToken() != XContentParser.Token.VALUE_NULL) {
objValue = parser.doubleValue(coerce.value());
}
} else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) {
boost = parser.floatValue();
} else {
throw new ElasticsearchIllegalArgumentException("unknown property [" + currentFieldName + "]");
}
}
}
if (objValue == null) {
// no value
return;
}
value = objValue;
} else {
value = parser.doubleValue(coerce.value());
if (context.includeInAll(includeInAll, this)) {
context.allEntries().addText(names.fullName(), parser.text(), boost);
}
}
}
if (fieldType.indexOptions() != IndexOptions.NONE || fieldType.stored()) {
CustomDoubleNumericField field = new CustomDoubleNumericField(this, value, fieldType);
field.setBoost(boost);
fields.add(field);
}
if (hasDocValues()) {
if (useSortedNumericDocValues) {
addDocValue(context, fields, NumericUtils.doubleToSortableLong(value));
} else {
CustomDoubleNumericDocValuesField field = (CustomDoubleNumericDocValuesField) context.doc().getByKey(names().indexName());
if (field != null) {
field.add(value);
} else {
field = new CustomDoubleNumericDocValuesField(names().indexName(), value);
context.doc().addWithKey(names().indexName(), field);
}
}
}
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
public void merge(Mapper mergeWith, MergeResult mergeResult) throws MergeMappingException {
super.merge(mergeWith, mergeResult);
if (!this.getClass().equals(mergeWith.getClass())) {
return;
}
if (!mergeResult.simulate()) {
this.nullValue = ((DoubleFieldMapper) mergeWith).nullValue;
this.nullValueAsString = ((DoubleFieldMapper) mergeWith).nullValueAsString;
}
}
@Override
protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
super.doXContentBody(builder, includeDefaults, params);
if (includeDefaults || precisionStep != Defaults.PRECISION_STEP_64_BIT) {
builder.field("precision_step", precisionStep);
}
if (includeDefaults || nullValue != null) {
builder.field("null_value", nullValue);
}
if (includeInAll != null) {
builder.field("include_in_all", includeInAll);
} else if (includeDefaults) {
builder.field("include_in_all", false);
}
}
@Override
public FieldStats stats(Terms terms, int maxDoc) throws IOException {
double minValue = NumericUtils.sortableLongToDouble(NumericUtils.getMinLong(terms));
double maxValue = NumericUtils.sortableLongToDouble(NumericUtils.getMaxLong(terms));
return new FieldStats.Double(
maxDoc, terms.getDocCount(), terms.getSumDocFreq(), terms.getSumTotalTermFreq(), minValue, maxValue
);
}
public static class CustomDoubleNumericField extends CustomNumericField {
private final double number;
private final NumberFieldMapper mapper;
public CustomDoubleNumericField(NumberFieldMapper mapper, double number, FieldType fieldType) {
super(mapper, number, fieldType);
this.mapper = mapper;
this.number = number;
}
@Override
public TokenStream tokenStream(Analyzer analyzer, TokenStream previous) throws IOException {
if (fieldType().indexOptions() != IndexOptions.NONE) {
return mapper.popCachedStream().setDoubleValue(number);
}
return null;
}
@Override
public String numericAsString() {
return Double.toString(number);
}
}
public static class CustomDoubleNumericDocValuesField extends CustomNumericDocValuesField {
public static final FieldType TYPE = new FieldType();
static {
TYPE.setDocValuesType(DocValuesType.BINARY);
TYPE.freeze();
}
private final DoubleArrayList values;
public CustomDoubleNumericDocValuesField(String name, double value) {
super(name);
values = new DoubleArrayList();
add(value);
}
public void add(double value) {
values.add(value);
}
@Override
public BytesRef binaryValue() {
CollectionUtils.sortAndDedup(values);
final byte[] bytes = new byte[values.size() * 8];
for (int i = 0; i < values.size(); ++i) {
ByteUtils.writeDoubleLE(values.get(i), bytes, i * 8);
}
return new BytesRef(bytes);
}
}
}
| |
/**
* SignatureActivity.java
* UL OCR Project
*
* Created by Gan Jianping on 02/10/13.
* Copyright (c) 2013 DBS. All rights reserved.
*/
package sg.lt.obs;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import org.ganjp.glib.core.entity.Response;
import org.ganjp.glib.core.util.DateUtil;
import org.ganjp.glib.core.util.DialogUtil;
import org.ganjp.glib.core.util.FileUtil;
import org.ganjp.glib.core.util.HttpConnection;
import org.ganjp.glib.core.util.ImageUtil;
import org.ganjp.glib.core.util.StringUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import sg.lt.obs.common.ObsConst;
import sg.lt.obs.common.other.ObsUtil;
import sg.lt.obs.common.other.PreferenceUtil;
import sg.lt.obs.common.view.CustomeFontButton;
public class SignatureActivity extends Activity {
private String tag = "Signature";
RelativeLayout mContent;
LinearLayout mResult;
signature mSignature;
CustomeFontButton mClear, mGetSign, mCancel;
public static String tempDir;
public int count = 1;
public String current = null;
private Bitmap mBitmap;
View mView;
File mypath;
private String uniqueId;
private Context context;
private String mBookingVehicleItemId;
private String mBookingNumber;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.signature_activity);
context = this;
tempDir = Environment.getExternalStorageDirectory() + "/tmp/";
prepareDirectory();
uniqueId = getTodaysDate() + "_" + getCurrentTime() + "_" + Math.random();
current = uniqueId + ".jpg";
Intent intent = getIntent();
mBookingVehicleItemId = intent.getStringExtra(ObsConst.KEY_BOOKING_VEHICLE_ITEM_ID);
mBookingNumber = intent.getStringExtra(ObsConst.KEY_BOOKING_NUMBER);
String signatureFullPath = intent.getStringExtra(ObsConst.KEY_FILE_FULL_PATH);
mypath = FileUtil.createFile(signatureFullPath);
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
int option = (int ) Math.floor((width - 100) / 208);
mContent = (RelativeLayout) findViewById(R.id.linearLayout);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(208*option, 95*option); // or wrap_content
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
mSignature = new signature(this, null);
mSignature.setBackgroundColor(getResources().getColor(R.color.white));
mSignature.setLayoutParams(layoutParams);
mContent.addView(mSignature);
mClear = (CustomeFontButton) findViewById(R.id.clear);
mGetSign = (CustomeFontButton) findViewById(R.id.getsign);
mGetSign.setEnabled(false);
mCancel = (CustomeFontButton) findViewById(R.id.cancel);
mView = mSignature;
mClear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mSignature.clear();
mGetSign.setEnabled(false);
}
});
mGetSign.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
boolean error = captureSignature();
if (!error) {
mView.setDrawingCacheEnabled(true);
mSignature.save(mView);
//ImageUtil.addWaterMark(mypath, "valid for limousineTransport");
String signaturePathBookingVehicleItemIds = PreferenceUtil.getString(ObsConst.KEY_SIGNATURE_PATH_BOOKING_VEHICLE_ITEM_IDS);
String value = mypath.getAbsolutePath() + "," + mBookingVehicleItemId;
if (StringUtil.hasText(signaturePathBookingVehicleItemIds)) {
if (signaturePathBookingVehicleItemIds.indexOf(value)==-1) {
signaturePathBookingVehicleItemIds += ";" + value;
}
} else {
signaturePathBookingVehicleItemIds = value;
}
PreferenceUtil.saveString(ObsConst.KEY_SIGNATURE_PATH_BOOKING_VEHICLE_ITEM_IDS, signaturePathBookingVehicleItemIds);
String[] signaturePathBookingVehicleItemIdArr = signaturePathBookingVehicleItemIds.split(";");
for (String signaturePathBookingVehicleItemId : signaturePathBookingVehicleItemIdArr) {
final String[] arr = signaturePathBookingVehicleItemId.split(",");
new ObsUtil.UploadSignatureTask(context).execute(ObsConst.URL_UPLOAD_SIGNATURE, arr[0], arr[1]);
}
PreferenceUtil.saveString(ObsConst.KEY_FILE_FULL_PATH, mypath.getAbsolutePath());
finish();
}
}
});
mCancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Bundle b = new Bundle();
b.putString("status", "cancel");
Intent intent = new Intent();
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
}
});
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
private boolean captureSignature() {
boolean error = false;
String errorMessage = "";
if (error) {
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, 105, 50);
toast.show();
}
return error;
}
private String getTodaysDate() {
final Calendar c = Calendar.getInstance();
int todaysDate = (c.get(Calendar.YEAR) * 10000)
+ ((c.get(Calendar.MONTH) + 1) * 100)
+ (c.get(Calendar.DAY_OF_MONTH));
return (String.valueOf(todaysDate));
}
private String getCurrentTime() {
final Calendar c = Calendar.getInstance();
int currentTime = (c.get(Calendar.HOUR_OF_DAY) * 10000)
+ (c.get(Calendar.MINUTE) * 100) + (c.get(Calendar.SECOND));
return (String.valueOf(currentTime));
}
private boolean prepareDirectory() {
try {
if (makedirs()) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
private boolean makedirs() {
File tempdir = new File(tempDir);
if (!tempdir.exists())
tempdir.mkdirs();
if (tempdir.isDirectory()) {
File[] files = tempdir.listFiles();
for (File file : files) {
if (!file.delete()) {
}
}
}
return (tempdir.isDirectory());
}
public class signature extends View {
private static final float STROKE_WIDTH = 5f;
private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
private Paint paint = new Paint();
private Path path = new Path();
private float lastTouchX;
private float lastTouchY;
private final RectF dirtyRect = new RectF();
public signature(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(STROKE_WIDTH);
}
public void save(View v) {
if (mBitmap == null) {
mBitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(mBitmap);
try {
FileOutputStream mFileOutStream = new FileOutputStream(mypath);
v.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
} catch (Exception e) {
}
}
public void clear() {
path.reset();
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
Paint paint1 = new Paint();
paint1.setTextSize(40);
paint1.setColor(Color.GRAY);
int height = canvas.getHeight();
int width = canvas.getWidth();
String text = "Only valid for " + mBookingNumber + " at " + DateUtil.getNowDdEmMmYYYYHhMmAmPmFormate();
canvas.drawText(text, (width-text.length()*20)/2, height-30, paint1);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
mGetSign.setEnabled(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
resetDirtyRect(eventX, eventY);
int historySize = event.getHistorySize();
for (int i = 0; i < historySize; i++) {
float historicalX = event.getHistoricalX(i);
float historicalY = event.getHistoricalY(i);
expandDirtyRect(historicalX, historicalY);
path.lineTo(historicalX, historicalY);
}
path.lineTo(eventX, eventY);
break;
default:
return false;
}
invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
(int) (dirtyRect.top - HALF_STROKE_WIDTH),
(int) (dirtyRect.right + HALF_STROKE_WIDTH),
(int) (dirtyRect.bottom + HALF_STROKE_WIDTH));
lastTouchX = eventX;
lastTouchY = eventY;
return true;
}
private void expandDirtyRect(float historicalX, float historicalY) {
if (historicalX < dirtyRect.left) {
dirtyRect.left = historicalX;
} else if (historicalX > dirtyRect.right) {
dirtyRect.right = historicalX;
}
if (historicalY < dirtyRect.top) {
dirtyRect.top = historicalY;
} else if (historicalY > dirtyRect.bottom) {
dirtyRect.bottom = historicalY;
}
}
private void resetDirtyRect(float eventX, float eventY) {
dirtyRect.left = Math.min(lastTouchX, eventX);
dirtyRect.right = Math.max(lastTouchX, eventX);
dirtyRect.top = Math.min(lastTouchY, eventY);
dirtyRect.bottom = Math.max(lastTouchY, eventY);
}
}
}
| |
package com.fasterxml.jackson.dataformat.yaml;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.format.InputAccessor;
import com.fasterxml.jackson.core.format.MatchStrength;
import com.fasterxml.jackson.core.io.IOContext;
public class YAMLFactory extends JsonFactory
{
/**
* Name used to identify YAML format.
* (and returned by {@link #getFormatName()}
*/
public final static String FORMAT_NAME_YAML = "YAML";
/**
* Bitfield (set of flags) of all parser features that are enabled
* by default.
*/
final static int DEFAULT_YAML_PARSER_FEATURE_FLAGS = YAMLParser.Feature.collectDefaults();
/**
* Bitfield (set of flags) of all generator features that are enabled
* by default.
*/
final static int DEFAULT_YAML_GENERATOR_FEATURE_FLAGS = YAMLGenerator.Feature.collectDefaults();
final static byte UTF8_BOM_1 = (byte) 0xEF;
final static byte UTF8_BOM_2 = (byte) 0xBB;
final static byte UTF8_BOM_3 = (byte) 0xBF;
/*
/**********************************************************************
/* Configuration
/**********************************************************************
*/
protected int _yamlParserFeatures = DEFAULT_YAML_PARSER_FEATURE_FLAGS;
protected int _yamlGeneratorFeatures = DEFAULT_YAML_GENERATOR_FEATURE_FLAGS;
/*
/**********************************************************************
/* Factory construction, configuration
/**********************************************************************
*/
protected DumperOptions _outputOptions;
protected Integer[] _version;
/**
* Default constructor used to create factory instances.
* Creation of a factory instance is a light-weight operation,
* but it is still a good idea to reuse limited number of
* factory instances (and quite often just a single instance):
* factories are used as context for storing some reused
* processing objects (such as symbol tables parsers use)
* and this reuse only works within context of a single
* factory instance.
*/
public YAMLFactory() { this(null); }
public YAMLFactory(ObjectCodec oc)
{
super(oc);
_outputOptions = _defaultOptions();
DumperOptions.Version version = _outputOptions.getVersion();
_version = (version == null) ? null : version.getArray();
}
private static DumperOptions _defaultOptions()
{
DumperOptions opt = new DumperOptions();
// would we want canonical?
opt.setCanonical(false);
// if not, MUST specify flow styles
opt.setDefaultFlowStyle(FlowStyle.BLOCK);
return opt;
}
/*
/**********************************************************
/* Versioned
/**********************************************************
*/
@Override
public Version version() {
return ModuleVersion.instance.version();
}
/*
/**********************************************************
/* Format detection functionality (since 1.8)
/**********************************************************
*/
@Override
public String getFormatName() {
return FORMAT_NAME_YAML;
}
/**
* Sub-classes need to override this method (as of 1.8)
*/
@Override
public MatchStrength hasFormat(InputAccessor acc) throws IOException
{
/* Actually quite possible to do, thanks to (optional) "---"
* indicator we may be getting...
*/
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
byte b = acc.nextByte();
// Very first thing, a UTF-8 BOM?
if (b == UTF8_BOM_1) { // yes, looks like UTF-8 BOM
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
if (acc.nextByte() != UTF8_BOM_2) {
return MatchStrength.NO_MATCH;
}
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
if (acc.nextByte() != UTF8_BOM_3) {
return MatchStrength.NO_MATCH;
}
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
b = acc.nextByte();
}
// as far as I know, leading space is NOT allowed before "---" marker?
if (b == '-' && (acc.hasMoreBytes() && acc.nextByte() == '-')
&& (acc.hasMoreBytes() && acc.nextByte() == '-')) {
return MatchStrength.FULL_MATCH;
}
return MatchStrength.INCONCLUSIVE;
}
/*
/**********************************************************
/* Configuration, parser settings
/**********************************************************
*/
/**
* Method for enabling or disabling specified parser feature
* (check {@link YAMLParser.Feature} for list of features)
*/
public final YAMLFactory configure(YAMLParser.Feature f, boolean state)
{
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
/**
* Method for enabling specified parser feature
* (check {@link YAMLParser.Feature} for list of features)
*/
public YAMLFactory enable(YAMLParser.Feature f) {
_yamlParserFeatures |= f.getMask();
return this;
}
/**
* Method for disabling specified parser features
* (check {@link YAMLParser.Feature} for list of features)
*/
public YAMLFactory disable(YAMLParser.Feature f) {
_yamlParserFeatures &= ~f.getMask();
return this;
}
/**
* Checked whether specified parser feature is enabled.
*/
public final boolean isEnabled(YAMLParser.Feature f) {
return (_yamlParserFeatures & f.getMask()) != 0;
}
/*
/**********************************************************
/* Configuration, generator settings
/**********************************************************
*/
/**
* Method for enabling or disabling specified generator feature
* (check {@link YAMLGenerator.Feature} for list of features)
*/
public final YAMLFactory configure(YAMLGenerator.Feature f, boolean state) {
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
/**
* Method for enabling specified generator features
* (check {@link YAMLGenerator.Feature} for list of features)
*/
public YAMLFactory enable(YAMLGenerator.Feature f) {
_yamlGeneratorFeatures |= f.getMask();
return this;
}
/**
* Method for disabling specified generator feature
* (check {@link YAMLGenerator.Feature} for list of features)
*/
public YAMLFactory disable(YAMLGenerator.Feature f) {
_yamlGeneratorFeatures &= ~f.getMask();
return this;
}
/**
* Check whether specified generator feature is enabled.
*/
public final boolean isEnabled(YAMLGenerator.Feature f) {
return (_yamlGeneratorFeatures & f.getMask()) != 0;
}
/*
/**********************************************************
/* Overridden parser factory methods (for 2.1)
/**********************************************************
*/
@Override
public YAMLParser createParser(String content)
throws IOException, JsonParseException
{
Reader r = new StringReader(content);
IOContext ctxt = _createContext(r, true); // true->own, can close
// [JACKSON-512]: allow wrapping with InputDecorator
if (_inputDecorator != null) {
r = _inputDecorator.decorate(ctxt, r);
}
return _createParser(r, ctxt);
}
@Override
public YAMLParser createParser(File f)
throws IOException, JsonParseException
{
IOContext ctxt = _createContext(f, true);
InputStream in = new FileInputStream(f);
// [JACKSON-512]: allow wrapping with InputDecorator
if (_inputDecorator != null) {
in = _inputDecorator.decorate(ctxt, in);
}
return _createParser(in, ctxt);
}
@Override
public YAMLParser createParser(URL url)
throws IOException, JsonParseException
{
IOContext ctxt = _createContext(url, true);
InputStream in = _optimizedStreamFromURL(url);
// [JACKSON-512]: allow wrapping with InputDecorator
if (_inputDecorator != null) {
in = _inputDecorator.decorate(ctxt, in);
}
return _createParser(in, ctxt);
}
@Override
public YAMLParser createParser(InputStream in)
throws IOException, JsonParseException
{
IOContext ctxt = _createContext(in, false);
// [JACKSON-512]: allow wrapping with InputDecorator
if (_inputDecorator != null) {
in = _inputDecorator.decorate(ctxt, in);
}
return _createParser(in, ctxt);
}
@Override
public JsonParser createParser(Reader r)
throws IOException, JsonParseException
{
IOContext ctxt = _createContext(r, false);
if (_inputDecorator != null) {
r = _inputDecorator.decorate(ctxt, r);
}
return _createParser(r, ctxt);
}
@Override
public YAMLParser createParser(byte[] data)
throws IOException, JsonParseException
{
IOContext ctxt = _createContext(data, true);
// [JACKSON-512]: allow wrapping with InputDecorator
if (_inputDecorator != null) {
InputStream in = _inputDecorator.decorate(ctxt, data, 0, data.length);
if (in != null) {
return _createParser(in, ctxt);
}
}
return _createParser(data, 0, data.length, ctxt);
}
@Override
public YAMLParser createParser(byte[] data, int offset, int len)
throws IOException, JsonParseException
{
IOContext ctxt = _createContext(data, true);
// [JACKSON-512]: allow wrapping with InputDecorator
if (_inputDecorator != null) {
InputStream in = _inputDecorator.decorate(ctxt, data, offset, len);
if (in != null) {
return _createParser(in, ctxt);
}
}
return _createParser(data, offset, len, ctxt);
}
/*
/**********************************************************
/* Overridden parser factory methods (2.0 and prior)
/**********************************************************
*/
@Override
public YAMLParser createJsonParser(String content)
throws IOException, JsonParseException
{
Reader r = new StringReader(content);
IOContext ctxt = _createContext(r, true); // true->own, can close
// [JACKSON-512]: allow wrapping with InputDecorator
if (_inputDecorator != null) {
r = _inputDecorator.decorate(ctxt, r);
}
return _createParser(r, ctxt);
}
@Override
public YAMLParser createJsonParser(File f)
throws IOException, JsonParseException
{
IOContext ctxt = _createContext(f, true);
InputStream in = new FileInputStream(f);
// [JACKSON-512]: allow wrapping with InputDecorator
if (_inputDecorator != null) {
in = _inputDecorator.decorate(ctxt, in);
}
return _createParser(in, ctxt);
}
@Override
public YAMLParser createJsonParser(URL url)
throws IOException, JsonParseException
{
IOContext ctxt = _createContext(url, true);
InputStream in = _optimizedStreamFromURL(url);
// [JACKSON-512]: allow wrapping with InputDecorator
if (_inputDecorator != null) {
in = _inputDecorator.decorate(ctxt, in);
}
return _createParser(in, ctxt);
}
@Override
public YAMLParser createJsonParser(InputStream in)
throws IOException, JsonParseException
{
IOContext ctxt = _createContext(in, false);
// [JACKSON-512]: allow wrapping with InputDecorator
if (_inputDecorator != null) {
in = _inputDecorator.decorate(ctxt, in);
}
return _createParser(in, ctxt);
}
@Override
public JsonParser createJsonParser(Reader r)
throws IOException, JsonParseException
{
IOContext ctxt = _createContext(r, false);
if (_inputDecorator != null) {
r = _inputDecorator.decorate(ctxt, r);
}
return _createParser(r, ctxt);
}
@Override
public YAMLParser createJsonParser(byte[] data)
throws IOException, JsonParseException
{
IOContext ctxt = _createContext(data, true);
// [JACKSON-512]: allow wrapping with InputDecorator
if (_inputDecorator != null) {
InputStream in = _inputDecorator.decorate(ctxt, data, 0, data.length);
if (in != null) {
return _createParser(in, ctxt);
}
}
return _createParser(data, 0, data.length, ctxt);
}
@Override
public YAMLParser createJsonParser(byte[] data, int offset, int len)
throws IOException, JsonParseException
{
IOContext ctxt = _createContext(data, true);
// [JACKSON-512]: allow wrapping with InputDecorator
if (_inputDecorator != null) {
InputStream in = _inputDecorator.decorate(ctxt, data, offset, len);
if (in != null) {
return _createParser(in, ctxt);
}
}
return _createParser(data, offset, len, ctxt);
}
/*
/**********************************************************
/* Overridden generator factory methods (2.1)
/**********************************************************
*/
@Override
public YAMLGenerator createGenerator(OutputStream out, JsonEncoding enc) throws IOException
{
// false -> we won't manage the stream unless explicitly directed to
IOContext ctxt = _createContext(out, false);
// [JACKSON-512]: allow wrapping with _outputDecorator
if (_outputDecorator != null) {
out = _outputDecorator.decorate(ctxt, out);
}
return _createGenerator(_createWriter(out, JsonEncoding.UTF8, ctxt), ctxt);
}
@Override
public YAMLGenerator createGenerator(OutputStream out) throws IOException
{
// false -> we won't manage the stream unless explicitly directed to
IOContext ctxt = _createContext(out, false);
// [JACKSON-512]: allow wrapping with _outputDecorator
if (_outputDecorator != null) {
out = _outputDecorator.decorate(ctxt, out);
}
return _createGenerator(_createWriter(out, JsonEncoding.UTF8, ctxt), ctxt);
}
@Override
public YAMLGenerator createGenerator(Writer out) throws IOException
{
IOContext ctxt = _createContext(out, false);
// [JACKSON-512]: allow wrapping with _outputDecorator
if (_outputDecorator != null) {
out = _outputDecorator.decorate(ctxt, out);
}
return _createGenerator(out, ctxt);
}
/*
/**********************************************************
/* Overridden generator factory methods (2.0 and before)
/**********************************************************
*/
@Override
public YAMLGenerator createJsonGenerator(OutputStream out, JsonEncoding enc) throws IOException {
return createGenerator(out, enc);
}
@Override
public YAMLGenerator createJsonGenerator(OutputStream out) throws IOException {
return createGenerator(out);
}
@Override
public YAMLGenerator createJsonGenerator(Writer out) throws IOException {
return createGenerator(out);
}
/*
/******************************************************
/* Overridden internal factory methods
/******************************************************
*/
//protected IOContext _createContext(Object srcRef, boolean resourceManaged)
@Override
protected YAMLParser _createParser(InputStream in, IOContext ctxt)
throws IOException, JsonParseException
{
Reader r = _createReader(in, null, ctxt);
return new YAMLParser(ctxt, _getBufferRecycler(), _parserFeatures, _yamlParserFeatures,
_objectCodec, r);
}
@Override
protected YAMLParser _createParser(Reader r, IOContext ctxt)
throws IOException, JsonParseException
{
return new YAMLParser(ctxt, _getBufferRecycler(), _parserFeatures, _yamlParserFeatures,
_objectCodec, r);
}
@Override
protected YAMLParser _createParser(byte[] data, int offset, int len, IOContext ctxt)
throws IOException, JsonParseException
{
Reader r = _createReader(data, offset, len, null, ctxt);
return new YAMLParser(ctxt, _getBufferRecycler(), _parserFeatures, _yamlParserFeatures,
_objectCodec, r);
}
@Override
protected YAMLParser _createJsonParser(InputStream in, IOContext ctxt)
throws IOException, JsonParseException
{
return _createParser(in, ctxt);
}
@Override
protected JsonParser _createJsonParser(Reader r, IOContext ctxt)
throws IOException, JsonParseException
{
return _createParser(r, ctxt);
}
@Override
protected YAMLParser _createJsonParser(byte[] data, int offset, int len, IOContext ctxt)
throws IOException, JsonParseException
{
return _createParser(data, offset, len, ctxt);
}
@Override
protected YAMLGenerator _createGenerator(Writer out, IOContext ctxt)
throws IOException
{
int feats = _yamlGeneratorFeatures;
YAMLGenerator gen = new YAMLGenerator(ctxt, _generatorFeatures, feats,
_objectCodec, out, _outputOptions, _version);
// any other initializations? No?
return gen;
}
@Override
protected YAMLGenerator _createJsonGenerator(Writer out, IOContext ctxt)
throws IOException
{
return _createGenerator(out, ctxt);
}
@Override
protected YAMLGenerator _createUTF8Generator(OutputStream out, IOContext ctxt) throws IOException {
throw new IllegalStateException("Method should never get called");
}
@Override
@Deprecated
protected YAMLGenerator _createUTF8JsonGenerator(OutputStream out, IOContext ctxt) throws IOException {
return _createUTF8Generator(out, ctxt);
}
@Override
protected Writer _createWriter(OutputStream out, JsonEncoding enc, IOContext ctxt) throws IOException
{
if (enc == JsonEncoding.UTF8) {
return new UTF8Writer(out);
}
return new OutputStreamWriter(out, enc.getJavaName());
}
/*
/**********************************************************
/* Internal methods
/**********************************************************
*/
protected final Charset UTF8 = Charset.forName("UTF-8");
protected Reader _createReader(InputStream in, JsonEncoding enc, IOContext ctxt) throws IOException
{
if (enc == null) {
enc = JsonEncoding.UTF8;
}
// default to UTF-8 if encoding missing
if (enc == JsonEncoding.UTF8) {
boolean autoClose = ctxt.isResourceManaged() || this.isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE);
return new UTF8Reader(in, autoClose);
// return new InputStreamReader(in, UTF8);
}
return new InputStreamReader(in, enc.getJavaName());
}
protected Reader _createReader(byte[] data, int offset, int len,
JsonEncoding enc, IOContext ctxt) throws IOException
{
if (enc == null) {
enc = JsonEncoding.UTF8;
}
// default to UTF-8 if encoding missing
if (enc == null || enc == JsonEncoding.UTF8) {
return new UTF8Reader(data, offset, len, true);
}
ByteArrayInputStream in = new ByteArrayInputStream(data, offset, len);
return new InputStreamReader(in, enc.getJavaName());
}
}
| |
/*
* 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.ignite.internal.util.nio;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
import junit.framework.TestCase;
import org.apache.ignite.internal.util.typedef.internal.U;
/**
* Tests pure round trip time on network.
*/
public class GridRoundTripTest extends TestCase {
/** Communication port. */
public static final int PORT = 47600;
/** Remote computer address. Change this field to run test. */
public static final String HOSTNAME = "localhost";
/**
* @throws IOException If error occurs.
* @throws InterruptedException If interrupted
*/
public void testRunServer() throws IOException, InterruptedException {
final ServerSocket sock = new ServerSocket();
sock.bind(new InetSocketAddress("0.0.0.0", PORT));
Thread runner = new Thread() {
@Override public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
Socket accepted = sock.accept();
new EchoReader(accepted).start();
}
}
catch (IOException e) {
System.err.println("Accept thread failed: " + e.getMessage());
}
finally {
System.out.println("Server finished.");
}
}
};
runner.start();
runner.join();
}
/**
* Runs client test
*/
@SuppressWarnings("InfiniteLoopStatement")
public void testRunClient() {
Socket sock = new Socket();
OutputStream out = null;
InputStream in = null;
try {
Random r = new Random();
sock.connect(new InetSocketAddress(HOSTNAME, PORT));
out = sock.getOutputStream();
in = new BufferedInputStream(sock.getInputStream());
while (true) {
byte[] msg = createMessage(r.nextInt(1024) + 1);
long start = System.currentTimeMillis();
System.out.println(">>>>>>> [" + start + "] sending message, " + msg.length + " bytes");
writeMessage(out, msg);
byte[] resp = readMessage(in);
if (resp.length != msg.length)
throw new IOException("Invalid response");
long end = System.currentTimeMillis();
System.out.println(">>>>>>> [" + end + "] response received, " + msg.length + " bytes");
System.out.println("======= Response received within " + (end - start) + "ms\r\n");
U.sleep(30);
}
}
catch (Exception e) {
System.out.println("Finishing test thread: " + e.getMessage());
}
finally {
U.closeQuiet(out);
U.closeQuiet(in);
U.closeQuiet(sock);
}
}
/**
* Echo thread.
*/
private static class EchoReader extends Thread {
/** Client socket. */
private Socket sock;
/**
* @param sock Accepted socket.
*/
private EchoReader(Socket sock) {
this.sock = sock;
}
/** {@inheritDoc} */
@SuppressWarnings("InfiniteLoopStatement")
@Override public void run() {
OutputStream out = null;
InputStream in = null;
try {
out = sock.getOutputStream();
in = new BufferedInputStream(sock.getInputStream());
while (true) {
byte[] msg = readMessage(in);
System.out.println(">>>>>>> [" + System.currentTimeMillis() + "] packet received, " +
msg.length + " bytes");
System.out.println(">>>>>>> [" + System.currentTimeMillis() + "] sending response, " +
msg.length + " bytes");
writeMessage(out, msg);
}
}
catch (Exception e) {
System.out.println("Finishing client thread: " + e.getMessage());
}
finally {
U.closeQuiet(in);
U.closeQuiet(out);
U.closeQuiet(sock);
}
}
}
/**
* @param in Input stream to read from.
* @return Read message.
* @throws IOException If connection closed or packet was incorrect.
*/
private static byte[] readMessage(InputStream in) throws IOException {
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
for (int i = 0; i < 4; i++) {
int symbol = in.read();
if (symbol == -1)
throw new IOException("Connection was closed.");
tmp.write(symbol);
}
int length = U.bytesToInt(tmp.toByteArray(), 0);
tmp.reset();
for (int i = 0; i < length; i++) {
int symbol = in.read();
if (symbol == -1)
throw new IOException("Connection was closed.");
if ((byte)symbol != (byte)i)
throw new IOException("Invalid packet: mismatch in position " + i);
tmp.write(symbol);
}
return tmp.toByteArray();
}
/**
* @param out Output stream to write to.
* @param msg Message to write.
* @throws IOException If error occurs.
*/
private static void writeMessage(OutputStream out, byte[] msg) throws IOException {
out.write(U.intToBytes(msg.length));
out.write(msg);
}
/**
* Creates message.
*
* @param len Message length.
* @return Message bytes.
*/
private static byte[] createMessage(int len) {
byte[] res = new byte[len];
for (int i = 0; i < len; i++)
res[i] = (byte)i;
return res;
}
}
| |
/*
* 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.storm.kafka.spout;
import static org.apache.storm.kafka.spout.builders.SingleTopicKafkaSpoutConfiguration.getKafkaSpoutConfig;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.storm.kafka.KafkaUnitRule;
import org.apache.storm.kafka.spout.builders.SingleTopicKafkaSpoutConfiguration;
import org.apache.storm.spout.SpoutOutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.tuple.Values;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.stream.IntStream;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.HashMap;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.storm.kafka.spout.internal.KafkaConsumerFactory;
import org.apache.storm.kafka.spout.internal.KafkaConsumerFactoryDefault;
import org.apache.storm.utils.Time;
import org.apache.storm.utils.Time.SimulatedTime;
import org.junit.Before;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
public class SingleTopicKafkaSpoutTest {
private class SpoutContext {
public KafkaSpout<String, String> spout;
public SpoutOutputCollector collector;
public SpoutContext(KafkaSpout<String, String> spout,
SpoutOutputCollector collector) {
this.spout = spout;
this.collector = collector;
}
}
@Rule
public KafkaUnitRule kafkaUnitRule = new KafkaUnitRule();
@Captor
private ArgumentCaptor<Map<TopicPartition, OffsetAndMetadata>> commitCapture;
private final TopologyContext topologyContext = mock(TopologyContext.class);
private final Map<String, Object> conf = new HashMap<>();
private final SpoutOutputCollector collector = mock(SpoutOutputCollector.class);
private final long commitOffsetPeriodMs = 2_000;
private KafkaConsumer<String, String> consumerSpy;
private KafkaConsumerFactory<String, String> consumerFactory;
private KafkaSpout<String, String> spout;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
KafkaSpoutConfig spoutConfig = getKafkaSpoutConfig(kafkaUnitRule.getKafkaUnit().getKafkaPort(), commitOffsetPeriodMs);
this.consumerSpy = spy(new KafkaConsumerFactoryDefault().createConsumer(spoutConfig));
this.consumerFactory = (kafkaSpoutConfig) -> consumerSpy;
this.spout = new KafkaSpout<>(spoutConfig, consumerFactory);
}
void populateTopicData(String topicName, int msgCount) throws InterruptedException, ExecutionException, TimeoutException {
kafkaUnitRule.getKafkaUnit().createTopic(topicName);
for (int i = 0; i < msgCount; i++) {
ProducerRecord<String, String> producerRecord = new ProducerRecord<>(
topicName, Integer.toString(i),
Integer.toString(i));
kafkaUnitRule.getKafkaUnit().sendMessage(producerRecord);
}
}
private void initializeSpout(int msgCount) throws InterruptedException, ExecutionException, TimeoutException {
populateTopicData(SingleTopicKafkaSpoutConfiguration.TOPIC, msgCount);
spout.open(conf, topologyContext, collector);
spout.activate();
}
/*
* Asserts that commitSync has been called once,
* that there are only commits on one topic,
* and that the committed offset covers messageCount messages
*/
private void verifyAllMessagesCommitted(long messageCount) {
verify(consumerSpy, times(1)).commitSync(commitCapture.capture());
Map<TopicPartition, OffsetAndMetadata> commits = commitCapture.getValue();
assertThat("Expected commits for only one topic partition", commits.entrySet().size(), is(1));
OffsetAndMetadata offset = commits.entrySet().iterator().next().getValue();
assertThat("Expected committed offset to cover all emitted messages", offset.offset(), is(messageCount - 1));
}
@Test
public void shouldContinueWithSlowDoubleAcks() throws Exception {
try (SimulatedTime simulatedTime = new SimulatedTime()) {
int messageCount = 20;
initializeSpout(messageCount);
//play 1st tuple
ArgumentCaptor<Object> messageIdToDoubleAck = ArgumentCaptor.forClass(Object.class);
spout.nextTuple();
verify(collector).emit(anyObject(), anyObject(), messageIdToDoubleAck.capture());
spout.ack(messageIdToDoubleAck.getValue());
//Emit some more messages
IntStream.range(0, messageCount / 2).forEach(value -> {
spout.nextTuple();
});
spout.ack(messageIdToDoubleAck.getValue());
//Emit any remaining messages
IntStream.range(0, messageCount).forEach(value -> {
spout.nextTuple();
});
//Verify that all messages are emitted, ack all the messages
ArgumentCaptor<Object> messageIds = ArgumentCaptor.forClass(Object.class);
verify(collector, times(messageCount)).emit(eq(SingleTopicKafkaSpoutConfiguration.STREAM),
anyObject(),
messageIds.capture());
messageIds.getAllValues().iterator().forEachRemaining(spout::ack);
Time.advanceTime(commitOffsetPeriodMs + KafkaSpout.TIMER_DELAY_MS);
//Commit offsets
spout.nextTuple();
verifyAllMessagesCommitted(messageCount);
}
}
@Test
public void shouldEmitAllMessages() throws Exception {
try (SimulatedTime simulatedTime = new SimulatedTime()) {
int messageCount = 10;
initializeSpout(messageCount);
//Emit all messages and check that they are emitted. Ack the messages too
IntStream.range(0, messageCount).forEach(value -> {
spout.nextTuple();
ArgumentCaptor<Object> messageId = ArgumentCaptor.forClass(Object.class);
verify(collector).emit(
eq(SingleTopicKafkaSpoutConfiguration.STREAM),
eq(new Values(SingleTopicKafkaSpoutConfiguration.TOPIC,
Integer.toString(value),
Integer.toString(value))),
messageId.capture());
spout.ack(messageId.getValue());
reset(collector);
});
Time.advanceTime(commitOffsetPeriodMs + KafkaSpout.TIMER_DELAY_MS);
//Commit offsets
spout.nextTuple();
verifyAllMessagesCommitted(messageCount);
}
}
@Test
public void shouldReplayInOrderFailedMessages() throws Exception {
try (SimulatedTime simulatedTime = new SimulatedTime()) {
int messageCount = 10;
initializeSpout(messageCount);
//play and ack 1 tuple
ArgumentCaptor<Object> messageIdAcked = ArgumentCaptor.forClass(Object.class);
spout.nextTuple();
verify(collector).emit(anyObject(), anyObject(), messageIdAcked.capture());
spout.ack(messageIdAcked.getValue());
reset(collector);
//play and fail 1 tuple
ArgumentCaptor<Object> messageIdFailed = ArgumentCaptor.forClass(Object.class);
spout.nextTuple();
verify(collector).emit(anyObject(), anyObject(), messageIdFailed.capture());
spout.fail(messageIdFailed.getValue());
reset(collector);
//Emit all remaining messages. Failed tuples retry immediately with current configuration, so no need to wait.
IntStream.range(0, messageCount).forEach(value -> {
spout.nextTuple();
});
ArgumentCaptor<Object> remainingMessageIds = ArgumentCaptor.forClass(Object.class);
//All messages except the first acked message should have been emitted
verify(collector, times(messageCount - 1)).emit(
eq(SingleTopicKafkaSpoutConfiguration.STREAM),
anyObject(),
remainingMessageIds.capture());
remainingMessageIds.getAllValues().iterator().forEachRemaining(spout::ack);
Time.advanceTime(commitOffsetPeriodMs + KafkaSpout.TIMER_DELAY_MS);
//Commit offsets
spout.nextTuple();
verifyAllMessagesCommitted(messageCount);
}
}
@Test
public void shouldReplayFirstTupleFailedOutOfOrder() throws Exception {
try (SimulatedTime simulatedTime = new SimulatedTime()) {
int messageCount = 10;
initializeSpout(messageCount);
//play 1st tuple
ArgumentCaptor<Object> messageIdToFail = ArgumentCaptor.forClass(Object.class);
spout.nextTuple();
verify(collector).emit(anyObject(), anyObject(), messageIdToFail.capture());
reset(collector);
//play 2nd tuple
ArgumentCaptor<Object> messageIdToAck = ArgumentCaptor.forClass(Object.class);
spout.nextTuple();
verify(collector).emit(anyObject(), anyObject(), messageIdToAck.capture());
reset(collector);
//ack 2nd tuple
spout.ack(messageIdToAck.getValue());
//fail 1st tuple
spout.fail(messageIdToFail.getValue());
//Emit all remaining messages. Failed tuples retry immediately with current configuration, so no need to wait.
IntStream.range(0, messageCount).forEach(value -> {
spout.nextTuple();
});
ArgumentCaptor<Object> remainingIds = ArgumentCaptor.forClass(Object.class);
//All messages except the first acked message should have been emitted
verify(collector, times(messageCount - 1)).emit(
eq(SingleTopicKafkaSpoutConfiguration.STREAM),
anyObject(),
remainingIds.capture());
remainingIds.getAllValues().iterator().forEachRemaining(spout::ack);
Time.advanceTime(commitOffsetPeriodMs + KafkaSpout.TIMER_DELAY_MS);
//Commit offsets
spout.nextTuple();
verifyAllMessagesCommitted(messageCount);
}
}
}
| |
/**
* $RCSfile$
* $Revision: $
* $Date: $
*
* Copyright (C) 2005-2008 Jive Software. 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.jivesoftware.util.cache;
import org.jivesoftware.openfire.cluster.ClusterNodeInfo;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* CacheFactoryStrategy for use in Openfire. It creates and manages local caches, and it's cluster
* related method implementations do nothing.
*
* @see Cache
* @see CacheFactory
*/
public class DefaultLocalCacheStrategy implements CacheFactoryStrategy {
/**
* Keep track of the locks that are currently being used.
*/
private Map<Object, LockAndCount> locks = new ConcurrentHashMap<Object, LockAndCount>();
public DefaultLocalCacheStrategy() {
}
public boolean startCluster() {
return false;
}
public void stopCluster() {
}
public Cache createCache(String name) {
// Get cache configuration from system properties or default (hardcoded) values
long maxSize = CacheFactory.getMaxCacheSize(name);
long lifetime = CacheFactory.getMaxCacheLifetime(name);
// Create cache with located properties
return new DefaultCache(name, maxSize, lifetime);
}
public void destroyCache(Cache cache) {
cache.clear();
}
public boolean isSeniorClusterMember() {
return true;
}
public Collection<ClusterNodeInfo> getClusterNodesInfo() {
return Collections.emptyList();
}
public int getMaxClusterNodes() {
return 0;
}
public byte[] getSeniorClusterMemberID() {
return null;
}
public byte[] getClusterMemberID() {
return new byte[0];
}
public long getClusterTime() {
return System.currentTimeMillis();
}
public void doClusterTask(final ClusterTask task) {
}
public boolean doClusterTask(ClusterTask task, byte[] nodeID) {
throw new IllegalStateException("Cluster service is not available");
}
public Collection<Object> doSynchronousClusterTask(ClusterTask task, boolean includeLocalMember) {
return Collections.emptyList();
}
public Object doSynchronousClusterTask(ClusterTask task, byte[] nodeID) {
throw new IllegalStateException("Cluster service is not available");
}
public void updateCacheStats(Map<String, Cache> caches) {
}
public String getPluginName() {
return "local";
}
public Lock getLock(Object key, Cache cache) {
Object lockKey = key;
if (key instanceof String) {
lockKey = ((String) key).intern();
}
return new LocalLock(lockKey);
}
private void acquireLock(Object key) {
ReentrantLock lock = lookupLockForAcquire(key);
lock.lock();
}
private void releaseLock(Object key) {
ReentrantLock lock = lookupLockForRelease(key);
lock.unlock();
}
private ReentrantLock lookupLockForAcquire(Object key) {
synchronized(key) {
LockAndCount lac = locks.get(key);
if (lac == null) {
lac = new LockAndCount(new ReentrantLock());
lac.count = 1;
locks.put(key, lac);
}
else {
lac.count++;
}
return lac.lock;
}
}
private ReentrantLock lookupLockForRelease(Object key) {
synchronized(key) {
LockAndCount lac = locks.get(key);
if (lac == null) {
throw new IllegalStateException("No lock found for object " + key);
}
if (lac.count <= 1) {
locks.remove(key);
}
else {
lac.count--;
}
return lac.lock;
}
}
private class LocalLock implements Lock {
private final Object key;
LocalLock(Object key) {
this.key = key;
}
public void lock(){
acquireLock(key);
}
public void unlock() {
releaseLock(key);
}
public void lockInterruptibly(){
throw new UnsupportedOperationException();
}
public Condition newCondition(){
throw new UnsupportedOperationException();
}
public boolean tryLock() {
throw new UnsupportedOperationException();
}
public boolean tryLock(long time, TimeUnit unit) {
throw new UnsupportedOperationException();
}
}
private static class LockAndCount {
final ReentrantLock lock;
int count;
LockAndCount(ReentrantLock lock) {
this.lock = lock;
}
}
public ClusterNodeInfo getClusterNodeInfo(byte[] nodeID) {
// not clustered
return null;
}
}
| |
/*
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.batik.dom;
import org.apache.batik.test.TestReport;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.DOMError;
import org.w3c.dom.DOMErrorHandler;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Tests Document.normalizeDocument.
*
* @author <a href="mailto:cam%40mcc%2eid%2eau">Cameron McCormack</a>
* @version $Id$
*/
public class DocumentNormalizeDocumentTest extends DOM3Test {
static class Handler implements DOMErrorHandler {
int cd = 0;
int wf = 0;
int wfn = 0;
public boolean handleError(DOMError e) {
if (e.getType().equals("cdata-sections-splitted")) {
cd++;
} else if (e.getType().equals("wf-invalid-character")) {
wf++;
} else if (e.getType().equals("wf-invalid-character-in-node-name")) {
wfn++;
}
return true;
}
public int get(String s) {
if (s.equals("cdata-sections-splitted")) {
return cd;
} else if (s.equals("wf-invalid-character")) {
return wf;
} else if (s.equals("wf-invalid-character-in-node-name")) {
return wfn;
} else {
return 0;
}
}
}
public TestReport runImpl() throws Exception {
Handler h = new Handler();
TestReport report = null;
// cdata-sections == false
Document doc = newSVGDoc();
DOMConfiguration conf = doc.getDomConfig();
conf.setParameter("cdata-sections", Boolean.FALSE);
Element e = doc.getDocumentElement();
e.appendChild(doc.createTextNode("abc"));
e.appendChild(doc.createCDATASection("def"));
e.appendChild(doc.createTextNode("ghi"));
doc.normalizeDocument();
if (!(e.getFirstChild().getNodeType() == Node.TEXT_NODE
&& e.getFirstChild().getNodeValue().equals("abcdefghi")
&& e.getFirstChild() == e.getLastChild())) {
if (report == null) {
report = reportError("Document.normalizeDocument test failed");
}
report.addDescriptionEntry("DOMConfiguration parameter", "cdata-sections == false");
}
// comments == false
doc = newSVGDoc();
conf = doc.getDomConfig();
conf.setParameter("comments", Boolean.FALSE);
e = doc.getDocumentElement();
e.appendChild(doc.createTextNode("abc"));
e.appendChild(doc.createComment("def"));
e.appendChild(doc.createTextNode("ghi"));
doc.normalizeDocument();
if (!(e.getFirstChild().getNodeType() == Node.TEXT_NODE
&& e.getFirstChild().getNodeValue().equals("abcghi")
&& e.getFirstChild() == e.getLastChild())) {
if (report == null) {
report = reportError("Document.normalizeDocument test failed");
}
report.addDescriptionEntry("DOMConfiguration parameter", "comments == false");
}
// element-content-whitespace == false
doc = newSVGDoc();
conf = doc.getDomConfig();
conf.setParameter("element-content-whitespace", Boolean.FALSE);
e = doc.getDocumentElement();
e.appendChild(doc.createTextNode(" "));
e.appendChild(doc.createElementNS(SVG_NAMESPACE_URI, "g"));
e.appendChild(doc.createTextNode(" "));
doc.normalizeDocument();
if (!(e.getFirstChild().getNodeType() == Node.ELEMENT_NODE
&& e.getFirstChild().getNodeName().equals("g")
&& e.getFirstChild() == e.getLastChild())) {
if (report == null) {
report = reportError("Document.normalizeDocument test failed");
}
report.addDescriptionEntry("DOMConfiguration parameter", "element-content-whitespace == false");
}
// split-cdata-sections == true
doc = newSVGDoc();
conf = doc.getDomConfig();
conf.setParameter("split-cdata-sections", Boolean.TRUE);
conf.setParameter("error-handler", h);
e = doc.getDocumentElement();
e.appendChild(doc.createCDATASection("before ]]> after"));
doc.normalizeDocument();
if (!(e.getFirstChild().getNodeType() == Node.CDATA_SECTION_NODE
&& e.getFirstChild().getNodeValue().equals("before ]]")
&& e.getFirstChild().getNextSibling().getNodeType() == Node.CDATA_SECTION_NODE
&& e.getFirstChild().getNextSibling().getNodeValue().equals("> after")
&& e.getFirstChild().getNextSibling() == e.getLastChild()
&& h.get("cdata-sections-splitted") == 1)) {
if (report == null) {
report = reportError("Document.normalizeDocument test failed");
}
report.addDescriptionEntry("DOMConfiguration parameter", "split-cdata-sections == true");
}
// well-formed
doc = newSVGDoc();
doc.setStrictErrorChecking(false);
conf = doc.getDomConfig();
conf.setParameter("error-handler", h);
e = doc.getDocumentElement();
e.appendChild(doc.createComment("before -- after"));
e.appendChild(doc.createComment("ends in a dash -"));
e.setAttribute("*", "blah");
e.appendChild(doc.createProcessingInstruction("abc", "def?>"));
doc.normalizeDocument();
if (!(h.get("wf-invalid-character-in-node-name") == 1
&& h.get("wf-invalid-character") == 3)) {
if (report == null) {
report = reportError("Document.normalizeDocument test failed");
}
report.addDescriptionEntry("DOMConfiguration parameter", "well-formed == true");
}
// namespaces
doc = newDoc();
e = doc.createElementNS(null, "root");
doc.appendChild(e);
Element e2 = doc.createElementNS(null, "parent");
e.appendChild(e2);
e2.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:ns", "http://www.example.org/ns1");
e2.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:bar", "http://www.example.org/ns2");
Element e3 = doc.createElementNS("http://www.example.org/ns1", "ns:child1");
e2.appendChild(e3);
e3.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:ns", "http://www.example.org/ns2");
e3 = doc.createElementNS("http://www.example.org/ns2", "ns:child2");
e2.appendChild(e3);
doc.normalizeDocument();
Attr a = e3.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "ns");
if (!(a != null
&& a.getNodeName().equals("xmlns:ns")
&& a.getNodeValue().equals("http://www.example.org/ns2"))) {
if (report == null) {
report = reportError("Document.normalizeDocument test failed");
}
report.addDescriptionEntry("DOMConfiguration parameter", "namespaces == true, test 1");
}
doc = newDoc();
e = doc.createElementNS(null, "root");
doc.appendChild(e);
e2 = doc.createElementNS("http://www.example.org/ns1", "ns:child1");
e.appendChild(e2);
e2.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:ns", "http://www.example.org/ns1");
e3 = doc.createElementNS("http://www.example.org/ns1", "ns:child2");
e2.appendChild(e3);
e2 = (Element) ((AbstractDocument) doc).renameNode(e2, "http://www.example.org/ns2", "ns:child1");
doc.normalizeDocument();
a = e2.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "ns");
Attr a2 = e3.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "ns");
if (!(a != null
&& a.getNodeName().equals("xmlns:ns")
&& a.getNodeValue().equals("http://www.example.org/ns2")
&& a2 != null
&& a2.getNodeName().equals("xmlns:ns")
&& a2.getNodeValue().equals("http://www.example.org/ns1"))) {
if (report == null) {
report = reportError("Document.normalizeDocument test failed");
}
report.addDescriptionEntry("DOMConfiguration parameter", "namespaces == true, test 2");
}
doc = newDoc();
e = doc.createElementNS(null, "root");
doc.appendChild(e);
e2 = doc.createElementNS("http://www.example.org/ns1", "child1");
e.appendChild(e2);
e2.setAttributeNS("http://www.example.org/ns2", "blah", "hi");
doc.normalizeDocument();
a = e2.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "xmlns");
a2 = e2.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "NS1");
if (!(a != null
&& a.getNodeValue().equals("http://www.example.org/ns1")
&& a2 != null
&& a2.getNodeValue().equals("http://www.example.org/ns2"))) {
if (report == null) {
report = reportError("Document.normalizeDocument test failed");
}
report.addDescriptionEntry("DOMConfiguration parameter", "namespaces == true, test 3");
}
// namespace-declarations == false
doc = newDoc();
e = doc.createElementNS(null, "ex:root");
e.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:ex", "http://www.example.org/ns1");
conf = doc.getDomConfig();
conf.setParameter("namespace-declarations", Boolean.FALSE);
doc.appendChild(e);
doc.normalizeDocument();
if (!(e.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "ex") == null)) {
if (report == null) {
report = reportError("Document.normalizeDocument test failed");
}
report.addDescriptionEntry("DOMConfiguration parameter", "namespace-declarations == false");
}
if (report == null) {
return reportSuccess();
}
return report;
}
}
| |
package org.zstack.compute.allocator;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.config.GlobalConfigVO;
import org.zstack.core.config.GlobalConfigVO_;
import org.zstack.core.db.Q;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.header.allocator.*;
import org.zstack.header.core.ReturnValueCompletion;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.host.HostInventory;
import org.zstack.header.host.HostVO;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.utils.DebugUtils;
import org.zstack.utils.SizeUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import java.util.*;
/**
*/
@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE)
public class HostAllocatorChain implements HostAllocatorTrigger, HostAllocatorStrategy {
private static final CLogger logger = Utils.getLogger(HostAllocatorChain.class);
private HostAllocatorSpec allocationSpec;
private String name;
private List<AbstractHostAllocatorFlow> flows;
private Iterator<AbstractHostAllocatorFlow> it;
private ErrorCode errorCode;
private List<HostVO> result = null;
private boolean isDryRun;
private ReturnValueCompletion<HostInventory> completion;
private ReturnValueCompletion<List<HostInventory>> dryRunCompletion;
private AbstractHostAllocatorFlow lastFlow;
private HostAllocationPaginationInfo paginationInfo;
private Set<String> seriesErrorWhenPagination = new HashSet<String>();
private MarshalResultFunction marshalResultFunction;
@Autowired
private ErrorFacade errf;
@Autowired
private PluginRegistry pluginRgty;
@Autowired
private HostCapacityOverProvisioningManager ratioMgr;
public HostAllocatorSpec getAllocationSpec() {
return allocationSpec;
}
public void setAllocationSpec(HostAllocatorSpec allocationSpec) {
this.allocationSpec = allocationSpec;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<AbstractHostAllocatorFlow> getFlows() {
return flows;
}
public void setFlows(List<AbstractHostAllocatorFlow> flows) {
this.flows = flows;
}
void reserveCapacity(final String hostUuid, final long requestCpu, final long requestMemory) {
HostCapacityUpdater updater = new HostCapacityUpdater(hostUuid);
String reservedMemoryOfGlobalConfig = Q.New(GlobalConfigVO.class).select(GlobalConfigVO_.value).eq(GlobalConfigVO_.name,"reservedMemory").findValue();
updater.run(new HostCapacityUpdaterRunnable() {
@Override
public HostCapacityVO call(HostCapacityVO cap) {
long availCpu = cap.getAvailableCpu() - requestCpu;
if (availCpu < 0) {
throw new UnableToReserveHostCapacityException(
String.format("no enough CPU[%s] on the host[uuid:%s]", requestCpu, hostUuid));
}
cap.setAvailableCpu(availCpu);
long availMemory = cap.getAvailableMemory() - ratioMgr.calculateMemoryByRatio(hostUuid, requestMemory);
if (availMemory - SizeUtils.sizeStringToBytes(reservedMemoryOfGlobalConfig) < 0) {
throw new UnableToReserveHostCapacityException(
String.format("no enough memory[%s] on the host[uuid:%s]", requestMemory, hostUuid));
}
cap.setAvailableMemory(availMemory);
return cap;
}
});
}
protected void marshalResult() {
if (marshalResultFunction != null) {
marshalResultFunction.marshal(result);
}
}
private void done() {
if (result == null) {
if (isDryRun) {
if (HostAllocatorError.NO_AVAILABLE_HOST.toString().equals(errorCode.getCode())) {
dryRunCompletion.success(new ArrayList<HostInventory>());
} else {
dryRunCompletion.fail(errorCode);
}
} else {
completion.fail(errorCode);
}
return;
}
// in case a wrong flow returns an empty result set
if (result.isEmpty()) {
if (isDryRun) {
dryRunCompletion.fail(errf.instantiateErrorCode(HostAllocatorError.NO_AVAILABLE_HOST,
"host allocation flow doesn't indicate any details"));
} else {
completion.fail(errf.instantiateErrorCode(HostAllocatorError.NO_AVAILABLE_HOST,
"host allocation flow doesn't indicate any details"));
}
return;
}
if (isDryRun) {
dryRunCompletion.success(HostInventory.valueOf(result));
return;
}
marshalResult();
try {
for (HostVO h : result) {
try {
reserveCapacity(h.getUuid(), allocationSpec.getCpuCapacity(), allocationSpec.getMemoryCapacity());
logger.debug(String.format("[Host Allocation]: successfully reserved cpu[%s], memory[%s bytes] on host[uuid:%s] for vm[uuid:%s]",
allocationSpec.getCpuCapacity(), allocationSpec.getMemoryCapacity(), h.getUuid(),
allocationSpec.getVmInstance().getUuid()));
completion.success(HostInventory.valueOf(h));
return;
} catch (UnableToReserveHostCapacityException e) {
logger.debug(String.format("[Host Allocation]: %s on host[uuid:%s]. try next one",
e.getMessage(), h.getUuid()), e);
}
}
if (paginationInfo != null) {
logger.debug("[Host Allocation]: unable to reserve cpu/memory on all candidate hosts; because of pagination is enabled, allocation will start over");
seriesErrorWhenPagination.add(String.format("{unable to reserve cpu[%s], memory[%s bytes] on all candidate hosts}",
allocationSpec.getCpuCapacity(), allocationSpec.getMemoryCapacity()));
startOver();
} else {
completion.fail(errf.instantiateErrorCode(HostAllocatorError.NO_AVAILABLE_HOST,
"reservation on cpu/memory failed on all candidates host"));
}
} catch (Throwable t) {
logger.debug(t.getClass().getName(), t);
completion.fail(errf.throwableToInternalError(t));
}
}
private void startOver() {
it = flows.iterator();
result = null;
runFlow(it.next());
}
private void runFlow(AbstractHostAllocatorFlow flow) {
try {
lastFlow = flow;
flow.setCandidates(result);
flow.setSpec(allocationSpec);
flow.setTrigger(this);
flow.setPaginationInfo(paginationInfo);
flow.allocate();
} catch (OperationFailureException ofe) {
if (ofe.getErrorCode().getCode().equals(HostAllocatorConstant.PAGINATION_INTERMEDIATE_ERROR.getCode())) {
logger.debug(String.format("[Host Allocation]: intermediate failure; " +
"because of pagination, will start over allocation again; " +
"current pagination info %s; failure details: %s",
JSONObjectUtil.toJsonString(paginationInfo), ofe.getErrorCode().getDetails()));
seriesErrorWhenPagination.add(String.format("{%s}", ofe.getErrorCode().getDetails()));
startOver();
} else {
fail(ofe.getErrorCode());
}
} catch (Throwable t) {
logger.warn("unhandled throwable", t);
completion.fail(errf.throwableToInternalError(t));
}
}
private void start() {
for (HostAllocatorPreStartExtensionPoint processor : pluginRgty.getExtensionList(HostAllocatorPreStartExtensionPoint.class)) {
processor.beforeHostAllocatorStart(allocationSpec, flows);
}
if (HostAllocatorGlobalConfig.USE_PAGINATION.value(Boolean.class)) {
paginationInfo = new HostAllocationPaginationInfo();
paginationInfo.setLimit(HostAllocatorGlobalConfig.PAGINATION_LIMIT.value(Integer.class));
}
it = flows.iterator();
DebugUtils.Assert(it.hasNext(), "can not run an empty host allocation chain");
runFlow(it.next());
}
private void allocate(ReturnValueCompletion<HostInventory> completion) {
isDryRun = false;
this.completion = completion;
start();
}
private void dryRun(ReturnValueCompletion<List<HostInventory>> completion) {
isDryRun = true;
this.dryRunCompletion = completion;
start();
}
@Override
public void next(List<HostVO> candidates) {
DebugUtils.Assert(candidates != null, "cannot pass null to next() method");
DebugUtils.Assert(!candidates.isEmpty(), "cannot pass empty candidates to next() method");
result = candidates;
VmInstanceInventory vm = allocationSpec.getVmInstance();
logger.debug(String.format("[Host Allocation]: flow[%s] successfully found %s candidate hosts for vm[uuid:%s, name:%s]",
lastFlow.getClass().getName(), result.size(), vm.getUuid(), vm.getName()));
if (logger.isTraceEnabled()) {
StringBuilder sb = new StringBuilder("[Host Allocation Details]:");
for (HostVO vo : result) {
sb.append(String.format("\ncandidate host[name:%s, uuid:%s, zoneUuid:%s, clusterUuid:%s, hypervisorType:%s]",
vo.getName(), vo.getUuid(), vo.getZoneUuid(), vo.getClusterUuid(), vo.getHypervisorType()));
}
logger.trace(sb.toString());
}
if (it.hasNext()) {
runFlow(it.next());
return;
}
done();
}
@Override
public void skip() {
logger.debug(String.format("[Host Allocation]: flow[%s] asks to skip itself, we are running to the next flow",
lastFlow.getClass()));
if (it.hasNext()) {
runFlow(it.next());
return;
}
done();
}
@Override
public int indexOfFlow(AbstractHostAllocatorFlow flow) {
return flows.indexOf(flow);
}
private void fail(ErrorCode errorCode) {
result = null;
if (seriesErrorWhenPagination.isEmpty()) {
logger.debug(String.format("[Host Allocation] flow[%s] failed to allocate host; %s",
lastFlow.getClass().getName(), errorCode.getDetails()));
this.errorCode = errorCode;
} else {
String err = String.format("unable to allocate hosts; due to pagination is enabled, " +
"there might be several allocation failures happened before;" +
" the error list is %s", seriesErrorWhenPagination);
logger.debug(err);
this.errorCode = errf.instantiateErrorCode(HostAllocatorError.NO_AVAILABLE_HOST, err);
}
done();
}
@Override
public void allocate(HostAllocatorSpec spec, ReturnValueCompletion<HostInventory> completion) {
this.allocationSpec = spec;
allocate(completion);
}
@Override
public void dryRun(HostAllocatorSpec spec, ReturnValueCompletion<List<HostInventory>> completion) {
this.allocationSpec = spec;
dryRun(completion);
}
@Override
public void setMarshalResultFunction(MarshalResultFunction func) {
marshalResultFunction = func;
}
}
| |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.dynamodbv2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Represents a request to perform a check that an item exists or to check the condition of specific attributes of the
* item..
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ConditionCheck" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ConditionCheck implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The primary key of the item to be checked. Each element consists of an attribute name and a value for that
* attribute.
* </p>
*/
private java.util.Map<String, AttributeValue> key;
/**
* <p>
* Name of the table for the check item request.
* </p>
*/
private String tableName;
/**
* <p>
* A condition that must be satisfied in order for a conditional update to succeed.
* </p>
*/
private String conditionExpression;
/**
* <p>
* One or more substitution tokens for attribute names in an expression.
* </p>
*/
private java.util.Map<String, String> expressionAttributeNames;
/**
* <p>
* One or more values that can be substituted in an expression.
* </p>
*/
private java.util.Map<String, AttributeValue> expressionAttributeValues;
/**
* <p>
* Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the
* <code>ConditionCheck</code> condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the valid
* values are: NONE and ALL_OLD.
* </p>
*/
private String returnValuesOnConditionCheckFailure;
/**
* <p>
* The primary key of the item to be checked. Each element consists of an attribute name and a value for that
* attribute.
* </p>
*
* @return The primary key of the item to be checked. Each element consists of an attribute name and a value for
* that attribute.
*/
public java.util.Map<String, AttributeValue> getKey() {
return key;
}
/**
* <p>
* The primary key of the item to be checked. Each element consists of an attribute name and a value for that
* attribute.
* </p>
*
* @param key
* The primary key of the item to be checked. Each element consists of an attribute name and a value for that
* attribute.
*/
public void setKey(java.util.Map<String, AttributeValue> key) {
this.key = key;
}
/**
* <p>
* The primary key of the item to be checked. Each element consists of an attribute name and a value for that
* attribute.
* </p>
*
* @param key
* The primary key of the item to be checked. Each element consists of an attribute name and a value for that
* attribute.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ConditionCheck withKey(java.util.Map<String, AttributeValue> key) {
setKey(key);
return this;
}
public ConditionCheck addKeyEntry(String key, AttributeValue value) {
if (null == this.key) {
this.key = new java.util.HashMap<String, AttributeValue>();
}
if (this.key.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.key.put(key, value);
return this;
}
/**
* Removes all the entries added into Key.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ConditionCheck clearKeyEntries() {
this.key = null;
return this;
}
/**
* <p>
* Name of the table for the check item request.
* </p>
*
* @param tableName
* Name of the table for the check item request.
*/
public void setTableName(String tableName) {
this.tableName = tableName;
}
/**
* <p>
* Name of the table for the check item request.
* </p>
*
* @return Name of the table for the check item request.
*/
public String getTableName() {
return this.tableName;
}
/**
* <p>
* Name of the table for the check item request.
* </p>
*
* @param tableName
* Name of the table for the check item request.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ConditionCheck withTableName(String tableName) {
setTableName(tableName);
return this;
}
/**
* <p>
* A condition that must be satisfied in order for a conditional update to succeed.
* </p>
*
* @param conditionExpression
* A condition that must be satisfied in order for a conditional update to succeed.
*/
public void setConditionExpression(String conditionExpression) {
this.conditionExpression = conditionExpression;
}
/**
* <p>
* A condition that must be satisfied in order for a conditional update to succeed.
* </p>
*
* @return A condition that must be satisfied in order for a conditional update to succeed.
*/
public String getConditionExpression() {
return this.conditionExpression;
}
/**
* <p>
* A condition that must be satisfied in order for a conditional update to succeed.
* </p>
*
* @param conditionExpression
* A condition that must be satisfied in order for a conditional update to succeed.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ConditionCheck withConditionExpression(String conditionExpression) {
setConditionExpression(conditionExpression);
return this;
}
/**
* <p>
* One or more substitution tokens for attribute names in an expression.
* </p>
*
* @return One or more substitution tokens for attribute names in an expression.
*/
public java.util.Map<String, String> getExpressionAttributeNames() {
return expressionAttributeNames;
}
/**
* <p>
* One or more substitution tokens for attribute names in an expression.
* </p>
*
* @param expressionAttributeNames
* One or more substitution tokens for attribute names in an expression.
*/
public void setExpressionAttributeNames(java.util.Map<String, String> expressionAttributeNames) {
this.expressionAttributeNames = expressionAttributeNames;
}
/**
* <p>
* One or more substitution tokens for attribute names in an expression.
* </p>
*
* @param expressionAttributeNames
* One or more substitution tokens for attribute names in an expression.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ConditionCheck withExpressionAttributeNames(java.util.Map<String, String> expressionAttributeNames) {
setExpressionAttributeNames(expressionAttributeNames);
return this;
}
public ConditionCheck addExpressionAttributeNamesEntry(String key, String value) {
if (null == this.expressionAttributeNames) {
this.expressionAttributeNames = new java.util.HashMap<String, String>();
}
if (this.expressionAttributeNames.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.expressionAttributeNames.put(key, value);
return this;
}
/**
* Removes all the entries added into ExpressionAttributeNames.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ConditionCheck clearExpressionAttributeNamesEntries() {
this.expressionAttributeNames = null;
return this;
}
/**
* <p>
* One or more values that can be substituted in an expression.
* </p>
*
* @return One or more values that can be substituted in an expression.
*/
public java.util.Map<String, AttributeValue> getExpressionAttributeValues() {
return expressionAttributeValues;
}
/**
* <p>
* One or more values that can be substituted in an expression.
* </p>
*
* @param expressionAttributeValues
* One or more values that can be substituted in an expression.
*/
public void setExpressionAttributeValues(java.util.Map<String, AttributeValue> expressionAttributeValues) {
this.expressionAttributeValues = expressionAttributeValues;
}
/**
* <p>
* One or more values that can be substituted in an expression.
* </p>
*
* @param expressionAttributeValues
* One or more values that can be substituted in an expression.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ConditionCheck withExpressionAttributeValues(java.util.Map<String, AttributeValue> expressionAttributeValues) {
setExpressionAttributeValues(expressionAttributeValues);
return this;
}
public ConditionCheck addExpressionAttributeValuesEntry(String key, AttributeValue value) {
if (null == this.expressionAttributeValues) {
this.expressionAttributeValues = new java.util.HashMap<String, AttributeValue>();
}
if (this.expressionAttributeValues.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.expressionAttributeValues.put(key, value);
return this;
}
/**
* Removes all the entries added into ExpressionAttributeValues.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ConditionCheck clearExpressionAttributeValuesEntries() {
this.expressionAttributeValues = null;
return this;
}
/**
* <p>
* Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the
* <code>ConditionCheck</code> condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the valid
* values are: NONE and ALL_OLD.
* </p>
*
* @param returnValuesOnConditionCheckFailure
* Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the
* <code>ConditionCheck</code> condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the
* valid values are: NONE and ALL_OLD.
* @see ReturnValuesOnConditionCheckFailure
*/
public void setReturnValuesOnConditionCheckFailure(String returnValuesOnConditionCheckFailure) {
this.returnValuesOnConditionCheckFailure = returnValuesOnConditionCheckFailure;
}
/**
* <p>
* Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the
* <code>ConditionCheck</code> condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the valid
* values are: NONE and ALL_OLD.
* </p>
*
* @return Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the
* <code>ConditionCheck</code> condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the
* valid values are: NONE and ALL_OLD.
* @see ReturnValuesOnConditionCheckFailure
*/
public String getReturnValuesOnConditionCheckFailure() {
return this.returnValuesOnConditionCheckFailure;
}
/**
* <p>
* Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the
* <code>ConditionCheck</code> condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the valid
* values are: NONE and ALL_OLD.
* </p>
*
* @param returnValuesOnConditionCheckFailure
* Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the
* <code>ConditionCheck</code> condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the
* valid values are: NONE and ALL_OLD.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ReturnValuesOnConditionCheckFailure
*/
public ConditionCheck withReturnValuesOnConditionCheckFailure(String returnValuesOnConditionCheckFailure) {
setReturnValuesOnConditionCheckFailure(returnValuesOnConditionCheckFailure);
return this;
}
/**
* <p>
* Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the
* <code>ConditionCheck</code> condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the valid
* values are: NONE and ALL_OLD.
* </p>
*
* @param returnValuesOnConditionCheckFailure
* Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the
* <code>ConditionCheck</code> condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the
* valid values are: NONE and ALL_OLD.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ReturnValuesOnConditionCheckFailure
*/
public ConditionCheck withReturnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure returnValuesOnConditionCheckFailure) {
this.returnValuesOnConditionCheckFailure = returnValuesOnConditionCheckFailure.toString();
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getKey() != null)
sb.append("Key: ").append(getKey()).append(",");
if (getTableName() != null)
sb.append("TableName: ").append(getTableName()).append(",");
if (getConditionExpression() != null)
sb.append("ConditionExpression: ").append(getConditionExpression()).append(",");
if (getExpressionAttributeNames() != null)
sb.append("ExpressionAttributeNames: ").append(getExpressionAttributeNames()).append(",");
if (getExpressionAttributeValues() != null)
sb.append("ExpressionAttributeValues: ").append(getExpressionAttributeValues()).append(",");
if (getReturnValuesOnConditionCheckFailure() != null)
sb.append("ReturnValuesOnConditionCheckFailure: ").append(getReturnValuesOnConditionCheckFailure());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ConditionCheck == false)
return false;
ConditionCheck other = (ConditionCheck) obj;
if (other.getKey() == null ^ this.getKey() == null)
return false;
if (other.getKey() != null && other.getKey().equals(this.getKey()) == false)
return false;
if (other.getTableName() == null ^ this.getTableName() == null)
return false;
if (other.getTableName() != null && other.getTableName().equals(this.getTableName()) == false)
return false;
if (other.getConditionExpression() == null ^ this.getConditionExpression() == null)
return false;
if (other.getConditionExpression() != null && other.getConditionExpression().equals(this.getConditionExpression()) == false)
return false;
if (other.getExpressionAttributeNames() == null ^ this.getExpressionAttributeNames() == null)
return false;
if (other.getExpressionAttributeNames() != null && other.getExpressionAttributeNames().equals(this.getExpressionAttributeNames()) == false)
return false;
if (other.getExpressionAttributeValues() == null ^ this.getExpressionAttributeValues() == null)
return false;
if (other.getExpressionAttributeValues() != null && other.getExpressionAttributeValues().equals(this.getExpressionAttributeValues()) == false)
return false;
if (other.getReturnValuesOnConditionCheckFailure() == null ^ this.getReturnValuesOnConditionCheckFailure() == null)
return false;
if (other.getReturnValuesOnConditionCheckFailure() != null
&& other.getReturnValuesOnConditionCheckFailure().equals(this.getReturnValuesOnConditionCheckFailure()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getKey() == null) ? 0 : getKey().hashCode());
hashCode = prime * hashCode + ((getTableName() == null) ? 0 : getTableName().hashCode());
hashCode = prime * hashCode + ((getConditionExpression() == null) ? 0 : getConditionExpression().hashCode());
hashCode = prime * hashCode + ((getExpressionAttributeNames() == null) ? 0 : getExpressionAttributeNames().hashCode());
hashCode = prime * hashCode + ((getExpressionAttributeValues() == null) ? 0 : getExpressionAttributeValues().hashCode());
hashCode = prime * hashCode + ((getReturnValuesOnConditionCheckFailure() == null) ? 0 : getReturnValuesOnConditionCheckFailure().hashCode());
return hashCode;
}
@Override
public ConditionCheck clone() {
try {
return (ConditionCheck) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.dynamodbv2.model.transform.ConditionCheckMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| |
/*
* 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.jmeter.protocol.java.control.gui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import junit.framework.TestCase;
import org.apache.jmeter.gui.util.VerticalPanel;
import org.apache.jmeter.protocol.java.sampler.JUnitSampler;
import org.apache.jmeter.samplers.gui.AbstractSamplerGui;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.gui.JLabeledTextField;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jorphan.reflect.ClassFinder;
import org.apache.jorphan.util.JOrphanUtils;
import org.apache.log.Logger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* The <code>JUnitTestSamplerGui</code> class provides the user interface
* for the {@link JUnitSampler}.
*
*/
public class JUnitTestSamplerGui extends AbstractSamplerGui
implements ChangeListener, ActionListener, ItemListener
{
private static final long serialVersionUID = 240L;
private static final Logger log = LoggingManager.getLoggerForClass();
private static final String TESTMETHOD_PREFIX = "test"; //$NON-NLS-1$
// Names of JUnit3 methods
private static final String ONETIMESETUP = "oneTimeSetUp"; //$NON-NLS-1$
private static final String ONETIMETEARDOWN = "oneTimeTearDown"; //$NON-NLS-1$
private static final String SUITE = "suite"; //$NON-NLS-1$
private static final String[] SPATHS;
static {
String paths[];
String ucp = JMeterUtils.getProperty("user.classpath");
if (ucp!=null){
String parts[] = ucp.split(File.pathSeparator);
paths = new String[parts.length+1];
paths[0] = JMeterUtils.getJMeterHome() + "/lib/junit/"; //$NON-NLS-1$
System.arraycopy(parts, 0, paths, 1, parts.length);
} else {
paths = new String[]{
JMeterUtils.getJMeterHome() + "/lib/junit/" //$NON-NLS-1$
};
}
SPATHS = paths;
}
private JLabeledTextField constructorLabel =
new JLabeledTextField(
JMeterUtils.getResString("junit_constructor_string")); //$NON-NLS-1$
private JLabel methodLabel =
new JLabel(
JMeterUtils.getResString("junit_test_method")); //$NON-NLS-1$
private JLabeledTextField successMsg =
new JLabeledTextField(
JMeterUtils.getResString("junit_success_msg")); //$NON-NLS-1$
private JLabeledTextField failureMsg =
new JLabeledTextField(
JMeterUtils.getResString("junit_failure_msg")); //$NON-NLS-1$
private JLabeledTextField errorMsg =
new JLabeledTextField(
JMeterUtils.getResString("junit_error_msg")); //$NON-NLS-1$
private JLabeledTextField successCode =
new JLabeledTextField(
JMeterUtils.getResString("junit_success_code")); //$NON-NLS-1$
private JLabeledTextField failureCode =
new JLabeledTextField(
JMeterUtils.getResString("junit_failure_code")); //$NON-NLS-1$
private JLabeledTextField errorCode =
new JLabeledTextField(
JMeterUtils.getResString("junit_error_code")); //$NON-NLS-1$
private JLabeledTextField filterpkg =
new JLabeledTextField(
JMeterUtils.getResString("junit_pkg_filter")); //$NON-NLS-1$
private JCheckBox doSetup = new JCheckBox(JMeterUtils.getResString("junit_do_setup_teardown")); //$NON-NLS-1$
private JCheckBox appendError = new JCheckBox(JMeterUtils.getResString("junit_append_error")); //$NON-NLS-1$
private JCheckBox appendExc = new JCheckBox(JMeterUtils.getResString("junit_append_exception")); //$NON-NLS-1$
private JCheckBox junit4 = new JCheckBox(JMeterUtils.getResString("junit_junit4")); //$NON-NLS-1$
private JCheckBox createInstancePerSample = new JCheckBox(JMeterUtils.getResString("junit_create_instance_per_sample")); //$NON-NLS-1$
/** A combo box allowing the user to choose a test class. */
private JComboBox<String> classnameCombo;
private JComboBox<String> methodName;
private final transient ClassLoader contextClassLoader =
Thread.currentThread().getContextClassLoader(); // Potentially expensive; do it once
/**
* Constructor for JUnitTestSamplerGui
*/
public JUnitTestSamplerGui()
{
super();
init();
}
@Override
public String getLabelResource()
{
return "junit_request"; //$NON-NLS-1$
}
/**
* Initialize the GUI components and layout.
*/
private void init() // WARNING: called from ctor so must not be overridden (i.e. must be private or final)
{
setLayout(new BorderLayout(0, 5));
setBorder(makeBorder());
add(makeTitlePanel(), BorderLayout.NORTH);
add(createClassPanel(), BorderLayout.CENTER);
}
@SuppressWarnings("unchecked")
private void setupClasslist(){
classnameCombo.removeAllItems();
methodName.removeAllItems();
try
{
List<String> classList;
if (junit4.isSelected()){
classList = ClassFinder.findAnnotatedClasses(SPATHS,
new Class[] {Test.class}, false);
} else {
classList = ClassFinder.findClassesThatExtend(SPATHS,
new Class[] { TestCase.class });
}
ClassFilter filter = new ClassFilter();
filter.setPackges(JOrphanUtils.split(filterpkg.getText(),",")); //$NON-NLS-1$
// change the classname drop down
String[] clist = filter.filterArray(classList);
for (String classStr : clist) {
classnameCombo.addItem(classStr);
}
}
catch (IOException e)
{
log.error("Exception getting interfaces.", e);
}
}
private JPanel createClassPanel()
{
JLabel label =
new JLabel(JMeterUtils.getResString("protocol_java_classname")); //$NON-NLS-1$
classnameCombo = new JComboBox<>();
classnameCombo.addActionListener(this);
classnameCombo.setEditable(false);
label.setLabelFor(classnameCombo);
methodName = new JComboBox<>();
methodName.addActionListener(this);
methodLabel.setLabelFor(methodName);
setupClasslist();
VerticalPanel panel = new VerticalPanel();
panel.add(junit4);
junit4.addItemListener(this);
panel.add(filterpkg);
filterpkg.addChangeListener(this);
panel.add(label);
panel.add(classnameCombo);
constructorLabel.setText("");
panel.add(constructorLabel);
panel.add(methodLabel);
panel.add(methodName);
panel.add(successMsg);
panel.add(successCode);
panel.add(failureMsg);
panel.add(failureCode);
panel.add(errorMsg);
panel.add(errorCode);
panel.add(doSetup);
panel.add(appendError);
panel.add(appendExc);
panel.add(createInstancePerSample);
return panel;
}
private void initGui(){
appendError.setSelected(false);
appendExc.setSelected(false);
createInstancePerSample.setSelected(false);
doSetup.setSelected(false);
junit4.setSelected(false);
filterpkg.setText(""); //$NON-NLS-1$
constructorLabel.setText(""); //$NON-NLS-1$
successCode.setText(JMeterUtils.getResString("junit_success_default_code")); //$NON-NLS-1$
successMsg.setText(JMeterUtils.getResString("junit_success_default_msg")); //$NON-NLS-1$
failureCode.setText(JMeterUtils.getResString("junit_failure_default_code")); //$NON-NLS-1$
failureMsg.setText(JMeterUtils.getResString("junit_failure_default_msg")); //$NON-NLS-1$
errorMsg.setText(JMeterUtils.getResString("junit_error_default_msg")); //$NON-NLS-1$
errorCode.setText(JMeterUtils.getResString("junit_error_default_code")); //$NON-NLS-1$
}
/** {@inheritDoc} */
@Override
public void clearGui() {
super.clearGui();
initGui();
}
/** {@inheritDoc} */
@Override
public TestElement createTestElement()
{
JUnitSampler sampler = new JUnitSampler();
modifyTestElement(sampler);
return sampler;
}
/** {@inheritDoc} */
@Override
public void modifyTestElement(TestElement el)
{
JUnitSampler sampler = (JUnitSampler)el;
configureTestElement(sampler);
if (classnameCombo.getSelectedItem() != null &&
classnameCombo.getSelectedItem() instanceof String) {
sampler.setClassname((String)classnameCombo.getSelectedItem());
} else {
sampler.setClassname(null);
}
sampler.setConstructorString(constructorLabel.getText());
if (methodName.getSelectedItem() != null) {
Object mobj = methodName.getSelectedItem();
sampler.setMethod((String)mobj);
} else {
sampler.setMethod(null);
}
sampler.setFilterString(filterpkg.getText());
sampler.setSuccess(successMsg.getText());
sampler.setSuccessCode(successCode.getText());
sampler.setFailure(failureMsg.getText());
sampler.setFailureCode(failureCode.getText());
sampler.setError(errorMsg.getText());
sampler.setErrorCode(errorCode.getText());
sampler.setDoNotSetUpTearDown(doSetup.isSelected());
sampler.setAppendError(appendError.isSelected());
sampler.setAppendException(appendExc.isSelected());
sampler.setCreateOneInstancePerSample(createInstancePerSample.isSelected());
sampler.setJunit4(junit4.isSelected());
}
/** {@inheritDoc} */
@Override
public void configure(TestElement el)
{
super.configure(el);
JUnitSampler sampler = (JUnitSampler)el;
junit4.setSelected(sampler.getJunit4());
filterpkg.setText(sampler.getFilterString());
classnameCombo.setSelectedItem(sampler.getClassname());
setupMethods();
methodName.setSelectedItem(sampler.getMethod());
constructorLabel.setText(sampler.getConstructorString());
if (sampler.getSuccessCode().length() > 0) {
successCode.setText(sampler.getSuccessCode());
} else {
successCode.setText(JMeterUtils.getResString("junit_success_default_code")); //$NON-NLS-1$
}
if (sampler.getSuccess().length() > 0) {
successMsg.setText(sampler.getSuccess());
} else {
successMsg.setText(JMeterUtils.getResString("junit_success_default_msg")); //$NON-NLS-1$
}
if (sampler.getFailureCode().length() > 0) {
failureCode.setText(sampler.getFailureCode());
} else {
failureCode.setText(JMeterUtils.getResString("junit_failure_default_code")); //$NON-NLS-1$
}
if (sampler.getFailure().length() > 0) {
failureMsg.setText(sampler.getFailure());
} else {
failureMsg.setText(JMeterUtils.getResString("junit_failure_default_msg")); //$NON-NLS-1$
}
if (sampler.getError().length() > 0) {
errorMsg.setText(sampler.getError());
} else {
errorMsg.setText(JMeterUtils.getResString("junit_error_default_msg")); //$NON-NLS-1$
}
if (sampler.getErrorCode().length() > 0) {
errorCode.setText(sampler.getErrorCode());
} else {
errorCode.setText(JMeterUtils.getResString("junit_error_default_code")); //$NON-NLS-1$
}
doSetup.setSelected(sampler.getDoNotSetUpTearDown());
appendError.setSelected(sampler.getAppendError());
appendExc.setSelected(sampler.getAppendException());
createInstancePerSample.setSelected(sampler.getCreateOneInstancePerSample());
}
private void setupMethods(){
String className =
((String) classnameCombo.getSelectedItem());
methodName.removeAllItems();
if (className != null) {
try {
// Don't instantiate class
Class<?> testClass = Class.forName(className, false, contextClassLoader);
String [] names = getMethodNames(testClass);
for (String name : names) {
methodName.addItem(name);
}
methodName.repaint();
} catch (ClassNotFoundException e) {
}
}
}
private String[] getMethodNames(Class<?> clazz)
{
Method[] meths = clazz.getMethods();
List<String> list = new ArrayList<>();
for (final Method method : meths) {
final String name = method.getName();
if (junit4.isSelected()) {
if (method.isAnnotationPresent(Test.class) ||
method.isAnnotationPresent(BeforeClass.class) ||
method.isAnnotationPresent(AfterClass.class)) {
list.add(name);
}
} else {
if (name.startsWith(TESTMETHOD_PREFIX) ||
name.equals(ONETIMESETUP) ||
name.equals(ONETIMETEARDOWN) ||
name.equals(SUITE)) {
list.add(name);
}
}
}
if (list.size() > 0){
return list.toArray(new String[list.size()]);
}
return new String[0];
}
/**
* Handle action events for this component. This method currently handles
* events for the classname combo box, and sets up the associated method names.
*
* @param evt the ActionEvent to be handled
*/
@Override
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == classnameCombo)
{
setupMethods();
}
}
/**
* Handle change events: currently handles events for the JUnit4
* checkbox, and sets up the relevant class names.
*/
@Override
public void itemStateChanged(ItemEvent event) {
if (event.getItem() == junit4){
setupClasslist();
}
}
/**
* the current implementation checks to see if the source
* of the event is the filterpkg field.
*/
@Override
public void stateChanged(ChangeEvent event) {
if ( event.getSource() == filterpkg) {
setupClasslist();
}
}
}
| |
/*
* (c) Copyright 2022 Micro Focus
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available 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.cloudslang.content.httpclient.build.conn;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: davidmih
* Date: 6/27/14
*/
public class SSLConnectionSocketFactoryBuilder {
public static final String TRUST_ALL_ROOTS_ERROR = "Could not use trustAllRoots=";
public static final String SSL_CONNECTION_ERROR = "Could not create SSL connection. Invalid keystore or trustKeystore certificates.";
public static final String BAD_KEYSTORE_ERROR = "The keystore provided in the 'keystore' input is corrupted OR the password (in the 'keystorePassword' input) is incorrect";
public static final String INVALID_KEYSTORE_ERROR = "A keystore could not be found or it does not contain the needed certificate";
public static final String BAD_TRUST_KEYSTORE_ERROR = "The trust keystore provided in the 'trustKeystore' input is corrupted OR the password (in the 'trustPassword' input) is incorrect";
public static final String INVALID_TRUST_KEYSTORE_ERROR = "A trust keystore could not be found or it does not contain the needed certificate";
public static final String SSLv3 = "SSLv3";
public static final String TLSv10 = "TLSv1";
public static final String TLSv11 = "TLSv1.1";
public static final String TLSv12 = "TLSv1.2";
public static final String[] ARRAY_TLSv12 = new String[]{"TLSv1.2"};
public static final String[] array = new String[0];
public static final String[] SUPPORTED_PROTOCOLS = new String[]{SSLv3, TLSv10, TLSv11, TLSv12};
public static final String[] SUPPORTED_CYPHERS = new String[]{"TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "THS_DHE_RSA_WITH_AES_256_CBC_SHA256", "THS_DHE_RSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_256_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA256"};
private static boolean checkArray = false;
public String[] cypherArray;
private String trustAllRootsStr = "false";
private String keystore;
private String inputTLS;
private String keystorePassword;
private String trustKeystore;
private String trustPassword;
private String inputCyphers;
private String x509HostnameVerifierInputValue = "strict";
private boolean flag = false;
private boolean hasTLS2;
public static boolean checkEquality(String[] subArray, String[] largeArray) {
for (String aLargeArray : largeArray)
for (int j = 0; j < subArray.length; j++)
if ((aLargeArray.toUpperCase()).equals((subArray[j]).toUpperCase())) {
subArray[j] = aLargeArray;
}
return Arrays.asList(largeArray).containsAll(Arrays.asList(subArray));
}
public static boolean checkIfTLS2(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
}
protected KeyStore createKeyStore(final URL url, final String password)
throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
if (url == null) {
throw new IllegalArgumentException("Keystore url may not be null");
}
KeyStore keystore = KeyStore.getInstance("jks");
InputStream is = null;
try {
is = url.openStream();
keystore.load(is, password != null ? password.toCharArray() : null);
} finally {
if (is != null) is.close();
}
return keystore;
}
public SSLConnectionSocketFactory build() {
if (!"true".equalsIgnoreCase(trustAllRootsStr) && !"false".equalsIgnoreCase(trustAllRootsStr)) {
throw new IllegalArgumentException("'trustAllRoots' can only be 'true' or 'false'");
}
boolean trustAllRoots = Boolean.parseBoolean(trustAllRootsStr);
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
String changeit = "changeit";
String javaKeystore = System.getProperty("java.home") + "/lib/security/cacerts";
if (!trustAllRoots) {
boolean useClientCert = StringUtils.isNotEmpty(keystore);
//validate SSL certificates sent by the server
boolean useTrustCert = StringUtils.isNotEmpty(trustKeystore);
boolean storeExists = new File(javaKeystore).exists();
if (!useClientCert && storeExists) {
keystore = "file:" + javaKeystore;
keystorePassword = StringUtils.isNotEmpty(keystorePassword) ? keystorePassword : changeit;
useClientCert = true;
} else if (useClientCert && !keystore.startsWith("http")) {
keystore = "file:" + keystore;
}
if (!useTrustCert && storeExists) {
trustKeystore = "file:" + javaKeystore;
trustPassword = StringUtils.isNotEmpty(trustPassword) ? trustPassword : changeit;
useTrustCert = true;
} else if (useTrustCert && !trustKeystore.startsWith("http")) {
trustKeystore = "file:" + trustKeystore;
}
createTrustKeystore(sslContextBuilder, useTrustCert);
//todo client key authentication should not depend on 'trustAllRoots'
createKeystore(sslContextBuilder, useClientCert);
} else {
try {
//need to override isTrusted() method to accept CA certs because the Apache HTTP Client ver.4.3 will only accepts self-signed certificates
KeyStore keyStore = createKeyStore(new URL("file:" + keystore), keystorePassword);
sslContextBuilder.loadKeyMaterial(keyStore, keystorePassword.toCharArray());
String internalJavaKeystoreUri = "file:" + javaKeystore;
KeyStore javaTrustStore = createKeyStore(new URL(internalJavaKeystoreUri), changeit);
sslContextBuilder.loadTrustMaterial(javaTrustStore, new TrustSelfSignedStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
});
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage() + ". " + TRUST_ALL_ROOTS_ERROR + trustAllRoots, e);
}
}
sslContextBuilder.useSSL();
sslContextBuilder.useTLS();
SSLConnectionSocketFactory sslsf = null;
try {
String x509HostnameVerifierStr = x509HostnameVerifierInputValue.toLowerCase();
X509HostnameVerifier x509HostnameVerifier;
switch (x509HostnameVerifierStr) {
case "strict":
x509HostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
break;
case "browser_compatible":
x509HostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
break;
case "allow_all":
x509HostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
break;
default:
throw new IllegalArgumentException("Invalid value '" + x509HostnameVerifierInputValue + "' for input 'x509HostnameVerifier'. Valid values: 'strict','browser_compatible','allow_all'.");
}
// Allow SSLv3, TLSv1, TLSv1.1 and TLSv1.2 protocols only. Client-server communication starts with TLSv1.2 and fallbacks to SSLv3 if needed.
if (!StringUtils.isEmpty(inputTLS)) {
Set<String> protocolSet = new HashSet<>(Arrays.asList(inputTLS.trim().split(",")));
String[] protocolArray = protocolSet.toArray(new String[0]);
if (!checkEquality(protocolArray, SUPPORTED_PROTOCOLS)) {
throw new IllegalArgumentException("Protocol not supported");
}
if (checkIfTLS2(protocolArray, TLSv12))
flag = true;
if (!StringUtils.isEmpty(inputCyphers))
cypherArray = inputCyphers.trim().split(",");
if (flag) {
if (cypherArray != null) {
sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), ARRAY_TLSv12, cypherArray, x509HostnameVerifier);
} else {
sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), protocolArray, null, x509HostnameVerifier);
}
} else {
sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), protocolArray, null, x509HostnameVerifier);
}
} else {
sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), SUPPORTED_PROTOCOLS, null, x509HostnameVerifier);
}
} catch (Exception e) {
if (e instanceof IllegalArgumentException) {
throw new IllegalArgumentException(e.getMessage());
}
throw new RuntimeException(e.getMessage() + ". " + SSL_CONNECTION_ERROR, e);
}
return sslsf;
}
protected void createKeystore(SSLContextBuilder sslContextBuilder, boolean useClientCert) {
if (useClientCert) {
KeyStore clientKeyStore;
try {
clientKeyStore = createKeyStore(new URL(keystore), keystorePassword);
sslContextBuilder.loadKeyMaterial(clientKeyStore, keystorePassword.toCharArray());
} catch (UnrecoverableKeyException | IOException ue) {
throw new IllegalArgumentException(ue.getMessage() + ". " + BAD_KEYSTORE_ERROR, ue);
} catch (GeneralSecurityException gse) {
throw new IllegalArgumentException(gse.getMessage() + ". " + INVALID_KEYSTORE_ERROR, gse);
}
}
}
protected void createTrustKeystore(SSLContextBuilder sslContextBuilder, boolean useTrustCert) {
if (useTrustCert) {
KeyStore trustKeyStore;
try {
//todo should we do this 'create' in each and every step?
trustKeyStore = createKeyStore(new URL(trustKeystore), trustPassword);
sslContextBuilder.loadTrustMaterial(trustKeyStore);
} catch (IOException ioe) {
throw new IllegalArgumentException(ioe.getMessage() + ". " + BAD_TRUST_KEYSTORE_ERROR, ioe);
} catch (GeneralSecurityException gse) {
throw new IllegalArgumentException(gse.getMessage() + ". " + INVALID_TRUST_KEYSTORE_ERROR, gse);
}
}
}
public SSLConnectionSocketFactoryBuilder setTrustAllRoots(String trustAllRoots) {
if (!StringUtils.isEmpty(trustAllRoots)) {
this.trustAllRootsStr = trustAllRoots;
}
return this;
}
public SSLConnectionSocketFactoryBuilder setInputTLS(String inputTLSversion) {
this.inputTLS = inputTLSversion;
return this;
}
public SSLConnectionSocketFactoryBuilder setKeystore(String keystore) {
this.keystore = keystore;
return this;
}
public SSLConnectionSocketFactoryBuilder setKeystorePassword(String keystorePassword) {
this.keystorePassword = keystorePassword;
return this;
}
public SSLConnectionSocketFactoryBuilder setTrustKeystore(String trustKeystore) {
this.trustKeystore = trustKeystore;
return this;
}
public SSLConnectionSocketFactoryBuilder setTrustPassword(String trustPassword) {
this.trustPassword = trustPassword;
return this;
}
public SSLConnectionSocketFactoryBuilder setallowedCyphers(String allowedCyphers) {
this.inputCyphers = allowedCyphers;
return this;
}
public SSLConnectionSocketFactoryBuilder setX509HostnameVerifier(String x509HostnameVerifier) {
if (!StringUtils.isEmpty(x509HostnameVerifier)) {
this.x509HostnameVerifierInputValue = x509HostnameVerifier;
}
return this;
}
}
| |
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.container.model;
/**
* GetOpenIDConfigResponse is an OIDC discovery document for the cluster. See the OpenID Connect
* Discovery 1.0 specification for details.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Kubernetes Engine API. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GetOpenIDConfigResponse extends com.google.api.client.json.GenericJson {
/**
* Supported claims.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("claims_supported")
private java.util.List<java.lang.String> claimsSupported;
/**
* Supported grant types.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("grant_types")
private java.util.List<java.lang.String> grantTypes;
/**
* supported ID Token signing Algorithms.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("id_token_signing_alg_values_supported")
private java.util.List<java.lang.String> idTokenSigningAlgValuesSupported;
/**
* OIDC Issuer.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String issuer;
/**
* JSON Web Key uri.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("jwks_uri")
private java.lang.String jwksUri;
/**
* Supported response types.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("response_types_supported")
private java.util.List<java.lang.String> responseTypesSupported;
/**
* Supported subject types.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("subject_types_supported")
private java.util.List<java.lang.String> subjectTypesSupported;
/**
* Supported claims.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getClaimsSupported() {
return claimsSupported;
}
/**
* Supported claims.
* @param claimsSupported claimsSupported or {@code null} for none
*/
public GetOpenIDConfigResponse setClaimsSupported(java.util.List<java.lang.String> claimsSupported) {
this.claimsSupported = claimsSupported;
return this;
}
/**
* Supported grant types.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getGrantTypes() {
return grantTypes;
}
/**
* Supported grant types.
* @param grantTypes grantTypes or {@code null} for none
*/
public GetOpenIDConfigResponse setGrantTypes(java.util.List<java.lang.String> grantTypes) {
this.grantTypes = grantTypes;
return this;
}
/**
* supported ID Token signing Algorithms.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getIdTokenSigningAlgValuesSupported() {
return idTokenSigningAlgValuesSupported;
}
/**
* supported ID Token signing Algorithms.
* @param idTokenSigningAlgValuesSupported idTokenSigningAlgValuesSupported or {@code null} for none
*/
public GetOpenIDConfigResponse setIdTokenSigningAlgValuesSupported(java.util.List<java.lang.String> idTokenSigningAlgValuesSupported) {
this.idTokenSigningAlgValuesSupported = idTokenSigningAlgValuesSupported;
return this;
}
/**
* OIDC Issuer.
* @return value or {@code null} for none
*/
public java.lang.String getIssuer() {
return issuer;
}
/**
* OIDC Issuer.
* @param issuer issuer or {@code null} for none
*/
public GetOpenIDConfigResponse setIssuer(java.lang.String issuer) {
this.issuer = issuer;
return this;
}
/**
* JSON Web Key uri.
* @return value or {@code null} for none
*/
public java.lang.String getJwksUri() {
return jwksUri;
}
/**
* JSON Web Key uri.
* @param jwksUri jwksUri or {@code null} for none
*/
public GetOpenIDConfigResponse setJwksUri(java.lang.String jwksUri) {
this.jwksUri = jwksUri;
return this;
}
/**
* Supported response types.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getResponseTypesSupported() {
return responseTypesSupported;
}
/**
* Supported response types.
* @param responseTypesSupported responseTypesSupported or {@code null} for none
*/
public GetOpenIDConfigResponse setResponseTypesSupported(java.util.List<java.lang.String> responseTypesSupported) {
this.responseTypesSupported = responseTypesSupported;
return this;
}
/**
* Supported subject types.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSubjectTypesSupported() {
return subjectTypesSupported;
}
/**
* Supported subject types.
* @param subjectTypesSupported subjectTypesSupported or {@code null} for none
*/
public GetOpenIDConfigResponse setSubjectTypesSupported(java.util.List<java.lang.String> subjectTypesSupported) {
this.subjectTypesSupported = subjectTypesSupported;
return this;
}
@Override
public GetOpenIDConfigResponse set(String fieldName, Object value) {
return (GetOpenIDConfigResponse) super.set(fieldName, value);
}
@Override
public GetOpenIDConfigResponse clone() {
return (GetOpenIDConfigResponse) super.clone();
}
}
| |
/*
* 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 ro.nextreports.designer.ui.tail;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import ro.nextreports.designer.Globals;
import ro.nextreports.designer.ui.tail.action.ClearLogAction;
import ro.nextreports.designer.ui.tail.action.ReloadLogAction;
import ro.nextreports.designer.util.FileUtil;
import ro.nextreports.designer.util.I18NSupport;
/**
* Created by IntelliJ IDEA.
* User: mihai.panaitescu
* Date: May 30, 2007
* Time: 4:23:51 PM
*/
public class LogPanel extends JPanel implements LogFileTailerListener {
private static final String LOG_DIR = Globals.USER_DATA_DIR + "/logs";
private static final String LOG = LOG_DIR + "/jdbc-spy.log";
private final String TITLE = I18NSupport.getString("logpanel.title");
private static LogFileTailer tailer;
private JTextArea textArea;
private JTextField linesTextField;
private static final int LINES = 100;
private Dimension dim = new Dimension(40, 20);
public LogPanel() {
if (tailer == null) {
setPreferredSize(new Dimension(400, 300));
setLayout(new BorderLayout());
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollPanel = new JScrollPane(textArea);
linesTextField = new JTextField();
linesTextField.setPreferredSize(dim);
linesTextField.setMinimumSize(dim);
linesTextField.setMaximumSize(dim);
linesTextField.setText(String.valueOf(LINES));
JToolBar toolBar = new JToolBar();
toolBar.setRollover(true);
toolBar.add(new ClearLogAction(textArea));
toolBar.add(new ReloadLogAction(textArea, this));
JPanel topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
topPanel.add(toolBar);
topPanel.add(Box.createHorizontalStrut(5));
topPanel.add(new JLabel(I18NSupport.getString("logpanel.last.lines")));
topPanel.add(Box.createHorizontalStrut(5));
topPanel.add(linesTextField);
topPanel.add(Box.createHorizontalGlue());
add(topPanel, BorderLayout.NORTH);
add(scrollPanel, BorderLayout.CENTER);
final File log = new File(LOG);
if (!log.exists()) {
try {
new File(LOG_DIR).mkdirs();
boolean created = log.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
// read existing text in log
Thread t = new Thread(new Runnable() {
public void run() {
Cursor hourGlassCursor = new Cursor(Cursor.WAIT_CURSOR);
setCursor(hourGlassCursor);
//@todo
//reload(log, textArea);
tailer = new LogFileTailer(log, 1000, false);
tailer.addLogFileTailerListener(LogPanel.this);
tailer.setPriority(Thread.MIN_PRIORITY);
// very consuming !!!
//tailer.start();
Cursor normalCursor = new Cursor(Cursor.DEFAULT_CURSOR);
setCursor(normalCursor);
}
}, "NEXT : " + getClass().getSimpleName());
t.start();
}
}
public void newLogFileLine(final String line) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(line);
textArea.append("\r\n");
textArea.setCaretPosition(textArea.getText().length());
}
});
}
public static void stop() {
if (tailer != null) {
tailer.stopTailing();
tailer = null;
}
}
private void reloadAll(final File log, final JTextArea textArea) {
Thread t = new Thread(new Runnable() {
public void run() {
RandomAccessFile file = null;
try {
file = new RandomAccessFile(log, "r");
String line = file.readLine();
textArea.setText("");
while (line != null) {
// try {
// //@todo
// Thread.sleep(10);
// } catch (InterruptedException ex) {
// }
line = file.readLine();
final String lin = line;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(lin);
textArea.append("\r\n");
textArea.setCaretPosition(textArea.getText().length());
}
});
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}, "NEXT : Reload Log");
t.start();
}
private void reload(final File log, final JTextArea textArea) {
int lines = 0;
boolean reloadAll = false;
String text = linesTextField.getText().trim();
if("".equals(text)) {
reloadAll = true;
} else {
try {
lines = Integer.parseInt(text);
if (lines == 0) {
reloadAll = true;
}
} catch (NumberFormatException ex) {
lines = LINES;
}
}
if (reloadAll) {
reloadAll(log, textArea);
} else {
final int noLines = lines;
Thread t = new Thread(new Runnable() {
public void run() {
final ArrayList<String> lines = FileUtil.tail(LOG, noLines);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
for (int i = lines.size() - 1; i >= 0; i--) {
textArea.append(lines.get(i));
textArea.append("\r\n");
}
textArea.setCaretPosition(textArea.getText().length());
}
});
}
}, "NEXT : Reload Log");
t.start();
}
}
public void reload(JTextArea textArea) {
textArea.setText("");
File log = new File(LOG);
reload(log, textArea);
}
}
| |
/*
* 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.syncope.fit.console;
import static org.apache.syncope.fit.console.AbstractConsoleITCase.TESTER;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.syncope.client.console.commons.Constants;
import org.apache.syncope.client.console.commons.status.Status;
import org.apache.syncope.client.console.commons.status.StatusBean;
import org.apache.wicket.Component;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.util.tester.FormTester;
import org.junit.Before;
import org.junit.Test;
public class BulkActionITCase extends AbstractConsoleITCase {
private static final String TAB_PANEL = "body:content:body:container:content:tabbedPanel:panel:searchResult:";
private static final String CONTAINER = TAB_PANEL + "container:content:";
@Before
public void login() {
doLogin(ADMIN_UNAME, ADMIN_PWD);
}
@Test
public void usersBulkAction() {
TESTER.clickLink("body:realmsLI:realms");
TESTER.clickLink("body:content:body:container:content:tabbedPanel:tabs-container:tabs:1:link");
Component component = findComponentByProp("username", CONTAINER
+ "searchContainer:resultTable:tablePanel:groupForm:checkgroup:dataTable", "rossini");
assertNotNull(component);
FormTester formTester = TESTER.newFormTester(CONTAINER
+ "searchContainer:resultTable:tablePanel:groupForm");
assertNotNull(formTester);
formTester.select("checkgroup", 2);
TESTER.executeAjaxEvent(CONTAINER + "searchContainer:resultTable:tablePanel:bulkActionLink",
Constants.ON_CLICK);
TESTER.assertComponent(CONTAINER
+ "searchContainer:resultTable:bulkModal:form:content:content:container", WebMarkupContainer.class);
assertNotNull(findComponentByProp("username", CONTAINER
+ "searchContainer:resultTable:bulkModal:form:content:content:container", "rossini"));
}
@Test
public void userResourceBulkAction() {
TESTER.clickLink("body:realmsLI:realms");
TESTER.clickLink("body:content:body:container:content:tabbedPanel:tabs-container:tabs:1:link");
Component component = findComponentByProp("username", CONTAINER
+ ":searchContainer:resultTable:tablePanel:groupForm:checkgroup:dataTable", "rossini");
assertNotNull(component);
TESTER.clickLink(component.getPageRelativePath()
+ ":cells:6:cell:panelManageResources:manageResourcesLink");
TESTER.assertComponent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:groupForm:"
+ "checkgroup:dataTable", WebMarkupContainer.class);
component = findComponentByProp("resourceName",
TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:groupForm:"
+ "checkgroup:dataTable", "resource-csv");
assertNotNull(component);
FormTester formTester = TESTER.newFormTester(
TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:firstLevelContainer:"
+ "first:container:content:searchContainer:resultTable:tablePanel:groupForm");
assertNotNull(formTester);
formTester.select("checkgroup", 2);
TESTER.executeAjaxEvent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:bulkActionLink",
Constants.ON_CLICK);
TESTER.assertComponent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "secondLevelContainer:second:container", WebMarkupContainer.class);
assertNotNull(findComponentByProp("resourceName", TAB_PANEL + "outerObjectsRepeater:1:outer:"
+ "form:content:status:secondLevelContainer:second:container", "resource-csv"));
}
@Test
public void userStatusBulkAction() {
userStatusBulkAction(1, "resource-testdb2");
}
@Test
public void userStatusOnSyncopeOnlyBulkAction() {
userStatusBulkAction(0, "Syncope");
}
private void userStatusBulkAction(final int index, final String resourceName) {
// suspend
TESTER.clickLink("body:realmsLI:realms");
TESTER.clickLink("body:content:body:container:content:tabbedPanel:tabs-container:tabs:1:link");
Component component = findComponentByProp("username", CONTAINER
+ ":searchContainer:resultTable:tablePanel:groupForm:checkgroup:dataTable", "rossini");
assertNotNull(component);
TESTER.clickLink(component.getPageRelativePath() + ":cells:6:cell:panelEnable:enableLink");
TESTER.assertComponent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:groupForm:"
+ "checkgroup:dataTable", WebMarkupContainer.class);
component = findComponentByProp("resourceName",
TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:firstLevelContainer:first:container:"
+ "content:searchContainer:resultTable:tablePanel:groupForm:checkgroup:dataTable", resourceName);
component = TESTER.getComponentFromLastRenderedPage(component.getPageRelativePath() + ":cells:1:cell:check");
assertEquals(Status.ACTIVE, StatusBean.class.cast(component.getDefaultModelObject()).getStatus());
assertEquals(resourceName, StatusBean.class.cast(component.getDefaultModelObject()).getResourceName());
FormTester formTester = TESTER.newFormTester(
TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:firstLevelContainer:"
+ "first:container:content:searchContainer:resultTable:tablePanel:groupForm");
assertNotNull(formTester);
formTester.select("checkgroup", index);
TESTER.executeAjaxEvent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:bulkActionLink",
Constants.ON_CLICK);
TESTER.assertComponent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "secondLevelContainer:second:container", WebMarkupContainer.class);
TESTER.executeAjaxEvent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:"
+ "status:secondLevelContainer:second:container:actions:panelSuspend:suspendLink",
Constants.ON_CLICK);
TESTER.assertInfoMessages("Operation executed successfully");
TESTER.cleanupFeedbackMessages();
TESTER.assertLabel(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "secondLevelContainer:second:container:selectedObjects:body:rows:1:cells:3:cell", "SUCCESS");
TESTER.
executeAjaxEvent(TAB_PANEL
+ "outerObjectsRepeater:1:outer:form:content:status:secondLevelContainer:back",
Constants.ON_CLICK);
component = findComponentByProp("resourceName",
TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:firstLevelContainer:first:container:"
+ "content:searchContainer:resultTable:tablePanel:groupForm:checkgroup:dataTable", resourceName);
component = TESTER.getComponentFromLastRenderedPage(component.getPageRelativePath() + ":cells:1:cell:check");
assertEquals(Status.SUSPENDED, StatusBean.class.cast(component.getDefaultModelObject()).getStatus());
assertEquals(resourceName, StatusBean.class.cast(component.getDefaultModelObject()).getResourceName());
// re-activate
TESTER.clickLink("body:realmsLI:realms");
TESTER.clickLink("body:content:body:container:content:tabbedPanel:tabs-container:tabs:1:link");
component = findComponentByProp("username", CONTAINER
+ ":searchContainer:resultTable:tablePanel:groupForm:checkgroup:dataTable", "rossini");
assertNotNull(component);
TESTER.clickLink(component.getPageRelativePath() + ":cells:6:cell:panelEnable:enableLink");
TESTER.assertComponent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:groupForm:"
+ "checkgroup:dataTable", WebMarkupContainer.class);
formTester = TESTER.newFormTester(
TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:firstLevelContainer:"
+ "first:container:content:searchContainer:resultTable:tablePanel:groupForm");
assertNotNull(formTester);
formTester.select("checkgroup", index);
TESTER.executeAjaxEvent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:bulkActionLink",
Constants.ON_CLICK);
TESTER.assertComponent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "secondLevelContainer:second:container", WebMarkupContainer.class);
TESTER.executeAjaxEvent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:"
+ "status:secondLevelContainer:second:container:actions:panelReactivate:reactivateLink",
Constants.ON_CLICK);
TESTER.assertInfoMessages("Operation executed successfully");
TESTER.cleanupFeedbackMessages();
TESTER.assertLabel(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "secondLevelContainer:second:container:selectedObjects:body:rows:1:cells:3:cell", "SUCCESS");
TESTER.
executeAjaxEvent(TAB_PANEL
+ "outerObjectsRepeater:1:outer:form:content:status:secondLevelContainer:back",
Constants.ON_CLICK);
component = findComponentByProp("resourceName",
TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:firstLevelContainer:first:container:"
+ "content:searchContainer:resultTable:tablePanel:groupForm:checkgroup:dataTable", resourceName);
component = TESTER.getComponentFromLastRenderedPage(component.getPageRelativePath() + ":cells:1:cell:check");
assertEquals(Status.ACTIVE, StatusBean.class.cast(component.getDefaultModelObject()).getStatus());
assertEquals(resourceName, StatusBean.class.cast(component.getDefaultModelObject()).getResourceName());
TESTER.executeAjaxEvent(TAB_PANEL + "outerObjectsRepeater:1:outer:dialog:footer:buttons:0:button",
Constants.ON_CLICK);
}
@Test
public void groupResourceBulkAction() {
TESTER.clickLink("body:realmsLI:realms");
TESTER.clickLink("body:content:body:container:content:tabbedPanel:tabs-container:tabs:2:link");
Component component = findComponentByProp("name", CONTAINER
+ ":searchContainer:resultTable:tablePanel:groupForm:checkgroup:dataTable", "director");
assertNotNull(component);
TESTER.clickLink(component.getPageRelativePath()
+ ":cells:4:cell:panelManageResources:manageResourcesLink");
TESTER.assertComponent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:groupForm:"
+ "checkgroup:dataTable", WebMarkupContainer.class);
TESTER.clickLink(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:firstLevelContainer:first:"
+ "container:content:searchContainer:resultTable:tablePanel:groupForm:checkgroup:dataTable:topToolbars:"
+ "toolbars:1:headers:2:header:orderByLink", true);
component = findComponentByProp("resourceName",
TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:groupForm:"
+ "checkgroup:dataTable", "ws-target-resource-1");
assertNotNull(component);
FormTester formTester = TESTER.newFormTester(
TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:firstLevelContainer:"
+ "first:container:content:searchContainer:resultTable:tablePanel:groupForm");
assertNotNull(formTester);
formTester.select("checkgroup", 7);
TESTER.executeAjaxEvent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:bulkActionLink",
Constants.ON_CLICK);
TESTER.assertComponent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "secondLevelContainer:second:container", WebMarkupContainer.class);
assertNotNull(findComponentByProp("resourceName", TAB_PANEL + "outerObjectsRepeater:1:outer:"
+ "form:content:status:secondLevelContainer:second:container:selectedObjects", "resource-testdb2"));
}
@Test
public void printerResourceBulkAction() {
TESTER.clickLink("body:realmsLI:realms");
TESTER.clickLink("body:content:body:container:content:tabbedPanel:tabs-container:tabs:3:link");
Component component = findComponentByProp("key", CONTAINER
+ ":searchContainer:resultTable:tablePanel:groupForm:checkgroup:dataTable",
"8559d14d-58c2-46eb-a2d4-a7d35161e8f8");
assertNotNull(component);
TESTER.clickLink(component.getPageRelativePath()
+ ":cells:4:cell:panelManageResources:manageResourcesLink");
TESTER.assertComponent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:groupForm:"
+ "checkgroup:dataTable", WebMarkupContainer.class);
TESTER.clickLink(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:firstLevelContainer:first:"
+ "container:content:searchContainer:resultTable:tablePanel:groupForm:checkgroup:dataTable:topToolbars:"
+ "toolbars:1:headers:2:header:orderByLink", true);
component = findComponentByProp("resourceName",
TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:groupForm:"
+ "checkgroup:dataTable", "ws-target-resource-1");
assertNotNull(component);
FormTester formTester = TESTER.newFormTester(
TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:firstLevelContainer:"
+ "first:container:content:searchContainer:resultTable:tablePanel:groupForm");
assertNotNull(formTester);
formTester.select("checkgroup", 7);
TESTER.executeAjaxEvent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:bulkActionLink",
Constants.ON_CLICK);
TESTER.assertComponent(TAB_PANEL + "outerObjectsRepeater:1:outer:form:content:status:"
+ "secondLevelContainer:second:container", WebMarkupContainer.class);
assertNotNull(findComponentByProp("resourceName", TAB_PANEL + "outerObjectsRepeater:1:outer:"
+ "form:content:status:secondLevelContainer:second:container:selectedObjects", "resource-testdb2"));
}
@Test
public void executePropagationTask() {
TESTER.clickLink("body:topologyLI:topology");
Component component = findComponentByProp("key", "body:resources", "resource-testdb");
assertNotNull(component);
TESTER.executeAjaxEvent(component.getPageRelativePath() + ":res", Constants.ON_CLICK);
TESTER.clickLink("body:toggle:container:content:togglePanelContainer:container:actions:propagation");
FormTester formTester = TESTER.newFormTester(
"body:toggle:outerObjectsRepeater:1:outer:form:content:tasks:firstLevelContainer:first:container:"
+ "content:searchContainer:resultTable:tablePanel:groupForm");
assertNotNull(formTester);
formTester.select("checkgroup", 0);
TESTER.executeAjaxEvent("body:toggle:outerObjectsRepeater:1:outer:form:content:tasks:"
+ "firstLevelContainer:first:container:content:searchContainer:resultTable:tablePanel:bulkActionLink",
Constants.ON_CLICK);
TESTER.assertComponent("body:toggle:outerObjectsRepeater:1:outer:form:content:tasks:secondLevelContainer:"
+ "second:container:selectedObjects:body:rows:1:cells:1:cell", Label.class);
}
}
| |
/*
* Copyright 2009-2012 Aluminum project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.aluminumproject.utilities.text;
import com.googlecode.aluminumproject.AluminumException;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Splits text on a number of separators, which are expressed as patterns (regular expressions). Text is scanned from
* the left to the right; each time a separator is found, a {@link TokenProcessor token processor} is notified of the
* token before the separator, the separator itself, and the separator pattern that matches the separator. If multiple
* separator patterns can match, the longest separator will be chosen. The last token will be offered to the token
* processor with the empty string as separator and {@code null} as separator pattern.
* <p>
* A character can be escaped to prevent it from being recognised as (part of) a separator. To escape a character,
* create a splitter with an escape character and put the escape character in front of each character that should be
* escaped. Another way to prevent tokens to be identified as separators is quoting them. To do so, create a splitter
* with one or more {@link QuotationCharacters quotation characters} and surround the token text with the quotation
* characters.
*/
public class Splitter {
private List<Pattern> separatorPatterns;
private char escapeCharacter;
private List<QuotationCharacters> quotationCharacters;
/**
* Creates a splitter with a number of separator patterns, but without an escape character or quotation characters.
*
* @param separatorPatterns the separator patterns to use
*/
public Splitter(List<String> separatorPatterns) {
this(separatorPatterns, '\0', Collections.<QuotationCharacters>emptyList());
}
/**
* Creates a splitter with a number of separator patterns and an escape character, but without quotation characters.
*
* @param separatorPatterns the separator patterns to use
* @param escapeCharacter the escape character to use
*/
public Splitter(List<String> separatorPatterns, char escapeCharacter) {
this(separatorPatterns, escapeCharacter, Collections.<QuotationCharacters>emptyList());
}
/**
* Creates a splitter with a number of separator patterns and a number of quotation characters, but without an
* escape character.
*
* @param separatorPatterns the separator patterns to use
* @param quotationCharacters the quotation characters to use
*/
public Splitter(List<String> separatorPatterns, List<QuotationCharacters> quotationCharacters) {
this(separatorPatterns, '\0', quotationCharacters);
}
/**
* Creates a splitter.
*
* @param separatorPatterns the separator patterns to use
* @param escapeCharacter the escape character to use
* @param quotationCharacters the quotation characters to use
*/
public Splitter(List<String> separatorPatterns,
char escapeCharacter, List<QuotationCharacters> quotationCharacters) {
this.separatorPatterns = new LinkedList<Pattern>();
for (String separatorPattern: separatorPatterns) {
this.separatorPatterns.add(Pattern.compile(separatorPattern));
}
this.escapeCharacter = escapeCharacter;
this.quotationCharacters = quotationCharacters;
}
/**
* Splits text as explained in the class description and notifies a token processor of each token.
*
* @param text the text to split
* @param tokenProcessor the token processor to notify of each token that can be found
* @throws AluminumException when the text to split ends with an escape character, when it contains an unclosed
* quote character, or when the token processor can't process one of the tokens
*/
public void split(String text, TokenProcessor tokenProcessor) throws AluminumException {
StringBuilder textBuffer = new StringBuilder();
StringBuilder matchTextBuffer = new StringBuilder();
fillBuffers(text, textBuffer, matchTextBuffer);
processTokens(textBuffer, findMatches(matchTextBuffer), tokenProcessor);
}
private void fillBuffers(
String text, StringBuilder textBuffer, StringBuilder matchTextBuffer) throws AluminumException {
boolean escaping = false;
QuotationCharacters quotationCharacters = null;
for (char character: text.toCharArray()) {
if (escaping) {
textBuffer.append(character);
matchTextBuffer.append('\0');
escaping = false;
} else if (character == escapeCharacter) {
escaping = true;
} else if (quotationCharacters == null) {
quotationCharacters = findQuotationCharacters(character);
if ((quotationCharacters == null) || quotationCharacters.keep) {
textBuffer.append(character);
matchTextBuffer.append((quotationCharacters == null) ? character : '\0');
}
} else {
if ((character != quotationCharacters.closingCharacter) || quotationCharacters.keep) {
textBuffer.append(character);
matchTextBuffer.append('\0');
}
if (character == quotationCharacters.closingCharacter) {
quotationCharacters = null;
}
}
}
if (escaping) {
throw new AluminumException("escape character ", escapeCharacter, " does not escape anything");
} else if (quotationCharacters != null) {
throw new AluminumException("quotation character ", quotationCharacters.openingCharacter, " is not closed");
}
}
private QuotationCharacters findQuotationCharacters(char character) {
QuotationCharacters quotationCharacters = null;
Iterator<QuotationCharacters> it = this.quotationCharacters.iterator();
while ((quotationCharacters == null) && it.hasNext()) {
QuotationCharacters currentQuotationCharacters = it.next();
if (character == currentQuotationCharacters.openingCharacter) {
quotationCharacters = currentQuotationCharacters;
}
}
return quotationCharacters;
}
private List<Match> findMatches(StringBuilder buffer) {
List<Match> matches = new LinkedList<Match>();
Match match;
int i = 0;
do {
match = null;
for (Pattern separatorPattern: separatorPatterns) {
Matcher matcher = separatorPattern.matcher(buffer);
if (matcher.find(i)) {
int startIndex = matcher.start();
int endIndex = matcher.end();
if ((match == null) || (startIndex < match.startIndex) ||
((startIndex == match.startIndex) &&
((endIndex - startIndex) > (match.endIndex - match.startIndex)))) {
match = new Match(startIndex, endIndex, separatorPattern.pattern());
}
}
}
if (match != null) {
matches.add(match);
i = match.endIndex;
}
} while ((i < buffer.length()) && (match != null));
return matches;
}
private void processTokens(
StringBuilder buffer, List<Match> matches, TokenProcessor tokenProcessor) throws AluminumException {
Match match;
int offset = 0;
do {
match = findMatch(matches, offset);
String token;
String separator;
String separatorPattern;
if (match == null) {
token = buffer.substring(offset, buffer.length());
separator = "";
separatorPattern = null;
} else {
token = buffer.substring(offset, match.startIndex);
separator = buffer.substring(match.startIndex, match.endIndex);
separatorPattern = match.separatorPattern;
offset = match.endIndex;
}
tokenProcessor.process(token, separator, separatorPattern);
} while (match != null);
}
private Match findMatch(List<Match> matches, int offset) {
Match match = null;
for (Match possibleMatch: matches) {
if ((possibleMatch.startIndex >= offset) &&
((match == null) || possibleMatch.isSoonerThan(match) || possibleMatch.isLongerThan(match))) {
match = possibleMatch;
}
}
return match;
}
private static class Match {
private final int startIndex;
private final int endIndex;
private final String separatorPattern;
public Match(int startIndex, int endIndex, String separatorPattern) {
this.startIndex = startIndex;
this.endIndex = endIndex;
this.separatorPattern = separatorPattern;
}
public boolean isSoonerThan(Match match) {
return startIndex < match.startIndex;
}
public boolean isLongerThan(Match match) {
return (startIndex == match.startIndex) && (endIndex > match.endIndex);
}
}
/**
* A pair of characters that can be used to prevent a {@link Splitter splitter} from seeing text as (part of) a
* separator.
*/
public static class QuotationCharacters {
private final char openingCharacter;
private final char closingCharacter;
private final boolean keep;
/**
* Creates a pair of quotation characters.
*
* @param openingCharacter the character that is used to open the quoted text
* @param closingCharacter the character that is used to close the quoted text
* @param keep whether the quotation characters should be part of the token that is given to the token processor
*/
public QuotationCharacters(char openingCharacter, char closingCharacter, boolean keep) {
this.openingCharacter = openingCharacter;
this.closingCharacter = closingCharacter;
this.keep = keep;
}
}
/**
* Will be notified of each token found by a {@link Splitter splitter}.
*/
public static interface TokenProcessor {
/**
* Processes a token that is found by a splitter.
*
* @param token the text before the separator
* @param separator the separator that was found (the empty string in case of the last token)
* @param separatorPattern the pattern that matches the separator that was found ({@code null} for the last
* token)
* @throws AluminumException when the token can't be processed (e.g. when the separator order is unexpected)
*/
void process(String token, String separator, String separatorPattern) throws AluminumException;
}
}
| |
/*
* 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.facebook.presto.block;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.block.BlockBuilder;
import com.facebook.presto.common.block.DictionaryBlock;
import com.facebook.presto.common.block.RowBlockBuilder;
import com.facebook.presto.common.block.RunLengthEncodedBlock;
import com.facebook.presto.common.function.OperatorType;
import com.facebook.presto.common.type.ArrayType;
import com.facebook.presto.common.type.DecimalType;
import com.facebook.presto.common.type.MapType;
import com.facebook.presto.common.type.RowType;
import com.facebook.presto.common.type.Type;
import io.airlift.slice.Slice;
import java.lang.invoke.MethodHandle;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;
import static com.facebook.presto.common.block.ArrayBlock.fromElementBlock;
import static com.facebook.presto.common.block.DictionaryId.randomDictionaryId;
import static com.facebook.presto.common.block.MethodHandleUtil.compose;
import static com.facebook.presto.common.block.MethodHandleUtil.nativeValueGetter;
import static com.facebook.presto.common.block.RowBlock.fromFieldBlocks;
import static com.facebook.presto.common.type.BigintType.BIGINT;
import static com.facebook.presto.common.type.BooleanType.BOOLEAN;
import static com.facebook.presto.common.type.DateType.DATE;
import static com.facebook.presto.common.type.Decimals.MAX_SHORT_PRECISION;
import static com.facebook.presto.common.type.Decimals.encodeUnscaledValue;
import static com.facebook.presto.common.type.Decimals.writeBigDecimal;
import static com.facebook.presto.common.type.DoubleType.DOUBLE;
import static com.facebook.presto.common.type.IntegerType.INTEGER;
import static com.facebook.presto.common.type.RealType.REAL;
import static com.facebook.presto.common.type.SmallintType.SMALLINT;
import static com.facebook.presto.common.type.TimestampType.TIMESTAMP;
import static com.facebook.presto.common.type.TimestampWithTimeZoneType.TIMESTAMP_WITH_TIME_ZONE;
import static com.facebook.presto.common.type.VarbinaryType.VARBINARY;
import static com.facebook.presto.common.type.VarcharType.VARCHAR;
import static com.facebook.presto.testing.TestingConnectorSession.SESSION;
import static com.facebook.presto.testing.TestingEnvironment.getOperatorMethodHandle;
import static com.facebook.presto.util.StructuralTestUtil.appendToBlockBuilder;
import static com.google.common.base.Preconditions.checkArgument;
import static io.airlift.slice.Slices.utf8Slice;
import static io.airlift.slice.Slices.wrappedBuffer;
import static java.lang.Float.floatToRawIntBits;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
import static org.testng.Assert.assertEquals;
public final class BlockAssertions
{
private static final int ENTRY_SIZE = 4;
private static final int MAX_STRING_SIZE = 50;
private BlockAssertions()
{
}
public static Object getOnlyValue(Type type, Block block)
{
assertEquals(block.getPositionCount(), 1, "Block positions");
return type.getObjectValue(SESSION.getSqlFunctionProperties(), block, 0);
}
public static List<Object> toValues(Type type, Iterable<Block> blocks)
{
List<Object> values = new ArrayList<>();
for (Block block : blocks) {
for (int position = 0; position < block.getPositionCount(); position++) {
values.add(type.getObjectValue(SESSION.getSqlFunctionProperties(), block, position));
}
}
return Collections.unmodifiableList(values);
}
public static List<Object> toValues(Type type, Block block)
{
List<Object> values = new ArrayList<>();
for (int position = 0; position < block.getPositionCount(); position++) {
values.add(type.getObjectValue(SESSION.getSqlFunctionProperties(), block, position));
}
return Collections.unmodifiableList(values);
}
public static void assertBlockEquals(Type type, Block actual, Block expected)
{
assertEquals(actual.getPositionCount(), expected.getPositionCount());
for (int position = 0; position < actual.getPositionCount(); position++) {
assertEquals(type.getObjectValue(SESSION.getSqlFunctionProperties(), actual, position), type.getObjectValue(SESSION.getSqlFunctionProperties(), expected, position));
}
}
public static Block createEmptyBlock(Type type)
{
return createAllNullsBlock(type, 0);
}
public static Block createAllNullsBlock(Type type, int positionCount)
{
BlockBuilder blockBuilder = type.createBlockBuilder(null, 1);
for (int i = 0; i < positionCount; i++) {
blockBuilder.appendNull();
}
return blockBuilder.build();
}
public static Block createStringsBlock(String... values)
{
requireNonNull(values, "varargs 'values' is null");
return createStringsBlock(Arrays.asList(values));
}
public static Block createStringsBlock(Iterable<String> values)
{
BlockBuilder builder = VARCHAR.createBlockBuilder(null, (int) StreamSupport.stream(values.spliterator(), false).count());
for (String value : values) {
if (value == null) {
builder.appendNull();
}
else {
VARCHAR.writeString(builder, value);
}
}
return builder.build();
}
public static Block createRandomStringBlock(int positionCount, float nullRate, int maxStringLength)
{
ValuesWithNullsGenerator<String> generator = new ValuesWithNullsGenerator(nullRate, () -> generateRandomStringWithLength(maxStringLength));
return createStringsBlock(
IntStream.range(0, positionCount)
.mapToObj(i -> generator.next())
.collect(Collectors.toList()));
}
public static Block createSlicesBlock(Slice... values)
{
requireNonNull(values, "varargs 'values' is null");
return createSlicesBlock(Arrays.asList(values));
}
public static Block createSlicesBlock(Iterable<Slice> values)
{
BlockBuilder builder = VARBINARY.createBlockBuilder(null, 100);
for (Slice value : values) {
if (value == null) {
builder.appendNull();
}
else {
VARBINARY.writeSlice(builder, value);
}
}
return builder.build();
}
public static Block createStringSequenceBlock(int start, int end)
{
BlockBuilder builder = VARCHAR.createBlockBuilder(null, 100);
for (int i = start; i < end; i++) {
VARCHAR.writeString(builder, String.valueOf(i));
}
return builder.build();
}
public static Block createStringDictionaryBlock(int start, int length)
{
checkArgument(length > 5, "block must have more than 5 entries");
int dictionarySize = length / 5;
BlockBuilder builder = VARCHAR.createBlockBuilder(null, dictionarySize);
for (int i = start; i < start + dictionarySize; i++) {
VARCHAR.writeString(builder, String.valueOf(i));
}
int[] ids = new int[length];
for (int i = 0; i < length; i++) {
ids[i] = i % dictionarySize;
}
return new DictionaryBlock(builder.build(), ids);
}
public static Block createStringArraysBlock(Iterable<? extends Iterable<String>> values)
{
ArrayType arrayType = new ArrayType(VARCHAR);
BlockBuilder builder = arrayType.createBlockBuilder(null, 100);
for (Iterable<String> value : values) {
if (value == null) {
builder.appendNull();
}
else {
arrayType.writeObject(builder, createStringsBlock(value));
}
}
return builder.build();
}
public static <K, V> Block createMapBlock(MapType type, Map<K, V> map)
{
BlockBuilder blockBuilder = type.createBlockBuilder(null, map.size());
for (Map.Entry<K, V> entry : map.entrySet()) {
BlockBuilder entryBuilder = blockBuilder.beginBlockEntry();
appendToBlockBuilder(BIGINT, entry.getKey(), entryBuilder);
appendToBlockBuilder(BIGINT, entry.getValue(), entryBuilder);
blockBuilder.closeEntry();
}
return blockBuilder.build();
}
public static Block createBooleansBlock(Boolean... values)
{
requireNonNull(values, "varargs 'values' is null");
return createBooleansBlock(Arrays.asList(values));
}
public static Block createBooleansBlock(Boolean value, int count)
{
return createBooleansBlock(Collections.nCopies(count, value));
}
public static Block createBooleansBlock(Iterable<Boolean> values)
{
BlockBuilder builder = BOOLEAN.createBlockBuilder(null, 100);
for (Boolean value : values) {
if (value == null) {
builder.appendNull();
}
else {
BOOLEAN.writeBoolean(builder, value);
}
}
return builder.build();
}
// Note: Make sure positionCount is sufficiently large if nullRate is greater than 0
public static Block createRandomBooleansBlock(int positionCount, float nullRate)
{
ValuesWithNullsGenerator<Boolean> generator = new ValuesWithNullsGenerator(nullRate, () -> ThreadLocalRandom.current().nextBoolean());
return createBooleansBlock(
IntStream.range(0, positionCount)
.mapToObj(i -> generator.next())
.collect(Collectors.toList()));
}
public static Block createShortDecimalsBlock(String... values)
{
requireNonNull(values, "varargs 'values' is null");
return createShortDecimalsBlock(Arrays.asList(values));
}
public static Block createShortDecimalsBlock(Iterable<String> values)
{
DecimalType shortDecimalType = DecimalType.createDecimalType(1);
BlockBuilder builder = shortDecimalType.createBlockBuilder(null, 100);
for (String value : values) {
if (value == null) {
builder.appendNull();
}
else {
shortDecimalType.writeLong(builder, new BigDecimal(value).unscaledValue().longValue());
}
}
return builder.build();
}
// Note: Make sure positionCount is sufficiently large if nullRate is greater than 0
public static Block createRandomShortDecimalsBlock(int positionCount, float nullRate)
{
ValuesWithNullsGenerator<String> generator = new ValuesWithNullsGenerator(nullRate, () -> Double.toString(ThreadLocalRandom.current().nextDouble() * ThreadLocalRandom.current().nextInt()));
return createShortDecimalsBlock(
IntStream.range(0, positionCount)
.mapToObj(i -> generator.next())
.collect(Collectors.toList()));
}
public static Block createLongDecimalsBlock(String... values)
{
requireNonNull(values, "varargs 'values' is null");
return createLongDecimalsBlock(Arrays.asList(values));
}
public static Block createLongDecimalsBlock(Iterable<String> values)
{
DecimalType longDecimalType = DecimalType.createDecimalType(MAX_SHORT_PRECISION + 1);
BlockBuilder builder = longDecimalType.createBlockBuilder(null, 100);
for (String value : values) {
if (value == null) {
builder.appendNull();
}
else {
writeBigDecimal(longDecimalType, builder, new BigDecimal(value));
}
}
return builder.build();
}
// Note: Make sure positionCount is sufficiently large if nullRate is greater than 0
public static Block createRandomLongDecimalsBlock(int positionCount, float nullRate)
{
ValuesWithNullsGenerator<String> generator = new ValuesWithNullsGenerator(nullRate, () -> Double.toString(ThreadLocalRandom.current().nextDouble() * ThreadLocalRandom.current().nextInt()));
return createLongDecimalsBlock(
IntStream.range(0, positionCount)
.mapToObj(i -> generator.next())
.collect(Collectors.toList()));
}
public static Block createIntsBlock(Integer... values)
{
requireNonNull(values, "varargs 'values' is null");
return createIntsBlock(Arrays.asList(values));
}
public static Block createIntsBlock(Iterable<Integer> values)
{
BlockBuilder builder = INTEGER.createBlockBuilder(null, 100);
for (Integer value : values) {
if (value == null) {
builder.appendNull();
}
else {
INTEGER.writeLong(builder, value);
}
}
return builder.build();
}
public static Block createRowBlock(List<Type> fieldTypes, Object[]... rows)
{
BlockBuilder rowBlockBuilder = new RowBlockBuilder(fieldTypes, null, 1);
for (Object[] row : rows) {
if (row == null) {
rowBlockBuilder.appendNull();
continue;
}
BlockBuilder singleRowBlockWriter = rowBlockBuilder.beginBlockEntry();
for (Object fieldValue : row) {
if (fieldValue == null) {
singleRowBlockWriter.appendNull();
continue;
}
if (fieldValue instanceof String) {
VARCHAR.writeSlice(singleRowBlockWriter, utf8Slice((String) fieldValue));
}
else if (fieldValue instanceof Slice) {
VARBINARY.writeSlice(singleRowBlockWriter, (Slice) fieldValue);
}
else if (fieldValue instanceof Double) {
DOUBLE.writeDouble(singleRowBlockWriter, ((Double) fieldValue).doubleValue());
}
else if (fieldValue instanceof Long) {
BIGINT.writeLong(singleRowBlockWriter, ((Long) fieldValue).longValue());
}
else if (fieldValue instanceof Boolean) {
BOOLEAN.writeBoolean(singleRowBlockWriter, ((Boolean) fieldValue).booleanValue());
}
else if (fieldValue instanceof Block) {
singleRowBlockWriter.appendStructure((Block) fieldValue);
}
else if (fieldValue instanceof Integer) {
INTEGER.writeLong(singleRowBlockWriter, ((Integer) fieldValue).intValue());
}
else {
throw new IllegalArgumentException();
}
}
rowBlockBuilder.closeEntry();
}
return rowBlockBuilder.build();
}
// Note: Make sure positionCount is sufficiently large if nullRate is greater than 0
public static Block createRandomIntsBlock(int positionCount, float nullRate)
{
ValuesWithNullsGenerator<Integer> generator = new ValuesWithNullsGenerator(nullRate, () -> ThreadLocalRandom.current().nextInt());
return createIntsBlock(
IntStream.range(0, positionCount)
.mapToObj(i -> generator.next())
.collect(Collectors.toList()));
}
public static Block createEmptyLongsBlock()
{
return BIGINT.createFixedSizeBlockBuilder(0).build();
}
// This method makes it easy to create blocks without having to add an L to every value
public static Block createLongsBlock(int... values)
{
BlockBuilder builder = BIGINT.createBlockBuilder(null, 100);
for (int value : values) {
BIGINT.writeLong(builder, (long) value);
}
return builder.build();
}
public static Block createLongsBlock(Long... values)
{
requireNonNull(values, "varargs 'values' is null");
return createLongsBlock(Arrays.asList(values));
}
public static Block createLongsBlock(Iterable<Long> values)
{
return createTypedLongsBlock(BIGINT, values);
}
// Note: Make sure positionCount is sufficiently large if nullRate is greater than 0
public static Block createRandomLongsBlock(int positionCount, float nullRate)
{
ValuesWithNullsGenerator<Long> generator = new ValuesWithNullsGenerator(nullRate, () -> ThreadLocalRandom.current().nextLong());
return createLongsBlock(
IntStream.range(0, positionCount)
.mapToObj(i -> generator.next())
.collect(Collectors.toList()));
}
public static Block createTypedLongsBlock(Type type, Iterable<Long> values)
{
BlockBuilder builder = type.createBlockBuilder(null, 100);
for (Long value : values) {
if (value == null) {
builder.appendNull();
}
else {
type.writeLong(builder, value);
}
}
return builder.build();
}
// Note: Make sure positionCount is sufficiently large if nullRate is greater than 0
public static Block createRandomSmallintsBlock(int positionCount, float nullRate)
{
ValuesWithNullsGenerator<Long> generator = new ValuesWithNullsGenerator(nullRate, () -> ThreadLocalRandom.current().nextLong() % Short.MIN_VALUE);
return createTypedLongsBlock(
SMALLINT,
IntStream.range(0, positionCount)
.mapToObj(i -> generator.next())
.collect(Collectors.toList()));
}
public static Block createLongSequenceBlock(int start, int end)
{
BlockBuilder builder = BIGINT.createFixedSizeBlockBuilder(end - start);
for (int i = start; i < end; i++) {
BIGINT.writeLong(builder, i);
}
return builder.build();
}
public static Block createLongDictionaryBlock(int start, int length)
{
checkArgument(length > 5, "block must have more than 5 entries");
int dictionarySize = length / 5;
BlockBuilder builder = BIGINT.createBlockBuilder(null, dictionarySize);
for (int i = start; i < start + dictionarySize; i++) {
BIGINT.writeLong(builder, i);
}
int[] ids = new int[length];
for (int i = 0; i < length; i++) {
ids[i] = i % dictionarySize;
}
return new DictionaryBlock(builder.build(), ids);
}
public static Block createLongRepeatBlock(int value, int length)
{
BlockBuilder builder = BIGINT.createFixedSizeBlockBuilder(length);
for (int i = 0; i < length; i++) {
BIGINT.writeLong(builder, value);
}
return builder.build();
}
public static Block createTimestampsWithTimezoneBlock(Long... values)
{
BlockBuilder builder = TIMESTAMP_WITH_TIME_ZONE.createFixedSizeBlockBuilder(values.length);
for (long value : values) {
TIMESTAMP_WITH_TIME_ZONE.writeLong(builder, value);
}
return builder.build();
}
public static Block createBooleanSequenceBlock(int start, int end)
{
BlockBuilder builder = BOOLEAN.createFixedSizeBlockBuilder(end - start);
for (int i = start; i < end; i++) {
BOOLEAN.writeBoolean(builder, i % 2 == 0);
}
return builder.build();
}
public static Block createBlockOfReals(Float... values)
{
requireNonNull(values, "varargs 'values' is null");
return createBlockOfReals(Arrays.asList(values));
}
private static Block createBlockOfReals(Iterable<Float> values)
{
BlockBuilder builder = REAL.createBlockBuilder(null, 100);
for (Float value : values) {
if (value == null) {
builder.appendNull();
}
else {
REAL.writeLong(builder, floatToRawIntBits(value));
}
}
return builder.build();
}
public static Block createSequenceBlockOfReal(int start, int end)
{
BlockBuilder builder = REAL.createFixedSizeBlockBuilder(end - start);
for (int i = start; i < end; i++) {
REAL.writeLong(builder, floatToRawIntBits((float) i));
}
return builder.build();
}
public static Block createDoublesBlock(Double... values)
{
requireNonNull(values, "varargs 'values' is null");
return createDoublesBlock(Arrays.asList(values));
}
public static Block createDoublesBlock(Iterable<Double> values)
{
BlockBuilder builder = DOUBLE.createBlockBuilder(null, 100);
for (Double value : values) {
if (value == null) {
builder.appendNull();
}
else {
DOUBLE.writeDouble(builder, value);
}
}
return builder.build();
}
public static Block createDoubleSequenceBlock(int start, int end)
{
BlockBuilder builder = DOUBLE.createFixedSizeBlockBuilder(end - start);
for (int i = start; i < end; i++) {
DOUBLE.writeDouble(builder, (double) i);
}
return builder.build();
}
public static Block createArrayBigintBlock(Iterable<? extends Iterable<Long>> values)
{
ArrayType arrayType = new ArrayType(BIGINT);
BlockBuilder builder = arrayType.createBlockBuilder(null, 100);
for (Iterable<Long> value : values) {
if (value == null) {
builder.appendNull();
}
else {
arrayType.writeObject(builder, createLongsBlock(value));
}
}
return builder.build();
}
public static Block createDateSequenceBlock(int start, int end)
{
BlockBuilder builder = DATE.createFixedSizeBlockBuilder(end - start);
for (int i = start; i < end; i++) {
DATE.writeLong(builder, i);
}
return builder.build();
}
public static Block createTimestampSequenceBlock(int start, int end)
{
BlockBuilder builder = TIMESTAMP.createFixedSizeBlockBuilder(end - start);
for (int i = start; i < end; i++) {
TIMESTAMP.writeLong(builder, i);
}
return builder.build();
}
public static Block createShortDecimalSequenceBlock(int start, int end, DecimalType type)
{
BlockBuilder builder = type.createFixedSizeBlockBuilder(end - start);
long base = BigInteger.TEN.pow(type.getScale()).longValue();
for (int i = start; i < end; ++i) {
type.writeLong(builder, base * i);
}
return builder.build();
}
public static Block createLongDecimalSequenceBlock(int start, int end, DecimalType type)
{
BlockBuilder builder = type.createFixedSizeBlockBuilder(end - start);
BigInteger base = BigInteger.TEN.pow(type.getScale());
for (int i = start; i < end; ++i) {
type.writeSlice(builder, encodeUnscaledValue(BigInteger.valueOf(i).multiply(base)));
}
return builder.build();
}
public static RunLengthEncodedBlock createRLEBlock(double value, int positionCount)
{
BlockBuilder blockBuilder = DOUBLE.createBlockBuilder(null, 1);
DOUBLE.writeDouble(blockBuilder, value);
return new RunLengthEncodedBlock(blockBuilder.build(), positionCount);
}
public static RunLengthEncodedBlock createRLEBlock(long value, int positionCount)
{
BlockBuilder blockBuilder = BIGINT.createBlockBuilder(null, 1);
BIGINT.writeLong(blockBuilder, value);
return new RunLengthEncodedBlock(blockBuilder.build(), positionCount);
}
public static RunLengthEncodedBlock createRLEBlock(String value, int positionCount)
{
BlockBuilder blockBuilder = VARCHAR.createBlockBuilder(null, 1);
VARCHAR.writeSlice(blockBuilder, wrappedBuffer(value.getBytes()));
return new RunLengthEncodedBlock(blockBuilder.build(), positionCount);
}
public static RunLengthEncodedBlock createRleBlockWithRandomValue(Block block, int positionCount)
{
checkArgument(block.getPositionCount() > 0, format("block positions %d is less than or equal to 0", block.getPositionCount()));
return new RunLengthEncodedBlock(block.getRegion(block.getPositionCount() / 2, 1), positionCount);
}
public static DictionaryBlock createRandomDictionaryBlock(Block dictionary, int positionCount)
{
return createRandomDictionaryBlock(dictionary, positionCount, false);
}
public static DictionaryBlock createRandomDictionaryBlock(Block dictionary, int positionCount, boolean isView)
{
checkArgument(dictionary.getPositionCount() > 0, format("dictionary's positionCount %d is less than or equal to 0", dictionary.getPositionCount()));
int idsOffset = 0;
if (isView) {
idsOffset = min(ThreadLocalRandom.current().nextInt(dictionary.getPositionCount()), 1);
}
int[] ids = IntStream.range(0, positionCount + idsOffset).map(i -> ThreadLocalRandom.current().nextInt(max(dictionary.getPositionCount() / 10, 1))).toArray();
return new DictionaryBlock(idsOffset, positionCount, dictionary, ids, false, randomDictionaryId());
}
// Note: Make sure positionCount is sufficiently large if nestedNullRate or primitiveNullRate is greater than 0
public static Block createRandomBlockForType(
Type type,
int positionCount,
float primitiveNullRate,
float nestedNullRate,
boolean createView,
List<Encoding> wrappings)
{
verifyNullRate(primitiveNullRate);
verifyNullRate(nestedNullRate);
Block block = null;
if (createView) {
positionCount *= 2;
}
if (type == BOOLEAN) {
block = createRandomBooleansBlock(positionCount, primitiveNullRate);
}
else if (type == BIGINT) {
block = createRandomLongsBlock(positionCount, primitiveNullRate);
}
else if (type == INTEGER || type == REAL) {
block = createRandomIntsBlock(positionCount, primitiveNullRate);
}
else if (type == SMALLINT) {
block = createRandomSmallintsBlock(positionCount, primitiveNullRate);
}
else if (type instanceof DecimalType) {
DecimalType decimalType = (DecimalType) type;
if (decimalType.isShort()) {
block = createRandomLongsBlock(positionCount, primitiveNullRate);
}
else {
block = createRandomLongDecimalsBlock(positionCount, primitiveNullRate);
}
}
else if (type == VARCHAR) {
block = createRandomStringBlock(positionCount, primitiveNullRate, MAX_STRING_SIZE);
}
else {
// Nested types
// Build isNull and offsets of size positionCount
boolean[] isNull = null;
if (nestedNullRate > 0) {
isNull = new boolean[positionCount];
}
int[] offsets = new int[positionCount + 1];
for (int position = 0; position < positionCount; position++) {
if (nestedNullRate > 0 && ThreadLocalRandom.current().nextDouble(1) < nestedNullRate) {
isNull[position] = true;
offsets[position + 1] = offsets[position];
}
else {
offsets[position + 1] = offsets[position] + (type instanceof RowType ? 1 : ThreadLocalRandom.current().nextInt(ENTRY_SIZE) + 1);
}
}
// Build the nested block of size offsets[positionCount].
if (type instanceof ArrayType) {
Block valuesBlock = createRandomBlockForType(((ArrayType) type).getElementType(), offsets[positionCount], primitiveNullRate, nestedNullRate, createView, wrappings);
block = fromElementBlock(positionCount, Optional.ofNullable(isNull), offsets, valuesBlock);
}
else if (type instanceof MapType) {
MapType mapType = (MapType) type;
Block keyBlock = createRandomBlockForType(mapType.getKeyType(), offsets[positionCount], 0.0f, 0.0f, createView, wrappings);
Block valueBlock = createRandomBlockForType(mapType.getValueType(), offsets[positionCount], primitiveNullRate, nestedNullRate, createView, wrappings);
block = mapType.createBlockFromKeyValue(positionCount, Optional.ofNullable(isNull), offsets, keyBlock, valueBlock);
}
else if (type instanceof RowType) {
List<Type> fieldTypes = type.getTypeParameters();
Block[] fieldBlocks = new Block[fieldTypes.size()];
for (int i = 0; i < fieldBlocks.length; i++) {
fieldBlocks[i] = createRandomBlockForType(fieldTypes.get(i), positionCount, primitiveNullRate, nestedNullRate, createView, wrappings);
}
block = fromFieldBlocks(positionCount, Optional.ofNullable(isNull), fieldBlocks);
}
else {
throw new IllegalArgumentException(format("type %s is not supported.", type));
}
}
if (createView) {
positionCount /= 2;
int offset = positionCount / 2;
block = block.getRegion(offset, positionCount);
}
if (!wrappings.isEmpty()) {
block = wrapBlock(block, positionCount, wrappings);
}
return block;
}
public static Block wrapBlock(Block block, int positionCount, List<Encoding> wrappings)
{
checkArgument(!wrappings.isEmpty(), "wrappings is empty");
Block wrappedBlock = block;
for (int i = wrappings.size() - 1; i >= 0; i--) {
switch (wrappings.get(i)) {
case DICTIONARY:
wrappedBlock = createRandomDictionaryBlock(wrappedBlock, positionCount, true);
break;
case RUN_LENGTH:
wrappedBlock = createRleBlockWithRandomValue(wrappedBlock, positionCount);
break;
default:
throw new IllegalArgumentException(format("wrappings %s is incorrect", wrappings));
}
}
return wrappedBlock;
}
public static MapType createMapType(Type keyType, Type valueType)
{
MethodHandle keyNativeEquals = getOperatorMethodHandle(OperatorType.EQUAL, keyType, keyType);
MethodHandle keyBlockEquals = compose(keyNativeEquals, nativeValueGetter(keyType), nativeValueGetter(keyType));
MethodHandle keyNativeHashCode = getOperatorMethodHandle(OperatorType.HASH_CODE, keyType);
MethodHandle keyBlockHashCode = compose(keyNativeHashCode, nativeValueGetter(keyType));
return new MapType(
keyType,
valueType,
keyBlockEquals,
keyBlockHashCode);
}
public enum Encoding
{
DICTIONARY,
RUN_LENGTH
}
private static String generateRandomStringWithLength(int length)
{
byte[] array = new byte[length];
ThreadLocalRandom.current().nextBytes(array);
return new String(array, UTF_8);
}
private static final class ValuesWithNullsGenerator<T>
{
private final float nullRate;
private final Supplier<T> supplier;
private ValuesWithNullsGenerator(float nullRate, Supplier<T> supplier)
{
verifyNullRate(nullRate);
this.nullRate = nullRate;
this.supplier = requireNonNull(supplier, "supplier is null");
}
public T next()
{
return nullRate > 0 && ThreadLocalRandom.current().nextDouble(1) < nullRate ? null : supplier.get();
}
}
private static void verifyNullRate(float nullRate)
{
if (nullRate < 0 || nullRate > 1) {
throw new IllegalArgumentException(format("nullRate %f is not valid.", nullRate));
}
}
}
| |
/* JAT: Java Astrodynamics Toolkit
*
* Copyright (c) 2003 National Aeronautics and Space Administration. All rights reserved.
* This file is part of JAT. JAT is free software; you can
* redistribute it and/or modify it under the terms of the
* NASA Open Source Agreement
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* NASA Open Source Agreement for more details.
*
* You should have received a copy of the NASA Open Source Agreement
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
package jat.coreNOSA.attitude.eom;
import jat.coreNOSA.algorithm.integrators.EquationsOfMotion;
import jat.coreNOSA.algorithm.integrators.RungeKutta8;
import jat.coreNOSA.attitude.QuatToDeg;
import jat.coreNOSA.math.MatrixVector.data.Matrix;
import jat.coreNOSA.plotutil.FourPlots;
import jat.coreNOSA.plotutil.SinglePlot;
import jat.coreNOSA.plotutil.ThreePlots;
/**
* This class contains the equations of motion for the simulation
* of a rigid spacecraft subjected to gravity gradient torque
* while it orbit around the earth.The spacecraft has a spherical
* damper for stabilization.
*
* The class implements jat.alg.integrators.Derivatives and
* jat.alg.integrateors.Printble, so an outside application code
* can perform a numerical simulation of equations of motion
* defined in this class and get the output from the simulation.
*
* @author Noriko Takada
* Modification since the last version
* Switched to the interface EquationsOfMotion
*
*/
public class RSphericalDamper implements EquationsOfMotion
{
// time_step: Time step of numerical integration
// quat_values[][] Two dimensional array that contains quarternions from simulation
// I1,I2,I3 Principal moments of inertia about 1,2, and 3 axes
// c Damping coefficient
// j Spherical damper inertia
// rotation_plot Plots of angular velocities
// damper_rotation_plot Plots of angular velocities of spherical damper
// angle_plot Plots of euler angles
// quarternion_check Plot of e1^2 + e2^2 + e3^2 +e4^2
double time_step;
public int currentPts;
private float quat_values[][];
// Create variables for the necessary plots
private ThreePlots angular_velocity_plot = new ThreePlots();
private ThreePlots damper_rotation_plot = new ThreePlots();
private ThreePlots euler_angle_plot = new ThreePlots();
private SinglePlot quarternion_check = new SinglePlot();
private SinglePlot angular_momentum = new SinglePlot();
private FourPlots quaternion_plot = new FourPlots();
private double I1 = 2000;//10.42; // spacecraft inertia
private double I2 = 1500;//35.42;
private double I3 = 1000;//41.67;
private double c = 30; // damping coefficient
private double j = 18; // spherical damper inertia
public static final int GG_YES = 1;
public static final int GG_NO = 0;
private int gravity_gradient = 0;
/**
* Constructor 1
* @param time_step: Time step of numerical integration
* @param quat_values[][] Two dimensional array that contains quarternions from simulation
* @param I1 Principle moment of inertia about 1 axis
* @param I2 Principle moment of inertia about 2 axis
* @param I3 Principle moment of inertia about 3 axis
* @param c Damping coefficient
* @param j Spherical damper inertia
*/
public RSphericalDamper(double time_step, double I1, double I2, double I3,
double c, double j, float quat_values[][])
{
setupPlots();
this.time_step = time_step;
this.quat_values = quat_values;
this.I1 = I1;
this.I2 = I2;
this.I3 = I3;
this.c = c;
this.j = j;
}
/**
* Constructor 2
* @param time_step: Time step of numerical integration
* @param quat_values[][] Two dimensional array that contains quarternions from simulation
*/
public RSphericalDamper(double time_step, float quat_values[][])
{
setupPlots();
this.time_step = time_step;
this.quat_values = quat_values;
}
///**
// * Apply or Remove Gracity Gradient on a spacecraft
// * @param a (int) GG_YES = 1: Applies gravity gradient torque assming a circular orbit
// * GG_NO = 0: No gravity gradient, simulation in seconds
// */
//public void setGravityGradient(int a)
//{
// gravity_gradient = a;
//}
/**
* setupPlots() sets up Plots
*/
void setupPlots()
{
// Setup plots
angular_velocity_plot.setTitle("Angular Velocities");
angular_velocity_plot.topPlot.setXLabel("t(sec)");
angular_velocity_plot.topPlot.setYLabel("w1");
angular_velocity_plot.middlePlot.setXLabel("t(sec)");
angular_velocity_plot.middlePlot.setYLabel("w2");
angular_velocity_plot.bottomPlot.setXLabel("t(sec)");
angular_velocity_plot.bottomPlot.setYLabel("w3");
damper_rotation_plot.setTitle("Damper/Spacecraft relative rates");
damper_rotation_plot.topPlot.setXLabel("t (sec)");
damper_rotation_plot.topPlot.setYLabel("Sigma1");
damper_rotation_plot.middlePlot.setXLabel("t (sec)");
damper_rotation_plot.middlePlot.setYLabel("Sigma2 ");
damper_rotation_plot.bottomPlot.setXLabel("t (sec)");
damper_rotation_plot.bottomPlot.setYLabel("Sigma3");
euler_angle_plot.setTitle("Euler Angles");
euler_angle_plot.topPlot.setXLabel("t(sec)");
euler_angle_plot.topPlot.setYLabel("Theta(degrees)");
euler_angle_plot.middlePlot.setXLabel("t(sec)");
euler_angle_plot.middlePlot.setYLabel("Psi(degrees)");
euler_angle_plot.bottomPlot.setXLabel("t(sec)");
euler_angle_plot.bottomPlot.setYLabel("Phi(degrees)");
quarternion_check.setTitle("Quarternion Check");
quarternion_check.plot.setXLabel("t(sec)");
quarternion_check.plot.setYLabel("e1^2 + e2^2 + e3^2 + e4^2");
angular_momentum.setTitle("Angular Momentum");
angular_momentum.plot.setXLabel("t (sec)");
angular_momentum.plot.setYLabel("Angular Momentum");
quaternion_plot.setTitle("Quarternions");
quaternion_plot.firstPlot.setXLabel("t (sec)");
quaternion_plot.firstPlot.setYLabel("q1");
quaternion_plot.secondPlot.setXLabel("t (sec)");
quaternion_plot.secondPlot.setYLabel("q2");
quaternion_plot.thirdPlot.setXLabel("t (sec) ");
quaternion_plot.thirdPlot.setYLabel("q3");
quaternion_plot.fourthPlot.setXLabel("t (sec)");
quaternion_plot.fourthPlot.setYLabel("q4");
}
/** Compute the derivatives.
* Equations of Motion
* @params t double containing time or the independent variable.
* @params x VectorN containing the required data.
* @return double [] containing the derivatives.
*/
public double[] derivs(double t, double[] x)
{
double c11 = 1- 2*( x[4]*x[4] + x[5]*x[5]);
double c21 = 2* (x[3]*x[4]-x[5]*x[6]);
double c31 = 2* (x[3]*x[5]+x[4]*x[6]);
// definition
double w1 = x[0]; //nondimensionalized
double w2 = x[1]; //nondimensionalized
double w3 = x[2]; //nondimensionalized
double q1 = x[3]; //nondimensionalized
double q2 = x[4]; //nondimensionalized
double q3 = x[5]; //nondimensionalized
double q4 = x[6]; //nondimensionalized
double sigma1 = x[7]; //nondimensionalized
double sigma2 = x[8]; //nondimensionalized
double sigma3 = x[9]; //nondimensionalized
double [] out = new double[10];
if (gravity_gradient == 1)
{
//out[0] = 2*Math.PI*((I2-I3)/I1)* (x[1]*x[2] - 3*c21*c31) - 2*Math.PI*(c/I1)*(x[0]-x[7]);
//out[1] = 2*Math.PI*((I3-I1)/I2)* (x[0]*x[2] - 3*c31*c11) - 2*Math.PI*(c/I2)*(x[1]-x[8]);
//out[2] = 2*Math.PI*((I1-I2)/I3)* (x[0]*x[1] - 3*c11*c21) - 2*Math.PI*(c/I3)*(x[2]-x[9]);
//out[3] = -Math.PI* (-(x[2]+1)*x[4] + x[1]*x[5] - x[0]*x[6]);
//out[4] = -Math.PI* ((x[2]+1)*x[3] - x[0]*x[5] - x[1]*x[6]);
//out[5] = -Math.PI* (-(x[2]-1)*x[6] + x[0]*x[4] - x[1]*x[3]);
//out[6] = -Math.PI* ((x[2]-1)*x[5] + x[1]*x[4] + x[0]*x[3]);
//out[7] = 2*Math.PI*(c/j)*(x[0]-x[7]) -2*Math.PI*(x[1]*x[9] - x[2]*x[8]);
//out[8] = 2*Math.PI*(c/j)*(x[1]-x[8]) -2*Math.PI*(x[2]*x[7] - x[0]*x[9]);
//out[9] = 2*Math.PI*(c/j)*(x[2]-x[9]) -2*Math.PI*(x[0]*x[8] - x[1]*x[7]);
}
else if (gravity_gradient==0)
{
out[0] = ((I2-I3)/(I1-j))*w2*w3 +(c/(I1-j))*sigma1; //+ (c/(I1-j))*(sigma1);
out[1] = ((I3-I1)/(I2-j))*w1*w3 +(c/(I2-j))*sigma2; //- (c/(I2-j))*(sigma2);
out[2] = ((I1-I2)/(I3-j))*w1*w2 +(c/(I3-j))*sigma3; //- (c/(I3-j))*(sigma3);
out[3] = -0.5* (-x[2]*x[4] + x[1]*x[5] - x[0]*x[6]);
out[4] = -0.5* (x[2]*x[3] - x[0]*x[5] - x[1]*x[6]);
out[5] = -0.5* (-x[2]*x[6] + x[0]*x[4] - x[1]*x[3]);
out[6] = -0.5* (x[2]*x[5] + x[1]*x[4] + x[0]*x[3]);
out[7] = -out[0] - (c/j)*(sigma1)- w2*sigma3 + w3*sigma2;
out[8] = -out[1] - (c/j)*(sigma2)- w3*sigma1 + w1*sigma3;
out[9] = -out[2] - (c/j)*(sigma3)- w1*sigma2 + w2*sigma1;
}
return out;
}// End of derivs
/** Implements the Printable interface to get the data out of the propagator and pass it to the plot.
* This method is executed by the propagator at each integration step.
* @param t Time.
* @param y Data array.
*/
public void print(double t, double [] y)
{
boolean first = true;
if (t == 0.0) first = false;
//int currentPts = (int)(t/time_step); // This is the array index
System.out.println(t+" "+y[0]+" "+y[1]+" "+first);
// Define state variables
double w1 = y[0];
double w2 = y[1];
double w3 = y[2];
double q1 = y[3];
double q2 = y[4];
double q3 = y[5];
double q4 = y[6];
double sigma1 = y[7];
double sigma2 = y[8];
double sigma3 = y[9];
QuatToDeg tester = new QuatToDeg(q1, q2, q3, q4);
double[] angle = new double[3];
angle = tester.calculateAngle();
double Theta = angle[0];
double Psi = angle[1];
double Phi = angle[2];
double quat_check = q1*q1+q2*q2+q3*q3+q4*q4;
double angMomentum = Math.sqrt((I1*w1+ j*(sigma1))*(I1*w1+ j*(sigma1))+ (I2*w2 + j*(sigma2))*(I2*w2 + j*(sigma2))+ (I3*w3 + j*(sigma3))*(I3*w3 + j*(sigma3)));
//double angMomentum = Math.sqrt((I1*w1+j*Alpha)*(I1*w1+j*Alpha)+(I2*w2+j*Beta)*(I2*w2+j*Beta)+(I3*w3 + j*Gamma)*(I3*w3 + j*Gamma));
// Calculate Transformation matrix elements
// Transform from A to B see Bong Wie (p.318)
double c11 = 1- 2*(q2*q2 + q3*q3);
double c12 = 2* (q1*q2 + q3*q4);
double c13 = 2* (q1*q3 - q2*q4);
double c21 = 2* (q2*q1 - q3*q4);
double c22 = 1- 2*(q3*q3 + q1*q1);
double c23 = 2* (q2*q3 + q1*q4);
double c31 = 2* (q3*q1 + q2*q4);
double c32 = 2* (q3*q2 - q1*q4);
double c33 = 1- 2*(q1*q1 + q2*q2);
// Build Transformation Matrix
double[][] array = new double[3][3];
// Row1
array[0][0] = c11;
array[0][1] = c12;
array[0][2] = c13;
// Row2
array[1][0] = c21;
array[1][1] = c22;
array[1][2] = c23;
// Row3
array[2][0] = c31;
array[2][1] = c32;
array[2][2] = c33;
//Construct Transformation Matrix
Matrix T = new Matrix(array,3,3);
Matrix T_transpose = new Matrix(T.transpose().A, 3,3);
// add data point to the plot
angular_velocity_plot.topPlot.addPoint(0, t,y[0], first);
angular_velocity_plot.middlePlot.addPoint(0, t, y[1], first);
angular_velocity_plot.bottomPlot.addPoint(0, t, y[2], first);
damper_rotation_plot.topPlot.addPoint(0, t, y[7], first);
damper_rotation_plot.middlePlot.addPoint(0, t, y[8], first);
damper_rotation_plot.bottomPlot.addPoint(0, t, y[9], first);
euler_angle_plot.topPlot.addPoint(0, t, Theta, first);
euler_angle_plot.middlePlot.addPoint(0, t, Psi, first);
euler_angle_plot.bottomPlot.addPoint(0, t, Phi, first);
quarternion_check.plot.addPoint(0, t, quat_check, first);
angular_momentum.plot.addPoint(0, t, angMomentum, first);
quaternion_plot.firstPlot.addPoint(0, t, q1, first);
quaternion_plot.secondPlot.addPoint(0, t, q2, first);
quaternion_plot.thirdPlot.addPoint(0, t, q3, first);
quaternion_plot.fourthPlot.addPoint(0, t, q4, first);
// Store quarternion values for use in animation
quat_values[0][currentPts] = (float)t; // time value
quat_values[1][currentPts] = (float)q1; // quaternion 1
quat_values[2][currentPts] = (float)q2; // quarternion 2
quat_values[3][currentPts] = (float)q3; // quarternion 3
quat_values[4][currentPts] = (float)q4; // quarternion 4
currentPts++;
}
/**
* Return the quarternion values after simulation
* @author Noriko Takada
*/
public float[][] getQuaternion()
{
return quat_values;
}
/**
* Make the plots visible after simulation
* @author Noriko Takada
*/
public void makePlotsVisible()
{
angular_velocity_plot.setVisible(true);
damper_rotation_plot.setVisible(true);
euler_angle_plot.setVisible(true);
quarternion_check.setVisible(true);
angular_momentum.setVisible(true);
quaternion_plot.setVisible(true);
}
/** Runs the example.
* @param args Arguments.
*/
public static void main(String[] args)
{
double time_step=0.1;
double timeDuration=10;
double tf = 20;
double t0 = 0.0;
RungeKutta8 rk8 = new RungeKutta8(time_step);
timeDuration=tf; // Duration of the simulation time is the same as the final time
int numberOfPts = (int)(timeDuration/time_step) +1 ;
float quat_values[][]= new float[5][numberOfPts+1];// +1 is for AnimationWindow
// create an instance
RSphericalDamper si = new RSphericalDamper(time_step, quat_values);
// initialize the variables
double [] x0 = new double[10];
x0[0] = 0.1224;
x0[1] = 0.0;
x0[2] = 2.99;
x0[3] = 0.0;
x0[4] = 0.0;
x0[5] = 0.0;
x0[6] = 1.0;
x0[7] = 0.0;
x0[8] = 0.0;
x0[9] = 0.0;
// integrate the equations
rk8.integrate(t0, x0, tf, si, true);
// make the plot visible
si.makePlotsVisible();
}
}// End of File
| |
/*
* Copyright 2011 Google 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.google.ipc.invalidation.ticl;
import com.google.ipc.invalidation.common.CommonProtos2;
import com.google.ipc.invalidation.external.client.SystemResources.Logger;
import com.google.ipc.invalidation.external.client.types.SimplePair;
import com.google.ipc.invalidation.util.InternalBase;
import com.google.ipc.invalidation.util.Marshallable;
import com.google.ipc.invalidation.util.TextBuilder;
import com.google.ipc.invalidation.util.TypedUtil;
import com.google.protos.ipc.invalidation.ClientProtocol.PropertyRecord;
import com.google.protos.ipc.invalidation.JavaClient.StatisticsState;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Statistics for the Ticl, e.g., number of registration calls, number of token mismatches, etc.
*
*/
public class Statistics extends InternalBase implements Marshallable<StatisticsState> {
// Implementation: To classify the statistics a bit better, we have a few enums to track different
// types of statistics, e.g., sent message types, errors, etc. For each statistic type, we create
// a map and provide a method to record an event for each type of statistic.
/** Types of messages sent to the server: {@code ClientToServerMessage} for their description. */
public enum SentMessageType {
INFO,
INITIALIZE,
INVALIDATION_ACK,
REGISTRATION,
REGISTRATION_SYNC,
TOTAL, // Refers to the actual ClientToServerMessage message sent on the network.
}
/**
* Types of messages received from the server: {@code ServerToClientMessage} for their
* description.
*/
public enum ReceivedMessageType {
INFO_REQUEST,
INVALIDATION,
REGISTRATION_STATUS,
REGISTRATION_SYNC_REQUEST,
TOKEN_CONTROL,
ERROR,
CONFIG_CHANGE,
TOTAL, // Refers to the actual ServerToClientMessage messages received from the network.
}
/** Interesting API calls coming from the application ({@code InvalidationClient}). */
public enum IncomingOperationType {
ACKNOWLEDGE,
REGISTRATION,
UNREGISTRATION,
}
/** Different types of events issued by the {@code InvalidationListener}). */
public enum ListenerEventType {
INFORM_ERROR,
INFORM_REGISTRATION_FAILURE,
INFORM_REGISTRATION_STATUS,
INVALIDATE,
INVALIDATE_ALL,
INVALIDATE_UNKNOWN,
REISSUE_REGISTRATIONS,
}
/** Different types of errors observed by the Ticl. */
public enum ClientErrorType {
/** Acknowledge call received from client with a bad handle. */
ACKNOWLEDGE_HANDLE_FAILURE,
/** Incoming message dropped due to parsing, validation problems. */
INCOMING_MESSAGE_FAILURE,
/** Tried to send an outgoing message that was invalid. */
OUTGOING_MESSAGE_FAILURE,
/** Persistent state failed to deserialize correctly. */
PERSISTENT_DESERIALIZATION_FAILURE,
/** Read of blob from persistent state failed. */
PERSISTENT_READ_FAILURE,
/** Write of blob from persistent state failed. */
PERSISTENT_WRITE_FAILURE,
/** Message received with incompatible protocol version. */
PROTOCOL_VERSION_FAILURE,
/**
* Registration at client and server is different, e.g., client thinks it is registered while
* the server says it is unregistered (of course, sync will fix it).
*/
REGISTRATION_DISCREPANCY,
/** The nonce from the server did not match the current nonce by the client. */
NONCE_MISMATCH,
/** The current token at the client is different from the token in the incoming message. */
TOKEN_MISMATCH,
/** No message sent due to token missing. */
TOKEN_MISSING_FAILURE,
/** Received a message with a token (transient) failure. */
TOKEN_TRANSIENT_FAILURE,
}
// Maps for each type of Statistic to keep track of how many times each event has occurred.
private final Map<SentMessageType, Integer> sentMessageTypes =
new HashMap<SentMessageType, Integer>();
private final Map<ReceivedMessageType, Integer> receivedMessageTypes =
new HashMap<ReceivedMessageType, Integer>();
private final Map<IncomingOperationType, Integer> incomingOperationTypes =
new HashMap<IncomingOperationType, Integer>();
private final Map<ListenerEventType, Integer> listenerEventTypes =
new HashMap<ListenerEventType, Integer>();
private final Map<ClientErrorType, Integer> clientErrorTypes =
new HashMap<ClientErrorType, Integer>();
public Statistics() {
initializeMap(sentMessageTypes, SentMessageType.values());
initializeMap(receivedMessageTypes, ReceivedMessageType.values());
initializeMap(incomingOperationTypes, IncomingOperationType.values());
initializeMap(listenerEventTypes, ListenerEventType.values());
initializeMap(clientErrorTypes, ClientErrorType.values());
}
/** Returns a copy of this. */
public Statistics getCopyForTest() {
Statistics statistics = new Statistics();
statistics.sentMessageTypes.putAll(sentMessageTypes);
statistics.receivedMessageTypes.putAll(receivedMessageTypes);
statistics.incomingOperationTypes.putAll(incomingOperationTypes);
statistics.listenerEventTypes.putAll(listenerEventTypes);
statistics.clientErrorTypes.putAll(clientErrorTypes);
return statistics;
}
/** Returns the counter value for {@code clientErrorType}. */
int getClientErrorCounterForTest(ClientErrorType clientErrorType) {
return TypedUtil.mapGet(clientErrorTypes, clientErrorType);
}
/** Returns the counter value for {@code sentMessageType}. */
int getSentMessageCounterForTest(SentMessageType sentMessageType) {
return TypedUtil.mapGet(sentMessageTypes, sentMessageType);
}
/** Returns the counter value for {@code receivedMessageType}. */
int getReceivedMessageCounterForTest(ReceivedMessageType receivedMessageType) {
return TypedUtil.mapGet(receivedMessageTypes, receivedMessageType);
}
/** Records the fact that a message of type {@code sentMessageType} has been sent. */
public void recordSentMessage(SentMessageType sentMessageType) {
incrementValue(sentMessageTypes, sentMessageType);
}
/** Records the fact that a message of type {@code receivedMessageType} has been received. */
public void recordReceivedMessage(ReceivedMessageType receivedMessageType) {
incrementValue(receivedMessageTypes, receivedMessageType);
}
/**
* Records the fact that the application has made a call of type
* {@code incomingOperationType}.
*/
public void recordIncomingOperation(IncomingOperationType incomingOperationType) {
incrementValue(incomingOperationTypes, incomingOperationType);
}
/** Records the fact that the listener has issued an event of type {@code listenerEventType}. */
public void recordListenerEvent(ListenerEventType listenerEventType) {
incrementValue(listenerEventTypes, listenerEventType);
}
/** Records the fact that the client has observed an error of type {@code clientErrorType}. */
public void recordError(ClientErrorType clientErrorType) {
incrementValue(clientErrorTypes, clientErrorType);
}
/**
* Modifies {@code performanceCounters} to contain all the statistics that are non-zero. Each pair
* has the name of the statistic event and the number of times that event has occurred since the
* client started.
*/
public void getNonZeroStatistics(List<SimplePair<String, Integer>> performanceCounters) {
// Add the non-zero values from the different maps to performanceCounters.
fillWithNonZeroStatistics(sentMessageTypes, performanceCounters);
fillWithNonZeroStatistics(receivedMessageTypes, performanceCounters);
fillWithNonZeroStatistics(incomingOperationTypes, performanceCounters);
fillWithNonZeroStatistics(listenerEventTypes, performanceCounters);
fillWithNonZeroStatistics(clientErrorTypes, performanceCounters);
}
/** Modifies {@code result} to contain those statistics from {@code map} whose value is > 0. */
private static <Key> void fillWithNonZeroStatistics(Map<Key, Integer> map,
List<SimplePair<String, Integer>> destination) {
String prefix = null;
for (Map.Entry<Key, Integer> entry : map.entrySet()) {
if (entry.getValue() > 0) {
// Initialize prefix if this is the first element being added.
if (prefix == null) {
prefix = entry.getKey().getClass().getSimpleName() + ".";
}
destination.add(SimplePair.of(prefix + entry.getKey(), entry.getValue()));
}
}
}
/** Increments the value of {@code map}[{@code key}] by 1. */
private static <Key> void incrementValue(Map<Key, Integer> map, Key key) {
map.put(key, TypedUtil.mapGet(map, key) + 1);
}
/** Initializes all values for {@code keys} in {@code map} to be 0. */
private static <Key> void initializeMap(Map<Key, Integer> map, Key[] keys) {
for (Key key : keys) {
map.put(key, 0);
}
}
@Override
public void toCompactString(TextBuilder builder) {
List<SimplePair<String, Integer>> nonZeroValues = new ArrayList<SimplePair<String, Integer>>();
getNonZeroStatistics(nonZeroValues);
builder.appendFormat("Client Statistics: %s\n", nonZeroValues);
}
@Override
public StatisticsState marshal() {
// Get all the non-zero counters, convert them to proto PropertyRecord messages, and return
// a StatisticsState containing the records.
StatisticsState.Builder builder = StatisticsState.newBuilder();
List<SimplePair<String, Integer>> counters = new ArrayList<SimplePair<String, Integer>>();
getNonZeroStatistics(counters);
for (SimplePair<String, Integer> counter : counters) {
builder.addCounter(CommonProtos2.newPropertyRecord(counter.getFirst(), counter.getSecond()));
}
return builder.build();
}
/**
* Given the serialized {@code performanceCounters} of the client statistics, returns a Statistics
* object with the performance counter values from {@code performanceCounters}.
*/
public static Statistics deserializeStatistics(Logger logger,
Collection<PropertyRecord> performanceCounters) {
Statistics statistics = new Statistics();
// For each counter, parse out the counter name and value.
for (PropertyRecord performanceCounter : performanceCounters) {
String counterName = performanceCounter.getName();
String[] parts = counterName.split("\\.");
if (parts.length != 2) {
logger.warning("Perf counter name must of form: class.value, skipping: %s", counterName);
continue;
}
String className = parts[0];
String fieldName = parts[1];
int counterValue = performanceCounter.getValue();
// Call the relevant method in a loop (i.e., depending on the type of the class).
if (TypedUtil.<String>equals(className, "SentMessageType")) {
SentMessageType sentMessageType = SentMessageType.valueOf(fieldName);
for (int i = 0; i < counterValue; i++) {
statistics.recordSentMessage(sentMessageType);
}
} else if (TypedUtil.<String>equals(className, "IncomingOperationType")) {
IncomingOperationType incomingOperationType = IncomingOperationType.valueOf(fieldName);
for (int i = 0; i < counterValue; i++) {
statistics.recordIncomingOperation(incomingOperationType);
}
} else if (TypedUtil.<String>equals(className, "ReceivedMessageType")) {
ReceivedMessageType receivedMessageType = ReceivedMessageType.valueOf(fieldName);
for (int i = 0; i < counterValue; i++) {
statistics.recordReceivedMessage(receivedMessageType);
}
} else if (TypedUtil.<String>equals(className, "ListenerEventType")) {
ListenerEventType listenerEventType = ListenerEventType.valueOf(fieldName);
for (int i = 0; i < counterValue; i++) {
statistics.recordListenerEvent(listenerEventType);
}
} else if (TypedUtil.<String>equals(className, "ClientErrorType")) {
ClientErrorType clientErrorType = ClientErrorType.valueOf(fieldName);
for (int i = 0; i < counterValue; i++) {
statistics.recordError(clientErrorType);
}
} else {
logger.warning("Skipping unknown enum class name %s", className);
}
}
return statistics;
}
}
| |
package com.wuman.android.auth;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.api.client.auth.oauth.OAuthAuthorizeTemporaryTokenUrl;
import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl;
import com.google.api.client.auth.oauth2.BrowserClientRequestUrl;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Preconditions;
import com.wuman.android.auth.oauth2.implicit.ImplicitResponseUrl;
import java.io.IOException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger;
public abstract class DialogFragmentController implements AuthorizationDialogController {
static final Logger LOGGER = Logger.getLogger(OAuthConstants.TAG);
private static final String FRAGMENT_TAG = "oauth_dialog";
/** A boolean to indicate if the dialog fragment needs to be full screen **/
public final boolean fullScreen;
/** A boolean to indicate if the dialog fragment needs to be horizontal **/
public final boolean horizontalProgress;
public final boolean hideFullScreenTitle;
private final FragmentManagerCompat fragmentManager;
/** {@link Handler} for running UI in the main thread. */
private final Handler uiHandler;
/**
* Verification code (for explicit authorization) or access token (for
* implicit authorization) or {@code null} for none.
*/
String codeOrToken;
/** Error code or {@code null} for none. */
String error;
/** Implicit response URL. */
ImplicitResponseUrl implicitResponseUrl;
/** Lock on the code and error. */
final Lock lock = new ReentrantLock();
/** Condition for receiving an authorization response. */
final Condition gotAuthorizationResponse = lock.newCondition();
/**
* @param fragmentManager
*/
public DialogFragmentController(android.support.v4.app.FragmentManager fragmentManager) {
this(fragmentManager, false);
}
/**
* @param fragmentManager
*/
public DialogFragmentController(android.app.FragmentManager fragmentManager) {
this(fragmentManager, false);
}
/**
*
* @param fragmentManager
* @param fullScreen
*/
public DialogFragmentController(android.support.v4.app.FragmentManager fragmentManager, boolean fullScreen) {
this(fragmentManager, fullScreen, false);
}
/**
*
* @param fragmentManager
* @param fullScreen
*/
public DialogFragmentController(android.app.FragmentManager fragmentManager, boolean fullScreen) {
this(fragmentManager, fullScreen, false);
}
/**
*
* @param fragmentManager
* @param fullScreen
* @param horizontalProgress
*/
public DialogFragmentController(android.support.v4.app.FragmentManager fragmentManager, boolean fullScreen,
boolean horizontalProgress) {
this(fragmentManager, fullScreen, horizontalProgress, false);
}
/**
*
* @param fragmentManager
* @param fullScreen
* @param horizontalProgress
*/
public DialogFragmentController(android.app.FragmentManager fragmentManager, boolean fullScreen,
boolean horizontalProgress) {
this(fragmentManager, fullScreen, horizontalProgress, false);
}
/**
*
* @param fragmentManager
* @param fullScreen
* @param horizontalProgress
* @param hideFullScreenTitle if you set this flag to true, {@param horizontalProgress} will be ignored
*/
public DialogFragmentController(android.support.v4.app.FragmentManager fragmentManager, boolean fullScreen,
boolean horizontalProgress, boolean hideFullScreenTitle) {
super();
this.uiHandler = new Handler(Looper.getMainLooper());
this.fragmentManager =
new FragmentManagerCompat(Preconditions.checkNotNull(fragmentManager));
this.fullScreen = fullScreen;
this.horizontalProgress = horizontalProgress;
this.hideFullScreenTitle = hideFullScreenTitle;
}
/**
*
* @param fragmentManager
* @param fullScreen
* @param horizontalProgress
* @param hideFullScreenTitle if you set this flag to true, {@param horizontalProgress} will be ignored
*/
public DialogFragmentController(android.app.FragmentManager fragmentManager, boolean fullScreen,
boolean horizontalProgress, boolean hideFullScreenTitle) {
super();
this.uiHandler = new Handler(Looper.getMainLooper());
this.fragmentManager =
new FragmentManagerCompat(Preconditions.checkNotNull(fragmentManager));
this.fullScreen = fullScreen;
this.horizontalProgress = horizontalProgress;
this.hideFullScreenTitle = hideFullScreenTitle;
}
Object getFragmentManager() {
return this.fragmentManager.getFragmentManager();
}
/**
* Executes the {@link Runnable} on the main thread.
*
* @param runnable
*/
private void runOnMainThread(Runnable runnable) {
uiHandler.post(runnable);
}
private void dismissDialog() {
runOnMainThread(new Runnable() {
public void run() {
DialogFragmentCompat frag = fragmentManager
.findFragmentByTag(DialogFragmentCompat.class, FRAGMENT_TAG);
if (frag != null) {
frag.dismiss();
}
}
});
}
@Override
public void set(String codeOrToken, String error, ImplicitResponseUrl implicitResponseUrl,
boolean signal) {
lock.lock();
try {
this.error = error;
this.codeOrToken = codeOrToken;
this.implicitResponseUrl = implicitResponseUrl;
if (signal) {
gotAuthorizationResponse.signal();
}
} finally {
lock.unlock();
}
}
@Override
public void requestAuthorization(OAuthAuthorizeTemporaryTokenUrl authorizationRequestUrl) {
internalRequestAuthorization(authorizationRequestUrl);
}
@Override
public void requestAuthorization(AuthorizationCodeRequestUrl authorizationRequestUrl) {
internalRequestAuthorization(authorizationRequestUrl);
}
@Override
public void requestAuthorization(BrowserClientRequestUrl authorizationRequestUrl) {
internalRequestAuthorization(authorizationRequestUrl);
}
private void internalRequestAuthorization(final GenericUrl authorizationRequestUrl) {
runOnMainThread(new Runnable() {
@Override
public void run() {
if(fragmentManager.isDestroyed()) {
return;
}
FragmentTransactionCompat ft = fragmentManager.beginTransaction();
FragmentCompat prevDialog =
fragmentManager.findFragmentByTag(FragmentCompat.class, FRAGMENT_TAG);
if (prevDialog != null) {
ft.remove(prevDialog);
}
DialogFragmentCompat frag =
OAuthDialogFragment.newInstance(
authorizationRequestUrl,
DialogFragmentController.this);
frag.show(ft, FRAGMENT_TAG);
}
});
}
@Override
public String waitForVerifierCode() throws IOException {
return waitForExplicitCode();
}
@Override
public String waitForExplicitCode() throws IOException {
lock.lock();
try {
while (codeOrToken == null && error == null) {
gotAuthorizationResponse.awaitUninterruptibly();
}
dismissDialog();
if (error != null) {
if (TextUtils.equals(ERROR_USER_CANCELLED, error)) {
throw new CancellationException("User authorization failed (" + error + ")");
} else {
throw new IOException("User authorization failed (" + error + ")");
}
}
return codeOrToken;
} finally {
lock.unlock();
}
}
@Override
public ImplicitResponseUrl waitForImplicitResponseUrl() throws IOException {
lock.lock();
try {
while (codeOrToken == null && error == null) {
gotAuthorizationResponse.awaitUninterruptibly();
}
dismissDialog();
if (error != null) {
if (TextUtils.equals(ERROR_USER_CANCELLED, error)) {
throw new CancellationException("User authorization failed (" + error + ")");
} else {
throw new IOException("User authorization failed (" + error + ")");
}
}
return implicitResponseUrl;
} finally {
lock.unlock();
}
}
@Override
public void stop() throws IOException {
set(null, null, null, true);
dismissDialog();
}
@Override
public void onPrepareDialog(Dialog dialog) {
// do nothing
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// use default implementation in DialogFragment
return null;
}
@Override
public boolean setProgressShown(String url, View view, int newProgress) {
// use default implementation in DialogFragment
return false;
}
}
| |
package maisPop;
import java.util.ArrayList;
import java.util.List;
public class Controller {
private List<Usuario> bancoDeUsuarios;
private Usuario usuarioLogado;
//TODO criar listaDeAmizades para nao ser preciso checar se us1 eh amigo de us2 em cada usuario.
public Controller() {
bancoDeUsuarios = new ArrayList<Usuario>();
}
public String cadastraUsuario(String nome, String email, String senha, String dataDeNasc) throws Exception {
return cadastraUsuario(nome, email, senha, dataDeNasc, "resources/default.jpg");
}
public String cadastraUsuario(String nome, String email, String senha, String dataDeNasc, String imagem)
throws Exception {
Usuario usr = new Usuario(nome, email, senha, dataDeNasc, imagem);
bancoDeUsuarios.add(usr);
return usr.getEmail();
}
public void fechaSistema() throws Exception {
if (usuarioLogado != null) {
throw new Exception("Nao foi possivel fechar o sistema. Um usuarix ainda esta logadx.");
}
}
public String getInfoUsuario(String atributo) throws Exception {
String saida = "";
if (atributo.equals(Usuario.NOME)) {
saida = usuarioLogado.getNome();
} else if (atributo.equals(Usuario.EMAIL)) {
saida = usuarioLogado.getEmail();
} else if (atributo.equals(Usuario.SENHA)) {
throw new Exception("A senha dx usuarix eh protegida.");
} else if (atributo.equals(Usuario.DATA_DE_NASCIMENTO)) {
saida = usuarioLogado.getDataDeNascimento();
} else if (atributo.equals(Usuario.FOTO)) {
saida = usuarioLogado.getCaminhoImagem();
}
return saida;
}
public String getInfoUsuario(String atributo, String email) throws Exception {
Usuario usr = retornaUsuarioPorEmail(email);
String saida = "";
if (atributo.equals(Usuario.NOME)) {
saida = usr.getNome();
} else if (atributo.equals(Usuario.EMAIL)) {
saida = retornaUsuarioPorEmail(atributo).getEmail();
} else if (atributo.equals(Usuario.SENHA)) {
throw new Exception("A senha dx usuarix eh protegida.");
} else if (atributo.equals(Usuario.DATA_DE_NASCIMENTO)) {
saida = usr.getDataDeNascimento();
} else if (atributo.equals(Usuario.FOTO)) {
saida = usr.getCaminhoImagem();
}
return saida;
}
public void iniciaSistema() {
//TODO Criar arquivos.
}
public Usuario loga(String email, String senha) throws Exception {
Usuario usrTemp;
try {
usrTemp = retornaUsuarioPorEmail(email);
} catch (Exception e) {
throw new Exception("Nao foi possivel realizar login. " + e.getMessage());
}
if (usrTemp.getSenha().equals(senha)) {
return usrTemp;
} else {
throw new Exception("Nao foi possivel realizar login. Senha invalida.");
}
}
public void login(String email, String senha) throws Exception {
if (usuarioLogado == null) {
this.usuarioLogado = loga(email, senha);
} else {
throw new Exception(
"Nao foi possivel realizar login. Um usuarix ja esta logadx: " + usuarioLogado.getNome() + ".");
}
}
public void logout() throws Exception {
if (usuarioLogado == null) {
throw new Exception("Nao eh possivel realizar logout. Nenhum usuarix esta logadx no +pop.");
}
if (usuarioLogado != null) {
usuarioLogado = null;
}
}
public void removeUsuario(String idDoUsuario) throws Exception {
try {
bancoDeUsuarios.remove(retornaUsuarioPorEmail(idDoUsuario));
} catch (Exception e) {
throw new Exception("Impossivel remover usuario, usuario nao cadastrado.");
}
}
public Usuario retornaUsuarioPorEmail(String usuarioEmail) throws Exception {
for (Usuario usuario : bancoDeUsuarios) {
if (usuario.getEmail().equals(usuarioEmail)) {
return usuario;
}
}
throw new Exception("Um usuarix com email " + usuarioEmail + " nao esta cadastradx.");
}
public void atualizaPerfil(String atributo, String valor) throws Exception {
if (usuarioLogado == null) {
throw new Exception("Nao eh possivel atualizar um perfil. Nenhum usuarix esta logadx no +pop.");
}
if (atributo.equals(Usuario.NOME)) {
usuarioLogado.setNome(valor);
} else if (atributo.equals(Usuario.EMAIL)) {
usuarioLogado.setEmail(valor);
} else if (atributo.equals(Usuario.DATA_DE_NASCIMENTO)) {
usuarioLogado.setDataDeNascimento(valor);
} else if (atributo.equals(Usuario.FOTO)) {
usuarioLogado.setCaminhoImagem(valor);
}
}
public void atualizaPerfil(String atributo, String novaSenha, String velhaSenha) throws Exception {
if (usuarioLogado == null) {
throw new Exception("Nao eh possivel atualizar um perfil. Nenhum usuarix esta logadx no +pop.");
}
if (atributo.equals(Usuario.SENHA)) {
if (velhaSenha.equals(usuarioLogado.getSenha())) {
usuarioLogado.setSenha(novaSenha);
} else {
throw new Exception("Erro na atualizacao de perfil. A senha fornecida esta incorreta.");
}
}
}
public void criaPost(String mensagem, String data) throws Exception {
Postagem post = usuarioLogado.criaPost(mensagem, data);
usuarioLogado.adicionaNoMural(post);
}
public Postagem getPost(int post) {
return usuarioLogado.getPost(post);
}
public String getPost(String atributo, int post) throws Exception {
return usuarioLogado.getPost(atributo, post);
}
public String getConteudoPost(int indice, int post) throws Exception {
return usuarioLogado.getConteudoPost(indice, post);
}
public void curtirPost(String usuarioEmail, int post) throws Exception {
if (usuarioLogado == null) {
throw new Exception("Nao eh possivel curtir o post. Nenhum usuarix esta logadx no +pop.");
}
Usuario usr = retornaUsuarioPorEmail(usuarioEmail);
adicionaNotificacao(usuarioEmail,
usuarioLogado.getNome() + " curtiu seu post de " + usr.getPost(Usuario.DATA_DA_POSTAGEM, post) + ".");
}
public void adicionaNotificacao(String usuarioEmail, String notificacao) throws Exception {
Usuario usr = retornaUsuarioPorEmail(usuarioEmail);
usr.getListaNotificacoes().add(notificacao);
}
public void adicionaSolicitacao(String usuarioEmail, String solicitacao) throws Exception {
Usuario usr = retornaUsuarioPorEmail(usuarioEmail);
usr.getSolicitacoes().add(solicitacao);
}
public void adicionaAmigo(String usuarioEmail) throws Exception {
if (usuarioLogado == null) {
throw new Exception("Nao eh possivel enviar solicitacao. Nenhum usuarix esta logadx no +pop.");
}
String mensagem = usuarioLogado.getNome() + " quer sua amizade.";
adicionaNotificacao(usuarioEmail, mensagem);
adicionaSolicitacao(usuarioEmail, mensagem);
}
public void aceitaAmizade(String usuarioEmail) throws Exception {
if (usuarioLogado == null) {
throw new Exception("Nao eh possivel aceitar solicitacao. Nenhum usuarix esta logadx no +pop.");
}
Usuario usr = retornaUsuarioPorEmail(usuarioEmail);
if (!temSolicitacao(usr)) {
throw new Exception(usr.getNome() + " nao lhe enviou solicitacoes de amizade.");
}
usuarioLogado.addAmigo(usuarioEmail);
usr.addAmigo(usuarioLogado.getEmail());
adicionaNotificacao(usuarioEmail, usuarioLogado.getNome() + " aceitou sua amizade.");
}
public void rejeitaAmizade(String usuarioEmail) throws Exception {
if (usuarioLogado == null) {
throw new Exception("Nao eh possivel rejeitar solicitacao. Nenhum usuarix esta logadx no +pop.");
}
Usuario usr = retornaUsuarioPorEmail(usuarioEmail);
if (!temSolicitacao(usr)) {
throw new Exception(usr.getNome() + " nao lhe enviou solicitacoes de amizade.");
}
adicionaNotificacao(usuarioEmail, usuarioLogado.getNome() + " rejeitou sua amizade.");
}
public void removeAmigo(String usuarioEmail) throws Exception {
if (usuarioLogado == null) {
throw new Exception("Nao eh possivel adicionar amigo. Nenhum usuarix esta logadx no +pop.");
}
usuarioLogado.getAmigos().remove(usuarioEmail);
Usuario usr = retornaUsuarioPorEmail(usuarioEmail);
usr.getAmigos().remove(usuarioLogado.getEmail());
adicionaNotificacao(usuarioEmail, usuarioLogado.getNome() + " removeu a sua amizade.");
}
public String getNextNotificacao() throws Exception {
return usuarioLogado.getNextNotificacao();
}
public int getQtdAmigos() {
return usuarioLogado.getQtdAmigos();
}
public int getNotificacoes() {
return usuarioLogado.getNotificacoes();
}
public boolean temSolicitacao(Usuario usr) {
String mensagem = usr.getNome() + " quer sua amizade.";
for (String solicitacao : usuarioLogado.getSolicitacoes()) {
if (solicitacao.equals(mensagem)) {
usuarioLogado.getSolicitacoes().remove(solicitacao);
return true;
}
}
return false;
}
}
| |
/*
* Copyright (c) 2012 David Green
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package castledesigner;
import java.awt.Dimension;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
*
* @author David Green
*/
public class BuildingTypeTest extends TestCase
{
public BuildingTypeTest(String testName)
{
super(testName);
}
public static Test suite()
{
TestSuite suite = new TestSuite(BuildingTypeTest.class);
return suite;
}
@Override
protected void setUp() throws Exception
{
super.setUp();
}
@Override
protected void tearDown() throws Exception
{
super.tearDown();
}
/**
* Test of values method, of class BuildingType.
*/
public void testValues()
{
System.out.println("values");
for (BuildingType buildingType : BuildingType.values())
{
assertNotNull(buildingType);
}
}
/**
* Test of valueOf method, of class BuildingType.
*/
public void testValueOf()
{
System.out.println("valueOf");
assertEquals(BuildingType.BALLISTA_TOWER, BuildingType.valueOf("BALLISTA_TOWER"));
assertEquals(BuildingType.STONE_GATEHOUSE, BuildingType.valueOf("STONE_GATEHOUSE"));
assertEquals(BuildingType.WOODEN_WALL, BuildingType.valueOf("WOODEN_WALL"));
}
/**
* Test of getHotspot method, of class BuildingType.
*/
public void testGetHotspot()
{
System.out.println("getHotspot");
assertEquals(0, BuildingType.MOAT.getHotspot()[0]);
assertEquals(0, BuildingType.MOAT.getHotspot()[1]);
assertEquals(2, BuildingType.MOAT.getHotspot().length);
assertEquals(0, BuildingType.STONE_WALL.getHotspot()[0]);
assertEquals(0, BuildingType.STONE_WALL.getHotspot()[0]);
assertEquals(1, BuildingType.BALLISTA_TOWER.getHotspot()[0]);
assertEquals(1, BuildingType.BALLISTA_TOWER.getHotspot()[0]);
assertEquals(1, BuildingType.SMELTER.getHotspot()[0]);
assertEquals(1, BuildingType.SMELTER.getHotspot()[0]);
assertEquals(0, BuildingType.LOOKOUT_TOWER.getHotspot()[0]);
assertEquals(0, BuildingType.LOOKOUT_TOWER.getHotspot()[0]);
assertEquals(1, BuildingType.SMALL_TOWER.getHotspot()[0]);
assertEquals(1, BuildingType.SMALL_TOWER.getHotspot()[0]);
assertEquals(1, BuildingType.LARGE_TOWER.getHotspot()[0]);
assertEquals(1, BuildingType.LARGE_TOWER.getHotspot()[0]);
assertEquals(2, BuildingType.GREAT_TOWER.getHotspot()[0]);
assertEquals(2, BuildingType.GREAT_TOWER.getHotspot()[0]);
}
/**
* Test of getDimension method, of class BuildingType.
*/
public void testGetDimension()
{
System.out.println("getDimension");
assertEquals(new Dimension(1, 1), BuildingType.MOAT.getDimension());
assertEquals(new Dimension(1, 1), BuildingType.STONE_WALL.getDimension());
assertEquals(new Dimension(3, 3), BuildingType.BALLISTA_TOWER.getDimension());
assertEquals(new Dimension(4, 4), BuildingType.SMELTER.getDimension());
assertEquals(new Dimension(2, 2), BuildingType.LOOKOUT_TOWER.getDimension());
assertEquals(new Dimension(3, 3), BuildingType.SMALL_TOWER.getDimension());
assertEquals(new Dimension(4, 4), BuildingType.LARGE_TOWER.getDimension());
assertEquals(new Dimension(5, 5), BuildingType.GREAT_TOWER.getDimension());
}
/**
* Test of isGapRequired method, of class BuildingType.
*/
public void testIsGapRequired()
{
System.out.println("isGapRequired");
assertTrue(BuildingType.LOOKOUT_TOWER.isGapRequired());
assertTrue(BuildingType.STONE_GATEHOUSE.isGapRequired());
assertFalse(BuildingType.STONE_WALL.isGapRequired());
assertFalse(BuildingType.GUARD_HOUSE.isGapRequired());
assertFalse(BuildingType.BALLISTA_TOWER.isGapRequired());
}
/**
* Test of getImage method, of class BuildingType.
*/
public void testGetImage()
{
System.out.println("getImage");
for (BuildingType buildingType : BuildingType.values())
{
assertNotNull(buildingType.getImage());
}
}
/**
* Test of getValidOverlay method, of class BuildingType.
*/
public void testGetValidOverlay()
{
System.out.println("getValidOverlay");
for (BuildingType buildingType : BuildingType.values())
{
assertNotNull(buildingType.getValidOverlay());
}
}
/**
* Test of getInvalidOverlay method, of class BuildingType.
*/
public void testGetInvalidOverlay()
{
System.out.println("getInvalidOverlay");
for (BuildingType buildingType : BuildingType.values())
{
assertNotNull(buildingType.getInvalidOverlay());
}
}
/**
* Test of toString method, of class BuildingType.
*/
public void testToString()
{
System.out.println("toString");
for (BuildingType buildingType : BuildingType.values())
{
assertNotNull(buildingType.toString());
}
}
/**
* Test of getColour method, of class BuildingType.
*/
public void testGetColour()
{
System.out.println("getColour");
for (BuildingType buildingType : BuildingType.values())
{
assertNotNull(buildingType.getColour());
}
}
/**
* Test of getCost method, of class BuildingType.
*/
public void testGetCost()
{
System.out.println("getCost");
for (BuildingType buildingType : BuildingType.values())
{
for (BuildingResource buildingResource : BuildingResource.values())
{
assertNotNull(buildingType.getCost(buildingResource));
}
}
}
/**
* Test of getBuildTime method, of class BuildingType.
*/
public void testGetBuildTime()
{
System.out.println("getBuildTime");
for (BuildingType buildingType : BuildingType.values())
{
assertTrue(buildingType.getBuildTime() >= 0);
}
}
}
| |
package org.jgroups;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.util.Headers;
import org.jgroups.util.Util;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Map;
/**
* A common superclass for all {@link Message} implementations. It contains functionality to manage headers, flags and
* destination and source addresses.
*
* @since 5.0
* @author Bela Ban
*/
public abstract class BaseMessage implements Message {
protected Address dest;
protected Address sender;
protected volatile Header[] headers;
protected volatile short flags;
protected volatile byte transient_flags; // transient_flags is neither marshalled nor copied
static final byte DEST_SET = 1;
static final byte SRC_SET = 1 << 1;
public BaseMessage() {
}
/**
* Constructs a message given a destination address
* @param dest The Address of the receiver. If it is null, then the message is sent to the group. Otherwise, it is
* sent to a single member.
*/
public BaseMessage(Address dest) {
setDest(dest);
headers=createHeaders(Util.DEFAULT_HEADERS);
}
public Address getDest() {return dest;}
public Message setDest(Address new_dest) {dest=new_dest; return this;}
public Address getSrc() {return sender;}
public Message setSrc(Address new_src) {sender=new_src; return this;}
public int getNumHeaders() {return Headers.size(this.headers);}
public Map<Short,Header> getHeaders() {return Headers.getHeaders(this.headers);}
public String printHeaders() {return Headers.printHeaders(this.headers);}
/**
* Sets a number of flags in a message
* @param flags The flag or flags
* @return A reference to the message
*/
public Message setFlag(Flag... flags) {
if(flags != null) {
short tmp=this.flags;
for(Flag flag : flags) {
if(flag != null)
tmp|=flag.value();
}
this.flags=tmp;
}
return this;
}
/**
* Same as {@link #setFlag(Flag...)} except that transient flags are not marshalled
* @param flags The flag
*/
public Message setFlag(TransientFlag... flags) {
if(flags != null) {
short tmp=this.transient_flags;
for(TransientFlag flag : flags)
if(flag != null)
tmp|=flag.value();
this.transient_flags=(byte)tmp;
}
return this;
}
public Message setFlag(short flag, boolean transient_flags) {
short tmp=transient_flags? this.transient_flags : this.flags;
tmp|=flag;
if(transient_flags)
this.transient_flags=(byte)tmp;
else
this.flags=tmp;
return this;
}
/**
* Returns the internal representation of flags. Don't use this, as the internal format might change at any time !
* This is only used by unit test code
* @return
*/
public short getFlags(boolean transient_flags) {return transient_flags? this.transient_flags : flags;}
/**
* Clears a number of flags in a message
* @param flags The flags
* @return A reference to the message
*/
public Message clearFlag(Flag... flags) {
if(flags != null) {
short tmp=this.flags;
for(Flag flag : flags)
if(flag != null)
tmp&=~flag.value();
this.flags=tmp;
}
return this;
}
public Message clearFlag(TransientFlag... flags) {
if(flags != null) {
short tmp=this.transient_flags;
for(TransientFlag flag : flags)
if(flag != null)
tmp&=~flag.value();
this.transient_flags=(byte)tmp;
}
return this;
}
/**
* Checks if a given flag is set
* @param flag The flag
* @return Whether or not the flag is currently set
*/
public boolean isFlagSet(Flag flag) {
return Util.isFlagSet(flags, flag);
}
public boolean isFlagSet(TransientFlag flag) {
return Util.isTransientFlagSet(transient_flags, flag);
}
/**
* Atomically checks if a given flag is set and - if not - sets it. When multiple threads
* concurrently call this method with the same flag, only one of them will be able to set the
* flag
*
* @param flag
* @return True if the flag could be set, false if not (was already set)
*/
public synchronized boolean setFlagIfAbsent(TransientFlag flag) {
if(isFlagSet(flag))
return false;
setFlag(flag);
return true;
}
/**
* Copies the source- and destination addresses, flags and headers (if copy_headers is true).<br/>
* If copy_payload is set, then method {@link #copyPayload(Message)} of the subclass will be called, which is
* responsible for copying the payload specific to that message type.<br/>
* Note that for headers, only the arrays holding references to the headers are copied, not the headers themselves !
* The consequence is that the headers array of the copy hold the *same* references as the original, so do *not*
* modify the headers ! If you want to change a header, copy it and call {@link Message#putHeader(short,Header)} again.
*/
public Message copy(boolean copy_payload, boolean copy_headers) {
BaseMessage retval=(BaseMessage)create().get();
retval.dest=dest;
retval.sender=sender;
retval.flags=this.flags;
retval.transient_flags=this.transient_flags;
retval.headers=copy_headers && headers != null? Headers.copy(this.headers) : createHeaders(Util.DEFAULT_HEADERS);
if(copy_payload)
copyPayload(retval);
return retval;
}
/** Puts a header given an ID into the hashmap. Overwrites potential existing entry. */
public Message putHeader(short id, Header hdr) {
if(id < 0)
throw new IllegalArgumentException("An ID of " + id + " is invalid");
if(hdr != null)
hdr.setProtId(id);
synchronized(this) {
if(this.headers == null)
this.headers=createHeaders(Util.DEFAULT_HEADERS);
Header[] resized_array=Headers.putHeader(this.headers, id, hdr, true);
if(resized_array != null)
this.headers=resized_array;
}
return this;
}
public <T extends Header> T getHeader(short id) {
if(id <= 0)
throw new IllegalArgumentException("An ID of " + id + " is invalid. Add the protocol which calls " +
"getHeader() to jg-protocol-ids.xml");
return Headers.getHeader(this.headers, id);
}
public <T> T getPayload() {return getObject();}
public Message setPayload(Object pl) {return setObject(pl);}
public String toString() {
return String.format("[%s to %s, %d bytes%s%s]", sender, dest == null? "<all>" : dest,
getLength(), flags > 0? ", flags=" + Util.flagsToString(flags) : "",
transient_flags > 0? ", transient_flags=" + Util.transientFlagsToString(transient_flags) : "");
}
public int serializedSize() {
return size();
}
public int size() {
int retval=Global.BYTE_SIZE // leading byte
+ Global.SHORT_SIZE; // flags
if(dest != null)
retval+=Util.size(dest);
if(sender != null)
retval+=Util.size(sender);
retval+=Global.SHORT_SIZE; // number of headers
retval+=Headers.marshalledSize(this.headers);
return retval;
}
public void writeTo(DataOutput out) throws IOException {
byte leading=0;
if(dest != null)
leading=Util.setFlag(leading, DEST_SET);
if(sender != null)
leading=Util.setFlag(leading, SRC_SET);
// write the leading byte first
out.write(leading);
// write the flags (e.g. OOB, LOW_PRIO), skip the transient flags
out.writeShort(flags);
// write the dest_addr
if(dest != null)
Util.writeAddress(dest, out);
// write the src_addr
if(sender != null)
Util.writeAddress(sender, out);
// write the headers
writeHeaders(this.headers, out, (short[])null);
// finally write the payload
writePayload(out);
}
public void writeToNoAddrs(Address src, DataOutput out, short... excluded_headers) throws IOException {
byte leading=0;
boolean write_src_addr=src == null || sender != null && !sender.equals(src);
if(write_src_addr)
leading=Util.setFlag(leading, SRC_SET);
// write the leading byte first
out.write(leading);
// write the flags (e.g. OOB, LOW_PRIO)
out.writeShort(flags);
// write the src_addr
if(write_src_addr)
Util.writeAddress(sender, out);
// write the headers
writeHeaders(this.headers, out, excluded_headers);
// finally write the payload
writePayload(out);
}
public void readFrom(DataInput in) throws IOException, ClassNotFoundException {
// 1. read the leading byte first
byte leading=in.readByte();
// 2. the flags
flags=in.readShort();
// 3. dest_addr
if(Util.isFlagSet(leading, DEST_SET))
dest=Util.readAddress(in);
// 4. src_addr
if(Util.isFlagSet(leading, SRC_SET))
sender=Util.readAddress(in);
// 5. headers
int len=in.readShort();
if(this.headers == null || len > this.headers.length)
this.headers=createHeaders(len);
for(int i=0; i < len; i++) {
short id=in.readShort();
Header hdr=readHeader(in).setProtId(id);
this.headers[i]=hdr;
}
readPayload(in);
}
/** Copies the payload */
protected Message copyPayload(Message copy) {
return copy;
}
protected static void writeHeaders(Header[] hdrs, DataOutput out, short ... excluded_headers) throws IOException {
int size=Headers.size(hdrs, excluded_headers);
out.writeShort(size);
if(size > 0) {
for(Header hdr : hdrs) {
if(hdr == null)
break;
short id=hdr.getProtId();
if(Util.containsId(id, excluded_headers))
continue;
out.writeShort(id);
writeHeader(hdr, out);
}
}
}
protected static void writeHeader(Header hdr, DataOutput out) throws IOException {
short magic_number=hdr.getMagicId();
out.writeShort(magic_number);
hdr.writeTo(out);
}
protected static Header readHeader(DataInput in) throws IOException, ClassNotFoundException {
short magic_number=in.readShort();
Header hdr=ClassConfigurator.create(magic_number);
hdr.readFrom(in);
return hdr;
}
protected static Header[] createHeaders(int size) {
return size > 0? new Header[size] : new Header[3];
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.netapp.models;
import com.azure.core.management.Region;
import com.azure.core.management.SystemData;
import com.azure.core.util.Context;
import com.azure.resourcemanager.netapp.fluent.models.SnapshotPolicyInner;
import java.util.Map;
/** An immutable client-side representation of SnapshotPolicy. */
public interface SnapshotPolicy {
/**
* Gets the id property: Fully qualified resource Id for the resource.
*
* @return the id value.
*/
String id();
/**
* Gets the name property: The name of the resource.
*
* @return the name value.
*/
String name();
/**
* Gets the type property: The type of the resource.
*
* @return the type value.
*/
String type();
/**
* Gets the location property: The geo-location where the resource lives.
*
* @return the location value.
*/
String location();
/**
* Gets the tags property: Resource tags.
*
* @return the tags value.
*/
Map<String, String> tags();
/**
* Gets the etag property: A unique read-only string that changes whenever the resource is updated.
*
* @return the etag value.
*/
String etag();
/**
* Gets the systemData property: The system meta data relating to this resource.
*
* @return the systemData value.
*/
SystemData systemData();
/**
* Gets the hourlySchedule property: Schedule for hourly snapshots.
*
* @return the hourlySchedule value.
*/
HourlySchedule hourlySchedule();
/**
* Gets the dailySchedule property: Schedule for daily snapshots.
*
* @return the dailySchedule value.
*/
DailySchedule dailySchedule();
/**
* Gets the weeklySchedule property: Schedule for weekly snapshots.
*
* @return the weeklySchedule value.
*/
WeeklySchedule weeklySchedule();
/**
* Gets the monthlySchedule property: Schedule for monthly snapshots.
*
* @return the monthlySchedule value.
*/
MonthlySchedule monthlySchedule();
/**
* Gets the enabled property: The property to decide policy is enabled or not.
*
* @return the enabled value.
*/
Boolean enabled();
/**
* Gets the provisioningState property: Azure lifecycle management.
*
* @return the provisioningState value.
*/
String provisioningState();
/**
* Gets the region of the resource.
*
* @return the region of the resource.
*/
Region region();
/**
* Gets the name of the resource region.
*
* @return the name of the resource region.
*/
String regionName();
/**
* Gets the inner com.azure.resourcemanager.netapp.fluent.models.SnapshotPolicyInner object.
*
* @return the inner object.
*/
SnapshotPolicyInner innerModel();
/** The entirety of the SnapshotPolicy definition. */
interface Definition
extends DefinitionStages.Blank,
DefinitionStages.WithLocation,
DefinitionStages.WithParentResource,
DefinitionStages.WithCreate {
}
/** The SnapshotPolicy definition stages. */
interface DefinitionStages {
/** The first stage of the SnapshotPolicy definition. */
interface Blank extends WithLocation {
}
/** The stage of the SnapshotPolicy definition allowing to specify location. */
interface WithLocation {
/**
* Specifies the region for the resource.
*
* @param location The geo-location where the resource lives.
* @return the next definition stage.
*/
WithParentResource withRegion(Region location);
/**
* Specifies the region for the resource.
*
* @param location The geo-location where the resource lives.
* @return the next definition stage.
*/
WithParentResource withRegion(String location);
}
/** The stage of the SnapshotPolicy definition allowing to specify parent resource. */
interface WithParentResource {
/**
* Specifies resourceGroupName, accountName.
*
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account.
* @return the next definition stage.
*/
WithCreate withExistingNetAppAccount(String resourceGroupName, String accountName);
}
/**
* The stage of the SnapshotPolicy definition which contains all the minimum required properties for the
* resource to be created, but also allows for any other optional properties to be specified.
*/
interface WithCreate
extends DefinitionStages.WithTags,
DefinitionStages.WithHourlySchedule,
DefinitionStages.WithDailySchedule,
DefinitionStages.WithWeeklySchedule,
DefinitionStages.WithMonthlySchedule,
DefinitionStages.WithEnabled {
/**
* Executes the create request.
*
* @return the created resource.
*/
SnapshotPolicy create();
/**
* Executes the create request.
*
* @param context The context to associate with this operation.
* @return the created resource.
*/
SnapshotPolicy create(Context context);
}
/** The stage of the SnapshotPolicy definition allowing to specify tags. */
interface WithTags {
/**
* Specifies the tags property: Resource tags..
*
* @param tags Resource tags.
* @return the next definition stage.
*/
WithCreate withTags(Map<String, String> tags);
}
/** The stage of the SnapshotPolicy definition allowing to specify hourlySchedule. */
interface WithHourlySchedule {
/**
* Specifies the hourlySchedule property: Schedule for hourly snapshots.
*
* @param hourlySchedule Schedule for hourly snapshots.
* @return the next definition stage.
*/
WithCreate withHourlySchedule(HourlySchedule hourlySchedule);
}
/** The stage of the SnapshotPolicy definition allowing to specify dailySchedule. */
interface WithDailySchedule {
/**
* Specifies the dailySchedule property: Schedule for daily snapshots.
*
* @param dailySchedule Schedule for daily snapshots.
* @return the next definition stage.
*/
WithCreate withDailySchedule(DailySchedule dailySchedule);
}
/** The stage of the SnapshotPolicy definition allowing to specify weeklySchedule. */
interface WithWeeklySchedule {
/**
* Specifies the weeklySchedule property: Schedule for weekly snapshots.
*
* @param weeklySchedule Schedule for weekly snapshots.
* @return the next definition stage.
*/
WithCreate withWeeklySchedule(WeeklySchedule weeklySchedule);
}
/** The stage of the SnapshotPolicy definition allowing to specify monthlySchedule. */
interface WithMonthlySchedule {
/**
* Specifies the monthlySchedule property: Schedule for monthly snapshots.
*
* @param monthlySchedule Schedule for monthly snapshots.
* @return the next definition stage.
*/
WithCreate withMonthlySchedule(MonthlySchedule monthlySchedule);
}
/** The stage of the SnapshotPolicy definition allowing to specify enabled. */
interface WithEnabled {
/**
* Specifies the enabled property: The property to decide policy is enabled or not.
*
* @param enabled The property to decide policy is enabled or not.
* @return the next definition stage.
*/
WithCreate withEnabled(Boolean enabled);
}
}
/**
* Begins update for the SnapshotPolicy resource.
*
* @return the stage of resource update.
*/
SnapshotPolicy.Update update();
/** The template for SnapshotPolicy update. */
interface Update
extends UpdateStages.WithTags,
UpdateStages.WithHourlySchedule,
UpdateStages.WithDailySchedule,
UpdateStages.WithWeeklySchedule,
UpdateStages.WithMonthlySchedule,
UpdateStages.WithEnabled {
/**
* Executes the update request.
*
* @return the updated resource.
*/
SnapshotPolicy apply();
/**
* Executes the update request.
*
* @param context The context to associate with this operation.
* @return the updated resource.
*/
SnapshotPolicy apply(Context context);
}
/** The SnapshotPolicy update stages. */
interface UpdateStages {
/** The stage of the SnapshotPolicy update allowing to specify tags. */
interface WithTags {
/**
* Specifies the tags property: Resource tags.
*
* @param tags Resource tags.
* @return the next definition stage.
*/
Update withTags(Map<String, String> tags);
}
/** The stage of the SnapshotPolicy update allowing to specify hourlySchedule. */
interface WithHourlySchedule {
/**
* Specifies the hourlySchedule property: Schedule for hourly snapshots.
*
* @param hourlySchedule Schedule for hourly snapshots.
* @return the next definition stage.
*/
Update withHourlySchedule(HourlySchedule hourlySchedule);
}
/** The stage of the SnapshotPolicy update allowing to specify dailySchedule. */
interface WithDailySchedule {
/**
* Specifies the dailySchedule property: Schedule for daily snapshots.
*
* @param dailySchedule Schedule for daily snapshots.
* @return the next definition stage.
*/
Update withDailySchedule(DailySchedule dailySchedule);
}
/** The stage of the SnapshotPolicy update allowing to specify weeklySchedule. */
interface WithWeeklySchedule {
/**
* Specifies the weeklySchedule property: Schedule for weekly snapshots.
*
* @param weeklySchedule Schedule for weekly snapshots.
* @return the next definition stage.
*/
Update withWeeklySchedule(WeeklySchedule weeklySchedule);
}
/** The stage of the SnapshotPolicy update allowing to specify monthlySchedule. */
interface WithMonthlySchedule {
/**
* Specifies the monthlySchedule property: Schedule for monthly snapshots.
*
* @param monthlySchedule Schedule for monthly snapshots.
* @return the next definition stage.
*/
Update withMonthlySchedule(MonthlySchedule monthlySchedule);
}
/** The stage of the SnapshotPolicy update allowing to specify enabled. */
interface WithEnabled {
/**
* Specifies the enabled property: The property to decide policy is enabled or not.
*
* @param enabled The property to decide policy is enabled or not.
* @return the next definition stage.
*/
Update withEnabled(Boolean enabled);
}
}
/**
* Refreshes the resource to sync with Azure.
*
* @return the refreshed resource.
*/
SnapshotPolicy refresh();
/**
* Refreshes the resource to sync with Azure.
*
* @param context The context to associate with this operation.
* @return the refreshed resource.
*/
SnapshotPolicy refresh(Context context);
}
| |
package org.apereo.cas.config;
import org.apereo.cas.adaptors.yubikey.DefaultYubiKeyAccountValidator;
import org.apereo.cas.adaptors.yubikey.YubiKeyAccount;
import org.apereo.cas.adaptors.yubikey.YubiKeyAccountRegistry;
import org.apereo.cas.adaptors.yubikey.YubiKeyAccountValidator;
import org.apereo.cas.adaptors.yubikey.YubiKeyAuthenticationHandler;
import org.apereo.cas.adaptors.yubikey.YubiKeyCredential;
import org.apereo.cas.adaptors.yubikey.YubiKeyMultifactorAuthenticationProvider;
import org.apereo.cas.adaptors.yubikey.YubiKeyRegisteredDevice;
import org.apereo.cas.adaptors.yubikey.registry.JsonYubiKeyAccountRegistry;
import org.apereo.cas.adaptors.yubikey.registry.OpenYubiKeyAccountRegistry;
import org.apereo.cas.adaptors.yubikey.registry.PermissiveYubiKeyAccountRegistry;
import org.apereo.cas.adaptors.yubikey.registry.RestfulYubiKeyAccountRegistry;
import org.apereo.cas.adaptors.yubikey.registry.YubiKeyAccountRegistryEndpoint;
import org.apereo.cas.authentication.AuthenticationEventExecutionPlanConfigurer;
import org.apereo.cas.authentication.AuthenticationHandler;
import org.apereo.cas.authentication.AuthenticationMetaDataPopulator;
import org.apereo.cas.authentication.MultifactorAuthenticationFailureModeEvaluator;
import org.apereo.cas.authentication.MultifactorAuthenticationProvider;
import org.apereo.cas.authentication.bypass.MultifactorAuthenticationProviderBypassEvaluator;
import org.apereo.cas.authentication.handler.ByCredentialTypeAuthenticationHandlerResolver;
import org.apereo.cas.authentication.metadata.AuthenticationContextAttributeMetaDataPopulator;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.authentication.principal.PrincipalFactoryUtils;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.util.crypto.CipherExecutor;
import org.apereo.cas.util.http.HttpClient;
import com.yubico.client.v2.YubicoClient;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.Clock;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* This is {@link YubiKeyAuthenticationEventExecutionPlanConfiguration}.
*
* @author Misagh Moayyed
* @author Dmitriy Kopylenko
* @since 5.1.0
*/
@Configuration("yubikeyAuthenticationEventExecutionPlanConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
@Slf4j
public class YubiKeyAuthenticationEventExecutionPlanConfiguration {
@Autowired
@Qualifier("yubikeyAccountCipherExecutor")
private ObjectProvider<CipherExecutor> yubikeyAccountCipherExecutor;
@Autowired
private CasConfigurationProperties casProperties;
@Autowired
@Qualifier("servicesManager")
private ObjectProvider<ServicesManager> servicesManager;
@Autowired
@Qualifier("noRedirectHttpClient")
private ObjectProvider<HttpClient> httpClient;
@Autowired
@Qualifier("yubikeyBypassEvaluator")
private ObjectProvider<MultifactorAuthenticationProviderBypassEvaluator> yubikeyBypassEvaluator;
@Autowired
@Qualifier("failureModeEvaluator")
private ObjectProvider<MultifactorAuthenticationFailureModeEvaluator> failureModeEvaluator;
@Bean
@RefreshScope
@ConditionalOnMissingBean(name = "yubikeyAuthenticationMetaDataPopulator")
public AuthenticationMetaDataPopulator yubikeyAuthenticationMetaDataPopulator() {
val authenticationContextAttribute = casProperties.getAuthn().getMfa().getAuthenticationContextAttribute();
return new AuthenticationContextAttributeMetaDataPopulator(
authenticationContextAttribute,
yubikeyAuthenticationHandler(),
yubikeyMultifactorAuthenticationProvider().getId()
);
}
@ConditionalOnMissingBean(name = "yubikeyPrincipalFactory")
@Bean
@RefreshScope
public PrincipalFactory yubikeyPrincipalFactory() {
return PrincipalFactoryUtils.newPrincipalFactory();
}
@RefreshScope
@Bean
@ConditionalOnMissingBean(name = "yubicoClient")
public YubicoClient yubicoClient() {
val yubi = this.casProperties.getAuthn().getMfa().getYubikey();
if (StringUtils.isBlank(yubi.getSecretKey())) {
throw new IllegalArgumentException("Yubikey secret key cannot be blank");
}
if (yubi.getClientId() <= 0) {
throw new IllegalArgumentException("Yubikey client id is undefined");
}
val client = YubicoClient.getClient(yubi.getClientId(), yubi.getSecretKey());
if (!yubi.getApiUrls().isEmpty()) {
val urls = yubi.getApiUrls().toArray(ArrayUtils.EMPTY_STRING_ARRAY);
client.setWsapiUrls(urls);
}
return client;
}
@Bean
@RefreshScope
@ConditionalOnMissingBean(name = "yubikeyAuthenticationHandler")
public AuthenticationHandler yubikeyAuthenticationHandler() {
val yubi = this.casProperties.getAuthn().getMfa().getYubikey();
return new YubiKeyAuthenticationHandler(yubi.getName(),
servicesManager.getObject(), yubikeyPrincipalFactory(),
yubicoClient(), yubiKeyAccountRegistry(),
yubi.getOrder());
}
@Bean
@RefreshScope
@ConditionalOnMissingBean(name = "yubiKeyAccountValidator")
public YubiKeyAccountValidator yubiKeyAccountValidator() {
return new DefaultYubiKeyAccountValidator(yubicoClient());
}
@Bean
@RefreshScope
@ConditionalOnMissingBean(name = "yubiKeyAccountRegistry")
public YubiKeyAccountRegistry yubiKeyAccountRegistry() {
val yubi = casProperties.getAuthn().getMfa().getYubikey();
val cipher = yubikeyAccountCipherExecutor.getObject();
if (yubi.getJsonFile() != null) {
LOGGER.debug("Using JSON resource [{}] as the YubiKey account registry", yubi.getJsonFile());
val registry = new JsonYubiKeyAccountRegistry(yubi.getJsonFile(), yubiKeyAccountValidator());
registry.setCipherExecutor(cipher);
return registry;
}
if (StringUtils.isNotBlank(yubi.getRest().getUrl())) {
LOGGER.debug("Using REST API resource [{}] as the YubiKey account registry", yubi.getRest().getUrl());
val registry = new RestfulYubiKeyAccountRegistry(yubi.getRest(), yubiKeyAccountValidator());
registry.setCipherExecutor(cipher);
return registry;
}
if (yubi.getAllowedDevices() != null && !yubi.getAllowedDevices().isEmpty()) {
LOGGER.debug("Using statically-defined devices for [{}] as the YubiKey account registry",
yubi.getAllowedDevices().keySet());
val map = (Map<String, YubiKeyAccount>) yubi.getAllowedDevices().entrySet()
.stream()
.map(entry -> YubiKeyAccount.builder()
.id(System.currentTimeMillis())
.username(entry.getKey())
.devices(List.of(YubiKeyRegisteredDevice.builder()
.publicId(entry.getValue())
.name(UUID.randomUUID().toString())
.registrationDate(ZonedDateTime.now(Clock.systemUTC()))
.build()))
.build())
.collect(Collectors.toMap(YubiKeyAccount::getUsername, acct -> acct));
val registry = new PermissiveYubiKeyAccountRegistry(map, yubiKeyAccountValidator());
registry.setCipherExecutor(CipherExecutor.noOpOfSerializableToString());
return registry;
}
LOGGER.warn("All credentials are considered eligible for YubiKey authentication. "
+ "Consider providing an account registry implementation via [{}]",
YubiKeyAccountRegistry.class.getName());
val registry = new OpenYubiKeyAccountRegistry(new DefaultYubiKeyAccountValidator(yubicoClient()));
registry.setCipherExecutor(cipher);
return registry;
}
@Bean
@ConditionalOnAvailableEndpoint
public YubiKeyAccountRegistryEndpoint yubiKeyAccountRegistryEndpoint() {
return new YubiKeyAccountRegistryEndpoint(casProperties, yubiKeyAccountRegistry());
}
@Bean
@RefreshScope
public MultifactorAuthenticationProvider yubikeyMultifactorAuthenticationProvider() {
val yubi = casProperties.getAuthn().getMfa().getYubikey();
val p = new YubiKeyMultifactorAuthenticationProvider(yubicoClient(), httpClient.getObject());
p.setBypassEvaluator(yubikeyBypassEvaluator.getObject());
p.setFailureMode(yubi.getFailureMode());
p.setFailureModeEvaluator(failureModeEvaluator.getObject());
p.setOrder(yubi.getRank());
p.setId(yubi.getId());
return p;
}
@ConditionalOnMissingBean(name = "yubikeyAuthenticationEventExecutionPlanConfigurer")
@Bean
public AuthenticationEventExecutionPlanConfigurer yubikeyAuthenticationEventExecutionPlanConfigurer() {
return plan -> {
val yubi = casProperties.getAuthn().getMfa().getYubikey();
if (yubi.getClientId() > 0 && StringUtils.isNotBlank(yubi.getSecretKey())) {
plan.registerAuthenticationHandler(yubikeyAuthenticationHandler());
plan.registerAuthenticationMetadataPopulator(yubikeyAuthenticationMetaDataPopulator());
plan.registerAuthenticationHandlerResolver(new ByCredentialTypeAuthenticationHandlerResolver(YubiKeyCredential.class));
}
};
}
}
| |
package org.yeastrc.xlink.www.annotation.sort_display_records_on_annotation_values;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.slf4j.LoggerFactory; import org.slf4j.Logger;
import org.yeastrc.xlink.dto.AnnotationDataBaseDTO;
import org.yeastrc.xlink.dto.AnnotationTypeDTO;
import org.yeastrc.xlink.dto.AnnotationTypeFilterableDTO;
import org.yeastrc.xlink.enum_classes.FilterDirectionType;
import org.yeastrc.xlink.www.exceptions.ProxlWebappDataException;
import org.yeastrc.xlink.www.objects.AnnotationDisplayNameDescription;
/**
*
* Only Sort on Best Peptide and Best PSM values
*/
public class SrtOnBestAnnValsPopAnnValListsRetnTblHeadrsSinglSrchId {
private static final Logger log = LoggerFactory.getLogger( SrtOnBestAnnValsPopAnnValListsRetnTblHeadrsSinglSrchId.class);
public static SrtOnBestAnnValsPopAnnValListsRetnTblHeadrsSinglSrchId getInstance() {
return new SrtOnBestAnnValsPopAnnValListsRetnTblHeadrsSinglSrchId();
}
// constructor
private SrtOnBestAnnValsPopAnnValListsRetnTblHeadrsSinglSrchId() { }
/**
* Sort on Best Peptide and Best PSM values for Proteins
*
* @param searchId
* @param sortDisplayRecordsWrapperBaseList
* @param peptideCutoffsAnnotationTypeDTOList
* @param psmCutoffsAnnotationTypeDTOList
* @return
* @throws ProxlWebappDataException
* @throws Exception
*/
public SrtOnBestAnnValsPopAnnValListsRetnTblHeadrsSinglSrchIdReslt sortOnBestPeptideBestPSMAnnValuesPopulateAnnValueListsReturnTableHeadersSingleSearchId(
int searchId,
List<? extends SortDisplayRecordsWrapperBase> sortDisplayRecordsWrapperBaseList,
final List<AnnotationTypeDTO> peptideCutoffsAnnotationTypeDTOList,
final List<AnnotationTypeDTO> psmCutoffsAnnotationTypeDTOList
) throws ProxlWebappDataException, Exception {
SrtOnBestAnnValsPopAnnValListsRetnTblHeadrsSinglSrchIdReslt result =
new SrtOnBestAnnValsPopAnnValListsRetnTblHeadrsSinglSrchIdReslt();
// Make local copies of annotation type lists for sorting
final List<AnnotationTypeDTO> peptideCutoffsAnnotationTypeDTOListRecordSortOrderSorted = new ArrayList<>( peptideCutoffsAnnotationTypeDTOList );
final List<AnnotationTypeDTO> peptideCutoffsAnnotationTypeDTOListAnnotationDisplayOrderSorted = new ArrayList<>( peptideCutoffsAnnotationTypeDTOList );
final List<AnnotationTypeDTO> psmCutoffsAnnotationTypeDTOListRecordSortOrderSorted = new ArrayList<>( psmCutoffsAnnotationTypeDTOList );
final List<AnnotationTypeDTO> psmCutoffsAnnotationTypeDTOListAnnotationDisplayOrderSorted = new ArrayList<>( psmCutoffsAnnotationTypeDTOList );
SortAnnotationDTORecords.getInstance()
.sortPeptideAnnotationTypeDTOForBestPeptideAnnotations_RecordsSortOrder( peptideCutoffsAnnotationTypeDTOListRecordSortOrderSorted );
SortAnnotationDTORecords.getInstance()
.sortPeptideAnnotationTypeDTOForBestPeptideAnnotations_AnnotationDisplayOrder( peptideCutoffsAnnotationTypeDTOListAnnotationDisplayOrderSorted );
SortAnnotationDTORecords.getInstance()
.sortPsmAnnotationTypeDTOForBestPsmAnnotations_RecordsSortOrder( psmCutoffsAnnotationTypeDTOListRecordSortOrderSorted );
SortAnnotationDTORecords.getInstance()
.sortPsmAnnotationTypeDTOForBestPsmAnnotations_AnnotationDisplayOrder( psmCutoffsAnnotationTypeDTOListAnnotationDisplayOrderSorted );
///////////////
// Sort Records on sort order
Collections.sort( sortDisplayRecordsWrapperBaseList, new Comparator<SortDisplayRecordsWrapperBase>() {
@Override
public int compare(SortDisplayRecordsWrapperBase o1, SortDisplayRecordsWrapperBase o2) {
// Loop through the Peptide annotation types (sorted ), comparing the values
for ( AnnotationTypeDTO annotationTypeDTO : peptideCutoffsAnnotationTypeDTOListRecordSortOrderSorted ) {
int typeId = annotationTypeDTO.getId();
AnnotationTypeFilterableDTO annotationTypeFilterableDTO = annotationTypeDTO.getAnnotationTypeFilterableDTO();
if ( annotationTypeFilterableDTO == null ) {
String msg = "Peptide AnnotationTypeFilterableDTO == null for type id: " + typeId;
log.error( msg );
throw new RuntimeException(msg);
}
FilterDirectionType annTypeFilterDirectionType = annotationTypeFilterableDTO.getFilterDirectionType();
if ( annTypeFilterDirectionType == null ) {
String msg = "Peptide FilterDirectionType == null for type id: " + typeId;
log.error( msg );
throw new RuntimeException(msg);
}
AnnotationDataBaseDTO o1_AnnotationDataBaseDTO = o1.getPeptideAnnotationDTOMap().get( typeId );
if ( o1_AnnotationDataBaseDTO == null ) {
String msg = "Unable to get Peptide Filterable Annotation data for type id: " + typeId;
log.error( msg );
throw new RuntimeException(msg);
}
double o1Value = o1_AnnotationDataBaseDTO.getValueDouble();
AnnotationDataBaseDTO o2_AnnotationDataBaseDTO = o2.getPeptideAnnotationDTOMap().get( typeId );
if ( o2_AnnotationDataBaseDTO == null ) {
String msg = "Unable to get Peptide Filterable Annotation data for type id: " + typeId;
log.error( msg );
throw new RuntimeException(msg);
}
double o2Value = o2_AnnotationDataBaseDTO.getValueDouble();
if ( o1Value != o2Value ) {
if ( annTypeFilterDirectionType == FilterDirectionType.ABOVE ) {
if ( o1Value > o2Value ) {
return -1;
} else {
return 1;
}
} else {
if ( o1Value < o2Value ) {
return -1;
} else {
return 1;
}
}
}
}
// Loop through the PSM annotation types (sorted ), comparing the values
for ( AnnotationTypeDTO annotationTypeDTO : psmCutoffsAnnotationTypeDTOListRecordSortOrderSorted ) {
int typeId = annotationTypeDTO.getId();
AnnotationTypeFilterableDTO annotationTypeFilterableDTO = annotationTypeDTO.getAnnotationTypeFilterableDTO();
if ( annotationTypeFilterableDTO == null ) {
String msg = "PSM AnnotationTypeFilterableDTO == null for type id: " + typeId;
log.error( msg );
throw new RuntimeException(msg);
}
FilterDirectionType annTypeFilterDirectionType = annotationTypeFilterableDTO.getFilterDirectionType();
if ( annTypeFilterDirectionType == null ) {
String msg = "PSM FilterDirectionType == null for type id: " + typeId;
log.error( msg );
throw new RuntimeException(msg);
}
// Map keyed on annotation type id of annotation data
Map<Integer, AnnotationDataBaseDTO> o1_psmAnnotationDTOMap = o1.getPsmAnnotationDTOMap();
Map<Integer, AnnotationDataBaseDTO> o2_psmAnnotationDTOMap = o2.getPsmAnnotationDTOMap();
AnnotationDataBaseDTO o1_AnnotationDataBaseDTO = o1_psmAnnotationDTOMap.get( typeId );
if ( o1_AnnotationDataBaseDTO == null ) {
String msg = "Unable to get PSM Filterable Annotation data for type id: " + typeId;
log.error( msg );
throw new RuntimeException(msg);
}
double o1Value = o1_AnnotationDataBaseDTO.getValueDouble();
AnnotationDataBaseDTO o2_AnnotationDataBaseDTO = o2_psmAnnotationDTOMap.get( typeId );
if ( o2_AnnotationDataBaseDTO == null ) {
String msg = "Unable to get PSM Filterable Annotation data for type id: " + typeId;
log.error( msg );
throw new RuntimeException(msg);
}
double o2Value = o2_AnnotationDataBaseDTO.getValueDouble();
if ( o1Value != o2Value ) {
if ( annTypeFilterDirectionType == FilterDirectionType.ABOVE ) {
if ( o1Value > o2Value ) {
return -1;
} else {
return 1;
}
} else {
if ( o1Value < o2Value ) {
return -1;
} else {
return 1;
}
}
}
}
// If everything matches, sort on provided sort value
return o1.getFinalSortOrderKey() - o2.getFinalSortOrderKey();
}
});
////////////////
// Copy annotation values to output lists
for ( SortDisplayRecordsWrapperBase wrapperItem : sortDisplayRecordsWrapperBaseList ) {
List<String> peptideAnnotationValueList = new ArrayList<>();
wrapperItem.setPeptideAnnotationValueList( peptideAnnotationValueList );
// Loop through the Peptide annotation types (sorted ), comparing the values
for ( AnnotationTypeDTO annotationTypeDTO : peptideCutoffsAnnotationTypeDTOListAnnotationDisplayOrderSorted ) {
int typeId = annotationTypeDTO.getId();
AnnotationDataBaseDTO annotationDataBaseDTO = wrapperItem.getPeptideAnnotationDTOMap().get( typeId );
if ( annotationDataBaseDTO == null ) {
String msg = "Unable to get Peptide Filterable Annotation data for type id: " + typeId;
log.error( msg );
throw new RuntimeException(msg);
}
peptideAnnotationValueList.add( annotationDataBaseDTO.getValueString() );
}
List<String> psmAnnotationValueList = new ArrayList<>();
wrapperItem.setPsmAnnotationValueList( psmAnnotationValueList );
// Loop through the PSM annotation types (sorted ), comparing the values
for ( AnnotationTypeDTO annotationTypeDTO : psmCutoffsAnnotationTypeDTOListAnnotationDisplayOrderSorted ) {
int typeId = annotationTypeDTO.getId();
AnnotationDataBaseDTO annotationDataBaseDTO = wrapperItem.getPsmAnnotationDTOMap().get( typeId );
if ( annotationDataBaseDTO == null ) {
String msg = "Unable to get PSM Filterable Annotation data for type id: " + typeId;
log.error( msg );
throw new RuntimeException(msg);
}
psmAnnotationValueList.add( annotationDataBaseDTO.getValueString() );
}
}
////////////////
// Copy Annotation Display Name and Descriptions to output lists, used for table headers in the HTML
List<AnnotationDisplayNameDescription> peptideAnnotationDisplayNameDescriptionList = new ArrayList<>( peptideCutoffsAnnotationTypeDTOListAnnotationDisplayOrderSorted.size() );
List<AnnotationDisplayNameDescription> psmAnnotationDisplayNameDescriptionList = new ArrayList<>( psmCutoffsAnnotationTypeDTOListAnnotationDisplayOrderSorted.size() );
for ( AnnotationTypeDTO item : peptideCutoffsAnnotationTypeDTOListAnnotationDisplayOrderSorted ) {
AnnotationDisplayNameDescription output = new AnnotationDisplayNameDescription();
output.setDisplayName( item.getName() );
output.setDescription( item.getDescription() );
peptideAnnotationDisplayNameDescriptionList.add(output);
}
for ( AnnotationTypeDTO item : psmCutoffsAnnotationTypeDTOListAnnotationDisplayOrderSorted ) {
AnnotationDisplayNameDescription output = new AnnotationDisplayNameDescription();
output.setDisplayName( item.getName() );
output.setDescription( item.getDescription() );
psmAnnotationDisplayNameDescriptionList.add(output);
}
result.setPeptideAnnotationDisplayNameDescriptionList( peptideAnnotationDisplayNameDescriptionList );
result.setPsmAnnotationDisplayNameDescriptionList( psmAnnotationDisplayNameDescriptionList );
return result;
}
}
| |
/*
Derby - Class org.apache.derby.iapi.types.UserType
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.derby.iapi.types;
import org.apache.derby.catalog.TypeDescriptor;
import org.apache.derby.iapi.reference.SQLState;
import org.apache.derby.iapi.services.loader.ClassInspector;
import org.apache.derby.shared.common.sanity.SanityManager;
import org.apache.derby.iapi.services.io.StoredFormatIds;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.services.cache.ClassSize;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
/**
* This contains an instance of a user-defined type, that is, a java object.
*
*/
public class UserType extends DataType
implements UserDataValue
{
private Object value;
/*
** DataValueDescriptor interface
** (mostly implemented in DataType)
*/
private static final int BASE_MEMORY_USAGE = ClassSize.estimateBaseFromCatalog( UserType.class);
public int estimateMemoryUsage()
{
int sz = BASE_MEMORY_USAGE;
if( null != value)
{
// Probably an underestimate. Examining each field value would be expensive
// and would produce an overestimate when fields reference shared objects
sz += ClassSize.estimateAndCatalogBase( value.getClass());
}
return sz;
} // end of estimateMemoryUsage
public String getString()
{
if (! isNull())
{
return value.toString();
}
else
{
return null;
}
}
/**
* @exception StandardException thrown on failure to convert
*/
public boolean getBoolean() throws StandardException
{
if (! isNull())
if (value instanceof Boolean) return ((Boolean)value).booleanValue();
return super.getBoolean();
}
/**
* @exception StandardException thrown on failure to convert
*/
public byte getByte() throws StandardException
{
if (! isNull())
// REMIND: check for overflow and truncation
if (value instanceof Number) return ((Number)value).byteValue();
return super.getByte();
}
/**
* @exception StandardException thrown on failure to convert
*/
public short getShort() throws StandardException
{
if (! isNull())
// REMIND: check for overflow and truncation
if (value instanceof Number) return ((Number)value).shortValue();
return super.getShort();
}
/**
* @exception StandardException thrown on failure to convert
*/
public int getInt() throws StandardException
{
if (! isNull())
// REMIND: check for overflow and truncation
if (value instanceof Number) return ((Number)value).intValue();
return super.getInt();
}
/**
* @exception StandardException thrown on failure to convert
*/
public long getLong() throws StandardException
{
if (! isNull())
// REMIND: check for overflow and truncation
if (value instanceof Number) return ((Number)value).longValue();
return super.getLong();
}
/**
* @exception StandardException thrown on failure to convert
*/
public float getFloat() throws StandardException
{
if (! isNull())
// REMIND: check for overflow
if (value instanceof Number) return ((Number)value).floatValue();
return super.getFloat();
}
/**
* @exception StandardException thrown on failure to convert
*/
public double getDouble() throws StandardException
{
if (! isNull())
// REMIND: check for overflow
if (value instanceof Number) return ((Number)value).doubleValue();
return super.getDouble();
}
/**
* @exception StandardException thrown on failure to convert
*/
public byte[] getBytes() throws StandardException
{
if (! isNull())
if (value instanceof byte[]) return ((byte[])value);
return super.getBytes();
}
/**
@exception StandardException thrown on failure
*/
public Date getDate( Calendar cal) throws StandardException
{
if (! isNull())
{
if (value instanceof Date)
return ((Date)value);
else if (value instanceof Timestamp)
return (new SQLTimestamp((Timestamp)value).getDate(cal));
}
return super.getDate(cal);
}
/**
@exception StandardException thrown on failure
*/
public Time getTime( Calendar cal) throws StandardException
{
if (! isNull())
{
if (value instanceof Time)
return ((Time)value);
else if (value instanceof Timestamp)
return (new SQLTimestamp((Timestamp)value).getTime(cal));
}
return super.getTime(cal);
}
/**
@exception StandardException thrown on failure
*/
public Timestamp getTimestamp( Calendar cal) throws StandardException
{
if (! isNull())
{
if (value instanceof Timestamp)
return ((Timestamp)value);
else if (value instanceof Date)
return (new SQLDate((Date)value).getTimestamp(cal));
else if (value instanceof Time)
return (new SQLTime((Time)value).getTimestamp(cal));
}
return super.getTimestamp(cal);
}
void setObject(Object theValue)
{
setValue( theValue );
}
public Object getObject()
{
return value;
}
public int getLength()
{
return TypeDescriptor.MAXIMUM_WIDTH_UNKNOWN;
}
/* this is for DataType's error generator */
public String getTypeName()
{
return isNull() ? "JAVA_OBJECT" : ClassInspector.readableClassName(value.getClass());
}
/**
* Get the type name of this value, overriding
* with the passed in class name (for user/java types).
*/
String getTypeName(String className)
{
return className;
}
/*
* Storable interface, implies Externalizable, TypedFormat
*/
/**
Return my format identifier.
@see org.apache.derby.iapi.services.io.TypedFormat#getTypeFormatId
*/
public int getTypeFormatId() {
return StoredFormatIds.SQL_USERTYPE_ID_V3;
}
/**
@exception IOException error writing data
*/
public void writeExternal(ObjectOutput out) throws IOException {
if (SanityManager.DEBUG)
SanityManager.ASSERT(!isNull(), "writeExternal() is not supposed to be called for null values.");
out.writeObject(value);
}
/**
* @see java.io.Externalizable#readExternal
*
* @exception IOException Thrown on error reading the object
* @exception ClassNotFoundException Thrown if the class of the object
* is not found
*/
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
/* RESOLVE: Sanity check for right class */
value = in.readObject();
}
/*
* DataValueDescriptor interface
*/
/** @see DataValueDescriptor#cloneValue */
public DataValueDescriptor cloneValue(boolean forceMaterialization)
{
// Call constructor with all of our info
return new UserType(value);
}
/**
* @see DataValueDescriptor#getNewNull
*/
public DataValueDescriptor getNewNull()
{
return new UserType();
}
/**
* @see org.apache.derby.iapi.services.io.Storable#restoreToNull
*
*/
public void restoreToNull()
{
value = null;
}
/*
* DataValueDescriptor interface
*/
/**
* @see DataValueDescriptor#setValueFromResultSet
*
* @exception SQLException Thrown on error
*/
public void setValueFromResultSet(ResultSet resultSet, int colNumber,
boolean isNullable)
throws SQLException
{
value = resultSet.getObject(colNumber);
}
/**
* Orderable interface
*
*
* @see org.apache.derby.iapi.types.Orderable
*
* @exception StandardException thrown on failure
*/
@SuppressWarnings("unchecked")
public int compare(DataValueDescriptor other)
throws StandardException
{
/* Use compare method from dominant type, negating result
* to reflect flipping of sides.
*/
if (typePrecedence() < other.typePrecedence())
{
return - (other.compare(this));
}
boolean thisNull, otherNull;
thisNull = this.isNull();
otherNull = other.isNull();
/*
* thisNull otherNull return
* T T 0 (this == other)
* F T -1 (this < other)
* T F 1 (this > other)
*/
if (thisNull || otherNull)
{
if (!thisNull) // otherNull must be true
return -1;
if (!otherNull) // thisNull must be true
return 1;
return 0;
}
/*
Neither are null compare them
*/
int comparison;
try
{
comparison = ((java.lang.Comparable<Object>) value).compareTo(other.getObject());
}
catch (ClassCastException cce)
{
throw StandardException.newException(SQLState.LANG_INVALID_COMPARE_TO,
getTypeName(),
ClassInspector.readableClassName(other.getObject().getClass()));
}
/*
** compareTo() can return any negative number if less than, and
** any positive number if greater than. Change to -1, 0, 1.
*/
if (comparison < 0)
comparison = -1;
else if (comparison > 0)
comparison = 1;
return comparison;
}
/**
@exception StandardException thrown on error
*/
public boolean compare(int op,
DataValueDescriptor other,
boolean orderedNulls,
boolean unknownRV)
throws StandardException
{
if (!orderedNulls) // nulls are unordered
{
if (this.isNull() || other.isNull())
return unknownRV;
}
/* For usertypes and equal do some special processing when
* neither value is null. (Superclass will handle comparison
* if either value is null.)
*/
if ( (op == ORDER_OP_EQUALS) &&
(! this.isNull()) && (! other.isNull()) )
{
// if this object implements java.lang.Comparable (JDK1.2)
// then we let the compareTo method handle equality
// if it doesn't then we use the equals() method
Object o = getObject();
if (!(o instanceof java.lang.Comparable))
{
return o.equals(other.getObject());
}
}
/* Do the comparison */
return super.compare(op, other, orderedNulls, unknownRV);
}
/*
** Class interface
*/
/*
** Constructors
*/
/** no-arg constructor required by Formattable */
public UserType() { }
public UserType(Object value)
{
this.value = value;
}
/**
* @see UserDataValue#setValue
*
*/
public void setValue(Object value)
{
this.value = value;
}
protected void setFrom(DataValueDescriptor theValue) throws StandardException {
setValue(theValue.getObject());
}
/**
* @see UserDataValue#setValue
*
*/
public void setBigDecimal(BigDecimal theValue)
{
// needed to allow serializable BigDecimal
setValue((Object) theValue);
}
public void setValue(String theValue)
{
if (theValue == null)
{
value = null;
}
else
{
// Higher levels must have performed type checking for us.
value = theValue;
}
}
/*
** SQL Operators
*/
/**
* The = operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the =
* @param right The value on the right side of the =
*
* @return A SQL boolean value telling whether the two parameters are equal
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue equals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
return SQLBoolean.truthValue(left,
right,
left.compare(ORDER_OP_EQUALS, right, true, false));
}
/**
* The <> operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the <>
* @param right The value on the right side of the <>
*
* @return A SQL boolean value telling whether the two parameters
* are not equal
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue notEquals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
return SQLBoolean.truthValue(left,
right,
!left.compare(ORDER_OP_EQUALS, right, true, false));
}
/*
** String display of value
*/
public String toString()
{
if (isNull())
{
return "NULL";
}
else
{
return value.toString();
}
}
/*
* Hash code
*/
public int hashCode()
{
if (isNull())
return 0;
return value.hashCode();
}
/** @see DataValueDescriptor#typePrecedence */
public int typePrecedence()
{
return TypeId.USER_PRECEDENCE;
}
/**
* Check if the value is null.
*
* @return Whether or not value is logically null.
*/
public final boolean isNull()
{
return (value == null);
}
}
| |
package jp.co.iret.sfq;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class SFQueueClientRemote extends SFQueueClient
{
static final String CRLF = "\r\n";
static final String LF = "\n";
Map<String, Object> conn_params;
SFQueueClientRemote(final Map<String, Object> params)
throws SFQueueClientException
{
if (params == null)
{
throw new SFQueueClientException(1040);
}
conn_params = params;
}
private Map<String, Object> remote_io(final String opname, final Map<String, Object> params)
throws SFQueueClientException
{
Map<String, Object> ret = null;
try
{
final String host = (String)conn_params.get("host");
@SuppressWarnings("unchecked")
final
//Map<String, Integer> portMap = (Map<String, Integer>)Optional.ofNullable(conn_params.get("port")).orElse(new HashMap<>());
Map<String, Integer> portMap = (Map<String, Integer>)conn_params.getOrDefault("port", new HashMap<>());
//int port = Optional.ofNullable(portMap.get(opname)).orElse(-1);
int port = portMap.getOrDefault(opname, -1);
if (port == -1)
{
switch (opname)
{
case "push": { port = 12701; break; }
case "pop": { port = 12711; break; }
case "shift": { port = 12721; break; }
default:
{
throw new Exception(opname + ": unknown operation");
}
}
}
final int timeout = (int)conn_params.getOrDefault("timeout", 2000);
//
final ArrayList<String> header_arr = new ArrayList<>();
final List<String> copyKeys = Arrays.asList("querootdir", "quename", "eworkdir");
final List<String> ignoreKeys = Arrays.asList("payload");
//
byte[] body = null;
if (params.containsKey("payload"))
{
final Object o = params.get("payload");
if (o instanceof String)
{
body = ((String)o).getBytes();
header_arr.add("payload-type: text");
}
else
{
body = (byte[])o;
header_arr.add("payload-type: binary");
}
header_arr.add("payload-length: " + body.length);
}
//
header_arr.addAll
(
conn_params.keySet().stream()
.filter(e -> copyKeys.contains(e))
.map(e -> e.replaceAll("_", "-") + ": " + (String)conn_params.get(e))
.collect(Collectors.toList())
);
header_arr.addAll
(
params.keySet().stream()
.filter(e -> ! ignoreKeys.contains(e))
.map(e -> e.replaceAll("_", "-") + ": " + (String)params.get(e))
.collect(Collectors.toList())
);
//header_arr.forEach(System.out::println);
//
byte[] respAll = null;
final String header = String.join(CRLF, header_arr) + CRLF + CRLF;
try (Socket sock = new Socket(host, port))
{
sock.setSoTimeout(timeout);
try (OutputStream os = sock.getOutputStream(); DataInputStream dis = new DataInputStream(sock.getInputStream()))
{
os.write(header.getBytes());
if (body != null)
{
os.write(body);
}
os.flush();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final byte[] buff = new byte[8192];
int rb = 0;
do
{
rb = dis.read(buff);
if (rb > 0)
{
baos.write(buff, 0, rb);
}
}
while (rb != -1);
respAll = baos.toByteArray();
}
}
ret = parse_response(respAll);
}
catch (final SFQueueClientException ex)
{
throw ex;
}
catch (final Exception ex)
{
throw new SFQueueClientException(1050, ex.getClass().getName());
}
return ret;
}
static Map<String, Object> parse_response(final byte[] arg) throws Exception
{
final Map<String, Object> ret = new HashMap<>();
final byte[] SEP_CRLF = (CRLF + CRLF).getBytes();
final byte[] SEP_LF = (LF + LF).getBytes();
int sep_offset = indexOf_byteArray(arg, SEP_CRLF);
int sep_length = SEP_CRLF.length;
if (sep_offset == -1)
{
sep_offset = indexOf_byteArray(arg, SEP_LF);
sep_length = SEP_LF.length;
}
byte[] baBody = null;
boolean bodyIsText = false;
if (sep_offset == -1)
{
// body only
baBody = arg;
}
else
{
if (sep_offset > 0)
{
final byte[] baHeader = Arrays.copyOfRange(arg, 0, sep_offset);
final String strHeader = new String(baHeader, "UTF-8");
final String[] strsHeader = strHeader.split(LF);
final Pattern pat = Pattern.compile("^\\s*([^:[:blank:]]+)\\s*:\\s*(.*)$");
for (final String str: strsHeader)
{
final Matcher matches = pat.matcher(str.trim());
if (! matches.find())
{
continue;
}
final String key = matches.group(1).trim().replaceAll("-", "_");
final String val = matches.group(2).trim();
if (key.equals("payload_type"))
{
if (val.equals("text"))
{
bodyIsText = true;
}
}
ret.put(key, val);
}
}
baBody = Arrays.copyOfRange(arg, sep_offset + sep_length, arg.length);
}
if (baBody != null)
{
final Object oBody = bodyIsText ? new String(baBody, "UTF-8") : baBody;
ret.put("payload", oBody);
}
return ret;
}
//
// http://stackoverflow.com/questions/21341027/find-indexof-a-byte-array-within-another-byte-array
//
static int indexOf_byteArray(final byte[] outerArray, final byte[] innerArray)
{
for(int i = 0; i < outerArray.length - innerArray.length; ++i)
{
boolean found = true;
for(int j = 0; j < innerArray.length; ++j)
{
if (outerArray[i+j] != innerArray[j])
{
found = false;
break;
}
}
if (found) return i;
}
return -1;
}
private boolean isDataOrThrow(final Map<String, Object> resp) throws SFQueueClientException
{
boolean ret = false;
if (! resp.containsKey("result_code"))
{
throw new SFQueueClientException(1050);
}
final int rc = Integer.parseInt((String)resp.get("result_code"));
if (rc == SFQ_RC_SUCCESS)
{
ret = true;
}
else
{
String msg = "* Un-Known *";
if (resp.containsKey("error_message"))
{
msg = (String)resp.get("error_message");
}
setLastError(rc);
setLastMessage("remote error rc=" + rc+ " msg=" + msg);
if (rc >= SFQ_RC_FATAL_MIN)
{
throw new SFQueueClientException(2000 + rc, "remote error rc=" + rc+ " msg=" + msg);
}
}
return ret;
}
@Override
public String push(final Map<String, Object> arg) throws SFQueueClientException
{
String ret = null;
clearLastError();
final Map<String, Object> resp = remote_io("push", arg);
if (isDataOrThrow(resp))
{
ret = (String)resp.getOrDefault("uuid", "");
}
return ret;
}
private Map<String, Object> remote_takeout(final String opname, final Map<String, Object> params)
throws SFQueueClientException
{
Map<String, Object> ret = null;
clearLastError();
final Map<String, Object> resp = remote_io(opname, params);
if (isDataOrThrow(resp))
{
ret = resp;
}
return ret;
}
@Override
public Map<String, Object> pop(final Map<String, Object> params) throws SFQueueClientException
{
return remote_takeout("pop", params);
}
@Override
public Map<String, Object> shift(final Map<String, Object> params) throws SFQueueClientException
{
return remote_takeout("shift", params);
}
}
| |
/*
* Copyright 2017-present Open Networking Foundation
*
* 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.onosproject.net.behaviour.trafficcontrol;
import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;
import org.onosproject.core.ApplicationId;
import org.onosproject.net.DeviceId;
import java.util.Collection;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Default implementation of the policer interface.
*/
@Beta
public final class DefaultPolicer implements Policer, PolicerEntry {
// Immutable parameters
private final DeviceId deviceId;
private final ApplicationId applicationId;
private final PolicerId policerId;
private final boolean colorAware;
private final Unit unit;
private final Collection<TokenBucket> tokenBuckets;
private final String description;
// Mutable parameters
private long referenceCount;
private long processedPackets;
private long processedBytes;
private long life;
private DefaultPolicer(DeviceId dId, ApplicationId aId, PolicerId pId,
boolean cA, Unit u, Collection<TokenBucket> tB,
String d) {
deviceId = dId;
applicationId = aId;
policerId = pId;
colorAware = cA;
unit = u;
tokenBuckets = tB;
description = d;
}
@Override
public DeviceId deviceId() {
return deviceId;
}
@Override
public ApplicationId applicationId() {
return applicationId;
}
@Override
public PolicerId policerId() {
return policerId;
}
@Override
public boolean isColorAware() {
return colorAware;
}
@Override
public Unit unit() {
return unit;
}
@Override
public Collection<TokenBucket> tokenBuckets() {
return tokenBuckets;
}
@Override
public String description() {
return description;
}
@Override
public long referenceCount() {
return referenceCount;
}
@Override
public void setReferenceCount(long count) {
referenceCount = count;
}
@Override
public long processedPackets() {
return processedPackets;
}
@Override
public void setProcessedPackets(long packets) {
processedPackets = packets;
}
@Override
public long processedBytes() {
return processedBytes;
}
@Override
public void setProcessedBytes(long bytes) {
processedBytes = bytes;
}
@Override
public long life() {
return life;
}
@Override
public void setLife(long l) {
life = l;
}
@Override
public String toString() {
return toStringHelper(this)
.add("appId", applicationId())
.add("id", policerId())
.add("isColorAware", isColorAware())
.add("unit", unit())
.add("tokenBuckets", tokenBuckets())
.add("description", description())
.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultPolicer that = (DefaultPolicer) o;
return Objects.equal(policerId, that.policerId);
}
@Override
public int hashCode() {
return policerId.hashCode();
}
/**
* Returns a new builder reference.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Implementation of the policer builder interface.
*/
public static final class Builder implements Policer.Builder {
private DeviceId deviceId;
private ApplicationId applicationId;
private PolicerId policerId;
// Default to unaware
private boolean colorAware = false;
// Default to MBps
private Unit unit = Unit.MB_PER_SEC;
private Collection<TokenBucket> tokenBuckets;
private String description = "";
@Override
public Policer.Builder forDeviceId(DeviceId dId) {
deviceId = dId;
return this;
}
@Override
public Policer.Builder fromApp(ApplicationId appId) {
applicationId = appId;
return this;
}
@Override
public Policer.Builder withId(PolicerId id) {
policerId = id;
return this;
}
@Override
public Policer.Builder colorAware(boolean isColorAware) {
colorAware = isColorAware;
return this;
}
@Override
public Policer.Builder withUnit(Unit u) {
unit = u;
return this;
}
@Override
public Policer.Builder withPolicingResource(PolicingResource policingResource) {
policerId = policingResource.policerId();
deviceId = policingResource.connectPoint().deviceId();
return this;
}
@Override
public Policer.Builder withTokenBuckets(Collection<TokenBucket> tB) {
tokenBuckets = ImmutableSet.copyOf(tB);
return this;
}
@Override
public Policer.Builder withDescription(String d) {
description = d;
return this;
}
@Override
public DefaultPolicer build() {
// Not null condition on some mandatory parameters
checkNotNull(deviceId, "Must specify a deviceId");
checkNotNull(applicationId, "Must specify an application id");
checkNotNull(policerId, "Must specify a policer id");
checkNotNull(unit, "Must specify a unit for the policer");
checkNotNull(tokenBuckets, "Must have token buckets");
checkNotNull(description, "Must have a description");
// Verify argument conditions
checkArgument(!tokenBuckets.isEmpty(), "Must have at least one token bucket");
// Finally we build the policer
return new DefaultPolicer(deviceId, applicationId, policerId,
colorAware, unit, tokenBuckets,
description);
}
}
}
| |
package org.newdawn.slick.geom;
/**
* Implemenation of a bunch of maths functions to do with lines. Note
* that lines can't be used as dynamic shapes right now - also collision
* with the end of a line is undefined.
*
* @author Kevin Glass
*/
public strictfp class Line extends Shape {
/** The start point of the line */
private Vector2f start;
/** The end point of the line */
private Vector2f end;
/** The vector between the two points */
private Vector2f vec;
/** The length of the line squared */
private float lenSquared;
/** Temporary storage - declared globally to reduce GC */
private Vector2f loc = new Vector2f(0,0);
/** Temporary storage - declared globally to reduce GC */
private Vector2f v = new Vector2f(0,0);
/** Temporary storage - declared globally to reduce GC */
private Vector2f v2 = new Vector2f(0,0);
/** Temporary storage - declared globally to reduce GC */
private Vector2f proj = new Vector2f(0,0);
/** Temporary storage - declared globally to reduce GC */
private Vector2f closest = new Vector2f(0,0);
/** Temporary storage - declared globally to reduce GC */
private Vector2f other = new Vector2f(0,0);
/** True if this line blocks on the outer edge */
private boolean outerEdge = true;
/** True if this line blocks on the inner edge */
private boolean innerEdge = true;
/**
* Create a new line based on the origin and a single point
*
* @param x The end point of the line
* @param y The end point of the line
* @param inner True if this line blocks on it's inner edge
* @param outer True if this line blocks on it's outer edge
*/
public Line(float x, float y, boolean inner, boolean outer) {
this(0,0,x,y);
}
/**
* Create a new line based on the origin and a single point
*
* @param x The end point of the line
* @param y The end point of the line
*/
public Line(float x, float y) {
this(x,y,true,true);
}
/**
* Create a new line based on two points
*
* @param x1 The x coordinate of the start point
* @param y1 The y coordinate of the start point
* @param x2 The x coordinate of the end point
* @param y2 The y coordinate of the end point
*/
public Line(float x1, float y1, float x2, float y2) {
this(new Vector2f(x1,y1), new Vector2f(x2,y2));
}
/**
* Create a line with relative second point
*
* @param x1 The x coordinate of the start point
* @param y1 The y coordinate of the start point
* @param dx The x change to get to the second point
* @param dy The y change to get to the second point
* @param dummy A dummy value
*/
public Line(float x1, float y1, float dx, float dy, boolean dummy) {
this(new Vector2f(x1,y1), new Vector2f(x1+dx,y1+dy));
}
/**
* Create a new line based on two points
*
* @param start The start point
* @param end The end point
*/
public Line(Vector2f start, Vector2f end) {
super();
set(start,end);
}
/**
* Get the start point of the line
*
* @return The start point of the line
*/
public Vector2f getStart() {
return start;
}
/**
* Get the end point of the line
*
* @return The end point of the line
*/
public Vector2f getEnd() {
return end;
}
/**
* Find the length of the line
*
* @return The the length of the line
*/
public float length() {
return vec.length();
}
/**
* Find the length of the line squared (cheaper and good for comparisons)
*
* @return The length of the line squared
*/
public float lengthSquared() {
return vec.lengthSquared();
}
/**
* Configure the line
*
* @param start The start point of the line
* @param end The end point of the line
*/
public void set(Vector2f start, Vector2f end) {
super.pointsDirty = true;
this.start = start;
this.end = end;
vec = new Vector2f(end);
vec.sub(start);
lenSquared = vec.length();
lenSquared *= lenSquared;
}
/**
* Get the x direction of this line
*
* @return The x direction of this line
*/
public float getDX() {
return end.getX() - start.getX();
}
/**
* Get the y direction of this line
*
* @return The y direction of this line
*/
public float getDY() {
return end.getY() - start.getY();
}
/**
* Get the x coordinate of the start point
*
* @return The x coordinate of the start point
*/
public float getX1() {
return start.getX();
}
/**
* Get the y coordinate of the start point
*
* @return The y coordinate of the start point
*/
public float getY1() {
return start.getY();
}
/**
* Get the x coordinate of the end point
*
* @return The x coordinate of the end point
*/
public float getX2() {
return end.getX();
}
/**
* Get the y coordinate of the end point
*
* @return The y coordinate of the end point
*/
public float getY2() {
return end.getY();
}
/**
* Get the shortest distance from a point to this line
*
* @param point The point from which we want the distance
* @return The distance from the line to the point
*/
public float distance(Vector2f point) {
return (float) Math.sqrt(distanceSquared(point));
}
/**
* Check if the given point is on the line
*
* @param point The point to check
* @return True if the point is on this line
*/
public boolean on(Vector2f point) {
return distanceSquared(point) == 0;
}
/**
* Get the shortest distance squared from a point to this line
*
* @param point The point from which we want the distance
* @return The distance squared from the line to the point
*/
public float distanceSquared(Vector2f point) {
getClosestPoint(point, closest);
closest.sub(point);
float result = closest.lengthSquared();
return result;
}
/**
* Get the closest point on the line to a given point
*
* @param point The point which we want to project
* @param result The point on the line closest to the given point
*/
public void getClosestPoint(Vector2f point, Vector2f result) {
loc.set(point);
loc.sub(start);
float projDistance = vec.dot(loc);
projDistance /= vec.lengthSquared();
if (projDistance < 0) {
result.set(start);
return;
}
if (projDistance > 1) {
result.set(end);
return;
}
result.x = start.getX() + projDistance * vec.getX();
result.y = start.getY() + projDistance * vec.getY();
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return "[Line "+start+","+end+"]";
}
/**
* Intersect this line with another
*
* @param other The other line we should intersect with
* @return The intersection point or null if the lines are parallel
*/
public Vector2f intersect(Line other) {
return intersect(other, false);
}
/**
* Intersect this line with another
*
* @param other The other line we should intersect with
* @param limit True if the collision is limited to the extent of the lines
* @return The intersection point or null if the lines don't intersect
*/
public Vector2f intersect(Line other, boolean limit) {
float dx1 = end.getX() - start.getX();
float dx2 = other.end.getX() - other.start.getX();
float dy1 = end.getY() - start.getY();
float dy2 = other.end.getY() - other.start.getY();
float denom = (dy2 * dx1) - (dx2 * dy1);
if (denom == 0) {
return null;
}
float ua = (dx2 * (start.getY() - other.start.getY())) - (dy2 * (start.getX() - other.start.getX()));
ua /= denom;
float ub = (dx1 * (start.getY() - other.start.getY())) - (dy1 * (start.getX() - other.start.getX()));
ub /= denom;
if ((limit) && ((ua < 0) || (ua > 1) || (ub < 0) || (ub > 1))) {
return null;
}
float u = ua;
float ix = start.getX() + (u * (end.getX() - start.getX()));
float iy = start.getY() + (u * (end.getY() - start.getY()));
return new Vector2f(ix,iy);
}
/**
* @see org.newdawn.slick.geom.Shape#createPoints()
*/
protected void createPoints() {
points = new float[4];
points[0] = getX1();
points[1] = getY1();
points[2] = getX2();
points[3] = getY2();
}
/**
* @see org.newdawn.slick.geom.Shape#transform(org.newdawn.slick.geom.Transform)
*/
public Shape transform(Transform transform) {
float[] temp = new float[4];
createPoints();
transform.transform(points, 0, temp, 0, 2);
return new Line(temp[0],temp[1],temp[2],temp[3]);
}
/**
* @see org.newdawn.slick.geom.Shape#closed()
*/
public boolean closed() {
return false;
}
}
| |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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.intellij.util;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.DifferenceFilter;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import sun.reflect.ConstructorAccessor;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.*;
public class ReflectionUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.util.ReflectionUtil");
private ReflectionUtil() {
}
@Nullable
public static Type resolveVariable(@NotNull TypeVariable variable, @NotNull Class classType) {
return resolveVariable(variable, classType, true);
}
@Nullable
public static Type resolveVariable(@NotNull TypeVariable variable, @NotNull Class classType, boolean resolveInInterfacesOnly) {
final Class aClass = getRawType(classType);
int index = ArrayUtilRt.find(aClass.getTypeParameters(), variable);
if (index >= 0) {
return variable;
}
final Class[] classes = aClass.getInterfaces();
final Type[] genericInterfaces = aClass.getGenericInterfaces();
for (int i = 0; i <= classes.length; i++) {
Class anInterface;
if (i < classes.length) {
anInterface = classes[i];
}
else {
anInterface = aClass.getSuperclass();
if (resolveInInterfacesOnly || anInterface == null) {
continue;
}
}
final Type resolved = resolveVariable(variable, anInterface);
if (resolved instanceof Class || resolved instanceof ParameterizedType) {
return resolved;
}
if (resolved instanceof TypeVariable) {
final TypeVariable typeVariable = (TypeVariable)resolved;
index = ArrayUtilRt.find(anInterface.getTypeParameters(), typeVariable);
if (index < 0) {
LOG.error("Cannot resolve type variable:\n" + "typeVariable = " + typeVariable + "\n" + "genericDeclaration = " +
declarationToString(typeVariable.getGenericDeclaration()) + "\n" + "searching in " + declarationToString(anInterface));
}
final Type type = i < genericInterfaces.length ? genericInterfaces[i] : aClass.getGenericSuperclass();
if (type instanceof Class) {
return Object.class;
}
if (type instanceof ParameterizedType) {
return getActualTypeArguments((ParameterizedType)type)[index];
}
throw new AssertionError("Invalid type: " + type);
}
}
return null;
}
@SuppressWarnings("HardCodedStringLiteral")
@NotNull
public static String declarationToString(@NotNull GenericDeclaration anInterface) {
return anInterface.toString()
+ Arrays.asList(anInterface.getTypeParameters())
+ " loaded by " + ((Class)anInterface).getClassLoader();
}
@NotNull
public static Class<?> getRawType(@NotNull Type type) {
if (type instanceof Class) {
return (Class)type;
}
if (type instanceof ParameterizedType) {
return getRawType(((ParameterizedType)type).getRawType());
}
if (type instanceof GenericArrayType) {
//todo[peter] don't create new instance each time
return Array.newInstance(getRawType(((GenericArrayType)type).getGenericComponentType()), 0).getClass();
}
assert false : type;
return null;
}
@NotNull
public static Type[] getActualTypeArguments(@NotNull ParameterizedType parameterizedType) {
return parameterizedType.getActualTypeArguments();
}
@Nullable
public static Class<?> substituteGenericType(@NotNull Type genericType, @NotNull Type classType) {
if (genericType instanceof TypeVariable) {
final Class<?> aClass = getRawType(classType);
final Type type = resolveVariable((TypeVariable)genericType, aClass);
if (type instanceof Class) {
return (Class)type;
}
if (type instanceof ParameterizedType) {
return (Class<?>)((ParameterizedType)type).getRawType();
}
if (type instanceof TypeVariable && classType instanceof ParameterizedType) {
final int index = ArrayUtilRt.find(aClass.getTypeParameters(), type);
if (index >= 0) {
return getRawType(getActualTypeArguments((ParameterizedType)classType)[index]);
}
}
}
else {
return getRawType(genericType);
}
return null;
}
@NotNull
public static List<Field> collectFields(@NotNull Class clazz) {
List<Field> result = new ArrayList<Field>();
collectFields(clazz, result);
return result;
}
@NotNull
public static Field findField(@NotNull Class clazz, @Nullable final Class type, @NotNull final String name) throws NoSuchFieldException {
Field result = processFields(clazz, new Condition<Field>() {
@Override
public boolean value(Field field) {
return name.equals(field.getName()) && (type == null || field.getType().equals(type));
}
});
if (result != null) return result;
throw new NoSuchFieldException("Class: " + clazz + " name: " + name + " type: " + type);
}
@NotNull
public static Field findAssignableField(@NotNull Class<?> clazz, @Nullable("null means any type") final Class<?> fieldType, @NotNull final String fieldName) throws NoSuchFieldException {
Field result = processFields(clazz, new Condition<Field>() {
@Override
public boolean value(Field field) {
return fieldName.equals(field.getName()) && (fieldType == null || fieldType.isAssignableFrom(field.getType()));
}
});
if (result != null) return result;
throw new NoSuchFieldException("Class: " + clazz + " fieldName: " + fieldName + " fieldType: " + fieldType);
}
private static void collectFields(@NotNull Class clazz, @NotNull List<Field> result) {
final Field[] fields = clazz.getDeclaredFields();
result.addAll(Arrays.asList(fields));
final Class superClass = clazz.getSuperclass();
if (superClass != null) {
collectFields(superClass, result);
}
final Class[] interfaces = clazz.getInterfaces();
for (Class each : interfaces) {
collectFields(each, result);
}
}
private static Field processFields(@NotNull Class clazz, @NotNull Condition<Field> checker) {
for (Field field : clazz.getDeclaredFields()) {
if (checker.value(field)) {
field.setAccessible(true);
return field;
}
}
final Class superClass = clazz.getSuperclass();
if (superClass != null) {
Field result = processFields(superClass, checker);
if (result != null) return result;
}
final Class[] interfaces = clazz.getInterfaces();
for (Class each : interfaces) {
Field result = processFields(each, checker);
if (result != null) return result;
}
return null;
}
public static void resetField(@NotNull Class clazz, @Nullable("null means of any type") Class type, @NotNull String name) {
try {
resetField(null, findField(clazz, type, name));
}
catch (NoSuchFieldException e) {
LOG.info(e);
}
}
public static void resetField(@NotNull Object object, @Nullable("null means any type") Class type, @NotNull String name) {
try {
resetField(object, findField(object.getClass(), type, name));
}
catch (NoSuchFieldException e) {
LOG.info(e);
}
}
public static void resetField(@NotNull Object object, @NotNull String name) {
try {
resetField(object, findField(object.getClass(), null, name));
}
catch (NoSuchFieldException e) {
LOG.info(e);
}
}
public static void resetField(@Nullable final Object object, @NotNull Field field) {
field.setAccessible(true);
Class<?> type = field.getType();
try {
if (type.isPrimitive()) {
if (boolean.class.equals(type)) {
field.set(object, Boolean.FALSE);
}
else if (int.class.equals(type)) {
field.set(object, Integer.valueOf(0));
}
else if (double.class.equals(type)) {
field.set(object, Double.valueOf(0));
}
else if (float.class.equals(type)) {
field.set(object, Float.valueOf(0));
}
}
else {
field.set(object, null);
}
}
catch (IllegalAccessException e) {
LOG.info(e);
}
}
public static void resetStaticField(@NotNull Class aClass, @NotNull @NonNls String name) {
resetField(aClass, null, name);
}
@Nullable
public static Method findMethod(@NotNull Collection<Method> methods, @NonNls @NotNull String name, @NotNull Class... parameters) {
for (final Method method : methods) {
if (name.equals(method.getName()) && Arrays.equals(parameters, method.getParameterTypes())) {
method.setAccessible(true);
return method;
}
}
return null;
}
@Nullable
public static Method getMethod(@NotNull Class aClass, @NonNls @NotNull String name, @NotNull Class... parameters) {
return findMethod(getClassPublicMethods(aClass, false), name, parameters);
}
@Nullable
public static Method getDeclaredMethod(@NotNull Class aClass, @NonNls @NotNull String name, @NotNull Class... parameters) {
return findMethod(getClassDeclaredMethods(aClass, false), name, parameters);
}
@Nullable
public static Field getDeclaredField(@NotNull Class aClass, @NonNls @NotNull final String name) {
return processFields(aClass, new Condition<Field>() {
@Override
public boolean value(Field field) {
return name.equals(field.getName());
}
});
}
@NotNull
public static List<Method> getClassPublicMethods(@NotNull Class aClass) {
return getClassPublicMethods(aClass, false);
}
@NotNull
public static List<Method> getClassPublicMethods(@NotNull Class aClass, boolean includeSynthetic) {
Method[] methods = aClass.getMethods();
return includeSynthetic ? Arrays.asList(methods) : filterRealMethods(methods);
}
@NotNull
public static List<Method> getClassDeclaredMethods(@NotNull Class aClass) {
return getClassDeclaredMethods(aClass, false);
}
@NotNull
public static List<Method> getClassDeclaredMethods(@NotNull Class aClass, boolean includeSynthetic) {
Method[] methods = aClass.getDeclaredMethods();
return includeSynthetic ? Arrays.asList(methods) : filterRealMethods(methods);
}
@NotNull
public static List<Field> getClassDeclaredFields(@NotNull Class aClass) {
Field[] fields = aClass.getDeclaredFields();
return Arrays.asList(fields);
}
@NotNull
private static List<Method> filterRealMethods(@NotNull Method[] methods) {
List<Method> result = ContainerUtil.newArrayList();
for (Method method : methods) {
if (!method.isSynthetic()) {
result.add(method);
}
}
return result;
}
@Nullable
public static Class getMethodDeclaringClass(@NotNull Class<?> instanceClass, @NonNls @NotNull String methodName, @NotNull Class... parameters) {
Method method = getMethod(instanceClass, methodName, parameters);
return method == null ? null : method.getDeclaringClass();
}
public static <T> T getField(@NotNull Class objectClass, @Nullable Object object, @Nullable("null means any type") Class<T> fieldType, @NotNull @NonNls String fieldName) {
try {
final Field field = findAssignableField(objectClass, fieldType, fieldName);
return (T)field.get(object);
}
catch (NoSuchFieldException e) {
LOG.debug(e);
return null;
}
catch (IllegalAccessException e) {
LOG.debug(e);
return null;
}
}
public static <T> T getStaticFieldValue(@NotNull Class objectClass, @Nullable("null means any type") Class<T> fieldType, @NotNull @NonNls String fieldName) {
try {
final Field field = findAssignableField(objectClass, fieldType, fieldName);
if (!Modifier.isStatic(field.getModifiers())) {
throw new IllegalArgumentException("Field " + objectClass + "." + fieldName + " is not static");
}
return (T)field.get(null);
}
catch (NoSuchFieldException e) {
LOG.debug(e);
return null;
}
catch (IllegalAccessException e) {
LOG.debug(e);
return null;
}
}
// returns true if value was set
public static <T> boolean setField(@NotNull Class objectClass,
Object object,
@Nullable("null means any type") Class<T> fieldType,
@NotNull @NonNls String fieldName,
T value) {
try {
final Field field = findAssignableField(objectClass, fieldType, fieldName);
field.set(object, value);
return true;
}
catch (NoSuchFieldException e) {
LOG.debug(e);
// this 'return' was moved into 'catch' block because otherwise reference to common super-class of these exceptions (ReflectiveOperationException)
// which doesn't exist in JDK 1.6 will be added to class-file during instrumentation
return false;
}
catch (IllegalAccessException e) {
LOG.debug(e);
return false;
}
}
public static Type resolveVariableInHierarchy(@NotNull TypeVariable variable, @NotNull Class aClass) {
Type type;
Class current = aClass;
while ((type = resolveVariable(variable, current, false)) == null) {
current = current.getSuperclass();
if (current == null) {
return null;
}
}
if (type instanceof TypeVariable) {
return resolveVariableInHierarchy((TypeVariable)type, aClass);
}
return type;
}
@NotNull
public static <T> Constructor<T> getDefaultConstructor(@NotNull Class<T> aClass) {
try {
final Constructor<T> constructor = aClass.getConstructor();
constructor.setAccessible(true);
return constructor;
}
catch (NoSuchMethodException e) {
throw new RuntimeException("No default constructor in " + aClass, e);
}
}
private static final Method acquireConstructorAccessorMethod = getDeclaredMethod(Constructor.class, "acquireConstructorAccessor");
private static final Method getConstructorAccessorMethod = getDeclaredMethod(Constructor.class, "getConstructorAccessor");
/** @deprecated private API (to be removed in IDEA 17) */
public static ConstructorAccessor getConstructorAccessor(@NotNull Constructor constructor) {
if (acquireConstructorAccessorMethod == null || getConstructorAccessorMethod == null) {
throw new IllegalStateException();
}
constructor.setAccessible(true);
try {
acquireConstructorAccessorMethod.invoke(constructor);
return (ConstructorAccessor)getConstructorAccessorMethod.invoke(constructor);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/** @deprecated private API, use {@link #createInstance(Constructor, Object...)} instead (to be removed in IDEA 17) */
public static <T> T createInstanceViaConstructorAccessor(@NotNull ConstructorAccessor constructorAccessor, @NotNull Object... arguments) {
try {
@SuppressWarnings("unchecked") T t = (T)constructorAccessor.newInstance(arguments);
return t;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/** @deprecated private API, use {@link #newInstance(Class)} instead (to be removed in IDEA 17) */
public static <T> T createInstanceViaConstructorAccessor(@NotNull ConstructorAccessor constructorAccessor) {
try {
@SuppressWarnings("unchecked") T t = (T)constructorAccessor.newInstance(ArrayUtil.EMPTY_OBJECT_ARRAY);
return t;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @deprecated use {@link #newInstance(Class)} instead (this method will fail anyway if non-empty {@code parameterTypes} is passed)
*/
public static <T> T newInstance(@NotNull Class<T> aClass, @NotNull Class... parameterTypes) {
return newInstance(aClass);
}
/**
* Like {@link Class#newInstance()} but also handles private classes
*/
@NotNull
public static <T> T newInstance(@NotNull Class<T> aClass) {
try {
Constructor<T> constructor = aClass.getDeclaredConstructor();
try {
constructor.setAccessible(true);
}
catch (SecurityException e) {
return aClass.newInstance();
}
return constructor.newInstance();
}
catch (Exception e) {
// support Kotlin data classes - pass null as default value
for (Annotation annotation : aClass.getAnnotations()) {
String name = annotation.annotationType().getName();
if (name.equals("kotlin.Metadata") || name.equals("kotlin.jvm.internal.KotlinClass")) {
Constructor<?>[] constructors = aClass.getDeclaredConstructors();
Exception exception = e;
ctorLoop:
for (Constructor<?> constructor1 : constructors) {
try {
try {
constructor1.setAccessible(true);
}
catch (Throwable ignored) {
}
Class<?>[] parameterTypes = constructor1.getParameterTypes();
for (Class<?> type : parameterTypes) {
if (type.getName().equals("kotlin.jvm.internal.DefaultConstructorMarker")) {
continue ctorLoop;
}
}
//noinspection unchecked
return (T)constructor1.newInstance(new Object[parameterTypes.length]);
}
catch (Exception e1) {
exception = e1;
}
}
throw new RuntimeException(exception);
}
}
throw new RuntimeException(e);
}
}
@NotNull
public static <T> T createInstance(@NotNull Constructor<T> constructor, @NotNull Object... args) {
try {
return constructor.newInstance(args);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void resetThreadLocals() {
resetField(Thread.currentThread(), null, "threadLocals");
}
@Nullable
public static Class getGrandCallerClass() {
int stackFrameCount = 3;
Class callerClass = findCallerClass(stackFrameCount);
while (callerClass != null && callerClass.getClassLoader() == null) { // looks like a system class
callerClass = findCallerClass(++stackFrameCount);
}
if (callerClass == null) {
callerClass = findCallerClass(2);
}
return callerClass;
}
public static void copyFields(@NotNull Field[] fields, @NotNull Object from, @NotNull Object to) {
copyFields(fields, from, to, null);
}
public static boolean copyFields(@NotNull Field[] fields, @NotNull Object from, @NotNull Object to, @Nullable DifferenceFilter diffFilter) {
Set<Field> sourceFields = new com.intellij.util.containers.HashSet<Field>(Arrays.asList(from.getClass().getFields()));
boolean valuesChanged = false;
for (Field field : fields) {
if (sourceFields.contains(field)) {
if (isPublic(field) && !isFinal(field)) {
try {
if (diffFilter == null || diffFilter.isAccept(field)) {
copyFieldValue(from, to, field);
valuesChanged = true;
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
return valuesChanged;
}
public static void copyFieldValue(@NotNull Object from, @NotNull Object to, @NotNull Field field)
throws IllegalAccessException {
Class<?> fieldType = field.getType();
if (fieldType.isPrimitive() || fieldType.equals(String.class)) {
field.set(to, field.get(from));
}
else {
throw new RuntimeException("Field '" + field.getName()+"' not copied: unsupported type: "+field.getType());
}
}
private static boolean isPublic(final Field field) {
return (field.getModifiers() & Modifier.PUBLIC) != 0;
}
private static boolean isFinal(final Field field) {
return (field.getModifiers() & Modifier.FINAL) != 0;
}
@NotNull
public static Class forName(@NotNull String fqn) {
try {
return Class.forName(fqn);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private static class MySecurityManager extends SecurityManager {
private static final MySecurityManager INSTANCE = new MySecurityManager();
public Class[] getStack() {
return getClassContext();
}
}
/**
* Returns the class this method was called 'framesToSkip' frames up the caller hierarchy.
*
* NOTE:
* <b>Extremely expensive!
* Please consider not using it.
* These aren't the droids you're looking for!</b>
*/
@Nullable
public static Class findCallerClass(int framesToSkip) {
try {
Class[] stack = MySecurityManager.INSTANCE.getStack();
int indexFromTop = 1 + framesToSkip;
return stack.length > indexFromTop ? stack[indexFromTop] : null;
}
catch (Exception e) {
LOG.warn(e);
return null;
}
}
public static boolean isAssignable(@NotNull Class<?> ancestor, @NotNull Class<?> descendant) {
return ancestor == descendant || ancestor.isAssignableFrom(descendant);
}
}
| |
/*
* Copyright (c) 2010-2020. Axon Framework
*
* 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.axonframework.eventhandling;
import org.axonframework.common.Assert;
import org.axonframework.common.AxonThreadFactory;
import org.axonframework.messaging.StreamableMessageSource;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static org.axonframework.common.BuilderUtils.assertNonNull;
import static org.axonframework.common.BuilderUtils.assertThat;
/**
* Configuration object for the {@link TrackingEventProcessor}. The TrackingEventProcessorConfiguration provides access
* to the options to tweak various settings. Instances are not thread-safe and should not be altered after they have
* been used to initialize a TrackingEventProcessor.
*
* @author Christophe Bouhier
* @author Allard Buijze
* @since 3.1
*/
public class TrackingEventProcessorConfiguration {
private static final int DEFAULT_BATCH_SIZE = 1;
private static final int DEFAULT_THREAD_COUNT = 1;
private static final int DEFAULT_TOKEN_CLAIM_INTERVAL = 5000;
private final int maxThreadCount;
private int batchSize;
private int initialSegmentCount;
private Function<StreamableMessageSource<TrackedEventMessage<?>>, TrackingToken> initialTrackingTokenBuilder = StreamableMessageSource::createTailToken;
private Function<String, ThreadFactory> threadFactory;
private long tokenClaimInterval;
private int eventAvailabilityTimeout = 1000;
private EventTrackerStatusChangeListener eventTrackerStatusChangeListener = EventTrackerStatusChangeListener.noOp();
/**
* Initialize a configuration with single threaded processing.
*
* @return a Configuration prepared for single threaded processing
*/
public static TrackingEventProcessorConfiguration forSingleThreadedProcessing() {
return new TrackingEventProcessorConfiguration(DEFAULT_THREAD_COUNT);
}
/**
* Initialize a configuration instance with the given {@code threadCount}. This is both the number of threads that a
* processor will start for processing, as well as the initial number of segments that will be created when the
* processor is first started.
*
* @param threadCount the number of segments to process in parallel
* @return a newly created configuration
*/
public static TrackingEventProcessorConfiguration forParallelProcessing(int threadCount) {
return new TrackingEventProcessorConfiguration(threadCount);
}
private TrackingEventProcessorConfiguration(int numberOfSegments) {
this.batchSize = DEFAULT_BATCH_SIZE;
this.initialSegmentCount = numberOfSegments;
this.maxThreadCount = numberOfSegments;
this.threadFactory = pn -> new AxonThreadFactory("EventProcessor[" + pn + "]");
this.tokenClaimInterval = DEFAULT_TOKEN_CLAIM_INTERVAL;
}
/**
* @param batchSize The maximum number of events to process in a single batch.
* @return {@code this} for method chaining
*/
public TrackingEventProcessorConfiguration andBatchSize(int batchSize) {
Assert.isTrue(batchSize > 0, () -> "Batch size must be greater or equal to 1");
this.batchSize = batchSize;
return this;
}
/**
* @param segmentsSize The number of segments requested for handling asynchronous processing of events.
* @return {@code this} for method chaining
*/
public TrackingEventProcessorConfiguration andInitialSegmentsCount(int segmentsSize) {
this.initialSegmentCount = segmentsSize;
return this;
}
/**
* Sets the ThreadFactory to use to create the threads to process events on. Each Segment will be processed by a
* separate thread.
*
* @param threadFactory The factory to create threads with
* @return {@code this} for method chaining
*/
public TrackingEventProcessorConfiguration andThreadFactory(Function<String, ThreadFactory> threadFactory) {
this.threadFactory = threadFactory;
return this;
}
/**
* Set the duration where a Tracking Processor will wait for the availability of Events, in each cycle, before
* extending the claim on the tokens it owns.
* <p>
* Note that some storage engines for the EmbeddedEventStore do not support streaming. They may poll for messages
* once on an {@link TrackingEventStream#hasNextAvailable(int, TimeUnit)} invocation, and wait for the timeout to
* occur.
* <p>
* This value should be significantly shorter than the claim timeout configured on the Token Store. Failure to do so
* may cause claims to be stolen while a tread is waiting for events. Also, with very long timeouts, it will take
* longer for threads to pick up the instructions they need to process.
* <p>
* Defaults to 1 second.
* <p>
* The given value must be strictly larger than 0, and may not exceed {@code Integer.MAX_VALUE} milliseconds.
*
* @param interval The interval in which claims on segments need to be extended
* @param unit The unit in which the interval is expressed
* @return {@code this} for method chaining
*/
public TrackingEventProcessorConfiguration andEventAvailabilityTimeout(long interval, TimeUnit unit) {
long i = unit.toMillis(interval);
assertThat(i, it -> it <= Integer.MAX_VALUE,
"Interval may not be longer than Integer.MAX_VALUE milliseconds long");
assertThat(i, it -> it > 0, "Interval must be strictly positive");
this.eventAvailabilityTimeout = (int) i;
return this;
}
/**
* Sets the Builder to use to create the initial tracking token. This token is used by the processor as a starting
* point.
*
* @param initialTrackingTokenBuilder The Builder of initial tracking token
* @return {@code this} for method chaining
*/
public TrackingEventProcessorConfiguration andInitialTrackingToken(
Function<StreamableMessageSource<TrackedEventMessage<?>>, TrackingToken> initialTrackingTokenBuilder) {
this.initialTrackingTokenBuilder = initialTrackingTokenBuilder;
return this;
}
/**
* Sets the time to wait after a failed attempt to claim any token, before making another attempt.
*
* @param tokenClaimInterval The time to wait in between attempts to claim a token
* @param timeUnit The unit of time
* @return {@code this} for method chaining
*/
public TrackingEventProcessorConfiguration andTokenClaimInterval(long tokenClaimInterval, TimeUnit timeUnit) {
this.tokenClaimInterval = timeUnit.toMillis(tokenClaimInterval);
return this;
}
/**
* Sets the {@link EventTrackerStatusChangeListener} which will be called on {@link EventTrackerStatus} changes.
* Defaults to {@link EventTrackerStatusChangeListener#noOp()}.
*
* @param eventTrackerStatusChangeListener the {@link EventTrackerStatusChangeListener} to use
* @return {@code this} for method chaining
*/
public TrackingEventProcessorConfiguration andEventTrackerStatusChangeListener(
EventTrackerStatusChangeListener eventTrackerStatusChangeListener
) {
assertNonNull(eventTrackerStatusChangeListener, "EventTrackerStatusChangeListener may not be null");
this.eventTrackerStatusChangeListener = eventTrackerStatusChangeListener;
return this;
}
/**
* @return the maximum number of events to process in a single batch.
*/
public int getBatchSize() {
return batchSize;
}
/**
* @return the number of segments requested for handling asynchronous processing of events.
*/
public int getInitialSegmentsCount() {
return initialSegmentCount;
}
/**
* @return the Builder of initial tracking token
*/
public Function<StreamableMessageSource<TrackedEventMessage<?>>, TrackingToken> getInitialTrackingToken() {
return initialTrackingTokenBuilder;
}
/**
* @return the pool size of core threads as per {@link ThreadPoolExecutor#getCorePoolSize()}
*/
public int getMaxThreadCount() {
return maxThreadCount;
}
/**
* @return the time, in milliseconds, that a processor should wait for available events before going into a cycle of
* updating claims and checking for incoming instructions.
*/
public int getEventAvailabilityTimeout() {
return eventAvailabilityTimeout;
}
/**
* Provides the ThreadFactory to use to construct Threads for the processor with given {@code processorName}
*
* @param processorName The name of the processor for which to return the ThreadFactory
* @return the thread factory configured
*/
public ThreadFactory getThreadFactory(String processorName) {
return threadFactory.apply(processorName);
}
/**
* Returns the time, in milliseconds, the processor should wait after a failed attempt to claim any segments for
* processing. Generally, this means all segments are claimed.
*
* @return the time, in milliseconds, to wait in between attempts to claim a token
* @see #andTokenClaimInterval(long, TimeUnit)
*/
public long getTokenClaimInterval() {
return tokenClaimInterval;
}
/**
* Returns the {@link EventTrackerStatusChangeListener} defined in this configuration, to be called whenever an
* {@link EventTrackerStatus} change occurs.
*
* @return the {@link EventTrackerStatusChangeListener} defined in this configuration
*/
public EventTrackerStatusChangeListener getEventTrackerStatusChangeListener() {
return eventTrackerStatusChangeListener;
}
}
| |
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* 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.alibaba.nacos.config.server.utils;
import com.alibaba.nacos.api.exception.NacosException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringJUnit4ClassRunner.class)
public class ParamUtilsTest {
@Test
public void testIsValid() {
Assert.assertTrue(ParamUtils.isValid("test"));
Assert.assertTrue(ParamUtils.isValid("test1234"));
Assert.assertTrue(ParamUtils.isValid("test_-.:"));
Assert.assertFalse(ParamUtils.isValid("test!"));
Assert.assertFalse(ParamUtils.isValid("test~"));
}
@Test
public void testCheckParamV1() {
//dataId is empty
String dataId = "";
String group = "test";
String datumId = "test";
String content = "test";
try {
ParamUtils.checkParam(dataId, group, datumId, content);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//group is empty
dataId = "test";
group = "";
datumId = "test";
content = "test";
try {
ParamUtils.checkParam(dataId, group, datumId, content);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//datumId is empty
dataId = "test";
group = "test";
datumId = "";
content = "test";
try {
ParamUtils.checkParam(dataId, group, datumId, content);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//content is empty
dataId = "test";
group = "test";
datumId = "test";
content = "";
try {
ParamUtils.checkParam(dataId, group, datumId, content);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//dataId invalid
dataId = "test!";
group = "test";
datumId = "test";
content = "test";
try {
ParamUtils.checkParam(dataId, group, datumId, content);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//group invalid
dataId = "test";
group = "test!";
datumId = "test";
content = "test";
try {
ParamUtils.checkParam(dataId, group, datumId, content);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//datumId invalid
dataId = "test";
group = "test";
datumId = "test!";
content = "test";
try {
ParamUtils.checkParam(dataId, group, datumId, content);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//content over length
dataId = "test";
group = "test";
datumId = "test";
int maxContent = 10 * 1024 * 1024;
StringBuilder contentBuilder = new StringBuilder();
for (int i = 0; i < maxContent + 1; i++) {
contentBuilder.append("t");
}
content = contentBuilder.toString();
try {
ParamUtils.checkParam(dataId, group, datumId, content);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
}
@Test
public void testCheckParamV2() {
//tag invalid
String tag = "test!";
try {
ParamUtils.checkParam(tag);
Assert.fail();
} catch (IllegalArgumentException e) {
System.out.println(e.toString());
}
//tag over length
tag = "testtesttesttest1";
try {
ParamUtils.checkParam(tag);
Assert.fail();
} catch (IllegalArgumentException e) {
System.out.println(e.toString());
}
}
@Test
public void testCheckParamV3() {
//tag size over 5
Map<String, Object> configAdvanceInfo = new HashMap<>();
configAdvanceInfo.put("config_tags", "test,test,test,test,test,test");
try {
ParamUtils.checkParam(configAdvanceInfo);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//tag length over 5
configAdvanceInfo.clear();
StringBuilder tagBuilder = new StringBuilder();
for (int i = 0; i < 65; i++) {
tagBuilder.append("t");
}
configAdvanceInfo.put("config_tags", tagBuilder.toString());
try {
ParamUtils.checkParam(configAdvanceInfo);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//desc length over 128
configAdvanceInfo.clear();
StringBuilder descBuilder = new StringBuilder();
for (int i = 0; i < 129; i++) {
descBuilder.append("t");
}
configAdvanceInfo.put("desc", descBuilder.toString());
try {
ParamUtils.checkParam(configAdvanceInfo);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//use length over 32
configAdvanceInfo.clear();
StringBuilder useBuilder = new StringBuilder();
for (int i = 0; i < 33; i++) {
useBuilder.append("t");
}
configAdvanceInfo.put("use", useBuilder.toString());
try {
ParamUtils.checkParam(configAdvanceInfo);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//effect length over 32
configAdvanceInfo.clear();
StringBuilder effectBuilder = new StringBuilder();
for (int i = 0; i < 33; i++) {
effectBuilder.append("t");
}
configAdvanceInfo.put("effect", effectBuilder.toString());
try {
ParamUtils.checkParam(configAdvanceInfo);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//type length over 32
configAdvanceInfo.clear();
StringBuilder typeBuilder = new StringBuilder();
for (int i = 0; i < 33; i++) {
typeBuilder.append("t");
}
configAdvanceInfo.put("type", typeBuilder.toString());
try {
ParamUtils.checkParam(configAdvanceInfo);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//schema length over 32768
configAdvanceInfo.clear();
StringBuilder schemaBuilder = new StringBuilder();
for (int i = 0; i < 32769; i++) {
schemaBuilder.append("t");
}
configAdvanceInfo.put("schema", schemaBuilder.toString());
try {
ParamUtils.checkParam(configAdvanceInfo);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
//invalid param
configAdvanceInfo.clear();
configAdvanceInfo.put("test", "test");
try {
ParamUtils.checkParam(configAdvanceInfo);
Assert.fail();
} catch (NacosException e) {
System.out.println(e.toString());
}
}
@Test
public void testCheckTenant() {
//tag invalid
String tenant = "test!";
try {
ParamUtils.checkTenant(tenant);
Assert.fail();
} catch (IllegalArgumentException e) {
System.out.println(e.toString());
}
//tag over length
int tanantMaxLen = 128;
StringBuilder tenantBuilder = new StringBuilder();
for (int i = 0; i < tanantMaxLen + 1; i++) {
tenantBuilder.append("t");
}
tenant = tenantBuilder.toString();
try {
ParamUtils.checkTenant(tenant);
Assert.fail();
} catch (IllegalArgumentException e) {
System.out.println(e.toString());
}
}
}
| |
/*
* $Id$
*/
/*
Copyright (c) 2007 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.plugin.simulated;
import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.*;
import java.net.*;
import java.text.*;
import org.archive.io.*;
import org.archive.io.arc.*;
import org.archive.io.warc.*;
import org.archive.uid.RecordIDGenerator;
import org.archive.uid.UUIDGenerator;
import org.archive.util.anvl.*;
import org.archive.util.ArchiveUtils;
import org.lockss.util.*;
import org.lockss.test.*;
import org.lockss.plugin.base.*;
import org.lockss.crawler.*;
import org.lockss.daemon.*;
/**
* A convenience class which takes care of handling the content
* tree itself for the case where the content is in a WARC file.
*
* @author David S. H. Rosenthal
* @author Felix Ostrowski
* @version 0.0
*/
public class SimulatedWarcContentGenerator extends SimulatedContentGenerator {
private static Logger logger = Logger.getLogger("SimulatedWarcContentGenerator");
String warcFilePrefix = "SimulatedCrawl";
AtomicInteger serialNo = new AtomicInteger(0);
int maxSize = 100000000;
String[] suffix = {
".txt",
".html",
".pdf",
".jpg",
".bin",
};
String[] mimeType = {
"text/plain",
"text/html",
"application/pdf",
"image/jpg",
"application/octet-stream",
};
String[] stem = {
"http://www.content.org/",
"http://www.website.org/",
"http://www.library.org/",
};
boolean compressWarc = true;
public SimulatedWarcContentGenerator(String rootPath) {
super(rootPath);
logger.debug3("Created instance for " + rootPath);
}
public String generateContentTree() {
String ret = super.generateContentTree();
WARCWriter aw = makeWARCWriter();
long startPosition = 0;
// There should now be a suitable hierarchy at contentRoot,
// except that there needs to be a link to the eventual WARC file(s).
try {
for (int i = 0; i < stem.length; i++) {
boolean kill = ((i + 1) >= stem.length);
aw.checkSize();
startPosition = aw.getPosition();
logger.debug2("About to pack content for " + stem[i] + " in WARC at " +
contentRoot + " offset " + startPosition);
packIntoWarcFile(new File(contentRoot), new URL(stem[i]), aw, 0, kill);
logger.debug2("Packed content for " + stem[i] + " in WARC at " +
contentRoot + " to " + aw.getPosition());
}
aw.close();
linkToWarcFiles();
} catch (IOException ex) {
logger.error("pack() threw " + ex);
return null;
} finally {
}
printWarcFiles();
return ret;
}
private void packIntoWarcFile(File f,
URL url,
WARCWriter aw,
int lev,
boolean kill) throws IOException {
String fPath = f.getCanonicalPath();
logger.debug3("packIntoWarcFile(" + fPath + ") lev " + lev + " kill " + kill);
if (f.isDirectory()) {
// Iterate through the directory
File[] names = f.listFiles();
for (int i = 0; i < names.length; i++) {
String newPath = fPath + File.separator + names[i].getName();
String newUrl = url.toString();
if (!newUrl.endsWith(File.separator)) {
newUrl += File.separator;
}
newUrl += names[i].getName();
File newFile = new File(newPath);
packIntoWarcFile(newFile, new URL(newUrl), aw, lev + 1, kill);
}
{
String[] namesLeft = f.list();
if (namesLeft.length == 0) {
logger.debug3(fPath + " empty");
} else for (int j = 0; j < namesLeft.length; j++) {
logger.debug3(fPath + " contains " + namesLeft[j]);
}
}
if (lev > 1 && kill) {
logger.debug3("rmdir(" + fPath + ")");
f.delete();
}
} else if (f.isFile()) {
logger.debug3("File " + fPath + " lev " + lev);
String extension = ".warc" + (compressWarc ? ".gz" : "");
if (!fPath.endsWith(extension) &&
!fPath.endsWith(extension + ".open") &&
!(fPath.endsWith("index.html") && lev <= 1)) {
String uri = url.toString();
String contentType = mimeType[mimeType.length-1];
String hostIP = "127.0.0.1";
String timeStamp = ArchiveUtils.getLog14Date();
int recordLength = (int) f.length();
InputStream is = new FileInputStream(f);
for (int i = 0; i < suffix.length; i++) {
String name = f.getName();
if (name.endsWith(suffix[i])) {
contentType = mimeType[i];
break;
}
}
logger.debug3("Packing " + fPath + " type " + contentType);
ANVLRecord record = null;
// Use the following to add additional data:
// ANVLRecord record = new ANVLRecord();
// record.addLabelValue("foo", "bar");
// TODO: implement request records.
aw.writeResourceRecord(uri, timeStamp, contentType, record, is, recordLength);
logger.debug3("Wrote to " + aw.getPosition() + ": Deleting " + fPath);
if (kill) {
f.delete();
}
} else {
logger.debug3("Ignoring " + fPath);
}
} else {
String msg = fPath + " is neither file not dir";
logger.error(msg);
throw new IOException(msg);
}
}
private WARCWriter makeWARCWriter() {
WARCWriter ret = null;
List dirs = new ArrayList();
dirs.add(new File(contentRoot));
List warcinfoData = new ArrayList();
warcinfoData.add("");
String template = "${prefix}-${timestamp17}-${serialno}";
RecordIDGenerator generator = new UUIDGenerator();
WARCWriterPoolSettingsData settings = new WARCWriterPoolSettingsData(
warcFilePrefix, template, maxSize, compressWarc, dirs, warcinfoData,
generator);
ret = new WARCWriter(serialNo, settings);
return ret;
}
private void linkToWarcFiles() {
File dir = new File(contentRoot);
if (dir.isDirectory()) {
File index = new File(dir, INDEX_NAME);
if (index.exists() && index.isFile()) try {
FileOutputStream fos = new FileOutputStream(index);
PrintWriter pw = new PrintWriter(fos);
logger.debug3("Re-creating index file at " + index.getAbsolutePath());
String file_content =
getIndexContent(dir, INDEX_NAME, LockssPermission.LOCKSS_PERMISSION_STRING);
pw.print(file_content);
pw.flush();
pw.close();
fos.close();
} catch (IOException ex) {
logger.error("linkToWarcFiles() threw " + ex);
} else {
logger.error("index.html missing");
}
} else {
logger.error("Directory " + contentRoot + " missing");
}
}
private void printWarcFiles() {
File dir = new File(contentRoot);
if (dir.isDirectory()) try {
String[] fileNames = dir.list();
for (int i = 0; i < fileNames.length; i++) {
if (fileNames[i].endsWith(".warc.gz") ||
fileNames[i].endsWith("warc")) {
logger.debug3("File: " + fileNames[i]);
File aFile = new File(dir, fileNames[i]);
ArchiveReader aRead = ArchiveReaderFactory.get(aFile);
// Just don't ask why the next line is necessary
// TODO: ask why the next line is necessary.
// ((ARCReader)aRead).setParseHttpHeaders(false);
for (Iterator it = aRead.iterator(); it.hasNext(); ) {
ArchiveRecord aRec = (ArchiveRecord)it.next();
ArchiveRecordHeader aHead = aRec.getHeader();
logger.debug3(aHead.toString());
}
}
}
} catch (IOException ex) {
logger.error("linkToWarcFiles() threw " + ex);
} else {
logger.error("Directory " + contentRoot + " missing");
}
}
}
| |
/*
* 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.kafka.clients.producer.internals;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.header.internals.RecordHeader;
import org.apache.kafka.common.record.CompressionType;
import org.apache.kafka.common.record.MemoryRecords;
import org.apache.kafka.common.record.MemoryRecordsBuilder;
import org.apache.kafka.common.record.Record;
import org.apache.kafka.common.record.RecordBatch;
import org.apache.kafka.common.record.TimestampType;
import org.apache.kafka.test.TestUtils;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import static org.apache.kafka.common.record.RecordBatch.MAGIC_VALUE_V0;
import static org.apache.kafka.common.record.RecordBatch.MAGIC_VALUE_V1;
import static org.apache.kafka.common.record.RecordBatch.MAGIC_VALUE_V2;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class ProducerBatchTest {
private final long now = 1488748346917L;
private final MemoryRecordsBuilder memoryRecordsBuilder = MemoryRecords.builder(ByteBuffer.allocate(512),
CompressionType.NONE, TimestampType.CREATE_TIME, 128);
@Test
public void testBatchAbort() throws Exception {
ProducerBatch batch = new ProducerBatch(new TopicPartition("topic", 1), memoryRecordsBuilder, now);
MockCallback callback = new MockCallback();
FutureRecordMetadata future = batch.tryAppend(now, null, new byte[10], Record.EMPTY_HEADERS, callback, now);
KafkaException exception = new KafkaException();
batch.abort(exception);
assertTrue(future.isDone());
assertEquals(1, callback.invocations);
assertEquals(exception, callback.exception);
assertNull(callback.metadata);
// subsequent completion should be ignored
assertFalse(batch.complete(500L, 2342342341L));
assertFalse(batch.completeExceptionally(new KafkaException(), index -> new KafkaException()));
assertEquals(1, callback.invocations);
assertTrue(future.isDone());
try {
future.get();
fail("Future should have thrown");
} catch (ExecutionException e) {
assertEquals(exception, e.getCause());
}
}
@Test
public void testBatchCannotAbortTwice() throws Exception {
ProducerBatch batch = new ProducerBatch(new TopicPartition("topic", 1), memoryRecordsBuilder, now);
MockCallback callback = new MockCallback();
FutureRecordMetadata future = batch.tryAppend(now, null, new byte[10], Record.EMPTY_HEADERS, callback, now);
KafkaException exception = new KafkaException();
batch.abort(exception);
assertEquals(1, callback.invocations);
assertEquals(exception, callback.exception);
assertNull(callback.metadata);
try {
batch.abort(new KafkaException());
fail("Expected exception from abort");
} catch (IllegalStateException e) {
// expected
}
assertEquals(1, callback.invocations);
assertTrue(future.isDone());
try {
future.get();
fail("Future should have thrown");
} catch (ExecutionException e) {
assertEquals(exception, e.getCause());
}
}
@Test
public void testBatchCannotCompleteTwice() throws Exception {
ProducerBatch batch = new ProducerBatch(new TopicPartition("topic", 1), memoryRecordsBuilder, now);
MockCallback callback = new MockCallback();
FutureRecordMetadata future = batch.tryAppend(now, null, new byte[10], Record.EMPTY_HEADERS, callback, now);
batch.complete(500L, 10L);
assertEquals(1, callback.invocations);
assertNull(callback.exception);
assertNotNull(callback.metadata);
assertThrows(IllegalStateException.class, () -> batch.complete(1000L, 20L));
RecordMetadata recordMetadata = future.get();
assertEquals(500L, recordMetadata.offset());
assertEquals(10L, recordMetadata.timestamp());
}
@Test
public void testSplitPreservesHeaders() {
for (CompressionType compressionType : CompressionType.values()) {
MemoryRecordsBuilder builder = MemoryRecords.builder(
ByteBuffer.allocate(1024),
MAGIC_VALUE_V2,
compressionType,
TimestampType.CREATE_TIME,
0L);
ProducerBatch batch = new ProducerBatch(new TopicPartition("topic", 1), builder, now);
Header header = new RecordHeader("header-key", "header-value".getBytes());
while (true) {
FutureRecordMetadata future = batch.tryAppend(
now, "hi".getBytes(), "there".getBytes(),
new Header[]{header}, null, now);
if (future == null) {
break;
}
}
Deque<ProducerBatch> batches = batch.split(200);
assertTrue(batches.size() >= 2, "This batch should be split to multiple small batches.");
for (ProducerBatch splitProducerBatch : batches) {
for (RecordBatch splitBatch : splitProducerBatch.records().batches()) {
for (Record record : splitBatch) {
assertTrue(record.headers().length == 1, "Header size should be 1.");
assertTrue(record.headers()[0].key().equals("header-key"), "Header key should be 'header-key'.");
assertTrue(new String(record.headers()[0].value()).equals("header-value"), "Header value should be 'header-value'.");
}
}
}
}
}
@Test
public void testSplitPreservesMagicAndCompressionType() {
for (byte magic : Arrays.asList(MAGIC_VALUE_V0, MAGIC_VALUE_V1, MAGIC_VALUE_V2)) {
for (CompressionType compressionType : CompressionType.values()) {
if (compressionType == CompressionType.NONE && magic < MAGIC_VALUE_V2)
continue;
if (compressionType == CompressionType.ZSTD && magic < MAGIC_VALUE_V2)
continue;
MemoryRecordsBuilder builder = MemoryRecords.builder(ByteBuffer.allocate(1024), magic,
compressionType, TimestampType.CREATE_TIME, 0L);
ProducerBatch batch = new ProducerBatch(new TopicPartition("topic", 1), builder, now);
while (true) {
FutureRecordMetadata future = batch.tryAppend(now, "hi".getBytes(), "there".getBytes(),
Record.EMPTY_HEADERS, null, now);
if (future == null)
break;
}
Deque<ProducerBatch> batches = batch.split(512);
assertTrue(batches.size() >= 2);
for (ProducerBatch splitProducerBatch : batches) {
assertEquals(magic, splitProducerBatch.magic());
assertTrue(splitProducerBatch.isSplitBatch());
for (RecordBatch splitBatch : splitProducerBatch.records().batches()) {
assertEquals(magic, splitBatch.magic());
assertEquals(0L, splitBatch.baseOffset());
assertEquals(compressionType, splitBatch.compressionType());
}
}
}
}
}
/**
* A {@link ProducerBatch} configured using a timestamp preceding its create time is interpreted correctly
* as not expired by {@link ProducerBatch#hasReachedDeliveryTimeout(long, long)}.
*/
@Test
public void testBatchExpiration() {
long deliveryTimeoutMs = 10240;
ProducerBatch batch = new ProducerBatch(new TopicPartition("topic", 1), memoryRecordsBuilder, now);
// Set `now` to 2ms before the create time.
assertFalse(batch.hasReachedDeliveryTimeout(deliveryTimeoutMs, now - 2));
// Set `now` to deliveryTimeoutMs.
assertTrue(batch.hasReachedDeliveryTimeout(deliveryTimeoutMs, now + deliveryTimeoutMs));
}
/**
* A {@link ProducerBatch} configured using a timestamp preceding its create time is interpreted correctly
* * as not expired by {@link ProducerBatch#hasReachedDeliveryTimeout(long, long)}.
*/
@Test
public void testBatchExpirationAfterReenqueue() {
ProducerBatch batch = new ProducerBatch(new TopicPartition("topic", 1), memoryRecordsBuilder, now);
// Set batch.retry = true
batch.reenqueued(now);
// Set `now` to 2ms before the create time.
assertFalse(batch.hasReachedDeliveryTimeout(10240, now - 2L));
}
@Test
public void testShouldNotAttemptAppendOnceRecordsBuilderIsClosedForAppends() {
ProducerBatch batch = new ProducerBatch(new TopicPartition("topic", 1), memoryRecordsBuilder, now);
FutureRecordMetadata result0 = batch.tryAppend(now, null, new byte[10], Record.EMPTY_HEADERS, null, now);
assertNotNull(result0);
assertTrue(memoryRecordsBuilder.hasRoomFor(now, null, new byte[10], Record.EMPTY_HEADERS));
memoryRecordsBuilder.closeForRecordAppends();
assertFalse(memoryRecordsBuilder.hasRoomFor(now, null, new byte[10], Record.EMPTY_HEADERS));
assertNull(batch.tryAppend(now + 1, null, new byte[10], Record.EMPTY_HEADERS, null, now + 1));
}
@Test
public void testCompleteExceptionallyWithRecordErrors() {
int recordCount = 5;
RuntimeException topLevelException = new RuntimeException();
Map<Integer, RuntimeException> recordExceptionMap = new HashMap<>();
recordExceptionMap.put(0, new RuntimeException());
recordExceptionMap.put(3, new RuntimeException());
Function<Integer, RuntimeException> recordExceptions = batchIndex ->
recordExceptionMap.getOrDefault(batchIndex, topLevelException);
testCompleteExceptionally(recordCount, topLevelException, recordExceptions);
}
@Test
public void testCompleteExceptionallyWithNullRecordErrors() {
int recordCount = 5;
RuntimeException topLevelException = new RuntimeException();
assertThrows(NullPointerException.class, () ->
testCompleteExceptionally(recordCount, topLevelException, null));
}
private void testCompleteExceptionally(
int recordCount,
RuntimeException topLevelException,
Function<Integer, RuntimeException> recordExceptions
) {
ProducerBatch batch = new ProducerBatch(
new TopicPartition("topic", 1),
memoryRecordsBuilder,
now
);
List<FutureRecordMetadata> futures = new ArrayList<>(recordCount);
for (int i = 0; i < recordCount; i++) {
futures.add(batch.tryAppend(now, null, new byte[10], Record.EMPTY_HEADERS, null, now));
}
assertEquals(recordCount, batch.recordCount);
batch.completeExceptionally(topLevelException, recordExceptions);
assertTrue(batch.isDone());
for (int i = 0; i < futures.size(); i++) {
FutureRecordMetadata future = futures.get(i);
RuntimeException caughtException = TestUtils.assertFutureThrows(future, RuntimeException.class);
RuntimeException expectedException = recordExceptions.apply(i);
assertEquals(expectedException, caughtException);
}
}
private static class MockCallback implements Callback {
private int invocations = 0;
private RecordMetadata metadata;
private Exception exception;
@Override
public void onCompletion(RecordMetadata metadata, Exception exception) {
invocations++;
this.metadata = metadata;
this.exception = exception;
}
}
}
| |
package uk.ac.ox.zoo.seeg.abraid.mp.common.domain;
import org.hibernate.annotations.*;
import org.joda.time.DateTime;
import javax.persistence.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.util.List;
/**
* Represents a run of the SEEG model.
*
* Copyright (c) 2014 University of Oxford
*/
@NamedQueries({
@NamedQuery(
name = "getModelRunByName",
query = "from ModelRun where name=:name"
),
@NamedQuery(
name = "getLastRequestedModelRun",
query = "from ModelRun " +
"where diseaseGroup.id=:diseaseGroupId " +
"and requestDate = " +
" (select max(requestDate) from ModelRun" +
" where diseaseGroup.id=:diseaseGroupId)"
),
@NamedQuery(
name = "getMostRecentlyRequestedModelRunWhichCompleted",
query = "from ModelRun " +
"where diseaseGroup.id=:diseaseGroupId " +
"and status = 'COMPLETED' " +
"and requestDate =" +
" (select max(requestDate) from ModelRun" +
" where diseaseGroup.id=:diseaseGroupId" +
" and status = 'COMPLETED')"
),
@NamedQuery(
name = "getMostRecentlyFinishedModelRunWhichCompleted",
query = "from ModelRun " +
"where diseaseGroup.id=:diseaseGroupId " +
"and status = 'COMPLETED' " +
"and responseDate =" +
" (select max(responseDate) from ModelRun" +
" where diseaseGroup.id=:diseaseGroupId" +
" and status = 'COMPLETED')"
),
@NamedQuery(
name = "getCompletedModelRunsForDisplay",
query = "select m from ModelRun m " +
"join fetch m.diseaseGroup d " +
"where m.status = 'COMPLETED' " +
"and (d.automaticModelRunsStartDate is null or m.requestDate >= d.automaticModelRunsStartDate)"
),
@NamedQuery(
name = "hasBatchingEverCompleted",
query = "select count(*) from ModelRun " +
"where diseaseGroup.id=:diseaseGroupId " +
"and batchingCompletedDate is not null"
),
@NamedQuery(
name = "getModelRunRequestServersByUsage",
query = "select requestServer from ModelRun " +
"group by requestServer " +
"order by " +
"sum(case(status) when 'IN_PROGRESS' then 1 else 0 end) asc, " +
"sum(case(status) when 'IN_PROGRESS' then 0 else 1 end) asc"
),
@NamedQuery(
name = "getModelRunsForDiseaseGroup",
query = "from ModelRun " +
"where diseaseGroup.id=:diseaseGroupId "
)
})
@Entity
@Table(name = "model_run")
public class ModelRun {
// The model run ID.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
// The model run name, as returned by the ModelWrapper.
@Column
private String name;
// The status of the model run.
@Column
@Enumerated(EnumType.STRING)
private ModelRunStatus status;
// The disease group for the model run.
@ManyToOne
@JoinColumn(name = "disease_group_id", nullable = false)
private DiseaseGroup diseaseGroup;
// Request server.
@Column(name = "request_server")
private String requestServer;
// The date that the model run was requested.
@Column(name = "request_date")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime requestDate;
// The date that the outputs for this model run were received.
@Column(name = "response_date")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime responseDate;
// The output text from the model run (stdout).
@Column(name = "output_text")
private String outputText;
// The error text from the model run (stderr).
@Column(name = "error_text")
private String errorText;
// List of submodel statistics associated with the model run.
@OneToMany(cascade = CascadeType.ALL, mappedBy = "modelRun")
private List<SubmodelStatistic> submodelStatistics;
// List of covariate influences associated with the model run.
@OneToMany(cascade = CascadeType.ALL, mappedBy = "modelRun")
private List<CovariateInfluence> covariateInfluences;
// The start date of this batch of disease occurrences (if relevant).
@Column(name = "batch_start_date")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime batchStartDate;
// The end date of this batch of disease occurrences (if relevant).
@Column(name = "batch_end_date")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime batchEndDate;
// The number of disease occurrences in this batch (if relevant).
@Column(name = "batch_occurrence_count")
private Integer batchOccurrenceCount;
// The date that batching for this model run completed (if relevant).
@Column(name = "batching_completed_date")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime batchingCompletedDate;
// The occurrence date of the earliest associated disease occurrence.
@Column(name = "occurrence_data_range_start_date")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime occurrenceDataRangeStartDate;
// The occurrence date of the latest associated disease occurrence.
@Column(name = "occurrence_data_range_end_date")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime occurrenceDataRangeEndDate;
// List of effect curve covariate influence data points associated with this model run.
@OneToMany(cascade = CascadeType.ALL, mappedBy = "modelRun")
private List<EffectCurveCovariateInfluence> effectCurveCovariateInfluences;
// List of disease occurrences used in this model run.
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "model_run_disease_occurrence",
joinColumns = @JoinColumn(name = "model_run_id"),
inverseJoinColumns = @JoinColumn(name = "disease_occurrence_id"))
@Fetch(FetchMode.SELECT)
private List<DiseaseOccurrence> inputDiseaseOccurrences;
// List of disease extent classes mapped to admin units used in this model run.
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "modelRun")
@Fetch(FetchMode.SELECT)
private List<ModelRunAdminUnitDiseaseExtentClass> inputDiseaseExtent;
public ModelRun() {
}
public ModelRun(int id) {
this.id = id;
}
public ModelRun(String name, DiseaseGroup diseaseGroup, String requestServer, DateTime requestDate,
DateTime occurrenceDataRangeStartDate, DateTime occurrenceDataRangeEndDate) {
this.name = name;
this.status = ModelRunStatus.IN_PROGRESS;
this.requestServer = requestServer;
this.requestDate = requestDate;
this.diseaseGroup = diseaseGroup;
this.occurrenceDataRangeStartDate = occurrenceDataRangeStartDate;
this.occurrenceDataRangeEndDate = occurrenceDataRangeEndDate;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ModelRunStatus getStatus() {
return status;
}
public void setStatus(ModelRunStatus status) {
this.status = status;
}
public int getDiseaseGroupId() {
return diseaseGroup.getId();
}
public DiseaseGroup getDiseaseGroup() {
return diseaseGroup;
}
public void setDiseaseGroup(DiseaseGroup diseaseGroup) {
this.diseaseGroup = diseaseGroup;
}
public String getRequestServer() {
return requestServer;
}
public DateTime getRequestDate() {
return requestDate;
}
public void setRequestDate(DateTime requestDate) {
this.requestDate = requestDate;
}
public DateTime getResponseDate() {
return responseDate;
}
public void setResponseDate(DateTime responseDate) {
this.responseDate = responseDate;
}
public String getOutputText() {
return outputText;
}
public void setOutputText(String outputText) {
this.outputText = outputText;
}
public String getErrorText() {
return errorText;
}
public void setErrorText(String errorText) {
this.errorText = errorText;
}
public List<SubmodelStatistic> getSubmodelStatistics() {
return submodelStatistics;
}
public void setSubmodelStatistics(List<SubmodelStatistic> submodelStatistics) {
this.submodelStatistics = submodelStatistics;
}
public List<CovariateInfluence> getCovariateInfluences() {
return covariateInfluences;
}
public void setCovariateInfluences(List<CovariateInfluence> covariateInfluences) {
this.covariateInfluences = covariateInfluences;
}
public DateTime getBatchStartDate() {
return batchStartDate;
}
public void setBatchStartDate(DateTime batchStartDate) {
this.batchStartDate = batchStartDate;
}
public DateTime getBatchEndDate() {
return batchEndDate;
}
public void setBatchEndDate(DateTime batchEndDate) {
this.batchEndDate = batchEndDate;
}
public Integer getBatchOccurrenceCount() {
return batchOccurrenceCount;
}
public void setBatchOccurrenceCount(Integer batchedOccurrenceCount) {
this.batchOccurrenceCount = batchedOccurrenceCount;
}
public DateTime getBatchingCompletedDate() {
return batchingCompletedDate;
}
public void setBatchingCompletedDate(DateTime batchingCompletedDate) {
this.batchingCompletedDate = batchingCompletedDate;
}
public List<EffectCurveCovariateInfluence> getEffectCurveCovariateInfluences() {
return effectCurveCovariateInfluences;
}
public void setEffectCurveCovariateInfluences(List<EffectCurveCovariateInfluence> effectCurveCovariateInfluences) {
this.effectCurveCovariateInfluences = effectCurveCovariateInfluences;
}
public List<DiseaseOccurrence> getInputDiseaseOccurrences() {
return inputDiseaseOccurrences;
}
public void setInputDiseaseOccurrences(List<DiseaseOccurrence> inputDiseaseOccurrences) {
this.inputDiseaseOccurrences = inputDiseaseOccurrences;
}
public List<ModelRunAdminUnitDiseaseExtentClass> getInputDiseaseExtent() {
return inputDiseaseExtent;
}
public void setInputDiseaseExtent(List<ModelRunAdminUnitDiseaseExtentClass> inputDiseaseExtent) {
this.inputDiseaseExtent = inputDiseaseExtent;
}
public DateTime getOccurrenceDataRangeStartDate() {
return occurrenceDataRangeStartDate;
}
public void setOccurrenceDataRangeStartDate(DateTime occurrenceDataRangeStartDate) {
this.occurrenceDataRangeStartDate = occurrenceDataRangeStartDate;
}
public DateTime getOccurrenceDataRangeEndDate() {
return occurrenceDataRangeEndDate;
}
public void setOccurrenceDataRangeEndDate(DateTime occurrenceDataRangeEndDate) {
this.occurrenceDataRangeEndDate = occurrenceDataRangeEndDate;
}
///COVERAGE:OFF - generated code
///CHECKSTYLE:OFF AvoidInlineConditionalsCheck|LineLengthCheck|MagicNumberCheck|NeedBracesCheck - generated code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ModelRun modelRun = (ModelRun) o;
if (diseaseGroup.getId() != modelRun.diseaseGroup.getId()) return false;
if (batchEndDate != null ? !batchEndDate.equals(modelRun.batchEndDate) : modelRun.batchEndDate != null)
return false;
if (batchOccurrenceCount != null ? !batchOccurrenceCount.equals(modelRun.batchOccurrenceCount) : modelRun.batchOccurrenceCount != null)
return false;
if (batchStartDate != null ? !batchStartDate.equals(modelRun.batchStartDate) : modelRun.batchStartDate != null)
return false;
if (batchingCompletedDate != null ? !batchingCompletedDate.equals(modelRun.batchingCompletedDate) : modelRun.batchingCompletedDate != null)
return false;
if (errorText != null ? !errorText.equals(modelRun.errorText) : modelRun.errorText != null) return false;
if (id != null ? !id.equals(modelRun.id) : modelRun.id != null) return false;
if (name != null ? !name.equals(modelRun.name) : modelRun.name != null) return false;
if (outputText != null ? !outputText.equals(modelRun.outputText) : modelRun.outputText != null) return false;
if (requestDate != null ? !requestDate.equals(modelRun.requestDate) : modelRun.requestDate != null)
return false;
if (requestServer != null ? !requestServer.equals(modelRun.requestServer) : modelRun.requestServer != null)
return false;
if (responseDate != null ? !responseDate.equals(modelRun.responseDate) : modelRun.responseDate != null)
return false;
if (occurrenceDataRangeStartDate != null ? !occurrenceDataRangeStartDate.equals(modelRun.occurrenceDataRangeStartDate) : modelRun.occurrenceDataRangeStartDate != null)
return false;
if (occurrenceDataRangeEndDate != null ? !occurrenceDataRangeEndDate.equals(modelRun.occurrenceDataRangeEndDate) : modelRun.occurrenceDataRangeEndDate != null)
return false;
if (status != modelRun.status) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (status != null ? status.hashCode() : 0);
result = 31 * result + diseaseGroup.getId();
result = 31 * result + (requestServer != null ? requestServer.hashCode() : 0);
result = 31 * result + (requestDate != null ? requestDate.hashCode() : 0);
result = 31 * result + (responseDate != null ? responseDate.hashCode() : 0);
result = 31 * result + (outputText != null ? outputText.hashCode() : 0);
result = 31 * result + (errorText != null ? errorText.hashCode() : 0);
result = 31 * result + (batchStartDate != null ? batchStartDate.hashCode() : 0);
result = 31 * result + (batchEndDate != null ? batchEndDate.hashCode() : 0);
result = 31 * result + (batchOccurrenceCount != null ? batchOccurrenceCount.hashCode() : 0);
result = 31 * result + (batchingCompletedDate != null ? batchingCompletedDate.hashCode() : 0);
result = 31 * result + (occurrenceDataRangeStartDate != null ? occurrenceDataRangeStartDate.hashCode() : 0);
result = 31 * result + (occurrenceDataRangeEndDate != null ? occurrenceDataRangeEndDate.hashCode() : 0);
return result;
}
///CHECKSTYLE:ON
///COVERAGE:ON
}
| |
/*
Copyright 2010 Massachusetts General Hospital
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.sc.probro.servlets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.apache.derby.jdbc.EmbeddedDataSource;
import org.eclipse.jetty.util.log.Log;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.json.JSONWriter;
import org.sc.probro.data.DBObject;
import org.sc.probro.data.RequestObject;
import org.sc.probro.exceptions.BrokerException;
import tdanford.json.schema.SchemaEnv;
public abstract class SkeletonServlet extends HttpServlet {
protected SchemaEnv schemaEnv;
public SkeletonServlet() {
}
public void init() throws ServletException {
super.init();
schemaEnv = new SchemaEnv(new File("docs/json-schemas"));
}
public static final String CONTENT_TYPE_JSON = "application/json";
public static final String CONTENT_TYPE_HTML = "text/html";
public static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
public String contentTypeFromFormat(String format, String... accept) throws BrokerException {
Set<String> acc = new TreeSet<String>();
for(String a : accept) { if(a != null) { acc.add(a); } }
if(acc.size() > 0 && !acc.contains(format)) {
throw new BrokerException(HttpServletResponse.SC_BAD_REQUEST, String.format(
"Unacceptable format '%s'", format));
}
if(format.equals("html")) {
return CONTENT_TYPE_HTML;
} else if (format.equals("json")) {
return CONTENT_TYPE_JSON;
} else if (format.equals("fieldset")) {
return CONTENT_TYPE_HTML;
}
throw new BrokerException(HttpServletResponse.SC_BAD_REQUEST, String.format(
"Unknown format '%s'", format));
}
public JSONObject getLocalJSON(HttpServletRequest req, String path) throws ServletException, IOException, JSONException, BrokerException {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(path);
DummyServletResponse response = new DummyServletResponse();
dispatcher.include(req, response);
if(response.getStatus() != HttpServletResponse.SC_OK) {
throw new BrokerException(response.getStatus(), response.getValue());
}
String value = response.getValue();
Log.info(value);
return new JSONObject(value);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
handleException(response, new BrokerException(HttpServletResponse.SC_FORBIDDEN, "Illegal operation."));
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
handleException(response, new BrokerException(HttpServletResponse.SC_FORBIDDEN, "Illegal operation."));
}
public void handleException(HttpServletResponse response, BrokerException e) throws IOException {
if(e.isFromThrowable()) {
Log.warn(e.getThrowable());
}
Log.warn(e.getDescription());
response.sendError(e.getCode(), e.asJSON().toString());
}
public static void raiseInternalError(HttpServletResponse response, Throwable t) throws IOException {
StringWriter stringer = new StringWriter();
JSONWriter writer = new JSONWriter(stringer);
int errorCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
int httpStatusCode = errorCode;
try {
String msg = t.getMessage();
writer
.object()
.key("error_code").value(errorCode)
.key("error_name").value(BrokerException.ERROR_NAMES.get(errorCode))
.key("error_description").value(msg)
.endObject();
String errorMessage = stringer.toString();
Log.warn(t);
Log.warn(errorMessage);
response.sendError(httpStatusCode, errorMessage);
} catch (JSONException e) {
Log.warn(e);
Log.warn(t);
response.sendError(httpStatusCode, t.getMessage());
}
}
public static void raiseInternalError(HttpServletResponse response, String msg) throws IOException {
raiseException(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
}
public static void raiseException(HttpServletResponse response, int errorCode, String msg) throws IOException {
raiseException(response, errorCode, errorCode, msg);
}
public static void raiseException(HttpServletResponse response, int httpStatusCode, int errorCode, String msg) throws IOException {
StringWriter stringer = new StringWriter();
JSONWriter writer = new JSONWriter(stringer);
try {
writer
.object()
.key("error_code").value(errorCode)
.key("error_name").value("")
.key("error_description").value(msg)
.endObject();
String errorMessage = stringer.toString();
Log.warn(errorMessage);
response.sendError(httpStatusCode, errorMessage);
} catch (JSONException e) {
Log.warn(e);
Log.warn(msg);
response.sendError(httpStatusCode, msg);
}
}
public static String decodeResponseType(HttpServletRequest request, String defaultType) {
return decodeResponseType(decodedParams(request), defaultType);
}
public <T> T getRequiredParam(HttpServletRequest req, String name, Class<T> type) throws BrokerException {
T value = getOptionalParam(req, name, type);
if(value == null) {
throw new BrokerException(HttpServletResponse.SC_BAD_REQUEST,
String.format("Missing required parameter: %s", name));
}
return value;
}
private <T> T decode(String[] undecoded, Class<T> type) throws BrokerException {
try {
String[] decoded = new String[undecoded.length];
for(int i = 0; i < undecoded.length; i++) {
decoded[i] = URLDecoder.decode(undecoded[i], "UTF-8");
}
if(type.isArray()) {
Class inner = type.getComponentType();
int len = undecoded.length;
Object arrayValue = Array.newInstance(inner, len);
for(int i = 0; i < len; i++) {
Array.set(arrayValue, i, decode(new String[] { undecoded[i] }, inner));
}
return (T)arrayValue;
} else if(DBObject.isSubclass(type, String.class)) {
return (T)decoded[0];
} else if (DBObject.isSubclass(type, Integer.class)) {
int parsed = Integer.parseInt(decoded[0]);
return (T)(new Integer(parsed));
} else if (DBObject.isSubclass(type, Double.class)) {
int parsed = Integer.parseInt(decoded[0]);
return (T)(new Integer(parsed));
} else if (DBObject.isSubclass(type, Boolean.class)) {
String lower = decoded[0].toLowerCase();
if(!lower.equals("true") && !lower.equals("1")) {
return (T)(Boolean.FALSE);
} else {
return (T)(Boolean.TRUE);
}
} else if (DBObject.isSubclass(type, JSONObject.class)) {
return (T)(new JSONObject(decoded[0]));
} else {
throw new IllegalArgumentException(type.getCanonicalName());
}
} catch (UnsupportedEncodingException e) {
throw new BrokerException(e);
} catch (JSONException e) {
throw new BrokerException(e);
}
}
public <T> T getOptionalParam(HttpServletRequest req, String name, Class<T> type) throws BrokerException {
String[] undecoded = req.getParameterValues(name);
if(undecoded != null) {
return decode(undecoded, type);
} else {
return null;
}
}
public static String decodeResponseType(Map<String,String[]> params, String defaultType) {
String contentType = defaultType;
if(params.containsKey("format")) {
String format = params.get("format")[0].toLowerCase();
if(format.equals("html")) {
contentType = CONTENT_TYPE_HTML;
} else if (format.equals("json")) {
contentType = CONTENT_TYPE_JSON;
} else {
return null;
}
}
return contentType;
}
public static Map<String,String[]> decodedParams(HttpServletRequest request) {
Map<String,ArrayList<String>> pmap = new LinkedHashMap<String,ArrayList<String>>();
Enumeration paramEnum = request.getParameterNames();
while(paramEnum.hasMoreElements()) {
String paramName = (String)paramEnum.nextElement();
if(!pmap.containsKey(paramName)) { pmap.put(paramName, new ArrayList<String>()); }
try {
String param = URLDecoder.decode(request.getParameter(paramName), "UTF-8");
pmap.get(paramName).add(param);
} catch (UnsupportedEncodingException e) {
Log.warn(e);
throw new IllegalArgumentException(paramName);
}
}
Map<String,String[]> params = new LinkedHashMap<String,String[]>();
for(String key : pmap.keySet()) {
params.put(key, pmap.get(key).toArray(new String[0]));
}
return params;
}
}
class DummyServletResponse implements HttpServletResponse {
private Map<String,Set<String>> headers;
private String encoding;
private String contentType;
private Locale locale;
private int status;
private StringWriter stringer;
private PrintWriter writer;
public DummyServletResponse() {
headers = new LinkedHashMap<String,Set<String>>();
status = 200;
stringer = new StringWriter();
writer = new PrintWriter(stringer);
encoding = "UTF-8";
contentType = "text/html";
locale = Locale.getDefault();
}
private class StringOutputStream extends ServletOutputStream {
public void write(int b) throws IOException {
stringer.append((char)b);
}
}
public String getValue() { return stringer.toString(); }
public int getStatus() { return status; }
public void addCookie(Cookie arg0) {
// do nothing.
}
public void addDateHeader(String key, long time) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
addHeader(key, format.format(new Date(time)));
}
public void addHeader(String key, String value) {
if(!(headers.containsKey(key))) { headers.put(key, new LinkedHashSet<String>()); }
headers.get(key).add(value);
}
public void addIntHeader(String key, int value) {
addHeader(key, String.valueOf(value));
}
public boolean containsHeader(String key) {
return headers.containsKey(key);
}
public String encodeRedirectURL(String url) {
try {
return URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace(System.err);
return null;
}
}
public String encodeRedirectUrl(String url) {
try {
return URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace(System.err);
return null;
}
}
public String encodeURL(String url) {
try {
return URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace(System.err);
return null;
}
}
public String encodeUrl(String url) {
try {
return URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace(System.err);
return null;
}
}
public void sendError(int status) throws IOException {
this.status = status;
writer.close();
writer = null;
}
public void sendError(int status, String msg) throws IOException {
writer.println(msg);
sendError(status);
}
public void sendRedirect(String url) throws IOException {
throw new RuntimeException();
}
public void setDateHeader(String key, long time) {
if(headers.containsKey(key)) { headers.get(key).clear(); }
addDateHeader(key, time);
}
public void setHeader(String key, String value) {
if(headers.containsKey(key)) { headers.get(key).clear(); }
addHeader(key, value);
}
public void setIntHeader(String key, int value) {
if(headers.containsKey(key)) { headers.get(key).clear(); }
addIntHeader(key, value);
}
public void setStatus(int status) {
this.status = status;
}
public void setStatus(int status, String msg) {
this.status = status;
writer.println(msg);
}
public void flushBuffer() throws IOException {
writer.flush();
}
public int getBufferSize() {
return 0;
}
public String getCharacterEncoding() {
return encoding;
}
public String getContentType() {
return contentType;
}
public Locale getLocale() {
return locale;
}
public ServletOutputStream getOutputStream() throws IOException {
return new StringOutputStream();
}
public PrintWriter getWriter() throws IOException {
return writer;
}
public boolean isCommitted() {
return writer == null;
}
public void reset() {
status = 200;
stringer = new StringWriter();
writer = new PrintWriter(stringer);
}
public void resetBuffer() {
// do nothing.
}
public void setBufferSize(int arg0) {
throw new UnsupportedOperationException();
}
public void setCharacterEncoding(String arg0) {
encoding = arg0;
}
public void setContentLength(int len) {
// do nothing.
}
public void setContentType(String arg0) {
contentType = arg0;
}
public void setLocale(Locale arg0) {
locale = arg0;
}
}
| |
/**
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* 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.
*/
package com.portlet.sample.model;
import com.liferay.portal.kernel.bean.AutoEscape;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.model.BaseModel;
import com.liferay.portal.model.CacheModel;
import com.liferay.portal.model.StagedGroupedModel;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portlet.expando.model.ExpandoBridge;
import java.io.Serializable;
import java.util.Date;
/**
* The base model interface for the SampleEntry service. Represents a row in the "Sample_SampleEntry" database table, with each column mapped to a property of this class.
*
* <p>
* This interface and its corresponding implementation {@link com.portlet.sample.model.impl.SampleEntryModelImpl} exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in {@link com.portlet.sample.model.impl.SampleEntryImpl}.
* </p>
*
* @author Scalsysu5
* @see SampleEntry
* @see com.portlet.sample.model.impl.SampleEntryImpl
* @see com.portlet.sample.model.impl.SampleEntryModelImpl
* @generated
*/
public interface SampleEntryModel extends BaseModel<SampleEntry>,
StagedGroupedModel {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this interface directly. All methods that expect a sample entry model instance should use the {@link SampleEntry} interface instead.
*/
/**
* Returns the primary key of this sample entry.
*
* @return the primary key of this sample entry
*/
public long getPrimaryKey();
/**
* Sets the primary key of this sample entry.
*
* @param primaryKey the primary key of this sample entry
*/
public void setPrimaryKey(long primaryKey);
/**
* Returns the uuid of this sample entry.
*
* @return the uuid of this sample entry
*/
@AutoEscape
@Override
public String getUuid();
/**
* Sets the uuid of this sample entry.
*
* @param uuid the uuid of this sample entry
*/
@Override
public void setUuid(String uuid);
/**
* Returns the entry ID of this sample entry.
*
* @return the entry ID of this sample entry
*/
public long getEntryId();
/**
* Sets the entry ID of this sample entry.
*
* @param entryId the entry ID of this sample entry
*/
public void setEntryId(long entryId);
/**
* Returns the company ID of this sample entry.
*
* @return the company ID of this sample entry
*/
@Override
public long getCompanyId();
/**
* Sets the company ID of this sample entry.
*
* @param companyId the company ID of this sample entry
*/
@Override
public void setCompanyId(long companyId);
/**
* Returns the group ID of this sample entry.
*
* @return the group ID of this sample entry
*/
@Override
public long getGroupId();
/**
* Sets the group ID of this sample entry.
*
* @param groupId the group ID of this sample entry
*/
@Override
public void setGroupId(long groupId);
/**
* Returns the user ID of this sample entry.
*
* @return the user ID of this sample entry
*/
@Override
public long getUserId();
/**
* Sets the user ID of this sample entry.
*
* @param userId the user ID of this sample entry
*/
@Override
public void setUserId(long userId);
/**
* Returns the user uuid of this sample entry.
*
* @return the user uuid of this sample entry
* @throws SystemException if a system exception occurred
*/
@Override
public String getUserUuid() throws SystemException;
/**
* Sets the user uuid of this sample entry.
*
* @param userUuid the user uuid of this sample entry
*/
@Override
public void setUserUuid(String userUuid);
/**
* Returns the user name of this sample entry.
*
* @return the user name of this sample entry
*/
@AutoEscape
@Override
public String getUserName();
/**
* Sets the user name of this sample entry.
*
* @param userName the user name of this sample entry
*/
@Override
public void setUserName(String userName);
/**
* Returns the title of this sample entry.
*
* @return the title of this sample entry
*/
@AutoEscape
public String getTitle();
/**
* Sets the title of this sample entry.
*
* @param title the title of this sample entry
*/
public void setTitle(String title);
/**
* Returns the content of this sample entry.
*
* @return the content of this sample entry
*/
@AutoEscape
public String getContent();
/**
* Sets the content of this sample entry.
*
* @param content the content of this sample entry
*/
public void setContent(String content);
/**
* Returns the create date of this sample entry.
*
* @return the create date of this sample entry
*/
@Override
public Date getCreateDate();
/**
* Sets the create date of this sample entry.
*
* @param createDate the create date of this sample entry
*/
@Override
public void setCreateDate(Date createDate);
/**
* Returns the modified date of this sample entry.
*
* @return the modified date of this sample entry
*/
@Override
public Date getModifiedDate();
/**
* Sets the modified date of this sample entry.
*
* @param modifiedDate the modified date of this sample entry
*/
@Override
public void setModifiedDate(Date modifiedDate);
/**
* Returns the status of this sample entry.
*
* @return the status of this sample entry
*/
public boolean getStatus();
/**
* Returns <code>true</code> if this sample entry is status.
*
* @return <code>true</code> if this sample entry is status; <code>false</code> otherwise
*/
public boolean isStatus();
/**
* Sets whether this sample entry is status.
*
* @param status the status of this sample entry
*/
public void setStatus(boolean status);
@Override
public boolean isNew();
@Override
public void setNew(boolean n);
@Override
public boolean isCachedModel();
@Override
public void setCachedModel(boolean cachedModel);
@Override
public boolean isEscapedModel();
@Override
public Serializable getPrimaryKeyObj();
@Override
public void setPrimaryKeyObj(Serializable primaryKeyObj);
@Override
public ExpandoBridge getExpandoBridge();
@Override
public void setExpandoBridgeAttributes(BaseModel<?> baseModel);
@Override
public void setExpandoBridgeAttributes(ExpandoBridge expandoBridge);
@Override
public void setExpandoBridgeAttributes(ServiceContext serviceContext);
@Override
public Object clone();
@Override
public int compareTo(SampleEntry sampleEntry);
@Override
public int hashCode();
@Override
public CacheModel<SampleEntry> toCacheModel();
@Override
public SampleEntry toEscapedModel();
@Override
public SampleEntry toUnescapedModel();
@Override
public String toString();
@Override
public String toXmlString();
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.cluster.health;
import com.carrotsearch.hppc.cursors.IntObjectCursor;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import org.elasticsearch.Version;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.health.TransportClusterHealthAction;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.ActionTestUtils;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RecoverySource;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.RoutingTableGenerator;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.UnassignedInfo;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.collect.ImmutableOpenIntMap;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.indices.TestIndexNameExpressionResolver;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.gateway.TestGatewayAllocator;
import org.elasticsearch.test.transport.CapturingTransport;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import static org.elasticsearch.test.ClusterServiceUtils.createClusterService;
import static org.elasticsearch.test.ClusterServiceUtils.setState;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
public class ClusterStateHealthTests extends ESTestCase {
private static ThreadPool threadPool;
private ClusterService clusterService;
private TransportService transportService;
private IndexNameExpressionResolver indexNameExpressionResolver;
@BeforeClass
public static void setupThreadPool() {
threadPool = new TestThreadPool("ClusterStateHealthTests");
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
clusterService = createClusterService(threadPool);
CapturingTransport transport = new CapturingTransport();
transportService = transport.createTransportService(clusterService.getSettings(), threadPool,
TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> clusterService.localNode(), null, Collections.emptySet());
transportService.start();
transportService.acceptIncomingRequests();
indexNameExpressionResolver = TestIndexNameExpressionResolver.newInstance(threadPool.getThreadContext());
}
@After
public void tearDown() throws Exception {
super.tearDown();
clusterService.close();
transportService.close();
}
@AfterClass
public static void terminateThreadPool() {
ThreadPool.terminate(threadPool, 30, TimeUnit.SECONDS);
threadPool = null;
}
public void testClusterHealthWaitsForClusterStateApplication() throws InterruptedException, ExecutionException {
final CountDownLatch applyLatch = new CountDownLatch(1);
final CountDownLatch listenerCalled = new CountDownLatch(1);
setState(clusterService, ClusterState.builder(clusterService.state())
.nodes(DiscoveryNodes.builder(clusterService.state().nodes()).masterNodeId(null)).build());
clusterService.addStateApplier(event -> {
listenerCalled.countDown();
try {
applyLatch.await();
} catch (InterruptedException e) {
logger.debug("interrupted", e);
}
});
logger.info("--> submit task to restore master");
ClusterState currentState = clusterService.getClusterApplierService().state();
clusterService.getClusterApplierService().onNewClusterState("restore master",
() -> ClusterState.builder(currentState)
.nodes(DiscoveryNodes.builder(currentState.nodes()).masterNodeId(currentState.nodes().getLocalNodeId())).build(),
(source, e) -> {});
logger.info("--> waiting for listener to be called and cluster state being blocked");
listenerCalled.await();
TransportClusterHealthAction action = new TransportClusterHealthAction(transportService,
clusterService, threadPool, new ActionFilters(new HashSet<>()), indexNameExpressionResolver,
new AllocationService(null, new TestGatewayAllocator(), null, null, null));
PlainActionFuture<ClusterHealthResponse> listener = new PlainActionFuture<>();
ActionTestUtils.execute(action, null, new ClusterHealthRequest().waitForGreenStatus(), listener);
assertFalse(listener.isDone());
logger.info("--> realising task to restore master");
applyLatch.countDown();
listener.get();
}
public void testClusterHealth() throws IOException {
RoutingTableGenerator routingTableGenerator = new RoutingTableGenerator();
RoutingTableGenerator.ShardCounter counter = new RoutingTableGenerator.ShardCounter();
RoutingTable.Builder routingTable = RoutingTable.builder();
Metadata.Builder metadata = Metadata.builder();
for (int i = randomInt(4); i >= 0; i--) {
int numberOfShards = randomInt(3) + 1;
int numberOfReplicas = randomInt(4);
IndexMetadata indexMetadata = IndexMetadata
.builder("test_" + Integer.toString(i))
.settings(settings(Version.CURRENT))
.numberOfShards(numberOfShards)
.numberOfReplicas(numberOfReplicas)
.build();
IndexRoutingTable indexRoutingTable = routingTableGenerator.genIndexRoutingTable(indexMetadata, counter);
metadata.put(indexMetadata, true);
routingTable.add(indexRoutingTable);
}
ClusterState clusterState = ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY))
.metadata(metadata)
.routingTable(routingTable.build())
.build();
String[] concreteIndices = indexNameExpressionResolver.concreteIndexNames(
clusterState, IndicesOptions.strictExpand(), (String[]) null
);
ClusterStateHealth clusterStateHealth = new ClusterStateHealth(clusterState, concreteIndices);
logger.info("cluster status: {}, expected {}", clusterStateHealth.getStatus(), counter.status());
clusterStateHealth = maybeSerialize(clusterStateHealth);
assertClusterHealth(clusterStateHealth, counter);
}
public void testClusterHealthOnIndexCreation() {
final String indexName = "test-idx";
final String[] indices = new String[] { indexName };
final List<ClusterState> clusterStates = simulateIndexCreationStates(indexName, false);
for (int i = 0; i < clusterStates.size(); i++) {
// make sure cluster health is always YELLOW, up until the last state where it should be GREEN
final ClusterState clusterState = clusterStates.get(i);
final ClusterStateHealth health = new ClusterStateHealth(clusterState, indices);
if (i < clusterStates.size() - 1) {
assertThat(health.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
} else {
assertThat(health.getStatus(), equalTo(ClusterHealthStatus.GREEN));
}
}
}
public void testClusterHealthOnIndexCreationWithFailedAllocations() {
final String indexName = "test-idx";
final String[] indices = new String[] { indexName };
final List<ClusterState> clusterStates = simulateIndexCreationStates(indexName, true);
for (int i = 0; i < clusterStates.size(); i++) {
// make sure cluster health is YELLOW up until the final cluster state, which contains primary shard
// failed allocations that should make the cluster health RED
final ClusterState clusterState = clusterStates.get(i);
final ClusterStateHealth health = new ClusterStateHealth(clusterState, indices);
if (i < clusterStates.size() - 1) {
assertThat(health.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
} else {
assertThat(health.getStatus(), equalTo(ClusterHealthStatus.RED));
}
}
}
public void testClusterHealthOnClusterRecovery() {
final String indexName = "test-idx";
final String[] indices = new String[] { indexName };
final List<ClusterState> clusterStates = simulateClusterRecoveryStates(indexName, false, false);
for (int i = 0; i < clusterStates.size(); i++) {
// make sure cluster health is YELLOW up until the final cluster state, when it turns GREEN
final ClusterState clusterState = clusterStates.get(i);
final ClusterStateHealth health = new ClusterStateHealth(clusterState, indices);
if (i < clusterStates.size() - 1) {
assertThat(health.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
} else {
assertThat(health.getStatus(), equalTo(ClusterHealthStatus.GREEN));
}
}
}
public void testClusterHealthOnClusterRecoveryWithFailures() {
final String indexName = "test-idx";
final String[] indices = new String[] { indexName };
final List<ClusterState> clusterStates = simulateClusterRecoveryStates(indexName, false, true);
for (int i = 0; i < clusterStates.size(); i++) {
// make sure cluster health is YELLOW up until the final cluster state, which contains primary shard
// failed allocations that should make the cluster health RED
final ClusterState clusterState = clusterStates.get(i);
final ClusterStateHealth health = new ClusterStateHealth(clusterState, indices);
if (i < clusterStates.size() - 1) {
assertThat(health.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
} else {
assertThat(health.getStatus(), equalTo(ClusterHealthStatus.RED));
}
}
}
public void testClusterHealthOnClusterRecoveryWithPreviousAllocationIds() {
final String indexName = "test-idx";
final String[] indices = new String[] { indexName };
final List<ClusterState> clusterStates = simulateClusterRecoveryStates(indexName, true, false);
for (int i = 0; i < clusterStates.size(); i++) {
// because there were previous allocation ids, we should be RED until the primaries are started,
// then move to YELLOW, and the last state should be GREEN when all shards have been started
final ClusterState clusterState = clusterStates.get(i);
final ClusterStateHealth health = new ClusterStateHealth(clusterState, indices);
if (i < clusterStates.size() - 1) {
// if the inactive primaries are due solely to recovery (not failed allocation or previously being allocated),
// then cluster health is YELLOW, otherwise RED
if (primaryInactiveDueToRecovery(indexName, clusterState)) {
assertThat(health.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
} else {
assertThat(health.getStatus(), equalTo(ClusterHealthStatus.RED));
}
} else {
assertThat(health.getStatus(), equalTo(ClusterHealthStatus.GREEN));
}
}
}
public void testClusterHealthOnClusterRecoveryWithPreviousAllocationIdsAndAllocationFailures() {
final String indexName = "test-idx";
final String[] indices = new String[] { indexName };
for (final ClusterState clusterState : simulateClusterRecoveryStates(indexName, true, true)) {
final ClusterStateHealth health = new ClusterStateHealth(clusterState, indices);
// if the inactive primaries are due solely to recovery (not failed allocation or previously being allocated)
// then cluster health is YELLOW, otherwise RED
if (primaryInactiveDueToRecovery(indexName, clusterState)) {
assertThat("clusterState is:\n" + clusterState, health.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
} else {
assertThat("clusterState is:\n" + clusterState, health.getStatus(), equalTo(ClusterHealthStatus.RED));
}
}
}
ClusterStateHealth maybeSerialize(ClusterStateHealth clusterStateHealth) throws IOException {
if (randomBoolean()) {
BytesStreamOutput out = new BytesStreamOutput();
clusterStateHealth.writeTo(out);
StreamInput in = out.bytes().streamInput();
clusterStateHealth = new ClusterStateHealth(in);
}
return clusterStateHealth;
}
private List<ClusterState> simulateIndexCreationStates(final String indexName, final boolean withPrimaryAllocationFailures) {
final int numberOfShards = randomIntBetween(1, 5);
final int numberOfReplicas = randomIntBetween(1, numberOfShards);
// initial index creation and new routing table info
final IndexMetadata indexMetadata = IndexMetadata.builder(indexName)
.settings(settings(Version.CURRENT)
.put(IndexMetadata.SETTING_INDEX_UUID, UUIDs.randomBase64UUID()))
.numberOfShards(numberOfShards)
.numberOfReplicas(numberOfReplicas)
.build();
final Metadata metadata = Metadata.builder().put(indexMetadata, true).build();
final RoutingTable routingTable = RoutingTable.builder().addAsNew(indexMetadata).build();
ClusterState clusterState = ClusterState.builder(new ClusterName("test_cluster"))
.metadata(metadata)
.routingTable(routingTable)
.build();
return generateClusterStates(clusterState, indexName, numberOfReplicas, withPrimaryAllocationFailures);
}
private List<ClusterState> simulateClusterRecoveryStates(final String indexName,
final boolean withPreviousAllocationIds,
final boolean withPrimaryAllocationFailures) {
final int numberOfShards = randomIntBetween(1, 5);
final int numberOfReplicas = randomIntBetween(1, numberOfShards);
// initial index creation and new routing table info
IndexMetadata indexMetadata = IndexMetadata.builder(indexName)
.settings(settings(Version.CURRENT)
.put(IndexMetadata.SETTING_INDEX_UUID, UUIDs.randomBase64UUID()))
.numberOfShards(numberOfShards)
.numberOfReplicas(numberOfReplicas)
.state(IndexMetadata.State.OPEN)
.build();
if (withPreviousAllocationIds) {
final IndexMetadata.Builder idxMetaWithAllocationIds = IndexMetadata.builder(indexMetadata);
boolean atLeastOne = false;
for (int i = 0; i < numberOfShards; i++) {
if (atLeastOne == false || randomBoolean()) {
idxMetaWithAllocationIds.putInSyncAllocationIds(i, Sets.newHashSet(UUIDs.randomBase64UUID()));
atLeastOne = true;
}
}
indexMetadata = idxMetaWithAllocationIds.build();
}
final Metadata metadata = Metadata.builder().put(indexMetadata, true).build();
final RoutingTable routingTable = RoutingTable.builder().addAsRecovery(indexMetadata).build();
ClusterState clusterState = ClusterState.builder(new ClusterName("test_cluster"))
.metadata(metadata)
.routingTable(routingTable)
.build();
return generateClusterStates(clusterState, indexName, numberOfReplicas, withPrimaryAllocationFailures);
}
private List<ClusterState> generateClusterStates(final ClusterState originalClusterState,
final String indexName,
final int numberOfReplicas,
final boolean withPrimaryAllocationFailures) {
// generate random node ids
final Set<String> nodeIds = new HashSet<>();
final int numNodes = randomIntBetween(numberOfReplicas + 1, 10);
for (int i = 0; i < numNodes; i++) {
nodeIds.add(randomAlphaOfLength(8));
}
final List<ClusterState> clusterStates = new ArrayList<>();
clusterStates.add(originalClusterState);
ClusterState clusterState = originalClusterState;
// initialize primaries
RoutingTable routingTable = originalClusterState.routingTable();
IndexRoutingTable indexRoutingTable = routingTable.index(indexName);
IndexRoutingTable.Builder newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
for (final ObjectCursor<IndexShardRoutingTable> shardEntry : indexRoutingTable.getShards().values()) {
final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
if (shardRouting.primary()) {
newIndexRoutingTable.addShard(
shardRouting.initialize(randomFrom(nodeIds), null, shardRouting.getExpectedShardSize())
);
} else {
newIndexRoutingTable.addShard(shardRouting);
}
}
}
routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
clusterStates.add(clusterState);
// some primaries started
indexRoutingTable = routingTable.index(indexName);
newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
ImmutableOpenIntMap.Builder<Set<String>> allocationIds = ImmutableOpenIntMap.<Set<String>>builder();
for (final ObjectCursor<IndexShardRoutingTable> shardEntry : indexRoutingTable.getShards().values()) {
final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
if (shardRouting.primary() && randomBoolean()) {
final ShardRouting newShardRouting = shardRouting.moveToStarted();
allocationIds.fPut(newShardRouting.getId(), Sets.newHashSet(newShardRouting.allocationId().getId()));
newIndexRoutingTable.addShard(newShardRouting);
} else {
newIndexRoutingTable.addShard(shardRouting);
}
}
}
routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
IndexMetadata.Builder idxMetaBuilder = IndexMetadata.builder(clusterState.metadata().index(indexName));
for (final IntObjectCursor<Set<String>> entry : allocationIds.build()) {
idxMetaBuilder.putInSyncAllocationIds(entry.key, entry.value);
}
Metadata.Builder metadataBuilder = Metadata.builder(clusterState.metadata()).put(idxMetaBuilder);
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).metadata(metadataBuilder).build();
clusterStates.add(clusterState);
if (withPrimaryAllocationFailures) {
boolean alreadyFailedPrimary = false;
// some primaries failed to allocate
indexRoutingTable = routingTable.index(indexName);
newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
for (final ObjectCursor<IndexShardRoutingTable> shardEntry : indexRoutingTable.getShards().values()) {
final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
if (shardRouting.primary() && (shardRouting.started() == false || alreadyFailedPrimary == false)) {
newIndexRoutingTable.addShard(shardRouting.moveToUnassigned(
new UnassignedInfo(UnassignedInfo.Reason.ALLOCATION_FAILED, "unlucky shard")));
alreadyFailedPrimary = true;
} else {
newIndexRoutingTable.addShard(shardRouting);
}
}
}
routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
clusterStates.add(ClusterState.builder(clusterState).routingTable(routingTable).build());
return clusterStates;
}
// all primaries started
indexRoutingTable = routingTable.index(indexName);
newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
allocationIds = ImmutableOpenIntMap.<Set<String>>builder();
for (final ObjectCursor<IndexShardRoutingTable> shardEntry : indexRoutingTable.getShards().values()) {
final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
if (shardRouting.primary() && shardRouting.started() == false) {
final ShardRouting newShardRouting = shardRouting.moveToStarted();
allocationIds.fPut(newShardRouting.getId(), Sets.newHashSet(newShardRouting.allocationId().getId()));
newIndexRoutingTable.addShard(newShardRouting);
} else {
newIndexRoutingTable.addShard(shardRouting);
}
}
}
routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
idxMetaBuilder = IndexMetadata.builder(clusterState.metadata().index(indexName));
for (final IntObjectCursor<Set<String>> entry : allocationIds.build()) {
idxMetaBuilder.putInSyncAllocationIds(entry.key, entry.value);
}
metadataBuilder = Metadata.builder(clusterState.metadata()).put(idxMetaBuilder);
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).metadata(metadataBuilder).build();
clusterStates.add(clusterState);
// initialize replicas
indexRoutingTable = routingTable.index(indexName);
newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
for (final ObjectCursor<IndexShardRoutingTable> shardEntry : indexRoutingTable.getShards().values()) {
final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
final String primaryNodeId = shardRoutingTable.primaryShard().currentNodeId();
Set<String> allocatedNodes = new HashSet<>();
allocatedNodes.add(primaryNodeId);
for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
if (shardRouting.primary() == false) {
// give the replica a different node id than the primary
String replicaNodeId = randomFrom(Sets.difference(nodeIds, allocatedNodes));
newIndexRoutingTable.addShard(shardRouting.initialize(replicaNodeId, null, shardRouting.getExpectedShardSize()));
allocatedNodes.add(replicaNodeId);
} else {
newIndexRoutingTable.addShard(shardRouting);
}
}
}
routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
clusterStates.add(ClusterState.builder(clusterState).routingTable(routingTable).build());
// some replicas started
indexRoutingTable = routingTable.index(indexName);
newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
for (final ObjectCursor<IndexShardRoutingTable> shardEntry : indexRoutingTable.getShards().values()) {
final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
if (shardRouting.primary() == false && randomBoolean()) {
newIndexRoutingTable.addShard(shardRouting.moveToStarted());
} else {
newIndexRoutingTable.addShard(shardRouting);
}
}
}
routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
clusterStates.add(ClusterState.builder(clusterState).routingTable(routingTable).build());
// all replicas started
boolean replicaStateChanged = false;
indexRoutingTable = routingTable.index(indexName);
newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
for (final ObjectCursor<IndexShardRoutingTable> shardEntry : indexRoutingTable.getShards().values()) {
final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
if (shardRouting.primary() == false && shardRouting.started() == false) {
newIndexRoutingTable.addShard(shardRouting.moveToStarted());
replicaStateChanged = true;
} else {
newIndexRoutingTable.addShard(shardRouting);
}
}
}
// all of the replicas may have moved to started in the previous phase already
if (replicaStateChanged) {
routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
clusterStates.add(ClusterState.builder(clusterState).routingTable(routingTable).build());
}
return clusterStates;
}
// returns true if the inactive primaries in the index are only due to cluster recovery
// (not because of allocation of existing shard or previously having allocation ids assigned)
private boolean primaryInactiveDueToRecovery(final String indexName, final ClusterState clusterState) {
for (final IntObjectCursor<IndexShardRoutingTable> shardRouting : clusterState.routingTable().index(indexName).shards()) {
final ShardRouting primaryShard = shardRouting.value.primaryShard();
if (primaryShard.active() == false) {
if (clusterState.metadata().index(indexName).inSyncAllocationIds(shardRouting.key).isEmpty() == false) {
return false;
}
if (primaryShard.recoverySource() != null &&
primaryShard.recoverySource().getType() == RecoverySource.Type.EXISTING_STORE) {
return false;
}
if (primaryShard.unassignedInfo().getNumFailedAllocations() > 0) {
return false;
}
if (primaryShard.unassignedInfo().getLastAllocationStatus() == UnassignedInfo.AllocationStatus.DECIDERS_NO) {
return false;
}
}
}
return true;
}
private void assertClusterHealth(ClusterStateHealth clusterStateHealth, RoutingTableGenerator.ShardCounter counter) {
assertThat(clusterStateHealth.getStatus(), equalTo(counter.status()));
assertThat(clusterStateHealth.getActiveShards(), equalTo(counter.active));
assertThat(clusterStateHealth.getActivePrimaryShards(), equalTo(counter.primaryActive));
assertThat(clusterStateHealth.getInitializingShards(), equalTo(counter.initializing));
assertThat(clusterStateHealth.getRelocatingShards(), equalTo(counter.relocating));
assertThat(clusterStateHealth.getUnassignedShards(), equalTo(counter.unassigned));
assertThat(clusterStateHealth.getActiveShardsPercent(), is(allOf(greaterThanOrEqualTo(0.0), lessThanOrEqualTo(100.0))));
}
}
| |
/*
* The MIT License
*
* Copyright (c) <2010> <Bruno P. Kinoshita>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package br.eti.kinoshita.testlinkjavaapi.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import br.eti.kinoshita.testlinkjavaapi.constants.ActionOnDuplicate;
import br.eti.kinoshita.testlinkjavaapi.constants.ExecutionStatus;
import br.eti.kinoshita.testlinkjavaapi.constants.ExecutionType;
import br.eti.kinoshita.testlinkjavaapi.constants.TestImportance;
/**
* @author Bruno P. Kinoshita - http://www.kinoshita.eti.br
* @since 1.9.0-1
*/
public class TestCase implements Serializable {
private static final long serialVersionUID = 1191213146080628314L;
private Integer id;
private String name;
private Integer testSuiteId;
private Integer testProjectId;
private String authorLogin;
private String summary;
private List<TestCaseStep> steps;
private String preconditions;
private TestImportance testImportance;
private ExecutionType executionType;
private Integer executionOrder;
private Integer order;
private Integer internalId;
private String fullExternalId;
private Boolean checkDuplicatedName;
private ActionOnDuplicate actionOnDuplicatedName;
private Integer versionId;
private Integer version;
private Integer parentId;
private List<CustomField> customFields;
private ExecutionStatus executionStatus;
private Platform platform;
private Integer featureId;
/**
*
*/
public TestCase() {
super();
this.steps = new ArrayList<TestCaseStep>();
this.customFields = new ArrayList<CustomField>();
}
/**
* Constructor with args.
*
* @param id
* @param name
* @param testSuiteId
* @param testProjectId
* @param authorLogin
* @param summary
* @param steps
* @param preconditions
* @param testImportance
* @param executionType
* @param executionOrder
* @param order
* @param internalId
* @param fullExternalId
* @param checkDuplicatedName
* @param actionOnDuplicatedName
* @param versionId
* @param version
* @param parentId
* @param customFields
* @param executionStatus
* @param plataform
* @param featureId
*/
public TestCase(Integer id, String name, Integer testSuiteId, Integer testProjectId, String authorLogin,
String summary, List<TestCaseStep> steps, String preconditions, TestImportance testImportance,
ExecutionType executionType, Integer executionOrder, Integer order, Integer internalId,
String fullExternalId, Boolean checkDuplicatedName, ActionOnDuplicate actionOnDuplicatedName,
Integer versionId, Integer version, Integer parentId, List<CustomField> customFields,
ExecutionStatus executionStatus, Platform platform, Integer featureId) {
super();
this.id = id;
this.name = name;
this.testSuiteId = testSuiteId;
this.testProjectId = testProjectId;
this.authorLogin = authorLogin;
this.summary = summary;
this.steps = steps;
this.preconditions = preconditions;
this.testImportance = testImportance;
this.executionType = executionType;
this.executionOrder = executionOrder;
this.order = order;
this.internalId = internalId;
this.fullExternalId = fullExternalId;
this.checkDuplicatedName = checkDuplicatedName;
this.actionOnDuplicatedName = actionOnDuplicatedName;
this.versionId = versionId;
this.version = version;
this.parentId = parentId;
this.customFields = customFields;
this.executionStatus = executionStatus;
this.platform = platform;
this.featureId = featureId;
}
/**
* @return the parentId
*/
public Integer getParentId() {
return parentId;
}
/**
* @param parentId the parentId to set
*/
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
/**
* @return the versionId
*/
public Integer getVersionId() {
return versionId;
}
/**
* @param versionId the versionId to set
*/
public void setVersionId(Integer versionId) {
this.versionId = versionId;
}
/**
* @return the version
*/
public Integer getVersion() {
return version;
}
/**
* @param version the version to set
*/
public void setVersion(Integer version) {
this.version = version;
}
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the testSuiteId
*/
public Integer getTestSuiteId() {
return testSuiteId;
}
/**
* @param testSuiteId the testSuiteId to set
*/
public void setTestSuiteId(Integer testSuiteId) {
this.testSuiteId = testSuiteId;
}
/**
* @return the testProjectId
*/
public Integer getTestProjectId() {
return testProjectId;
}
/**
* @param testProjectId the testProjectId to set
*/
public void setTestProjectId(Integer testProjectId) {
this.testProjectId = testProjectId;
}
/**
* @return the authorLogin
*/
public String getAuthorLogin() {
return authorLogin;
}
/**
* @param authorLogin the authorLogin to set
*/
public void setAuthorLogin(String authorLogin) {
this.authorLogin = authorLogin;
}
/**
* @return the summary
*/
public String getSummary() {
return summary;
}
/**
* @param summary the summary to set
*/
public void setSummary(String summary) {
this.summary = summary;
}
/**
* @return the steps
*/
public List<TestCaseStep> getSteps() {
return steps;
}
/**
* @param steps the steps to set
*/
public void setSteps(List<TestCaseStep> steps) {
this.steps = steps;
}
/**
* @return the preconditions
*/
public String getPreconditions() {
return preconditions;
}
/**
* @param preconditions the preconditions to set
*/
public void setPreconditions(String preconditions) {
this.preconditions = preconditions;
}
/**
* @return the testImportance
*/
public TestImportance getTestImportance() {
return testImportance;
}
/**
* @param testImportance the testImportance to set
*/
public void setTestImportance(TestImportance testImportance) {
this.testImportance = testImportance;
}
/**
* @return the executionOrder
*/
public Integer getExecutionOrder() {
return executionOrder;
}
/**
* @param executionOrder the executionOrder to set
*/
public void setExecutionOrder(Integer executionOrder) {
this.executionOrder = executionOrder;
}
/**
* @return the executionType
*/
public ExecutionType getExecutionType() {
return executionType;
}
/**
* @param executionType the executionType to set
*/
public void setExecutionType(ExecutionType executionType) {
this.executionType = executionType;
}
/**
* @return the order
*/
public Integer getOrder() {
return order;
}
/**
* @param order the order to set
*/
public void setOrder(Integer order) {
this.order = order;
}
/**
* @return the internalId
*/
public Integer getInternalId() {
return internalId;
}
/**
* @param internalId the internalId to set
*/
public void setInternalId(Integer internalId) {
this.internalId = internalId;
}
/**
*
* @return the full external Id, composed by the prefix + externalId
*/
public String getFullExternalId() {
return fullExternalId;
}
/**
*
* @param fullExternalId the full externalId to set
*/
public void setFullExternalId(String fullExternalId) {
this.fullExternalId = fullExternalId;
}
/**
* @return the checkDuplicatedName
*/
public Boolean getCheckDuplicatedName() {
return checkDuplicatedName;
}
/**
* @param checkDuplicatedName the checkDuplicatedName to set
*/
public void setCheckDuplicatedName(Boolean checkDuplicatedName) {
this.checkDuplicatedName = checkDuplicatedName;
}
/**
* @return the actionOnDuplicatedName
*/
public ActionOnDuplicate getActionOnDuplicatedName() {
return actionOnDuplicatedName;
}
/**
* @param actionOnDuplicatedName the actionOnDuplicatedName to set
*/
public void setActionOnDuplicatedName(ActionOnDuplicate actionOnDuplicatedName) {
this.actionOnDuplicatedName = actionOnDuplicatedName;
}
/**
* @return the customFields
*/
public List<CustomField> getCustomFields() {
return customFields;
}
/**
* @param customFields the customFields to set
*/
public void setCustomFields(List<CustomField> customFields) {
this.customFields = customFields;
}
/**
* @return the executionStatus
*/
public ExecutionStatus getExecutionStatus() {
return executionStatus;
}
/**
* @param executionStatus the executionStatus to set
*/
public void setExecutionStatus(ExecutionStatus executionStatus) {
this.executionStatus = executionStatus;
}
/**
* @return the platform
*/
public Platform getPlatform() {
return platform;
}
/**
* @param platform the platform to set
*/
public void setPlatform(Platform platform) {
this.platform = platform;
}
/**
* @return the featureId
*/
public Integer getFeatureId() {
return featureId;
}
/**
* @param featureId the featureId to set
*/
public void setFeatureId(Integer featureId) {
this.featureId = featureId;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "TestCase [id=" + id + ", name=" + name + ", testSuiteId=" + testSuiteId + ", testProjectId="
+ testProjectId + ", authorLogin=" + authorLogin + ", summary=" + summary + ", steps=" + steps
+ ", preconditions=" + preconditions + ", testImportance=" + testImportance + ", executionType="
+ executionType + ", executionOrder=" + executionOrder + ", order=" + order + ", internalId="
+ internalId + ", fullExternalId=" + fullExternalId + ", checkDuplicatedName=" + checkDuplicatedName
+ ", actionOnDuplicatedName=" + actionOnDuplicatedName + ", versionId=" + versionId + ", version="
+ version + ", parentId=" + parentId + ", customFields=" + customFields + ", executionStatus="
+ executionStatus + ", platform=" + platform + ", featureId=" + featureId + "]";
}
}
| |
package virtualbuddy;
import java.net.*;
import java.util.LinkedList;
import java.io.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.*;
import org.tudelft.affectbutton.AffectButton;
import org.tudelft.affectbutton.PADFaceMapped;
import jcmdline.StringFormatHelper;
public class DemoRobin extends JApplet {
private static final long serialVersionUID = 1L;
// gui components
JTextArea conversation, input;
JScrollPane conversationScroll;
JPanel userInput;
JPanel abPanel;
Embodiment faceRobin;
TextInputPanel tip;
JButton send;
AffectButton ab;
JButton activateAB, croButton;
Font normalFont;
String userName;
//UserSpeechActs uSA;
LinkedList<SpeechAct> currentResponseOptions;
String abActionCommand;
Topic currentTopic;
LinkedList<String> incidentFacts;
UtteranceParser uParser;
SequenceParser sParser;
private volatile boolean waitForUser;
private volatile boolean emotionalResponseInProgress;
private volatile boolean conversationInProgress;
int facialExpressionDelay;
EmotionalResponse feltEmotion;
private boolean affectButtonUsed;
Logger log;
// condition
boolean verbal;
boolean nonverbal;
public void init(){
log = new Logger();
userName = "Tom";
//setCondition( getParameter("foo") );
setCondition("4");
//uSA = new UserSpeechActs();
currentResponseOptions = new LinkedList<SpeechAct>();
uParser = new UtteranceParser();
sParser = new SequenceParser();
waitForUser = false;
emotionalResponseInProgress = false;
affectButtonUsed = false;
conversationInProgress = true;
facialExpressionDelay = 2500;
feltEmotion = new EmotionalResponse();
incidentFacts = new LinkedList<String>();
//incidentFacts.add("conversation(conversation_objective,tips)");
//incidentFacts.add("incident(cf_conversation_partner,dont_know)");
//incidentFacts.add("incident(tell_story_to,teacher)");
currentTopic = new TopicHello();
//currentTopic = new TopicConversationObjective();
//currentTopic = new TopicAdvice(incidentFacts);
//currentTopic = new TopicBye();
//currentTopic = new TopicCopingFuture("qa(tell_story_to)");
//currentTopic = new TopicCopingFuture("coping_options");
//Execute a job on the event-dispatching thread:
//creating this applet's GUI.
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
log.log("error, createGUI didn't successfully complete");
}
//addMessageToChat("------------------------------------------------------");
//addMessageToChat("Empathic virtual buddy demo");
//addMessageToChat("For demonstration purposes only!");
//addMessageToChat("Please refer to http://ict1.tbm.tudelft.nl/empathicbuddy/ for instructions");
//addMessageToChat("------------------------------------------------------");
//addMessageToChat("------------------------------------------------------");
//addMessageToChat("Empathische virtuele buddy demo");
//addMessageToChat("Alleen ter demonstratie!");
//addMessageToChat("Kijk op http://ict1.tbm.tudelft.nl/empathicbuddy/ voor gebruiksinstructies");
//addMessageToChat("------------------------------------------------------");
Thread thread = new Thread(){
public void run(){
while(conversationInProgress){
if(!waitForUser && !emotionalResponseInProgress){
String ns = null;
synchronized(incidentFacts){
currentTopic = currentTopic.getCurrentTopic(incidentFacts);
if(currentTopic != null ){
//addMessageToChat("topic: "+currentTopic.getName());
ns = currentTopic.nextSequence(incidentFacts);
} else {
conversationInProgress = false;
}
}
//addMessageToChat("about to do sequence: "+ns);
if(ns != null) doSequence( ns, null );
}
}
// gesprek is afgelopen
//addMessageToChat("[End of conversation]");
addMessageToChat("[Het gesprek is afgelopen]");
//waitTime(1500);
//addMessageToChat("Je mag nu verder gaan met het invullen van de vragenlijst.");
// TODO log naar db schrijven
//System.out.println(log.getLog());
}
};
thread.start();
}
private void setCondition(String parameter) {
nonverbal = false;
verbal = false;
if( parameter.equals("2") ){
nonverbal = true;
} else if( parameter.equals("3") ){
verbal = true;
} else if( parameter.equals("4") ){
verbal = true;
nonverbal = true;
}
}
public void doSequence(String sequenceName, Fact2Emotion em){
int utteranceLength = 0;
if(em!=null){
// delay for changing expression
waitTime(1000);
if(em.getMirror()){
// mirror emotion
faceRobin.setExpression(em.getEmotionLabel(), em.getEmotionIntensity());
} else {
//addMessageToChat("Emotional response: "+em.getEmotionLabel());
waitTime(1500);
faceRobin.addEmotion(em.getEmotionLabel(), em.getSteps());
}
} else {
// decay emotion - one step to content - med
if( ! (faceRobin.getExpressionLabel().equals("content") && faceRobin.getExpressionIntensity().equals("med")) ){
faceRobin.addEmotion("content", 1);
//addMessageToChat("Decay emotion");
}
}
log.log("robin,"+faceRobin.getExpressionLabel()+","+faceRobin.getExpressionIntensity());
if(sequenceName != null){
// LinkedList van speech acts maken op basis van naam
LinkedList<SpeechAct2> sequenceSpeechActs = sParser.getSpeechActs(sequenceName);
//waitForUser = false;
// Loop over linked list speech acts
for( SpeechAct2 s : sequenceSpeechActs ){
// find nlUtterance
String from = s.getFrom();
if(from.equals("robin")){
Utterance2 t = uParser.findUtterance(from, s.getContents());
utteranceLength = t.getUtterance().length();
//addMessageToChat("Lengte bericht: "+(t.getUtterance().length()));
// delay for typing
waitTime((int) ((utteranceLength/5.0) * 200));
// stuur bericht naar chat interface
//addMessageToChat(uParser.capitalize(from)+" zegt: "+t.getUtterance());
addMessageToChat(uParser.capitalize(from)+" says: "+t.getUtterance());
log.log("robin,"+t.getCode());
// Display response options
LinkedList<SpeechAct> options = new LinkedList<SpeechAct>();
//addMessageToChat("sequenceName");
// wachten met volgende bericht (leestijd) als het een lang bericht is
if(utteranceLength > 200){
waitTime(7000);
} else if(utteranceLength > 100 ){
waitTime(3500);
} else {
waitTime(2000);
}
// AffectButton nodig?
if(sequenceName.equals("qa(emotional_state)") && !affectButtonUsed){
abActionCommand = t.getCode();
ab.setActionCommand(abActionCommand);
showAffectButton();
} else if(!t.getResponseOptions().isEmpty()) {
for (String ro : t.getResponseOptions()) {
SpeechAct sa = new SpeechAct("inform", "user", ro, uParser);
options.add(sa);
}
changeResponseOptions(options);
}
} else {
waitForUser = true;
//addMessageToChat("Wait for user!");
}
}
}
// aanhouden facial expression na verbale uiting (leestijd)
if(em!=null){
waitTime(facialExpressionDelay);
}
}
public String getLog(){
return log.getLog().toString();
}
private void println(String msg) {
addMessageToChat(msg);
}
public void addMessageToChat(String message){
message = message.replace("***", "\n");
message = message.replace("NAAM", userName);
message = message.replace("HYVESURL", "http://www.hyves.nl/help/feedback/?feedbackMode= email&answerId=96&categoryId=142&category= Privacy%2C+pesten+en+spam");
message = StringFormatHelper.getHelper().formatHangingIndent(message, 5, 60);
conversation.append(message+ "\n\n");
conversation.setCaretPosition(conversation.getText().length() - 1);
}
public String getUserName(){
return userName;
}
//public LinkedList<SpeechAct> getUserSpeechActs(){
// return uSA.getUserSpeechActs();
//}
// Bij klikken op de knop wordt er een Speech Act toegevoegd aan de UserSpeechActs
public class UserInputButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e){
String ac = e.getActionCommand();
Fact2Emotion em;
if(ac.equals(abActionCommand)){
// AffectButton in response to question
affectButtonUsed = true;
double p = ab.getP();
double a = ab.getA();
double d = ab.getD();
//String message = getUserName()+" uses AffectButton (P:"+p+" A:"+a+" D:"+d+")";
//String message = getUserName()+" klikt op de AffectButton";
String message = getUserName()+" clicks the AffectButton";
addMessageToChat(message);
SpeechAct sa = new SpeechAct(p, a, d, ac);
log.log("user,"+sa.getCode());
synchronized(incidentFacts){
incidentFacts.add(sa.getCode());
}
//addMessageToChat("about to hide affectbutton");
hideAffectButton();
//addMessageToChat("affectbutton hidden");
em = new Fact2Emotion(p,a,d,faceRobin);
} else {
// Response option
SpeechAct sa = null;
for(SpeechAct option:currentResponseOptions){
if(ac.equals(option.getCode())){
sa = option;
//addMessageToChat(sa.toString());
}
}
if(sa != null ){
synchronized(incidentFacts){
incidentFacts.add(sa.getCode());
}
//String message = getUserName()+" zegt: "+sa.getNLUtterance();
String message = getUserName()+" says: "+sa.getNLUtterance();
addMessageToChat(message);
log.log("user,"+sa.getCode());
}
em = feltEmotion.getEmotionalResponse(ac);
// Remove response options
changeResponseOptions(new LinkedList<SpeechAct>());
}
if(em != null){
emotionalResponseInProgress = true;
EmotionalResponseThread t = new EmotionalResponseThread(em);
t.start();
}
waitForUser = false;
//addMessageToChat("Wait for user is klaar");
}
} // einde class UserInputButtonListener
public class EmotionalResponseThread extends Thread {
Fact2Emotion emotion;
public EmotionalResponseThread(Fact2Emotion em){
emotion = em;
}
public void run(){
//addMessageToChat("Emotionele reactie voor: "+userMessage);
//addMessageToChat("about to do sequence (+emotion): "+em.getSequenceName());
while(waitForUser){
waitTime(10);
}
if(verbal && nonverbal){
doSequence(emotion.getSequenceName(), emotion);
} else if(verbal){
doSequence(emotion.getSequenceName(), null);
} else if(nonverbal){
doSequence(null, emotion);
}
emotionalResponseInProgress = false;
}
} // einde class EmotionalResponseThread
/**
* GUI
*/
public void changeResponseOptions(LinkedList<SpeechAct> options) {
remove(userInput);
GridBagConstraints c;
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
//c.gridheight = 2;
//c.insets = new Insets(10, 5, 0, 5);
c.anchor = GridBagConstraints.FIRST_LINE_START;
userInput = generateResponseOptions(options);
add(userInput, c);
validate();
repaint();
}
public JPanel generateResponseOptions(LinkedList<SpeechAct> options){
JPanel responsePanel = new JPanel();
JButton b;
responsePanel.setBackground(Color.white);
responsePanel.setLayout(new GridLayout(0,1));
currentResponseOptions.clear();
for(SpeechAct option : options){
currentResponseOptions.add(option);
b = newButton(option.getNLUtterance(), option.getCode());
responsePanel.add(b);
}
return responsePanel;
}
public JButton newButton(String name, String actionCommand){
name = name.replace("NAAM", userName);
JButton button = new JButton(name);
button.setFont(normalFont);
button.setHorizontalAlignment(SwingConstants.LEFT);
button.setActionCommand(actionCommand);
button.addActionListener(new UserInputButtonListener());
return button;
}
private void createGUI() {
//Border blackline = BorderFactory.createLineBorder(Color.gray);
Border innerBorder = BorderFactory.createEmptyBorder(10, 10, 10, 10);
//Border compound = BorderFactory.createCompoundBorder(blackline, innerBorder);
Border blueline = BorderFactory.createLineBorder(new Color(68, 131, 208), 2);
Border greenline = BorderFactory.createLineBorder(new Color(228, 210, 103), 2);
//backgroundColor = new Color(250,255,191);
Color backgroundColor = Color.white;
//setSize(800, 700);
setSize(800,600);
Container content = getContentPane();
content.setBackground(backgroundColor);
//((JComponent) content).setBorder(greenline);
// set default font
normalFont = new Font("Serif", Font.PLAIN, 18);
faceRobin = new Embodiment(normalFont);
// message history
conversation = new JTextArea(12, 33);
conversation.setFont(normalFont);
conversation.setEditable(false);
conversation.setOpaque(false);
conversation.setWrapStyleWord(true);
conversation.setLineWrap(true);
conversation.setBorder(innerBorder);
conversationScroll = new JScrollPane(conversation, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
ab = new AffectButton(new PADFaceMapped(0,0,1));
ab.setActionCommand("ab");
ab.addActionListener(new UserInputButtonListener());
ab.setBounds(0, 0, 150, 150);
//ab.setVisible(false);
// For some reason the AffectButton doesn't have a size, unless it is added to its own panel
abPanel = new JPanel();
abPanel.setLayout(null);
abPanel.setPreferredSize(new Dimension(200, 200));
abPanel.setBackground(Color.white);
abPanel.add(ab);
JPanel spacer = new JPanel();
spacer.setLayout(null);
spacer.setPreferredSize(new Dimension(200, 200));
spacer.setBackground(Color.white);
// Response options
userInput = generateResponseOptions(new LinkedList<SpeechAct>());
userInput.setPreferredSize(new Dimension(150, 200));
content.setLayout(new GridBagLayout());
GridBagConstraints c;
// Plaatje buddy
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10, 10, 10, 5);
c.anchor = GridBagConstraints.FIRST_LINE_START;
content.add(faceRobin.getExpression(), c);
// message history
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(10, 5, 10, 5);
//c.gridwidth = 2;
//c.gridheight = 2;
c.anchor = GridBagConstraints.FIRST_LINE_START;
content.add(conversationScroll, c);
// spacer
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(10, 10, 10, 5);
c.anchor = GridBagConstraints.CENTER;
content.add(spacer, c);
// response options
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
//c.gridheight = 2;
//c.insets = new Insets(10, 5, 0, 5);
c.anchor = GridBagConstraints.FIRST_LINE_START;
content.add(userInput, c);
}
public void showAffectButton(){
remove(userInput);
GridBagConstraints c;
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
//c.gridheight = 2;
//c.insets = new Insets(10, 5, 0, 5);
c.anchor = GridBagConstraints.FIRST_LINE_START;
add(abPanel, c);
validate();
repaint();
}
public void hideAffectButton(){
remove(abPanel);
changeResponseOptions(new LinkedList<SpeechAct>());
}
/**
* Other methods
*/
public void waitTime(int delay){
// delay for changing expression
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setEmotionalResponseInProgress(boolean e) {
emotionalResponseInProgress = e;
}
}
| |
/*
* Copyright 2014 Google 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 com.google.plus.samples.haikuplus;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.CredentialRefreshListener;
import com.google.api.client.auth.oauth2.TokenErrorResponse;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.auth.oauth2.TokenResponseException;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.repackaged.com.google.common.annotations.VisibleForTesting;
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.model.PeopleFeed;
import com.google.api.services.plus.model.Person;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.Expose;
import com.google.plus.samples.haikuplus.model.DataStore;
import com.google.plus.samples.haikuplus.model.Jsonifiable;
import com.google.plus.samples.haikuplus.model.User;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Provides the logic for authenticating a user before continuing with the intended API call.
*
* @author joannasmith@google.com (Joanna Smith)
* @author ldenison@google.com (Lee Denison)
*/
public class Authenticate {
/**
* Session ID cookie name.
*/
static final String SESSION_ID_NAME = "HaikuSessionId";
/**
* Local storage of sessions and the user associated with each session. This unbounded mapping
* lives here, rather than the datastore, for simplicity in the sample as it is used in
* authenticating a user. For a production app, you would want a more reliable and
* maintainable storage solution.
*/
static Map<String, User> authenticatedSessions = new ConcurrentHashMap<String, User>();
/**
* Special keyword for making Google API calls on behalf of the authenticated user.
*/
private static final String ME = "me";
/**
* Special keyword for making Google API calls for the visible collection.GoogleClientSecrets
*/
private static final String VISIBLE = "visible";
/**
* Client secret configuration. This is read from the client_secrets.json file.
*
*/
private static GoogleClientSecrets clientSecrets;
/**
* This is the default redirect URI for web applications and tells the browser to return
* to the parent of the dialog. This value is used to validate a redirect URI provided in
* the X-Oauth-Code header. It is important to validate all supplied redirect URIs, as
* explained in the OAuth specification (http://tools.ietf.org/html/rfc6749#section-10.6).
*/
private static final String WEB_REDIRECT_URI = "postmessage";
/**
* This is the default redirect URI for installed applications and is the equivalent of
* a "null" value. This value is used to validate a redirect URI provided in
* the X-Oauth-Code header. It is important to validate all supplied redirect URIs, as
* explained in the OAuth specification (http://tools.ietf.org/html/rfc6749#section-10.6).
*/
private static final String INSTALLED_REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
/**
* Authentication identifier for an ID token.
*/
private static final String BEARER_SCHEME = "Bearer";
/**
* Authentication identifier for an authorization code.
*/
private static final String CODE_SCHEME = "X-OAuth-Code";
/**
* Name of the authorization code authorization header.
*/
private static final String CODE_AUTHORIZATION_HEADER_NAME = CODE_SCHEME;
/**
* Regular expression for identifying an authorization code header.
*/
private static final Pattern CODE_REGEX =
Pattern.compile("\\s*(\\S+)(?:\\s+redirect_uri='(.+)')?");
/**
* Name of the Bearer authorization header.
*/
private static final String BEARER_AUTHORIZATION_HEADER_NAME = "Authorization";
/**
* Regular expression for identifying an authorization ID token header.
*/
private static final Pattern BEARER_REGEX =
Pattern.compile("\\s*" + BEARER_SCHEME + "\\s+(\\S+)");
/**
* For use in verifying access tokens, as the client library currently does not provide
* a validation method for access tokens.
*/
private static final String TOKEN_INFO_ENDPOINT =
"https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s";
/**
* Regular expression for identifying client IDs from the same API Console project.
*/
private static final Pattern CLIENT_ID_REGEX = Pattern.compile("(^\\d+).*");
/**
* For use in building authentication response headers.
*/
private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
/**
* For use in building authentication response headers.
*/
private static final String GOOGLE_REALM =
"realm=\"https://www.google.com/accounts/AuthSubRequest\"";
/**
* Verifier object for use in validating ID tokens.
*/
private final GoogleIdTokenVerifier idTokenVerifier;
/**
* Repository pattern to wrap a static/final call for testing purposes.
*/
private final GoogleIdTokenRepository tokenRepo;
/**
* Used to construct and run a background thread for the people.list API call.
*/
private ExecutorService executor;
/**
* Logger for the Authenticate class.
*/
Logger logger = Logger.getLogger("Authenticate");
Authenticate(ExecutorService executor) {
this(new GoogleIdTokenVerifier(HaikuPlus.TRANSPORT, HaikuPlus.JSON_FACTORY),
new GoogleIdTokenRepository(),
executor);
}
@VisibleForTesting
Authenticate(GoogleIdTokenVerifier verifier, GoogleIdTokenRepository repo,
ExecutorService executor) {
idTokenVerifier = verifier;
tokenRepo = repo;
this.executor = executor;
initClientSecretInfo();
}
/**
* This is the Client ID that you generated in the API Console. It is stored
* in the client secret JSON file.
* The clientSecrets value is initialized at construction time, and is never null.
*/
public static String getClientId() {
return clientSecrets.getWeb().getClientId();
}
/**
* This is the Client secret that you generated in the API Console. It is stored
* in the client secret JSON file.
* The clientSecrets value is initialized at construction time, and is never null.
*/
public static String getClientSecret() {
return clientSecrets.getWeb().getClientSecret();
}
/**
* Authenticates a user by associating this session with a user based on a provided ID token
* {@code idAuth} and by associating a user with valid credentials based on a provided
* authorization code {@code codeAuth}. Once a request has been authenticated, calls
* chain.doFilter() to invoke the associated servlet and complete the API call made by
* the client.
*
* @return the User object indicating the authenticated and authorized Haiku+ user, or null
* to indicate that additional authentication information is needed.
*/
User requireAuthentication(String sessionId, HttpServletRequest request,
HttpServletResponse response) {
User user = null;
String googleUserId = null;
GoogleCredential credential = null;
// Isolate the authorization piece of the relevant headers, if they exist.
String codeAuth =
parseAuthorizationHeader(request, CODE_AUTHORIZATION_HEADER_NAME, CODE_REGEX, 1);
String idAuth =
parseAuthorizationHeader(request, BEARER_AUTHORIZATION_HEADER_NAME, BEARER_REGEX, 1);
String redirectUri =
parseAuthorizationHeader(request, CODE_AUTHORIZATION_HEADER_NAME, CODE_REGEX, 2);
// Must be one of these two values, correct to INSTALLED otherwise.
if (!WEB_REDIRECT_URI.equals(redirectUri)) {
redirectUri = INSTALLED_REDIRECT_URI;
}
if (codeAuth != null) {
// The request supplied an authorization header, so we process the credentials before
// attempting to service the request. If the credentials are valid, googleUserId will
// be assigned the Google ID of the authorized user, and the credentials will be
// stored in the DataStore.
GoogleTokenResponse tokenResponse =
exchangeAuthorizationCode(codeAuth, redirectUri, response);
if (tokenResponse != null) {
credential =
createCredential(tokenResponse.getAccessToken(), tokenResponse.getRefreshToken());
// An ID Token is a cryptographically-signed JSON object encoded in base 64.
// Normally, it is critical that you validate an ID Token before you use it,
// but since you are communicating directly with Google over an
// intermediary-free HTTPS channel and using your Client Secret to
// authenticate yourself to Google, you can be confident that the token you
// receive really comes from Google and is valid. If your server passes the
// ID Token to other components of your app, it is extremely important that
// the other components validate the token before using it.
googleUserId = parseIdToken(tokenResponse, response);
if (googleUserId != null) {
DataStore.updateCredentialWithGoogleId(googleUserId, credential);
}
}
}
if (idAuth != null) {
// The request supplied a bearer token, so we verify the token before attempting to
// service the request. The bearer token may be either an ID token or an access token for
// requests from iOS devices, which currently cannot use authorization codes.
// If the verification succeeds, googleUserId will be assigned the Google ID of the
// authenticated user.
// If more than one authentication header is provided, and this verification fails, the
// authorization credentials will be stored above, but googleUserId will be reset to null
// to indicate that the currently signed in user is not authenticated.
googleUserId = verifyBearerToken(idAuth, response);
}
if (googleUserId != null) {
// If a valid authentication header was supplied, or if valid credentials were associated
// with this user, then we check to see if that same user is associated with the current
// session before attempting to service the request. If not, a new session is created
// and associated with the authenticated/authorized user.
user = authenticateSession(sessionId, googleUserId, request);
}
if (user == null) {
// If the authentication or authorization step failed, then we were unable to retrieve
// the associated Haiku+ user, so we check to see if there is a user associated with the
// current session and attempt to service the request, based off of stored user credentials.
User sessionUser = authenticatedSessions.get(sessionId);
if (sessionUser == null) {
// The HTTP session does not have an authenticated user ID in it (or we were unable
// to find the corresponding user in our database) and the request did not supply
// an authorization header, so we return a request to authenticate with a bearer
// token.
// IETF RFC6750 defines how we should indicate that the user agent needs to
// authenticate with a bearer token.
logger.log(Level.INFO, "The session does not have an authenticated user,"
+ " so return a 401 and request a bearer token.");
response.addHeader(WWW_AUTHENTICATE, BEARER_SCHEME + " " + GOOGLE_REALM);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return null;
} else {
googleUserId = sessionUser.getGoogleUserId();
}
}
// At this point, we have the correct user associated with the current authenticated session,
// so we attempt to service the request.
try {
// We check the profile on every call to ensure that the cached Google user data is fresh,
// since the Date check is cheap.
return updateUserCache(googleUserId);
} catch (DataStore.CredentialNotFoundException e) {
logger.log(Level.INFO,
"No credentials for Google user:" + googleUserId + "; request auth code with 401");
// There are no associated credentials for the user, so we return a request to
// authenticate with an authorization code.
// There is no standard way for our server to request a new authorization code from
// our client, so we use an non-standard scheme (X-OAuth-Code) to indicate that we
// need a new refresh token.
response.addHeader(CODE_SCHEME, GOOGLE_REALM);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return null;
} catch (InvalidAccessTokenException e) {
logger.log(Level.INFO,
"Access token expired for user" + googleUserId + "; request auth code with 401");
// The refresh token was invalidated, so we return a request to authenticate with
// an authorization code.
// There is no standard way for our server to request a new authorization code from
// our client, so we use an non-standard scheme (X-OAuth-Code) to indicate that we
// need a new refresh token.
response.addHeader(CODE_SCHEME, GOOGLE_REALM);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return null;
} catch (IOException e) {
logger.log(Level.INFO, "Something went wrong processing the request; return 500", e);
// Likely a temporary network error
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return null;
}
}
/**
* Exchanges an authorization code for Google credentials, including an access and a refresh
* token. If the exchange fails, an IOException is raised, and a 400 is specified in the
* HTTP response, indicating that the authorization code was invalid. If the exchange succeeds,
* a GoogleTokenResponse object is returned. Otherwise, null is returned to indicate a failure.
*/
private GoogleTokenResponse exchangeAuthorizationCode(String authorization, String redirectUri,
HttpServletResponse response) {
try {
// Upgrade the authorization code into an access and refresh token.
return createTokenExchanger(authorization, redirectUri).execute();
} catch (TokenResponseException e) {
//Failed to exchange authorization code.
logger.log(Level.INFO, "Failed to exchange auth code; return 400", e);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return null;
} catch (IOException e) {
logger.log(Level.INFO, "Failed to exchange auth code; return 400", e);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
}
/**
* Parses an ID token from a TokenResponse. If the parse fails, a 500 is specified and
* null is returned, indicating that the ID token Google returned with a Credential object
* is invalid. Otherwise, the Google user ID associated with the token is returned.
*/
private String parseIdToken(GoogleTokenResponse tokenResponse, HttpServletResponse response) {
try {
// You can read the Google user ID in the ID token.
GoogleIdToken idToken = tokenResponse.parseIdToken();
return getGoogleIdFromIdToken(idToken);
} catch (IOException e) {
logger.log(Level.INFO, "Failed to parse ID token from tokenResponse object; return 500", e);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return null;
}
}
/**
* Retrieves the Google ID of a user out of an ID token.
*/
private String getGoogleIdFromIdToken(GoogleIdToken idToken) {
Payload payload = idToken.getPayload();
return payload.getSubject();
}
/**
* Create a GoogleCredential from the provided access and refresh tokens.
*/
@VisibleForTesting
GoogleCredential createCredential(String accessToken, String refreshToken) {
return new GoogleCredential.Builder()
.setJsonFactory(HaikuPlus.JSON_FACTORY)
.setTransport(HaikuPlus.TRANSPORT)
.setClientSecrets(clientSecrets)
.addRefreshListener(new InvalidateRefreshTokenOnExpired())
.build()
.setAccessToken(accessToken)
.setRefreshToken(refreshToken);
}
/**
* Validates the provided bearer token as an ID token. If the validation fails, an attempt
* is made to validate the token as an access token. If the verifier fails, a 403 is
* specified in the HTTP response, whereas an IOException thrown by a Google server indicates
* that the token was invalid and a 400 is specified in the response.
*
* @return Google ID of the user the token is associated with; null if the token is invalid.
*/
private String verifyBearerToken(String authorization, HttpServletResponse response) {
String googlePlusId = null;
GoogleIdToken idToken = null;
try {
// Attempt to parse the bearer token as an ID token. If this fails, pass the bearer token
// along to be parsed as an access token.
idToken = tokenRepo.parse(HaikuPlus.JSON_FACTORY, authorization);
} catch (IllegalArgumentException e) {
logger.log(Level.INFO,
"Failed to verify bearer token as ID token; attempting to verify as access token");
return verifyAccessToken(authorization, response);
} catch (IOException e) {
logger.log(Level.INFO, "Failed to parse ID token; return 400", e);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
try {
// Verify the ID token before retrieving the Google ID of the user associated with the token
if (idTokenVerifier.verify(idToken)
&& tokenRepo.verifyAudience(idToken, Collections.singletonList(getClientId()))) {
googlePlusId = getGoogleIdFromIdToken(idToken);
return googlePlusId;
} else {
return null;
}
} catch (IOException e) {
logger.log(Level.INFO, "Failed to verify ID token", e);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return null;
} catch (GeneralSecurityException e) {
logger.log(Level.INFO, "Failed to verify ID token", e);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return null;
}
}
/**
* Validates the provided bearer token against the OAuth TokenInfo endpoint. If the HTTP request
* fails, a 500 is specified in the response. If the token is invalid, a 400 is specified.
* If the token is valid, a credential object is created and stored against the Google user
* ID and that ID is returned. Otherwise, null is returned to indicate the failure.
*/
@VisibleForTesting
String verifyAccessToken(String authorization, HttpServletResponse response) {
TokenInfoResponse tokenResponse = null;
try {
// Form a request to the token info endpoint, since the Java client library does not
// provide a method to validate an access token.
HttpResponse httpResponse = HaikuPlus.TRANSPORT.createRequestFactory()
.buildGetRequest(new GenericUrl(String.format(TOKEN_INFO_ENDPOINT, authorization)))
.execute();
// Read the response into a TokenInfoResponse object.
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
getContent(httpResponse.getContent(), out);
tokenResponse = tokenRepo.fromJson(out);
} catch (JsonParseException e) {
logger.log(Level.INFO, "Unable to parse token info HTTP response; return 400", e);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return null;
} finally {
out.close();
}
} catch (HttpResponseException e) {
logger.log(Level.INFO, "Token info HTTP request failed with error code", e);
// The response code from the GET request was an error code.
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return null;
} catch (IOException e) {
logger.log(Level.INFO, "Response from token info HTTP request was malformed", e);
// The response from the GET request was malformed or could not be read.
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return null;
}
String googlePlusId = null;
// The client ID may not be a perfect match if the request came from an installed
// application. Rather than verifying equality of the client IDs, we need to verify
// that both client IDs belong to the same project. The easiest way to do this is to
// compare the initial digit grouping from the client IDs, as this first part will
// always be the project ID.
Matcher tokenMatcher = CLIENT_ID_REGEX.matcher(tokenResponse.audience);
Matcher clientIdMatcher = CLIENT_ID_REGEX.matcher(getClientId());
boolean tokenMatch = tokenMatcher.matches();
boolean clientIdMatch = clientIdMatcher.matches();
String tokenProject = "";
String clientIdProject = "";
if (tokenMatch && clientIdMatch) {
tokenProject = tokenMatcher.group(1);
clientIdProject = clientIdMatcher.group(1);
}
if (tokenResponse.expiresIn != null && tokenProject.equals(clientIdProject)) {
googlePlusId = tokenResponse.userId;
DataStore.updateCredentialWithGoogleId(googlePlusId, createCredential(authorization, null));
}
return googlePlusId;
}
/**
* Checks if the current session is associated with the specified Google user. If so, the
* user object is returned. If not, the current session is discarded and a new one is
* created and associated with the user object of the specified Google user.
*/
private User authenticateSession(String sessionId, String googleUserId,
HttpServletRequest request) {
User user = authenticatedSessions.get(sessionId);
if (user != null) {
if (googleUserId.equals(user.getGoogleUserId())) {
// We have the correct user associated with the current session, so return the user object.
return user;
} else {
// The user IDs don't match, so we disassociate the current session from the user.
authenticatedSessions.remove(sessionId);
}
}
user = DataStore.loadUserWithGoogleId(googleUserId);
if (user == null) {
// Create a new user
user = new User();
user.setGoogleUserId(googleUserId);
DataStore.updateUser(user);
}
// Invalidate the current session and authenticate the user for the new session.
if (!request.getSession().isNew()) {
request.getSession().invalidate();
}
String newSessionId = request.getSession().getId();
authenticatedSessions.put(newSessionId, user);
return user;
}
/**
* @return the authorization component of the header associated with the provided name based
* on the provided regex pattern; null if the component does not exist
*/
private String parseAuthorizationHeader(HttpServletRequest request, String headerName,
Pattern pattern, int groupNumber) {
String header = request.getHeader(headerName);
String auth = null;
if (header != null) {
Matcher authMatcher = pattern.matcher(header);
boolean authMatch = authMatcher.matches();
if (authMatch) {
if (authMatcher.groupCount() >= groupNumber) {
auth = authMatcher.group(groupNumber);
}
}
}
return auth;
}
/**
* Updates the user's Google data in the Haiku+ DataStore, if the cached data is more
* than one day old.
*
* @param googleId the current authenticated user
* @return the User object stored in the DataStore
*/
private User updateUserCache(String googleId)
throws DataStore.CredentialNotFoundException, IOException {
User profile = DataStore.loadUserWithGoogleId(googleId);
if (profile == null) {
profile = new User();
profile.setGoogleUserId(googleId);
}
// If the user's profile was updated less than one day ago, do nothing.
if (!profile.isDataFresh()) {
fetchGoogleUserData(profile);
DataStore.updateUser(profile);
}
return profile;
}
/**
* Performs the Google+ people.get API call to refresh a user's cached Google data. This data
* should never be stored permanently and should be refreshed regularly (i.e. if it is older
* than 24 hours).
*
* @param user the current authenticated user
*/
private void fetchGoogleUserData(User user)
throws DataStore.CredentialNotFoundException, IOException {
GoogleCredential credential = DataStore.requireCredentialWithGoogleId(user.getGoogleUserId());
Plus service = createPlusApiClient(credential);
Person person = service.people().get(ME).execute();
// A Person resource contains many things, but in this sample, we chose to focus on the
// Google ID, the display name, and the URLs of the user's profile and profile photo.
user.setGoogleUserId(person.getId());
user.setGoogleDisplayName(person.getDisplayName());
user.setGooglePhotoUrl(person.getImage().getUrl());
user.setGoogleProfileUrl(person.getUrl());
user.setLastUpdated();
// Now we call a separate method to perform the people.list API call to retrieve the
// user's circles via a background thread.
fetchGooglePeopleList(user, service);
}
/**
* Performs the Google+ people.list API call to refresh a user's social graph, based on
* the connections provided in the user's circles. If a circled connection is also a
* Haiku+ user, that connection is stored in the DataStore. Otherwise, the connection is
* ignored, as the data is refreshed every 24 hours, and new Haiku+ users can be easily
* discovered. Some developers prefer to store the connection and update the edge when
* new users join the app, but we recommend short caching times instead.
*
* @param user the current authenticated user
* @param service the Google+ API client object that can make API calls
*/
private void fetchGooglePeopleList(final User user, final Plus service) {
executor.submit(new Runnable() {
@Override
public void run() {
List<String> circledHaikuUsers = new ArrayList<String>();
try {
PeopleFeed people = service.people().list(ME, VISIBLE).execute();
String personGoogleId = null;
User haikuUser = null;
for (Person person : people.getItems()) {
personGoogleId = person.getId();
haikuUser = DataStore.loadUserWithGoogleId(personGoogleId);
if (haikuUser != null) {
// The Google+ connection is also a Haiku+ user, so we need to create an edge.
// To do this, we add their Haiku+ ID to a list to pass to the DataStore, where the
// edges will be created. If the Google+ connection is not a Haiku+ user, we do not
// create an edge yet. Since we update the user's edges every time the data is older
// than 24 hours, we will be able to catch new Haiku+ users easily.
circledHaikuUsers.add(haikuUser.getUserId());
}
personGoogleId = null;
haikuUser = null;
}
// Pass the compiled list to the DataStore to create a DirectedUserToUserEdge mapping
// the single-directional relationship from the authenticated user to each Haiku+ user
// that has been circled by the authenticated user.
DataStore.updateCirclesForUser(user.getUserId(), circledHaikuUsers);
} catch (DataStore.UserNotFoundException e) {
logger.log(Level.INFO, "people.list failed due to user not existing in DataStore", e);
// Somehow, the DataStore has an inconsistency and the sourceUser is not a Haiku+
// user. This should never happen, but if it does, we simply do not write the edges.
} catch (InvalidAccessTokenException e) {
logger.log(Level.INFO, "people.list failed due to invalid token", e);
// The token may have expired between the people.get and people.list calls. In this case,
// we cannot communicate with the client, and so we simply leave the user with no edges.
}
catch (IOException e) {
logger.log(Level.INFO, "people.list call failed for unknown reason", e);
// The API call may have failed or there may be a network error. In this case,
// we cannot communicate with the client, and so we simply leave the user with no edges.
}
}
});
}
/**
* Reads the content of an InputStream.
*
* @param inputStream the InputStream to be read.
* @param outputStream the content of the InputStream as a ByteArrayOutputStream.
*/
private static void getContent(InputStream inputStream, ByteArrayOutputStream outputStream)
throws IOException {
// Read the response into a buffered stream
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
int readChar;
while ((readChar = reader.read()) != -1) {
outputStream.write(readChar);
}
} finally {
reader.close();
}
}
/**
* Creates a token verifier object using the client secret values provided by client_secrets.json.
*
* @param authorization the authorization code to be exchanged for a bearer token once verified
* @param redirectUri the redirect URI to be used for token exchange, from the APIs console.
*/
@VisibleForTesting
GoogleAuthorizationCodeTokenRequest createTokenExchanger(String authorization,
String redirectUri) {
return new GoogleAuthorizationCodeTokenRequest(HaikuPlus.TRANSPORT,
HaikuPlus.JSON_FACTORY,
getClientId(),
getClientSecret(),
authorization,
redirectUri);
}
/**
* Creates a new authorized Google+ API client that can make calls to the Google+ API on behalf
* of the application through the Java client library.
*/
@VisibleForTesting
Plus createPlusApiClient(GoogleCredential credential) {
return new Plus.Builder(HaikuPlus.TRANSPORT, HaikuPlus.JSON_FACTORY, credential).build();
}
/**
* Reads in the client_secrets.json file and returns the constructed GoogleClientSecrets
* object. This method is called lazily to set the client ID,
* client secret, and redirect uri.
* @throws RuntimeException if there is an IOException reading the configuration
*/
public static synchronized void initClientSecretInfo() {
if (clientSecrets == null) {
try {
Reader reader = new FileReader("client_secrets.json");
clientSecrets = GoogleClientSecrets.load(HaikuPlus.JSON_FACTORY, reader);
} catch (IOException e) {
throw new RuntimeException("Cannot initialize client secrets", e);
}
}
}
/**
* Internal class used to monitor access and refresh tokens. If a token is invalid for an
* API request, the tokens in the credential are inalidated and an InvalidAccessTokenException
* is thrown to indicate that a new authorization code or bearer token is needed from the client.
*/
public static class InvalidateRefreshTokenOnExpired implements CredentialRefreshListener {
@Override
public void onTokenErrorResponse(Credential credential, TokenErrorResponse error)
throws IOException {
if (error != null && "invalid_grant".equals(error.getError())) {
credential.setAccessToken(null);
credential.setRefreshToken(null);
throw new InvalidAccessTokenException();
}
}
@Override
public void onTokenResponse(Credential credential, TokenResponse response) throws IOException {}
}
/**
* Inner class to define the InvalidAccessTokenException, which is raised when a
* refresh token fails to refresh the access token, indicating that the token has
* expired or been invalidated and a new one is needed. Also may be raised when no
* refresh token exists an the access token has expired, as is the case for the iOS client.
*/
@VisibleForTesting
static class InvalidAccessTokenException extends IOException {}
/**
* Rebuilds a token from a JSON response from the OAuth 2.0 token info endpoint.
*/
@VisibleForTesting
static class TokenInfoResponse extends Jsonifiable {
@Expose
String audience;
@Expose
String userId;
@Expose
String expiresIn;
}
/**
* Used as an abstract factory for testing static and final method calls.
*/
@VisibleForTesting
static class GoogleIdTokenRepository {
public GoogleIdToken parse(JsonFactory jsonFactory, String idAuth) throws IOException {
return GoogleIdToken.parse(jsonFactory, idAuth);
}
public boolean verifyAudience(GoogleIdToken idToken, List<String> audience) {
return idToken.verifyAudience(audience);
}
public TokenInfoResponse fromJson(ByteArrayOutputStream out)
throws UnsupportedEncodingException {
return Jsonifiable.fromJson(out.toString("UTF-8"), TokenInfoResponse.class);
}
}
}
| |
package org.sagebionetworks.table.query.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import java.util.Collections;
import java.util.HashSet;
import org.junit.Before;
import org.junit.Test;
import org.sagebionetworks.repo.model.table.ColumnModel;
import org.sagebionetworks.repo.model.table.ColumnType;
import org.sagebionetworks.repo.model.table.FacetColumnRangeRequest;
import org.sagebionetworks.repo.model.table.FacetColumnRequest;
import org.sagebionetworks.repo.model.table.FacetColumnValuesRequest;
import org.sagebionetworks.repo.model.table.FacetType;
import org.sagebionetworks.repo.model.table.TableConstants;
import org.sagebionetworks.schema.adapter.JSONObjectAdapter;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import com.google.common.collect.Sets;
public class FacetRequestColumnModelTest {
String columnId;
String columnName;
ColumnModel columnModel;
FacetColumnValuesRequest facetValues;
FacetColumnRangeRequest facetRange;
StringBuilder stringBuilder;
@Before
public void setUp(){
columnName = "someColumn";
columnId = "123";
facetValues = new FacetColumnValuesRequest();
facetValues.setColumnName(columnName);
facetRange = new FacetColumnRangeRequest();
facetRange.setColumnName(columnName);
columnModel = new ColumnModel();
columnModel.setId(columnId);
columnModel.setName(columnName);
columnModel.setColumnType(ColumnType.STRING);
columnModel.setFacetType(FacetType.enumeration);
stringBuilder = new StringBuilder();
}
@Test (expected = IllegalArgumentException.class)
public void testConstructorNullColumnModel() {
new FacetRequestColumnModel(null, facetValues);
}
@Test (expected = IllegalArgumentException.class)
public void testConstructorNullName() {
columnModel.setName(null);
new FacetRequestColumnModel(columnModel, facetValues);
}
@Test (expected = IllegalArgumentException.class)
public void testConstructorNullFacetType() {
columnModel.setFacetType(null);
new FacetRequestColumnModel(columnModel, facetValues);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorNullColumnType(){
columnModel.setColumnType(null);
new FacetRequestColumnModel(columnModel, facetValues);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorNonmatchingColumnNames(){
columnModel.setName("wrongName");
new FacetRequestColumnModel(columnModel, facetValues);
}
@Test (expected = IllegalArgumentException.class)
public void testConstructorWrongParameterForEnumeration(){
columnModel.setFacetType(FacetType.enumeration);
new FacetRequestColumnModel(columnModel, facetRange);
}
@Test (expected = IllegalArgumentException.class)
public void testConstructorWrongParameterForRange(){
columnModel.setFacetType(FacetType.range);
new FacetRequestColumnModel(columnModel, facetValues);
}
@Test
public void testConstructorNullFacetRequest(){
FacetRequestColumnModel validatedQueryFacetColumn = new FacetRequestColumnModel(columnModel, null);
assertEquals(columnName, validatedQueryFacetColumn.getColumnName());
assertNull(validatedQueryFacetColumn.getFacetColumnRequest());
assertNull(validatedQueryFacetColumn.getSearchConditionString());
}
@Test
public void testConstructorForEnumerationNoSearchCondition(){
columnModel.setFacetType(FacetType.enumeration);
FacetRequestColumnModel validatedQueryFacetColumn = new FacetRequestColumnModel(columnModel, facetValues);
assertEquals(columnName, validatedQueryFacetColumn.getColumnName());
assertFalse(validatedQueryFacetColumn.getFacetColumnRequest() instanceof FacetColumnRangeRequest);
assertEquals(facetValues, validatedQueryFacetColumn.getFacetColumnRequest());
assertNull(validatedQueryFacetColumn.getSearchConditionString());
}
@Test
public void testConstructorForRangeNoSearchCondition(){
columnModel.setFacetType(FacetType.range);
FacetRequestColumnModel validatedQueryFacetColumn = new FacetRequestColumnModel(columnModel, facetRange);
assertEquals(columnName, validatedQueryFacetColumn.getColumnName());
assertFalse(validatedQueryFacetColumn.getFacetColumnRequest() instanceof FacetColumnValuesRequest);
assertEquals(facetRange, validatedQueryFacetColumn.getFacetColumnRequest());
assertNull(validatedQueryFacetColumn.getSearchConditionString());
}
///////////////////////////////////////////
// createFacetSearchConditionString() tests
///////////////////////////////////////////
@Test
public void testCreateFacetSearchConditionStringNullFacet(){
assertNull(FacetRequestColumnModel.createFacetSearchConditionString(null, false));
}
@Test
public void testCreateFacetSearchConditionString_UsingFacetColumnValuesRequestClass_SingleValueColumn(){
facetValues.setFacetValues(Sets.newHashSet("hello"));
assertEquals(FacetRequestColumnModel.createSingleValueColumnEnumerationSearchCondition(facetValues),
FacetRequestColumnModel.createFacetSearchConditionString(facetValues, false));
}
@Test
public void testCreateFacetSearchConditionString_UsingFacetColumnValuesRequestClass_ListColumn(){
facetValues.setFacetValues(Sets.newHashSet("hello"));
assertEquals(FacetRequestColumnModel.createListColumnEnumerationSearchCondition(facetValues),
FacetRequestColumnModel.createFacetSearchConditionString(facetValues, true));
}
@Test
public void testCreateFacetSearchConditionStringUsingFacetColumnRangeRequestClass(){
facetRange.setMax("123");
assertEquals(FacetRequestColumnModel.createRangeSearchCondition(facetRange),
FacetRequestColumnModel.createFacetSearchConditionString(facetRange, false));
}
@Test (expected = IllegalArgumentException.class)
public void testCreateFacetSearchConditionStringUsingUnknownFacetClass(){
FacetRequestColumnModel.createFacetSearchConditionString(new FacetColumnRequest(){
public JSONObjectAdapter initializeFromJSONObject(JSONObjectAdapter toInitFrom)
throws JSONObjectAdapterException {return null;}
public JSONObjectAdapter writeToJSONObject(JSONObjectAdapter writeTo) throws JSONObjectAdapterException {return null;}
public String getJSONSchema() {return null;}
public String getConcreteType() {return null;}
public FacetColumnRequest setConcreteType(String concreteType) { return this;}
public String getColumnName() {return null;}
public FacetColumnRequest setColumnName(String columnName) {return this;}
}, false);
}
////////////////////////////////////////////
// createSingleValueColumnEnumerationSearchCondition() tests
///////////////////////////////////////////
@Test
public void testSingleValueColumnEnumerationSearchConditionString_NullFacet(){
assertNull(FacetRequestColumnModel.createSingleValueColumnEnumerationSearchCondition(null));
}
@Test
public void testSingleValueColumnEnumerationSearchConditionString_NullFacetValues(){
facetValues.setFacetValues(null);
assertNull(FacetRequestColumnModel.createSingleValueColumnEnumerationSearchCondition(facetValues));
}
@Test
public void testSingleValueColumnEnumerationSearchConditionString_EmptyFacetValues(){
facetValues.setFacetValues(new HashSet<String>());
assertNull(FacetRequestColumnModel.createSingleValueColumnEnumerationSearchCondition(facetValues));
}
@Test
public void testSingleValueColumnEnumerationSearchConditionString_OneValue(){
String value = "hello";
facetValues.setFacetValues(Sets.newHashSet(value));
String searchConditionString = FacetRequestColumnModel.createSingleValueColumnEnumerationSearchCondition(facetValues);
assertEquals("(\"someColumn\"='hello')", searchConditionString);
}
@Test
public void testSingleValueColumnEnumerationSearchConditionString_OneValueIsNullKeyword(){
String value = TableConstants.NULL_VALUE_KEYWORD;
facetValues.setFacetValues(Sets.newHashSet(value));
String searchConditionString = FacetRequestColumnModel.createSingleValueColumnEnumerationSearchCondition(facetValues);
assertEquals("(\"someColumn\" IS NULL)", searchConditionString);
}
@Test
public void testSingleValueColumnEnumerationSearchConditionString_TwoValues(){
String value1 = "hello";
String value2 = "world";
facetValues.setFacetValues(Sets.newHashSet(value1, value2));
String searchConditionString = FacetRequestColumnModel.createSingleValueColumnEnumerationSearchCondition(facetValues);
assertEquals("(\"someColumn\"='hello' OR \"someColumn\"='world')", searchConditionString);
}
@Test
public void testSingleValueColumnEnumerationSearchConditionString_TwoValuesWithOneBeingNullKeyword(){
String value1 = TableConstants.NULL_VALUE_KEYWORD;
String value2 = "world";
facetValues.setFacetValues(Sets.newHashSet(value1, value2));
String searchConditionString = FacetRequestColumnModel.createSingleValueColumnEnumerationSearchCondition(facetValues);
assertEquals("(\"someColumn\" IS NULL OR \"someColumn\"='world')", searchConditionString);
}
@Test
public void testSingleValueColumnEnumerationSearchConditionString_OneValueContainsSpace(){
String value = "hello world";
facetValues.setFacetValues(Sets.newHashSet(value));
String searchConditionString = FacetRequestColumnModel.createSingleValueColumnEnumerationSearchCondition(facetValues);
assertEquals("(\"someColumn\"='hello world')", searchConditionString);
}
@Test
public void testEnumerationSearchConditionStringColumnNameWithQuotes() {
String columnName = "\"quoted\"Column";
facetValues.setColumnName(columnName);
facetValues.setFacetValues(Collections.singleton("myValue"));
String expectedResult = "(\"\"\"quoted\"\"Column\"='myValue')";
String searchConditionString = FacetRequestColumnModel.createSingleValueColumnEnumerationSearchCondition(facetValues);
assertEquals(expectedResult, searchConditionString);
}
////////////////////////////////////////////
// createListColumnEnumerationSearchCondition() tests
///////////////////////////////////////////
@Test
public void testListColumnEnumerationSearchConditionString_NullFacet(){
assertNull(FacetRequestColumnModel.createListColumnEnumerationSearchCondition(null));
}
@Test
public void testListColumnEnumerationSearchConditionString_NullFacetValues(){
facetValues.setFacetValues(null);
assertNull(FacetRequestColumnModel.createListColumnEnumerationSearchCondition(facetValues));
}
@Test
public void testListColumnEnumerationSearchConditionString_EmptyFacetValues(){
facetValues.setFacetValues(Collections.emptySet());
assertNull(FacetRequestColumnModel.createListColumnEnumerationSearchCondition(facetValues));
}
@Test
public void testListColumnEnumerationSearchConditionString_OneValue(){
String value = "hello";
facetValues.setFacetValues(Sets.newHashSet(value));
String searchConditionString = FacetRequestColumnModel.createListColumnEnumerationSearchCondition(facetValues);
assertEquals("(\"someColumn\" HAS ('hello'))", searchConditionString);
}
@Test
public void testListColumnEnumerationSearchConditionString_OneValueIsNullKeyword(){
String value = TableConstants.NULL_VALUE_KEYWORD;
facetValues.setFacetValues(Sets.newHashSet(value));
String searchConditionString = FacetRequestColumnModel.createListColumnEnumerationSearchCondition(facetValues);
assertEquals("(\"someColumn\" IS NULL)", searchConditionString);
}
@Test
public void testListColumnEnumerationSearchConditionString_TwoValues(){
String value1 = "hello";
String value2 = "world";
facetValues.setFacetValues(Sets.newHashSet(value1, value2));
String searchConditionString = FacetRequestColumnModel.createListColumnEnumerationSearchCondition(facetValues);
assertEquals("(\"someColumn\" HAS ('hello','world'))", searchConditionString);
}
@Test
public void testListColumnEnumerationSearchConditionString_TwoValuesWithNull(){
String value1 = "hello";
String value2 = "world";
facetValues.setFacetValues(Sets.newHashSet(value1, value2, TableConstants.NULL_VALUE_KEYWORD));
String searchConditionString = FacetRequestColumnModel.createListColumnEnumerationSearchCondition(facetValues);
assertEquals("(\"someColumn\" HAS ('hello','world') OR \"someColumn\" IS NULL)", searchConditionString);
}
@Test
public void testListColumnEnumerationSearchConditionString_TwoValuesWithOneBeingNullKeyword(){
String value1 = TableConstants.NULL_VALUE_KEYWORD;
String value2 = "world";
facetValues.setFacetValues(Sets.newHashSet(value1, value2));
String searchConditionString = FacetRequestColumnModel.createListColumnEnumerationSearchCondition(facetValues);
assertEquals("(\"someColumn\" HAS ('world') OR \"someColumn\" IS NULL)", searchConditionString);
}
@Test
public void testListColumnEnumerationSearchConditionString_OneValueContainsSpace() {
String value = "hello world";
facetValues.setFacetValues(Sets.newHashSet(value));
String searchConditionString = FacetRequestColumnModel.createListColumnEnumerationSearchCondition(facetValues);
assertEquals("(\"someColumn\" HAS ('hello world'))", searchConditionString);
}
//////////////////////////////////////
// createRangeSearchCondition() tests
//////////////////////////////////////
@Test
public void testRangeSearchConditionNullFacet(){
assertNull(FacetRequestColumnModel.createRangeSearchCondition(null));
}
@Test
public void testRangeSearchConditionNoMinAndNoMax(){
facetRange.setMax(null);
facetRange.setMin("");
assertNull(FacetRequestColumnModel.createRangeSearchCondition(facetRange));
}
@Test
public void testRangeSearchConditionStringMinOnly(){
String min = "42";
facetRange.setMin(min);
String searchConditionString = FacetRequestColumnModel.createRangeSearchCondition(facetRange);
assertEquals("(\"someColumn\">='42')", searchConditionString);
}
@Test
public void testRangeSearchConditionStringMaxOnly(){
String max = "42";
facetRange.setMax(max);
String searchConditionString = FacetRequestColumnModel.createRangeSearchCondition(facetRange);
assertEquals("(\"someColumn\"<='42')", searchConditionString);
}
@Test
public void testRangeSearchConditionStringMinAndMax(){
String min = "123";
String max = "456";
facetRange.setMin(min);
facetRange.setMax(max);
String searchConditionString = FacetRequestColumnModel.createRangeSearchCondition(facetRange);
assertEquals("(\"someColumn\" BETWEEN '123' AND '456')", searchConditionString);
}
@Test
public void testRangeSearchConditionStringMinIsNullValueKeyword(){
String min = TableConstants.NULL_VALUE_KEYWORD;
String max = "456";
facetRange.setMin(min);
facetRange.setMax(max);
String searchConditionString = FacetRequestColumnModel.createRangeSearchCondition(facetRange);
assertEquals("(\"someColumn\" IS NULL)", searchConditionString);
}
@Test
public void testRangeSearchConditionStringMaxIsNullValueKeyword() {
String min = "123";
String max = TableConstants.NULL_VALUE_KEYWORD;
facetRange.setMin(min);
facetRange.setMax(max);
String searchConditionString = FacetRequestColumnModel.createRangeSearchCondition(facetRange);
assertEquals("(\"someColumn\" IS NULL)", searchConditionString);
}
@Test
public void testRangeSearchConditionStringColumnNameWithQuotes() {
String columnName = "\"quoted\"Column";
facetRange.setColumnName(columnName);
facetRange.setMax("42");
String expectedResult = "(\"\"\"quoted\"\"Column\"<='42')";
String searchConditionString = FacetRequestColumnModel.createRangeSearchCondition(facetRange);
assertEquals(expectedResult, searchConditionString);
}
//////////////////////////////////////
// appendValueToStringBuilder() Tests
//////////////////////////////////////
@Test
public void testAppendValueToStringBuilderStringType(){
String value = "value asdf 48109-8)(_*()*)(7^*&%$%W$%#%$^^%$%^=";
String expectedResult = "'"+value+"'";
FacetRequestColumnModel.appendValueToStringBuilder(stringBuilder, value);
assertEquals(expectedResult, stringBuilder.toString());
}
@Test
public void testAppendValueToStringBuilderNonStringType(){
String value = "682349708";
String expectedResult = "'"+value+"'";
FacetRequestColumnModel.appendValueToStringBuilder(stringBuilder, value);
assertEquals(expectedResult, stringBuilder.toString());
}
@Test
public void testAppendValueToStringBuilderEscapeSingleQuotes(){
String value = "whomst'd've";
String expectedResult = "'whomst''d''ve'";
FacetRequestColumnModel.appendValueToStringBuilder(stringBuilder, value);
assertEquals(expectedResult, stringBuilder.toString());
}
}
| |
/**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo 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 the following location:
*
* 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.jasig.portal.portlet.marketplace;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.jasig.portal.EntityIdentifier;
import org.jasig.portal.portlet.om.IPortletDefinition;
import org.jasig.portal.portlet.om.IPortletDefinitionId;
import org.jasig.portal.portlet.om.IPortletDefinitionParameter;
import org.jasig.portal.portlet.om.IPortletDescriptorKey;
import org.jasig.portal.portlet.om.IPortletPreference;
import org.jasig.portal.portlet.om.IPortletType;
import org.jasig.portal.portlet.om.PortletCategory;
import org.jasig.portal.portlet.om.PortletLifecycleState;
import org.jasig.portal.portlet.registry.IPortletCategoryRegistry;
import org.jasig.portal.security.AuthorizationPrincipalHelper;
import org.jasig.portal.security.IAuthorizationPrincipal;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.utils.web.PortalWebUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Marketplace portlet definitions add Marketplace-specific features upon an underlying
* IPortletDefinition.
*
* @since uPortal 4.1
*/
public class MarketplacePortletDefinition implements IPortletDefinition{
public static final String MARKETPLACE_FNAME = "portletmarketplace";
public static final int QUANTITY_RELATED_PORTLETS_TO_SHOW = 5;
private static final String INITIAL_RELEASE_DATE_PREFERENCE_NAME="Initial_Release_Date";
private static final String RELEASE_DATE_PREFERENCE_NAME="Release_Date";
private static final String RELEASE_NOTE_PREFERENCE_NAME="Release_Notes";
private static final String RELEASE_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String MARKETPLACE_SHORT_LINK_PREF = "short_link";
private static final String MARKETPLACE_KEYWORDS_PREF = "keywords";
private static final DateTimeFormatter releaseDateFormatter = DateTimeFormat.forPattern(RELEASE_DATE_FORMAT);
protected final Logger logger = LoggerFactory.getLogger(getClass());
private IMarketplaceService marketplaceService;
private IPortletCategoryRegistry portletCategoryRegistry;
private IPortletDefinition portletDefinition;
private List<ScreenShot> screenShots;
private PortletReleaseNotes releaseNotes;
private Set<PortletCategory> categories;
// that MarketplacePortletDefinition contains more MarketplacePortletDefinition is okay only so long as
// related portlets are lazy-initialized on access and are not always accessed.
private Set<MarketplacePortletDefinition> relatedPortlets;
private Set<PortletCategory> parentCategories;
private String shortURL = null;
private List<String> keywords = null;
/**
*
* @param portletDefinition the portlet definition to make this MarketplacePD
* @param registry the registry you want to use for categories and related apps
* Benefit: screenshot property is set if any are available. This includes URL and caption
*/
public MarketplacePortletDefinition(final IPortletDefinition portletDefinition,
final IMarketplaceService service, final IPortletCategoryRegistry registry){
this.portletCategoryRegistry = registry;
this.marketplaceService = service;
this.portletDefinition = portletDefinition;
this.initDefinitions();
}
private void initDefinitions(){
this.initScreenShots();
this.initPortletReleaseNotes();
this.initCategories();
this.initShortURL();
this.initKeywords();
// deliberately does *not* init related portlets, to avoid infinite recursion of initing related portlets.
// TODO: use a caching registry so that get some cache hits when referencing MarketplacePortletDefinitions
}
private void initKeywords() {
List<IPortletPreference> portletPreferences = this.portletDefinition.getPortletPreferences();
for(IPortletPreference pref : portletPreferences) {
if(MARKETPLACE_KEYWORDS_PREF.equalsIgnoreCase(pref.getName())) {
this.keywords = new ArrayList<String>(Arrays.asList(pref.getValues()));
break;
}
}
}
private void initShortURL() {
List<IPortletPreference> portletPreferences = this.portletDefinition.getPortletPreferences();
for(IPortletPreference pref : portletPreferences) {
if(MARKETPLACE_SHORT_LINK_PREF.equalsIgnoreCase(pref.getName())
&& pref.getValues().length == 1) {
setShortURL(pref.getValues()[0]);
break;
}
}
}
private void initScreenShots(){
List<IPortletPreference> portletPreferences = this.portletDefinition.getPortletPreferences();
List<IPortletPreference> urls = new ArrayList<IPortletPreference>(portletPreferences.size());
List<IPortletPreference> captions = new ArrayList<IPortletPreference>(portletPreferences.size());
List<ScreenShot> screenShots = new ArrayList<ScreenShot>();
//Creates a list of captions and list of urls
for(int i=0; i<portletPreferences.size(); i++){
//Most screenshots possible is i
urls.add(null);
captions.add(null);
for(int j=0; j<portletPreferences.size(); j++){
if(portletPreferences.get(j).getName().equalsIgnoreCase("screen_shot"+Integer.toString(i+1))){
urls.set(i, portletPreferences.get(j));
}
if(portletPreferences.get(j).getName().equalsIgnoreCase("screen_shot"+Integer.toString(i+1)+"_caption")){
captions.set(i, portletPreferences.get(j));
}
}
}
for(int i=0; i<urls.size(); i++){
if(urls.get(i)!=null){
if(captions.size()>i && captions.get(i)!=null){
screenShots.add(new ScreenShot(urls.get(i).getValues()[0], Arrays.asList(captions.get(i).getValues())));
}else{
screenShots.add(new ScreenShot(urls.get(i).getValues()[0]));
}
}
}
this.setScreenShots(screenShots);
}
private void initPortletReleaseNotes(){
PortletReleaseNotes temp = new PortletReleaseNotes();
for(IPortletPreference portletPreference:this.portletDefinition.getPortletPreferences()){
if(MarketplacePortletDefinition.RELEASE_DATE_PREFERENCE_NAME.equalsIgnoreCase(portletPreference.getName())){
try {
DateTime dt = releaseDateFormatter.parseDateTime(portletPreference.getValues()[0]);
temp.setReleaseDate(dt);
} catch (Exception e){
logger.warn("Issue with parsing "+ RELEASE_DATE_PREFERENCE_NAME + ". Should be in format " + RELEASE_DATE_FORMAT, e);
}
continue;
}
if(MarketplacePortletDefinition.RELEASE_NOTE_PREFERENCE_NAME.equalsIgnoreCase(portletPreference.getName())){
temp.setReleaseNotes(Arrays.asList(portletPreference.getValues()));
continue;
}
if(MarketplacePortletDefinition.INITIAL_RELEASE_DATE_PREFERENCE_NAME.equalsIgnoreCase(portletPreference.getName())){
try {
DateTime dt = releaseDateFormatter.parseDateTime(portletPreference.getValues()[0]);
temp.setInitialReleaseDate(dt);
} catch (Exception e){
logger.warn("Issue with parsing "+ INITIAL_RELEASE_DATE_PREFERENCE_NAME + ". Should be in format " + RELEASE_DATE_FORMAT, e);
}
continue;
}
}
this.setPortletReleaseNotes(temp);
}
/**
* private method that sets the parentCategories field and the categories field
* This will ensure that the public methods {@link #getParentCategories() getParentCategories()}
* and {@link #getCategories() getCategories()} will not return null.
* Empty sets are allowed
*/
private void initCategories(){
Set<PortletCategory> allCategories = new HashSet<PortletCategory>();
this.setParentCategories(this.portletCategoryRegistry.getParentCategories(this));
for(PortletCategory childCategory:this.parentCategories){
allCategories.add(childCategory);
allCategories.addAll(this.portletCategoryRegistry.getAllParentCategories(childCategory));
}
this.setCategories(allCategories);
}
/**
* Initialize related portlets.
* This must be called lazily so that MarketplacePortletDefinitions instantiated as related
* portlets off of a MarketplacePortletDefinition do not always instantiate their related
* MarketplacePortletDefinitions, ad infinitem.
*/
private void initRelatedPortlets(){
final Set<MarketplacePortletDefinition> allRelatedPortlets = new HashSet<>();
for(PortletCategory parentCategory: this.portletCategoryRegistry.getParentCategories(this)){
final Set<IPortletDefinition> portletsInCategory =
this.portletCategoryRegistry.getAllChildPortlets(parentCategory);
for (IPortletDefinition portletDefinition : portletsInCategory) {
allRelatedPortlets.add(
new MarketplacePortletDefinition(portletDefinition,
this.marketplaceService, this.portletCategoryRegistry));
}
}
allRelatedPortlets.remove(this);
this.relatedPortlets = allRelatedPortlets;
}
private void setScreenShots(List<ScreenShot> screenShots){
this.screenShots = screenShots;
}
/**
* @return the screenShotList. Will not be null.
*/
public List<ScreenShot> getScreenShots() {
if(screenShots==null){
this.initScreenShots();
}
return screenShots;
}
private void setPortletReleaseNotes(PortletReleaseNotes portletReleaseNotes){
this.releaseNotes = portletReleaseNotes;
}
/**
* @return the releaseNotes. Will not be null.
*/
public PortletReleaseNotes getPortletReleaseNotes() {
if(releaseNotes==null){
this.initPortletReleaseNotes();
}
return releaseNotes;
}
private void setCategories(Set<PortletCategory> categories){
this.categories = categories;
}
/**
*
* @return a set of categories that includes all the categories that this definition is in
* and all parent categories of the portlet's category. Will not return null. Might return
* empty set.
*/
public Set<PortletCategory> getCategories() {
if(this.categories == null){
this.initCategories();
}
return this.categories;
}
private void setParentCategories(Set<PortletCategory> parentCategories) {
this.parentCategories = parentCategories;
}
/**
* @return a set of categories that this portlet directly belongs too. Will
* not traverse up the category tree and return grandparent categories and
* farther. Will not return null. Might return empty set.
*/
public Set<PortletCategory> getParentCategories() {
if(this.parentCategories == null){
this.initCategories();
}
return this.parentCategories;
}
/**
* @return a set of portlets that include all portlets in this portlets immediate categories and children categories
* Will not return null. Will not include self in list. Might return an empty set.
*/
public Set<MarketplacePortletDefinition> getRelatedPortlets() {
// lazy init is essential to avoid infinite recursion in graphing related portlets.
if(this.relatedPortlets==null){
this.initRelatedPortlets();
}
return this.relatedPortlets;
}
/**
* Obtain up to QUANTITY_RELATED_PORTLETS_TO_SHOW random related portlets BROWSEable by the
* given user.
*
* @return a non-null potentially empty Set of related portlets BROWSEable by the user
*/
public Set<MarketplacePortletDefinition> getRandomSamplingRelatedPortlets(final IPerson user) {
Validate.notNull(user, "Cannot filter to BROWSEable by a null user");
final IAuthorizationPrincipal principal = AuthorizationPrincipalHelper.principalFromUser(user);
// lazy init is essential to avoid infinite recursion in graphing related portlets.
if(this.relatedPortlets==null){
this.initRelatedPortlets();
}
if(this.relatedPortlets.isEmpty()){
return this.relatedPortlets;
}
List<MarketplacePortletDefinition> tempList = new ArrayList<MarketplacePortletDefinition>(this.relatedPortlets);
Collections.shuffle(tempList);
final int count = Math.min(QUANTITY_RELATED_PORTLETS_TO_SHOW, tempList.size());
final Set<MarketplacePortletDefinition> rslt = new HashSet<MarketplacePortletDefinition>();
for (final MarketplacePortletDefinition relatedPortlet : tempList) {
if (marketplaceService.mayBrowsePortlet(principal, relatedPortlet)) {
rslt.add(relatedPortlet);
}
if (rslt.size() >= count) break; // escape the loop if we've hit our target quantity
// of related portlets
}
return rslt;
}
/**
* Convenience method for getting a bookmarkable URL for rendering the defined portlet,
*
* Normally this is the portal rendering of the portlet, addressed by fname, and in that case
* this method will *ONLY* work when invoked in the context of a Spring-managed
* HttpServletRequest available via RequestContextHolder.
*
* When there is an alternativeMaximizedLink, this method returns that instead.
*
* WARNING: This method does not consider whether the requesting user has permission to render
* the target portlet, so this might be getting a URL that the user can't actually use.
*
* @return URL for rendering the portlet
* @throws IllegalStateException when context does not allow computing the URL
*/
public String getRenderUrl() {
final String alternativeMaximizedUrl = getAlternativeMaximizedLink();
if (null != alternativeMaximizedUrl) {
return alternativeMaximizedUrl;
}
final String contextPath = PortalWebUtils.currentRequestContextPath();
// TODO: stop abstraction violation of relying on knowledge of uPortal URL implementation details
return contextPath + "/p/" + getFName() + "/render.uP";
}
@Override
public String getDataId() {
return this.portletDefinition.getDataId();
}
@Override
public String getDataTitle() {
return this.portletDefinition.getDataTitle();
}
@Override
public String getDataDescription(){
return this.portletDefinition.getDataDescription();
}
@Override
public IPortletDefinitionId getPortletDefinitionId() {
return this.portletDefinition.getPortletDefinitionId();
}
@Override
public List<IPortletPreference> getPortletPreferences() {
return this.portletDefinition.getPortletPreferences();
}
@Override
public boolean setPortletPreferences(List<IPortletPreference> portletPreferences) {
return this.portletDefinition.setPortletPreferences(portletPreferences);
}
@Override
public PortletLifecycleState getLifecycleState() {
return this.portletDefinition.getLifecycleState();
}
@Override
public String getFName() {
return this.portletDefinition.getFName();
}
@Override
public String getName() {
return this.portletDefinition.getName();
}
@Override
public String getDescription() {
return this.portletDefinition.getDescription();
}
@Override
public IPortletDescriptorKey getPortletDescriptorKey() {
return this.portletDefinition.getPortletDescriptorKey();
}
@Override
public String getTitle() {
return this.portletDefinition.getTitle();
}
@Override
public int getTimeout() {
return this.portletDefinition.getTimeout();
}
@Override
public Integer getActionTimeout() {
return this.portletDefinition.getActionTimeout();
}
@Override
public Integer getEventTimeout() {
return this.portletDefinition.getEventTimeout();
}
@Override
public Integer getRenderTimeout() {
return this.portletDefinition.getRenderTimeout();
}
@Override
public Integer getResourceTimeout() {
return this.portletDefinition.getResourceTimeout();
}
@Override
public IPortletType getType() {
return this.portletDefinition.getType();
}
@Override
public int getPublisherId() {
return this.portletDefinition.getPublisherId();
}
@Override
public int getApproverId() {
return this.portletDefinition.getApproverId();
}
@Override
public Date getPublishDate() {
return this.portletDefinition.getPublishDate();
}
@Override
public Date getApprovalDate() {
return this.portletDefinition.getApprovalDate();
}
@Override
public int getExpirerId() {
return this.portletDefinition.getExpirerId();
}
@Override
public Date getExpirationDate() {
return this.portletDefinition.getExpirationDate();
}
@Override
public Set<IPortletDefinitionParameter> getParameters() {
return this.portletDefinition.getParameters();
}
@Override
public IPortletDefinitionParameter getParameter(String key) {
return this.portletDefinition.getParameter(key);
}
@Override
public Map<String, IPortletDefinitionParameter> getParametersAsUnmodifiableMap() {
return this.portletDefinition.getParametersAsUnmodifiableMap();
}
@Override
public String getName(String locale) {
return this.portletDefinition.getName();
}
@Override
public String getDescription(String locale) {
return this.portletDefinition.getDescription();
}
@Override
public String getTitle(String locale) {
return this.portletDefinition.getTitle(locale);
}
@Override
public String getAlternativeMaximizedLink() {
return this.portletDefinition.getAlternativeMaximizedLink();
}
@Override
public void setFName(String fname){
this.portletDefinition.setFName(fname);
}
@Override
public void setName(String name) {
this.portletDefinition.setName(name);
}
@Override
public void setDescription(String descr) {
this.portletDefinition.setDescription(descr);
}
@Override
public void setTitle(String title) {
this.portletDefinition.setTitle(title);
}
@Override
public void setTimeout(int timeout) {
this.portletDefinition.setTimeout(timeout);
}
@Override
public void setActionTimeout(Integer actionTimeout) {
this.portletDefinition.setActionTimeout(actionTimeout);
}
@Override
public void setEventTimeout(Integer eventTimeout) {
this.portletDefinition.setEventTimeout(eventTimeout);
}
@Override
public void setRenderTimeout(Integer renderTimeout) {
this.portletDefinition.setRenderTimeout(renderTimeout);
}
@Override
public void setResourceTimeout(Integer resourceTimeout) {
this.portletDefinition.setResourceTimeout(resourceTimeout);
}
@Override
public void setType(IPortletType channelType) {
this.portletDefinition.setType(channelType);
}
@Override
public void setPublisherId(int publisherId) {
this.portletDefinition.setPublisherId(publisherId);
}
@Override
public void setApproverId(int approvalId) {
this.portletDefinition.setApproverId(approvalId);
}
@Override
public void setPublishDate(Date publishDate) {
this.portletDefinition.setPublishDate(publishDate);
}
@Override
public void setApprovalDate(Date approvalDate) {
this.portletDefinition.setApprovalDate(approvalDate);
}
@Override
public void setExpirerId(int expirerId) {
this.portletDefinition.setExpirerId(expirerId);
}
@Override
public void setExpirationDate(Date expirationDate) {
this.portletDefinition.setExpirationDate(expirationDate);
}
@Override
public void setParameters(Set<IPortletDefinitionParameter> parameters) {
this.portletDefinition.setParameters(parameters);
}
@Override
public void addLocalizedTitle(String locale, String chanTitle) {
this.portletDefinition.addLocalizedTitle(locale, chanTitle);
}
@Override
public void addLocalizedName(String locale, String chanName) {
this.portletDefinition.addLocalizedName(locale, chanName);
}
@Override
public void addLocalizedDescription(String locale, String chanDesc) {
this.portletDefinition.addLocalizedDescription(locale, chanDesc);
}
@Override
public EntityIdentifier getEntityIdentifier() {
return this.portletDefinition.getEntityIdentifier();
}
@Override
public void addParameter(IPortletDefinitionParameter parameter) {
this.portletDefinition.addParameter(parameter);
}
@Override
public void addParameter(String name, String value) {
this.portletDefinition.addParameter(name, value);
}
@Override
public void removeParameter(IPortletDefinitionParameter parameter) {
this.portletDefinition.removeParameter(parameter);
}
@Override
public void removeParameter(String name) {
this.portletDefinition.removeParameter(name);
}
@Override
public Double getRating() {
return this.portletDefinition.getRating();
}
@Override
public void setRating(Double rating) {
this.portletDefinition.setRating(rating);
}
@Override
public Long getUsersRated() {
return this.portletDefinition.getUsersRated();
}
@Override
public void setUsersRated(Long usersRated) {
this.portletDefinition.setUsersRated(usersRated);
}
public String getShortURL() {
return shortURL;
}
public void setShortURL(String shortURL) {
this.shortURL = shortURL;
}
@Override
public String getTarget() {
return this.portletDefinition.getTarget();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("fname", getFName())
.toString();
}
/*
* Marketplace portlet definitions are definitively identified by the fname of their underlying
* portlet publication, so only the fname contributes to the hashcode.
* @since uPortal 4.2
*/
@Override
public int hashCode() {
return getFName().hashCode();
}
/*
* Equal where the other object is a MarketplacePortletDefinition with the same fname.
* This is important so that Set operations work properly.
* @since uPortal 4.2
*/
@Override
public boolean equals(Object other) {
if (null == other) { return false; }
if (this == other) { return true; }
if (getClass() != other.getClass()) {
return false;
}
final MarketplacePortletDefinition otherDefinition = (MarketplacePortletDefinition) other;
if (getFName() == otherDefinition.getFName()) { return true; }; // both null fname case
return getFName().equals(otherDefinition.getFName());
}
public List<String> getKeywords() {
return keywords;
}
}
| |
package cz.metacentrum.perun.core.bl;
import java.util.List;
import java.util.Map;
import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.ExtSource;
import cz.metacentrum.perun.core.api.Group;
import cz.metacentrum.perun.core.api.Member;
import cz.metacentrum.perun.core.api.Pair;
import cz.metacentrum.perun.core.api.Perun;
import cz.metacentrum.perun.core.api.PerunBean;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.Resource;
import cz.metacentrum.perun.core.api.RichGroup;
import cz.metacentrum.perun.core.api.RichMember;
import cz.metacentrum.perun.core.api.RichUser;
import cz.metacentrum.perun.core.api.Status;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.Vo;
import cz.metacentrum.perun.core.api.exceptions.AlreadyMemberException;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.ExtSourceNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.AlreadyAdminException;
import cz.metacentrum.perun.core.api.exceptions.GroupAlreadyRemovedException;
import cz.metacentrum.perun.core.api.exceptions.GroupAlreadyRemovedFromResourceException;
import cz.metacentrum.perun.core.api.exceptions.GroupExistsException;
import cz.metacentrum.perun.core.api.exceptions.GroupNotAdminException;
import cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.GroupOperationsException;
import cz.metacentrum.perun.core.api.exceptions.GroupRelationAlreadyExists;
import cz.metacentrum.perun.core.api.exceptions.GroupRelationCannotBeRemoved;
import cz.metacentrum.perun.core.api.exceptions.GroupRelationDoesNotExist;
import cz.metacentrum.perun.core.api.exceptions.GroupRelationNotAllowed;
import cz.metacentrum.perun.core.api.exceptions.GroupSynchronizationAlreadyRunningException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.MemberAlreadyRemovedException;
import cz.metacentrum.perun.core.api.exceptions.NotGroupMemberException;
import cz.metacentrum.perun.core.api.exceptions.NotMemberOfParentGroupException;
import cz.metacentrum.perun.core.api.exceptions.ParentGroupNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.RelationExistsException;
import cz.metacentrum.perun.core.api.exceptions.UserNotAdminException;
import cz.metacentrum.perun.core.api.exceptions.UserNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException;
import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
/**
* <p>Groups manager can do all work about groups in VOs.</p>
*
* <p>You must get an instance of GroupsManager from instance of Perun (perun si singleton - see how to get it's instance on wiki):</p>
* <pre>
* GroupsManager gm = perun.getGroupsManager();
* </pre>
*
* @author Michal Prochazka
* @author Slavek Licehammer
* @see Perun
*/
public interface GroupsManagerBl {
/**
* Creates a new top-level group and associate it with the VO.
*
* For this method (new group) has always same shortName like Name.
*
* @param perunSession
* @param vo
* @param group with name without ":"
*
* @return newly created top-level group
*
* @throws InternalErrorException if group.name contains ':' or other internal error occur
* @throws GroupExistsException
*/
Group createGroup(PerunSession perunSession, Vo vo, Group group) throws GroupExistsException, InternalErrorException;
/**
* Creates a new subgroup of the existing group.
*
* @param perunSession
* @param parentGroup
* @param group group.name must contain only shortName (without ":"). Hierarchy is defined by parentGroup parameter.
*
* @return newly created sub group with full group.Name with ":"
* @throws GroupExistsException
* @throws InternalErrorException
* @throws GroupOperationsException
* @throws GroupRelationNotAllowed
* @throws GroupRelationAlreadyExists
*/
Group createGroup(PerunSession perunSession, Group parentGroup, Group group) throws GroupExistsException, InternalErrorException, GroupOperationsException, GroupRelationNotAllowed, GroupRelationAlreadyExists;
/**
* Gets all groups which have enabled synchronization.
*
* @param sess
* @return list of groups to synchronize
* @throws InternalErrorException
* @throws GroupNotExistsException
*/
List<Group> getGroupsToSynchronize(PerunSession sess) throws InternalErrorException;
/**
* If forceDelete is false, delete only group and if this group has members or subgroups, throw an exception.
* If forceDelete is true, delete group with all subgroups, members and administrators, then delete this group.
*
* @param perunSession
* @param group group to delete
* @param forceDelete if forceDelete is false, delete group only if is empty and has no subgroups, if is true, delete anyway with all connections
*
* @throws InternalErrorException
* @throws RelationExistsException
* @throws GroupAlreadyRemovedException
* @throws GroupAlreadyRemovedFromResourceException
* @throws GroupOperationsException
* @throws GroupNotExistsException
* @throws GroupRelationDoesNotExist
* @throws GroupRelationCannotBeRemoved
*/
void deleteGroup(PerunSession perunSession, Group group, boolean forceDelete) throws InternalErrorException, RelationExistsException, GroupAlreadyRemovedException, GroupAlreadyRemovedFromResourceException, GroupOperationsException, GroupNotExistsException, GroupRelationDoesNotExist, GroupRelationCannotBeRemoved;
/**
* Delete all groups in list from perun. (Except members group)
*
* If forceDelete is false, delete groups only if none of them (IN MOMENT OF DELETING) has subgroups and members, in other case throw exception.
* if forceDelete is true, delete groups with all subgroups and members.
*
* Groups are deleted in order: from longest name to the shortest
* - ex: Group A:b:c will be deleted sooner than Group A:b etc.
* - reason for this: with group are deleted its subgroups too
*
* Important: Groups can be from different VOs.
*
* @param perunSession
* @param groups list of groups to deleted
* @param forceDelete if forceDelete is false, delete groups only if all of them have no subgroups and no members, if is true, delete anyway with all connections
*
* @throws InternalErrorException
* @throws GroupAlreadyRemovedException
* @throws RelationExistsException
* @throws GroupAlreadyRemovedFromResourceException
* @throws GroupOperationsException
* @throws GroupNotExistsException
* @throws GroupRelationDoesNotExist
* @throws GroupRelationCannotBeRemoved
*/
void deleteGroups(PerunSession perunSession, List<Group> groups, boolean forceDelete) throws InternalErrorException, GroupAlreadyRemovedException, RelationExistsException, GroupAlreadyRemovedFromResourceException, GroupOperationsException, GroupNotExistsException, GroupRelationDoesNotExist, GroupRelationCannotBeRemoved;
/**
* Deletes built-in members group.
*
* @param sess
* @param vo
* @throws InternalErrorException
* @throws GroupAlreadyRemovedException
* @throws GroupAlreadyRemovedFromResourceException
* @throws GroupOperationsException
* @throws GroupNotExistsException
* @throws GroupRelationDoesNotExist
* @throws GroupRelationCannotBeRemoved
*/
void deleteMembersGroup(PerunSession sess, Vo vo) throws InternalErrorException, GroupAlreadyRemovedException, GroupAlreadyRemovedFromResourceException, GroupOperationsException, GroupNotExistsException, GroupRelationDoesNotExist, GroupRelationCannotBeRemoved;
/**
* Deletes all groups under the VO except built-in groups (members, admins groups).
*
* @param perunSession
* @param vo VO
*
* @throws InternalErrorException
* @throws GroupAlreadyRemovedException
* @throws GroupAlreadyRemovedFromResourceException
* @throws GroupOperationsException
* @throws GroupNotExistsException
* @throws GroupRelationDoesNotExist
* @throws GroupRelationCannotBeRemoved
*/
void deleteAllGroups(PerunSession perunSession, Vo vo) throws InternalErrorException, GroupAlreadyRemovedException, GroupAlreadyRemovedFromResourceException, GroupOperationsException, GroupNotExistsException, GroupRelationDoesNotExist, GroupRelationCannotBeRemoved;
/**
* Updates group by ID.
*
* Update shortName (use shortName) and description. Group.name is ignored.
* Return Group with correctly set parameters (including group.name)
*
* @param perunSession
* @param group to update (use only ID, shortName and description)
*
* @return updated group with correctly set parameters (including group.name)
*
* @throws InternalErrorException
*/
Group updateGroup(PerunSession perunSession, Group group) throws InternalErrorException;
/**
* Search for the group with specified id in all VOs.
*
* @param id
* @param perunSession
*
* @return group with specified id or throws
* @throws InternalErrorException
* @throws GroupNotExistsException
*/
Group getGroupById(PerunSession perunSession, int id) throws InternalErrorException, GroupNotExistsException;
/**
* Search for the group with specified name in specified VO.
*
* IMPORTANT: need to use full name of group (ex. 'toplevel:a:b', not the shortname which is in this example 'b')
*
* @param perunSession
* @param vo
* @param name
*
* @return group with specified name or throws in specified VO
*
* @throws InternalErrorException
* @throws GroupNotExistsException
*/
Group getGroupByName(PerunSession perunSession, Vo vo, String name) throws InternalErrorException, GroupNotExistsException;
/**
* Adds member of the VO to the group in the same VO. But not to administrators and members group.
*
* @param perunSession
* @param group
* @param member
* @throws InternalErrorException
* @throws AlreadyMemberException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
* @throws NotMemberOfParentGroupException
* @throws GroupNotExistsException
* @throws GroupOperationsException
*/
void addMember(PerunSession perunSession, Group group, Member member) throws InternalErrorException, AlreadyMemberException, WrongAttributeValueException, WrongReferenceAttributeValueException, NotMemberOfParentGroupException, GroupNotExistsException, GroupOperationsException;
/**
* Special addMember which is able to add members into the members and administrators group.
*
* @param perunSession
* @param group
* @param member
* @throws InternalErrorException
* @throws AlreadyMemberException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
* @throws NotMemberOfParentGroupException
* @throws GroupNotExistsException
* @throws GroupOperationsException
*/
void addMemberToMembersGroup(PerunSession perunSession, Group group, Member member) throws InternalErrorException, AlreadyMemberException, WrongAttributeValueException, WrongReferenceAttributeValueException, NotMemberOfParentGroupException, GroupNotExistsException, GroupOperationsException;
/**
* Return list of assigned groups on the resource (without subgroups unless they are assigned too)
*
* @param perunSession
* @param resource
*
* @return list of groups, which are assigned on the resource
*
* @throws InternalErrorException
*/
List<Group> getAssignedGroupsToResource(PerunSession perunSession, Resource resource) throws InternalErrorException;
/** Return list of assigned groups on the resource.
*
* @param perunSession
* @param resource
* @param withSubGroups if true returns also all subgroups of assigned groups
*
* @return list of groups, which are assigned on the resource
*
* @throws InternalErrorException
*/
List<Group> getAssignedGroupsToResource(PerunSession perunSession, Resource resource, boolean withSubGroups) throws InternalErrorException;
/**
* Removes member form the group. But not from members or administrators group.
*
* @param perunSession
* @param group
* @param member
*
* @throws InternalErrorException
* @throws NotGroupMemberException
* @throws GroupNotExistsException
* @throws GroupOperationsException
*/
void removeMember(PerunSession perunSession, Group group, Member member) throws InternalErrorException, NotGroupMemberException, GroupNotExistsException, GroupOperationsException;
/**
* Removes member from members or administrators group only.
*
* @param perunSession
* @param group
* @param member
* @throws InternalErrorException
* @throws NotGroupMemberException
* @throws GroupNotExistsException
* @throws GroupOperationsException
*/
void removeMemberFromMembersOrAdministratorsGroup(PerunSession perunSession, Group group, Member member) throws InternalErrorException, NotGroupMemberException, GroupNotExistsException, GroupOperationsException;
/**
* Return all group members.
*
* @param perunSession
* @param group
* @return list of users or empty list if the group is empty
*
* @throws InternalErrorException
*/
List<Member> getGroupMembers(PerunSession perunSession, Group group) throws InternalErrorException;
/**
* Return only valid, suspended, expired and disabled group members.
*
* @param perunSession
* @param group
*
* @return list members or empty list if there are no such members
*
* @throws InternalErrorException
*/
List<Member> getGroupMembersExceptInvalid(PerunSession perunSession, Group group) throws InternalErrorException;
/**
* Return only valid, suspended and expired group members.
*
* @param perunSession
* @param group
*
* @return list members or empty list if there are no such members
*
* @throws InternalErrorException
*/
List<Member> getGroupMembersExceptInvalidAndDisabled(PerunSession perunSession, Group group) throws InternalErrorException;
/**
* Return group members.
*
* @param perunSession
* @param group
* @param status
*
* @return list users or empty list if there are no users on specified page
*
* @throws InternalErrorException
*/
List<Member> getGroupMembers(PerunSession perunSession, Group group, Status status) throws InternalErrorException;
/**
* Return group users sorted by name.
*
* @param perunSession
* @param group
* @return list users sorted or empty list if there are no users on specified page
*/
List<User> getGroupUsers(PerunSession perunSession, Group group) throws InternalErrorException;
/**
* Returns group members in the RichMember object, which contains Member+User data.
*
* @param sess
* @param group
*
* @return list of RichMembers
* @throws InternalErrorException
*/
List<RichMember> getGroupRichMembers(PerunSession sess, Group group) throws InternalErrorException;
/**
* Returns only valid, suspended and expired group members in the RichMember object, which contains Member+User data.
*
* @param sess
* @param group
*
* @return list of RichMembers
* @throws InternalErrorException
*/
List<RichMember> getGroupRichMembersExceptInvalid(PerunSession sess, Group group) throws InternalErrorException;
/**
* Returns group members in the RichMember object, which contains Member+User data.
*
* @param sess
* @param group
* @param status
*
* @return list of RichMembers
* @throws InternalErrorException
*/
List<RichMember> getGroupRichMembers(PerunSession sess, Group group, Status status) throws InternalErrorException;
/**
* Returns group members in the RichMember object, which contains Member+User data. Also contains user and member attributes.
*
* @param sess
* @param group
*
* @return list of RichMembers
* @throws InternalErrorException
*/
List<RichMember> getGroupRichMembersWithAttributes(PerunSession sess, Group group) throws InternalErrorException;
/**
* Returns only valid, suspended and expired group members in the RichMember object, which contains Member+User data. Also contains user and member attributes.
*
* @param sess
* @param group
*
* @return list of RichMembers
* @throws InternalErrorException
*/
List<RichMember> getGroupRichMembersWithAttributesExceptInvalid(PerunSession sess, Group group) throws InternalErrorException;
/**
* Returns group members in the RichMember object, which contains Member+User data. Also contains user and member attributes.
*
* @param sess
* @param group
* @param status
*
* @return list of RichMembers
* @throws InternalErrorException
*/
List<RichMember> getGroupRichMembersWithAttributes(PerunSession sess, Group group, Status status) throws InternalErrorException;
/**
* @param perunSession
* @param group
*
* @return count of members of specified group
*
* @throws InternalErrorException
*/
int getGroupMembersCount(PerunSession perunSession, Group group) throws InternalErrorException;
/**
* Checks whether the user is member of the group.
*
* @param sess
* @param user
* @param group
* @return true if the user is member of the group
* @throws InternalErrorException
*/
boolean isUserMemberOfGroup(PerunSession sess, User user, Group group) throws InternalErrorException;
/**
* Get all groups of the VO.
*
* @param sess
* @param vo
*
* @return list of groups
*
* @throws InternalErrorException
*/
List<Group> getAllGroups(PerunSession sess, Vo vo) throws InternalErrorException;
/**
* Get all groups of the VO stored in the map reflecting the hierarchy.
*
* @param sess
* @param vo
*
* @return map of the groups hierarchically organized
*
* @throws InternalErrorException
*/
Map<Group, Object> getAllGroupsWithHierarchy(PerunSession sess, Vo vo) throws InternalErrorException;
/**
* Get parent group.
* If group is topLevel group or Members group, return Members group.
*
* @param sess
* @param group
* @return parent group
* @throws InternalErrorException
* @throws ParentGroupNotExistsException
*/
Group getParentGroup(PerunSession sess, Group group) throws InternalErrorException, ParentGroupNotExistsException;
/**
* Get all subgroups of the parent group under the VO.
*
* @param sess
* @param parentGroup parent group
*
* @return list of groups
* @throws InternalErrorException
*/
List<Group> getSubGroups(PerunSession sess, Group parentGroup) throws InternalErrorException;
/**
* Get all subgroups of the parentGroup recursively.
* (parentGroup subgroups, their subgroups etc...)
*
* @param sess
* @param parentGroup parent group
*
* @return list of groups
* @throws InternalErrorException
*/
List<Group> getAllSubGroups(PerunSession sess, Group parentGroup) throws InternalErrorException;
/**
* Adds an administrator of the group.
*
* @param perunSession
* @param group
* @param user
*
* @throws InternalErrorException
* @throws AlreadyAdminException
*/
void addAdmin(PerunSession perunSession, Group group, User user) throws InternalErrorException, AlreadyAdminException;
/**
* Adds a group administrator to the group.
*
* @param perunSession
* @param group - group that will be assigned admins (users) from authorizedGroup
* @param authorizedGroup - group that will be given the privilege
*
* @throws InternalErrorException
* @throws AlreadyAdminException
*/
void addAdmin(PerunSession perunSession, Group group, Group authorizedGroup) throws InternalErrorException, AlreadyAdminException;
/**
* Removes an administrator form the group.
*
* @param perunSession
* @param group
* @param user
*
* @throws InternalErrorException
* @throws UserNotAdminException
*/
void removeAdmin(PerunSession perunSession, Group group, User user) throws InternalErrorException, UserNotAdminException;
/**
* Removes a group administrator of the group.
*
* @param perunSession
* @param group
* @param authorizedGroup group that will be removed the privilege
*
* @throws InternalErrorException
* @throws GroupNotAdminException
*/
void removeAdmin(PerunSession perunSession, Group group, Group authorizedGroup) throws InternalErrorException, GroupNotAdminException;
/**
* Get list of all user administrators for supported role and specific group.
*
* If onlyDirectAdmins is true, return only direct users of the group for supported role.
*
* Supported roles: GroupAdmin
*
* @param perunSession
* @param group
* @param onlyDirectAdmins if true, get only direct user administrators (if false, get both direct and indirect)
*
* @return list of all user administrators of the given group for supported role
*
* @throws InternalErrorException
*/
List<User> getAdmins(PerunSession perunSession, Group group, boolean onlyDirectAdmins) throws InternalErrorException;
/**
* Get list of all richUser administrators for the group and supported role with specific attributes.
*
* Supported roles: GroupAdmin
*
* If "onlyDirectAdmins" is "true", return only direct users of the group for supported role with specific attributes.
* If "allUserAttributes" is "true", do not specify attributes through list and return them all in objects richUser. Ignoring list of specific attributes.
*
* @param perunSession
* @param group
*
* @param specificAttributes list of specified attributes which are needed in object richUser
* @param allUserAttributes if true, get all possible user attributes and ignore list of specificAttributes (if false, get only specific attributes)
* @param onlyDirectAdmins if true, get only direct user administrators (if false, get both direct and indirect)
*
* @return list of RichUser administrators for the group and supported role with attributes
*
* @throws InternalErrorException
* @throws UserNotExistsException
*/
List<RichUser> getRichAdmins(PerunSession perunSession, Group group, List<String> specificAttributes, boolean allUserAttributes, boolean onlyDirectAdmins) throws InternalErrorException, UserNotExistsException;
/**
* Gets list of all user administrators of this group.
* If some group is administrator of the given group, all members are included in the list.
*
* @param perunSession
* @param group
*
* @throws InternalErrorException
*
* @return list of administrators
*/
@Deprecated
List<User> getAdmins(PerunSession perunSession, Group group) throws InternalErrorException;
/**
* Gets list of direct user administrators of this group.
* 'Direct' means, there aren't included users, who are members of group administrators, in the returned list.
*
* @param perunSession
* @param group
*
* @throws InternalErrorException
*
* @return list of direct administrators
*/
@Deprecated
List<User> getDirectAdmins(PerunSession perunSession, Group group) throws InternalErrorException;
/**
* Gets list of all group administrators of this group.
*
* @param perunSession
* @param group
*
* @throws InternalErrorException
*
* @return list of group administrators
*/
List<Group> getAdminGroups(PerunSession perunSession, Group group) throws InternalErrorException;
/**
* Gets list of all administrators of this group like RichUsers without attributes.
*
* @param perunSession
* @param group
*
* @throws InternalErrorException
* @throws UserNotExistsException
*/
@Deprecated
List<RichUser> getRichAdmins(PerunSession perunSession, Group group) throws InternalErrorException, UserNotExistsException;
/**
* Gets list of all administrators of this group, which are assigned directly, like RichUsers without attributes.
*
* @param perunSession
* @param group
*
* @throws InternalErrorException
* @throws UserNotExistsException
*/
@Deprecated
List<RichUser> getDirectRichAdmins(PerunSession perunSession, Group group) throws InternalErrorException, UserNotExistsException;
/**
* Gets list of all administrators of this group like RichUsers with attributes.
*
* @param perunSession
* @param group
*
* @throws InternalErrorException
* @throws UserNotExistsException
*/
@Deprecated
List<RichUser> getRichAdminsWithAttributes(PerunSession perunSession, Group group) throws InternalErrorException, UserNotExistsException;
/**
* Get list of Group administrators with specific attributes.
* From list of specificAttributes get all Users Attributes and find those for every RichAdmin (only, other attributes are not searched)
*
* @param perunSession
* @param group
* @param specificAttributes
* @return list of RichUsers with specific attributes.
* @throws InternalErrorException
* @throws UserNotExistsException
*/
@Deprecated
List<RichUser> getRichAdminsWithSpecificAttributes(PerunSession perunSession, Group group, List<String> specificAttributes) throws InternalErrorException, UserNotExistsException;
/**
* Get list of Group administrators, which are directly assigned (not by group membership) with specific attributes.
* From list of specificAttributes get all Users Attributes and find those for every RichAdmin (only, other attributes are not searched)
*
* @param perunSession
* @param group
* @param specificAttributes
* @return list of RichUsers with specific attributes.
* @throws InternalErrorException
* @throws UserNotExistsException
*/
@Deprecated
List<RichUser> getDirectRichAdminsWithSpecificAttributes(PerunSession perunSession, Group group, List<String> specificAttributes) throws InternalErrorException, UserNotExistsException;
/**
* Get all groups of users under the VO.
*
* @param sess
* @param vo vo
*
* @throws InternalErrorException
*
* @return list of groups
*/
List<Group> getGroups(PerunSession sess, Vo vo) throws InternalErrorException;
/**
* Get groups by theirs Id.
*
* @param sess
* @param groupsIds
* @return list of groups
* @throws InternalErrorException
*/
List<Group> getGroupsByIds(PerunSession sess, List<Integer> groupsIds) throws InternalErrorException;
/**
* @param sess
* @param vo
*
* @return count of VO's groups
*
* @throws InternalErrorException
*/
int getGroupsCount(PerunSession sess, Vo vo) throws InternalErrorException;
/**
* Get count of all groups.
*
* @param perunSession
*
* @return count of all groups
*
* @throws InternalErrorException
*/
int getGroupsCount(PerunSession perunSession) throws InternalErrorException;
/**
* Returns number of immediate subgroups of the parent group.
*
* @param sess
* @param parentGroup
*
* @return count of parent group immediate subgroups
*
* @throws InternalErrorException
*/
int getSubGroupsCount(PerunSession sess, Group parentGroup) throws InternalErrorException;
/**
* Gets the Vo which is owner of the group.
*
* @param sess
* @param group
*
* @return Vo which is owner of the group.
*
* @throws InternalErrorException
*/
Vo getVo(PerunSession sess, Group group) throws InternalErrorException;
/**
* Get members from parent group. If the parent group doesn't exist (this is top level group) return all VO (from which the group is) members instead.
*
* @param sess
* @param group
* @return
*
* @throws InternalErrorException
*/
List<Member> getParentGroupMembers(PerunSession sess, Group group) throws InternalErrorException;
/**
* Get members form the parent group in RichMember format.
* @param sess
* @param group
* @return list of parent group rich members
* @throws InternalErrorException
*/
List<RichMember> getParentGroupRichMembers(PerunSession sess, Group group) throws InternalErrorException;
/**
* Get members form the parent group in RichMember format including user/member attributes.
* @param sess
* @param group
* @return list of parent group rich members
* @throws InternalErrorException
*/
List<RichMember> getParentGroupRichMembersWithAttributes(PerunSession sess, Group group) throws InternalErrorException;
/**
* Synchronizes the group with the external group without checking if the synchronization is already in progress.
* If some members from extSource of this group were skipped, return info about them.
* if not, return empty string instead, which means all members was successfully load from extSource.
*
* @param sess
* @param group
* @return List of strings with skipped users with reasons why were skipped
* @throws InternalErrorException
* @throws MemberAlreadyRemovedException
* @throws AttributeNotExistsException
* @throws WrongAttributeAssignmentException
* @throws ExtSourceNotExistsException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
* @throws GroupOperationsException
* @throws NotMemberOfParentGroupException
* @throws GroupNotExistsException
*/
List<String> synchronizeGroup(PerunSession sess, Group group) throws InternalErrorException, MemberAlreadyRemovedException, AttributeNotExistsException, WrongAttributeAssignmentException, ExtSourceNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, GroupOperationsException, NotMemberOfParentGroupException, GroupNotExistsException;
/**
* Synchronize the group with external group. It checks if the synchronization of the same group is already in progress.
*
* @param sess
* @param group
* @throws InternalErrorException
* @throws GroupSynchronizationAlreadyRunningException
*/
void forceGroupSynchronization(PerunSession sess, Group group) throws InternalErrorException, GroupSynchronizationAlreadyRunningException;
/**
* Synchronize all groups which have enabled synchronization. This method is run by the scheduler every 5 minutes.
*
* @throws InternalErrorException
*/
void synchronizeGroups(PerunSession sess) throws InternalErrorException;
/**
* Returns all members groups. Except 'members' group.
*
* @param sess
* @param member
* @return
* @throws InternalErrorException
*/
List<Group> getMemberGroups(PerunSession sess, Member member) throws InternalErrorException;
/**
* Get all groups (except member groups) where member has direct membership.
*
* @param sess
* @param member to get information about
* @return list of groups where member is direct member (not members group), empty list if there is no such group
* @throws InternalErrorException
*/
List<Group> getMemberDirectGroups(PerunSession sess, Member member) throws InternalErrorException;
/**
* Method return list of groups for selected member which (groups) has set specific attribute.
* Attribute can be only from namespace "GROUP"
*
* @param sess sess
* @param member member
* @param attribute attribute from "GROUP" namespace
*
* @return list of groups which contain member and have attribute with same value
*
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Group> getMemberGroupsByAttribute(PerunSession sess, Member member, Attribute attribute) throws WrongAttributeAssignmentException, InternalErrorException;
/**
* Return all member's groups. Included members and administrators groups.
*
* @param sess
* @param member
* @return
* @throws InternalErrorException
*/
List<Group> getAllMemberGroups(PerunSession sess, Member member) throws InternalErrorException;
/**
* Returns all groups which have set the attribute with the value. Searching only def and opt attributes.
*
* @param sess
* @param attribute
* @return list of groups
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Group> getGroupsByAttribute(PerunSession sess, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Returns all group-resource which have set the attribute with the value. Searching only def and opt attributes.
*
* @param sess
* @param attribute
* @return
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Pair<Group, Resource>> getGroupResourcePairsByAttribute(PerunSession sess, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Return true if Member is member of the Group
*
*
* @param sess
* @param group
* @param member
* @return true if Member is member of the Group
*
* @throws InternalErrorException
*/
boolean isGroupMember(PerunSession sess, Group group, Member member) throws InternalErrorException;
/**
* !!! Not Complete yet, need to implement all perunBeans !!!
*
* Get perunBean and try to find all connected Groups
*
* @param sess
* @param perunBean
* @return list of groups connected with perunBeans
* @throws InternalErrorException
*/
List<Group> getGroupsByPerunBean(PerunSession sess, PerunBean perunBean) throws InternalErrorException;
void checkGroupExists(PerunSession sess, Group group) throws InternalErrorException, GroupNotExistsException;
/**
* This method take list of members (also with duplicit) and:
* 1] add all members with direct membership to target list
* 2] add all members with indirect membership who are not already in target list to the target list
*
* @param members list of members to filtering
* @return filteredMembers list of members without duplicit after filtering
*/
List<Member> filterMembersByMembershipTypeInGroup(List<Member> members) throws InternalErrorException;
/**
* For richGroup filter all his group attributes and remove all which principal has no access to.
*
* @param sess
* @param richGroup
* @return richGroup with only allowed attributes
* @throws InternalErrorException
*/
RichGroup filterOnlyAllowedAttributes(PerunSession sess, RichGroup richGroup) throws InternalErrorException;
/**
* For list of richGroups filter all their group attributes and remove all which principal has no access to.
*
* @param sess
* @param richGroups
* @return list of RichGroups with only allowed attributes
* @throws InternalErrorException
*/
List<RichGroup> filterOnlyAllowedAttributes(PerunSession sess, List<RichGroup> richGroups) throws InternalErrorException;
/**
* This method takes group and creates RichGroup containing all attributes
*
* @param sess
* @param group
* @return RichGroup
* @throws InternalErrorException
*/
RichGroup convertGroupToRichGroupWithAttributes(PerunSession sess, Group group) throws InternalErrorException;
/**
* This method takes group and creates RichGroup containing selected attributes
*
* @param sess
* @param group
* @param attrNames list of selected attributes
* @return RichGroup
* @throws InternalErrorException
*/
RichGroup convertGroupToRichGroupWithAttributesByName(PerunSession sess, Group group, List<String> attrNames) throws InternalErrorException;
/**
* This method takes list of groups and creates list of RichGroups containing all attributes
*
* @param sess
* @param groups list of groups
* @return RichGroup
* @throws InternalErrorException
*/
List<RichGroup> convertGroupsToRichGroupsWithAttributes(PerunSession sess, List<Group> groups) throws InternalErrorException;
/**
* This method takes list of groups and creates list of RichGroups containing selected attributes
*
* @param sess
* @param groups list of groups
* @param attrNames list of selected attributes
* @return RichGroup
* @throws InternalErrorException
*/
List<RichGroup> convertGroupsToRichGroupsWithAttributes(PerunSession sess, List<Group> groups, List<String> attrNames) throws InternalErrorException;
/**
* Returns all RichGroups containing selected attributes
*
* @param sess
* @param vo
* @param attrNames if attrNames is null method will return RichGroups containing all attributes
* @return List of RichGroups
* @throws InternalErrorException
*/
List<RichGroup> getAllRichGroupsWithAttributesByNames(PerunSession sess, Vo vo, List<String> attrNames) throws InternalErrorException;
/**
* Returns RichSubGroups from parentGroup containing selected attributes (only 1 level subgroups)
*
* @param sess
* @param parentGroup
* @param attrNames if attrNames is null method will return RichGroups containing all attributes
* @return List of RichGroups
* @throws InternalErrorException
*/
List<RichGroup> getRichSubGroupsWithAttributesByNames(PerunSession sess, Group parentGroup, List<String> attrNames) throws InternalErrorException;
/**
* Returns all RichSubGroups from parentGroup containing selected attributes (all levels subgroups)
*
* @param sess
* @param parentGroup
* @param attrNames if attrNames is null method will return RichGroups containing all attributes
* @return List of RichGroups
* @throws InternalErrorException
*/
List<RichGroup> getAllRichSubGroupsWithAttributesByNames(PerunSession sess, Group parentGroup, List<String> attrNames) throws InternalErrorException;
/**
* Returns RichGroup selected by id containing selected attributes
*
* @param sess
* @param groupId
* @param attrNames if attrNames is null method will return RichGroup containing all attributes
* @return RichGroup
* @throws InternalErrorException
* @throws GroupNotExistsException
*/
RichGroup getRichGroupByIdWithAttributesByNames(PerunSession sess, int groupId, List<String> attrNames) throws InternalErrorException, GroupNotExistsException;
/**
* This method will set timestamp and exceptionMessage to group attributes for the group.
* Also log information about failed synchronization to auditer_log.
*
* IMPORTANT: This method runs in new transaction (because of using in synchronization of groups)
*
* Set timestamp to attribute "group_def_lastSynchronizationTimestamp"
* Set exception message to attribute "group_def_lastSynchronizationState"
*
* FailedDueToException is true means group synchronization failed at all.
* FailedDueToException is false means group synchronization is ok or finished with some errors (some members were not synchronized)
*
* @param sess perun session
* @param group the group for synchronization
* @param failedDueToException if exception means fail of whole synchronization of this group or only problem with some data
* @param exceptionMessage message of an exception, ok if everything is ok
* @throws AttributeNotExistsException
* @throws InternalErrorException
* @throws WrongReferenceAttributeValueException
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
*/
void saveInformationAboutGroupSynchronization(PerunSession sess, Group group, boolean failedDueToException, String exceptionMessage) throws AttributeNotExistsException, InternalErrorException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException, WrongAttributeValueException;
/**
* Get all groups in specific vo with assigned extSource
*
* @param sess
* @param source
* @param vo
* @return l
* @throws InternalErrorException
*/
List<Group> getGroupsWithAssignedExtSourceInVo(PerunSession sess, ExtSource source, Vo vo) throws InternalErrorException;
/**
* Method recalculates all relations between groups. Based on <code>addition</code> parameter
* it recursively adds or removes members from groups and all their relations. The method is called in case of:
* 1) added or removed relation
* 2) added or removed member
* 3) group creation
* 4) group removal
*
* @param sess perun session
* @param resultGroup group to which members are added or removed from
* @param changedMembers list of changed members which is passed as argument to add/remove indirect members method.
* Based on these two types of operations the list contains:
* 1) adding indirect (<code>addition</code> true) - records of added indirect members from operand group.
* 2) removing indirect (<code>addition</code> false) - records of removed indirect members from operand group.
*
* @param sourceGroupId id of a group from which members originate
* @param addition if true member records are added; if false member records are removed
* @throws GroupOperationsException when any error occurs which prevent operation to finish.
*/
void processRelationMembers(PerunSession sess, Group resultGroup, List<Member> changedMembers, int sourceGroupId, boolean addition) throws GroupOperationsException;
/**
* Performs union operation on two groups. Members from operand group are added to result group as indirect.
*
* @param sess perun session
* @param resultGroup group to which members are added
* @param operandGroup group from which members are taken
* @param parentFlag if true union cannot be deleted; false otherwise (it flags relations created by hierarchical structure)
* @return result group
*
* @throws GroupOperationsException
* @throws GroupRelationAlreadyExists
* @throws GroupRelationNotAllowed
* @throws InternalErrorException
*/
Group createGroupUnion(PerunSession sess, Group resultGroup, Group operandGroup, boolean parentFlag) throws GroupOperationsException, InternalErrorException, GroupRelationAlreadyExists, GroupRelationNotAllowed;
/**
* Removes a union relation between two groups. All indirect members that originate from operand group are removed from result group.
*
* @param sess perun session
* @param resultGroup group from which members are removed
* @param operandGroup group which members are removed from result group
* @param parentFlag if true union cannot be deleted; false otherwise (it flags relations created by hierarchical structure)
*
* @throws GroupOperationsException
* @throws GroupRelationDoesNotExist
* @throws GroupRelationCannotBeRemoved
* @throws InternalErrorException
*/
void removeGroupUnion(PerunSession sess, Group resultGroup, Group operandGroup, boolean parentFlag) throws GroupOperationsException, InternalErrorException, GroupRelationDoesNotExist, GroupRelationCannotBeRemoved;
/**
* Get list of group unions for specified group.
* @param sess perun session
* @param group group
* @param reverseDirection if false get all operand groups of requested result group
* if true get all result groups of requested operand group
* @return list of groups.
*
* @throws InternalErrorException
*/
List<Group> getGroupUnions(PerunSession sess, Group group, boolean reverseDirection) throws InternalErrorException;
}
| |
/*
* Copyright 2012 - 2015 Manuel Laggner
*
* 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.tinymediamanager.ui.tvshows;
import static org.tinymediamanager.core.Constants.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.tinymediamanager.core.tvshow.TvShowList;
import org.tinymediamanager.core.tvshow.entities.TvShow;
import org.tinymediamanager.core.tvshow.entities.TvShowEpisode;
import org.tinymediamanager.core.tvshow.entities.TvShowSeason;
import org.tinymediamanager.ui.tvshows.TvShowExtendedMatcher.SearchOptions;
/**
* The Class TvShowTreeModel.
*
* @author Manuel Laggner
*/
public class TvShowTreeModel implements TreeModel {
private TvShowRootTreeNode root = new TvShowRootTreeNode();
private List<TreeModelListener> listeners = new ArrayList<TreeModelListener>();
private Map<Object, TreeNode> nodeMap = Collections.synchronizedMap(new HashMap<Object, TreeNode>());
private TvShowList tvShowList = TvShowList.getInstance();
private PropertyChangeListener propertyChangeListener;
private TvShowExtendedMatcher matcher = new TvShowExtendedMatcher();
/**
* Instantiates a new tv show tree model.
*
* @param tvShows
* the tv shows
*/
public TvShowTreeModel(List<TvShow> tvShows) {
// create the listener
propertyChangeListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
// added a tv show
if (ADDED_TV_SHOW.equals(evt.getPropertyName()) && evt.getNewValue() instanceof TvShow) {
TvShow tvShow = (TvShow) evt.getNewValue();
addTvShow(tvShow);
}
// removed a tv show
if (REMOVED_TV_SHOW.equals(evt.getPropertyName()) && evt.getNewValue() instanceof TvShow) {
TvShow tvShow = (TvShow) evt.getNewValue();
removeTvShow(tvShow);
}
// added a season
if (ADDED_SEASON.equals(evt.getPropertyName()) && evt.getNewValue() instanceof TvShowSeason) {
TvShowSeason season = (TvShowSeason) evt.getNewValue();
// need to lock it here, because of nested calls
synchronized (root) {
addTvShowSeason(season, season.getTvShow());
}
}
// added an episode
if (ADDED_EPISODE.equals(evt.getPropertyName()) && evt.getNewValue() instanceof TvShowEpisode) {
TvShowEpisode episode = (TvShowEpisode) evt.getNewValue();
addTvShowEpisode(episode, episode.getTvShow().getSeasonForEpisode(episode));
}
// removed an episode
if (REMOVED_EPISODE.equals(evt.getPropertyName()) && evt.getNewValue() instanceof TvShowEpisode) {
TvShowEpisode episode = (TvShowEpisode) evt.getNewValue();
removeTvShowEpisode(episode);
}
// changed the season of an episode
if (SEASON.equals(evt.getPropertyName()) && evt.getSource() instanceof TvShowEpisode) {
// simply remove it from the tree and readd it
TvShowEpisode episode = (TvShowEpisode) evt.getSource();
removeTvShowEpisode(episode);
addTvShowEpisode(episode, episode.getTvShow().getSeasonForEpisode(episode));
}
// update on changes of tv show
if (evt.getSource() instanceof TvShow
&& (TITLE.equals(evt.getPropertyName()) || HAS_NFO_FILE.equals(evt.getPropertyName()) || HAS_IMAGES.equals(evt.getPropertyName()))) {
// inform listeners (root - to update the sum)
TreeModelEvent event = new TreeModelEvent(this, root.getPath(), null, null);
for (TreeModelListener listener : listeners) {
listener.treeNodesChanged(event);
}
}
// update on changes of episode
if (evt.getSource() instanceof TvShowEpisode) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodeMap.get(evt.getSource());
if (node != null) {
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
int index = parent.getIndex(node);
if (index >= 0) {
TreeModelEvent event = new TreeModelEvent(this, parent.getPath(), new int[] { index }, new Object[] { node });
for (TreeModelListener listener : listeners) {
try {
listener.treeNodesChanged(event);
}
catch (Exception e) {
}
}
}
}
}
}
};
// install a property change listener to the TvShowList
tvShowList.addPropertyChangeListener(propertyChangeListener);
// build initial tree
for (TvShow tvShow : tvShows) {
addTvShow(tvShow);
}
}
/**
* Adds the tv show.
*
* @param tvShow
* the tv show
*/
private void addTvShow(TvShow tvShow) {
synchronized (root) {
DefaultMutableTreeNode tvShowNode = new TvShowTreeNode(tvShow);
root.add(tvShowNode);
nodeMap.put(tvShow, tvShowNode);
for (TvShowSeason season : new ArrayList<TvShowSeason>(tvShow.getSeasons())) {
// check if there is a node for its season
TvShowSeasonTreeNode seasonNode = (TvShowSeasonTreeNode) nodeMap.get(season);
if (seasonNode == null) {
addTvShowSeason(season, tvShow);
}
for (TvShowEpisode episode : new ArrayList<TvShowEpisode>(season.getEpisodes())) {
addTvShowEpisode(episode, season);
}
}
int index = getIndexOfChild(root, tvShowNode);
// inform listeners
if (index > -1) {
TreeModelEvent event = new TreeModelEvent(this, root.getPath(), new int[] { index }, new Object[] { tvShow });
for (TreeModelListener listener : listeners) {
listener.treeNodesInserted(event);
}
}
}
tvShow.addPropertyChangeListener(propertyChangeListener);
}
/**
* Removes the tv show.
*
* @param tvShow
* the tv show
*/
private void removeTvShow(TvShow tvShow) {
synchronized (root) {
TvShowTreeNode child = (TvShowTreeNode) nodeMap.get(tvShow);
DefaultMutableTreeNode parent = root;
if (child != null) {
int index = getIndexOfChild(parent, child);
nodeMap.remove(tvShow);
for (TvShowEpisode episode : new ArrayList<TvShowEpisode>(tvShow.getEpisodes())) {
nodeMap.remove(episode);
episode.removePropertyChangeListener(propertyChangeListener);
}
tvShow.removePropertyChangeListener(propertyChangeListener);
child.removeAllChildren();
child.removeFromParent();
// inform listeners
if (index > -1) {
TreeModelEvent event = new TreeModelEvent(this, parent.getPath(), new int[] { index }, new Object[] { child });
for (TreeModelListener listener : listeners) {
listener.treeNodesRemoved(event);
}
}
}
}
}
/**
* Adds the tv show season.
*
* @param season
* the season
* @param tvShow
* the tv show
*/
private void addTvShowSeason(TvShowSeason season, TvShow tvShow) {
// since we can call this from addEpisode, we have to lock it at calling
// synchronized (root) {
// get the tv show node
TvShowTreeNode parent = (TvShowTreeNode) nodeMap.get(tvShow);
TvShowSeasonTreeNode child = new TvShowSeasonTreeNode(season);
if (parent != null) {
parent.add(child);
nodeMap.put(season, child);
int index = getIndexOfChild(parent, child);
// inform listeners (tv show)
if (index > -1) {
TreeModelEvent event = new TreeModelEvent(this, parent.getPath(), new int[] { index }, new Object[] { child });
for (TreeModelListener listener : listeners) {
listener.treeNodesInserted(event);
}
}
// inform listeners (root - to update the sum)
TreeModelEvent event = new TreeModelEvent(this, root.getPath(), null, null);
for (TreeModelListener listener : listeners) {
listener.treeNodesChanged(event);
}
}
// }
}
/**
* Adds the tv show episode.
*
* @param episode
* the episode
* @param season
* the season
*/
private void addTvShowEpisode(TvShowEpisode episode, TvShowSeason season) {
synchronized (root) {
// get the tv show season node
TvShowSeasonTreeNode parent = (TvShowSeasonTreeNode) nodeMap.get(season);
// no parent (season) here - recreate it
if (parent == null) {
addTvShowSeason(season, episode.getTvShow());
parent = (TvShowSeasonTreeNode) nodeMap.get(season);
}
TvShowEpisodeTreeNode child = new TvShowEpisodeTreeNode(episode);
if (parent != null) {
parent.add(child);
nodeMap.put(episode, child);
int index = getIndexOfChild(parent, child);
// inform listeners
if (index > -1) {
TreeModelEvent event = new TreeModelEvent(this, parent.getPath(), new int[] { index }, new Object[] { child });
for (TreeModelListener listener : listeners) {
listener.treeNodesInserted(event);
}
}
// inform listeners (root - to update the sum)
TreeModelEvent event = new TreeModelEvent(this, root.getPath(), null, null);
for (TreeModelListener listener : listeners) {
listener.treeNodesChanged(event);
}
}
}
episode.addPropertyChangeListener(propertyChangeListener);
}
/**
* Removes the tv show episode.
*
* @param episode
* the episode
* @param season
* the season
*/
private void removeTvShowEpisode(TvShowEpisode episode) {
synchronized (root) {
// get the tv show season node
TvShowEpisodeTreeNode child = (TvShowEpisodeTreeNode) nodeMap.get(episode);
TvShowSeasonTreeNode parent = null;
if (child != null) {
parent = (TvShowSeasonTreeNode) child.getParent();
}
if (parent != null && child != null) {
int index = getIndexOfChild(parent, child);
parent.remove(child);
nodeMap.remove(episode);
episode.removePropertyChangeListener(propertyChangeListener);
// inform listeners
if (index > -1) {
TreeModelEvent event = new TreeModelEvent(this, parent.getPath(), new int[] { index }, new Object[] { child });
for (TreeModelListener listener : listeners) {
listener.treeNodesRemoved(event);
}
}
// remove tv show if there is no more episode in it
if (parent.getChildCount() == 0) {
TvShowSeason season = null;
for (Entry<Object, TreeNode> entry : nodeMap.entrySet()) {
if (entry.getValue() == parent) {
season = (TvShowSeason) entry.getKey();
}
}
if (season != null) {
removeTvShowSeason(season);
}
}
}
}
}
/**
* Removes the tv show season.
*
* @param season
* the season
*/
private void removeTvShowSeason(TvShowSeason season) {
synchronized (root) {
TvShowSeasonTreeNode child = (TvShowSeasonTreeNode) nodeMap.get(season);
TvShowTreeNode parent = null;
if (child != null) {
parent = (TvShowTreeNode) child.getParent();
}
if (parent != null && child != null) {
int index = getIndexOfChild(parent, child);
parent.remove(child);
nodeMap.remove(season);
// inform listeners
if (index > -1) {
TreeModelEvent event = new TreeModelEvent(this, parent.getPath(), new int[] { index }, new Object[] { child });
for (TreeModelListener listener : listeners) {
listener.treeNodesRemoved(event);
}
}
}
}
}
@Override
public void addTreeModelListener(TreeModelListener listener) {
listeners.add(listener);
}
@Override
public Object getChild(Object parent, int index) {
int count = 0;
int childCount = getChildCountInternal(parent);
for (int i = 0; i < childCount; i++) {
Object child = getChildInternal(parent, i);
if (matches(child)) {
if (count == index) {
return child;
}
count++;
}
}
return null;
}
@Override
public int getChildCount(Object parent) {
int count = 0;
int childCount = getChildCountInternal(parent);
for (int i = 0; i < childCount; i++) {
Object child = getChildInternal(parent, i);
if (matches(child)) {
count++;
}
}
return count;
}
@Override
public int getIndexOfChild(Object parent, Object childToFind) {
int childCount = getChildCountInternal(parent);
for (int i = 0; i < childCount; i++) {
Object child = getChildInternal(parent, i);
if (matches(child)) {
if (childToFind.equals(child)) {
return i;
}
}
}
return -1;
}
private boolean matches(Object node) {
Object bean = null;
if (node instanceof TvShowTreeNode) {
bean = (TvShow) ((TvShowTreeNode) node).getUserObject();
}
// if the node is a TvShowSeasonNode, we have to check the parent TV show and its episodes
if (node instanceof TvShowSeasonTreeNode) {
bean = (TvShowSeason) ((TvShowSeasonTreeNode) node).getUserObject();
}
// if the node is a TvShowEpisodeNode, we have to check the parent TV show and the episode
if (node instanceof TvShowEpisodeTreeNode) {
bean = (TvShowEpisode) ((TvShowEpisodeTreeNode) node).getUserObject();
}
if (bean == null) {
return true;
}
return matcher.matches(bean);
}
@Override
public Object getRoot() {
return root;
}
@Override
public boolean isLeaf(Object node) {
// root is never a leaf
if (node == root) {
return false;
}
if (node instanceof TvShowTreeNode || node instanceof TvShowSeasonTreeNode) {
return false;
}
if (node instanceof TvShowEpisodeTreeNode) {
return true;
}
return getChildCount(node) == 0;
}
@Override
public void removeTreeModelListener(TreeModelListener listener) {
listeners.remove(listener);
}
@Override
public void valueForPathChanged(TreePath arg0, Object arg1) {
}
private int getChildCountInternal(Object node) {
if (node == null) {
return 0;
}
return ((TreeNode) node).getChildCount();
}
private Object getChildInternal(Object parent, int index) {
return ((TreeNode) parent).getChildAt(index);
}
public void setFilter(SearchOptions option, Object filterArg) {
if (matcher.searchOptions.containsKey(option)) {
matcher.searchOptions.remove(option);
}
matcher.searchOptions.put(option, filterArg);
}
public void removeFilter(SearchOptions option) {
if (matcher.searchOptions.containsKey(option)) {
matcher.searchOptions.remove(option);
}
}
public void filter(JTree tree) {
TreePath selection = tree.getSelectionPath();
List<TreePath> currOpen = getCurrExpandedPaths(tree);
reload();
reExpandPaths(tree, currOpen);
restoreSelection(selection, tree);
}
private List<TreePath> getCurrExpandedPaths(JTree tree) {
List<TreePath> paths = new ArrayList<TreePath>();
Enumeration<TreePath> expandEnum = tree.getExpandedDescendants(new TreePath(root.getPath()));
if (expandEnum == null) {
return null;
}
while (expandEnum.hasMoreElements()) {
paths.add(expandEnum.nextElement());
}
return paths;
}
private void reExpandPaths(JTree tree, List<TreePath> expPaths) {
if (expPaths == null) {
return;
}
for (TreePath tp : expPaths) {
tree.expandPath(tp);
}
}
private void reload() {
TreeModelEvent event = new TreeModelEvent(this, root.getPath(), null, null);
for (TreeModelListener listener : listeners) {
listener.treeStructureChanged(event);
}
}
private void restoreSelection(TreePath path, JTree tree) {
if (path != null) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode) path.getLastPathComponent();
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) child.getParent();
if (getIndexOfChild(parent, child) > -1) {
tree.setSelectionPath(path);
return;
}
}
// search first valid node to select
DefaultMutableTreeNode root = (DefaultMutableTreeNode) getRoot();
for (int i = 0; i < root.getChildCount(); i++) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode) root.getChildAt(i);
if (getIndexOfChild(root, child) > -1) {
tree.setSelectionPath(new TreePath(child.getPath()));
break;
}
}
}
}
| |
/**
*
* Copyright 2016-2021, Optimizely and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.optimizely.ab.config.parser;
import com.optimizely.ab.config.*;
import com.optimizely.ab.config.Experiment.ExperimentStatus;
import com.optimizely.ab.config.audience.Audience;
import com.optimizely.ab.config.audience.AudienceIdCondition;
import com.optimizely.ab.config.audience.Condition;
import com.optimizely.ab.config.audience.UserAttribute;
import com.optimizely.ab.internal.ConditionUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import javax.annotation.Nonnull;
import java.util.*;
/**
* {@code org.json}-based config parser implementation.
*/
final public class JsonConfigParser implements ConfigParser {
@Override
public ProjectConfig parseProjectConfig(@Nonnull String json) throws ConfigParseException {
try {
JSONObject rootObject = new JSONObject(json);
String accountId = rootObject.getString("accountId");
String projectId = rootObject.getString("projectId");
String revision = rootObject.getString("revision");
String version = rootObject.getString("version");
int datafileVersion = Integer.parseInt(version);
List<Experiment> experiments = parseExperiments(rootObject.getJSONArray("experiments"));
List<Attribute> attributes;
attributes = parseAttributes(rootObject.getJSONArray("attributes"));
List<EventType> events = parseEvents(rootObject.getJSONArray("events"));
List<Audience> audiences = Collections.emptyList();
if (rootObject.has("audiences")) {
audiences = parseAudiences(rootObject.getJSONArray("audiences"));
}
List<Audience> typedAudiences = null;
if (rootObject.has("typedAudiences")) {
typedAudiences = parseTypedAudiences(rootObject.getJSONArray("typedAudiences"));
}
List<Group> groups = parseGroups(rootObject.getJSONArray("groups"));
boolean anonymizeIP = false;
if (datafileVersion >= Integer.parseInt(ProjectConfig.Version.V3.toString())) {
anonymizeIP = rootObject.getBoolean("anonymizeIP");
}
List<FeatureFlag> featureFlags = null;
List<Rollout> rollouts = null;
String sdkKey = null;
String environmentKey = null;
Boolean botFiltering = null;
boolean sendFlagDecisions = false;
if (datafileVersion >= Integer.parseInt(ProjectConfig.Version.V4.toString())) {
featureFlags = parseFeatureFlags(rootObject.getJSONArray("featureFlags"));
rollouts = parseRollouts(rootObject.getJSONArray("rollouts"));
if (rootObject.has("sdkKey"))
sdkKey = rootObject.getString("sdkKey");
if (rootObject.has("environmentKey"))
environmentKey = rootObject.getString("environmentKey");
if (rootObject.has("botFiltering"))
botFiltering = rootObject.getBoolean("botFiltering");
if (rootObject.has("sendFlagDecisions"))
sendFlagDecisions = rootObject.getBoolean("sendFlagDecisions");
}
return new DatafileProjectConfig(
accountId,
anonymizeIP,
sendFlagDecisions,
botFiltering,
projectId,
revision,
sdkKey,
environmentKey,
version,
attributes,
audiences,
typedAudiences,
events,
experiments,
featureFlags,
groups,
rollouts
);
} catch (RuntimeException e) {
throw new ConfigParseException("Unable to parse datafile: " + json, e);
} catch (Exception e) {
throw new ConfigParseException("Unable to parse datafile: " + json, e);
}
}
//======== Helper methods ========//
private List<Experiment> parseExperiments(JSONArray experimentJson) {
return parseExperiments(experimentJson, "");
}
private List<Experiment> parseExperiments(JSONArray experimentJson, String groupId) {
List<Experiment> experiments = new ArrayList<Experiment>(experimentJson.length());
for (int i = 0; i < experimentJson.length(); i++) {
Object obj = experimentJson.get(i);
JSONObject experimentObject = (JSONObject) obj;
String id = experimentObject.getString("id");
String key = experimentObject.getString("key");
String status = experimentObject.isNull("status") ?
ExperimentStatus.NOT_STARTED.toString() : experimentObject.getString("status");
String layerId = experimentObject.has("layerId") ? experimentObject.getString("layerId") : null;
JSONArray audienceIdsJson = experimentObject.getJSONArray("audienceIds");
List<String> audienceIds = new ArrayList<String>(audienceIdsJson.length());
for (int j = 0; j < audienceIdsJson.length(); j++) {
Object audienceIdObj = audienceIdsJson.get(j);
audienceIds.add((String) audienceIdObj);
}
Condition conditions = null;
if (experimentObject.has("audienceConditions")) {
Object jsonCondition = experimentObject.get("audienceConditions");
conditions = ConditionUtils.<AudienceIdCondition>parseConditions(AudienceIdCondition.class, jsonCondition);
}
// parse the child objects
List<Variation> variations = parseVariations(experimentObject.getJSONArray("variations"));
Map<String, String> userIdToVariationKeyMap =
parseForcedVariations(experimentObject.getJSONObject("forcedVariations"));
List<TrafficAllocation> trafficAllocations =
parseTrafficAllocation(experimentObject.getJSONArray("trafficAllocation"));
experiments.add(new Experiment(id, key, status, layerId, audienceIds, conditions, variations, userIdToVariationKeyMap,
trafficAllocations, groupId));
}
return experiments;
}
private List<String> parseExperimentIds(JSONArray experimentIdsJson) {
ArrayList<String> experimentIds = new ArrayList<String>(experimentIdsJson.length());
for (int i = 0; i < experimentIdsJson.length(); i++) {
Object experimentIdObj = experimentIdsJson.get(i);
experimentIds.add((String) experimentIdObj);
}
return experimentIds;
}
private List<FeatureFlag> parseFeatureFlags(JSONArray featureFlagJson) {
List<FeatureFlag> featureFlags = new ArrayList<FeatureFlag>(featureFlagJson.length());
for (int i = 0; i < featureFlagJson.length();i++) {
Object obj = featureFlagJson.get(i);
JSONObject featureFlagObject = (JSONObject) obj;
String id = featureFlagObject.getString("id");
String key = featureFlagObject.getString("key");
String layerId = featureFlagObject.getString("rolloutId");
List<String> experimentIds = parseExperimentIds(featureFlagObject.getJSONArray("experimentIds"));
List<FeatureVariable> variables = parseFeatureVariables(featureFlagObject.getJSONArray("variables"));
featureFlags.add(new FeatureFlag(
id,
key,
layerId,
experimentIds,
variables
));
}
return featureFlags;
}
private List<Variation> parseVariations(JSONArray variationJson) {
List<Variation> variations = new ArrayList<Variation>(variationJson.length());
for (int i = 0; i < variationJson.length(); i++) {
Object obj = variationJson.get(i);
JSONObject variationObject = (JSONObject) obj;
String id = variationObject.getString("id");
String key = variationObject.getString("key");
Boolean featureEnabled = false;
if (variationObject.has("featureEnabled") && !variationObject.isNull("featureEnabled")) {
featureEnabled = variationObject.getBoolean("featureEnabled");
}
List<FeatureVariableUsageInstance> featureVariableUsageInstances = null;
if (variationObject.has("variables")) {
featureVariableUsageInstances =
parseFeatureVariableInstances(variationObject.getJSONArray("variables"));
}
variations.add(new Variation(id, key, featureEnabled, featureVariableUsageInstances));
}
return variations;
}
private Map<String, String> parseForcedVariations(JSONObject forcedVariationJson) {
Map<String, String> userIdToVariationKeyMap = new HashMap<String, String>();
Set<String> userIdSet = forcedVariationJson.keySet();
for (String userId : userIdSet) {
userIdToVariationKeyMap.put(userId, forcedVariationJson.get(userId).toString());
}
return userIdToVariationKeyMap;
}
private List<TrafficAllocation> parseTrafficAllocation(JSONArray trafficAllocationJson) {
List<TrafficAllocation> trafficAllocation = new ArrayList<TrafficAllocation>(trafficAllocationJson.length());
for (int i = 0; i < trafficAllocationJson.length();i++) {
Object obj = trafficAllocationJson.get(i);
JSONObject allocationObject = (JSONObject) obj;
String entityId = allocationObject.getString("entityId");
int endOfRange = allocationObject.getInt("endOfRange");
trafficAllocation.add(new TrafficAllocation(entityId, endOfRange));
}
return trafficAllocation;
}
private List<Attribute> parseAttributes(JSONArray attributeJson) {
List<Attribute> attributes = new ArrayList<Attribute>(attributeJson.length());
for (int i = 0; i < attributeJson.length();i++) {
Object obj = attributeJson.get(i);
JSONObject attributeObject = (JSONObject) obj;
String id = attributeObject.getString("id");
String key = attributeObject.getString("key");
attributes.add(new Attribute(id, key, attributeObject.optString("segmentId", null)));
}
return attributes;
}
private List<EventType> parseEvents(JSONArray eventJson) {
List<EventType> events = new ArrayList<EventType>(eventJson.length());
for (int i = 0; i < eventJson.length(); i++) {
Object obj = eventJson.get(i);
JSONObject eventObject = (JSONObject) obj;
List<String> experimentIds = parseExperimentIds(eventObject.getJSONArray("experimentIds"));
String id = eventObject.getString("id");
String key = eventObject.getString("key");
events.add(new EventType(id, key, experimentIds));
}
return events;
}
private List<Audience> parseAudiences(JSONArray audienceJson) {
List<Audience> audiences = new ArrayList<Audience>(audienceJson.length());
for (int i = 0; i < audienceJson.length(); i++) {
Object obj = audienceJson.get(i);
JSONObject audienceObject = (JSONObject) obj;
String id = audienceObject.getString("id");
String key = audienceObject.getString("name");
Object conditionsObject = audienceObject.get("conditions");
if (conditionsObject instanceof String) { // should always be true
JSONTokener tokener = new JSONTokener((String) conditionsObject);
char token = tokener.nextClean();
if (token == '[') {
// must be an array
conditionsObject = new JSONArray((String) conditionsObject);
} else if (token == '{') {
conditionsObject = new JSONObject((String) conditionsObject);
}
}
Condition conditions = ConditionUtils.<UserAttribute>parseConditions(UserAttribute.class, conditionsObject);
audiences.add(new Audience(id, key, conditions));
}
return audiences;
}
private List<Audience> parseTypedAudiences(JSONArray audienceJson) {
List<Audience> audiences = new ArrayList<Audience>(audienceJson.length());
for (int i = 0; i < audienceJson.length(); i++) {
Object obj = audienceJson.get(i);
JSONObject audienceObject = (JSONObject) obj;
String id = audienceObject.getString("id");
String key = audienceObject.getString("name");
Object conditionsObject = audienceObject.get("conditions");
Condition conditions = ConditionUtils.<UserAttribute>parseConditions(UserAttribute.class, conditionsObject);
audiences.add(new Audience(id, key, conditions));
}
return audiences;
}
private List<Group> parseGroups(JSONArray groupJson) {
List<Group> groups = new ArrayList<Group>(groupJson.length());
for (int i = 0; i < groupJson.length(); i++) {
Object obj = groupJson.get(i);
JSONObject groupObject = (JSONObject) obj;
String id = groupObject.getString("id");
String policy = groupObject.getString("policy");
List<Experiment> experiments = parseExperiments(groupObject.getJSONArray("experiments"), id);
List<TrafficAllocation> trafficAllocations =
parseTrafficAllocation(groupObject.getJSONArray("trafficAllocation"));
groups.add(new Group(id, policy, experiments, trafficAllocations));
}
return groups;
}
private List<FeatureVariable> parseFeatureVariables(JSONArray featureVariablesJson) {
List<FeatureVariable> featureVariables = new ArrayList<FeatureVariable>(featureVariablesJson.length());
for (int i = 0; i < featureVariablesJson.length();i++) {
Object obj = featureVariablesJson.get(i);
JSONObject FeatureVariableObject = (JSONObject) obj;
String id = FeatureVariableObject.getString("id");
String key = FeatureVariableObject.getString("key");
String defaultValue = FeatureVariableObject.getString("defaultValue");
String type = FeatureVariableObject.getString("type");
String subType = null;
if (FeatureVariableObject.has("subType")) {
subType = FeatureVariableObject.getString("subType");
}
FeatureVariable.VariableStatus status = null;
if (FeatureVariableObject.has("status")) {
status = FeatureVariable.VariableStatus.fromString(FeatureVariableObject.getString("status"));
}
featureVariables.add(new FeatureVariable(id, key, defaultValue, status, type, subType));
}
return featureVariables;
}
private List<FeatureVariableUsageInstance> parseFeatureVariableInstances(JSONArray featureVariableInstancesJson) {
List<FeatureVariableUsageInstance> featureVariableUsageInstances = new ArrayList<FeatureVariableUsageInstance>(featureVariableInstancesJson.length());
for (int i = 0; i < featureVariableInstancesJson.length(); i++) {
Object obj = featureVariableInstancesJson.get(i);
JSONObject featureVariableInstanceObject = (JSONObject) obj;
String id = featureVariableInstanceObject.getString("id");
String value = featureVariableInstanceObject.getString("value");
featureVariableUsageInstances.add(new FeatureVariableUsageInstance(id, value));
}
return featureVariableUsageInstances;
}
private List<Rollout> parseRollouts(JSONArray rolloutsJson) {
List<Rollout> rollouts = new ArrayList<Rollout>(rolloutsJson.length());
for (int i = 0; i < rolloutsJson.length(); i++) {
Object obj = rolloutsJson.get(i);
JSONObject rolloutObject = (JSONObject) obj;
String id = rolloutObject.getString("id");
List<Experiment> experiments = parseExperiments(rolloutObject.getJSONArray("experiments"));
rollouts.add(new Rollout(id, experiments));
}
return rollouts;
}
@Override
public String toJson(Object src) {
JSONObject json = (JSONObject)JsonHelpers.convertToJsonObject(src);
return json.toString();
}
@Override
public <T> T fromJson(String json, Class<T> clazz) throws JsonParseException {
if (Map.class.isAssignableFrom(clazz)) {
JSONObject obj = new JSONObject(json);
return (T)JsonHelpers.jsonObjectToMap(obj);
}
// org.json parser does not support parsing to user objects
throw new JsonParseException("Parsing fails with a unsupported type");
}
}
| |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.glassfish.admingui.devtests;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.Select;
import static org.junit.Assert.assertEquals;
/**
*
* @author Jeremy Lv
*
*/
public class ConnectorsTest extends BaseSeleniumTestClass {
@Test
public void testConnectorResources() {
String testPool = "connectorPool" + generateRandomString();
String testConnector = "connectorResource" + generateRandomString();
StandaloneTest standaloneTest = new StandaloneTest();
ClusterTest clusterTest = new ClusterTest();
standaloneTest.deleteAllStandaloneInstances();
clusterTest.deleteAllCluster();
clickAndWait("treeForm:tree:resources:Connectors:connectorConnectionPools:connectorConnectionPools_link");
// Create new connection connection pool
clickAndWait("propertyForm:poolTable:topActionsGroup1:newButton");
setFieldValue("propertyForm:propertySheet:generalPropertySheet:jndiProp:name", testPool);
Select select = new Select(driver.findElement(By.id("propertyForm:propertySheet:generalPropertySheet:resAdapterProp:db")));
select.selectByVisibleText("jmsra");
sleep(1000);
Select select1 = new Select(driver.findElement(By.id("propertyForm:propertySheet:generalPropertySheet:connectionDefProp:db")));
select1.selectByVisibleText("javax.jms.QueueConnectionFactory");
waitForButtonEnabled("propertyForm:title:topButtons:nextButton");
clickAndWait("propertyForm:title:topButtons:nextButton");
Select select2 = new Select(driver.findElement(By.id("propertyForm:propertySheet:poolPropertySheet:transprop:trans")));
select2.selectByVisibleText("NoTransaction");
clickAndWait("propertyForm:propertyContentPage:topButtons:finishButton");
String prefix = getTableRowByValue("propertyForm:poolTable", testPool, "col1");
assertEquals(testPool, getText(prefix + "col1:link"));
// Create new connector resource which uses this new pool
clickAndWait("treeForm:tree:resources:Connectors:connectorResources:connectorResources_link");
clickAndWait("propertyForm:resourcesTable:topActionsGroup1:newButton");
setFieldValue("form:propertySheet:propertSectionTextField:jndiTextProp:jnditext", testConnector);
Select select3 = new Select(driver.findElement(By.id("form:propertySheet:propertSectionTextField:poolNameProp:PoolName")));
select3.selectByVisibleText(testPool);
clickAndWait("form:propertyContentPage:topButtons:newButton");
//test disable button
String connectorPrefix = getTableRowByValue("propertyForm:resourcesTable", testConnector, "col1");
isElementPresent("propertyForm:resourcesTable:topActionsGroup1:newButton");
String selectId = connectorPrefix + "col0:select";
clickByIdAction(selectId);
clickAndWait("propertyForm:resourcesTable:topActionsGroup1:button3");
//test enable button
waitforBtnDisable("propertyForm:resourcesTable:topActionsGroup1:button2");
clickByIdAction(selectId);
clickAndWait("propertyForm:resourcesTable:topActionsGroup1:button2");
// Delete connector resource
waitforBtnDisable("propertyForm:resourcesTable:topActionsGroup1:button1");
deleteRow("propertyForm:resourcesTable:topActionsGroup1:button1", "propertyForm:resourcesTable", testConnector);
// Delete connector connection pool
clickAndWait("treeForm:tree:resources:Connectors:connectorConnectionPools:connectorConnectionPools_link");
deleteRow("propertyForm:poolTable:topActionsGroup1:button1", "propertyForm:poolTable", testPool);
}
@Test
public void testConnectorResourcesWithTargets() {
gotoDasPage();
String testPool = "connectorPool" + generateRandomString();
String testConnector = "connectorResource" + generateRandomString();
final String instanceName = "standalone" + generateRandomString();
clickAndWait("treeForm:tree:resources:Connectors:connectorConnectionPools:connectorConnectionPools_link");
// Create new connection connection pool
clickAndWait("propertyForm:poolTable:topActionsGroup1:newButton");
setFieldValue("propertyForm:propertySheet:generalPropertySheet:jndiProp:name", testPool);
Select select = new Select(driver.findElement(By.id("propertyForm:propertySheet:generalPropertySheet:resAdapterProp:db")));
select.selectByVisibleText("jmsra");
sleep(1000);
Select select1 = new Select(driver.findElement(By.id("propertyForm:propertySheet:generalPropertySheet:connectionDefProp:db")));
select1.selectByVisibleText("javax.jms.QueueConnectionFactory");
waitForButtonEnabled("propertyForm:title:topButtons:nextButton");
clickAndWait("propertyForm:title:topButtons:nextButton");
Select select2 = new Select(driver.findElement(By.id("propertyForm:propertySheet:poolPropertySheet:transprop:trans")));
select2.selectByVisibleText("NoTransaction");
clickAndWait("propertyForm:propertyContentPage:topButtons:finishButton");
String prefix = getTableRowByValue("propertyForm:poolTable", testPool, "col1");
assertEquals(testPool, getText(prefix + "col1:link"));
StandaloneTest instanceTest = new StandaloneTest();
instanceTest.createStandAloneInstance(instanceName);
// Create new connector resource which uses this new pool
clickAndWait("treeForm:tree:resources:Connectors:connectorResources:connectorResources_link");
clickAndWait("propertyForm:resourcesTable:topActionsGroup1:newButton");
setFieldValue("form:propertySheet:propertSectionTextField:jndiTextProp:jnditext", testConnector);
Select select3 = new Select(driver.findElement(By.id("form:propertySheet:propertSectionTextField:poolNameProp:PoolName")));
select3.selectByVisibleText(testPool);
int count = addTableRow("form:basicTable", "form:basicTable:topActionsGroup1:addSharedTableButton");
setFieldValue("form:basicTable:rowGroup1:0:col2:col1St", "property" + generateRandomString());
setFieldValue("form:basicTable:rowGroup1:0:col3:col1St", "value");
setFieldValue("form:basicTable:rowGroup1:0:col4:col1St", "description");
Select select4 = new Select(driver.findElement(By.id("form:targetSection:targetSectionId:addRemoveProp:commonAddRemove_available")));
select4.selectByVisibleText(instanceName);
select4.selectByVisibleText("server");
clickByIdAction("form:targetSection:targetSectionId:addRemoveProp:commonAddRemove:commonAddRemove_addButton");
clickAndWait("form:propertyContentPage:topButtons:newButton");
String connectorPrefix = getTableRowByValue("propertyForm:resourcesTable", testConnector, "col1");
assertEquals(testConnector, getText(connectorPrefix + "col1:link"));
String clickId = connectorPrefix + "col1:link";
clickByIdAction(clickId);
assertTableRowCount("propertyForm:basicTable", count);
clickAndWait("propertyForm:propertyContentPage:topButtons:cancelButton");
//test disable button
isElementPresent("propertyForm:resourcesTable:topActionsGroup1:newButton");
String selectId = connectorPrefix + "col0:select";
clickByIdAction(selectId);
clickAndWait("propertyForm:resourcesTable:topActionsGroup1:button3");
//test enable button
waitforBtnDisable("propertyForm:resourcesTable:topActionsGroup1:button2");
clickByIdAction(selectId);
clickAndWait("propertyForm:resourcesTable:topActionsGroup1:button2");
//test manage target
waitforBtnDisable("propertyForm:resourcesTable:topActionsGroup1:button2");
clickByIdAction(clickId);
clickAndWait("propertyForm:resEditTabs:targetTab");
clickAndWait("propertyForm:targetTable:topActionsGroup1:manageTargetButton");
Select select5 = new Select(driver.findElement(By.id("form:targetSection:targetSectionId:addRemoveProp:commonAddRemove_selected")));
select5.selectByVisibleText(instanceName);
select5.selectByVisibleText("server");
clickByIdAction("form:targetSection:targetSectionId:addRemoveProp:commonAddRemove:commonAddRemove_removeButton");
clickByIdAction("form:propertyContentPage:topButtons:saveButton");
// Delete connector resource
clickAndWait("treeForm:tree:resources:Connectors:connectorResources:connectorResources_link");
deleteRow("propertyForm:resourcesTable:topActionsGroup1:button1", "propertyForm:resourcesTable", testConnector);
// Delete connector connection pool
clickAndWait("treeForm:tree:resources:Connectors:connectorConnectionPools:connectorConnectionPools_link");
deleteRow("propertyForm:poolTable:topActionsGroup1:button1", "propertyForm:poolTable", testPool);
//Delete the instance
clickAndWait("treeForm:tree:standaloneTreeNode:standaloneTreeNode_link");
deleteRow("propertyForm:instancesTable:topActionsGroup1:button1", "propertyForm:instancesTable", instanceName);
}
// //This tests need to be finished and retested after the GLASSFISH-20812 has been resolved!
// @Test
// public void testConnectorSecurityMaps() {
// gotoDasPage();
// String testPool = generateRandomString();
// String testSecurityMap = generateRandomString();
// String testGroup = generateRandomString();
// String testPassword = generateRandomString();
// String testUserName = generateRandomString();
//
// clickAndWait("treeForm:tree:resources:Connectors:connectorConnectionPools:connectorConnectionPools_link");
//
// // Create new connection connection pool
// clickAndWait("propertyForm:poolTable:topActionsGroup1:newButton");
//
// setFieldValue("propertyForm:propertySheet:generalPropertySheet:jndiProp:name", testPool);
// Select select = new Select(driver.findElement(By.id("propertyForm:propertySheet:generalPropertySheet:resAdapterProp:db")));
// select.selectByVisibleText("jmsra");
// sleep(1000);
//
// Select select1 = new Select(driver.findElement(By.id("propertyForm:propertySheet:generalPropertySheet:connectionDefProp:db")));
// select1.selectByVisibleText("javax.jms.QueueConnectionFactory");
// waitForButtonEnabled("propertyForm:title:topButtons:nextButton");
//
// clickAndWait("propertyForm:title:topButtons:nextButton");
//
// Select select2 = new Select(driver.findElement(By.id("propertyForm:propertySheet:poolPropertySheet:transprop:trans")));
// select2.selectByVisibleText("NoTransaction");
// clickAndWait("propertyForm:propertyContentPage:topButtons:finishButton");
//
// String prefix = getTableRowByValue("propertyForm:poolTable", testPool, "col1");
// assertEquals(testPool, getText(prefix + "col1:link"));
//
// //Create Connector Security Map
// String clickId = prefix + "col1:link";
// clickByIdAction(clickId);
// clickAndWait("propertyForm:connectorPoolSet:securityMapTab");
// clickAndWait("propertyForm:resourcesTable:topActionsGroup1:newButton");
//
// setFieldValue("propertyForm:propertySheet:propertSectionTextField:mapNameNew:mapName", testSecurityMap);
// setFieldValue("propertyForm:propertySheet:propertSectionTextField:groupProp:group", testGroup);
// setFieldValue("propertyForm:propertySheet:propertSectionTextField2:userNameEdit:userNameEdit", testUserName);
// setFieldValue("propertyForm:propertySheet:propertSectionTextField2:passwordEdit:passwordEdit", testPassword);
// clickAndWait("propertyForm:propertyContentPage:topButtons:newButton");
//
// String securityPrefix = getTableRowByValue("propertyForm:resourcesTable", testSecurityMap, "col1");
// String clickId1 = securityPrefix + "col1:link";
// clickByIdAction(clickId1);
// Assert.assertEquals(testGroup, getValue("propertyForm:propertySheet:propertSectionTextField:groupProp:group", "value"));
// clickAndWait("propertyForm:propertyContentPage:topButtons:cancelButton");
//
// //Delete Connector Security Maps
// deleteRow("propertyForm:resourcesTable:topActionsGroup1:button1", "propertyForm:resourcesTable", testSecurityMap);
//
// // Delete connector connection pool
// clickAndWait("treeForm:tree:resources:Connectors:connectorConnectionPools:connectorConnectionPools_link");
// deleteRow("propertyForm:poolTable:topActionsGroup1:button1", "propertyForm:poolTable", testPool);
// }
}
| |
/*
* Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.patientcorrelation.nhinc.parsers.PRPAIN201309UV;
//import com.sun.org.apache.bcel.internal.classfile.ConstantString;
import gov.hhs.fha.nhinc.common.nhinccommon.QualifiedSubjectIdentifierType;
import gov.hhs.fha.nhinc.common.patientcorrelationfacade.RetrievePatientCorrelationsRequestType;
import gov.hhs.fha.nhinc.nhinclib.NullChecker;
import gov.hhs.fha.nhinc.patientcorrelation.nhinc.parsers.PRPAIN201309UV.helpers.AssigningAuthorityHomeCommunityMappingHelper;
import gov.hhs.fha.nhinc.patientcorrelation.nhinc.parsers.PRPAIN201309UV.helpers.CDHelper;
import gov.hhs.fha.nhinc.patientcorrelation.nhinc.parsers.PRPAIN201309UV.helpers.CSHelper;
import gov.hhs.fha.nhinc.patientcorrelation.nhinc.parsers.PRPAIN201309UV.helpers.Constants;
import gov.hhs.fha.nhinc.patientcorrelation.nhinc.parsers.PRPAIN201309UV.helpers.CreationTimeHelper;
import gov.hhs.fha.nhinc.patientcorrelation.nhinc.parsers.PRPAIN201309UV.helpers.IIHelper;
import gov.hhs.fha.nhinc.patientcorrelation.nhinc.parsers.PRPAIN201309UV.helpers.InteractionIdHelper;
import gov.hhs.fha.nhinc.patientcorrelation.nhinc.parsers.PRPAIN201309UV.helpers.SemanticsTextHelper;
import gov.hhs.fha.nhinc.patientcorrelation.nhinc.parsers.PRPAIN201309UV.helpers.SenderReceiverHelper;
import gov.hhs.fha.nhinc.patientcorrelation.nhinc.parsers.PRPAIN201309UV.helpers.UniqueIdHelper;
import java.util.List;
import javax.xml.bind.JAXBElement;
import org.hl7.v3.COCTMT090100UV01AssignedPerson;
import org.hl7.v3.II;
import org.hl7.v3.PRPAIN201309UV02;
import org.hl7.v3.PRPAIN201309UV02QUQIMT021001UV01ControlActProcess;
import org.hl7.v3.PRPAMT201307UV02DataSource;
import org.hl7.v3.PRPAMT201307UV02ParameterList;
import org.hl7.v3.PRPAMT201307UV02PatientIdentifier;
import org.hl7.v3.PRPAMT201307UV02QueryByParameter;
import org.hl7.v3.QUQIMT021001UV01AuthorOrPerformer;
import org.hl7.v3.XActMoodIntentEvent;
import org.hl7.v3.XParticipationAuthorPerformer;
/**
*
* @author rayj
*/
public class PixRetrieveBuilder {
private AssigningAuthorityHomeCommunityMappingHelper aaMappingHelper;
public static final String ControlActProcessCode = "PRPA_TE201309UV";
private static final String AcceptAckCodeValue = "AL";
private static final String InteractionIdExtension = "PRPA_IN201309";
private static final String ProcessingCodeValue = "P";
private static final String ProcessingModeCode = "T";
private static final String ITSVersion = "XML_1.0";
private static final String MoodCodeValue = "EVN";
/**
*
*/
public PixRetrieveBuilder() {
aaMappingHelper = new AssigningAuthorityHomeCommunityMappingHelper();
}
/**
* @param aaMappingHelper
*/
public PixRetrieveBuilder(AssigningAuthorityHomeCommunityMappingHelper aaMappingHelper) {
this.aaMappingHelper = aaMappingHelper;
}
public PRPAIN201309UV02 createPixRetrieve(
RetrievePatientCorrelationsRequestType retrievePatientCorrelationsRequest) {
List<String> targetAssigningAuthorities = extractTargetAssigningAuthorities(retrievePatientCorrelationsRequest);
PRPAIN201309UV02 pixRetrieve = createTransmissionWrapper("1.1", null);
PRPAIN201309UV02QUQIMT021001UV01ControlActProcess controlActProcess = createBaseControlActProcess();
PRPAMT201307UV02QueryByParameter queryByParameter = createQueryByParameter(
retrievePatientCorrelationsRequest.getQualifiedPatientIdentifier(), targetAssigningAuthorities);
JAXBElement<PRPAMT201307UV02QueryByParameter> createQueryByParameterElement = createQueryByParameterElement(queryByParameter);
controlActProcess.setQueryByParameter(createQueryByParameterElement);
pixRetrieve.setControlActProcess(controlActProcess);
return pixRetrieve;
}
private List<String> extractTargetAssigningAuthorities(
RetrievePatientCorrelationsRequestType retrievePatientCorrelationsRequest) {
// if assigning authorities are present, use those. If not, convert home community to assigning authority
List<String> targetAssigningAuthorities = retrievePatientCorrelationsRequest.getTargetAssigningAuthority();
if (NullChecker.isNullish(targetAssigningAuthorities)) {
List<String> targetHomeCommunities = retrievePatientCorrelationsRequest.getTargetHomeCommunity();
if (NullChecker.isNotNullish(targetHomeCommunities)) {
targetAssigningAuthorities = aaMappingHelper
.lookupAssigningAuthorities(targetHomeCommunities);
}
}
return targetAssigningAuthorities;
}
private static JAXBElement<COCTMT090100UV01AssignedPerson> createAssignedPersonElement() {
COCTMT090100UV01AssignedPerson assignedPerson = new COCTMT090100UV01AssignedPerson();
assignedPerson.getId().add(IIHelper.IIFactoryCreateNull());
JAXBElement<COCTMT090100UV01AssignedPerson> assignedPersonElement;
javax.xml.namespace.QName xmlqname = new javax.xml.namespace.QName("urn:hl7-org:v3", "assignedPerson");
assignedPersonElement = new JAXBElement<COCTMT090100UV01AssignedPerson>(xmlqname,
COCTMT090100UV01AssignedPerson.class, assignedPerson);
return assignedPersonElement;
}
private static QUQIMT021001UV01AuthorOrPerformer createAuthor() {
QUQIMT021001UV01AuthorOrPerformer author = new QUQIMT021001UV01AuthorOrPerformer();
XParticipationAuthorPerformer xAuthor = XParticipationAuthorPerformer.AUT;
author.setTypeCode(xAuthor);
author.setAssignedPerson(createAssignedPersonElement());
return author;
}
private static PRPAMT201307UV02ParameterList createParameterList(
QualifiedSubjectIdentifierType qualifiedSubjectIdentifier, List<String> targetAssigningAuthorities) {
PRPAMT201307UV02ParameterList parameterList = new PRPAMT201307UV02ParameterList();
PRPAMT201307UV02PatientIdentifier patId = createPatientIdentifier(qualifiedSubjectIdentifier);
parameterList.getPatientIdentifier().add(patId);
if (targetAssigningAuthorities != null) {
for (String targetAssigningAuthority : targetAssigningAuthorities) {
PRPAMT201307UV02DataSource dataSourceItem = new PRPAMT201307UV02DataSource();
II dataSourceValue = new II();
dataSourceValue.setRoot(targetAssigningAuthority);
dataSourceItem.getValue().add(dataSourceValue);
parameterList.getDataSource().add(dataSourceItem);
}
}
return parameterList;
}
private static PRPAIN201309UV02 createTransmissionWrapper(String senderId, String receiverId) {
PRPAIN201309UV02 message = new PRPAIN201309UV02();
message.setITSVersion(ITSVersion);
message.setId(UniqueIdHelper.createUniqueId());
message.setCreationTime(CreationTimeHelper.getCreationTime());
message.setInteractionId(InteractionIdHelper.createInteractionId(InteractionIdExtension));
message.setProcessingCode(CSHelper.buildCS(ProcessingCodeValue));
message.setProcessingModeCode(CSHelper.buildCS(ProcessingModeCode));
message.setAcceptAckCode(CSHelper.buildCS(AcceptAckCodeValue));
message.getReceiver().add(SenderReceiverHelper.CreateReceiver(receiverId));
message.setSender(SenderReceiverHelper.CreateSender(senderId));
return message;
}
private static PRPAIN201309UV02QUQIMT021001UV01ControlActProcess createBaseControlActProcess() {
PRPAIN201309UV02QUQIMT021001UV01ControlActProcess controlActProcess = new PRPAIN201309UV02QUQIMT021001UV01ControlActProcess();
controlActProcess.setMoodCode(XActMoodIntentEvent.EVN);
controlActProcess.setCode(CDHelper.CDFactory(ControlActProcessCode, Constants.HL7_OID));
controlActProcess.getAuthorOrPerformer().add(createAuthor());
return controlActProcess;
}
private static PRPAMT201307UV02QueryByParameter createQueryByParameter(
QualifiedSubjectIdentifierType qualifiedSubjectIdentifier, List<String> targetAssigningAuthorities) {
PRPAMT201307UV02QueryByParameter queryByParameter = new PRPAMT201307UV02QueryByParameter();
queryByParameter.setQueryId(UniqueIdHelper.createUniqueId("1.1"));
queryByParameter.setStatusCode(CSHelper.buildCS("new"));
queryByParameter.setResponsePriorityCode(CSHelper.buildCS("I"));
queryByParameter.setParameterList(createParameterList(qualifiedSubjectIdentifier, targetAssigningAuthorities));
return queryByParameter;
}
private static JAXBElement<PRPAMT201307UV02QueryByParameter> createQueryByParameterElement(
PRPAMT201307UV02QueryByParameter queryByParameter) {
JAXBElement<PRPAMT201307UV02QueryByParameter> queryByParameterElement;
javax.xml.namespace.QName xmlqname = new javax.xml.namespace.QName("urn:hl7-org:v3", "queryByParameter");
queryByParameterElement = new JAXBElement<PRPAMT201307UV02QueryByParameter>(xmlqname,
PRPAMT201307UV02QueryByParameter.class, new PRPAMT201307UV02QueryByParameter());
queryByParameterElement.setValue(queryByParameter);
return queryByParameterElement;
}
private static II getII(String assignAuth, String root, String ext) {
II val = new II();
val.setAssigningAuthorityName(assignAuth);
val.setExtension(ext);
val.setRoot(root);
return val;
}
private static PRPAMT201307UV02PatientIdentifier createPatientIdentifier(
QualifiedSubjectIdentifierType qualifiedSubjectIdentifier) {
PRPAMT201307UV02PatientIdentifier patientIdentifier = new PRPAMT201307UV02PatientIdentifier();
patientIdentifier.getValue().add(IIHelper.IIFactory(qualifiedSubjectIdentifier));
patientIdentifier.setSemanticsText(SemanticsTextHelper.createSemanticsText("Patient.Id"));
return patientIdentifier;
}
}
| |
package com.android305.lights.util.encryption;
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* 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.
*/
/**
* Provides Base64 encoding and decoding as defined by RFC 2045.
* <p/>
* <p>This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite>
* from RFC 2045 <cite>Multipurpose Internet Mail Extensions (MIME) Part One:
* Format of Internet Message Bodies</cite> by Freed and Borenstein.</p>
*
* @author Apache Software Foundation
* @version $Id: Base64.java,v 1.20 2004/05/24 00:21:24 ggregory Exp $
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
* @since 1.0-dev
*/
public class ApacheBase64 {
/**
* Chunk size per RFC 2045 section 6.8.
* <p/>
* <p>The {@value} character limit does not count the trailing CRLF, but counts
* all other characters, including any equal signs.</p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
*/
static final int CHUNK_SIZE = 76;
/**
* Chunk separator per RFC 2045 section 2.1.
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
*/
static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes();
/**
* The base length.
*/
static final int BASELENGTH = 255;
/**
* Lookup length.
*/
static final int LOOKUPLENGTH = 64;
/**
* Used to calculate the number of bits in a byte.
*/
static final int EIGHTBIT = 8;
/**
* Used when encoding something which has fewer than 24 bits.
*/
static final int SIXTEENBIT = 16;
/**
* Used to determine how many bits data contains.
*/
static final int TWENTYFOURBITGROUP = 24;
/**
* Used to get the number of Quadruples.
*/
static final int FOURBYTE = 4;
/**
* Used to test the sign of a byte.
*/
static final int SIGN = -128;
/**
* Byte used to pad output.
*/
static final byte PAD = (byte) '=';
// Create arrays to hold the base64 characters and a
// lookup for base64 chars
private static byte[] base64Alphabet = new byte[BASELENGTH];
private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
// Populating the lookup and character arrays
static {
for (int i = 0; i < BASELENGTH; i++) {
base64Alphabet[i] = (byte) -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (byte) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (byte) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (byte) ('0' + j);
}
lookUpBase64Alphabet[62] = (byte) '+';
lookUpBase64Alphabet[63] = (byte) '/';
}
private static boolean isBase64(byte octect) {
return octect == PAD || !(base64Alphabet[octect] == -1);
}
/**
* Encodes binary data using the base64 algorithm but
* does not chunk the output.
*
* @param binaryData binary data to encode
* @return Base64 characters
*/
public static byte[] encodeBase64(byte[] binaryData) {
return encodeBase64(binaryData, false);
}
/**
* Encodes binary data using the base64 algorithm and chunks
* the encoded output into 76 character blocks
*
* @param binaryData binary data to encode
* @return Base64 characters chunked in 76 character blocks
*/
public static byte[] encodeBase64Chunked(byte[] binaryData) {
return encodeBase64(binaryData, true);
}
/**
* Encodes binary data using the base64 algorithm, optionally
* chunking the output into 76 character blocks.
*
* @param binaryData Array containing binary data to encode.
* @param isChunked if isChunked is true this encoder will chunk
* the base64 output into 76 character blocks
* @return Base64-encoded data.
*/
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
int lengthDataBits = binaryData.length * EIGHTBIT;
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int nbrChunks = 0;
byte encodedData[];
int encodedDataLength;
if (fewerThan24bits != 0) {
//data not divisible by 24 bit
encodedDataLength = (numberTriplets + 1) * 4;
} else {
// 16 or 8 bit
encodedDataLength = numberTriplets * 4;
}
// If the output is to be "chunked" into 76 character sections,
// for compliance with RFC 2045 MIME, then it is important to
// allow for extra length to account for the separator(s)
if (isChunked) {
nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE));
encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length;
}
encodedData = new byte[encodedDataLength];
byte k, l, b1, b2, b3;
int encodedIndex = 0;
int dataIndex;
int i;
int nextSeparatorIndex = CHUNK_SIZE;
int chunksSoFar = 0;
//log.debug("number of triplets = " + numberTriplets);
for (i = 0; i < numberTriplets; i++) {
dataIndex = i * 3;
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
b3 = binaryData[dataIndex + 2];
//log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3);
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
//log.debug( "val2 = " + val2 );
//log.debug( "k4 = " + (k<<4) );
//log.debug( "vak = " + (val2 | (k<<4)) );
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
encodedIndex += 4;
// If we are chunking, let's put a chunk separator down.
if (isChunked) {
// this assumes that CHUNK_SIZE % 4 == 0
if (encodedIndex == nextSeparatorIndex) {
System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length);
chunksSoFar++;
nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length);
encodedIndex += CHUNK_SEPARATOR.length;
}
}
}
// form integral number of 6-bit groups
dataIndex = i * 3;
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
//log.debug("b1=" + b1);
//log.debug("b1<<2 = " + (b1>>2) );
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex + 2] = PAD;
encodedData[encodedIndex + 3] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex + 3] = PAD;
}
if (isChunked) {
// we also add a separator to the end of the final chunk.
if (chunksSoFar < nbrChunks) {
System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length);
}
}
return encodedData;
}
/**
* Decodes Base64 data into octects
*
* @param base64Data Byte array containing Base64 data
* @return Array containing decoded data.
*/
public static byte[] decodeBase64(byte[] base64Data) {
// RFC 2045 requires that we discard ALL non-Base64 characters
base64Data = discardNonBase64(base64Data);
// handle the edge case, so we don't have to worry about it later
if (base64Data.length == 0) {
return new byte[0];
}
int numberQuadruple = base64Data.length / FOURBYTE;
byte decodedData[];
byte b1, b2, b3, b4, marker0, marker1;
// Throw away anything not in base64Data
int encodedIndex = 0;
int dataIndex;
{
// this sizes the output array properly - rlw
int lastData = base64Data.length;
// ignore the '=' padding
while (base64Data[lastData - 1] == PAD) {
if (--lastData == 0) {
return new byte[0];
}
}
decodedData = new byte[lastData - numberQuadruple];
}
for (int i = 0; i < numberQuadruple; i++) {
dataIndex = i * 4;
marker0 = base64Data[dataIndex + 2];
marker1 = base64Data[dataIndex + 3];
b1 = base64Alphabet[base64Data[dataIndex]];
b2 = base64Alphabet[base64Data[dataIndex + 1]];
if (marker0 != PAD && marker1 != PAD) {
//No PAD e.g 3cQl
b3 = base64Alphabet[marker0];
b4 = base64Alphabet[marker1];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
} else if (marker0 == PAD) {
//Two PAD e.g. 3c[Pad][Pad]
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
} else {
//One PAD e.g. 3cQ[Pad]
b3 = base64Alphabet[marker0];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
}
encodedIndex += 3;
}
return decodedData;
}
/**
* Discards any whitespace from a base-64 encoded block.
*
* @param data The base-64 encoded data to discard the whitespace
* from.
* @return The data, less whitespace (see RFC 2045).
*/
static byte[] discardWhitespace(byte[] data) {
byte groomedData[] = new byte[data.length];
int bytesCopied = 0;
for (byte d : data) {
switch (d) {
case (byte) ' ':
case (byte) '\n':
case (byte) '\r':
case (byte) '\t':
break;
default:
groomedData[bytesCopied++] = d;
}
}
byte packedData[] = new byte[bytesCopied];
System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
return packedData;
}
/**
* Discards any characters outside of the base64 alphabet, per
* the requirements on page 25 of RFC 2045 - "Any characters
* outside of the base64 alphabet are to be ignored in base64
* encoded data."
*
* @param data The base-64 encoded data to groom
* @return The data, less non-base64 characters (see RFC 2045).
*/
static byte[] discardNonBase64(byte[] data) {
byte groomedData[] = new byte[data.length];
int bytesCopied = 0;
for (byte d : data) {
if (isBase64(d)) {
groomedData[bytesCopied++] = d;
}
}
byte packedData[] = new byte[bytesCopied];
System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
return packedData;
}
}
| |
package org.keycloak.testsuite.broker;
import org.keycloak.broker.saml.SAMLIdentityProviderConfig;
import org.keycloak.crypto.Algorithm;
import org.keycloak.dom.saml.v2.protocol.AuthnRequestType;
import org.keycloak.models.IdentityProviderSyncMode;
import org.keycloak.protocol.saml.SamlConfigAttributes;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.saml.common.constants.JBossSAMLURIConstants;
import org.keycloak.saml.common.util.DocumentUtil;
import org.keycloak.saml.processing.api.saml.v2.request.SAML2Request;
import org.keycloak.saml.processing.core.parsers.saml.assertion.SAMLAssertionQNames;
import org.keycloak.saml.processing.core.parsers.saml.protocol.SAMLProtocolQNames;
import org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder;
import org.keycloak.testsuite.saml.AbstractSamlTest;
import org.keycloak.testsuite.updaters.ClientAttributeUpdater;
import org.keycloak.testsuite.updaters.IdentityProviderAttributeUpdater;
import org.keycloak.testsuite.updaters.RealmAttributeUpdater;
import org.keycloak.testsuite.util.KeyUtils;
import org.keycloak.testsuite.util.SamlClient;
import org.keycloak.testsuite.util.SamlClient.Binding;
import org.keycloak.testsuite.util.SamlClientBuilder;
import org.keycloak.testsuite.util.saml.SamlDocumentStepBuilder.Saml2DocumentTransformer;
import java.io.Closeable;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.ws.rs.core.Response.Status;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.namespace.QName;
import org.apache.http.HttpResponse;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.keycloak.testsuite.broker.BrokerTestConstants.*;
import static org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot;
import static org.keycloak.testsuite.util.Matchers.bodyHC;
import static org.keycloak.testsuite.util.Matchers.isSamlResponse;
import static org.keycloak.testsuite.broker.BrokerTestTools.getProviderRoot;
public class KcSamlSignedBrokerTest extends AbstractBrokerTest {
private static final String PRIVATE_KEY = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAs46ICYPRIkmr8diECmyT59cChTWIEiXYBY3T6OLlZrF8ofVCzbEeoUOmhrtHijxxuKSoqLWP4nNOt3rINtQNBQIDAQABAkBL2nyxuFQTLhhLdPJjDPd2y6gu6ixvrjkSL5ZEHgZXWRHzhTzBT0eRxg/5rJA2NDRMBzTTegaEGkWUt7lF5wDJAiEA5pC+h9NEgqDJSw42I52BOml3II35Z6NlNwl6OMfnD1sCIQDHXUiOIJy4ZcSgv5WGue1KbdNVOT2gop1XzfuyWgtjHwIhAOCjLb9QC3PqC7Tgx8azcnDiyHojWVesTrTsuvQPcAP5AiAkX5OeQrr1NbQTNAEe7IsrmjAFi4T/6stUOsOiPaV4NwIhAJIeyh4foIXIVQ+M4To2koaDFRssxKI9/O72vnZSJ+uA";
private static final String PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALOOiAmD0SJJq/HYhApsk+fXAoU1iBIl2AWN0+ji5WaxfKH1Qs2xHqFDpoa7R4o8cbikqKi1j+JzTrd6yDbUDQUCAwEAAQ==";
public void withSignedEncryptedAssertions(Runnable testBody, boolean signedDocument, boolean signedAssertion, boolean encryptedAssertion) throws Exception {
String providerCert = KeyUtils.getActiveSigningKey(adminClient.realm(bc.providerRealmName()).keys().getKeyMetadata(), Algorithm.RS256).getCertificate();
Assert.assertThat(providerCert, Matchers.notNullValue());
String consumerCert = KeyUtils.getActiveSigningKey(adminClient.realm(bc.consumerRealmName()).keys().getKeyMetadata(), Algorithm.RS256).getCertificate();
Assert.assertThat(consumerCert, Matchers.notNullValue());
try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource)
.setAttribute(SAMLIdentityProviderConfig.VALIDATE_SIGNATURE, Boolean.toString(signedAssertion || signedDocument))
.setAttribute(SAMLIdentityProviderConfig.WANT_ASSERTIONS_SIGNED, Boolean.toString(signedAssertion))
.setAttribute(SAMLIdentityProviderConfig.WANT_ASSERTIONS_ENCRYPTED, Boolean.toString(encryptedAssertion))
.setAttribute(SAMLIdentityProviderConfig.WANT_AUTHN_REQUESTS_SIGNED, "false")
.setAttribute(SAMLIdentityProviderConfig.ENCRYPTION_PUBLIC_KEY, PUBLIC_KEY)
.setAttribute(SAMLIdentityProviderConfig.SIGNING_CERTIFICATE_KEY, providerCert)
.update();
Closeable clientUpdater = ClientAttributeUpdater.forClient(adminClient, bc.providerRealmName(), bc.getIDPClientIdInProviderRealm())
.setAttribute(SamlConfigAttributes.SAML_ENCRYPT, Boolean.toString(encryptedAssertion))
.setAttribute(SamlConfigAttributes.SAML_ENCRYPTION_CERTIFICATE_ATTRIBUTE, consumerCert)
.setAttribute(SamlConfigAttributes.SAML_SERVER_SIGNATURE, Boolean.toString(signedDocument))
.setAttribute(SamlConfigAttributes.SAML_ASSERTION_SIGNATURE, Boolean.toString(signedAssertion))
.setAttribute(SamlConfigAttributes.SAML_ENCRYPTION_PRIVATE_KEY_ATTRIBUTE, PRIVATE_KEY)
.setAttribute(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, "false") // Do not require client signature
.update())
{
testBody.run();
}
}
@Override
protected BrokerConfiguration getBrokerConfiguration() {
return new KcSamlSignedBrokerConfiguration();
}
@Test
public void testWithExpiredBrokerCertificate() throws Exception {
try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource)
.setAttribute(SAMLIdentityProviderConfig.VALIDATE_SIGNATURE, Boolean.toString(true))
.setAttribute(SAMLIdentityProviderConfig.WANT_ASSERTIONS_SIGNED, Boolean.toString(true))
.setAttribute(SAMLIdentityProviderConfig.WANT_ASSERTIONS_ENCRYPTED, Boolean.toString(false))
.setAttribute(SAMLIdentityProviderConfig.WANT_AUTHN_REQUESTS_SIGNED, "true")
.setAttribute(SAMLIdentityProviderConfig.SIGNING_CERTIFICATE_KEY, AbstractSamlTest.SAML_CLIENT_SALES_POST_SIG_EXPIRED_CERTIFICATE)
.update();
Closeable clientUpdater = ClientAttributeUpdater.forClient(adminClient, bc.providerRealmName(), bc.getIDPClientIdInProviderRealm())
.setAttribute(SamlConfigAttributes.SAML_ENCRYPT, Boolean.toString(false))
.setAttribute(SamlConfigAttributes.SAML_SERVER_SIGNATURE, "true")
.setAttribute(SamlConfigAttributes.SAML_ASSERTION_SIGNATURE, Boolean.toString(true))
.setAttribute(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, "false")
.update();
Closeable realmUpdater = new RealmAttributeUpdater(adminClient.realm(bc.providerRealmName()))
.setPublicKey(AbstractSamlTest.SAML_CLIENT_SALES_POST_SIG_EXPIRED_PUBLIC_KEY)
.setPrivateKey(AbstractSamlTest.SAML_CLIENT_SALES_POST_SIG_EXPIRED_PRIVATE_KEY)
.update())
{
AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
Document doc = SAML2Request.convert(loginRep);
new SamlClientBuilder()
.authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build() // Request to consumer IdP
.login().idp(bc.getIDPAlias()).build()
.assertResponse(org.keycloak.testsuite.util.Matchers.statusCodeIsHC(Status.BAD_REQUEST));
}
}
@Test
public void testSignedEncryptedAssertions() throws Exception {
withSignedEncryptedAssertions(this::testAssertionSignatureRespected, false, true, true);
}
@Test
public void testSignedAssertion() throws Exception {
withSignedEncryptedAssertions(this::testAssertionSignatureRespected, false, true, false);
}
private void testAssertionSignatureRespected() {
// Login should pass because assertion is signed.
loginUser();
// Logout should fail because logout response is not signed.
final String redirectUri = getAccountUrl(getProviderRoot(), bc.providerRealmName());
final String logoutUri = oauth.realm(bc.providerRealmName()).getLogoutUrl().redirectUri(redirectUri).build();
driver.navigate().to(logoutUri);
errorPage.assertCurrent();
}
private Document extractNamespacesToTopLevelElement(Document original) {
HashMap<String, String> namespaces = new HashMap<>();
enumerateAndRemoveNamespaces(original.getDocumentElement(), namespaces);
log.infof("Namespaces: %s", namespaces);
log.infof("Document: %s", DocumentUtil.asString(original));
Element rootNode = original.getDocumentElement();
for (Entry<String, String> me : namespaces.entrySet()) {
rootNode.setAttribute(me.getKey(), me.getValue());
}
log.infof("Updated document: %s", DocumentUtil.asString(original));
return original;
}
private void enumerateAndRemoveNamespaces(Element documentElement, HashMap<String, String> namespaces) {
final NamedNodeMap attrs = documentElement.getAttributes();
if (attrs != null) {
final Set<String> found = new HashSet<>();
for (int i = attrs.getLength() - 1; i >= 0; i--) {
Node item = attrs.item(i);
String nodeName = item.getNodeName();
if (nodeName != null && nodeName.startsWith("xmlns:")) {
namespaces.put(nodeName, item.getNodeValue());
found.add(nodeName);
}
}
found.forEach(documentElement::removeAttribute);
}
NodeList childNodes = documentElement.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i ++) {
Node childNode = childNodes.item(i);
if (childNode instanceof Element) {
enumerateAndRemoveNamespaces((Element) childNode, namespaces);
}
}
}
// KEYCLOAK-5581
@Test
public void loginUserAllNamespacesInTopElement() {
AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST, getConsumerRoot() + "/sales-post/saml", null);
Document doc;
try {
doc = extractNamespacesToTopLevelElement(SAML2Request.convert(loginRep));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
SAMLDocumentHolder samlResponse = new SamlClientBuilder()
.authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build() // Request to consumer IdP
.login().idp(bc.getIDPAlias()).build()
.processSamlResponse(Binding.POST) // AuthnRequest to producer IdP
.targetAttributeSamlRequest()
.transformDocument(this::extractNamespacesToTopLevelElement)
.build()
.login().user(bc.getUserLogin(), bc.getUserPassword()).build()
.processSamlResponse(Binding.POST) // Response from producer IdP
.transformDocument(this::extractNamespacesToTopLevelElement)
.build()
// first-broker flow
.updateProfile().firstName("a").lastName("b").email(bc.getUserEmail()).username(bc.getUserLogin()).build()
.followOneRedirect()
.getSamlResponse(Binding.POST); // Response from consumer IdP
Assert.assertThat(samlResponse, Matchers.notNullValue());
Assert.assertThat(samlResponse.getSamlObject(), isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
}
@Test
public void loginUserAllNamespacesInTopElementSignedEncryptedAssertion() throws Exception {
withSignedEncryptedAssertions(this::loginUserAllNamespacesInTopElement, false, true, true);
}
@Test
public void loginUserAllNamespacesInTopElementSignedAssertion() throws Exception {
withSignedEncryptedAssertions(this::loginUserAllNamespacesInTopElement, false, true, false);
}
@Test
public void loginUserAllNamespacesInTopElementEncryptedAssertion() throws Exception {
withSignedEncryptedAssertions(this::loginUserAllNamespacesInTopElement, false, false, true);
}
public class KcSamlSignedBrokerConfiguration extends KcSamlBrokerConfiguration {
@Override
public RealmRepresentation createProviderRealm() {
RealmRepresentation realm = super.createProviderRealm();
realm.setPublicKey(REALM_PUBLIC_KEY);
realm.setPrivateKey(REALM_PRIVATE_KEY);
return realm;
}
@Override
public RealmRepresentation createConsumerRealm() {
RealmRepresentation realm = super.createConsumerRealm();
realm.setPublicKey(REALM_PUBLIC_KEY);
realm.setPrivateKey(REALM_PRIVATE_KEY);
return realm;
}
@Override
public List<ClientRepresentation> createProviderClients() {
List<ClientRepresentation> clientRepresentationList = super.createProviderClients();
String consumerCert = KeyUtils.getActiveSigningKey(adminClient.realm(consumerRealmName()).keys().getKeyMetadata(), Algorithm.RS256).getCertificate();
Assert.assertThat(consumerCert, Matchers.notNullValue());
for (ClientRepresentation client : clientRepresentationList) {
client.setClientAuthenticatorType("client-secret");
client.setSurrogateAuthRequired(false);
Map<String, String> attributes = client.getAttributes();
if (attributes == null) {
attributes = new HashMap<>();
client.setAttributes(attributes);
}
attributes.put(SamlConfigAttributes.SAML_ASSERTION_SIGNATURE, "true");
attributes.put(SamlConfigAttributes.SAML_SERVER_SIGNATURE, "true");
attributes.put(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, "true");
attributes.put(SamlConfigAttributes.SAML_SIGNATURE_ALGORITHM, "RSA_SHA256");
attributes.put(SamlConfigAttributes.SAML_SIGNING_CERTIFICATE_ATTRIBUTE, consumerCert);
}
return clientRepresentationList;
}
@Override
public IdentityProviderRepresentation setUpIdentityProvider(IdentityProviderSyncMode syncMode) {
IdentityProviderRepresentation result = super.setUpIdentityProvider(syncMode);
String providerCert = KeyUtils.getActiveSigningKey(adminClient.realm(providerRealmName()).keys().getKeyMetadata(), Algorithm.RS256).getCertificate();
Assert.assertThat(providerCert, Matchers.notNullValue());
Map<String, String> config = result.getConfig();
config.put(SAMLIdentityProviderConfig.VALIDATE_SIGNATURE, "true");
config.put(SAMLIdentityProviderConfig.WANT_ASSERTIONS_SIGNED, "true");
config.put(SAMLIdentityProviderConfig.WANT_AUTHN_REQUESTS_SIGNED, "true");
config.put(SAMLIdentityProviderConfig.SIGNING_CERTIFICATE_KEY, providerCert);
return result;
}
}
@Test
public void testSignatureTampering_NOsignDoc_NOsignAssert_NOencAssert() throws Exception {
loginAttackChangeSignature(false, false, false);
}
@Test
public void testSignatureTampering_NOsignDoc_NOsignAssert_encAssert() throws Exception {
loginAttackChangeSignature(false, false, true);
}
@Test
public void testSignatureTampering_NOsignDoc_signAssert_NOencAssert() throws Exception {
loginAttackChangeSignature(false, true, false);
}
@Test
public void testSignatureTampering_NOsignDoc_signAssert_encAssert() throws Exception {
loginAttackChangeSignature(false, true, true);
}
@Test
public void testSignatureTampering_signDoc_NOsignAssert_NOencAssert() throws Exception {
loginAttackChangeSignature(true, false, false);
}
@Test
public void testSignatureTampering_signDoc_NOsignAssert_encAssert() throws Exception {
loginAttackChangeSignature(true, false, true);
}
@Test
public void testSignatureTampering_signDoc_signAssert_NOencAssert() throws Exception {
loginAttackChangeSignature(true, true, false);
}
@Test
public void testSignatureTampering_signDoc_signAssert_encAssert() throws Exception {
loginAttackChangeSignature(true, true, true);
}
private Document removeDocumentSignature(Document orig) {
return removeSignatureTag(orig, Collections.singleton(SAMLProtocolQNames.RESPONSE.getQName()));
}
private Document removeAssertionSignature(Document orig) {
return removeSignatureTag(orig, Collections.singleton(SAMLAssertionQNames.ASSERTION.getQName()));
}
private Document removeDocumentAndAssertionSignature(Document orig) {
return removeSignatureTag(orig,
new HashSet<>(Arrays.asList(SAMLProtocolQNames.RESPONSE.getQName(), SAMLAssertionQNames.ASSERTION.getQName()))
);
}
private Document removeSignatureTag(Document orig, final Set<QName> qNames) throws DOMException {
NodeList sigElements = orig.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
LinkedList<Node> nodesToRemove = new LinkedList<>();
for (int i = 0; i < sigElements.getLength(); i ++) {
Node n = sigElements.item(i);
final Node p = n.getParentNode();
QName q = new QName(p.getNamespaceURI(), p.getLocalName());
if (qNames.contains(q)) {
nodesToRemove.add(n);
}
}
nodesToRemove.forEach(n -> n.getParentNode().removeChild(n));
return orig;
}
private void loginAttackChangeSignature(boolean producerSignDocument, boolean producerSignAssertions, boolean producerEncryptAssertions) throws Exception {
log.debug("");
loginAttackChangeSignature("No changes to SAML document", producerSignDocument, producerSignAssertions, producerEncryptAssertions,
t -> t, true);
// TODO: producerSignAssertions should be removed once there would be option to force check SAML document signature
boolean validAfterTamperingWithDocumentSignature = ! producerSignDocument || producerSignAssertions;
loginAttackChangeSignature("Remove document signature", producerSignDocument, producerSignAssertions, producerEncryptAssertions,
this::removeDocumentSignature, validAfterTamperingWithDocumentSignature);
// Tests for assertion signature manipulation follow. Tampering with assertion signature is
// relevant only if assertion is not encrypted since signature is part of encrypted data,
// hence skipped in the opposite case.
if (producerEncryptAssertions) {
return;
}
// When assertion signature is removed, the expected document validation passes only
// if neither the document was not signed
// (otherwise document signature is invalidated by removing signature from the assertion)
// nor the assertion is
boolean validAfterTamperingWithAssertionSignature = ! producerSignAssertions;
// When both assertion and document signatures are removed, the document validation passes only
// if neiter the document nor assertion were signed
boolean validAfterTamperingWithBothDocumentAndAssertionSignature = ! producerSignDocument && ! producerSignAssertions;
loginAttackChangeSignature("Remove assertion signature", producerSignDocument, producerSignAssertions, producerEncryptAssertions,
this::removeAssertionSignature, validAfterTamperingWithAssertionSignature);
loginAttackChangeSignature("Remove both document and assertion signature", producerSignDocument, producerSignAssertions, producerEncryptAssertions,
this::removeDocumentAndAssertionSignature, validAfterTamperingWithBothDocumentAndAssertionSignature);
}
private void loginAttackChangeSignature(String description,
boolean producerSignDocument, boolean producerSignAssertions, boolean producerEncryptAssertions,
Saml2DocumentTransformer tr, boolean shouldSucceed) throws Exception {
log.infof("producerSignDocument: %s, producerSignAssertions: %s, producerEncryptAssertions: %s", producerSignDocument, producerSignAssertions, producerEncryptAssertions);
Matcher<HttpResponse> responseFromConsumerMatcher = shouldSucceed
? bodyHC(containsString("Update Account Information"))
: not(bodyHC(containsString("Update Account Information")));
AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST, getConsumerRoot() + "/sales-post/saml", null);
Document doc = SAML2Request.convert(loginRep);
withSignedEncryptedAssertions(() -> {
new SamlClientBuilder()
.authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build() // Request to consumer IdP
.login().idp(bc.getIDPAlias()).build()
.processSamlResponse(Binding.POST).build() // AuthnRequest to producer IdP
.login().user(bc.getUserLogin(), bc.getUserPassword()).build()
.processSamlResponse(Binding.POST) // Response from producer IdP
.transformDocument(tr)
.build()
// first-broker flow: if valid request, it displays an update profile page on consumer realm
.execute(currentResponse -> assertThat(description, currentResponse, responseFromConsumerMatcher));
}, producerSignDocument, producerSignAssertions, producerEncryptAssertions);
}
@Test
public void testSignatureDataWhenWantsRequestsSigned() throws Exception {
// Verifies that an AuthnRequest contains the KeyInfo/X509Data element when
// client AuthnRequest signature is requested
String providerCert = KeyUtils.getActiveSigningKey(adminClient.realm(bc.providerRealmName()).keys().getKeyMetadata(), Algorithm.RS256).getCertificate();
Assert.assertThat(providerCert, Matchers.notNullValue());
String consumerCert = KeyUtils.getActiveSigningKey(adminClient.realm(bc.consumerRealmName()).keys().getKeyMetadata(), Algorithm.RS256).getCertificate();
Assert.assertThat(consumerCert, Matchers.notNullValue());
try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource)
.setAttribute(SAMLIdentityProviderConfig.VALIDATE_SIGNATURE, Boolean.toString(true))
.setAttribute(SAMLIdentityProviderConfig.WANT_ASSERTIONS_SIGNED, Boolean.toString(true))
.setAttribute(SAMLIdentityProviderConfig.WANT_ASSERTIONS_ENCRYPTED, Boolean.toString(false))
.setAttribute(SAMLIdentityProviderConfig.WANT_AUTHN_REQUESTS_SIGNED, "true")
.setAttribute(SAMLIdentityProviderConfig.SIGNING_CERTIFICATE_KEY, AbstractSamlTest.SAML_CLIENT_SALES_POST_SIG_EXPIRED_CERTIFICATE)
.update();
Closeable clientUpdater = ClientAttributeUpdater.forClient(adminClient, bc.providerRealmName(), bc.getIDPClientIdInProviderRealm())
.setAttribute(SamlConfigAttributes.SAML_ENCRYPT, Boolean.toString(false))
.setAttribute(SamlConfigAttributes.SAML_SERVER_SIGNATURE, "true")
.setAttribute(SamlConfigAttributes.SAML_ASSERTION_SIGNATURE, Boolean.toString(true))
.setAttribute(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, "false")
.update())
{
// Build the login request document
AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
Document doc = SAML2Request.convert(loginRep);
new SamlClientBuilder()
.authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST)
.build() // Request to consumer IdP
.login().idp(bc.getIDPAlias()).build()
.processSamlResponse(Binding.POST) // AuthnRequest to producer IdP
.targetAttributeSamlRequest()
.transformDocument(this::extractNamespacesToTopLevelElement)
.transformDocument((document) -> {
try
{
// Find the Signature element
Element signatureElement = DocumentUtil.getDirectChildElement(document.getDocumentElement(), XMLSignature.XMLNS, "Signature");
Assert.assertThat("Signature element not found in request document", signatureElement, Matchers.notNullValue());
// Find the KeyInfo element
Element keyInfoElement = DocumentUtil.getDirectChildElement(signatureElement, XMLSignature.XMLNS, "KeyInfo");
Assert.assertThat("KeyInfo element not found in request Signature element", keyInfoElement, Matchers.notNullValue());
// Find the X509Data element
Element x509DataElement = DocumentUtil.getDirectChildElement(keyInfoElement, XMLSignature.XMLNS, "X509Data");
Assert.assertThat("X509Data element not found in request Signature/KeyInfo element", x509DataElement, Matchers.notNullValue());
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
})
.build()
.execute();
}
}
}
| |
package com.crawljax.core.state;
import com.codahale.metrics.MetricRegistry;
import com.crawljax.browser.EmbeddedBrowser;
import com.crawljax.condition.invariant.Invariant;
import com.crawljax.core.CrawlSession;
import com.crawljax.core.CrawlerContext;
import com.crawljax.core.ExitNotifier;
import com.crawljax.core.configuration.CrawljaxConfiguration;
import com.crawljax.core.configuration.CrawljaxConfiguration.CrawljaxConfigurationBuilder;
import com.crawljax.core.plugin.OnInvariantViolationPlugin;
import com.crawljax.core.plugin.OnNewStatePlugin;
import com.crawljax.core.plugin.Plugins;
import com.crawljax.core.state.Eventable.EventType;
import com.crawljax.core.state.Identification.How;
import com.crawljax.oraclecomparator.StateComparator;
import com.google.common.collect.ImmutableList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import static org.junit.Assert.*;
@RunWith(MockitoJUnitRunner.class)
public class StateMachineTest {
private StateMachine sm;
private final StateVertex index =
new StateVertexImpl(StateVertex.INDEX_ID, "index", "<table><div>index</div></table>");
@Mock
private EmbeddedBrowser dummyBrowser;
@Mock
private StateComparator comparator;
@Mock
private CrawlSession session;
@Mock
private CrawlerContext context;
@Mock
private Plugins plugins;
private static boolean hit = false;
/**
* Run before every test case.
*/
@Before
public void initStateMachine() {
InMemoryStateFlowGraph sfg = newStateFlowGraph();
sm = new StateMachine(sfg, ImmutableList.<Invariant>of(), plugins, comparator,
new ArrayList<>());
}
@Test
public void testInitOk() {
assertNotNull(sm);
assertNotNull(sm.getCurrentState());
assertEquals(sm.getCurrentState(), index);
}
/**
* Test the Change State operation.
*/
@Test
public void testChangeState() {
StateVertex state2 = new StateVertexImpl(2, "state2", "<table><div>state2</div></table>");
// Can not change index because not added.
assertFalse(sm.changeState(state2));
assertNotSame(sm.getCurrentState(), state2);
// Add index.
Eventable c = new Eventable(new Identification(How.xpath, "/bla"), EventType.click);
assertTrue(sm.switchToStateAndCheckIfClone(c, state2, context));
// Current index is the new index
assertEquals(sm.getCurrentState(), state2);
// Change back.
assertTrue(sm.changeState(index));
assertEquals(sm.getCurrentState(), index);
}
/**
* Test the Clone state behaviour.
*/
@Test
public void testCloneState() {
// state2.equals(state3)
StateVertex state2 = new StateVertexImpl(2, "state2", "<table><div>state2</div></table>");
StateVertex state3 = new StateVertexImpl(3, "state3", "<table><div>state2</div></table>");
/*
* Can not change to state2 because not inserted yet.
*/
assertFalse(sm.changeState(state2));
assertNotSame(sm.getCurrentState(), state2);
Eventable c = new Eventable(new Identification(How.xpath, "/bla"), EventType.click);
assertTrue(sm.switchToStateAndCheckIfClone(c, state2, context));
// can not change to state2 because we are already in state2
assertFalse(sm.changeState(state2));
assertSame(sm.getCurrentState(), state2);
// state2.equals(state3)
assertEquals("state2 equals state3", state2, state3);
// state2 != state3 because other objects.
assertNotSame("state2 != state3", state2, state3);
Eventable c2 = new Eventable(new Identification(How.xpath, "/bla2"), EventType.click);
// False because its CLONE!
assertFalse(sm.switchToStateAndCheckIfClone(c2, state3, context));
// state2.equals(state3)
assertEquals("state2 equals state3", state2, state3);
// state2 == sm.getCurrentState() because changed in update.
assertSame("state2 == state3", state2, sm.getCurrentState());
}
/**
* Test the Rewind Operation.
*/
@Test
public void testRewind() {
// state2.equals(state3)
StateVertex state2 = new StateVertexImpl(2, "state2", "<table><div>state2</div></table>");
StateVertex state3 = new StateVertexImpl(3, "state3", "<table><div>state2</div></table>");
StateVertex state4 = new StateVertexImpl(4, "state4", "<table><div>state4</div></table>");
/*
* Can not change to state2 because not inserted yet.
*/
assertFalse(sm.changeState(state2));
assertNotSame(sm.getCurrentState(), state2);
Eventable c = new Eventable(new Identification(How.xpath, "/bla"), EventType.click);
assertTrue(sm.switchToStateAndCheckIfClone(c, state2, context));
// can not change to state2 because we are already in state2
assertFalse(sm.changeState(state2));
assertSame(sm.getCurrentState(), state2);
// state2.equals(state3)
assertEquals("state2 equals state3", state2, state3);
// !state2.equals(state4)
assertFalse("state2 not equals state4", state2.equals(state4));
Eventable c2 = new Eventable(new Identification(How.xpath, "/bla2"), EventType.click);
// False because its CLONE!
assertFalse(sm.switchToStateAndCheckIfClone(c2, state3, context));
Eventable c3 = new Eventable(new Identification(How.xpath, "/bla2"), EventType.click);
// True because its not yet known
assertTrue(sm.switchToStateAndCheckIfClone(c3, state4, context));
sm.rewind();
assertEquals("CurrentState == index", index, sm.getCurrentState());
// Now we can go from index -> state2
assertTrue(sm.changeState(state2));
// Now we can go from state2 -> state2
assertTrue(sm.changeState(state2));
// Now we can go from state2 -> state4
assertTrue(sm.changeState(state4));
sm.rewind();
assertEquals("CurrentState == index", index, sm.getCurrentState());
// Now we can not go from index -> state4
assertFalse(sm.changeState(state4));
}
/**
* Make sure Invariants are executed!
*/
@Test
public void testInvariants() {
// state2.equals(state3)
StateVertex state2 = new StateVertexImpl(2, "state2", "<table><div>state2</div></table>");
StateVertex state3 = new StateVertexImpl(3, "state3", "<table><div>state2</div></table>");
hit = false;
ImmutableList<Invariant> iList =
ImmutableList.of(new Invariant("Test123", browser -> {
hit = true;
return false;
}));
InMemoryStateFlowGraph sfg = newStateFlowGraph();
StateMachine smLocal =
new StateMachine(sfg, iList, plugins, comparator, new ArrayList<>());
Eventable c = new Eventable(new Identification(How.xpath, "/bla"), EventType.click);
assertTrue(smLocal.switchToStateAndCheckIfClone(c, state2, context));
// New State so hit must be true;
assertTrue("Invariants are executed", hit);
hit = false;
assertFalse("Hit reset", hit);
Eventable c2 = new Eventable(new Identification(How.xpath, "/bla"), EventType.click);
assertFalse(smLocal.switchToStateAndCheckIfClone(c2, state3, context));
// CLONE State so hit must be true;
assertTrue("Invariants are executed", hit);
}
private InMemoryStateFlowGraph newStateFlowGraph() {
InMemoryStateFlowGraph sfg =
new InMemoryStateFlowGraph(new ExitNotifier(0), new DefaultStateVertexFactory());
sfg.putIndex(index);
return sfg;
}
/**
* Make sure On new State Plugin executed.
*/
@Test
public void testOnNewStatePlugin() {
hit = false;
CrawljaxConfiguration config = CrawljaxConfiguration.builderFor("http://localhost")
.addPlugin((OnNewStatePlugin) (context, state) -> hit = true).build();
setStateMachineForConfig(config);
// state2.equals(state3)
StateVertex state2 = new StateVertexImpl(2, "state2", "<table><div>state2</div></table>");
StateVertex state3 = new StateVertexImpl(3, "state3", "<table><div>state2</div></table>");
Eventable c = new Eventable(new Identification(How.xpath, "/bla"), EventType.click);
assertTrue(sm.switchToStateAndCheckIfClone(c, state2, context));
// New State so hit must be true;
assertTrue("Plugins are executed", hit);
hit = false;
assertFalse("Hit reset", hit);
Eventable c2 = new Eventable(new Identification(How.xpath, "/bla"), EventType.click);
assertFalse(sm.switchToStateAndCheckIfClone(c2, state3, context));
// CLONE State so no plugin execution
assertFalse("Plugins are NOT executed", hit);
}
private void setStateMachineForConfig(CrawljaxConfiguration config) {
sm = new StateMachine(newStateFlowGraph(), config.getCrawlRules().getInvariants(),
new Plugins(config, new MetricRegistry()), comparator, new ArrayList<>());
}
/**
* Make sure InvariantViolationPlugin executed.
*/
@Test
public void testInvariantFailurePlugin() {
hit = false;
CrawljaxConfigurationBuilder builder = CrawljaxConfiguration
.builderFor("http://localhost").addPlugin(
(OnInvariantViolationPlugin) (invariant, context) -> hit = true);
builder.crawlRules().addInvariant(new Invariant("Test123", browser -> false));
setStateMachineForConfig(builder.build());
// state2.equals(state3)
StateVertex state2 = new StateVertexImpl(2, "state2", "<table><div>state2</div></table>");
StateVertex state3 = new StateVertexImpl(3, "state3", "<table><div>state2</div></table>");
Eventable c = new Eventable(new Identification(How.xpath, "/bla"), EventType.click);
assertTrue(sm.switchToStateAndCheckIfClone(c, state2, context));
// New State so hit must be true;
assertTrue("InvariantViolationPlugin are executed", hit);
hit = false;
assertFalse("Hit reset", hit);
Eventable c2 = new Eventable(new Identification(How.xpath, "/bla"), EventType.click);
assertFalse(sm.switchToStateAndCheckIfClone(c2, state3, context));
// New State so plugin execution
assertTrue("InvariantViolationPlugin are executed", hit);
}
}
| |
package org.adligo.xml_io_tests.shared;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.adligo.i.util.shared.I_Iterator;
import org.adligo.models.params.shared.I_XMLBuilder;
import org.adligo.models.params.shared.Parser;
import org.adligo.models.params.shared.TagAttribute;
import org.adligo.models.params.shared.TagInfo;
import org.adligo.xml_io.shared.I_AttributeSetter;
import org.adligo.xml_io.shared.I_Converter;
import org.adligo.xml_io.shared.I_FieldSetter;
import org.adligo.xml_io.shared.NamespaceConvertersMutant;
import org.adligo.xml_io.shared.NamespacePrefixConfig;
import org.adligo.xml_io.shared.NamespacePrefixConfigMutant;
import org.adligo.xml_io.shared.ObjectFromXml;
import org.adligo.xml_io.shared.Xml_IOConstants;
import org.adligo.xml_io.shared.Xml_IOReaderContext;
import org.adligo.xml_io.shared.Xml_IOSettingsMutant;
import org.adligo.xml_io.shared.Xml_IOWriterContext;
import org.adligo.xml_io.shared.converters.DefaultNamespaceConverters;
public class CustomComplexModelConverter implements I_Converter<CustomComplexModel>{
private static final String TAG_NAME = "ccm";
private static final Map<String, I_AttributeSetter<CustomComplexModel>> SETTERS = getSetters();
private static final Map<String, I_FieldSetter<CustomComplexModel>> FIELD_SETTERS = getFieldSetters();
public static Map<String, I_AttributeSetter<CustomComplexModel>> getSetters() {
Map<String, I_AttributeSetter<CustomComplexModel>> toRet =
new HashMap<String, I_AttributeSetter<CustomComplexModel>>();
toRet.put("id", new I_AttributeSetter<CustomComplexModel>() {
public void set(CustomComplexModel obj, String value, Xml_IOReaderContext context) {
Object toSet = context.readAttribute(Integer.class, value);
obj.setId((Integer) toSet);
}
});
toRet.put("sid", new I_AttributeSetter<CustomComplexModel>() {
public void set(CustomComplexModel obj, String value, Xml_IOReaderContext context) {
Object toSet = context.readAttribute(Short.class, value);
obj.setSid((Short) toSet);
}
});
toRet.put("lid", new I_AttributeSetter<CustomComplexModel>() {
public void set(CustomComplexModel obj, String value, Xml_IOReaderContext context) {
Object toSet = context.readAttribute(Long.class, value);
obj.setLid((Long) toSet);
}
});
toRet.put("did", new I_AttributeSetter<CustomComplexModel>() {
public void set(CustomComplexModel obj, String value, Xml_IOReaderContext context) {
Object toSet = context.readAttribute(Double.class, value);
obj.setDid((Double) toSet);
}
});
toRet.put("fid", new I_AttributeSetter<CustomComplexModel>() {
public void set(CustomComplexModel obj, String value, Xml_IOReaderContext context) {
Object toSet = context.readAttribute(Float.class, value);
obj.setFid((Float) toSet);
}
});
toRet.put("chars", new I_AttributeSetter<CustomComplexModel>() {
public void set(CustomComplexModel obj, String value, Xml_IOReaderContext context) {
Object toSet = context.readAttribute(DefaultNamespaceConverters.CHAR_ARRAY_CLASS, value);
obj.setChars((char []) toSet);
}
});
toRet.put("bytes", new I_AttributeSetter<CustomComplexModel>() {
public void set(CustomComplexModel obj, String value, Xml_IOReaderContext context) {
Object toSet = context.readAttribute(DefaultNamespaceConverters.BYTE_ARRAY_CLASS, value);
obj.setBytes((byte []) toSet);
}
});
toRet.put("bools", new I_AttributeSetter<CustomComplexModel>() {
public void set(CustomComplexModel obj, String value, Xml_IOReaderContext context) {
Object toSet = context.readAttribute(DefaultNamespaceConverters.BOOLEAN_ARRAY_CLASS, value);
obj.setBools((boolean []) toSet);
}
});
return Collections.unmodifiableMap(toRet);
}
public static Map<String, I_FieldSetter<CustomComplexModel>> getFieldSetters() {
Map<String, I_FieldSetter<CustomComplexModel>> toRet =
new HashMap<String, I_FieldSetter<CustomComplexModel>>();
toRet.put("stringsList", new I_FieldSetter<CustomComplexModel>() {
@SuppressWarnings("unchecked")
public void set(CustomComplexModel obj, Object value) {
obj.setStringsList((List<String>) value);
}
});
toRet.put("stringsArray", new I_FieldSetter<CustomComplexModel>() {
@SuppressWarnings("unchecked")
public void set(CustomComplexModel obj, Object value) {
List<String> items = (List<String>) value;
String [] itemsArray = new String [items.size()];
items.toArray(itemsArray);
obj.setStringsArray(itemsArray);
}
});
toRet.put("keyValues", new I_FieldSetter<CustomComplexModel>() {
@SuppressWarnings("unchecked")
public void set(CustomComplexModel obj, Object value) {
obj.setKeyValues((Map<Integer, String>) value);
}
});
return Collections.unmodifiableMap(toRet);
}
@Override
public ObjectFromXml<CustomComplexModel> fromXml(String xml, TagInfo info,
Xml_IOReaderContext context) {
//the CustomModel class is mutable so just call setters
CustomComplexModel toRet = new CustomComplexModel();
I_Iterator it = Parser.getAttributes(info, xml);
while (it.hasNext()) {
TagAttribute attrib = (TagAttribute) it.next();
String name = attrib.getName();
String value = attrib.getValue();
I_AttributeSetter<CustomComplexModel> setter = SETTERS.get(name);
if (setter != null) {
setter.set(toRet, value, context);
}
}
it = info.getChildren();
while (it.hasNext()) {
TagInfo child = (TagInfo) it.next();
String subTag = Parser.substring(xml, child);
ObjectFromXml<?> obj = context.readXml(subTag);
String name = obj.getName();
I_FieldSetter<CustomComplexModel> setter = FIELD_SETTERS.get(name);
Object value = obj.getValue();
setter.set(toRet, value);
}
return new ObjectFromXml<CustomComplexModel>(toRet);
}
@Override
public void toXml(CustomComplexModel p, Xml_IOWriterContext context) {
I_XMLBuilder builder = context.getBuilder();
context.appendTagHeaderStart(CustomSimpleModelConverter.CUSTOM_NAMESPACE, TAG_NAME);
context.appendSchemaInfoToFirstTag();
String name = context.getNextTagNameAttribute();
if (name != null) {
builder.appendAttribute(Xml_IOConstants.N_NAME_ATTRIBUTE, name);
context.setNextTagNameAttribute(null);
}
//do attributes
context.writeXmlAttribute("id", p.getId());
context.writeXmlAttribute("sid", p.getSid());
context.writeXmlAttribute("lid", p.getLid());
context.writeXmlAttribute("did", p.getDid());
context.writeXmlAttribute("fid", p.getFid());
context.writeXmlAttribute("chars", p.getChars());
context.writeXmlAttribute("bytes", p.getBytes());
context.writeXmlAttribute("bools", p.getBools());
builder.appendTagHeaderEnd(true);
builder.addIndentLevel();
//do nested tags
context.setNextTagNameAttribute("stringsList");
context.writeXml(p.getStringsList());
context.setNextTagNameAttribute("stringsArray");
context.writeXml(p.getStringsArray());
context.setNextTagNameAttribute("keyValues");
context.writeXml(p.getKeyValues());
builder.removeIndentLevel();
context.appendEndTag(CustomSimpleModelConverter.CUSTOM_NAMESPACE, TAG_NAME);
}
public static void setUp(Xml_IOSettingsMutant settings) {
NamespaceConvertersMutant converters = new NamespaceConvertersMutant();
converters.setNamespace(CustomSimpleModelConverter.CUSTOM_NAMESPACE);
converters.setPackageName("customPackagename");
converters.addXmlToObjectConverter(TAG_NAME, new CustomComplexModelConverter());
converters.addObjectToXmlConverter(CustomComplexModel.class, new CustomComplexModelConverter());
NamespacePrefixConfigMutant config = new NamespacePrefixConfigMutant();
config.addNamespace(converters);
settings.setConfig(new NamespacePrefixConfig(config));
}
}
| |
package cyclops.reactive;
import cyclops.reactive.collections.immutable.BagX;
import cyclops.reactive.collections.immutable.LinkedListX;
import cyclops.reactive.collections.immutable.OrderedSetX;
import cyclops.reactive.collections.immutable.PersistentQueueX;
import cyclops.reactive.collections.immutable.PersistentSetX;
import cyclops.reactive.collections.immutable.VectorX;
import cyclops.reactive.collections.mutable.DequeX;
import cyclops.reactive.collections.mutable.ListX;
import cyclops.reactive.collections.mutable.QueueX;
import cyclops.reactive.collections.mutable.SetX;
import cyclops.reactive.collections.mutable.SortedSetX;
;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.*;
public class SpoutsCollectionsTest {
Executor ex = Executors.newFixedThreadPool(1);
AtomicBoolean complete;
ReactiveSeq<Integer> async ;
@Before
public void setup(){
complete = new AtomicBoolean(false);
async = Spouts.reactive(Stream.of(100,100,100), ex)
.map(i->{
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return i;
})
.onComplete(()->complete.set(true));
}
@Test
public void listX(){
System.out.println("Initializing!");
ListX<Integer> asyncList = ReactiveCollections.listX(async)
.map(i->i+1);
boolean blocked = complete.get();
System.out.println("Blocked? " + blocked);
assertFalse(complete.get());
int value = asyncList.get(0);
System.out.println("First value is " + value);
assertThat(value,equalTo(101));
System.out.println("Blocked? " + complete.get());
assertTrue(complete.get());
}
@Test
public void queueX(){
System.out.println("Initializing!");
QueueX<Integer> asyncList = ReactiveCollections.queueX(async)
.map(i->i+1);
boolean blocked = complete.get();
System.out.println("Blocked? " + blocked);
assertFalse(complete.get());
int value = asyncList.firstValue(-1);
System.out.println("First value is " + value);
assertThat(value,equalTo(101));
System.out.println("Blocked? " + complete.get());
assertTrue(complete.get());
}
@Test
public void setX(){
System.out.println("Initializing!");
SetX<Integer> asyncList = ReactiveCollections.setX(async)
.map(i->i+1);
boolean blocked = complete.get();
System.out.println("Blocked? " + blocked);
assertFalse(complete.get());
int value = asyncList.firstValue(-1);
System.out.println("First value is " + value);
assertThat(value,equalTo(101));
System.out.println("Blocked? " + complete.get());
assertTrue(complete.get());
}
@Test
public void sortedSetX(){
System.out.println("Initializing!");
SortedSetX<Integer> asyncList = ReactiveCollections.sortedSetX(async)
.map(i->i+1);
boolean blocked = complete.get();
System.out.println("Blocked? " + blocked);
assertFalse(complete.get());
int value = asyncList.firstValue(-1);
System.out.println("First value is " + value);
assertThat(value,equalTo(101));
System.out.println("Blocked? " + complete.get());
assertTrue(complete.get());
}
@Test
public void dequeX() throws InterruptedException {
System.out.println("Initializing!");
DequeX<Integer> asyncList = ReactiveCollections.dequeX(async)
.map(i->i+1);
boolean blocked = complete.get();
System.out.println("Blocked? " + blocked);
assertFalse(complete.get());
int value = asyncList.firstValue(-1);
System.out.println("First value is " + value);
assertThat(value,equalTo(101));
Thread.sleep(1000);
System.out.println("Blocked? " + complete.get());
assertTrue(complete.get());
}
@Test
public void linkedListX(){
System.out.println("Initializing!");
LinkedListX<Integer> asyncList = ReactiveCollections.linkedListX(async)
.map(i->i+1);
boolean blocked = complete.get();
System.out.println("Blocked? " + blocked);
assertFalse(complete.get());
int value = asyncList.getOrElse(0,-1);
System.out.println("First value is " + value);
assertThat(value,equalTo(101));
System.out.println("Blocked? " + complete.get());
assertTrue(complete.get());
}
@Test
public void vectorX(){
System.out.println("Initializing!");
VectorX<Integer> asyncList = ReactiveCollections.vectorX(async)
.map(i->i+1);
boolean blocked = complete.get();
System.out.println("Blocked? " + blocked);
assertFalse(complete.get());
int value = asyncList.getOrElse(0,-1);
System.out.println("First value is " + value);
assertThat(value,equalTo(101));
System.out.println("Blocked? " + complete.get());
assertTrue(complete.get());
}
@Test
public void persistentQueueX(){
System.out.println("Initializing!");
PersistentQueueX<Integer> asyncList = ReactiveCollections.persistentQueueX(async)
.map(i->i+1);
boolean blocked = complete.get();
System.out.println("Blocked? " + blocked);
assertFalse(complete.get());
int value = asyncList.firstValue(-1);
System.out.println("First value is " + value);
assertThat(value,equalTo(101));
System.out.println("Blocked? " + complete.get());
assertTrue(complete.get());
}
@Test
public void persistentSetX(){
System.out.println("Initializing!");
PersistentSetX<Integer> asyncList = ReactiveCollections.persistentSetX(async)
.map(i->i+1);
boolean blocked = complete.get();
System.out.println("Blocked? " + blocked);
assertFalse(complete.get());
int value = asyncList.firstValue(-1);
System.out.println("First value is " + value);
assertThat(value,equalTo(101));
System.out.println("Blocked? " + complete.get());
assertTrue(complete.get());
}
@Test
public void orderedSetX(){
System.out.println("Initializing!");
OrderedSetX<Integer> asyncList = ReactiveCollections.orderedSetX(async)
.map(i->i+1);
boolean blocked = complete.get();
System.out.println("Blocked? " + blocked);
assertFalse(complete.get());
int value = asyncList.firstValue(-1);
System.out.println("First value is " + value);
assertThat(value,equalTo(101));
System.out.println("Blocked? " + complete.get());
assertTrue(complete.get());
}
@Test
public void bagX(){
System.out.println("Initializing!");
BagX<Integer> asyncList = ReactiveCollections.bagX(async)
.map(i->i+1);
boolean blocked = complete.get();
System.out.println("Blocked? " + blocked);
assertFalse(complete.get());
int value = asyncList.firstValue(-1);
System.out.println("First value is " + value);
assertThat(value,equalTo(101));
System.out.println("Blocked? " + complete.get());
assertTrue(complete.get());
}
}
| |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.intellij.openapi.actionSystem.impl;
import com.intellij.ide.DataManager;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.impl.actionholder.ActionRef;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.IdeFrame;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.ui.plaf.beg.IdeaMenuUI;
import com.intellij.ui.plaf.gtk.GtkMenuUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.plaf.MenuItemUI;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public final class ActionMenu extends JMenu {
private final String myPlace;
private DataContext myContext;
private final ActionRef<ActionGroup> myGroup;
private final PresentationFactory myPresentationFactory;
private final Presentation myPresentation;
private boolean myMnemonicEnabled;
private MenuItemSynchronizer myMenuItemSynchronizer;
private StubItem myStubItem; // A PATCH!!! Do not remove this code, otherwise you will lose all keyboard navigation in JMenuBar.
private final boolean myTopLevel;
public ActionMenu(final DataContext context,
@NotNull final String place,
final ActionGroup group,
final PresentationFactory presentationFactory,
final boolean enableMnemonics,
final boolean topLevel) {
myContext = context;
myPlace = place;
myGroup = ActionRef.fromAction(group);
myPresentationFactory = presentationFactory;
myPresentation = myPresentationFactory.getPresentation(group);
myMnemonicEnabled = enableMnemonics;
myTopLevel = topLevel;
updateUI();
init();
// addNotify won't be called for menus in MacOS system menu
if (SystemInfo.isMacSystemMenu) {
installSynchronizer();
}
if (UIUtil.isUnderIntelliJLaF()) {
setOpaque(true);
}
}
public void updateContext(DataContext context) {
myContext = context;
}
public void addNotify() {
super.addNotify();
installSynchronizer();
}
private void installSynchronizer() {
if (myMenuItemSynchronizer == null) {
myMenuItemSynchronizer = new MenuItemSynchronizer();
myGroup.getAction().addPropertyChangeListener(myMenuItemSynchronizer);
myPresentation.addPropertyChangeListener(myMenuItemSynchronizer);
}
}
@Override
public void removeNotify() {
uninstallSynchronizer();
super.removeNotify();
}
private void uninstallSynchronizer() {
if (myMenuItemSynchronizer != null) {
myGroup.getAction().removePropertyChangeListener(myMenuItemSynchronizer);
myPresentation.removePropertyChangeListener(myMenuItemSynchronizer);
myMenuItemSynchronizer = null;
}
}
@Override
public void updateUI() {
boolean isAmbiance = UIUtil.isUnderGTKLookAndFeel() && "Ambiance".equalsIgnoreCase(UIUtil.getGtkThemeName());
if (myTopLevel && !isAmbiance && UIUtil.GTK_AMBIANCE_TEXT_COLOR.equals(getForeground())) {
setForeground(null);
}
if (UIUtil.isStandardMenuLAF()) {
super.updateUI();
}
else {
setUI(IdeaMenuUI.createUI(this));
setFont(UIUtil.getMenuFont());
JPopupMenu popupMenu = getPopupMenu();
if (popupMenu != null) {
popupMenu.updateUI();
}
}
if (myTopLevel && isAmbiance) {
setForeground(UIUtil.GTK_AMBIANCE_TEXT_COLOR);
}
if (myTopLevel && UIUtil.isUnderGTKLookAndFeel()) {
Insets insets = getInsets();
Insets newInsets = new Insets(insets.top, insets.left, insets.bottom, insets.right);
if (insets.top + insets.bottom < 6) {
newInsets.top = newInsets.bottom = 3;
}
if (insets.left + insets.right < 12) {
newInsets.left = newInsets.right = 6;
}
if (!newInsets.equals(insets)) {
setBorder(BorderFactory.createEmptyBorder(newInsets.top, newInsets.left, newInsets.bottom, newInsets.right));
}
}
}
@Override
public void setUI(final MenuItemUI ui) {
final MenuItemUI newUi = !myTopLevel && UIUtil.isUnderGTKLookAndFeel() && GtkMenuUI.isUiAcceptable(ui) ? new GtkMenuUI(ui) : ui;
super.setUI(newUi);
}
private void init() {
boolean macSystemMenu = SystemInfo.isMacSystemMenu && myPlace == ActionPlaces.MAIN_MENU;
myStubItem = macSystemMenu ? null : new StubItem();
addStubItem();
addMenuListener(new MenuListenerImpl());
setBorderPainted(false);
setVisible(myPresentation.isVisible());
setEnabled(myPresentation.isEnabled());
setText(myPresentation.getText());
updateIcon();
setMnemonicEnabled(myMnemonicEnabled);
}
private void addStubItem() {
if (myStubItem != null) {
add(myStubItem);
}
}
public void setMnemonicEnabled(boolean enable) {
myMnemonicEnabled = enable;
setMnemonic(myPresentation.getMnemonic());
setDisplayedMnemonicIndex(myPresentation.getDisplayedMnemonicIndex());
}
@Override
public void setDisplayedMnemonicIndex(final int index) throws IllegalArgumentException {
super.setDisplayedMnemonicIndex(myMnemonicEnabled ? index : -1);
}
@Override
public void setMnemonic(int mnemonic) {
super.setMnemonic(myMnemonicEnabled ? mnemonic : 0);
}
private void updateIcon() {
if (UISettings.getInstance().SHOW_ICONS_IN_MENUS) {
final Presentation presentation = myPresentation;
final Icon icon = presentation.getIcon();
setIcon(icon);
if (presentation.getDisabledIcon() != null) {
setDisabledIcon(presentation.getDisabledIcon());
}
else {
setDisabledIcon(IconLoader.getDisabledIcon(icon));
}
}
}
@Override
public void menuSelectionChanged(boolean isIncluded) {
super.menuSelectionChanged(isIncluded);
showDescriptionInStatusBar(isIncluded, this, myPresentation.getDescription());
}
public static void showDescriptionInStatusBar(boolean isIncluded, Component component, String description) {
IdeFrame frame = component instanceof IdeFrame
? (IdeFrame)component
: (IdeFrame)SwingUtilities.getAncestorOfClass(IdeFrame.class, component);
StatusBar statusBar;
if (frame != null && (statusBar = frame.getStatusBar()) != null) {
statusBar.setInfo(isIncluded ? description : null);
}
}
private class MenuListenerImpl implements MenuListener {
public void menuCanceled(MenuEvent e) {
clearItems();
addStubItem();
}
public void menuDeselected(MenuEvent e) {
clearItems();
addStubItem();
}
public void menuSelected(MenuEvent e) {
fillMenu();
}
}
private void clearItems() {
if (SystemInfo.isMacSystemMenu && myPlace == ActionPlaces.MAIN_MENU) {
for (Component menuComponent : getMenuComponents()) {
if (menuComponent instanceof ActionMenu) {
((ActionMenu)menuComponent).clearItems();
if (SystemInfo.isMacSystemMenu) {
// hideNotify is not called on Macs
((ActionMenu)menuComponent).uninstallSynchronizer();
}
}
else if (menuComponent instanceof ActionMenuItem) {
// Looks like an old-fashioned ugly workaround
// JDK 1.7 on Mac works wrong with such functional keys
if (!(SystemInfo.isJavaVersionAtLeast("1.7") && SystemInfo.isMac)) {
((ActionMenuItem)menuComponent).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F24, 0));
}
}
}
}
removeAll();
validate();
}
private void fillMenu() {
DataContext context;
boolean mayContextBeInvalid;
if (myContext != null) {
context = myContext;
mayContextBeInvalid = false;
}
else {
@SuppressWarnings("deprecation") DataContext contextFromFocus = DataManager.getInstance().getDataContext();
context = contextFromFocus;
if (PlatformDataKeys.CONTEXT_COMPONENT.getData(context) == null) {
IdeFrame frame = UIUtil.getParentOfType(IdeFrame.class, this);
context = DataManager.getInstance().getDataContext(IdeFocusManager.getGlobalInstance().getLastFocusedFor(frame));
}
mayContextBeInvalid = true;
}
Utils.fillMenu(myGroup.getAction(), this, myMnemonicEnabled, myPresentationFactory, context, myPlace, true, mayContextBeInvalid);
}
private class MenuItemSynchronizer implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
String name = e.getPropertyName();
if (Presentation.PROP_VISIBLE.equals(name)) {
setVisible(myPresentation.isVisible());
if (SystemInfo.isMacSystemMenu && myPlace.equals(ActionPlaces.MAIN_MENU)) {
validateTree();
}
}
else if (Presentation.PROP_ENABLED.equals(name)) {
setEnabled(myPresentation.isEnabled());
}
else if (Presentation.PROP_MNEMONIC_KEY.equals(name)) {
setMnemonic(myPresentation.getMnemonic());
}
else if (Presentation.PROP_MNEMONIC_INDEX.equals(name)) {
setDisplayedMnemonicIndex(myPresentation.getDisplayedMnemonicIndex());
}
else if (Presentation.PROP_TEXT.equals(name)) {
setText(myPresentation.getText());
}
else if (Presentation.PROP_ICON.equals(name) || Presentation.PROP_DISABLED_ICON.equals(name)) {
updateIcon();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.