code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
private float calculateDy(float distanceY) {
int currentY = view.getScrollY();
float nextY = distanceY + currentY;
boolean isInsideVertically = nextY >= minY && nextY <= maxY;
return isInsideVertically ? distanceY : 0;
} | Returns the distance in the Y axes to perform the scroll taking into account the view
boundary. |
@Override
public String exportAsString() throws DescriptorExportException {
// Export as bytes
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
this.exportTo(baos);
// Make a String out of the bytes
final String content;
try {
content = baos.toString(Charset.UTF8.name());
} catch (final UnsupportedEncodingException e) {
throw new DescriptorExportException("Inconsistent encoding used during export", e);
}
// Return
return content;
} | {@inheritDoc}
@see org.jboss.shrinkwrap.descriptor.api.Descriptor#exportAsString() |
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain) throws Exception {
if (isLogoutRequest(context.getRequest())) {
logger.debug("Processing logout request");
Authentication auth = SecurityUtils.getAuthentication(context.getRequest());
if (auth != null) {
authenticationManager.invalidateAuthentication(auth);
}
onLogoutSuccess(context, auth);
} else {
processorChain.processRequest(context);
}
} | Checks if the request URL matches the {@code logoutUrl} and the HTTP method matches the {@code logoutMethod}.
If it does, it proceeds to logout the user, by invalidating the authentication through
{@link AuthenticationManager#invalidateAuthentication(Authentication)}
@param context the context which holds the current request and response
@param processorChain the processor chain, used to call the next processor |
@Override
public List<String> getAllDescription() {
final List<String> result = new ArrayList<String>();
final List<Node> nodes = this.getRootNode().get("description");
for (final Node node : nodes) {
result.add(node.getText());
}
return result;
} | TODO Add @Override |
@Override
public List<Entitlement> getCurrentUsage() {
Entitlement sites = new Entitlement();
sites.setType(EntitlementType.SITE);
Entitlement users = new Entitlement();
users.setType(EntitlementType.USER);
try {
sites.setValue((int) tenantRepository.count());
users.setValue((int) profileRepository.count());
} catch (Exception e) {
logger.error("Error fetching data", e);
}
return Arrays.asList(sites, users);
} | {@inheritDoc} |
@Override
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain) throws Exception {
AddSecurityCookiesResponseWrapper response = wrapResponse(context);
context.setResponse(response);
logger.debug("Wrapped response in a {}", response.getClass().getName());
try {
processorChain.processRequest(context);
} finally {
response.addCookies();
}
} | Wraps the response in a wrapper that adds (or deletes) the security cookies before the response is sent.
@param context the context which holds the current request and response
@param processorChain the {@link RequestSecurityProcessorChain}, used to call the next processor |
public boolean isValidGitRepository(Path folder) {
if (Files.exists(folder) && Files.isDirectory(folder)) {
// If it has been at least initialized
if (RepositoryCache.FileKey.isGitRepository(folder.toFile(), FS.DETECTED)) {
// we are assuming that the clone worked at that time, caller should call hasAtLeastOneReference
return true;
} else {
return false;
}
} else {
return false;
}
} | Checks if given folder is a git repository
@param folder
to check
@return true if it is a git repository, false otherwise. |
public Ref checkoutTag(Git git, String tag) {
try {
return git.checkout()
.setName("tags/" + tag).call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Checkout existing tag.
@param git
instance.
@param tag
to move
@return Ref to current branch |
public boolean isLocalBranch(final Git git, final String branch) {
try {
final List<Ref> refs = git.branchList().call();
return refs.stream()
.anyMatch(ref -> ref.getName().endsWith(branch));
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Checks if given branch has been checkedout locally too.
@param git
instance.
@param branch
to check.
@return True if it is local, false otherwise. |
public boolean isRemoteBranch(final Git git, final String branch, final String remote) {
try {
final List<Ref> refs = git.branchList()
.setListMode(ListBranchCommand.ListMode.REMOTE).call();
final String remoteBranch = remote + "/" + branch;
return refs.stream().anyMatch(ref -> ref.getName().endsWith(remoteBranch));
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Checks if given branch is remote.
@param git
instance.
@param branch
to check.
@param remote
name.
@return True if it is remote, false otherwise. |
public Ref checkoutBranch(Git git, String branch) {
try {
return git.checkout()
.setName(branch)
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Checkout existing branch.
@param git
instance.
@param branch
to move
@return Ref to current branch |
public Ref createBranchAndCheckout(Git git, String branch) {
try {
return git.checkout()
.setCreateBranch(true)
.setName(branch)
.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Executes a checkout -b command using given branch.
@param git
instance.
@param branch
to create and checkout.
@return Ref to current branch. |
public RevCommit addAndCommit(Git git, String message) {
try {
git.add()
.addFilepattern(".")
.call();
return git.commit()
.setMessage(message)
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Add all files and commit them with given message. This is equivalent as doing git add . git commit -m "message".
@param git
instance.
@param message
of the commit.
@return RevCommit of this commit. |
public PullResult pullFromRepository(Git git, String remote, String remoteBranch) {
try {
return git.pull()
.setRemote(remote)
.setRemoteBranchName(remoteBranch)
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Pull repository from current branch and remote branch with same name as current
@param git
instance.
@param remote
to be used.
@param remoteBranch
to use. |
public Iterable<PushResult> pushToRepository(Git git, String remote) {
try {
return git.push()
.setRemote(remote)
.setPushAll()
.setPushTags()
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Push all changes and tags to given remote.
@param git
instance.
@param remote
to be used.
@return List of all results of given push. |
public Iterable<PushResult> pushToRepository(Git git, String remote, String username, String password) {
try {
return git.push()
.setRemote(remote)
.setPushAll()
.setPushTags()
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Push all changes and tags to given remote.
@param git
instance.
@param remote
to be used.
@param username
to login.
@param password
to login.
@return List of all results of given push. |
public Ref createTag(Git git, String name) {
try {
return git.tag()
.setName(name)
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Creates a tag.
@param git
instance.
@param name
of the tag.
@return Ref created to tag. |
public Iterable<PushResult> pushToRepository(Git git, String remote, String passphrase, Path privateKey) {
SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
session.setUserInfo(new PassphraseUserInfo(passphrase));
}
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {
if (privateKey != null) {
JSch defaultJSch = super.createDefaultJSch(fs);
defaultJSch.addIdentity(privateKey.toFile().getAbsolutePath());
return defaultJSch;
} else {
return super.createDefaultJSch(fs);
}
}
};
try {
return git.push()
.setRemote(remote)
.setPushAll()
.setPushTags()
.setTransportConfigCallback(transport -> {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(sshSessionFactory);
})
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Push all changes and tags to given remote.
@param git
instance.
@param remote
to be used.
@param passphrase
to access private key.
@param privateKey
file location.
@return List of all results of given push. |
public PullResult pullFromRepository(Git git, String remote, String remoteBranch, String username, String password) {
try {
return git.pull()
.setRemote(remote)
.setRemoteBranchName(remoteBranch)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Pull repository from current branch and remote branch with same name as current
@param git
instance.
@param remote
to be used.
@param remoteBranch
to use.
@param username
to connect
@param password
to connect |
public PullResult pullFromRepository(final Git git, final String remote, String remoteBranch, final String passphrase,
final Path privateKey) {
SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
session.setUserInfo(new PassphraseUserInfo(passphrase));
}
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {
if (privateKey != null) {
JSch defaultJSch = super.createDefaultJSch(fs);
defaultJSch.addIdentity(privateKey.toFile().getAbsolutePath());
return defaultJSch;
} else {
return super.createDefaultJSch(fs);
}
}
};
try {
return git.pull()
.setRemote(remote)
.setRemoteBranchName(remoteBranch)
.setTransportConfigCallback(transport -> {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(sshSessionFactory);
})
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Pull repository from current branch and remote branch with same name as current
@param git
instance.
@param remote
to be used.
@param remoteBranch
to use.
@param passphrase
to access private key.
@param privateKey
file location. |
public Git cloneRepository(String remoteUrl, Path localPath) {
try {
return Git.cloneRepository()
.setURI(remoteUrl)
.setDirectory(localPath.toFile())
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Clones a public remote git repository. Caller is responsible of closing git repository.
@param remoteUrl
to connect.
@param localPath
where to clone the repo.
@return Git instance. Caller is responsible to close the connection. |
public Git cloneRepository(String remoteUrl, Path localPath, String username, String password) {
try {
return Git.cloneRepository()
.setURI(remoteUrl)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
.setDirectory(localPath.toFile())
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Clones a private remote git repository. Caller is responsible of closing git repository.
@param remoteUrl
to connect.
@param localPath
where to clone the repo.
@param username
to connect
@param password
to connect
@return Git instance. Caller is responsible to close the connection. |
public Git cloneRepository(final String remoteUrl, final Path localPath, final String passphrase,
final Path privateKey) {
SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
session.setUserInfo(new PassphraseUserInfo(passphrase));
}
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {
if (privateKey != null) {
JSch defaultJSch = super.createDefaultJSch(fs);
defaultJSch.addIdentity(privateKey.toFile().getAbsolutePath());
return defaultJSch;
} else {
return super.createDefaultJSch(fs);
}
}
};
try {
return Git.cloneRepository()
.setURI(remoteUrl)
.setTransportConfigCallback(transport -> {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(sshSessionFactory);
})
.setDirectory(localPath.toFile())
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | Clones a private remote git repository. Caller is responsible of closing git repository.
@param remoteUrl
to connect.
@param localPath
where to clone the repo.
@param passphrase
to access private key.
@param privateKey
file location. If null default (~.ssh/id_rsa) location is used.
@return Git instance. Caller is responsible to close the connection. |
public boolean hasAtLeastOneReference(Repository repo) {
for (Ref ref : repo.getAllRefs().values()) {
if (ref.getObjectId() == null)
continue;
return true;
}
return false;
} | Checks if a repo has been cloned correctly.
@param repo
to check
@return true if has been cloned correctly, false otherwise |
public Node attribute(final String name, final Object value) {
return attribute(name, String.valueOf(value));
} | Add or override a named attribute.<br/>
<br/>
value will be converted to String using String.valueOf(value);
@param name
The attribute name
@param value
The given value
@return This {@link Node}
@see #attribute(String, String) |
public Node attribute(final String name, final String value) {
this.attributes.put(name, value);
return this;
} | Add or override a named attribute.<br/>
@param name
The attribute name
@param value
The given value
@return This {@link Node} |
public String removeAttribute(final String name) throws IllegalArgumentException {
// Precondition check
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("name must be specified");
}
final String remove = this.attributes.remove(name);
return remove;
} | Remove a named attribute.<br/>
@param name
The attribute name
@return The attribute value that was removed, or null if the attribute with the given name was not found.
@throws IllegalArgumentException
If the name is not specified |
public void setComment(final boolean comment) throws IllegalArgumentException {
// Cannot have children
if (this.children.size() > 0) {
throw new IllegalArgumentException("Cannot mark a " + Node.class.getSimpleName()
+ " with children as a comment");
}
// Set
this.comment = comment;
} | Marks this {@link Node} as a comment
@param comment
Whether or not this is a comment
@return
@throws IllegalArgumentException
If this node has children |
public Node createChild(final String name) throws IllegalArgumentException {
// Precondition checks
if (name == null || name.trim().length() == 0) {
throw new IllegalArgumentException("name must be specified");
}
// Create
return createChild(Patterns.from(name));
} | Create a new {@link Node} with given name. <br/>
<br/>
The new {@link Node} will have this as parent.
@param name
The name of the {@link Node}.
@return A new child {@link Node}
@throws IllegalArgumentException
If the name is not specified |
public List<Node> removeChildren(final String name) throws IllegalArgumentException {
if (name == null || name.trim().length() == 0) {
throw new IllegalArgumentException("Path must not be null or empty");
}
List<Node> found = get(name);
for (Node child : found) {
children.remove(child);
}
return found;
} | Remove all child nodes found at the given query.
@return the {@link List} of removed children.
@throws IllegalArgumentException
If the specified name is not specified |
public List<Node> removeChildren(final Pattern pattern, final Pattern... patterns) {
// Precondition check
final Pattern[] merged = this.validateAndMergePatternInput(pattern, patterns);
final List<Node> found = get(merged);
if (found == null) {
return Collections.emptyList();
}
for (Node child : found) {
children.remove(child);
}
return found;
} | Remove all child nodes found at the given {@link Pattern}s.
@return the {@link List} of removed children.
@throws IllegalArgumentException
If pattern is not specified |
public Node removeChild(final String name) {
final Node node = getSingle(name);
if (node != null) {
removeChild(node);
}
return node;
} | Remove a single child from this {@link Node}
@return true if this node contained the given child
@throws IllegalArgumentException
if multiple children with name exist. |
public String getTextValueForPatternName(final String name) {
Node n = this.getSingle(name);
String text = n == null ? null : n.getText();
return text;
} | Get the text value of the element found at the given query name. If no element is found, or no text exists,
return null; |
public List<String> getTextValuesForPatternName(final String name) {
List<String> result = new ArrayList<String>();
List<Node> jars = this.get(name);
for (Node node : jars) {
String text = node.getText();
if (text != null) {
result.add(text);
}
}
return Collections.unmodifiableList(result);
} | Get the text values of all elements found at the given query name. If no elements are found, or no text exists,
return an empty list; |
private Node deepCopy(final Node copyTarget){
// Precondition checks
assert copyTarget != null : "Node to copy information into must be specified";
// Set attributes
final Map<String, String> attributes = this.getAttributes();
final Set<String> attributeKeys = attributes.keySet();
for (final String key : attributeKeys) {
final String value = attributes.get(key);
copyTarget.attribute(key, value);
}
// Set text
copyTarget.text(this.getText());
// Set children
final List<Node> children = this.getChildren();
for (final Node child : children) {
final Node newChild = copyTarget.createChild(child.getName());
// Recurse in
child.deepCopy(newChild);
}
// Return
return this;
} | Copies <code>this</code> reference to the specified {@link Node}
@param copyTarget
@return |
private Pattern[] validateAndMergePatternInput(final Pattern pattern, final Pattern... patterns) {
// Precondition check
if (pattern == null) {
throw new IllegalArgumentException("At least one pattern must not be specified");
}
final List<Pattern> merged = new ArrayList<Pattern>();
merged.add(pattern);
for (final Pattern p : patterns) {
merged.add(p);
}
return merged.toArray(PATTERN_CAST);
} | Validates that at least one pattern was specified, merges all patterns together, and returns the result
@param pattern
@param patterns
@return |
public static <T extends Descriptor> T create(final Class<T> type) throws IllegalArgumentException {
return create(type, null);
} | Creates a new Descriptor instance; the predefined default descriptor name for this type will be used.
@param <T>
@param type
@return
@see #create(Class, String)
@throws IllegalArgumentException
If the type is not specified |
public static <T extends Descriptor> T create(final Class<T> type, final String descriptorName)
throws IllegalArgumentException {
// Precondition checks
if (type == null) {
throw new IllegalArgumentException("type must be specified");
}
// Create
return DescriptorInstantiator.createFromUserView(type, descriptorName);
} | Creates a new named {@link Descriptor} instance. If the name specified is null, the default name for this type
will be assigned.
@param <T>
@param type
@param descriptorName
the descriptor name
@return
@throws IllegalArgumentException
If the type is not specified |
public static <T extends Descriptor> DescriptorImporter<T> importAs(final Class<T> type)
throws IllegalArgumentException {
return importAs(type, null);
} | Returns a new {@link DescriptorImporter} instance, ready to import as a new {@link Descriptor} instance of the
given type
@param type
@return
@throws IllegalArgumentException
If the type is not specified |
public static <T extends Descriptor> DescriptorImporter<T> importAs(final Class<T> type, final String descriptorName)
throws IllegalArgumentException {
// Precondition checks
if (type == null) {
throw new IllegalArgumentException("type must be specified");
}
// Create new importer
return DescriptorInstantiator.createImporterFromUserView(type, descriptorName);
} | Returns a new named {@link DescriptorImporter} instance, ready to import as a new {@link Descriptor} instance of
the given type. If the name specified is null, the default name for this type will be assigned.
@param type
@param descriptorName
@return
@throws IllegalArgumentException
If the type is not specified |
public void generateEnums() throws JClassAlreadyExistsException, IOException {
final JCodeModel cm = new JCodeModel();
for (final MetadataEnum metadataEnum : metadata.getEnumList()) {
final String fqnEnum = metadataEnum.getPackageApi() + "." + getPascalizeCase(metadataEnum.getName());
final JDefinedClass dc = cm._class(fqnEnum, ClassType.ENUM);
final JDocComment javaDocComment = dc.javadoc();
final Map<String, String> part = javaDocComment.addXdoclet("author");
part.put("<a href", "'mailto:[email protected]'>Ralf Battenfeld</a>");
for (final String enumConstant : metadataEnum.getValueList()) {
dc.enumConstant(getEnumConstantName(enumConstant));
}
final JMethod toStringMethod = dc.method(1, String.class, "toString");
toStringMethod.body()._return(JExpr.direct("name().substring(1)"));
}
final File file = new File("./src/test/java");
file.mkdirs();
cm.build(file);
} | Generates all enumeration classes.
@param metadata
@throws JClassAlreadyExistsException
@throws IOException |
public boolean isEnum(final String elementType) {
final String namespace = splitElementType(elementType)[0];
final String localname = splitElementType(elementType)[1];
boolean isEnum = false;
for (final MetadataEnum metadataEnum : metadata.getEnumList()) {
if (metadataEnum.getName().equals(localname) && metadataEnum.getNamespace().equals(namespace)) {
isEnum = true;
break;
}
}
return isEnum;
} | Returns true, if the given string argument represents a enumeration class.
@param elementName
@return true, if the string represents a enumeration, otherwise false. |
public static Long getProfileLastModifiedCookie(HttpServletRequest request) {
String profileLastModified = HttpUtils.getCookieValue(PROFILE_LAST_MODIFIED_COOKIE_NAME, request);
if (StringUtils.isNotEmpty(profileLastModified)) {
try {
return new Long(profileLastModified);
} catch (NumberFormatException e) {
logger.error("Invalid profile last modified cookie format: {}", profileLastModified);
}
}
return null;
} | Returns the last modified timestamp cookie from the request.
@param request the request where to retrieve the last modified timestamp from
@return the last modified timestamp of the authenticated profile |
public static Authentication getCurrentAuthentication() {
RequestContext context = RequestContext.getCurrent();
if (context != null) {
return getAuthentication(context.getRequest());
} else {
return null;
}
} | Returns the authentication attribute from the current request.
@return the authentication object |
public static void setCurrentAuthentication(Authentication authentication) {
RequestContext context = RequestContext.getCurrent();
if (context != null) {
setAuthentication(context.getRequest(), authentication);
}
} | Sets the authentication attribute in the current request.
@param authentication the authentication object to set as request attribute |
public static void removeCurrentAuthentication() {
RequestContext context = RequestContext.getCurrent();
if (context != null) {
removeAuthentication(context.getRequest());
}
} | Removes the authentication attribute from the current request. |
public static Profile getCurrentProfile() {
RequestContext context = RequestContext.getCurrent();
if (context != null) {
return getProfile(context.getRequest());
} else {
return null;
}
} | Returns the profile from authentication attribute from the current request.
@return the profile object, or null if there's no authentication |
public static Profile getProfile(HttpServletRequest request) {
Authentication auth = getAuthentication(request);
if (auth != null) {
return auth.getProfile();
} else {
return null;
}
} | Returns the profile from authentication attribute from the specified request.
@return the profile object, or null if there's no authentication |
public static void redirect(HttpServletRequest request, HttpServletResponse response,
String url) throws IOException {
String redirectUrl;
if (url.startsWith("/")) {
redirectUrl = request.getContextPath() + url;
} else {
redirectUrl = url;
}
logger.debug("Redirecting to URL: {}", redirectUrl);
response.sendRedirect(redirectUrl);
} | Redirects to the specified URL. If the URL starts with '/', the request context path is added.
@param request the request
@param response the response
@param url the URL to redirect to |
@Required
public void setUrlRestrictions(Map<String, String> restrictions) {
urlRestrictions = new LinkedHashMap<>();
ExpressionParser parser = new SpelExpressionParser();
for (Map.Entry<String, String> entry : restrictions.entrySet()) {
urlRestrictions.put(entry.getKey(), parser.parseExpression(entry.getValue()));
}
} | Sets the map of restrictions. Each key of the map is ANT-style path pattern, used to match the URLs of incoming
requests, and each value is a Spring EL expression. |
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain) throws Exception {
Map<String, Expression> urlRestrictions = getUrlRestrictions();
if (MapUtils.isNotEmpty(urlRestrictions)) {
HttpServletRequest request = context.getRequest();
String requestUrl = getRequestUrl(context.getRequest());
logger.debug("Checking access restrictions for URL {}", requestUrl);
for (Map.Entry<String, Expression> entry : urlRestrictions.entrySet()) {
String urlPattern = entry.getKey();
Expression expression = entry.getValue();
if (pathMatcher.match(urlPattern, requestUrl)) {
logger.debug("Checking restriction [{} => {}]", requestUrl, expression.getExpressionString());
if (isAccessAllowed(request, expression)) {
logger.debug("Restriction [{}' => {}] evaluated to true for user: access allowed", requestUrl,
expression.getExpressionString());
break;
} else {
throw new AccessDeniedException("Restriction ['" + requestUrl + "' => " +
expression.getExpressionString() + "] evaluated to false " +
"for user: access denied");
}
}
}
}
processorChain.processRequest(context);
} | Matches the request URL against the keys of the {@code restriction} map, which are ANT-style path patterns. If
a key matches, the value is interpreted as a Spring EL expression, the expression is executed, and if it returns
true, the processor chain is continued, if not an {@link AccessDeniedException} is thrown.
@param context the context which holds the current request and response
@param processorChain the processor chain, used to call the next processor |
private void loadImage() {
List<Transformation> transformations = getTransformations();
boolean hasUrl = url != null;
boolean hasResourceId = resourceId != null;
boolean hasPlaceholder = placeholderId != null;
ListenerTarget listenerTarget = getLinearTarget(listener);
if (hasUrl) {
RequestCreator bitmapRequest = Picasso.with(context).load(url).tag(PICASSO_IMAGE_LOADER_TAG);
applyPlaceholder(bitmapRequest).resize(size, size)
.transform(transformations)
.into(listenerTarget);
} else if (hasResourceId || hasPlaceholder) {
Resources resources = context.getResources();
Drawable placeholder = null;
Drawable drawable = null;
if (hasPlaceholder) {
placeholder = resources.getDrawable(placeholderId);
listenerTarget.onPrepareLoad(placeholder);
}
if (hasResourceId) {
drawable = resources.getDrawable(resourceId);
listenerTarget.onDrawableLoad(drawable);
}
} else {
throw new IllegalArgumentException(
"Review your request, you are trying to load an image without a url or a resource id.");
}
} | Uses the configuration previously applied using this ImageLoader builder to download a
resource asynchronously and notify the result to the listener. |
private ListenerTarget getLinearTarget(final Listener listener) {
ListenerTarget target = targets.get(listener);
if (target == null) {
target = new ListenerTarget(listener);
targets.put(listener, target);
}
return target;
} | Given a listener passed as argument creates or returns a lazy instance of a Picasso Target.
This implementation is needed because Picasso doesn't keep a strong reference to the target
passed as parameter. Without this method Picasso looses the reference to the target and never
notifies when the resource has been downloaded.
Listener and Target instances are going to be stored into a WeakHashMap to avoid a memory leak
when ImageLoader client code is garbage collected. |
private List<Transformation> getTransformations() {
if (transformations == null) {
transformations = new LinkedList<Transformation>();
if (useCircularTransformation) {
transformations.add(new CircleTransformation());
}
}
return transformations;
} | Lazy instantiation of the list of transformations used during the image download. This method
returns a List<Transformation> because Picasso doesn't support a null instance as
transformation. |
public ElasticSearch format(ElasticSearchFormat format) {
String strFormat;
switch (format) {
case FULL_INTERACTION_META:
strFormat = "full_interaction_meta";
break;
default:
case BASIC_INTERACTION_META:
strFormat = "basic_interaction_meta";
break;
}
return setParam("format", strFormat);
} | /*
The output format for your data:
basic_interaction_meta - The current default format, where each payload contains only basic interaction JSON
document.
full_interaction_meta - The payload is a full interaction with augmentations.
Take a look at our
<a href="http://dev.datasift.com/docs/push/sample-output-database-connectors">Sample Output for Database
Connectors page.</a>
@return this |
public S3 format(S3OutputFormat format) {
String strFormat;
switch (format) {
case JSON_ARRAY:
strFormat = "json_array";
break;
case JSON_NEW_LINE:
strFormat = "json_new_line";
break;
case JSON_META:
default:
strFormat = "json_meta";
break;
}
setParam("format", strFormat);
return this;
} | /*
Sets the output format for your data
@param format one of the allowed S3 formats, defaults to json_meta
@return this |
static DateTimeZone getDateTimeZone(PageContext pc, Tag fromTag) {
DateTimeZone tz = null;
Tag t = findAncestorWithClass(fromTag, DateTimeZoneSupport.class);
if (t != null) {
// use time zone from parent <timeZone> tag
DateTimeZoneSupport parent = (DateTimeZoneSupport) t;
tz = parent.getDateTimeZone();
} else {
// get time zone from configuration setting
Object obj = Config.find(pc, FMT_TIME_ZONE);
if (obj != null) {
if (obj instanceof DateTimeZone) {
tz = (DateTimeZone) obj;
} else {
try {
tz = DateTimeZone.forID((String) obj);
} catch (IllegalArgumentException iae) {
tz = DateTimeZone.UTC;
}
}
}
}
return tz;
} | Determines and returns the time zone to be used by the given action.
<p>
If the given action is nested inside a <dateTimeZone> action,
the time zone is taken from the enclosing <dateTimeZone> action.
<p>
Otherwise, the time zone configuration setting
<tt>org.joda.time.FMT_TIME_ZONE</tt> is used.
@param pc the page containing the action for which the time zone
needs to be determined
@param fromTag the action for which the time zone needs to be determined
@return the time zone, or <tt> null </tt> if the given action is not
nested inside a <dateTimeZone> action and no time zone configuration
setting exists |
void stopEventBus(@Observes StopBus event) {
CommandBusOnClient bus = commandBusInst.get();
bus.stopBus();
} | Stops the Event Bus |
public static <T> T contextualize(final OperationalContext context, final T instance, Class<?> interfaze,
Class<?>... contextPropagatingInterfaces) {
OperationalContextRetriver retriever = new OperationalContextRetriver() {
@Override
public OperationalContext retrieve() {
return context;
}
};
return contextualize(retriever, instance, interfaze);
} | Contextualizes operation with contexts given by {@link OperationalContext}
@param retriever the context
@param instance the instance to wrap (must comply with given interface)
@param interfaze the interface of return object
@param contextPropagatingInterfaces when a return type of any invocation is one of these interfaces, the given result will be call contextually as well |
@SuppressWarnings("unchecked")
public static <T> T contextualize(final OperationalContextRetriver retriver, final T instance, Class<?> interfaze,
final Class<?>... contextPropagatingInterfaces) {
return (T) Proxy.newProxyInstance(instance.getClass().getClassLoader(), new Class<?>[] {interfaze},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
OperationalContext context = retriver.retrieve();
context.activate();
try {
Object result = method.invoke(instance, args);
Class<?> type = method.getReturnType();
if (result != null && type != null && type.isInterface() && Arrays.asList(
contextPropagatingInterfaces).contains(type)) {
return contextualize(retriver, result, type, contextPropagatingInterfaces);
} else {
return result;
}
} catch (InvocationTargetException e) {
throw e.getTargetException();
} finally {
context.deactivate();
}
}
});
} | Contextualizes operation with contexts given by {@link OperationalContext} which is given by provided
{@link OperationalContextRetriver}
@param retriever the context retriever
@param instance the instance to wrap (must comply with given interface)
@param interfaze the interface of return object
@param contextPropagatingInterfaces when a return type of any invocation is one of these interfaces, the given result will be call contextually as well |
@Override
public boolean isEnriched(HttpRequest request, HttpResponse response) {
Long serialId = getSerialId(request);
return serialId != null;
} | /*
(non-Javadoc)
@see
org.jboss.arquillian.warp.impl.client.enrichment.HttpResponseDeenrichmentService#isEnriched(org.jboss.netty.handler.codec
.http.HttpResponse) |
@Override
public void deenrichResponse(HttpRequest request, HttpResponse response) {
final WarpContext context = WarpContextStore.get();
try {
long serialId = getSerialId(request);
ResponsePayload payload = retrieveResponsePayload(serialId);
if (context != null) {
verifyResponsePayload.fire(new VerifyResponsePayload(payload));
context.pushResponsePayload(payload);
}
} catch (Exception originalException) {
if (context != null) {
WarpExecutionException explainingException;
if (originalException instanceof WarpExecutionException) {
explainingException = (WarpExecutionException) originalException;
} else {
explainingException = new ClientWarpExecutionException("deenriching response failed: "
+ originalException.getMessage(), originalException);
}
context.pushException(explainingException);
} else {
log.log(Level.WARNING, "Unable to push exception to WarpContext", originalException);
}
}
} | /*
(non-Javadoc)
@see
org.jboss.arquillian.warp.impl.client.enrichment.HttpResponseDeenrichmentService#deenrichResponse(org.jboss.netty.handler
.codec.http.HttpResponse) |
private ResponsePayload retrieveResponsePayload(long serialId) throws InterruptedException {
ResponsePayloadWasNeverRegistered last = null;
for (int i = 0; i <= 10; i++) {
try {
RetrievePayloadFromServer result =
remoteOperationService().execute(new RetrievePayloadFromServer(serialId));
return result.getResponsePayload();
} catch (ResponsePayloadWasNeverRegistered e) {
Thread.sleep(300);
last = e;
} catch (Throwable e) {
throw new ServerWarpExecutionException("failed to retrieve a response payloade: " + e.getMessage(), e);
}
}
throw last;
} | Contacts server and tries to retrieve response payload via serialId.
<p>
Repeats the retrieval until the payload is found or number of allowed iterations is reached. |
public Map<String, String> verifyAndGet() {
for (String paramName : required) {
if (params.get(paramName) == null) {
throw new IllegalStateException(format("Param %s is required but has not been supplied", paramName));
}
}
return params;
} | /*
Verifies that all required parameters have been set
@return a map of the parameters |
public FutureData<HistoricsPreview> create(long start, long end, Stream stream, String[] parameters) {
if (stream == null) {
throw new IllegalArgumentException("A valid hash is required");
}
if (parameters == null || parameters.length == 0) {
throw new IllegalArgumentException("A at least 1 historics preview parameter is required");
}
if (parameters.length > 20) {
throw new IllegalArgumentException("No more than 20 historics preview parameters are allowed");
}
FutureData<HistoricsPreview> future = new FutureData<HistoricsPreview>();
URI uri = newParams().forURL(config.newAPIEndpointURI(CREATE));
POST request = config.http()
.POST(uri, new PageReader(newRequestCallback(future, new HistoricsPreview(), config)))
.form("start", start)
.form("hash", stream.hash());
StringBuilder b = new StringBuilder();
for (String p : parameters) {
b.append(p).append(',');
}
request.form("parameters", b.toString().substring(0, b.length() - 1));
if (end > 0) {
request.form("end", end);
}
performRequest(future, request);
return future;
} | /*
Create a historic preview for the given stream within the given time frame, using the set of parameters provided
@param start a timestamp of when to start the preview from
@param end optionally when the preview ends - If not specified, i.e. set to a value less than 1,
defaults to the earliest out of start + 24 hours or now - 1 hour.
@param stream the stream/filter to create the preview for
@param parameters A list of at least one but no more than 20 Historics Preview parameters e.g. target,
pylon, argument see http://dev.datasift.com/docs/api/rest-api/endpoints/previewcreate
for documentation of available parameters
@return the preview created |
public FutureData<HistoricsPreviewData> get(HistoricsPreview preview) {
if (preview == null || preview.id() == null) {
throw new IllegalArgumentException("A valid preview isntance is required");
}
FutureData<HistoricsPreviewData> future = new FutureData<HistoricsPreviewData>();
URI uri = newParams().forURL(config.newAPIEndpointURI(GET));
POST request = config.http()
.POST(uri, new PageReader(newRequestCallback(future, new HistoricsPreviewData(), config)))
.form("id", preview.id());
performRequest(future, request);
return future;
} | /*
Get the data that's available for the given preview
@param preview the historics preview to fetch
@return the data available |
public static <T extends Annotation> T get(Class<T> annotationType, Map<String, ?> values) {
if (annotationType == null) {
throw new IllegalArgumentException("Must specify an annotation");
}
Class<?> clazz = Proxy.getProxyClass(annotationType.getClassLoader(), annotationType, Serializable.class);
AnnotationInvocationHandler handler = new AnnotationInvocationHandler(values, annotationType);
// create a new instance by obtaining the constructor via relection
try {
return annotationType.cast(clazz.getConstructor(new Class[] {InvocationHandler.class}).newInstance(
new Object[] {handler}));
} catch (IllegalArgumentException e) {
throw new IllegalStateException(
"Error instantiating proxy for annotation. Annotation type: " + annotationType, e);
} catch (InstantiationException e) {
throw new IllegalStateException(
"Error instantiating proxy for annotation. Annotation type: " + annotationType, e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Error instantiating proxy for annotation. Annotation type: " + annotationType, e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(
"Error instantiating proxy for annotation. Annotation type: " + annotationType,
e.getCause());
} catch (SecurityException e) {
throw new IllegalStateException("Error accessing proxy constructor for annotation. Annotation type: "
+ annotationType, e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Error accessing proxy constructor for annotation. Annotation type: "
+ annotationType, e);
}
} | <p>
Returns an instance of the given annotation type with attribute values specified in the map.
</p>
<p>
<ul>
<li>
For {@link Annotation}, array and enum types the values must exactly match the declared return type of the attribute or a
{@link ClassCastException} will result.</li>
<p>
<li>
For character types the the value must be an instance of {@link Character} or {@link String}.</li>
<p>
<li>
Numeric types do not have to match exactly, as they are converted using {@link Number}.</li>
</ul>
<p>
<p>
If am member does not have a corresponding entry in the value map then the annotations default value will be used.
</p>
<p>
<p>
If the annotation member does not have a default value then a NullMemberException will be thrown
</p>
@param annotationType the type of the annotation instance to generate
@param values the attribute values of this annotation |
public static <A extends BaseDataSiftResult> FutureData<A> wrap(A obj) {
if (obj == null) {
throw new IllegalArgumentException("You cannot wrap null as future data");
}
FutureData<A> future = new FutureData<A>();
obj.setResponse(new WrappedResponse());
future.data = obj;
return future;
} | /*
Wraps any object in a {@link FutureData} instance
<p/>
Intended use is to enable any object obtained without a future to be passed to API methods.
This allows API methods to accept FutureData objects and alleviates the need for a user to add
many callbacks and instead just pass futures around as if they were already obtained values.
Note that any listeners added will be immediately invoked/notified, seeing as the result they would
await has already been obtained
@param obj the object to wrap
@param <A> the type of the object
@return a future that will fire onData events for the given object |
public FutureData<T> onData(FutureResponse<T> response) {
this.listeners.add(response);
//if we already received a response then notify straight away
if (this.data != null) {
response.apply(this.data);
doNotify();
}
return this;
} | /*
Adds an event listener that is notified when data is received
@param response the future which should listen for a response
@return this to enable chaining |
public T sync() {
//if data is present there's no need to block
if (data != null) {
return data;
}
synchronized (this) {
try {
// wait();
block.take();
} catch (InterruptedException e) {
if (interruptCause == null) {
interruptCause = e;
}
}
if (interruptCause != null) {
if (interruptCause instanceof DataSiftException) {
throw (DataSiftException) interruptCause;
} else {
throw new DataSiftException("Interrupted while waiting for response", interruptCause);
}
}
return data;
}
} | /*
Forces the client to wait until a response is received before returning
@return a result instance - if an interrupt exception is thrown it is possible that a response isn't available
yet the user must check to ensure null isn't returned |
public boolean tryDelegateRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
for (RequestDelegationService service : delegationServices) {
if (canDelegate(service, request)) {
delegate(service, request, response, filterChain);
return true;
}
}
return false;
} | Checks whether the request should be delegated to some of the registered {@link RequestDelegationService}s. |
private void delegate(RequestDelegationService service, HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) {
try {
service.delegate(request, response, filterChain);
} catch (Exception e) {
throw new RequestDelegationException(
String.format("The request processing delegation failed: %s", e.getCause()), e);
}
} | Delegates given request and response to be processed by given service.
@throws RequestDelegationException in case the delegated request processing fails |
private boolean canDelegate(RequestDelegationService delegate, HttpServletRequest request) {
try {
return delegate.canDelegate(request);
} catch (Exception e) {
log.log(Level.SEVERE,
String.format("The delegation service can't check the delegability of the request: %s", e.getCause()),
e.getCause());
return false;
}
} | Checks whether the given service can serve given request. |
public static PushSubscription fromString(String str) {
if (str == null || str.isEmpty()) {
throw new IllegalArgumentException("Cannot create a stream from an empty or null string");
}
PushSubscription stream = new PushSubscription();
stream.id = str;
return stream;
} | /*
Create a {@link PushSubscription} instance containing only an id
@param str the ID obtained from DataSift for creating a push subscription
@return an instance which can be used by the client |
public static HttpMethod valueOf(String name) {
if (name == null) {
throw new NullPointerException("name");
}
name = name.trim().toUpperCase();
if (name.length() == 0) {
throw new IllegalArgumentException("empty name");
}
HttpMethod result = methodMap.get(name);
if (result != null) {
return result;
} else {
return new HttpMethod(name);
}
} | Returns the {@link HttpMethod} represented by the specified name.
If the specified name is a standard HTTP method name, a cached instance
will be returned. Otherwise, a new instance will be returned. |
public void verifyWarpDeployment(@Observes DeploymentScenario deploymentScenario) {
if (WarpCommons.isWarpTest(testClass.get().getJavaClass())) {
for (Deployment deployment : deploymentScenario.deployments()) {
DeploymentDescription description = deployment.getDescription();
if (!description.testable()) {
throw new IllegalArgumentException(
"Warp deployments must be testable: " + testClass.get().getJavaClass()
+ " - check that you have @Deployment(testable=true)");
}
}
}
} | Verifies that deployments for Warp tests are all testable |
@Override
public HttpFilterBuilder addFilter(RequestFilter<HttpRequest> filter) {
requestFilter = new ChainHttpRequestFilter(filter, requestFilter);
return this;
} | {@inheritDoc} |
public static <T> LifecycleManager get(Class<T> type, T boundObject) throws ObjectNotAssociatedException {
return getCurrentStore().obtain(type, boundObject);
} | Retrieves instance of {@link LifecycleManager} for given instance of given class.
@param clazz the class used as denominator during retrieval
@param boundObject the object used as key for retriving {@link LifecycleManager}
@return the bound instance of {@link LifecycleManager}
@throws ObjectNotAssociatedException when instance of no such class and class' instance was associated with any
{@link LifecycleManager} |
static LifecycleManagerStore getCurrentStore() {
LifecycleManagerStore store = INSTANCE.get();
if (store != null) {
return store;
}
try {
InputStream resourceAsStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("META-INF/services/" + LifecycleManagerStore.class.getName());
if (resourceAsStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(resourceAsStream));
String type = reader.readLine();
store = (LifecycleManagerStore) Class.forName(type).newInstance();
INSTANCE.compareAndSet(null, store);
return INSTANCE.get();
}
} catch (Exception e) {
throw new IllegalStateException("Cannot load " + LifecycleManagerStore.class.getSimpleName() + " service", e);
}
throw new IllegalStateException("No " + LifecycleManagerStore.class.getSimpleName() + " service is defined");
} | Retrieves instance of {@link LifecycleManager} for given instance of given class.
@param clazz the class used as denominator during retrieval
@param boundObject the object used as key for retriving {@link LifecycleManager}
@return the bound instance of {@link LifecycleManager}
@throws ObjectNotAssociatedException when instance of no such class and class' instance was associated with any
{@link LifecycleManager} |
public static PylonStream fromString(String str) {
if (str == null || str.isEmpty()) {
throw new IllegalArgumentException("Cannot create a stream from an empty or null string");
}
PylonStream stream = new PylonStream();
stream.hash = str;
return stream;
} | /*
Create a stream instance containing only a hash
@param str the hash obtained from DataSift for a stream
@return an instance which can be used by the client |
void awaitRequests() {
if (!isWaitingForEnriching()) {
return;
}
for (int i = 0; i < NUMBER_OF_WAIT_LOOPS; i++) {
try {
Thread.sleep(THREAD_SLEEP);
if (!isEnrichmentAdvertised()) {
return;
}
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
throw new SettingRequestTimeoutException();
} | Await client activity causing requests in order to enrich requests |
void awaitResponses() {
try {
boolean finishedNicely = responseFinished.await(WAIT_TIMEOUT_MILISECONDS, TimeUnit.MILLISECONDS);
if (!finishedNicely) {
throw new WarpSynchronizationException(WarpContextStore.get());
}
} catch (InterruptedException e) {
}
} | Await responses for requests or premature finishing |
public SFTP auth(String username, String password) {
return username(username).password(password);
} | /*
Sets the authentication information that should be used for the connector
@param username the username
@param password the password
@return this |
public SFTP format(SFTPFormat format) {
String strFormat;
switch (format) {
case JSON_ARRAY:
strFormat = "json_array";
break;
case JSON_NEW_LINE:
strFormat = "json_new_line";
break;
default:
case JSON_META:
strFormat = "json_meta";
break;
}
return setParam("format", strFormat);
} | /*
The output format for your data:
<p/>
json_meta - The current default format, where each payload contains a full JSON document. It contains metadata
and an "interactions" property that has an array of interactions.
<p/>
json_array - The payload is a full JSON document, but just has an array of interactions.
<p/>
json_new_line - The payload is NOT a full JSON document. Each interaction is flattened and separated by a line
break.
If you omit this parameter or set it to json_meta, your output consists of JSON metadata followed by a JSON
array of interactions (wrapped in square brackets and separated by commas).
Take a look at our Sample Output for File-Based Connectors page.
If you select json_array, DataSift omits the metadata and sends just the array of interactions.
If you select json_new_line, DataSift omits the metadata and sends each interaction as a single JSON object.
@return this |
public void setDateTimeZone(Object dtz) throws JspTagException {
if (dtz == null || dtz instanceof String
&& ((String) dtz).length() == 0) {
this.dateTimeZone = null;
} else if (dtz instanceof DateTimeZone) {
this.dateTimeZone = (DateTimeZone) dtz;
} else {
try {
this.dateTimeZone = DateTimeZone.forID((String) dtz);
} catch (IllegalArgumentException iae) {
this.dateTimeZone = DateTimeZone.UTC;
}
}
} | Sets the zone attribute.
@param dtz the zone |
public void setLocale(Object loc) throws JspTagException {
if (loc == null
|| (loc instanceof String && ((String) loc).length() == 0)) {
this.locale = null;
} else if (loc instanceof Locale) {
this.locale = (Locale) loc;
} else {
locale = Util.parseLocale((String) loc);
}
} | Sets the style attribute.
@param loc the locale |
private boolean isJodaTag(String tagUri, String tagLn, String target) {
return isTag(tagUri, tagLn, this.uri, target);
} | } |
protected boolean hasNoInvalidScope(Attributes a) {
String scope = a.getValue(SCOPE);
if ((scope != null) && !scope.equals(PAGE_SCOPE)
&& !scope.equals(REQUEST_SCOPE) && !scope.equals(SESSION_SCOPE)
&& !scope.equals(APPLICATION_SCOPE)) {
return false;
}
return true;
} | returns true if the 'scope' attribute is valid |
protected boolean hasDanglingScope(Attributes a) {
return (a.getValue(SCOPE) != null && a.getValue(VAR) == null);
} | returns true if the 'scope' attribute is present without 'var' |
protected String getLocalPart(String qname) {
int colon = qname.indexOf(":");
return (colon == -1) ? qname : qname.substring(colon + 1);
} | retrieves the local part of a QName |
private static ValidationMessage[] vmFromVector(Vector v) {
ValidationMessage[] vm = new ValidationMessage[v.size()];
for (int i = 0; i < vm.length; i++) {
vm[i] = (ValidationMessage) v.get(i);
}
return vm;
} | constructs a ValidationMessage[] from a ValidationMessage Vector |
@Override
public HttpFilterBuilder equal(final String parameterName, final String value) {
return addFilter(new RequestFilter<HttpRequest>() {
@Override
public boolean matches(HttpRequest request) {
final List<String> parameters = getParameterListOrNull(request, parameterName);
return parameters != null && parameters.size() == 1 && parameters.contains(value);
}
@Override
public String toString() {
return String.format("parameter.equal('%s', '%s')", parameterName, value);
}
});
} | {@inheritDoc} |
@Override
public HttpFilterBuilder containsParameter(final String parameterName) {
return addFilter(new RequestFilter<HttpRequest>() {
@Override
public boolean matches(HttpRequest request) {
final List<String> parameters = getParameterListOrNull(request, parameterName);
return parameters != null;
}
@Override
public String toString() {
return String.format("containsParameter('%s')", parameterName);
}
});
} | {@inheritDoc} |
public static HistoricsQuery fromString(String historicsQueryId) {
if (historicsQueryId == null || historicsQueryId.isEmpty()) {
throw new IllegalArgumentException("Cannot create a stream from an empty or null string");
}
HistoricsQuery stream = new HistoricsQuery();
stream.id = historicsQueryId;
return stream;
} | /*
Create a HistoricsQuery instance containing only an ID
@param historicsQueryId the id obtained from DataSift
@return an instance which can be used by the client |
public static URL buildUrl(String context, String... relocations) {
try {
return buildUrl(new URL(context), relocations);
} catch (MalformedURLException e) {
throw new AssertionError("URL('" + context + "') isn't valid URL");
}
} | Use URL context and one or more relocations to build end URL.
@param context first URL used like a context root for all relocation changes
@param relocations array of relocation URLs
@return end url after all changes made on context with relocations
@throws AssertionError when context or some of relocations are malformed URLs |
public static URL buildUrl(URL context, String... relocations) {
URL url = context;
for (String move : relocations) {
try {
url = new URL(url, move);
} catch (MalformedURLException e) {
throw new AssertionError("URL('" + url + "', '" + move + "') isn't valid URL");
}
}
return url;
} | Use URL context and one or more relocations to build end URL.
@param context first URL used like a context root for all relocation changes
@param relocations array of relocation URLs
@return end url after all changes made on context with relocations
@throws AssertionError when context or some of relocations are malformed URLs |
public void onModuleLoad() {
RestRequestBuilder.setDefaultApplicationPath( "rest" );
final Button sendGetButton = new Button( "GET" );
final Button sendPostButton = new Button( "POST" );
final Button sendPostPathButton = new Button( "POST + Path" );
final TextBox nameField = new TextBox();
nameField.setText( "GWT User" );
final Label errorLabel = new Label();
// We can add style names to widgets
sendGetButton.addStyleName( "sendButton" );
sendPostButton.addStyleName( "sendButton" );
sendPostPathButton.addStyleName( "sendButton" );
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get( "nameFieldContainer" ).add( nameField );
RootPanel.get( "sendButtonContainer" ).add( sendGetButton );
RootPanel.get( "sendButtonContainer" ).add( sendPostButton );
RootPanel.get( "sendButtonContainer" ).add( sendPostPathButton );
RootPanel.get( "errorLabelContainer" ).add( errorLabel );
// Focus the cursor on the name field when the app loads
nameField.setFocus( true );
nameField.selectAll();
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText( "Remote Procedure Call" );
dialogBox.setAnimationEnabled( true );
final Button closeButton = new Button( "Close" );
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId( "closeButton" );
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName( "dialogVPanel" );
dialogVPanel.add( new HTML( "<b>Sending name to the server:</b>" ) );
dialogVPanel.add( textToServerLabel );
dialogVPanel.add( new HTML( "<br><b>Server replies:</b>" ) );
dialogVPanel.add( serverResponseLabel );
dialogVPanel.setHorizontalAlignment( VerticalPanel.ALIGN_RIGHT );
dialogVPanel.add( closeButton );
dialogBox.setWidget( dialogVPanel );
// Add a handler to close the DialogBox
closeButton.addClickHandler( new ClickHandler() {
public void onClick( ClickEvent event ) {
dialogBox.hide();
sendGetButton.setEnabled( true );
sendPostButton.setEnabled( true );
sendPostPathButton.setEnabled( true );
}
} );
// Create a handler for the sendButton and nameField
class MyHandler implements ClickHandler, KeyUpHandler {
private final int req;
MyHandler( int req ) {
this.req = req;
}
/**
* Fired when the user clicks on the sendButton.
*/
public void onClick( ClickEvent event ) {
sendNameToServer();
}
/**
* Fired when the user types in the nameField.
*/
public void onKeyUp( KeyUpEvent event ) {
if ( event.getNativeKeyCode() == KeyCodes.KEY_ENTER ) {
sendNameToServer();
}
}
/**
* Send the name from the nameField to the server and wait for a response.
*/
private void sendNameToServer() {
// First, we validate the input.
errorLabel.setText( "" );
String textToServer = nameField.getText();
if ( !FieldVerifier.isValidName( textToServer ) ) {
errorLabel.setText( "Please enter at least four characters" );
return;
}
// Then, we send the input to the server.
sendGetButton.setEnabled( false );
sendPostButton.setEnabled( false );
sendPostPathButton.setEnabled( false );
textToServerLabel.setText( textToServer );
serverResponseLabel.setText( "" );
RestCallback<GreetingResponse> callback = new RestCallback<GreetingResponse>() {
@Override
public void onSuccess( GreetingResponse result ) {
dialogBox.setText( "Remote Procedure Call" );
serverResponseLabel.removeStyleName( "serverResponseLabelError" );
serverResponseLabel.setHTML( new SafeHtmlBuilder().appendEscaped( result.getGreeting() )
.appendHtmlConstant( "<br><br>I am running " ).appendEscaped( result.getServerInfo() )
.appendHtmlConstant( ".<br><br>It looks like you are using:<br>" ).appendEscaped( result
.getUserAgent() ).toSafeHtml() );
dialogBox.center();
closeButton.setFocus( true );
}
@Override
public void onError( Response response ) {
onRequestFailure();
}
@Override
public void onFailure( Throwable throwable ) {
onRequestFailure();
}
};
if ( req == 0 ) {
GreetingResourceBuilder.hello( textToServer ).callback( callback ).send();
} else {
if ( req == 1 ) {
GreetingResourceBuilder.greet( new GreetingRequest( textToServer ) )
.callback( callback )
.send();
} else if ( req == 2 ) {
GreetingResourceBuilder.greet( "someId", null, new GreetingRequest( textToServer ) )
.addQueryParam( "other" )
.callback( callback )
.send();
} else {
GreetingResourceBuilder.greetWithCustomHTTPCode( "someId", null, new GreetingRequest( textToServer ) )
.addQueryParam( "other" )
.callback( callback )
.send();
}
}
}
private void onRequestFailure() {
// Show the RPC error message to the user
dialogBox.setText( "Remote Procedure Call - Failure" );
serverResponseLabel.addStyleName( "serverResponseLabelError" );
serverResponseLabel.setHTML( SERVER_ERROR );
dialogBox.center();
closeButton.setFocus( true );
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler( 0 );
sendGetButton.addClickHandler( handler );
nameField.addKeyUpHandler( handler );
sendPostButton.addClickHandler( new MyHandler( 1 ) );
sendPostPathButton.addClickHandler( new MyHandler( 2 ) );
} | This is the entry point method. |
@Override
public GroupExecutionSpecifier observe(Class<? extends RequestObserver> observer) {
this.observer = SecurityActions.newInstance(observer.getName(), new Class<?>[] {}, new Object[] {},
RequestFilter.class);
return this;
} | /*
(non-Javadoc)
@see org.jboss.arquillian.warp.client.execution.FilterSpecifier#filter(java.lang.Class) |
@Override
public <T extends Inspection> T getInspection() {
return (T) payloads.values().iterator().next().getInspections().get(0);
} | /*
(non-Javadoc)
@see org.jboss.arquillian.warp.client.result.WarpGroupResult#getInspection() |
@Override
public <T extends Inspection> T getInspectionForHitNumber(int hitNumber) {
return (T) getInspectionsForHitNumber(hitNumber).get(0);
} | /*
(non-Javadoc)
@see org.jboss.arquillian.warp.client.result.WarpGroupResult#getInspectionForHitNumber(int) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.