text
stringlengths 7
1.01M
|
|---|
package com.codepath.instagramviewer.adapters;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.codepath.instagramviewer.R;
import com.codepath.instagramviewer.models.InstagramPhoto;
import com.makeramen.roundedimageview.RoundedImageView;
import com.makeramen.roundedimageview.RoundedTransformationBuilder;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import java.util.List;
/**
* Created by Shyam Rokde on 1/30/16.
*/
public class InstagramPhotosAdapter extends ArrayAdapter<InstagramPhoto> {
public InstagramPhotosAdapter(Context context, List<InstagramPhoto> objects) {
super(context, android.R.layout.simple_list_item_1, objects);
}
static class ViewHolderItem {
ImageView ivProfile;
ImageView ivPhoto;
TextView tvCaption;
TextView tvUsername;
TextView tvTime;
TextView tvLikes;
TextView tvComment;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItem viewHolder;
// Get data
InstagramPhoto photo = getItem(position);
// Is Recycle
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_photo, parent, false);
// Set up view holder
viewHolder = new ViewHolderItem();
viewHolder.ivProfile = (RoundedImageView) convertView.findViewById(R.id.ivProfile);
viewHolder.tvCaption = (TextView) convertView.findViewById(R.id.tvCaption);
viewHolder.ivPhoto = (ImageView) convertView.findViewById(R.id.ivPhoto);
viewHolder.tvUsername = (TextView) convertView.findViewById(R.id.tvUsername);
viewHolder.tvTime = (TextView) convertView.findViewById(R.id.tvTime);
viewHolder.tvLikes = (TextView) convertView.findViewById(R.id.tvLikes);
viewHolder.tvComment = (TextView) convertView.findViewById(R.id.tvComment);
// Store view holder with the view
convertView.setTag(viewHolder);
}else {
viewHolder = (ViewHolderItem) convertView.getTag();
}
// Profile Picture
Transformation transformation = new RoundedTransformationBuilder().cornerRadiusDp(25)
.oval(false)
.build();
Picasso.with(getContext()).load(photo.getProfilePicture()).fit().transform(transformation)
.into(viewHolder.ivProfile);
// Username
viewHolder.tvUsername.setText(photo.getUsername());
// Caption
viewHolder.tvCaption.setText(photo.getCaption());
// Image
viewHolder.ivPhoto.setImageResource(0);
Picasso.with(getContext())
.load(photo.getImageUrl())
.placeholder(R.drawable.ic_picture_240)
.into(viewHolder.ivPhoto);
// Relative Time
viewHolder.tvTime.setText(photo.getCreatedTime());
// Likes
viewHolder.tvLikes.setText(String.format("%,d likes", photo.getLikeCount()));
viewHolder.tvComment.setText(Html.fromHtml(photo.getLatestComment()));
// Insert Model
// Return
return convertView;
}
}
|
package org.jsoup.parser;
import org.jsoup.helper.Validate;
/**
* A character queue with parsing helpers.
*
* @author Jonathan Hedley
*/
public class TokenQueue {
private String queue;
private int pos = 0;
private static final Character ESC = '\\'; // escape char for chomp balanced.
/**
Create a new TokenQueue.
@param data string of data to back queue.
*/
public TokenQueue(String data) {
Validate.notNull(data);
queue = data;
}
/**
* Is the queue empty?
* @return true if no data left in queue.
*/
public boolean isEmpty() {
return remainingLength() == 0;
}
private int remainingLength() {
return queue.length() - pos;
}
/**
* Retrieves but does not remove the first character from the queue.
* @return First character, or null if empty.
*/
public Character peek() {
return isEmpty() ? null : queue.charAt(pos);
}
/**
Add a character to the start of the queue (will be the next character retrieved).
@param c character to add
*/
public void addFirst(Character c) {
addFirst(c.toString());
}
/**
Add a string to the start of the queue.
@param seq string to add.
*/
public void addFirst(String seq) {
// not very performant, but an edge case
queue = seq + queue.substring(pos);
pos = 0;
}
/**
* Tests if the next characters on the queue match the sequence. Case insensitive.
* @param seq String to check queue for.
* @return true if the next characters match.
*/
public boolean matches(String seq) {
int count = seq.length();
if (count > remainingLength())
return false;
while (--count >= 0) {
if (Character.toLowerCase(seq.charAt(count)) != Character.toLowerCase(queue.charAt(pos+count)))
return false;
}
return true;
}
/**
* Case sensitive match test.
* @param seq
* @return
*/
public boolean matchesCS(String seq) {
return queue.startsWith(seq, pos);
}
/**
Tests if the next characters match any of the sequences. Case insensitive.
@param seq
@return
*/
public boolean matchesAny(String... seq) {
for (String s : seq) {
if (matches(s))
return true;
}
return false;
}
public boolean matchesAny(char... seq) {
if (isEmpty())
return false;
for (char c: seq) {
if (queue.charAt(pos) == c)
return true;
}
return false;
}
public boolean matchesStartTag() {
// micro opt for matching "<x"
return (remainingLength() >= 2 && queue.charAt(pos) == '<' && Character.isLetterOrDigit(queue.charAt(pos+1)));
}
/**
* Tests if the queue matches the sequence (as with match), and if they do, removes the matched string from the
* queue.
* @param seq String to search for, and if found, remove from queue.
* @return true if found and removed, false if not found.
*/
public boolean matchChomp(String seq) {
if (matches(seq)) {
pos += seq.length();
return true;
} else {
return false;
}
}
/**
Tests if queue starts with a whitespace character.
@return if starts with whitespace
*/
public boolean matchesWhitespace() {
return !isEmpty() && Character.isWhitespace(queue.charAt(pos));
}
/**
Test if the queue matches a word character (letter or digit).
@return if matches a word character
*/
public boolean matchesWord() {
return !isEmpty() && Character.isLetterOrDigit(queue.charAt(pos));
}
/**
* Drops the next character off the queue.
*/
public void advance() {
if (!isEmpty()) pos++;
}
/**
* Consume one character off queue.
* @return first character on queue.
*/
public Character consume() {
Character c = queue.charAt(pos);
pos++;
return c;
}
/**
* Consumes the supplied sequence of the queue. If the queue does not start with the supplied sequence, will
* throw an illegal state exception -- but you should be running match() against that condition.
<p>
Case insensitive.
* @param seq sequence to remove from head of queue.
*/
public void consume(String seq) {
if (!matches(seq))
throw new IllegalStateException("Queue did not match expected sequence");
int len = seq.length();
if (len > remainingLength())
throw new IllegalStateException("Queue not long enough to consume sequence");
pos += len;
}
/**
* Pulls a string off the queue, up to but exclusive of the match sequence, or to the queue running out.
* @param seq String to end on (and not include in return, but leave on queue). <b>Case sensitive.</b>
* @return The matched data consumed from queue.
*/
public String consumeTo(String seq) {
int offset = queue.indexOf(seq, pos);
if (offset != -1) {
String consumed = queue.substring(pos, offset);
pos += consumed.length();
return consumed;
} else {
return remainder();
}
}
public String consumeToIgnoreCase(String seq) {
int start = pos;
String first = seq.substring(0, 1);
boolean canScan = first.toLowerCase().equals(first.toUpperCase()); // if first is not cased, use index of
while (!isEmpty() && !matches(seq)) {
if (canScan) {
int skip = queue.indexOf(first, pos) - pos;
if (skip <= 0)
pos++;
else if (skip < 0) // no chance of finding, grab to end
pos = queue.length() - 1;
else
pos += skip;
}
else
pos++;
}
String data = queue.substring(start, pos);
return data;
}
/**
Consumes to the first sequence provided, or to the end of the queue. Leaves the terminator on the queue.
@param seq any number of terminators to consume to. <b>Case insensitive.</b>
@return consumed string
*/
// todo: method name. not good that consumeTo cares for case, and consume to any doesn't. And the only use for this
// is is a case sensitive time...
public String consumeToAny(String... seq) {
int start = pos;
while (!isEmpty() && !matchesAny(seq)) {
pos++;
}
String data = queue.substring(start, pos);
return data;
}
/**
* Pulls a string off the queue (like consumeTo), and then pulls off the matched string (but does not return it).
* <p>
* If the queue runs out of characters before finding the seq, will return as much as it can (and queue will go
* isEmpty() == true).
* @param seq String to match up to, and not include in return, and to pull off queue. <b>Case sensitive.</b>
* @return Data matched from queue.
*/
public String chompTo(String seq) {
String data = consumeTo(seq);
matchChomp(seq);
return data;
}
public String chompToIgnoreCase(String seq) {
String data = consumeToIgnoreCase(seq); // case insensitive scan
matchChomp(seq);
return data;
}
/**
* Pulls a balanced string off the queue. E.g. if queue is "(one (two) three) four", (,) will return "one (two) three",
* and leave " four" on the queue. Unbalanced openers and closers can be escaped (with \). Those escapes will be left
* in the returned string, which is suitable for regexes (where we need to preserve the escape), but unsuitable for
* contains text strings; use unescape for that.
* @param open opener
* @param close closer
* @return data matched from the queue
*/
public String chompBalanced(Character open, Character close) {
StringBuilder accum = new StringBuilder();
int depth = 0;
Character last = null;
do {
if (isEmpty()) break;
Character c = consume();
if (last == null || !last.equals(ESC)) {
if (c.equals(open))
depth++;
else if (c.equals(close))
depth--;
}
if (depth > 0 && last != null)
accum.append(c); // don't include the outer match pair in the return
last = c;
} while (depth > 0);
return accum.toString();
}
/**
* Unescaped a \ escaped string.
* @param in backslash escaped string
* @return unescaped string
*/
public static String unescape(String in) {
StringBuilder out = new StringBuilder();
Character last = null;
for (Character c : in.toCharArray()) {
if (c.equals(ESC)) {
if (last != null && last.equals(ESC))
out.append(c);
}
else
out.append(c);
last = c;
}
return out.toString();
}
/**
* Pulls the next run of whitespace characters of the queue.
*/
public boolean consumeWhitespace() {
boolean seen = false;
while (matchesWhitespace()) {
pos++;
seen = true;
}
return seen;
}
/**
* Retrieves the next run of word type (letter or digit) off the queue.
* @return String of word characters from queue, or empty string if none.
*/
public String consumeWord() {
int start = pos;
while (matchesWord())
pos++;
return queue.substring(start, pos);
}
/**
* Consume an tag name off the queue (word or :, _, -)
*
* @return tag name
*/
public String consumeTagName() {
int start = pos;
while (!isEmpty() && (matchesWord() || matchesAny(':', '_', '-')))
pos++;
return queue.substring(start, pos);
}
/**
* Consume a CSS element selector (tag name, but | instead of : for namespaces, to not conflict with :pseudo selects).
*
* @return tag name
*/
public String consumeElementSelector() {
int start = pos;
while (!isEmpty() && (matchesWord() || matchesAny('|', '_', '-')))
pos++;
return queue.substring(start, pos);
}
/**
Consume a CSS identifier (ID or class) off the queue (letter, digit, -, _)
http://www.w3.org/TR/CSS2/syndata.html#value-def-identifier
@return identifier
*/
public String consumeCssIdentifier() {
int start = pos;
while (!isEmpty() && (matchesWord() || matchesAny('-', '_')))
pos++;
return queue.substring(start, pos);
}
/**
Consume an attribute key off the queue (letter, digit, -, _, :")
@return attribute key
*/
public String consumeAttributeKey() {
int start = pos;
while (!isEmpty() && (matchesWord() || matchesAny('-', '_', ':')))
pos++;
return queue.substring(start, pos);
}
/**
Consume and return whatever is left on the queue.
@return remained of queue.
*/
public String remainder() {
StringBuilder accum = new StringBuilder();
while (!isEmpty()) {
accum.append(consume());
}
return accum.toString();
}
public String toString() {
return queue.substring(pos);
}
}
|
package com.cyecize.http;
import java.util.List;
import java.util.Map;
public interface HttpRequest {
void setMethod(String method);
void setRequestURL(String requestUrl);
void setContentLength(int contentLength);
void setSession(HttpSession session);
void addHeader(String header, String value);
void addBodyParameter(String parameter, String value);
void addMultipartFile(MultipartFile multipartFile);
boolean isResource();
int getContentLength();
String getMethod();
String getRequestURL();
String getHost();
String getRequestURI();
String getContentType();
String getQueryParam(String paramName);
String getBodyParam(String paramName);
String get(String paramName);
String getHeader(String headerName);
HttpSession getSession();
HttpCookie getCookie(String cookieName);
List<MultipartFile> getMultipartFiles();
Map<String, String> getHeaders();
Map<String, String> getQueryParameters();
Map<String, String> getBodyParameters();
Map<String, List<String>> getBodyParametersAsList();
Map<String, HttpCookie> getCookies();
}
|
package com.weberfly.entities;
/*******************************************************************************
* 2017, All rights reserved.
*******************************************************************************/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.persistence.*;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
// Start of user code (user defined imports)
// End of user code
/**
* Description of User.
*
* @author kamal
*/
@Entity
@Table(name="User")
@Scope("session")
public class User implements UserDetails{
/**
* Description of the property id.
*/
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id ;
public static enum Role{
ADMIN,
USER
}
/**
* Description of the property email.
*/
@Column(unique = true)
private String username ;
@JsonProperty(access = Access.WRITE_ONLY)
private String password ;
private String role;
private String fullName;
private boolean blocked ;
private Date dateRegister=new Date();
/**
* Description of the property session.
*/
@OneToOne(cascade = CascadeType.ALL)
private Session session =new Session();
/**
* Description of the property recivedMessages.
*/
@OneToMany(cascade = CascadeType.ALL,mappedBy="sender")
private List<Message> recivedMessages ;
/**
* Description of the property sendedMessages.
*/
@OneToMany(cascade = CascadeType.ALL,mappedBy="receiver")
private List<Message> sendedMessages;
/**
* Description of the property profiles.
*/
@OneToOne(cascade = CascadeType.ALL)
private Profile profile = new Profile() ;
/*
* Description of the property Posts.
*/
@OneToMany(cascade = CascadeType.ALL,mappedBy="user")
private List<Post> posts ;
@ManyToMany(cascade = CascadeType.MERGE ,fetch= FetchType.EAGER)
@JoinTable(name = "user_twitter_keyword", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "keyword_id", referencedColumnName = "id"))
private List<TwitterKeyWord> twitterKeyWords ;
/**
* Description of the property notifications.
*/
@OneToMany(mappedBy="user")
private List<Notification> notifications ;
/**
* Description of the property comments.
*/
@OneToMany(cascade = CascadeType.ALL,mappedBy="user")
private List<Comment> comments ;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "User_Folowers", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "folowing_id", referencedColumnName = "id"))
private List<User> following;
// @ManyToMany(cascade = CascadeType.ALL)
// @JoinTable(name = "User_Categories", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "category_id", referencedColumnName = "id"))
// private List<Category> categories;
@ManyToMany(mappedBy="following")
private List<User> users;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsename() {
return username;
}
public void setUsename(String usename) {
this.username = usename;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public void setSession(Session session) {
this.session = session;
}
public Session getSession(){
return this.session;
}
public void setRecivedMessages(List<Message> recivedMessages) {
this.recivedMessages = recivedMessages;
}
public Date getDateRegister() {
return dateRegister;
}
public void setDateRegister(Date dateRegister) {
this.dateRegister = dateRegister;
}
public boolean isBlocked() {
return blocked;
}
public void setBlocked(boolean blocked) {
this.blocked = blocked;
}
public void setSendedMessages(List<Message> sendedMessages) {
this.sendedMessages = sendedMessages;
}
public void setPosts(List<Post> Posts) {
this.posts = Posts;
}
public List<TwitterKeyWord> getTwitterKeyWords() {
return twitterKeyWords;
}
public void setNotifications(List<Notification> notifications) {
this.notifications = notifications;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public void setFollowing(List<User> following) {
this.following = following;
}
public void setTwitterKeyWords(List<TwitterKeyWord> twitterKeyWords) {
this.twitterKeyWords = twitterKeyWords;
}
public void setUsers(List<User> users) {
this.users = users;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@JsonIgnore
@Override
public boolean isEnabled() {
return true;
}
@JsonIgnore
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isAccountNonLocked() {
return true;
}
@JsonIgnore
@Override
public boolean isAccountNonExpired() {
return true;
}
@JsonIgnore
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(role));
return authorities;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", role=" + role +
", profile=" + profile + "]";
}
}
|
package plugin.doors;
import java.util.Objects;
import io.astraeus.game.world.Direction;
import io.astraeus.game.world.Position;
import io.astraeus.game.world.entity.object.GameObject;
import io.astraeus.game.world.entity.object.GameObjectType;
/**
* Represents a door object in the game world.
*
* @author SeVen
*/
public final class Door extends GameObject {
/**
* The modified id of this door.
*/
private int currentId;
/**
* The modified Position of this door.
*/
private Position currentPosition;
/**
* The flag that denotes the door is open.
*/
private boolean open;
/**
* The next orientation.
*/
private Direction nextOrientation;
/**
* The flag that denotes this door has already been clicked.
*/
private boolean activated;
/**
* Creates a new {@link Door}.
*
* @param id The id of the door.
* @param type The type of door.
* @param Position The Position of this door.
*/
public Door(int id, GameObjectType type, Position Position, boolean open, Direction orientation) {
super(id, type, Position, orientation);
this.currentId = id;
this.currentPosition = Position;
this.open = open;
this.nextOrientation = orientation;
}
/**
* Gets the modified id of this door.
*
* @return The modified id.
*/
public int getCurrentId() {
return currentId;
}
/**
* Sets the id of this object.
*
* @param id The new id of this object.
*/
public void setCurrentId(int id) {
this.currentId = id;
}
/**
* Gets the modified Position of this door.
*
* @return The modified Position.
*/
public Position getCurrentPosition() {
return currentPosition;
}
/**
* Sets the Position of this door.
*
* @param Position The new Position.
*/
public void setCurrentPosition(Position Position) {
this.currentPosition = Position;
}
/**
* Determines if this door is open.
*
* @return {@code true} If this door is open. {@code false} The door is closed.
*/
public boolean isOpened() {
return open;
}
/**
* Sets the flag that denotes this door is opened.
*
* @param opened The flag to set.
*/
public void setOpened(boolean opened) {
this.open = opened;
}
/**
* Gets the next orientation of this door.
*
* @return The next orientation.
*/
public Direction getNextOrientation() {
return nextOrientation;
}
/**
* Sets the next orientation of this door.
*
* @param nextOrientation The next orientation to set.
*/
public void setNextOrientation(Direction nextOrientation) {
this.nextOrientation = nextOrientation;
}
/**
* Determines if this door has already been clicked.
*
* @return {@code true} If this door has been clicked. {@code false} otherwise.
*/
public boolean isActivated() {
return activated;
}
/**
* Sets the flag that denotes this door has been clicked.
*
* @param activated The flag to set.
*/
public void setActivated(boolean activated) {
this.activated = activated;
}
/**
* Determines if this door is a single door.
*
* @return {@code true} If this door is a single door. {@code false} otherwise.
*/
public boolean isSingle() {
return DoorUtils.SINGLE_DOORS.stream().anyMatch($it -> $it == getCurrentId());
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o instanceof Door) {
Door other = (Door) o;
return (this.hashCode() == other.hashCode());
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(currentId, getType(), currentPosition, open, nextOrientation);
}
@Override
public String toString() {
return String.format("[DOOR] [id= %d] [type= %s] [loc= %s] [open= %s] [orientation= %s]", currentId, getEnumeratedObjectType().name(), currentPosition.toString(), Boolean.toString(open), nextOrientation.name());
}
}
|
/*
* Copyright 2011-2021 the original author or 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
*
* 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.lettuce.core;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import reactor.test.StepVerifier;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.core.codec.*;
import io.lettuce.test.LettuceExtension;
/**
* @author Will Glozer
* @author Mark Paluch
*/
@ExtendWith(LettuceExtension.class)
class CustomCodecIntegrationTests extends TestSupport {
private final SecretKeySpec secretKey = new SecretKeySpec("1234567890123456".getBytes(), "AES");
private final IvParameterSpec iv = new IvParameterSpec("1234567890123456".getBytes());
// Creates a CryptoCipher instance with the transformation and properties.
private final String transform = "AES/CBC/PKCS5Padding";
CipherCodec.CipherSupplier encrypt = (CipherCodec.KeyDescriptor keyDescriptor) -> {
Cipher cipher = Cipher.getInstance(transform);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return cipher;
};
CipherCodec.CipherSupplier decrypt = (CipherCodec.KeyDescriptor keyDescriptor) -> {
Cipher cipher = Cipher.getInstance(transform);
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
return cipher;
};
private final RedisClient client;
@Inject
CustomCodecIntegrationTests(RedisClient client) {
this.client = client;
}
@Test
void testJavaSerializer() {
StatefulRedisConnection<String, Object> redisConnection = client.connect(new SerializedObjectCodec());
RedisCommands<String, Object> sync = redisConnection.sync();
List<String> list = list("one", "two");
sync.set(key, list);
assertThat(sync.get(key)).isEqualTo(list);
assertThat(sync.set(key, list)).isEqualTo("OK");
assertThat(sync.set(key, list, SetArgs.Builder.ex(1))).isEqualTo("OK");
redisConnection.close();
}
@Test
void testJavaSerializerReactive() {
StatefulRedisConnection<String, Object> redisConnection = client.connect(new SerializedObjectCodec());
List<String> list = list("one", "two");
StepVerifier.create(redisConnection.reactive().set(key, list, SetArgs.Builder.ex(1))).expectNext("OK").verifyComplete();
redisConnection.close();
}
@Test
void testDeflateCompressedJavaSerializer() {
RedisCommands<String, Object> connection = client
.connect(
CompressionCodec.valueCompressor(new SerializedObjectCodec(), CompressionCodec.CompressionType.DEFLATE))
.sync();
List<String> list = list("one", "two");
connection.set(key, list);
assertThat(connection.get(key)).isEqualTo(list);
connection.getStatefulConnection().close();
}
@Test
void testGzipompressedJavaSerializer() {
RedisCommands<String, Object> connection = client
.connect(CompressionCodec.valueCompressor(new SerializedObjectCodec(), CompressionCodec.CompressionType.GZIP))
.sync();
List<String> list = list("one", "two");
connection.set(key, list);
assertThat(connection.get(key)).isEqualTo(list);
connection.getStatefulConnection().close();
}
@Test
void testEncryptedCodec() {
RedisCommands<String, String> connection = client.connect(CipherCodec.forValues(StringCodec.UTF8, encrypt, decrypt))
.sync();
connection.set(key, "foobar");
assertThat(connection.get(key)).isEqualTo("foobar");
connection.getStatefulConnection().close();
}
@Test
void testByteCodec() {
RedisCommands<byte[], byte[]> connection = client.connect(new ByteArrayCodec()).sync();
String value = "üöäü+#";
connection.set(key.getBytes(), value.getBytes());
assertThat(connection.get(key.getBytes())).isEqualTo(value.getBytes());
connection.set(key.getBytes(), null);
assertThat(connection.get(key.getBytes())).isEqualTo(new byte[0]);
List<byte[]> keys = connection.keys(key.getBytes());
assertThat(keys).contains(key.getBytes());
connection.getStatefulConnection().close();
}
@Test
void testByteBufferCodec() {
RedisCommands<ByteBuffer, ByteBuffer> connection = client.connect(new ByteBufferCodec()).sync();
String value = "üöäü+#";
ByteBuffer wrap = ByteBuffer.wrap(value.getBytes());
connection.set(wrap, wrap);
List<ByteBuffer> keys = connection.keys(wrap);
assertThat(keys).hasSize(1);
ByteBuffer byteBuffer = keys.get(0);
byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);
assertThat(bytes).isEqualTo(value.getBytes());
connection.getStatefulConnection().close();
}
@Test
void testComposedCodec() {
RedisCodec<String, Object> composed = RedisCodec.of(StringCodec.ASCII, new SerializedObjectCodec());
RedisCommands<String, Object> connection = client.connect(composed).sync();
connection.set(key, new Person());
List<String> keys = connection.keys(key);
assertThat(keys).hasSize(1);
assertThat(connection.get(key)).isInstanceOf(Person.class);
connection.getStatefulConnection().close();
}
class SerializedObjectCodec implements RedisCodec<String, Object> {
private Charset charset = StandardCharsets.UTF_8;
@Override
public String decodeKey(ByteBuffer bytes) {
return charset.decode(bytes).toString();
}
@Override
public Object decodeValue(ByteBuffer bytes) {
try {
byte[] array = new byte[bytes.remaining()];
bytes.get(array);
ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(array));
return is.readObject();
} catch (Exception e) {
return null;
}
}
@Override
public ByteBuffer encodeKey(String key) {
return charset.encode(key);
}
@Override
public ByteBuffer encodeValue(Object value) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bytes);
os.writeObject(value);
return ByteBuffer.wrap(bytes.toByteArray());
} catch (IOException e) {
return null;
}
}
}
static class Person implements Serializable {
}
}
|
/**
* \file ListWznmQBlkAItem.java
* Java API code for record set of table TblWznmQBlkAItem
* \copyright (C) 2018-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
package apiwznm;
import java.util.*;
import org.w3c.dom.*;
import sbecore.*;
public class ListWznmQBlkAItem {
public ListWznmQBlkAItem() {
nodes = new ArrayList<WznmQBlkAItem>();
};
public void clear() {
nodes.clear();
};
public ArrayList<WznmQBlkAItem> nodes;
public boolean readXML(
Document doc
, String basexpath
, boolean addbasetag
) {
Vector<Integer> ics = new Vector<Integer>();
Vector<Boolean> shorttags = new Vector<Boolean>();
WznmQBlkAItem rec;
String s;
if (addbasetag) basexpath = Xmlio.checkUclcXPaths(doc, basexpath, "ListWznmQBlkAItem");
if (Xmlio.checkXPath(doc, basexpath)) {
Xmlio.extractList(doc, basexpath, "WznmQBlkAItem", "row", "jnum", ics, shorttags);
clear();
for (int i = 0; i < ics.size(); i++) {
rec = new WznmQBlkAItem(i+1, "", "", "", "", "", "", "", "", "", "", "", "", "");
if (shorttags.get(i)) s = basexpath + "/row[@jnum='" + ics.get(i).toString() + "']";
else s = basexpath + "/WznmQBlkAItem[@jnum='" + ics.get(i).toString() + "']";
if (rec.readXML(doc, s, false)) nodes.add(rec);
};
return true;
};
return false;
};
};
|
package net.jackw.olep.common.store;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier;
import org.apache.kafka.streams.state.KeyValueStore;
public class ChronicleMapKeyValueBytesStoreSupplier<K, V> implements KeyValueBytesStoreSupplier {
private final String name;
private final int maxEntries;
private final Serializer<K> keySerializer;
private final Serializer<V> valueSerializer;
private final K averageKey;
private final V averageValue;
public ChronicleMapKeyValueBytesStoreSupplier(
String name, int maxEntries, Serializer<K> keySerializer, Serializer<V> valueSerializer, K averageKey,
V averageValue
) {
this.name = name;
this.maxEntries = maxEntries;
this.keySerializer = keySerializer;
this.valueSerializer = valueSerializer;
this.averageKey = averageKey;
this.averageValue = averageValue;
}
@Override
public String name() {
return name;
}
@Override
public KeyValueStore<Bytes, byte[]> get() {
return ChronicleMapKafkaStateStore.create(name, maxEntries, keySerializer, valueSerializer, averageKey, averageValue);
}
@Override
public String metricsScope() {
return "chroniclemap-state";
}
}
|
package org.monjasa.application.model.risk;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.monjasa.application.model.Evaluation;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Entity
public class RiskEvent {
@Id
@GeneratedValue
@EqualsAndHashCode.Include
private Long id;
private RiskType riskType;
private String name;
private boolean assessed;
private BigDecimal budget;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
@JoinColumn(name = "probability_evaluation_id")
@Fetch(value = FetchMode.SUBSELECT)
private List<Evaluation> probabilityEvaluations;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
@JoinColumn(name = "loss_evaluation_id")
@Fetch(value = FetchMode.SUBSELECT)
private List<Evaluation> lossEvaluations;
@ManyToOne()
@JoinColumn(name = "arrangement_id")
private Arrangement arrangement;
public double getWeightedRiskProbability() {
double weightSum = probabilityEvaluations.stream()
.map(Evaluation::getWeight)
.reduce(Double::sum)
.orElse(1.0);
return probabilityEvaluations.stream()
.mapToDouble(Evaluation::getWeightedValue)
.summaryStatistics()
.getSum() / weightSum;
}
public double getWeightedRiskLoss() {
double weightSum = lossEvaluations.stream()
.map(Evaluation::getWeight)
.reduce(Double::sum)
.orElse(1.0);
return lossEvaluations.stream()
.mapToDouble(Evaluation::getWeightedValue)
.summaryStatistics()
.getSum() / weightSum;
}
public BigDecimal getBudgetLoss() {
return budget.multiply(BigDecimal.valueOf(getWeightedRiskLoss()));
}
}
|
package com.streem.selectcontact;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Contacts.Entity;
import android.util.Log;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
public class SelectContactModule extends ReactContextBaseJavaModule implements ActivityEventListener {
private static final String TAG = "SelectContactModule";
private static final int CONTACT_REQUEST = 11112;
public static final String E_CONTACT_CANCELLED = "E_CONTACT_CANCELLED";
public static final String E_CONTACT_NO_DATA = "E_CONTACT_NO_DATA";
public static final String E_CONTACT_EXCEPTION = "E_CONTACT_EXCEPTION";
public static final String E_CONTACT_PERMISSION = "E_CONTACT_PERMISSION";
private Promise mContactsPromise;
private final ContentResolver contentResolver;
public SelectContactModule(ReactApplicationContext reactContext) {
super(reactContext);
this.contentResolver = getReactApplicationContext().getContentResolver();
reactContext.addActivityEventListener(this);
}
@Override
public String getName() {
return "SelectContact";
}
@ReactMethod
public void openContactSelection(Promise contactsPromise) {
launchPicker(contactsPromise, CONTACT_REQUEST);
}
/**
* Lanch the contact picker, with the specified requestCode for returned data.
*
* @param contactsPromise - promise passed in from React Native.
* @param requestCode - request code to specify what contact data to return
*/
private void launchPicker(Promise contactsPromise, int requestCode) {
mContactsPromise = contactsPromise;
Cursor cursor = this.contentResolver.query(Contacts.CONTENT_URI, null, null, null, null);
if (cursor != null) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(Contacts.CONTENT_TYPE);
Activity activity = getCurrentActivity();
if (intent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivityForResult(intent, requestCode);
}
cursor.close();
} else {
mContactsPromise.reject(E_CONTACT_PERMISSION, "no permission");
}
}
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent intent) {
if (mContactsPromise == null || requestCode != CONTACT_REQUEST) {
return;
}
//Request was cancelled
if (resultCode != Activity.RESULT_OK) {
mContactsPromise.reject(E_CONTACT_CANCELLED, "Cancelled");
return;
}
// Retrieve all possible data about contact and return as a JS object
WritableMap contactData = Arguments.createMap();
try {
String id = getContactId(intent.getData());
contactData.putString("recordId", id);
Uri contactUri = buildContactUri(id);
boolean foundData = false;
WritableArray phones = Arguments.createArray();
WritableArray emails = Arguments.createArray();
WritableArray postalAddresses = Arguments.createArray();
Cursor cursor = openContactQuery(contactUri);
if (cursor.moveToFirst()) {
do {
String mime = cursor.getString(cursor.getColumnIndex(Entity.MIMETYPE));
switch (mime) {
case StructuredName.CONTENT_ITEM_TYPE:
addNameData(contactData, cursor);
foundData = true;
break;
case StructuredPostal.CONTENT_ITEM_TYPE:
addPostalData(postalAddresses, cursor, activity);
foundData = true;
break;
case Phone.CONTENT_ITEM_TYPE:
addPhoneEntry(phones, cursor, activity);
foundData = true;
break;
case Email.CONTENT_ITEM_TYPE:
addEmailEntry(emails, cursor, activity);
foundData = true;
break;
}
} while (cursor.moveToNext());
}
cursor.close();
contactData.putArray("phones", phones);
contactData.putArray("emails", emails);
contactData.putArray("postalAddresses", postalAddresses);
if (foundData) {
mContactsPromise.resolve(contactData);
} else {
mContactsPromise.reject(E_CONTACT_NO_DATA, "No data found for contact");
}
} catch (SelectContactException e) {
mContactsPromise.reject(E_CONTACT_EXCEPTION, e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Unexpected exception reading from contacts", e);
mContactsPromise.reject(E_CONTACT_EXCEPTION, e.getMessage());
}
}
private String getContactId(Uri contactUri) throws SelectContactException {
Cursor cursor = this.contentResolver.query(contactUri, null, null, null, null);
if (cursor == null || !cursor.moveToFirst()) {
throw new SelectContactException(E_CONTACT_NO_DATA, "Contact Data Not Found");
}
return cursor.getString(cursor.getColumnIndex(Contacts._ID));
}
private Uri buildContactUri(String id) {
return Uri
.withAppendedPath(Contacts.CONTENT_URI, id)
.buildUpon()
.appendPath(Entity.CONTENT_DIRECTORY)
.build();
}
private Cursor openContactQuery(Uri contactUri) throws SelectContactException {
String[] projection = {
Entity.MIMETYPE,
Entity.DATA1,
Entity.DATA2,
Entity.DATA3
};
String sortOrder = Entity.RAW_CONTACT_ID + " ASC";
Cursor cursor = this.contentResolver.query(contactUri, projection, null, null, sortOrder);
if (cursor == null) {
throw new SelectContactException(E_CONTACT_EXCEPTION, "Could not query contacts data. Unable to create cursor.");
}
return cursor;
}
private void addNameData(WritableMap contactData, Cursor cursor) {
int displayNameIndex = cursor.getColumnIndex(StructuredName.DISPLAY_NAME);
contactData.putString("name", cursor.getString(displayNameIndex));
int givenNameColumn = cursor.getColumnIndex(StructuredName.GIVEN_NAME);
if (givenNameColumn != -1) {
String givenName = cursor.getString(givenNameColumn);
contactData.putString("givenName", givenName);
}
int familyNameColumn = cursor.getColumnIndex(StructuredName.FAMILY_NAME);
if (familyNameColumn != -1) {
String familyName = cursor.getString(cursor.getColumnIndex(StructuredName.FAMILY_NAME));
contactData.putString("familyName", familyName);
}
int middleNameColumn = cursor.getColumnIndex(StructuredName.MIDDLE_NAME);
if (middleNameColumn != -1) {
String middleName = cursor.getString(middleNameColumn);
contactData.putString("middleName", middleName);
}
}
private void addPostalData(WritableArray postalAddresses, Cursor cursor, Activity activity) {
// we need to see if the postal address columns exist, if so, add them
int formattedAddressColumn = cursor.getColumnIndex(StructuredPostal.FORMATTED_ADDRESS);
int streetColumn = cursor.getColumnIndex(StructuredPostal.STREET);
int cityColumn = cursor.getColumnIndex(StructuredPostal.CITY);
int stateColumn = cursor.getColumnIndex(StructuredPostal.REGION);
int postalCodeColumn = cursor.getColumnIndex(StructuredPostal.POSTCODE);
int isoCountryCodeColumn = cursor.getColumnIndex(StructuredPostal.COUNTRY);
WritableMap addressEntry = Arguments.createMap();
if (formattedAddressColumn != -1) {
addressEntry.putString("formattedAddress", cursor.getString(formattedAddressColumn));
}
if (streetColumn != -1) {
addressEntry.putString("street", cursor.getString(streetColumn));
}
if (cityColumn != -1) {
addressEntry.putString("city", cursor.getString(cityColumn));
}
if (stateColumn != -1) {
addressEntry.putString("state", cursor.getString(stateColumn));
}
if (postalCodeColumn != -1) {
addressEntry.putString("postalCode", cursor.getString(postalCodeColumn));
}
if (isoCountryCodeColumn != -1) {
addressEntry.putString("isoCountryCode", cursor.getString(isoCountryCodeColumn));
}
// add the address type here
int addressTypeColumn = cursor.getColumnIndex(StructuredPostal.TYPE);
int addressLabelColumn = cursor.getColumnIndex(StructuredPostal.LABEL);
if (addressTypeColumn != -1 && addressLabelColumn != -1) {
String addressLabel = cursor.getString(addressLabelColumn);
int addressType = cursor.getInt(addressTypeColumn);
CharSequence typeLabel = StructuredPostal.getTypeLabel(activity.getResources(), addressType, addressLabel);
addressEntry.putString("type", String.valueOf(typeLabel));
}
postalAddresses.pushMap(addressEntry);
}
private void addPhoneEntry(WritableArray phones, Cursor cursor, Activity activity) {
String phoneNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
int phoneType = cursor.getInt(cursor.getColumnIndex(Phone.TYPE));
String phoneLabel = cursor.getString(cursor.getColumnIndex(Phone.LABEL));
CharSequence typeLabel = Phone.getTypeLabel(activity.getResources(), phoneType, phoneLabel);
WritableMap phoneEntry = Arguments.createMap();
phoneEntry.putString("number", phoneNumber);
phoneEntry.putString("type", String.valueOf(typeLabel));
phones.pushMap(phoneEntry);
}
private void addEmailEntry(WritableArray emails, Cursor cursor, Activity activity) {
String emailAddress = cursor.getString(cursor.getColumnIndex(Email.ADDRESS));
int emailType = cursor.getInt(cursor.getColumnIndex(Email.TYPE));
String emailLabel = cursor.getString(cursor.getColumnIndex(Email.LABEL));
CharSequence typeLabel = Email.getTypeLabel(activity.getResources(), emailType, emailLabel);
WritableMap emailEntry = Arguments.createMap();
emailEntry.putString("address", emailAddress);
emailEntry.putString("type", String.valueOf(typeLabel));
emails.pushMap(emailEntry);
}
@Override
public void onNewIntent(Intent intent) {
}
public static class SelectContactException extends Exception {
private final String errorCode;
public SelectContactException(String errorCode, String errorMessage) {
super(errorMessage);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}
}
|
package com.udacity.jdnd.course3.critter.entity;
import com.udacity.jdnd.course3.critter.entity.enums.EmployeeSkill;
import lombok.Data;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Set;
@Entity
@Data
public class Schedule extends BaseEntity {
private LocalDate date;
@ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@JoinTable(name="schedule_employee",
joinColumns = @JoinColumn(name="schdeule_id"),
inverseJoinColumns = @JoinColumn(name = "employee_id")
)
private List<Employee> employees;
@ManyToMany(fetch = FetchType.LAZY , cascade = CascadeType.ALL)
@JoinTable(name="schdeule_pet",
joinColumns = @JoinColumn(name = "schedule_id"),
inverseJoinColumns = @JoinColumn(name = "pet_id")
)
private List<Pet> pets;
@ElementCollection
@Enumerated(EnumType.STRING)
private Set<EmployeeSkill> activities;
}
|
package org.sheepy.lily.vulkan.process.graphic.pipeline.builder;
import static org.lwjgl.vulkan.VK10.*;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.vulkan.VkPipelineMultisampleStateCreateInfo;
public class MultisampleBuilder
{
public VkPipelineMultisampleStateCreateInfo allocCreateInfo(MemoryStack stack)
{
final var multisampling = VkPipelineMultisampleStateCreateInfo.mallocStack(stack);
multisampling.sType(VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO);
multisampling.sampleShadingEnable(false);
multisampling.rasterizationSamples(VK_SAMPLE_COUNT_1_BIT);
multisampling.minSampleShading(1.0f); // Optional
multisampling.pSampleMask(null); // Optional
multisampling.alphaToCoverageEnable(false); // Optional
multisampling.alphaToOneEnable(false); // Optional
multisampling.pNext(VK_NULL_HANDLE);
multisampling.flags(0);
return multisampling;
}
}
|
package com.roberto.avitec.repository;
import com.roberto.avitec.domain.entities.TabelaPadrao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TabelaPadraoRepository extends JpaRepository<TabelaPadrao, Long> {}
|
package CliqueSearchPack;
import java.util.*;
import java.io.*;
import java.lang.StrictMath;
import java.lang.Double;
import GraphPack.WeightedVertexPack.WeightedVertex;
import GraphPack.WeightedVertexPack.VertexPack.Vertex;
import InterfacePack.IntRelate;
import TwoParametersInterfacePack.TwoParametersBehavior;
import ZeroParameterInterfacePack.ZeroParameterBehavior;
import DegreeBucketPack.DegreeBasedPartition;
import WeightBucketPack.WeightBasedPartition;
import ConfigPack.*;
import UsrPausePack.UsrPause;
public class CliqueSearch{
private Random rand;
// private BitSet vertex_used_bits;
private ArrayList<Integer> top_level_weights_wrt_colors;
private ArrayList<Integer> last_top_level_weight_updated_colors;
private final static int MAX_GUESS_NUM = 50;
public CliqueSearch(int vertex_num, int seed)
{
rand = new Random(seed);
// vertex_used_bits = new BitSet(vertex_num + 1);
top_level_weights_wrt_colors = new ArrayList<Integer>();
last_top_level_weight_updated_colors = new ArrayList<Integer>();
}
public ArrayList<Integer> get_top_level_weights_wrt_colors()
{
return top_level_weights_wrt_colors;
}
public ArrayList<Integer> top_weight_vertices(WeightedVertex[] vertices, ArrayList<Integer> remaining_vertex_list)
{
ArrayList<Integer> top_weight_v_list = new ArrayList<Integer>();
int best_weight = 0;
for(int v : remaining_vertex_list)
{
if(vertices[v].get_weight() > best_weight)
{
best_weight = vertices[v].get_weight();
top_weight_v_list.clear();
top_weight_v_list.add(v);
}
else if(vertices[v].get_weight() == best_weight)
{
top_weight_v_list.add(v);
}
}
ArrayList<Integer> ret_list = new ArrayList<Integer>();
// System.out.println("top_weight_vertices: " + top_weight_v_list);
// return new ArrayList<Integer>(top_weight_v_list.subList(0, 150));
return top_weight_v_list;
} // public ArrayList<Integer> top_weight_vertices(Vertex[] vertices, ArrayList<Integer> remaining_vertex_list)
// public ArrayList<Integer> top_degree_vertices(Vertex[] vertices, LinkedList<Integer> remaining_vertex_list)
private ArrayList<Integer> top_degree_vertices(Vertex[] vertices, ArrayList<Integer> remaining_vertex_list)
{
ArrayList<Integer> top_degree_v_list = new ArrayList<Integer>();
int best_degree = 0;
for(int v : remaining_vertex_list)
{
if(vertices[v].get_degree() > best_degree)
{
best_degree = vertices[v].get_degree();
top_degree_v_list.clear();
top_degree_v_list.add(v);
}
else if(vertices[v].get_degree() == best_degree)
{
top_degree_v_list.add(v);
}
}
return top_degree_v_list;
} // public ArrayList<Integer> top_degree_vertices(Vertex[] vertices, ArrayList<Integer> remaining_vertex_list)
private ArrayList<Integer> random_degree_greedy_clique(int u, Vertex[] vertices, IntRelate int_relate_ob)
{
int[] nbs = vertices[u].get_neighbors();
Integer[] nbs_int_obj_array = Arrays.stream(nbs).boxed().toArray(Integer[]::new);
ArrayList<Integer> cand_vertices = new ArrayList<>(Arrays.asList(nbs_int_obj_array));
ArrayList<Integer> cand_clique = new ArrayList<Integer>();
cand_clique.add(u);
//System.out.println("having added " + u + " into the clique");
while(!cand_vertices.isEmpty())
{
int best_v = 0;
int best_degree = 0;
ArrayList<Integer> top_degree_v_list = new ArrayList<Integer>();
// Integer[] ia;
for(int v : cand_vertices)
{
if(vertices[v].get_degree() > best_degree)
{
best_degree = vertices[v].get_degree();
top_degree_v_list.clear();
top_degree_v_list.add(v);
}
else if(vertices[v].get_degree() == best_degree)
{
top_degree_v_list.add(v);
}
} // for(int v : cand_vertices.toArray())
int rand_top_degree_v = top_degree_v_list.get(rand.nextInt(top_degree_v_list.size()));
top_degree_v_list.clear();
cand_clique.add(rand_top_degree_v);
// System.out.println("having added " + rand_top_degree_v + " into the clique");
for(int i = cand_vertices.size() - 1; i >= 0; i--)
{
// if(rand_top_degree_v == cand_vertices.get(i) || is_connected(rand_top_degree_v, cand_vertices.get(i)))
if(rand_top_degree_v == cand_vertices.get(i) || !int_relate_ob.related((long)rand_top_degree_v, (long)cand_vertices.get(i)))
{
//System.out.println("remove " + cand_vertices.get(i));
cand_vertices.remove(i);
}
}
//System.out.println("cand_vertices: " + cand_vertices);
} // while(!cand_vertices.isEmpty())
//System.out.println("One degree-greedy clique completed.");
return cand_clique;
} // public ArrayList<Integer> degree_greedy_clique(int u, Vertex[] vertices)
public void update_top_level_weights_wrt_new_critical_cliques(ArrayList<Integer> colored_clique, ArrayList<ArrayList<Integer>> critical_clique_list, TreeSet<Integer> cand_remove_vertices_for_clique_reductions_wrt_degree_decrease, WeightedVertex[] vertices, IntRelate int_relate_ob, ZeroParameterBehavior zero_param_behav_ob, TwoParametersBehavior two_param_behav_ob, WeightBasedPartition weight_based_partition) //
{
BitSet top_level_weight_wrt_colors_updated_bits = new BitSet(top_level_weights_wrt_colors.size()); // 1 means updated, 0 means the opposite
for(int i = 0; i <= top_level_weights_wrt_colors.size(); i++)
{
// System.out.println("as to the " + (i + 1) + "-th color, the top weight is " + (i == top_level_weights_wrt_colors.size() ? 0 : top_level_weights_wrt_colors.get(i)) + ", trying to find a tighter bound+++++++++++++++++++++++");
// UsrPause.press_enter_to_continue();
if(i < top_level_weights_wrt_colors.size())
{
if(i > 0 && !top_level_weight_wrt_colors_updated_bits.get(i-1) && top_level_weights_wrt_colors.get(i) == top_level_weights_wrt_colors.get(i-1))
// if the top-level weight of the former color failed to be updated,
// and that of the current color is equal to it, then this weight will not be updated
{
System.out.println("the top-level weight of the former color, i.e., the " + (i) + "-th color, failed to be updated,");
System.out.println("which implies that the top-level weight of this color, i.e., the " + (i+1) + "-th color will not (continue to) be updated either, since the weights are equal to each other");
continue;
}
}
ArrayList<Integer> cand_vertices;
// prepare cand_vertices and lower_bound for i
if(i == top_level_weights_wrt_colors.size())
cand_vertices = weight_based_partition.get_vertex_list_of_weight_at_least(1);
else
cand_vertices = weight_based_partition.get_vertex_list_of_weight_at_least(top_level_weights_wrt_colors.get(i) + 1);
int lower_bound_for_requested_clique = i + 1;
if(cand_vertices.size() < lower_bound_for_requested_clique)
{
//System.out.println("cand_vertices.size(): " + cand_vertices.size());
//System.out.println("lower_bound: " + lower_bound_for_requested_clique);
//System.out.println("too few vertices to form a clique which contains at least " + lower_bound_for_requested_clique + " vertices");
continue;
}
boolean lower_bound_improved = update_top_level_weights_wrt_new_critical_cliques_in_vertex_list(cand_vertices, lower_bound_for_requested_clique, colored_clique, critical_clique_list, vertices, int_relate_ob, two_param_behav_ob);
// add those vertices which were not considered in the previous clique enumeration procedure
cand_remove_vertices_for_clique_reductions_wrt_degree_decrease.addAll(cand_vertices);
boolean OK = zero_param_behav_ob.behavior();
if(lower_bound_improved)
{
top_level_weight_wrt_colors_updated_bits.set(i);
i--; // in order to reconsider the current color
//System.out.println("will shrink cand_vertices according to the newly found top-level weights, and continue to search for a clique whose size is at least as big as " + lower_bound_for_requested_clique);
//System.out.print("colors whose top-level weights have been updated: ");
//for(int j = 0; j < top_level_weights_wrt_colors.size(); j++)
//if(top_level_weight_wrt_colors_updated_bits.get(j))
//System.out.print((j+1) + "-th\t");
//System.out.println();
}
// UsrPause.press_enter_to_continue();
}
System.out.println("eventual top_level_weights_wrt_colors: " + top_level_weights_wrt_colors);
}
public void update_top_level_weights_wrt_probabilistic_greedy_cliques(ArrayList<Integer> colored_clique, ArrayList<ArrayList<Integer>> critical_clique_list, WeightedVertex[] vertices, IntRelate int_relate_ob, ZeroParameterBehavior zero_param_behav_ob, TwoParametersBehavior two_param_behav_ob, WeightBasedPartition weight_based_partition) //
{
for(int i = 0; i <= top_level_weights_wrt_colors.size(); i++)
{
System.out.println("as to the " + (i + 1) + "-th color, the top weight is " + (i == top_level_weights_wrt_colors.size() ? 0 : top_level_weights_wrt_colors.get(i)) + ", trying to find a tighter bound (probabilistically)++++++++++++++");
// UsrPause.press_enter_to_continue();
ArrayList<Integer> cand_vertices;
// prepare cand_vertices and lower_bound for i
if(i == top_level_weights_wrt_colors.size())
{
cand_vertices = weight_based_partition.get_vertex_list_of_weight_at_least(1);
System.out.println("trying to find a clique which is larger than any found one");
}
else
cand_vertices = weight_based_partition.get_vertex_list_of_weight_at_least(top_level_weights_wrt_colors.get(i) + 1);
int lower_bound_for_requested_clique = i + 1;
if(cand_vertices.size() < lower_bound_for_requested_clique)
{
System.out.println("cand_vertices.size(): " + cand_vertices.size());
System.out.println("lower_bound_for_requested_clique: " + lower_bound_for_requested_clique);
System.out.println("too few vertices to form a clique which contains at least " + lower_bound_for_requested_clique + " vertices");
continue;
}
boolean lower_bound_improved = update_top_level_weights_wrt_one_probabilistic_greedy_clique_in_vertex_list(colored_clique, critical_clique_list, vertices, cand_vertices, lower_bound_for_requested_clique, int_relate_ob);
if(lower_bound_improved)
{
two_param_behav_ob.behavior(last_top_level_weight_updated_colors, new ArrayList<Integer>());
boolean OK = zero_param_behav_ob.behavior();
i--;
System.out.println("will shrink cand_vertices according to the newly found top-level weights, and continue to search for a clique whose size is at least as big as " + lower_bound_for_requested_clique);
}
// UsrPause.press_enter_to_continue();
}
System.out.println("eventual top_level_weights_wrt_colors: " + top_level_weights_wrt_colors);
}
public void update_top_level_weights_wrt_enumerated_cliques_adhere_to_vertex_list(ArrayList<Integer> colored_clique, ArrayList<ArrayList<Integer>> critical_clique_list, TreeSet<Integer> cand_remove_vertices_for_clique_reductions_wrt_degree_decrease, WeightedVertex[] vertices, ArrayList<Integer> starting_vertex_list, IntRelate int_relate_ob, ZeroParameterBehavior zero_param_behav_ob, TwoParametersBehavior two_param_behav_ob) // apply clique reductions after each enumeration
{
for(int v : starting_vertex_list)
{
// System.out.println("as to the " + (starting_vertex_list.indexOf(v) + 1) + "-th vertex " + v + " from the top weight/degree list++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
update_top_level_weights_wrt_enumerated_cliques_adhere_to_given_vertex(v, colored_clique, critical_clique_list, vertices, int_relate_ob, two_param_behav_ob);
// add those vertices which were not considered in the previous clique enumeration procedure
int[] nbs = vertices[v].get_neighbors();
Integer[] nbs_int_obj_array = Arrays.stream(nbs).boxed().toArray(Integer[]::new);
ArrayList<Integer> cand_vertices = new ArrayList<>(Arrays.asList(nbs_int_obj_array));
cand_remove_vertices_for_clique_reductions_wrt_degree_decrease.addAll(cand_vertices);
cand_remove_vertices_for_clique_reductions_wrt_degree_decrease.add(v);
boolean OK = zero_param_behav_ob.behavior();
// UsrPause.press_enter_to_continue();
}
}
private boolean update_top_level_weights_wrt_new_critical_cliques_in_vertex_list(ArrayList<Integer> cand_vertices, int lower_bound_for_requested_clique, ArrayList<Integer> colored_clique, ArrayList<ArrayList<Integer>> critical_clique_list, WeightedVertex[] vertices, IntRelate int_relate_ob, TwoParametersBehavior two_param_behav_ob)
{
// System.out.println("start to look for cliques containing at least " + lower_bound_for_requested_clique + " vertices, dfs");
ArrayList<Integer> reserved_vertex_list = new ArrayList<Integer>(cand_vertices);
ArrayDeque<Integer> decision_vertex_stack = new ArrayDeque<Integer>();
ArrayDeque<Integer> excluded_vertex_stack = new ArrayDeque<Integer>();
while(true)
{
// shrink cand_vertices to obtain a clique
int v_to_exclude = 0;
obtain_undesired_vertex_label:
// no need to deal with the special case when cand_vertices.size() == 1
for(int x1 : cand_vertices)
{
for(int x2 : cand_vertices)
{
if(x1 == x2) continue;
if(!int_relate_ob.related(x1, x2))
{
v_to_exclude = x1;
break obtain_undesired_vertex_label;
}
}
}
if(v_to_exclude != 0)
{
// make a decision, i.e., choose one branch
decision_vertex_stack.push(v_to_exclude);
cand_vertices.remove(Integer.valueOf(v_to_exclude));
excluded_vertex_stack.push(v_to_exclude);
if(cand_vertices.size() >= lower_bound_for_requested_clique) continue;
}
if(v_to_exclude == 0 && cand_vertices.size() >= lower_bound_for_requested_clique) // I think v_to_exclude == 0 implies cand_vertices.size() >= lower_bound_for_clique. NO!!!!!!!!!!!!!!!!!! If the input is a clique whose size is smaller than this bound, then my assumption does not hold.
{
// utilize this clique
ArrayList<Integer> cand_clique = new ArrayList<Integer>(cand_vertices);
// System.out.println("having obtained a maximal clique of size " + cand_clique.size() + "**: " + cand_clique);
// System.out.println("having obtained a maximal clique of size " + cand_clique.size() + "**, decision_stack_size: " + decision_vertex_stack.size());
// UsrPause.press_enter_to_continue();
boolean lower_bound_improved = update_top_level_weights_wrt_one_enumerated_clique(colored_clique, critical_clique_list, cand_clique, vertices);
if(lower_bound_improved)
{
// System.out.println("start reductions");
// apply clique reductions
two_param_behav_ob.behavior(last_top_level_weight_updated_colors, reserved_vertex_list);
// System.out.println("complete reductions");
return true;
}
}
do{
// below change the last decision
if(decision_vertex_stack.isEmpty()) // all branches covered
{
// System.out.println("enumerations completed");
return false;
}
int decision_v = decision_vertex_stack.pop(); // erase last decision
// back to a decision point
int v_to_include;
do{
v_to_include = excluded_vertex_stack.pop();
cand_vertices.add(v_to_include);
}while(v_to_include != decision_v);
// enter the other branch
ArrayList<Integer> removed_list = new ArrayList<Integer>();
for(int x : cand_vertices)
{
if(x == decision_v)
{
continue;
}
if(int_relate_ob.related(x, decision_v))
{
continue;
}
removed_list.add(x);
}
for(int x : removed_list)
{
cand_vertices.remove(Integer.valueOf(x));
excluded_vertex_stack.push(x);
}
}while(cand_vertices.size() < lower_bound_for_requested_clique);
} // while(true)
}
private void update_top_level_weights_wrt_enumerated_cliques_adhere_to_given_vertex(int u, ArrayList<Integer> colored_clique, ArrayList<ArrayList<Integer>> critical_clique_list, WeightedVertex[] vertices, IntRelate int_relate_ob, TwoParametersBehavior two_param_behav_ob)
{
// System.out.println("start to enumerate cliques which contains " + u);
int[] nbs = vertices[u].get_neighbors();
Integer[] nbs_int_obj_array = Arrays.stream(nbs).boxed().toArray(Integer[]::new);
ArrayList<Integer> cand_vertices = new ArrayList<>(Arrays.asList(nbs_int_obj_array));
ArrayList<Integer> reserved_vertex_list = new ArrayList<Integer>(cand_vertices);
reserved_vertex_list.add(u);
ArrayDeque<Integer> decision_vertex_stack = new ArrayDeque<Integer>();
ArrayDeque<Integer> excluded_vertex_stack = new ArrayDeque<Integer>();
while(true)
{
// shrink cand_vertices to obtain a clique
int v_to_exclude = 0;
obtain_undesired_vertex_label:
// no need to deal with the special case when cand_vertices.size() == 1
for(int x1 : cand_vertices)
{
for(int x2 : cand_vertices)
{
if(x1 == x2) continue;
if(!int_relate_ob.related(x1, x2))
{
v_to_exclude = x1;
break obtain_undesired_vertex_label;
}
}
}
if(v_to_exclude != 0)
{
// make a decision, i.e., choose one branch
decision_vertex_stack.push(v_to_exclude);
cand_vertices.remove(Integer.valueOf(v_to_exclude));
excluded_vertex_stack.push(v_to_exclude);
continue;
}
// a maximal clique found
// utilize this clique
ArrayList<Integer> cand_clique = new ArrayList<Integer>(cand_vertices);
cand_clique.add(u);
// System.out.println("having obtained a maximal clique of size " + cand_clique.size() + "**: " + cand_clique);
// System.out.println("having obtained a maximal clique of size " + cand_clique.size() + "**, decision_stack_size: " + decision_vertex_stack.size());
boolean lower_bound_improved = update_top_level_weights_wrt_one_enumerated_clique(colored_clique, critical_clique_list, cand_clique, vertices);
if(lower_bound_improved)
{
// System.out.println("start reductions");
// apply clique reductions
two_param_behav_ob.behavior(last_top_level_weight_updated_colors, reserved_vertex_list);
// System.out.println("complete reductions");
}
// below change the last decision
if(decision_vertex_stack.isEmpty())
{
// System.out.println("enumerations completed");
return;
}
int decision_v = decision_vertex_stack.pop(); // erase last decision
// back to a decision point
int v_to_include;
do{
v_to_include = excluded_vertex_stack.pop();
cand_vertices.add(v_to_include);
}while(v_to_include != decision_v);
// enter the other branch
ArrayList<Integer> removed_list = new ArrayList<Integer>();
for(int x : cand_vertices)
{
if(x == decision_v)
{
continue;
}
if(int_relate_ob.related(x, decision_v))
{
continue;
}
removed_list.add(x);
}
for(int x : removed_list)
{
cand_vertices.remove(Integer.valueOf(x));
excluded_vertex_stack.push(x);
}
} // while(true)
}
private ArrayList<Integer> random_weight_size_tuned_greedy_clique(int u, WeightedVertex[] vertices, IntRelate int_relate_ob, double mu)
// preconditions:
// post conditions: return a greedy clique wrt. mu, where u is the smallest vertex id
{
int[] nbs = vertices[u].get_neighbors();
Integer[] nbs_int_obj_array = Arrays.stream(nbs).boxed().toArray(Integer[]::new);
ArrayList<Integer> cand_vertices = new ArrayList<>(Arrays.asList(nbs_int_obj_array));
ArrayList<Integer> cand_clique = new ArrayList<Integer>();
cand_clique.add(u);
// System.out.println("having added " + u + " into cand_clique");
// System.out.println("its neighbors: " + cand_vertices);
while(!cand_vertices.isEmpty())
{
int best_v = 0;
double best_benefit = 0;
ArrayList<Double> hybrid_benefit_list = new ArrayList<Double>();
ArrayList<Integer> best_hybrid_benefit_v_list = new ArrayList<Integer>();
for(int v : cand_vertices)
{
int connection_benefit = 0; // how many cand vertices will remain if we add v
for(int x : cand_vertices)
{
if(x == v) continue;
if(!int_relate_ob.related(x, v)) continue;
connection_benefit++;
}
hybrid_benefit_list.add((double) vertices[v].get_weight() * mu + (double) connection_benefit);
}
for(int i = cand_vertices.size() - 1; i >= 0; i--)
{
int v = cand_vertices.get(i);
if(Double.compare(hybrid_benefit_list.get(i), best_benefit) > 0)
{
best_benefit = hybrid_benefit_list.get(i);
best_hybrid_benefit_v_list.clear();
best_hybrid_benefit_v_list.add(v);
}
else if(Double.compare(hybrid_benefit_list.get(i), best_benefit) == 0)
{
best_hybrid_benefit_v_list.add(v);
}
} // for(int v : cand_vertices)
hybrid_benefit_list.clear();
// System.out.println("best_hybrid_benefit_v_list: " + best_hybrid_benefit_v_list);
// since we require v < last_added_vertex, we may obtain no best_hybrid_benefit_v
/*
if(best_hybrid_benefit_v_list.isEmpty())
{
cand_vertices.clear();
break;
}
*/
int rand_best_hybrid_benefit_v = best_hybrid_benefit_v_list.get(rand.nextInt(best_hybrid_benefit_v_list.size()));
best_hybrid_benefit_v_list.clear();
cand_clique.add(rand_best_hybrid_benefit_v);
// System.out.println("having added " + rand_best_hybrid_benefit_v + " into cand_clique");
for(int i = cand_vertices.size() - 1; i >= 0; i--)
{
if(!int_relate_ob.related(rand_best_hybrid_benefit_v, cand_vertices.get(i)))
{
//System.out.println("remove " + cand_vertices.get(i));
cand_vertices.remove(i);
}
} // for(int i = cand_vertices.size() - 1; i >= 0; i--)
} // while(!cand_vertices.isEmpty())
// System.out.println("a hybrid-benefit greedy clique found: " + cand_clique);
return cand_clique;
}
private ArrayList<Integer> probabilistic_greedy_clique_based_on_missing_degree_in_vertex_list(ArrayList<Integer> cand_vertices, int lower_bound_for_requested_clique, IntRelate int_relate_ob)
// preconditions:
// post conditions: return a greedy maximal clique whose vertices are selected based on a probability proportional to its missing degree if lower_bound sat.
{
while(true)
{
ArrayList<Integer> missing_degree_list = new ArrayList<Integer>();
int missing_degree_sum = 0;
// compute missing degrees
for(int v : cand_vertices)
{
int missing_degree = 0; // how many cand vertices will be removed if we add v
for(int x : cand_vertices)
{
if(x == v) continue;
if(int_relate_ob.related(x, v)) continue;
missing_degree++;
}
// System.out.println("missing degree of " + v + " is " + missing_degree);
missing_degree_list.add(missing_degree);
missing_degree_sum += missing_degree;
}
if(missing_degree_sum == 0) // a clique has been found
{
// System.out.println("having obtained a probabilistic clique of size " + cand_vertices.size() + ": " + cand_vertices);
// UsrPause.press_enter_to_continue();
ArrayList<Integer> cand_clique = new ArrayList<Integer>();
if(cand_vertices.size() >= lower_bound_for_requested_clique)
cand_clique = new ArrayList<Integer>(cand_vertices);
return cand_clique;
}
// select a random vertex with probability proportional to missing_degree
int rand_num = rand.nextInt(missing_degree_sum);
int j = 0;
int next_bound = missing_degree_list.get(j);
while(rand_num >= next_bound)
{
j++;
next_bound += missing_degree_list.get(j);
}
// exclude it
int excluded_v = cand_vertices.get(j);
cand_vertices.remove(Integer.valueOf(excluded_v));
// System.out.println("having excluded " + excluded_v);
} // while(true)
}
private ArrayList<Integer> probabilistic_greedy_clique_based_on_missing_degree_in_vertex_list_2(ArrayList<Integer> cand_vertices, int lower_bound_for_requested_clique, IntRelate int_relate_ob)
// preconditions:
// post conditions: return a greedy maximal clique whose vertices have the min missing degree, breaking ties randomly, if lower_bound sat.
{
while(true)
{
// compute missing degrees
int max_missing_degree = 0;
ArrayList<Integer> best_missing_degree_remove_list = new ArrayList<Integer>();
for(int v : cand_vertices)
{
int missing_degree = 0; // how many cand vertices will be removed if we add v
for(int x : cand_vertices)
{
if(x == v) continue;
if(int_relate_ob.related(x, v)) continue;
missing_degree++;
}
// System.out.println("missing degree of " + v + " is " + missing_degree);
if(missing_degree > max_missing_degree)
{
max_missing_degree = missing_degree;
best_missing_degree_remove_list.clear();
best_missing_degree_remove_list.add(v);
}
else if(missing_degree == max_missing_degree)
{
best_missing_degree_remove_list.add(v);
}
}
if(max_missing_degree == 0)
{
ArrayList<Integer> cand_clique = new ArrayList<Integer>();
if(cand_vertices.size() >= lower_bound_for_requested_clique)
{
cand_clique = new ArrayList<Integer>(cand_vertices);
}
return cand_clique;
}
// select a random vertex with the max missing degree
int remove_v = best_missing_degree_remove_list.get(rand.nextInt(best_missing_degree_remove_list.size()));
cand_vertices.remove(Integer.valueOf(remove_v));
// System.out.println("having excluded " + remove_v);
} // while(true)
}
private ArrayList<Integer> probabilistic_greedy_clique_based_on_missing_degree_in_vertex_list_3(ArrayList<Integer> cand_vertices, int lower_bound_for_requested_clique, IntRelate int_relate_ob)
// preconditions:
// post conditions: return a greedy maximal clique whose vertices have the min missing degree, breaking ties randomly, if lower_bound sat.
{
while(true)
{
// compute missing degrees
int max_missing_degree = 0;
ArrayList<Integer> best_missing_degree_remove_list = new ArrayList<Integer>();
TreeMap<Integer, Integer> vertex_missing_degree = new TreeMap<Integer, Integer>();
for(int v : cand_vertices)
{
int missing_degree = 0; // how many cand vertices will be removed if we add v
for(int x : cand_vertices)
{
if(x == v) continue;
if(int_relate_ob.related(x, v)) continue;
missing_degree++;
}
vertex_missing_degree.put(v, missing_degree);
// System.out.println("missing degree of " + v + " is " + missing_degree);
if(missing_degree > max_missing_degree)
{
max_missing_degree = missing_degree;
best_missing_degree_remove_list.clear();
best_missing_degree_remove_list.add(v);
}
else if(missing_degree == max_missing_degree)
{
best_missing_degree_remove_list.add(v);
}
}
if(max_missing_degree == 0)
{
ArrayList<Integer> cand_clique = new ArrayList<Integer>();
if(cand_vertices.size() >= lower_bound_for_requested_clique)
{
cand_clique = new ArrayList<Integer>(cand_vertices);
}
return cand_clique;
}
ArrayList<Integer> best_second_level_missing_degree_remove_list = new ArrayList<Integer>();
int min_second_level_missing_degree = cand_vertices.size() * (cand_vertices.size() - 1); // assume complete graph, large enough
// System.out.println("best_missing_degree_remove_list (of size " + best_missing_degree_remove_list.size() +"): " + best_missing_degree_remove_list);
for(int v : best_missing_degree_remove_list)
{
int second_level_missing_degree = 0;
for(int x : cand_vertices)
{
if(x == v) continue;
if(int_relate_ob.related(x, v)) continue;
second_level_missing_degree += vertex_missing_degree.get(x);
}
// System.out.println("second_level_missing_degree of " + v + " is " + second_level_missing_degree);
if(second_level_missing_degree < min_second_level_missing_degree)
{
min_second_level_missing_degree = second_level_missing_degree;
best_second_level_missing_degree_remove_list.clear();
best_second_level_missing_degree_remove_list.add(v);
}
else if(second_level_missing_degree == min_second_level_missing_degree)
{
best_second_level_missing_degree_remove_list.add(v);
}
}
// System.out.println("best_second_level_missing_degree_remove_list (of size " + best_second_level_missing_degree_remove_list + "): " + best_second_level_missing_degree_remove_list);
// select a random vertex with the max missing degree, breaking ties in favor of the min second-level missing degree
int best_remove_v;
if(true)
// if(rand.nextBoolean()) // with p(=0.5) select among the second greedy, with 1-p select among the greedy
best_remove_v = best_second_level_missing_degree_remove_list.get(rand.nextInt(best_second_level_missing_degree_remove_list.size()));
else
best_remove_v = best_missing_degree_remove_list.get(rand.nextInt(best_missing_degree_remove_list.size()));
cand_vertices.remove(Integer.valueOf(best_remove_v));
// System.out.println("having excluded " + best_remove_v);
//UsrPause.press_enter_to_continue();
} // while(true)
}
private ArrayList<Integer> random_weight_greedy_clique(int u, WeightedVertex[] vertices, IntRelate int_relate_ob)
{
int[] nbs = vertices[u].get_neighbors();
Integer[] nbs_int_obj_array = Arrays.stream(nbs).boxed().toArray(Integer[]::new);
ArrayList<Integer> cand_vertices = new ArrayList<>(Arrays.asList(nbs_int_obj_array));
ArrayList<Integer> cand_clique = new ArrayList<Integer>();
cand_clique.add(u);
//System.out.println("having added " + u + " into the clique");
while(!cand_vertices.isEmpty())
{
int best_v = 0;
int best_weight = 0;
ArrayList<Integer> top_weight_v_list = new ArrayList<Integer>();
for(int v : cand_vertices)
{
if(vertices[v].get_weight() > best_weight)
{
best_weight = vertices[v].get_weight();
top_weight_v_list.clear();
top_weight_v_list.add(v);
}
else if(vertices[v].get_weight() == best_weight)
{
top_weight_v_list.add(v);
}
} // for(int v : cand_vertices)
int rand_top_weight_v = top_weight_v_list.get(rand.nextInt(top_weight_v_list.size()));
top_weight_v_list.clear();
cand_clique.add(rand_top_weight_v);
//System.out.println("having added " + rand_top_weight_v + " into the clique");
for(int i = cand_vertices.size() - 1; i >= 0; i--)
{
if(rand_top_weight_v == cand_vertices.get(i) || !int_relate_ob.related(rand_top_weight_v, cand_vertices.get(i)))
{
//System.out.println("remove " + cand_vertices.get(i));
cand_vertices.remove(i);
}
}
//System.out.println("cand_vertices: " + cand_vertices);
} // while(!cand_vertices.isEmpty())
//System.out.println("One weight-greedy clique completed.");
return cand_clique;
} // public ArrayList<Integer> weight_greedy_clique(int u, Vertex[] vertices, int seed)
public boolean update_top_level_weights_wrt_vertex_weight_decrease_clique(ArrayList<Integer> colored_clique, ArrayList<ArrayList<Integer>> critical_clique_list, ArrayList<Integer> cand_clique, WeightedVertex[] vertices)
// preconditions: cand_clique must be sorted, vertex weight must decrease
// return true of lower-bound actually improved, false otherwise
{
//System.out.println("current top_level_weights_wrt_colors: " + top_level_weights_wrt_colors);
last_top_level_weight_updated_colors.clear();
if(colored_clique.size() == 0)
{
colored_clique.addAll(cand_clique);
}
// update top_level_weights
boolean lower_bound_improved = false;
for(int i = 0; i < cand_clique.size(); i++)
{
int v = cand_clique.get(i);
if(i < top_level_weights_wrt_colors.size())
{
if(top_level_weights_wrt_colors.get(i) < vertices[v].get_weight())
{
// System.out.println("weight " + top_level_weights_wrt_colors.get(i) + " will be increased to be " + vertices[v].get_weight());
top_level_weights_wrt_colors.set(i, vertices[v].get_weight());
last_top_level_weight_updated_colors.add(i);
lower_bound_improved = true;
}
}
else
{
top_level_weights_wrt_colors.add(vertices[v].get_weight());
last_top_level_weight_updated_colors.add(i);
lower_bound_improved = true;
// System.out.println("insert a new weight: " + vertices[v].get_weight() + " into top level weights");
}
}
// update colored_clique
boolean need_to_update_colored_clique = false;
for(int i = 0; i < cand_clique.size(); i++)
{
if(i >= colored_clique.size())
{
need_to_update_colored_clique = true;
break;
}
if(vertices[cand_clique.get(i)].get_weight() > vertices[colored_clique.get(i)].get_weight())
{
need_to_update_colored_clique = true;
break;
}
else if(vertices[cand_clique.get(i)].get_weight() < vertices[colored_clique.get(i)].get_weight())
{
break;
}
} // for(int i = 0; i < cand_clique.size(); i++)
if(need_to_update_colored_clique)
{
// System.out.println("should be updated");
colored_clique.clear();
colored_clique.addAll(cand_clique);
}
// place cand_clique into critical_clique_list
if(!sorted_clique_strictly_below_top_level_weights(cand_clique, vertices) && !sorted_clique_covered_by_critical_clique_list(cand_clique, critical_clique_list, vertices))
critical_clique_list.add(cand_clique); // insert better ones
if(lower_bound_improved)
{
// delete redundant critical cliques
for(int i = critical_clique_list.size() - 1; i >= 0; i--)
{
// ArrayList<Integer> critical_clq = critical_clique_list.get(i);
if(sorted_clique_dominate_eq(cand_clique, critical_clique_list.get(i), vertices))
{
critical_clique_list.remove(i);// delete worse cliques
}
}
for(int i = critical_clique_list.size() - 1; i >= 0; i--)
{
if(!sorted_clique_intersect_with_top_level_weights(critical_clique_list.get(i), vertices))
{
critical_clique_list.remove(i);// delete redundant cliques
}
}
// System.out.println("lower-bound improved with the clique: " + cand_clique);
// System.out.println("top_level_weights: " + top_level_weights_wrt_colors);
}
return lower_bound_improved;
}
boolean sorted_clique_covered_by_critical_clique_list(ArrayList<Integer> cand_clique, ArrayList<ArrayList<Integer>> critical_clique_list, WeightedVertex[] vertices)
{
for(int i = 0; i < critical_clique_list.size(); i++)
{
if(sorted_clique_dominate_eq(critical_clique_list.get(i), cand_clique, vertices))
return true;
}
return false;
}
boolean sorted_clique_strictly_below_top_level_weights(ArrayList<Integer> tested_clique, WeightedVertex[] vertices)
// preconditions: tested_clique should be sorted, vertex weights from big to small
{
if(tested_clique.size() > top_level_weights_wrt_colors.size()) return false;
for(int i = 0; i < tested_clique.size(); i++)
if(vertices[tested_clique.get(i)].get_weight() >= top_level_weights_wrt_colors.get(i)) return false;
return true;
}
boolean sorted_clique_intersect_with_top_level_weights(ArrayList<Integer> tested_clique, WeightedVertex[] vertices)
// preconditions: tested_clique should be sorted, vertex weights from big to small
// preconditions: |C| <= |top_level_weights|
{
for(int i = 0; i < tested_clique.size(); i++)
{
if(vertices[tested_clique.get(i)].get_weight() == top_level_weights_wrt_colors.get(i)) return true;
}
return false;
}
//
boolean sorted_clique_dominate_eq(ArrayList<Integer> clq_1, ArrayList<Integer> clq_2, WeightedVertex[] vertices)
// preconditions: both cliques should be sorted, vertex weights from big to small
{
if(clq_1.size() < clq_2.size()) return false;
for(int i = 0; i < clq_2.size(); i++)
{
if(vertices[clq_1.get(i)].get_weight() < vertices[clq_2.get(i)].get_weight())
{
return false;
}
}
return true;
}
// public void update_top_level_weights_wrt_degree_greedy_clique(ArrayList<Integer> top_level_weights_wrt_colors, WeightedVertex[] vertices, LinkedList<Integer> remaining_vertex_list, IntRelate int_relate_ob, int seed)
public void update_top_level_weights_wrt_degree_greedy_clique(ArrayList<Integer> colored_clique, ArrayList<ArrayList<Integer>> critical_clique_list, WeightedVertex[] vertices, ArrayList<Integer> remaining_vertex_list, IntRelate int_relate_ob)
{
ArrayList<Integer> top_degree_v_list = top_degree_vertices(vertices, remaining_vertex_list);
int rand_top_degree_v = top_degree_v_list.get(rand.nextInt(top_degree_v_list.size()));
ArrayList<Integer> rand_degree_greedy_clique = random_degree_greedy_clique(rand_top_degree_v, vertices, int_relate_ob);
Collections.sort(rand_degree_greedy_clique, new Comparator<Integer>(){
public int compare(Integer n1, Integer n2){
if(vertices[n1].get_weight() < vertices[n2].get_weight() || (vertices[n1].get_weight() == vertices[n2].get_weight() && n1 < n2)){
return 1;
}
else{
return -1;
}
}
});
// System.out.println("Contents of degree_greedy_clique: " + degree_greedy_clique);
update_top_level_weights_wrt_vertex_weight_decrease_clique(colored_clique, critical_clique_list, rand_degree_greedy_clique, vertices);
} // public void update_top_level_weights_wrt_degree_greedy_clique(ArrayList<Integer> top_level_weights_wrt_colors, Vertex[] vertices, int seed)
public boolean update_top_level_weights_wrt_one_enumerated_clique(ArrayList<Integer> colored_clique, ArrayList<ArrayList<Integer>> critical_clique_list, ArrayList<Integer> enumerated_clique, WeightedVertex[] vertices)
{
Collections.sort(enumerated_clique, new Comparator<Integer>(){
public int compare(Integer n1, Integer n2){
if(vertices[n1].get_weight() < vertices[n2].get_weight() || (vertices[n1].get_weight() == vertices[n2].get_weight() && n1 < n2)){
return 1;
}
else{
return -1;
}
}
});
// System.out.println("after sorted by weight: " + enumerated_clique);
return update_top_level_weights_wrt_vertex_weight_decrease_clique(colored_clique, critical_clique_list, enumerated_clique, vertices);
} // public void update_top_level_weights_wrt_one_enumerated_clique(ArrayList<Integer> colored_clique, ArrayList<Integer> cand_clique, WeightedVertex[] vertices)
public void update_top_level_weights_wrt_weight_size_tuned_greedy_clique_list(ArrayList<Integer> colored_clique, ArrayList<ArrayList<Integer>> critical_clique_list, WeightedVertex[] vertices, IntRelate int_relate_ob, ZeroParameterBehavior zero_param_behav_ob, TwoParametersBehavior two_param_behav_ob, DegreeBasedPartition dgr_based_partition, WeightBasedPartition weight_based_partition)
{
ArrayList<Integer> starting_vertex_list;
/*
starting_vertex_list = weight_based_partition.get_vertices_of_maximum_weight();
starting_vertex_list.addAll(dgr_based_partition.get_vertices_of_maximum_degree());
*/
starting_vertex_list = weight_based_partition.get_vertex_list_of_weight_at_least(1); // obtain all vertices
for(int i = starting_vertex_list.size() - 1; i >= 0; i--)
{
System.out.println("remaining number of vertices for weight-size tuned clique constructions: " + starting_vertex_list.size() + "-------------------------");
int starting_vertex = starting_vertex_list.get(i);
starting_vertex_list.remove(i);
if(vertices[starting_vertex].get_degree() == 0)
{
ArrayList<Integer> single_vertex_clique = new ArrayList<Integer>();
single_vertex_clique.add(starting_vertex);
boolean lower_bound_improved = update_top_level_weights_wrt_vertex_weight_decrease_clique(colored_clique, critical_clique_list, single_vertex_clique, vertices);
if(lower_bound_improved)
{
two_param_behav_ob.behavior(last_top_level_weight_updated_colors, new ArrayList<Integer>());
boolean OK = zero_param_behav_ob.behavior();
}
continue;
}
System.out.println("about to contruct cliques with vertex: " + starting_vertex);
// preparing parameter values
double mu_max = vertices[starting_vertex].get_degree(); // weight difference is absolute
// System.out.println("degree: " + vertices[starting_vertex].get_degree());
// System.out.println("mu_max: " + mu_max);
int max_w = 0;
for(int nb : vertices[starting_vertex].get_neighbors())
{
max_w = StrictMath.max(max_w, vertices[nb].get_weight());
}
// System.out.println("max_w: " + max_w);
double mu_min = 1.0 / ((double)max_w); // connection difference is absolute
// System.out.println("mu_min: " + mu_min);
for(double mu = mu_max; Double.compare(mu, mu_min) > 0; mu /= 1.414) //sqrt(2), instead of 2 to allow better diversification, but more time needed
{
// System.out.println("mu: " + mu);
boolean lower_bound_improved = update_top_level_weights_wrt_one_weight_size_tuned_greedy_clique(colored_clique, critical_clique_list, vertices, starting_vertex, int_relate_ob, mu);
if(lower_bound_improved)
{
two_param_behav_ob.behavior(last_top_level_weight_updated_colors, new ArrayList<Integer>());
boolean OK = zero_param_behav_ob.behavior();
}
}
// UsrPause.press_enter_to_continue();
}
}
private boolean update_top_level_weights_wrt_one_weight_size_tuned_greedy_clique(ArrayList<Integer> colored_clique, ArrayList<ArrayList<Integer>> critical_clique_list, WeightedVertex[] vertices, int starting_vertex, IntRelate int_relate_ob, double mu)
{
ArrayList<Integer> rand_tuned_greedy_clique = random_weight_size_tuned_greedy_clique(starting_vertex, vertices, int_relate_ob, mu);
Collections.sort(rand_tuned_greedy_clique, new Comparator<Integer>(){
public int compare(Integer n1, Integer n2){
if(vertices[n1].get_weight() < vertices[n2].get_weight() || (vertices[n1].get_weight() == vertices[n2].get_weight() && n1 < n2)){
return 1;
}
else{
return -1;
}
}
});
// System.out.println("having obtained a sorted tuned clique: " + rand_tuned_greedy_clique);
// UsrPause.press_enter_to_continue();
return update_top_level_weights_wrt_vertex_weight_decrease_clique(colored_clique, critical_clique_list, rand_tuned_greedy_clique, vertices);
} //
private boolean update_top_level_weights_wrt_one_probabilistic_greedy_clique_in_vertex_list(ArrayList<Integer> colored_clique, ArrayList<ArrayList<Integer>> critical_clique_list, WeightedVertex[] vertices, ArrayList<Integer> cand_vertices, int lower_bound_for_requested_clique, IntRelate int_relate_ob)
// postconditions: return true if lower_bound_improved, false otherwise
{
ArrayList<Integer> probabilistic_greedy_clique = new ArrayList<Integer>();
for(int i = 0; i < MAX_GUESS_NUM; i++)
{
// System.out.println("the " + (i+1) + "-th attempt to find a clique whose size is at least " + lower_bound_for_requested_clique);
// probabilistic_greedy_clique = probabilistic_greedy_clique_based_on_missing_degree_in_vertex_list(new ArrayList<Integer>(cand_vertices), lower_bound_for_requested_clique, int_relate_ob);
// probabilistic_greedy_clique = probabilistic_greedy_clique_based_on_missing_degree_in_vertex_list_2(new ArrayList<Integer>(cand_vertices), lower_bound_for_requested_clique, int_relate_ob);
probabilistic_greedy_clique = probabilistic_greedy_clique_based_on_missing_degree_in_vertex_list_3(new ArrayList<Integer>(cand_vertices), lower_bound_for_requested_clique, int_relate_ob);
if(!probabilistic_greedy_clique.isEmpty())
{
System.out.println("having obtained a new critical clique at the " + (i+1) + "-th guess: " + probabilistic_greedy_clique);
UsrPause.press_enter_to_continue();
break;
}
}
if(probabilistic_greedy_clique.isEmpty())
return false;
Collections.sort(probabilistic_greedy_clique, new Comparator<Integer>(){
public int compare(Integer n1, Integer n2){
if(vertices[n1].get_weight() < vertices[n2].get_weight() || (vertices[n1].get_weight() == vertices[n2].get_weight() && n1 < n2)){
return 1;
}
else{
return -1;
}
}
});
System.out.println("having obtained a sorted tuned clique: " + probabilistic_greedy_clique);
// UsrPause.press_enter_to_continue();
return update_top_level_weights_wrt_vertex_weight_decrease_clique(colored_clique, critical_clique_list, probabilistic_greedy_clique, vertices);
} //
// public void update_top_level_weights_wrt_weight_greedy_clique(ArrayList<Integer> top_level_weights_wrt_colors, WeightedVertex[] vertices, LinkedList<Integer> remaining_vertex_list, IntRelate int_relate_ob, int seed)
public void update_top_level_weights_wrt_weight_greedy_clique(ArrayList<Integer> colored_clique, ArrayList<ArrayList<Integer>> critical_clique_list, WeightedVertex[] vertices, ArrayList<Integer> remaining_vertex_list, IntRelate int_relate_ob)
{
// ArrayList<Integer> top_weight_v_list = cliq_search.top_weight_vertices(instance_graph);
ArrayList<Integer> top_weight_v_list = top_weight_vertices(vertices, remaining_vertex_list);
//System.out.println("Contents of top weight vertex list: " + top_weight_v_list);
int rand_top_weight_v = top_weight_v_list.get(rand.nextInt(top_weight_v_list.size()));
ArrayList<Integer> rand_weight_greedy_clique = random_weight_greedy_clique(rand_top_weight_v, vertices, int_relate_ob);
Collections.sort(rand_weight_greedy_clique, new Comparator<Integer>(){
public int compare(Integer n1, Integer n2){
// if(instance_graph.get_vertices()[n1].get_weight() < instance_graph.get_vertices()[n2].get_weight()){
if(vertices[n1].get_weight() < vertices[n2].get_weight() || (vertices[n1].get_weight() == vertices[n2].get_weight() && n1 < n2)){
return 1;
}
else{
return -1;
}
}
});
// System.out.println("Contents of weight_greedy_clique: " + weight_greedy_clique);
update_top_level_weights_wrt_vertex_weight_decrease_clique(colored_clique, critical_clique_list, rand_weight_greedy_clique, vertices);
} // public void update_top_level_weights_wrt_weight_greedy_clique(ArrayList<Integer> top_level_weights_wrt_colors, Vertex[] vertices, int seed)
} // class CliqueSearch
|
/*
* Copyright 2015-2020 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.personalize.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.personalize.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ListSolutionVersionsResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListSolutionVersionsResultJsonUnmarshaller implements Unmarshaller<ListSolutionVersionsResult, JsonUnmarshallerContext> {
public ListSolutionVersionsResult unmarshall(JsonUnmarshallerContext context) throws Exception {
ListSolutionVersionsResult listSolutionVersionsResult = new ListSolutionVersionsResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return listSolutionVersionsResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("solutionVersions", targetDepth)) {
context.nextToken();
listSolutionVersionsResult.setSolutionVersions(new ListUnmarshaller<SolutionVersionSummary>(SolutionVersionSummaryJsonUnmarshaller
.getInstance())
.unmarshall(context));
}
if (context.testExpression("nextToken", targetDepth)) {
context.nextToken();
listSolutionVersionsResult.setNextToken(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return listSolutionVersionsResult;
}
private static ListSolutionVersionsResultJsonUnmarshaller instance;
public static ListSolutionVersionsResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ListSolutionVersionsResultJsonUnmarshaller();
return instance;
}
}
|
package com.codeborne.selenide.collections;
import com.codeborne.selenide.CollectionCondition;
import com.codeborne.selenide.ex.ListSizeMismatch;
import com.codeborne.selenide.impl.CollectionSource;
import org.openqa.selenium.WebElement;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.List;
@ParametersAreNonnullByDefault
public class SizeGreaterThan extends CollectionCondition {
protected final int expectedSize;
public SizeGreaterThan(int expectedSize) {
this.expectedSize = expectedSize;
}
@Override
public boolean test(List<WebElement> elements) {
return apply(elements.size());
}
@Override
public void fail(CollectionSource collection,
@Nullable List<WebElement> elements,
@Nullable Exception lastError,
long timeoutMs) {
throw new ListSizeMismatch(collection.driver(), ">", expectedSize, explanation, collection, elements, lastError, timeoutMs);
}
@Override
public boolean missingElementSatisfiesCondition() {
return apply(0);
}
@Override
public String toString() {
return String.format("size > %s", expectedSize);
}
private boolean apply(int size) {
return size > expectedSize;
}
}
|
/*
* Copyright (c) 2018 Cloudera, Inc. All Rights Reserved.
*
* Portions Copyright (c) Copyright 2013-2018 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.
* 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.cloudera.cdp.opdb.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.cloudera.cdp.client.CdpResponse;
/**
* Lists the in-progress diagnostic bundle operations.
**/
@javax.annotation.Generated(value = "com.cloudera.cdp.client.codegen.CdpSDKJavaCodegen", date = "2021-12-01T15:55:33.142-08:00")
public class ListDiagnosticsRequest {
/**
* The name of the environment
**/
private String environmentName = null;
/**
* The name of the database
**/
private String databaseName = null;
/**
* Getter for environmentName.
* The name of the environment
**/
@JsonProperty("environmentName")
public String getEnvironmentName() {
return environmentName;
}
/**
* Setter for environmentName.
* The name of the environment
**/
public void setEnvironmentName(String environmentName) {
this.environmentName = environmentName;
}
/**
* Getter for databaseName.
* The name of the database
**/
@JsonProperty("databaseName")
public String getDatabaseName() {
return databaseName;
}
/**
* Setter for databaseName.
* The name of the database
**/
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ListDiagnosticsRequest listDiagnosticsRequest = (ListDiagnosticsRequest) o;
if (!Objects.equals(this.environmentName, listDiagnosticsRequest.environmentName)) {
return false;
}
if (!Objects.equals(this.databaseName, listDiagnosticsRequest.databaseName)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(environmentName, databaseName);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ListDiagnosticsRequest {\n");
sb.append(" environmentName: ").append(toIndentedString(environmentName)).append("\n");
sb.append(" databaseName: ").append(toIndentedString(databaseName)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line except the first indented by 4 spaces.
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
/*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package eu.virtuwind.monitoring.impl.util;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
/* InstanceIdentifierUtils provides utility functions related to InstanceIdentifiers.
*/
public final class InstanceIdentifierUtils {
private InstanceIdentifierUtils() {
throw new UnsupportedOperationException("Utility class should never be instantiated");
}
/**
* @param node
* @return
*/
public static InstanceIdentifier<Node> generateNodeInstanceIdentifier(final String node) {
NodeId nodeId = new NodeId(node);
return InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId)).build();
}
/**
* @param node
* @param flowTableKey
* @return
*/
public static InstanceIdentifier<Table> generateFlowTableInstanceIdentifier(final String node,
final TableKey flowTableKey) {
return generateNodeInstanceIdentifier(node).builder().augmentation(FlowCapableNode.class)
.child(Table.class, flowTableKey).build();
}
/**
* @param node
* @param flowTableKey
* @param flowKey
* @return
*/
public static InstanceIdentifier<Flow> generateFlowInstanceIdentifier(final String node,
final TableKey flowTableKey, final FlowKey flowKey) {
return generateFlowTableInstanceIdentifier(node, flowTableKey).child(Flow.class, flowKey);
}
}
|
/*
* Copyright 2019 Scott Logic 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.scottlogic.datahelix.generator.core.config.detail;
public enum DataGenerationType {
FULL_SEQUENTIAL,
RANDOM
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.daw.dao.specificDaoImplementation_0;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import net.daw.bean.beanImplementation.UsuarioBean;
import net.daw.bean.publicBeanInterface.BeanInterface;
import net.daw.dao.genericDaoImplementation.GenericDaoImplementation;
import net.daw.dao.publicDaoInterface.DaoInterface;
import net.daw.factory.BeanFactory;
import net.daw.helper.UserActivationEmail;
/**
*
* @author Ramón
*/
public class UsuarioDao_0 extends GenericDaoImplementation implements DaoInterface{
public UsuarioDao_0(Connection oConnection, String ob,UsuarioBean oUsuarioBeanSession) {
super(oConnection, ob, oUsuarioBeanSession);
}
@Override
public BeanInterface get(int id, Integer expand) throws Exception {
throw new Exception("Error en Dao remove de " + ob + ": No autorizado");
}
@Override
public int remove(int id) throws Exception {
throw new Exception("Error en Dao remove de " + ob + ": No autorizado");
}
@Override
public int getcount() throws Exception {
throw new Exception("Error en Dao remove de " + ob + ": No autorizado");
}
@Override
public BeanInterface create(BeanInterface oBean) throws Exception {
UsuarioBean oUsuarioBeanIf = (UsuarioBean) oBean;
UsuarioBean oBeanActivation;
int idtipousuario = oUsuarioBeanIf.getId_tipousuario();
if (idtipousuario == 0) {
try {
oBeanActivation = (UsuarioBean) super.create(oBean);
String email = oBeanActivation.getEmail();
String nombre = oBeanActivation.getNombre();
UsuarioBean oBeanToken = (UsuarioBean) super.get(oBeanActivation.getId(), 1);
String token = oBeanToken.getToken();
UserActivationEmail.sendActivationEmail(email, nombre, token);
} catch (Exception ex) {
throw new Exception("Error en Dao create de " + ob + ": " + ex.getMessage(), ex);
}
return oBeanActivation;
} else {
throw new Exception("Error en Dao create de " + ob + ": No autorizado");
}
}
@Override
public int update(BeanInterface oBean) throws Exception {
throw new Exception("Error en Dao remove de " + ob + ": No autorizado");
}
@Override
public ArrayList<BeanInterface> getpage(int iRpp, int iPage, HashMap<String, String> hmOrder, Integer expand) throws Exception {
throw new Exception("Error en Dao remove de " + ob + ": No autorizado");
}
public UsuarioBean login(String strUserName, String strPassword) throws Exception {
String strSQL = "SELECT * FROM " + ob + " WHERE login=? AND pass=?";
UsuarioBean oUsuarioBean;
ResultSet oResultSet = null;
PreparedStatement oPreparedStatement = null;
try {
oPreparedStatement = oConnection.prepareStatement(strSQL);
oPreparedStatement.setString(1, strUserName);
oPreparedStatement.setString(2, strPassword);
oResultSet = oPreparedStatement.executeQuery();
if (oResultSet.next()) {
oUsuarioBean = new UsuarioBean();
oUsuarioBean.fill(oResultSet, oConnection, 1, oUsuarioBeanSession);
} else {
oUsuarioBean = null;
}
} catch (SQLException e) {
throw new Exception("Error en Dao get de " + ob, e);
} finally {
if (oResultSet != null) {
oResultSet.close();
}
if (oPreparedStatement != null) {
oPreparedStatement.close();
}
}
return oUsuarioBean;
}
public BeanInterface comprobarToken(String token, Integer expand) throws Exception {
strSQL_get = "SELECT * FROM " + ob + " WHERE token=?";
BeanInterface oBean;
ResultSet oResultSet = null;
PreparedStatement oPreparedStatement = null;
try {
oPreparedStatement = oConnection.prepareStatement(strSQL_get);
oPreparedStatement.setString(1, token);
oResultSet = oPreparedStatement.executeQuery();
if (oResultSet.next()) {
oBean = BeanFactory.getBean(ob);
oBean.fill(oResultSet, oConnection, expand, oUsuarioBeanSession);
} else {
oBean = null;
}
} catch (SQLException e) {
throw new Exception("Error en Dao get de " + ob, e);
} finally {
if (oResultSet != null) {
oResultSet.close();
}
if (oPreparedStatement != null) {
oPreparedStatement.close();
}
}
return oBean;
}
//Esto tiene que ser un get, para pasarle campos a sendConfirmationEmail - Corregir
// public int comprobarToken(String token) throws Exception {
// strSQL_getcount = "SELECT COUNT(id) FROM " + ob + " WHERE token=?";
// int res = 0;
// ResultSet oResultSet = null;
// PreparedStatement oPreparedStatement = null;
// try {
// oPreparedStatement = oConnection.prepareStatement(strSQL_getcount);
// oPreparedStatement.setString(1, token);
// oResultSet = oPreparedStatement.executeQuery();
// if (oResultSet.next()) {
// res = oResultSet.getInt(1);
// }
// } catch (SQLException e) {
// throw new Exception("Error en Dao comprobarToken de " + ob + ": " + e.getMessage(), e);
// } finally {
// if (oResultSet != null) {
// oResultSet.close();
// }
// if (oPreparedStatement != null) {
// oPreparedStatement.close();
// }
// }
// return res;
// }
public int activarUsuario(String token) throws Exception {
int iResult = 0;
strSQL_update = "UPDATE " + ob + " SET ";
strSQL_update += "id_tipousuario=2,validado=1 ";
strSQL_update += "WHERE token=?";
PreparedStatement oPreparedStatement = null;
try {
oPreparedStatement = oConnection.prepareStatement(strSQL_update);
oPreparedStatement.setString(1, token);
iResult = oPreparedStatement.executeUpdate();
} catch (SQLException e) {
throw new Exception("Error en Dao activarUsuario de " + ob + ": " + e.getMessage(), e);
} finally {
if (oPreparedStatement != null) {
oPreparedStatement.close();
}
}
return iResult;
}
public Integer activar(String token) throws Exception {
int resultadoActivacion = 0;
UsuarioBean oUsuarioBean = (UsuarioBean) this.comprobarToken(token, 2);
if (oUsuarioBean.getToken().equals(token)) {
resultadoActivacion = this.activarUsuario(token);
UserActivationEmail.sendCofirmationEmail(oUsuarioBean.getEmail(), oUsuarioBean.getNombre());
}
return resultadoActivacion;
}
}
|
/*
* © 2020. TU Dortmund University,
* Institute of Energy Systems, Energy Efficiency and Energy Economics,
* Research group Distribution grid planning and operation
*/
package edu.ie3.datamodel.io.sink;
import edu.ie3.datamodel.exceptions.SinkException;
import edu.ie3.datamodel.io.connectors.InfluxDbConnector;
import edu.ie3.datamodel.io.csv.FileNamingStrategy;
import edu.ie3.datamodel.io.processor.ProcessorProvider;
import edu.ie3.datamodel.io.processor.timeseries.TimeSeriesProcessorKey;
import edu.ie3.datamodel.models.UniqueEntity;
import edu.ie3.datamodel.models.result.ResultEntity;
import edu.ie3.datamodel.models.timeseries.TimeSeries;
import edu.ie3.datamodel.models.timeseries.TimeSeriesEntry;
import edu.ie3.datamodel.models.value.Value;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.influxdb.InfluxDB;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
/** InfluxDB Sink for result and time series data */
public class InfluxDbSink implements OutputDataSink {
private static final Logger log = LogManager.getLogger(InfluxDbSink.class);
/** Field name for timestamp field in result entities */
private static final String FIELD_NAME_TIMESTAMP = "timestamp";
/** Field name for timestamp field in time series */
private static final String FIELD_NAME_TIME = "time";
/** Field name for input model uuid field in result entities */
private static final String FIELD_NAME_INPUT = "inputModel";
private final InfluxDbConnector connector;
private final FileNamingStrategy fileNamingStrategy;
private final ProcessorProvider processorProvider;
/**
* Initializes a new InfluxDbWeatherSource
*
* @param connector needed for database connection
* @param fileNamingStrategy needed to create measurement names for entities
*/
public InfluxDbSink(InfluxDbConnector connector, FileNamingStrategy fileNamingStrategy) {
this.connector = connector;
this.fileNamingStrategy = fileNamingStrategy;
this.processorProvider =
new ProcessorProvider(
ProcessorProvider.allResultEntityProcessors(),
ProcessorProvider.allTimeSeriesProcessors());
}
/**
* Initializes a new InfluxDbWeatherSource with a default FileNamingStrategy
*
* @param connector needed for database connection
*/
public InfluxDbSink(InfluxDbConnector connector) {
this(connector, new FileNamingStrategy());
}
@Override
public void shutdown() {
connector.shutdown();
}
@Override
public <C extends UniqueEntity> void persist(C entity) {
Set<Point> points = extractPoints(entity);
// writes only the exact one point instead of unnecessarily wrapping it in BatchPoints
if (points.size() == 1) write(points.iterator().next());
else writeAll(points);
}
@Override
public <C extends UniqueEntity> void persistAll(Collection<C> entities) {
Set<Point> points = new HashSet<>();
for (C entity : entities) {
points.addAll(extractPoints(entity));
}
writeAll(points);
}
@Override
public <E extends TimeSeriesEntry<V>, V extends Value> void persistTimeSeries(
TimeSeries<E, V> timeSeries) {
Set<Point> points = transformToPoints(timeSeries);
writeAll(points);
}
/**
* Transforms a ResultEntity to an influxDB data point. <br>
* As the equivalent to a relational table, the influxDB measurement point will be named using the
* given FileNamingStrategy if possible, or the class name otherwise. All special characters in
* the measurement name will be replaced by underscores.
*
* @param entity the entity to transform
*/
private Optional<Point> transformToPoint(ResultEntity entity) {
Optional<String> measurementName =
fileNamingStrategy.getResultEntityFileName(entity.getClass());
if (!measurementName.isPresent())
log.warn(
"I could not get a measurement name for class {}. I am using its simple name instead.",
entity.getClass().getSimpleName());
return transformToPoint(entity, measurementName.orElse(entity.getClass().getSimpleName()));
}
/**
* Transforms a ResultEntity to an influxDB data point. <br>
* All special characters in the measurement name will be replaced by underscores.
*
* @param entity the entity to transform
* @param measurementName equivalent to the name of a relational table
*/
private Optional<Point> transformToPoint(ResultEntity entity, String measurementName) {
LinkedHashMap<String, String> entityFieldData;
try {
entityFieldData =
processorProvider
.handleEntity(entity)
.orElseThrow(
() ->
new SinkException(
"Cannot persist entity of type '"
+ entity.getClass().getSimpleName()
+ "'. This sink can only process the following entities: ["
+ processorProvider.getRegisteredClasses().stream()
.map(Class::getSimpleName)
.collect(Collectors.joining(","))
+ "]"));
entityFieldData.remove(FIELD_NAME_TIMESTAMP);
return Optional.of(
Point.measurement(transformToMeasurementName(measurementName))
.time((entity).getTimestamp().toInstant().toEpochMilli(), TimeUnit.MILLISECONDS)
.tag("input_model", entityFieldData.remove(FIELD_NAME_INPUT))
.tag("scenario", connector.getScenarioName())
.fields(Collections.unmodifiableMap(entityFieldData))
.build());
} catch (SinkException e) {
log.error(
"Cannot persist provided entity '{}'. Exception: {}",
() -> entity.getClass().getSimpleName(),
() -> e);
}
return Optional.empty();
}
/**
* Transforms a timeSeries to influxDB data points, one point for each value. <br>
* As the equivalent to a relational table, the influxDB measurement point will be named using the
* given FileNamingStrategy if possible, or the class name otherwise. All special characters in
* the measurement name will be replaced by underscores.
*
* @param timeSeries the time series to transform
*/
private <E extends TimeSeriesEntry<V>, V extends Value> Set<Point> transformToPoints(
TimeSeries<E, V> timeSeries) {
if (timeSeries.getEntries().isEmpty()) return Collections.emptySet();
Optional<String> measurementName = fileNamingStrategy.getFileName(timeSeries);
if (!measurementName.isPresent()) {
String valueClassName =
timeSeries.getEntries().iterator().next().getValue().getClass().getSimpleName();
log.warn(
"I could not get a measurement name for TimeSeries value class {}. I am using it's value's simple name instead.",
valueClassName);
return transformToPoints(timeSeries, valueClassName);
}
return transformToPoints(timeSeries, measurementName.get());
}
/**
* Transforms a timeSeries to influxDB data points, one point for each value. <br>
* All special characters in the measurement name will be replaced by underscores.
*
* @param timeSeries the time series to transform
* @param measurementName equivalent to the name of a relational table
*/
private <E extends TimeSeriesEntry<V>, V extends Value> Set<Point> transformToPoints(
TimeSeries<E, V> timeSeries, String measurementName) {
TimeSeriesProcessorKey key = new TimeSeriesProcessorKey(timeSeries);
Set<Point> points = new HashSet<>();
try {
Set<LinkedHashMap<String, String>> entityFieldData =
processorProvider
.handleTimeSeries(timeSeries)
.orElseThrow(
() ->
new SinkException(
"Cannot persist time series of combination '"
+ key
+ "'. This sink can only process the following combinations: ["
+ processorProvider.getRegisteredTimeSeriesCombinations().stream()
.map(TimeSeriesProcessorKey::toString)
.collect(Collectors.joining(","))
+ "]"));
for (LinkedHashMap<String, String> dataMapping : entityFieldData) {
String timeString = dataMapping.remove(FIELD_NAME_TIME);
long timeMillis = ZonedDateTime.parse(timeString).toInstant().toEpochMilli();
Point point =
Point.measurement(transformToMeasurementName(measurementName))
.time(timeMillis, TimeUnit.MILLISECONDS)
.tag("scenario", connector.getScenarioName())
.fields(Collections.unmodifiableMap(dataMapping))
.build();
points.add(point);
}
} catch (SinkException e) {
log.error("Cannot persist provided time series '{}'. Exception: {}", () -> key, () -> e);
}
return points;
}
/**
* Transforms an entity to an influxDB data point. <br>
* The measurement point will be named by the given FileNamingStrategy if possible, or the class
* name otherwise. All special characters in the measurement name will be replaced by underscores.
*
* @param entity the entity of which influxDB points will be extracted
* @param <C> bounded to be all unique entities, but logs an error and returns an empty Set if it
* does not extend {@link ResultEntity} or {@link TimeSeries}
*/
private <C extends UniqueEntity> Set<Point> extractPoints(C entity) {
Set<Point> points = new HashSet<>();
/* Distinguish between result models and time series */
if (entity instanceof ResultEntity) {
try {
points.add(
transformToPoint((ResultEntity) entity)
.orElseThrow(() -> new SinkException("Could not transform entity")));
} catch (SinkException e) {
log.error(
"Cannot persist provided entity '{}'. Exception: {}",
() -> entity.getClass().getSimpleName(),
() -> e);
}
} else if (entity instanceof TimeSeries) {
TimeSeries<?, ?> timeSeries = (TimeSeries<?, ?>) entity;
points.addAll(transformToPoints(timeSeries));
} else {
log.error(
"I don't know how to handle an entity of class {}", entity.getClass().getSimpleName());
}
return points;
}
/**
* Writes the point to the database
*
* @param point point to write
*/
private void write(Point point) {
if (point == null) return;
try (InfluxDB session = connector.getSession()) {
session.write(point);
}
}
/**
* Writes all points as a batch to the database
*
* @param points points to write
*/
private void writeAll(Collection<Point> points) {
if (points.isEmpty()) return;
BatchPoints batchPoints = BatchPoints.builder().points(points).build();
try (InfluxDB session = connector.getSession()) {
session.write(batchPoints);
}
}
/**
* Remove leading and trailing whitespace and replace all special characters with underscores
*
* @param filename the file name to transform
*/
private static String transformToMeasurementName(String filename) {
return filename.trim().replaceAll("\\W", "_");
}
}
|
/*
* 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.
*/
// Generated by http://code.google.com/p/protostuff/ ... DO NOT EDIT!
// Generated from protobuf
package org.apache.drill.exec.proto.beans;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import com.dyuproject.protostuff.GraphIOUtil;
import com.dyuproject.protostuff.Input;
import com.dyuproject.protostuff.Message;
import com.dyuproject.protostuff.Output;
import com.dyuproject.protostuff.Schema;
public final class FragmentHandle implements Externalizable, Message<FragmentHandle>, Schema<FragmentHandle>
{
public static Schema<FragmentHandle> getSchema()
{
return DEFAULT_INSTANCE;
}
public static FragmentHandle getDefaultInstance()
{
return DEFAULT_INSTANCE;
}
static final FragmentHandle DEFAULT_INSTANCE = new FragmentHandle();
private QueryId queryId;
private int majorFragmentId;
private int minorFragmentId;
private QueryId parentQueryId;
public FragmentHandle()
{
}
// getters and setters
// queryId
public QueryId getQueryId()
{
return queryId;
}
public FragmentHandle setQueryId(QueryId queryId)
{
this.queryId = queryId;
return this;
}
// majorFragmentId
public int getMajorFragmentId()
{
return majorFragmentId;
}
public FragmentHandle setMajorFragmentId(int majorFragmentId)
{
this.majorFragmentId = majorFragmentId;
return this;
}
// minorFragmentId
public int getMinorFragmentId()
{
return minorFragmentId;
}
public FragmentHandle setMinorFragmentId(int minorFragmentId)
{
this.minorFragmentId = minorFragmentId;
return this;
}
// parentQueryId
public QueryId getParentQueryId()
{
return parentQueryId;
}
public FragmentHandle setParentQueryId(QueryId parentQueryId)
{
this.parentQueryId = parentQueryId;
return this;
}
// java serialization
public void readExternal(ObjectInput in) throws IOException
{
GraphIOUtil.mergeDelimitedFrom(in, this, this);
}
public void writeExternal(ObjectOutput out) throws IOException
{
GraphIOUtil.writeDelimitedTo(out, this, this);
}
// message method
public Schema<FragmentHandle> cachedSchema()
{
return DEFAULT_INSTANCE;
}
// schema methods
public FragmentHandle newMessage()
{
return new FragmentHandle();
}
public Class<FragmentHandle> typeClass()
{
return FragmentHandle.class;
}
public String messageName()
{
return FragmentHandle.class.getSimpleName();
}
public String messageFullName()
{
return FragmentHandle.class.getName();
}
public boolean isInitialized(FragmentHandle message)
{
return true;
}
public void mergeFrom(Input input, FragmentHandle message) throws IOException
{
for(int number = input.readFieldNumber(this);; number = input.readFieldNumber(this))
{
switch(number)
{
case 0:
return;
case 1:
message.queryId = input.mergeObject(message.queryId, QueryId.getSchema());
break;
case 2:
message.majorFragmentId = input.readInt32();
break;
case 3:
message.minorFragmentId = input.readInt32();
break;
case 4:
message.parentQueryId = input.mergeObject(message.parentQueryId, QueryId.getSchema());
break;
default:
input.handleUnknownField(number, this);
}
}
}
public void writeTo(Output output, FragmentHandle message) throws IOException
{
if(message.queryId != null)
output.writeObject(1, message.queryId, QueryId.getSchema(), false);
if(message.majorFragmentId != 0)
output.writeInt32(2, message.majorFragmentId, false);
if(message.minorFragmentId != 0)
output.writeInt32(3, message.minorFragmentId, false);
if(message.parentQueryId != null)
output.writeObject(4, message.parentQueryId, QueryId.getSchema(), false);
}
public String getFieldName(int number)
{
switch(number)
{
case 1: return "queryId";
case 2: return "majorFragmentId";
case 3: return "minorFragmentId";
case 4: return "parentQueryId";
default: return null;
}
}
public int getFieldNumber(String name)
{
final Integer number = __fieldMap.get(name);
return number == null ? 0 : number.intValue();
}
private static final java.util.HashMap<String,Integer> __fieldMap = new java.util.HashMap<String,Integer>();
static
{
__fieldMap.put("queryId", 1);
__fieldMap.put("majorFragmentId", 2);
__fieldMap.put("minorFragmentId", 3);
__fieldMap.put("parentQueryId", 4);
}
}
|
/**
* 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.yarn.server.nodemanager.containermanager.localizer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyShort;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Future;
import org.apache.hadoop.fs.Options;
import org.junit.Assert;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.AbstractFileSystem;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FSError;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Options.ChecksumOpt;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.UnsupportedFileSystemException;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.Server;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.LocalResource;
import org.apache.hadoop.yarn.api.records.LocalResourceType;
import org.apache.hadoop.yarn.api.records.LocalResourceVisibility;
import org.apache.hadoop.yarn.api.records.SerializedException;
import org.apache.hadoop.yarn.api.records.URL;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.event.AsyncDispatcher;
import org.apache.hadoop.yarn.event.Dispatcher;
import org.apache.hadoop.yarn.event.DrainDispatcher;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor;
import org.apache.hadoop.yarn.server.nodemanager.DeletionService;
import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService;
import org.apache.hadoop.yarn.server.nodemanager.NodeManager.NMContext;
import org.apache.hadoop.yarn.server.nodemanager.api.ResourceLocalizationSpec;
import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalResourceStatus;
import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerAction;
import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerHeartbeatResponse;
import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerStatus;
import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.ResourceStatusType;
import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.impl.pb.LocalResourceStatusPBImpl;
import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.impl.pb.LocalizerStatusPBImpl;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEventType;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationImpl;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerEventType;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerImpl;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerResourceFailedEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ResourceLocalizationService.LocalizerRunner;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ResourceLocalizationService.LocalizerTracker;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ResourceLocalizationService.PublicLocalizer;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ApplicationLocalizationEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ContainerLocalizationCleanupEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ContainerLocalizationEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ContainerLocalizationRequestEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizationEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizationEventType;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizerEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizerEventType;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizerResourceRequestEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceFailedLocalizationEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceLocalizedEvent;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMMemoryStateStoreService;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMNullStateStoreService;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
import org.apache.hadoop.yarn.server.nodemanager.security.NMContainerTokenSecretManager;
import org.apache.hadoop.yarn.server.nodemanager.security.NMTokenSecretManagerInNM;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.apache.hadoop.yarn.util.ConverterUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class TestResourceLocalizationService {
static final Path basedir =
new Path("target", TestResourceLocalizationService.class.getName());
static Server mockServer;
private Configuration conf;
private AbstractFileSystem spylfs;
private FileContext lfs;
private NMContext nmContext;
@BeforeClass
public static void setupClass() {
mockServer = mock(Server.class);
doReturn(new InetSocketAddress(123)).when(mockServer).getListenerAddress();
}
@Before
public void setup() throws IOException {
conf = new Configuration();
spylfs = spy(FileContext.getLocalFSFileContext().getDefaultFileSystem());
lfs = FileContext.getFileContext(spylfs, conf);
String logDir = lfs.makeQualified(new Path(basedir, "logdir ")).toString();
conf.set(YarnConfiguration.NM_LOG_DIRS, logDir);
nmContext = new NMContext(new NMContainerTokenSecretManager(
conf), new NMTokenSecretManagerInNM(), null,
new ApplicationACLsManager(conf), new NMNullStateStoreService());
}
@After
public void cleanup() throws IOException {
conf = null;
FileUtils.deleteDirectory(new File(basedir.toString()));
}
@Test
public void testLocalizationInit() throws Exception {
conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077");
AsyncDispatcher dispatcher = new AsyncDispatcher();
dispatcher.init(new Configuration());
ContainerExecutor exec = mock(ContainerExecutor.class);
DeletionService delService = spy(new DeletionService(exec));
delService.init(conf);
delService.start();
List<Path> localDirs = new ArrayList<Path>();
String[] sDirs = new String[4];
for (int i = 0; i < 4; ++i) {
localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
sDirs[i] = localDirs.get(i).toString();
}
conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
LocalDirsHandlerService diskhandler = new LocalDirsHandlerService();
diskhandler.init(conf);
ResourceLocalizationService locService =
spy(new ResourceLocalizationService(dispatcher, exec, delService,
diskhandler, nmContext));
doReturn(lfs)
.when(locService).getLocalFileContext(isA(Configuration.class));
try {
dispatcher.start();
// initialize ResourceLocalizationService
locService.init(conf);
final FsPermission defaultPerm = new FsPermission((short)0755);
// verify directory creation
for (Path p : localDirs) {
p = new Path((new URI(p.toString())).getPath());
Path usercache = new Path(p, ContainerLocalizer.USERCACHE);
verify(spylfs)
.mkdir(eq(usercache),
eq(defaultPerm), eq(true));
Path publicCache = new Path(p, ContainerLocalizer.FILECACHE);
verify(spylfs)
.mkdir(eq(publicCache),
eq(defaultPerm), eq(true));
Path nmPriv = new Path(p, ResourceLocalizationService.NM_PRIVATE_DIR);
verify(spylfs).mkdir(eq(nmPriv),
eq(ResourceLocalizationService.NM_PRIVATE_PERM), eq(true));
}
} finally {
dispatcher.stop();
delService.stop();
}
}
@Test
public void testDirectoryCleanupOnNewlyCreatedStateStore()
throws IOException, URISyntaxException {
conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077");
AsyncDispatcher dispatcher = new AsyncDispatcher();
dispatcher.init(new Configuration());
ContainerExecutor exec = mock(ContainerExecutor.class);
DeletionService delService = spy(new DeletionService(exec));
delService.init(conf);
delService.start();
List<Path> localDirs = new ArrayList<Path>();
String[] sDirs = new String[4];
for (int i = 0; i < 4; ++i) {
localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
sDirs[i] = localDirs.get(i).toString();
}
conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
LocalDirsHandlerService diskhandler = new LocalDirsHandlerService();
diskhandler.init(conf);
NMStateStoreService nmStateStoreService = mock(NMStateStoreService.class);
when(nmStateStoreService.canRecover()).thenReturn(true);
when(nmStateStoreService.isNewlyCreated()).thenReturn(true);
ResourceLocalizationService locService =
spy(new ResourceLocalizationService(dispatcher, exec, delService,
diskhandler,nmContext));
doReturn(lfs)
.when(locService).getLocalFileContext(isA(Configuration.class));
try {
dispatcher.start();
// initialize ResourceLocalizationService
locService.init(conf);
final FsPermission defaultPerm = new FsPermission((short)0755);
// verify directory creation
for (Path p : localDirs) {
p = new Path((new URI(p.toString())).getPath());
Path usercache = new Path(p, ContainerLocalizer.USERCACHE);
verify(spylfs)
.rename(eq(usercache), any(Path.class), any(Options.Rename.class));
verify(spylfs)
.mkdir(eq(usercache),
eq(defaultPerm), eq(true));
Path publicCache = new Path(p, ContainerLocalizer.FILECACHE);
verify(spylfs)
.rename(eq(usercache), any(Path.class), any(Options.Rename.class));
verify(spylfs)
.mkdir(eq(publicCache),
eq(defaultPerm), eq(true));
Path nmPriv = new Path(p, ResourceLocalizationService.NM_PRIVATE_DIR);
verify(spylfs)
.rename(eq(usercache), any(Path.class), any(Options.Rename.class));
verify(spylfs).mkdir(eq(nmPriv),
eq(ResourceLocalizationService.NM_PRIVATE_PERM), eq(true));
}
} finally {
dispatcher.stop();
delService.stop();
}
}
@Test
@SuppressWarnings("unchecked") // mocked generics
public void testResourceRelease() throws Exception {
List<Path> localDirs = new ArrayList<Path>();
String[] sDirs = new String[4];
for (int i = 0; i < 4; ++i) {
localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
sDirs[i] = localDirs.get(i).toString();
}
conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
LocalizerTracker mockLocallilzerTracker = mock(LocalizerTracker.class);
DrainDispatcher dispatcher = new DrainDispatcher();
dispatcher.init(conf);
dispatcher.start();
EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
dispatcher.register(ApplicationEventType.class, applicationBus);
EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
dispatcher.register(ContainerEventType.class, containerBus);
//Ignore actual localization
EventHandler<LocalizerEvent> localizerBus = mock(EventHandler.class);
dispatcher.register(LocalizerEventType.class, localizerBus);
ContainerExecutor exec = mock(ContainerExecutor.class);
LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
dirsHandler.init(conf);
DeletionService delService = new DeletionService(exec);
delService.init(new Configuration());
delService.start();
ResourceLocalizationService rawService =
new ResourceLocalizationService(dispatcher, exec, delService,
dirsHandler, nmContext);
ResourceLocalizationService spyService = spy(rawService);
doReturn(mockServer).when(spyService).createServer();
doReturn(mockLocallilzerTracker).when(spyService).createLocalizerTracker(
isA(Configuration.class));
doReturn(lfs).when(spyService)
.getLocalFileContext(isA(Configuration.class));
try {
spyService.init(conf);
spyService.start();
final String user = "user0";
// init application
final Application app = mock(Application.class);
final ApplicationId appId =
BuilderUtils.newApplicationId(314159265358979L, 3);
when(app.getUser()).thenReturn(user);
when(app.getAppId()).thenReturn(appId);
spyService.handle(new ApplicationLocalizationEvent(
LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
dispatcher.await();
//Get a handle on the trackers after they're setup with INIT_APP_RESOURCES
LocalResourcesTracker appTracker =
spyService.getLocalResourcesTracker(
LocalResourceVisibility.APPLICATION, user, appId);
LocalResourcesTracker privTracker =
spyService.getLocalResourcesTracker(LocalResourceVisibility.PRIVATE,
user, appId);
LocalResourcesTracker pubTracker =
spyService.getLocalResourcesTracker(LocalResourceVisibility.PUBLIC,
user, appId);
// init container.
final Container c = getMockContainer(appId, 42, user);
// init resources
Random r = new Random();
long seed = r.nextLong();
System.out.println("SEED: " + seed);
r.setSeed(seed);
// Send localization requests for one resource of each type.
final LocalResource privResource = getPrivateMockedResource(r);
final LocalResourceRequest privReq =
new LocalResourceRequest(privResource);
final LocalResource pubResource = getPublicMockedResource(r);
final LocalResourceRequest pubReq = new LocalResourceRequest(pubResource);
final LocalResource pubResource2 = getPublicMockedResource(r);
final LocalResourceRequest pubReq2 =
new LocalResourceRequest(pubResource2);
final LocalResource appResource = getAppMockedResource(r);
final LocalResourceRequest appReq = new LocalResourceRequest(appResource);
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req =
new HashMap<LocalResourceVisibility,
Collection<LocalResourceRequest>>();
req.put(LocalResourceVisibility.PRIVATE,
Collections.singletonList(privReq));
req.put(LocalResourceVisibility.PUBLIC,
Collections.singletonList(pubReq));
req.put(LocalResourceVisibility.APPLICATION,
Collections.singletonList(appReq));
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req2 =
new HashMap<LocalResourceVisibility,
Collection<LocalResourceRequest>>();
req2.put(LocalResourceVisibility.PRIVATE,
Collections.singletonList(privReq));
req2.put(LocalResourceVisibility.PUBLIC,
Collections.singletonList(pubReq2));
Set<LocalResourceRequest> pubRsrcs = new HashSet<LocalResourceRequest>();
pubRsrcs.add(pubReq);
pubRsrcs.add(pubReq2);
// Send Request event
spyService.handle(new ContainerLocalizationRequestEvent(c, req));
spyService.handle(new ContainerLocalizationRequestEvent(c, req2));
dispatcher.await();
int privRsrcCount = 0;
for (LocalizedResource lr : privTracker) {
privRsrcCount++;
Assert.assertEquals("Incorrect reference count", 2, lr.getRefCount());
Assert.assertEquals(privReq, lr.getRequest());
}
Assert.assertEquals(1, privRsrcCount);
int pubRsrcCount = 0;
for (LocalizedResource lr : pubTracker) {
pubRsrcCount++;
Assert.assertEquals("Incorrect reference count", 1, lr.getRefCount());
pubRsrcs.remove(lr.getRequest());
}
Assert.assertEquals(0, pubRsrcs.size());
Assert.assertEquals(2, pubRsrcCount);
int appRsrcCount = 0;
for (LocalizedResource lr : appTracker) {
appRsrcCount++;
Assert.assertEquals("Incorrect reference count", 1, lr.getRefCount());
Assert.assertEquals(appReq, lr.getRequest());
}
Assert.assertEquals(1, appRsrcCount);
//Send Cleanup Event
spyService.handle(new ContainerLocalizationCleanupEvent(c, req));
verify(mockLocallilzerTracker)
.cleanupPrivLocalizers("container_314159265358979_0003_01_000042");
req2.remove(LocalResourceVisibility.PRIVATE);
spyService.handle(new ContainerLocalizationCleanupEvent(c, req2));
dispatcher.await();
pubRsrcs.add(pubReq);
pubRsrcs.add(pubReq2);
privRsrcCount = 0;
for (LocalizedResource lr : privTracker) {
privRsrcCount++;
Assert.assertEquals("Incorrect reference count", 1, lr.getRefCount());
Assert.assertEquals(privReq, lr.getRequest());
}
Assert.assertEquals(1, privRsrcCount);
pubRsrcCount = 0;
for (LocalizedResource lr : pubTracker) {
pubRsrcCount++;
Assert.assertEquals("Incorrect reference count", 0, lr.getRefCount());
pubRsrcs.remove(lr.getRequest());
}
Assert.assertEquals(0, pubRsrcs.size());
Assert.assertEquals(2, pubRsrcCount);
appRsrcCount = 0;
for (LocalizedResource lr : appTracker) {
appRsrcCount++;
Assert.assertEquals("Incorrect reference count", 0, lr.getRefCount());
Assert.assertEquals(appReq, lr.getRequest());
}
Assert.assertEquals(1, appRsrcCount);
} finally {
dispatcher.stop();
delService.stop();
}
}
@Test
@SuppressWarnings("unchecked") // mocked generics
public void testRecovery() throws Exception {
final String user1 = "user1";
final String user2 = "user2";
final ApplicationId appId1 = ApplicationId.newInstance(1, 1);
final ApplicationId appId2 = ApplicationId.newInstance(1, 2);
List<Path> localDirs = new ArrayList<Path>();
String[] sDirs = new String[4];
for (int i = 0; i < 4; ++i) {
localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
sDirs[i] = localDirs.get(i).toString();
}
conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
conf.setBoolean(YarnConfiguration.NM_RECOVERY_ENABLED, true);
NMMemoryStateStoreService stateStore = new NMMemoryStateStoreService();
stateStore.init(conf);
stateStore.start();
DrainDispatcher dispatcher = new DrainDispatcher();
dispatcher.init(conf);
dispatcher.start();
EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
dispatcher.register(ApplicationEventType.class, applicationBus);
EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
dispatcher.register(ContainerEventType.class, containerBus);
//Ignore actual localization
EventHandler<LocalizerEvent> localizerBus = mock(EventHandler.class);
dispatcher.register(LocalizerEventType.class, localizerBus);
LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
dirsHandler.init(conf);
ResourceLocalizationService spyService =
createSpyService(dispatcher, dirsHandler, stateStore);
try {
spyService.init(conf);
spyService.start();
final Application app1 = mock(Application.class);
when(app1.getUser()).thenReturn(user1);
when(app1.getAppId()).thenReturn(appId1);
final Application app2 = mock(Application.class);
when(app2.getUser()).thenReturn(user2);
when(app2.getAppId()).thenReturn(appId2);
spyService.handle(new ApplicationLocalizationEvent(
LocalizationEventType.INIT_APPLICATION_RESOURCES, app1));
spyService.handle(new ApplicationLocalizationEvent(
LocalizationEventType.INIT_APPLICATION_RESOURCES, app2));
dispatcher.await();
//Get a handle on the trackers after they're setup with INIT_APP_RESOURCES
LocalResourcesTracker appTracker1 =
spyService.getLocalResourcesTracker(
LocalResourceVisibility.APPLICATION, user1, appId1);
LocalResourcesTracker privTracker1 =
spyService.getLocalResourcesTracker(LocalResourceVisibility.PRIVATE,
user1, null);
LocalResourcesTracker appTracker2 =
spyService.getLocalResourcesTracker(
LocalResourceVisibility.APPLICATION, user2, appId2);
LocalResourcesTracker pubTracker =
spyService.getLocalResourcesTracker(LocalResourceVisibility.PUBLIC,
null, null);
// init containers
final Container c1 = getMockContainer(appId1, 1, user1);
final Container c2 = getMockContainer(appId2, 2, user2);
// init resources
Random r = new Random();
long seed = r.nextLong();
System.out.println("SEED: " + seed);
r.setSeed(seed);
// Send localization requests of each type.
final LocalResource privResource1 = getPrivateMockedResource(r);
final LocalResourceRequest privReq1 =
new LocalResourceRequest(privResource1);
final LocalResource privResource2 = getPrivateMockedResource(r);
final LocalResourceRequest privReq2 =
new LocalResourceRequest(privResource2);
final LocalResource pubResource1 = getPublicMockedResource(r);
final LocalResourceRequest pubReq1 =
new LocalResourceRequest(pubResource1);
final LocalResource pubResource2 = getPublicMockedResource(r);
final LocalResourceRequest pubReq2 =
new LocalResourceRequest(pubResource2);
final LocalResource appResource1 = getAppMockedResource(r);
final LocalResourceRequest appReq1 =
new LocalResourceRequest(appResource1);
final LocalResource appResource2 = getAppMockedResource(r);
final LocalResourceRequest appReq2 =
new LocalResourceRequest(appResource2);
final LocalResource appResource3 = getAppMockedResource(r);
final LocalResourceRequest appReq3 =
new LocalResourceRequest(appResource3);
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req1 =
new HashMap<LocalResourceVisibility,
Collection<LocalResourceRequest>>();
req1.put(LocalResourceVisibility.PRIVATE,
Arrays.asList(new LocalResourceRequest[] { privReq1, privReq2 }));
req1.put(LocalResourceVisibility.PUBLIC,
Collections.singletonList(pubReq1));
req1.put(LocalResourceVisibility.APPLICATION,
Collections.singletonList(appReq1));
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req2 =
new HashMap<LocalResourceVisibility,
Collection<LocalResourceRequest>>();
req2.put(LocalResourceVisibility.APPLICATION,
Arrays.asList(new LocalResourceRequest[] { appReq2, appReq3 }));
req2.put(LocalResourceVisibility.PUBLIC,
Collections.singletonList(pubReq2));
// Send Request event
spyService.handle(new ContainerLocalizationRequestEvent(c1, req1));
spyService.handle(new ContainerLocalizationRequestEvent(c2, req2));
dispatcher.await();
// Simulate start of localization for all resources
privTracker1.getPathForLocalization(privReq1,
dirsHandler.getLocalPathForWrite(
ContainerLocalizer.USERCACHE + user1));
privTracker1.getPathForLocalization(privReq2,
dirsHandler.getLocalPathForWrite(
ContainerLocalizer.USERCACHE + user1));
LocalizedResource privLr1 = privTracker1.getLocalizedResource(privReq1);
LocalizedResource privLr2 = privTracker1.getLocalizedResource(privReq2);
appTracker1.getPathForLocalization(appReq1,
dirsHandler.getLocalPathForWrite(
ContainerLocalizer.APPCACHE + appId1));
LocalizedResource appLr1 = appTracker1.getLocalizedResource(appReq1);
appTracker2.getPathForLocalization(appReq2,
dirsHandler.getLocalPathForWrite(
ContainerLocalizer.APPCACHE + appId2));
LocalizedResource appLr2 = appTracker2.getLocalizedResource(appReq2);
appTracker2.getPathForLocalization(appReq3,
dirsHandler.getLocalPathForWrite(
ContainerLocalizer.APPCACHE + appId2));
LocalizedResource appLr3 = appTracker2.getLocalizedResource(appReq3);
pubTracker.getPathForLocalization(pubReq1,
dirsHandler.getLocalPathForWrite(ContainerLocalizer.FILECACHE));
LocalizedResource pubLr1 = pubTracker.getLocalizedResource(pubReq1);
pubTracker.getPathForLocalization(pubReq2,
dirsHandler.getLocalPathForWrite(ContainerLocalizer.FILECACHE));
LocalizedResource pubLr2 = pubTracker.getLocalizedResource(pubReq2);
// Simulate completion of localization for most resources with
// possibly different sizes than in the request
assertNotNull("Localization not started", privLr1.getLocalPath());
privTracker1.handle(new ResourceLocalizedEvent(privReq1,
privLr1.getLocalPath(), privLr1.getSize() + 5));
assertNotNull("Localization not started", privLr2.getLocalPath());
privTracker1.handle(new ResourceLocalizedEvent(privReq2,
privLr2.getLocalPath(), privLr2.getSize() + 10));
assertNotNull("Localization not started", appLr1.getLocalPath());
appTracker1.handle(new ResourceLocalizedEvent(appReq1,
appLr1.getLocalPath(), appLr1.getSize()));
assertNotNull("Localization not started", appLr3.getLocalPath());
appTracker2.handle(new ResourceLocalizedEvent(appReq3,
appLr3.getLocalPath(), appLr3.getSize() + 7));
assertNotNull("Localization not started", pubLr1.getLocalPath());
pubTracker.handle(new ResourceLocalizedEvent(pubReq1,
pubLr1.getLocalPath(), pubLr1.getSize() + 1000));
assertNotNull("Localization not started", pubLr2.getLocalPath());
pubTracker.handle(new ResourceLocalizedEvent(pubReq2,
pubLr2.getLocalPath(), pubLr2.getSize() + 99999));
dispatcher.await();
assertEquals(ResourceState.LOCALIZED, privLr1.getState());
assertEquals(ResourceState.LOCALIZED, privLr2.getState());
assertEquals(ResourceState.LOCALIZED, appLr1.getState());
assertEquals(ResourceState.DOWNLOADING, appLr2.getState());
assertEquals(ResourceState.LOCALIZED, appLr3.getState());
assertEquals(ResourceState.LOCALIZED, pubLr1.getState());
assertEquals(ResourceState.LOCALIZED, pubLr2.getState());
// restart and recover
spyService = createSpyService(dispatcher, dirsHandler, stateStore);
spyService.init(conf);
spyService.recoverLocalizedResources(
stateStore.loadLocalizationState());
dispatcher.await();
appTracker1 = spyService.getLocalResourcesTracker(
LocalResourceVisibility.APPLICATION, user1, appId1);
privTracker1 = spyService.getLocalResourcesTracker(
LocalResourceVisibility.PRIVATE, user1, null);
appTracker2 = spyService.getLocalResourcesTracker(
LocalResourceVisibility.APPLICATION, user2, appId2);
pubTracker = spyService.getLocalResourcesTracker(
LocalResourceVisibility.PUBLIC, null, null);
LocalizedResource recoveredRsrc =
privTracker1.getLocalizedResource(privReq1);
assertEquals(privReq1, recoveredRsrc.getRequest());
assertEquals(privLr1.getLocalPath(), recoveredRsrc.getLocalPath());
assertEquals(privLr1.getSize(), recoveredRsrc.getSize());
assertEquals(ResourceState.LOCALIZED, recoveredRsrc.getState());
recoveredRsrc = privTracker1.getLocalizedResource(privReq2);
assertEquals(privReq2, recoveredRsrc.getRequest());
assertEquals(privLr2.getLocalPath(), recoveredRsrc.getLocalPath());
assertEquals(privLr2.getSize(), recoveredRsrc.getSize());
assertEquals(ResourceState.LOCALIZED, recoveredRsrc.getState());
recoveredRsrc = appTracker1.getLocalizedResource(appReq1);
assertEquals(appReq1, recoveredRsrc.getRequest());
assertEquals(appLr1.getLocalPath(), recoveredRsrc.getLocalPath());
assertEquals(appLr1.getSize(), recoveredRsrc.getSize());
assertEquals(ResourceState.LOCALIZED, recoveredRsrc.getState());
recoveredRsrc = appTracker2.getLocalizedResource(appReq2);
assertNull("in-progress resource should not be present", recoveredRsrc);
recoveredRsrc = appTracker2.getLocalizedResource(appReq3);
assertEquals(appReq3, recoveredRsrc.getRequest());
assertEquals(appLr3.getLocalPath(), recoveredRsrc.getLocalPath());
assertEquals(appLr3.getSize(), recoveredRsrc.getSize());
assertEquals(ResourceState.LOCALIZED, recoveredRsrc.getState());
} finally {
dispatcher.stop();
stateStore.close();
}
}
@Test( timeout = 10000)
@SuppressWarnings("unchecked") // mocked generics
public void testLocalizerRunnerException() throws Exception {
DrainDispatcher dispatcher = new DrainDispatcher();
dispatcher.init(conf);
dispatcher.start();
EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
dispatcher.register(ApplicationEventType.class, applicationBus);
EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
dispatcher.register(ContainerEventType.class, containerBus);
ContainerExecutor exec = mock(ContainerExecutor.class);
LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
LocalDirsHandlerService dirsHandlerSpy = spy(dirsHandler);
dirsHandlerSpy.init(conf);
DeletionService delServiceReal = new DeletionService(exec);
DeletionService delService = spy(delServiceReal);
delService.init(new Configuration());
delService.start();
ResourceLocalizationService rawService =
new ResourceLocalizationService(dispatcher, exec, delService,
dirsHandlerSpy, nmContext);
ResourceLocalizationService spyService = spy(rawService);
doReturn(mockServer).when(spyService).createServer();
try {
spyService.init(conf);
spyService.start();
// init application
final Application app = mock(Application.class);
final ApplicationId appId =
BuilderUtils.newApplicationId(314159265358979L, 3);
when(app.getUser()).thenReturn("user0");
when(app.getAppId()).thenReturn(appId);
spyService.handle(new ApplicationLocalizationEvent(
LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
dispatcher.await();
Random r = new Random();
long seed = r.nextLong();
System.out.println("SEED: " + seed);
r.setSeed(seed);
final Container c = getMockContainer(appId, 42, "user0");
final LocalResource resource1 = getPrivateMockedResource(r);
System.out.println("Here 4");
final LocalResourceRequest req1 = new LocalResourceRequest(resource1);
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> rsrcs =
new HashMap<LocalResourceVisibility,
Collection<LocalResourceRequest>>();
List<LocalResourceRequest> privateResourceList =
new ArrayList<LocalResourceRequest>();
privateResourceList.add(req1);
rsrcs.put(LocalResourceVisibility.PRIVATE, privateResourceList);
final Constructor<?>[] constructors =
FSError.class.getDeclaredConstructors();
constructors[0].setAccessible(true);
FSError fsError =
(FSError) constructors[0].newInstance(new IOException("Disk Error"));
Mockito
.doThrow(fsError)
.when(dirsHandlerSpy)
.getLocalPathForWrite(isA(String.class));
spyService.handle(new ContainerLocalizationRequestEvent(c, rsrcs));
Thread.sleep(1000);
dispatcher.await();
// Verify if ContainerResourceFailedEvent is invoked on FSError
verify(containerBus).handle(isA(ContainerResourceFailedEvent.class));
} finally {
spyService.stop();
dispatcher.stop();
delService.stop();
}
}
@Test( timeout = 10000)
@SuppressWarnings("unchecked") // mocked generics
public void testLocalizationHeartbeat() throws Exception {
List<Path> localDirs = new ArrayList<Path>();
String[] sDirs = new String[1];
// Making sure that we have only one local disk so that it will only be
// selected for consecutive resource localization calls. This is required
// to test LocalCacheDirectoryManager.
localDirs.add(lfs.makeQualified(new Path(basedir, 0 + "")));
sDirs[0] = localDirs.get(0).toString();
conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
// Adding configuration to make sure there is only one file per
// directory
conf.set(YarnConfiguration.NM_LOCAL_CACHE_MAX_FILES_PER_DIRECTORY, "37");
DrainDispatcher dispatcher = new DrainDispatcher();
dispatcher.init(conf);
dispatcher.start();
EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
dispatcher.register(ApplicationEventType.class, applicationBus);
EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
dispatcher.register(ContainerEventType.class, containerBus);
ContainerExecutor exec = mock(ContainerExecutor.class);
LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
dirsHandler.init(conf);
DeletionService delServiceReal = new DeletionService(exec);
DeletionService delService = spy(delServiceReal);
delService.init(new Configuration());
delService.start();
ResourceLocalizationService rawService =
new ResourceLocalizationService(dispatcher, exec, delService,
dirsHandler, nmContext);
ResourceLocalizationService spyService = spy(rawService);
doReturn(mockServer).when(spyService).createServer();
doReturn(lfs).when(spyService).getLocalFileContext(isA(Configuration.class));
FsPermission defaultPermission =
FsPermission.getDirDefault().applyUMask(lfs.getUMask());
FsPermission nmPermission =
ResourceLocalizationService.NM_PRIVATE_PERM.applyUMask(lfs.getUMask());
final Path userDir =
new Path(sDirs[0].substring("file:".length()),
ContainerLocalizer.USERCACHE);
final Path fileDir =
new Path(sDirs[0].substring("file:".length()),
ContainerLocalizer.FILECACHE);
final Path sysDir =
new Path(sDirs[0].substring("file:".length()),
ResourceLocalizationService.NM_PRIVATE_DIR);
final FileStatus fs =
new FileStatus(0, true, 1, 0, System.currentTimeMillis(), 0,
defaultPermission, "", "", new Path(sDirs[0]));
final FileStatus nmFs =
new FileStatus(0, true, 1, 0, System.currentTimeMillis(), 0,
nmPermission, "", "", sysDir);
doAnswer(new Answer<FileStatus>() {
@Override
public FileStatus answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
if (args.length > 0) {
if (args[0].equals(userDir) || args[0].equals(fileDir)) {
return fs;
}
}
return nmFs;
}
}).when(spylfs).getFileStatus(isA(Path.class));
try {
spyService.init(conf);
spyService.start();
// init application
final Application app = mock(Application.class);
final ApplicationId appId =
BuilderUtils.newApplicationId(314159265358979L, 3);
when(app.getUser()).thenReturn("user0");
when(app.getAppId()).thenReturn(appId);
spyService.handle(new ApplicationLocalizationEvent(
LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
ArgumentMatcher<ApplicationEvent> matchesAppInit =
new ArgumentMatcher<ApplicationEvent>() {
@Override
public boolean matches(Object o) {
ApplicationEvent evt = (ApplicationEvent) o;
return evt.getType() == ApplicationEventType.APPLICATION_INITED
&& appId == evt.getApplicationID();
}
};
dispatcher.await();
verify(applicationBus).handle(argThat(matchesAppInit));
// init container rsrc, localizer
Random r = new Random();
long seed = r.nextLong();
System.out.println("SEED: " + seed);
r.setSeed(seed);
final Container c = getMockContainer(appId, 42, "user0");
FSDataOutputStream out =
new FSDataOutputStream(new DataOutputBuffer(), null);
doReturn(out).when(spylfs).createInternal(isA(Path.class),
isA(EnumSet.class), isA(FsPermission.class), anyInt(), anyShort(),
anyLong(), isA(Progressable.class), isA(ChecksumOpt.class), anyBoolean());
final LocalResource resource1 = getPrivateMockedResource(r);
LocalResource resource2 = null;
do {
resource2 = getPrivateMockedResource(r);
} while (resource2 == null || resource2.equals(resource1));
LocalResource resource3 = null;
do {
resource3 = getPrivateMockedResource(r);
} while (resource3 == null || resource3.equals(resource1)
|| resource3.equals(resource2));
// above call to make sure we don't get identical resources.
final LocalResourceRequest req1 = new LocalResourceRequest(resource1);
final LocalResourceRequest req2 = new LocalResourceRequest(resource2);
final LocalResourceRequest req3 = new LocalResourceRequest(resource3);
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> rsrcs =
new HashMap<LocalResourceVisibility,
Collection<LocalResourceRequest>>();
List<LocalResourceRequest> privateResourceList =
new ArrayList<LocalResourceRequest>();
privateResourceList.add(req1);
privateResourceList.add(req2);
privateResourceList.add(req3);
rsrcs.put(LocalResourceVisibility.PRIVATE, privateResourceList);
spyService.handle(new ContainerLocalizationRequestEvent(c, rsrcs));
// Sigh. Thread init of private localizer not accessible
Thread.sleep(1000);
dispatcher.await();
String appStr = ConverterUtils.toString(appId);
String ctnrStr = c.getContainerId().toString();
ArgumentCaptor<Path> tokenPathCaptor = ArgumentCaptor.forClass(Path.class);
verify(exec).startLocalizer(tokenPathCaptor.capture(),
isA(InetSocketAddress.class), eq("user0"), eq(appStr), eq(ctnrStr),
isA(LocalDirsHandlerService.class));
Path localizationTokenPath = tokenPathCaptor.getValue();
// heartbeat from localizer
LocalResourceStatus rsrc1success = mock(LocalResourceStatus.class);
LocalResourceStatus rsrc2pending = mock(LocalResourceStatus.class);
LocalResourceStatus rsrc2success = mock(LocalResourceStatus.class);
LocalResourceStatus rsrc3success = mock(LocalResourceStatus.class);
LocalizerStatus stat = mock(LocalizerStatus.class);
when(stat.getLocalizerId()).thenReturn(ctnrStr);
when(rsrc1success.getResource()).thenReturn(resource1);
when(rsrc2pending.getResource()).thenReturn(resource2);
when(rsrc2success.getResource()).thenReturn(resource2);
when(rsrc3success.getResource()).thenReturn(resource3);
when(rsrc1success.getLocalSize()).thenReturn(4344L);
when(rsrc2success.getLocalSize()).thenReturn(2342L);
when(rsrc3success.getLocalSize()).thenReturn(5345L);
URL locPath = getPath("/cache/private/blah");
when(rsrc1success.getLocalPath()).thenReturn(locPath);
when(rsrc2success.getLocalPath()).thenReturn(locPath);
when(rsrc3success.getLocalPath()).thenReturn(locPath);
when(rsrc1success.getStatus()).thenReturn(ResourceStatusType.FETCH_SUCCESS);
when(rsrc2pending.getStatus()).thenReturn(ResourceStatusType.FETCH_PENDING);
when(rsrc2success.getStatus()).thenReturn(ResourceStatusType.FETCH_SUCCESS);
when(rsrc3success.getStatus()).thenReturn(ResourceStatusType.FETCH_SUCCESS);
// Four heartbeats with sending:
// 1 - empty
// 2 - resource1 FETCH_SUCCESS
// 3 - resource2 FETCH_PENDING
// 4 - resource2 FETCH_SUCCESS, resource3 FETCH_SUCCESS
List<LocalResourceStatus> rsrcs4 = new ArrayList<LocalResourceStatus>();
rsrcs4.add(rsrc2success);
rsrcs4.add(rsrc3success);
when(stat.getResources())
.thenReturn(Collections.<LocalResourceStatus>emptyList())
.thenReturn(Collections.singletonList(rsrc1success))
.thenReturn(Collections.singletonList(rsrc2pending))
.thenReturn(rsrcs4)
.thenReturn(Collections.<LocalResourceStatus>emptyList());
String localPath = Path.SEPARATOR + ContainerLocalizer.USERCACHE +
Path.SEPARATOR + "user0" + Path.SEPARATOR +
ContainerLocalizer.FILECACHE;
// First heartbeat
LocalizerHeartbeatResponse response = spyService.heartbeat(stat);
assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
assertEquals(1, response.getResourceSpecs().size());
assertEquals(req1,
new LocalResourceRequest(response.getResourceSpecs().get(0).getResource()));
URL localizedPath =
response.getResourceSpecs().get(0).getDestinationDirectory();
// Appending to local path unique number(10) generated as a part of
// LocalResourcesTracker
assertTrue(localizedPath.getFile().endsWith(
localPath + Path.SEPARATOR + "10"));
// Second heartbeat
response = spyService.heartbeat(stat);
assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
assertEquals(1, response.getResourceSpecs().size());
assertEquals(req2, new LocalResourceRequest(response.getResourceSpecs()
.get(0).getResource()));
localizedPath =
response.getResourceSpecs().get(0).getDestinationDirectory();
// Resource's destination path should be now inside sub directory 0 as
// LocalCacheDirectoryManager will be used and we have restricted number
// of files per directory to 1.
assertTrue(localizedPath.getFile().endsWith(
localPath + Path.SEPARATOR + "0" + Path.SEPARATOR + "11"));
// Third heartbeat
response = spyService.heartbeat(stat);
assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
assertEquals(1, response.getResourceSpecs().size());
assertEquals(req3, new LocalResourceRequest(response.getResourceSpecs()
.get(0).getResource()));
localizedPath =
response.getResourceSpecs().get(0).getDestinationDirectory();
assertTrue(localizedPath.getFile().endsWith(
localPath + Path.SEPARATOR + "1" + Path.SEPARATOR + "12"));
response = spyService.heartbeat(stat);
assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
spyService.handle(new ContainerLocalizationEvent(
LocalizationEventType.CONTAINER_RESOURCES_LOCALIZED, c));
// get shutdown after receive CONTAINER_RESOURCES_LOCALIZED event
response = spyService.heartbeat(stat);
assertEquals(LocalizerAction.DIE, response.getLocalizerAction());
dispatcher.await();
// verify container notification
ArgumentMatcher<ContainerEvent> matchesContainerLoc =
new ArgumentMatcher<ContainerEvent>() {
@Override
public boolean matches(Object o) {
ContainerEvent evt = (ContainerEvent) o;
return evt.getType() == ContainerEventType.RESOURCE_LOCALIZED
&& c.getContainerId() == evt.getContainerID();
}
};
// total 3 resource localzation calls. one for each resource.
verify(containerBus, times(3)).handle(argThat(matchesContainerLoc));
// Verify deletion of localization token.
verify(delService).delete((String)isNull(), eq(localizationTokenPath));
} finally {
spyService.stop();
dispatcher.stop();
delService.stop();
}
}
@Test
@SuppressWarnings("unchecked")
public void testPublicResourceInitializesLocalDir() throws Exception {
// Setup state to simulate restart NM with existing state meaning no
// directory creation during initialization
NMStateStoreService spyStateStore = spy(nmContext.getNMStateStore());
when(spyStateStore.canRecover()).thenReturn(true);
NMContext spyContext = spy(nmContext);
when(spyContext.getNMStateStore()).thenReturn(spyStateStore);
List<Path> localDirs = new ArrayList<Path>();
String[] sDirs = new String[4];
for (int i = 0; i < 4; ++i) {
localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
sDirs[i] = localDirs.get(i).toString();
}
conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
DrainDispatcher dispatcher = new DrainDispatcher();
EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
dispatcher.register(ApplicationEventType.class, applicationBus);
EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
dispatcher.register(ContainerEventType.class, containerBus);
ContainerExecutor exec = mock(ContainerExecutor.class);
DeletionService delService = mock(DeletionService.class);
LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
dirsHandler.init(conf);
dispatcher.init(conf);
dispatcher.start();
try {
ResourceLocalizationService rawService =
new ResourceLocalizationService(dispatcher, exec, delService,
dirsHandler, spyContext);
ResourceLocalizationService spyService = spy(rawService);
doReturn(mockServer).when(spyService).createServer();
doReturn(lfs).when(spyService).getLocalFileContext(
isA(Configuration.class));
spyService.init(conf);
final FsPermission defaultPerm = new FsPermission((short)0755);
// verify directory is not created at initialization
for (Path p : localDirs) {
p = new Path((new URI(p.toString())).getPath());
Path publicCache = new Path(p, ContainerLocalizer.FILECACHE);
verify(spylfs, never())
.mkdir(eq(publicCache),eq(defaultPerm), eq(true));
}
spyService.start();
final String user = "user0";
// init application
final Application app = mock(Application.class);
final ApplicationId appId =
BuilderUtils.newApplicationId(314159265358979L, 3);
when(app.getUser()).thenReturn(user);
when(app.getAppId()).thenReturn(appId);
spyService.handle(new ApplicationLocalizationEvent(
LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
dispatcher.await();
// init container.
final Container c = getMockContainer(appId, 42, user);
// init resources
Random r = new Random();
long seed = r.nextLong();
System.out.println("SEED: " + seed);
r.setSeed(seed);
// Queue up public resource localization
final LocalResource pubResource1 = getPublicMockedResource(r);
final LocalResourceRequest pubReq1 =
new LocalResourceRequest(pubResource1);
LocalResource pubResource2 = null;
do {
pubResource2 = getPublicMockedResource(r);
} while (pubResource2 == null || pubResource2.equals(pubResource1));
// above call to make sure we don't get identical resources.
final LocalResourceRequest pubReq2 =
new LocalResourceRequest(pubResource2);
Set<LocalResourceRequest> pubRsrcs = new HashSet<LocalResourceRequest>();
pubRsrcs.add(pubReq1);
pubRsrcs.add(pubReq2);
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req =
new HashMap<LocalResourceVisibility,
Collection<LocalResourceRequest>>();
req.put(LocalResourceVisibility.PUBLIC, pubRsrcs);
spyService.handle(new ContainerLocalizationRequestEvent(c, req));
dispatcher.await();
verify(spyService, times(1)).checkAndInitializeLocalDirs();
// verify directory creation
for (Path p : localDirs) {
p = new Path((new URI(p.toString())).getPath());
Path publicCache = new Path(p, ContainerLocalizer.FILECACHE);
verify(spylfs).mkdir(eq(publicCache),eq(defaultPerm), eq(true));
}
} finally {
dispatcher.stop();
}
}
@Test(timeout=20000)
@SuppressWarnings("unchecked") // mocked generics
public void testFailedPublicResource() throws Exception {
List<Path> localDirs = new ArrayList<Path>();
String[] sDirs = new String[4];
for (int i = 0; i < 4; ++i) {
localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
sDirs[i] = localDirs.get(i).toString();
}
conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
DrainDispatcher dispatcher = new DrainDispatcher();
EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
dispatcher.register(ApplicationEventType.class, applicationBus);
EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
dispatcher.register(ContainerEventType.class, containerBus);
ContainerExecutor exec = mock(ContainerExecutor.class);
DeletionService delService = mock(DeletionService.class);
LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
dirsHandler.init(conf);
dispatcher.init(conf);
dispatcher.start();
try {
ResourceLocalizationService rawService =
new ResourceLocalizationService(dispatcher, exec, delService,
dirsHandler, nmContext);
ResourceLocalizationService spyService = spy(rawService);
doReturn(mockServer).when(spyService).createServer();
doReturn(lfs).when(spyService).getLocalFileContext(
isA(Configuration.class));
spyService.init(conf);
spyService.start();
final String user = "user0";
// init application
final Application app = mock(Application.class);
final ApplicationId appId =
BuilderUtils.newApplicationId(314159265358979L, 3);
when(app.getUser()).thenReturn(user);
when(app.getAppId()).thenReturn(appId);
spyService.handle(new ApplicationLocalizationEvent(
LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
dispatcher.await();
// init container.
final Container c = getMockContainer(appId, 42, user);
// init resources
Random r = new Random();
long seed = r.nextLong();
System.out.println("SEED: " + seed);
r.setSeed(seed);
// cause chmod to fail after a delay
final CyclicBarrier barrier = new CyclicBarrier(2);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) throws IOException {
try {
barrier.await();
} catch (InterruptedException e) {
} catch (BrokenBarrierException e) {
}
throw new IOException("forced failure");
}
}).when(spylfs)
.setPermission(isA(Path.class), isA(FsPermission.class));
// Queue up two localization requests for the same public resource
final LocalResource pubResource = getPublicMockedResource(r);
final LocalResourceRequest pubReq = new LocalResourceRequest(pubResource);
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req =
new HashMap<LocalResourceVisibility,
Collection<LocalResourceRequest>>();
req.put(LocalResourceVisibility.PUBLIC,
Collections.singletonList(pubReq));
Set<LocalResourceRequest> pubRsrcs = new HashSet<LocalResourceRequest>();
pubRsrcs.add(pubReq);
spyService.handle(new ContainerLocalizationRequestEvent(c, req));
spyService.handle(new ContainerLocalizationRequestEvent(c, req));
dispatcher.await();
// allow the chmod to fail now that both requests have been queued
barrier.await();
verify(containerBus, timeout(5000).times(2))
.handle(isA(ContainerResourceFailedEvent.class));
} finally {
dispatcher.stop();
}
}
/*
* Test case for handling RejectedExecutionException and IOException which can
* be thrown when adding public resources to the pending queue.
* RejectedExecutionException can be thrown either due to the incoming queue
* being full or if the ExecutorCompletionService threadpool is shutdown.
* Since it's hard to simulate the queue being full, this test just shuts down
* the threadpool and makes sure the exception is handled. If anything is
* messed up the async dispatcher thread will cause a system exit causing the
* test to fail.
*/
@Test
@SuppressWarnings("unchecked")
public void testPublicResourceAddResourceExceptions() throws Exception {
List<Path> localDirs = new ArrayList<Path>();
String[] sDirs = new String[4];
for (int i = 0; i < 4; ++i) {
localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
sDirs[i] = localDirs.get(i).toString();
}
conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
conf.setBoolean(Dispatcher.DISPATCHER_EXIT_ON_ERROR_KEY, true);
DrainDispatcher dispatcher = new DrainDispatcher();
EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
dispatcher.register(ApplicationEventType.class, applicationBus);
EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
dispatcher.register(ContainerEventType.class, containerBus);
ContainerExecutor exec = mock(ContainerExecutor.class);
DeletionService delService = mock(DeletionService.class);
LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
LocalDirsHandlerService dirsHandlerSpy = spy(dirsHandler);
dirsHandlerSpy.init(conf);
dispatcher.init(conf);
dispatcher.start();
try {
ResourceLocalizationService rawService =
new ResourceLocalizationService(dispatcher, exec, delService,
dirsHandlerSpy, nmContext);
ResourceLocalizationService spyService = spy(rawService);
doReturn(mockServer).when(spyService).createServer();
doReturn(lfs).when(spyService).getLocalFileContext(
isA(Configuration.class));
spyService.init(conf);
spyService.start();
final String user = "user0";
// init application
final Application app = mock(Application.class);
final ApplicationId appId =
BuilderUtils.newApplicationId(314159265358979L, 3);
when(app.getUser()).thenReturn(user);
when(app.getAppId()).thenReturn(appId);
spyService.handle(new ApplicationLocalizationEvent(
LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
dispatcher.await();
// init resources
Random r = new Random();
r.setSeed(r.nextLong());
// Queue localization request for the public resource
final LocalResource pubResource = getPublicMockedResource(r);
final LocalResourceRequest pubReq = new LocalResourceRequest(pubResource);
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req =
new HashMap<LocalResourceVisibility, Collection<LocalResourceRequest>>();
req
.put(LocalResourceVisibility.PUBLIC, Collections.singletonList(pubReq));
// init container.
final Container c = getMockContainer(appId, 42, user);
// first test ioexception
Mockito
.doThrow(new IOException())
.when(dirsHandlerSpy)
.getLocalPathForWrite(isA(String.class), Mockito.anyLong(),
Mockito.anyBoolean());
// send request
spyService.handle(new ContainerLocalizationRequestEvent(c, req));
dispatcher.await();
LocalResourcesTracker tracker =
spyService.getLocalResourcesTracker(LocalResourceVisibility.PUBLIC,
user, appId);
Assert.assertNull(tracker.getLocalizedResource(pubReq));
// test IllegalArgumentException
String name = Long.toHexString(r.nextLong());
URL url = getPath("/local/PRIVATE/" + name + "/");
final LocalResource rsrc =
BuilderUtils.newLocalResource(url, LocalResourceType.FILE,
LocalResourceVisibility.PUBLIC, r.nextInt(1024) + 1024L,
r.nextInt(1024) + 2048L);
final LocalResourceRequest pubReq1 = new LocalResourceRequest(rsrc);
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req1 =
new HashMap<LocalResourceVisibility,
Collection<LocalResourceRequest>>();
req1.put(LocalResourceVisibility.PUBLIC,
Collections.singletonList(pubReq1));
Mockito
.doCallRealMethod()
.when(dirsHandlerSpy)
.getLocalPathForWrite(isA(String.class), Mockito.anyLong(),
Mockito.anyBoolean());
// send request
spyService.handle(new ContainerLocalizationRequestEvent(c, req1));
dispatcher.await();
tracker =
spyService.getLocalResourcesTracker(LocalResourceVisibility.PUBLIC,
user, appId);
Assert.assertNull(tracker.getLocalizedResource(pubReq));
// test RejectedExecutionException by shutting down the thread pool
PublicLocalizer publicLocalizer = spyService.getPublicLocalizer();
publicLocalizer.threadPool.shutdown();
spyService.handle(new ContainerLocalizationRequestEvent(c, req));
dispatcher.await();
tracker =
spyService.getLocalResourcesTracker(LocalResourceVisibility.PUBLIC,
user, appId);
Assert.assertNull(tracker.getLocalizedResource(pubReq));
} finally {
// if we call stop with events in the queue, an InterruptedException gets
// thrown resulting in the dispatcher thread causing a system exit
dispatcher.await();
dispatcher.stop();
}
}
@Test(timeout = 100000)
@SuppressWarnings("unchecked")
public void testParallelDownloadAttemptsForPrivateResource() throws Exception {
DrainDispatcher dispatcher1 = null;
try {
dispatcher1 = new DrainDispatcher();
String user = "testuser";
ApplicationId appId = BuilderUtils.newApplicationId(1, 1);
// creating one local directory
List<Path> localDirs = new ArrayList<Path>();
String[] sDirs = new String[1];
for (int i = 0; i < 1; ++i) {
localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
sDirs[i] = localDirs.get(i).toString();
}
conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
LocalDirsHandlerService localDirHandler = new LocalDirsHandlerService();
localDirHandler.init(conf);
// Registering event handlers
EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
dispatcher1.register(ApplicationEventType.class, applicationBus);
EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
dispatcher1.register(ContainerEventType.class, containerBus);
ContainerExecutor exec = mock(ContainerExecutor.class);
DeletionService delService = mock(DeletionService.class);
LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
// initializing directory handler.
dirsHandler.init(conf);
dispatcher1.init(conf);
dispatcher1.start();
ResourceLocalizationService rls =
new ResourceLocalizationService(dispatcher1, exec, delService,
localDirHandler, nmContext);
dispatcher1.register(LocalizationEventType.class, rls);
rls.init(conf);
rls.handle(createApplicationLocalizationEvent(user, appId));
LocalResourceRequest req =
new LocalResourceRequest(new Path("file:///tmp"), 123L,
LocalResourceType.FILE, LocalResourceVisibility.PRIVATE, "");
// We need to pre-populate the LocalizerRunner as the
// Resource Localization Service code internally starts them which
// definitely we don't want.
// creating new containers and populating corresponding localizer runners
// Container - 1
ContainerImpl container1 = createMockContainer(user, 1);
String localizerId1 = container1.getContainerId().toString();
rls.getPrivateLocalizers().put(
localizerId1,
rls.new LocalizerRunner(new LocalizerContext(user, container1
.getContainerId(), null), localizerId1));
LocalizerRunner localizerRunner1 = rls.getLocalizerRunner(localizerId1);
dispatcher1.getEventHandler().handle(
createContainerLocalizationEvent(container1,
LocalResourceVisibility.PRIVATE, req));
Assert
.assertTrue(waitForPrivateDownloadToStart(rls, localizerId1, 1, 200));
// Container - 2 now makes the request.
ContainerImpl container2 = createMockContainer(user, 2);
String localizerId2 = container2.getContainerId().toString();
rls.getPrivateLocalizers().put(
localizerId2,
rls.new LocalizerRunner(new LocalizerContext(user, container2
.getContainerId(), null), localizerId2));
LocalizerRunner localizerRunner2 = rls.getLocalizerRunner(localizerId2);
dispatcher1.getEventHandler().handle(
createContainerLocalizationEvent(container2,
LocalResourceVisibility.PRIVATE, req));
Assert
.assertTrue(waitForPrivateDownloadToStart(rls, localizerId2, 1, 200));
// Retrieving localized resource.
LocalResourcesTracker tracker =
rls.getLocalResourcesTracker(LocalResourceVisibility.PRIVATE, user,
appId);
LocalizedResource lr = tracker.getLocalizedResource(req);
// Resource would now have moved into DOWNLOADING state
Assert.assertEquals(ResourceState.DOWNLOADING, lr.getState());
// Resource should have one permit
Assert.assertEquals(1, lr.sem.availablePermits());
// Resource Localization Service receives first heart beat from
// ContainerLocalizer for container1
LocalizerHeartbeatResponse response1 =
rls.heartbeat(createLocalizerStatus(localizerId1));
// Resource must have been added to scheduled map
Assert.assertEquals(1, localizerRunner1.scheduled.size());
// Checking resource in the response and also available permits for it.
Assert.assertEquals(req.getResource(), response1.getResourceSpecs()
.get(0).getResource().getResource());
Assert.assertEquals(0, lr.sem.availablePermits());
// Resource Localization Service now receives first heart beat from
// ContainerLocalizer for container2
LocalizerHeartbeatResponse response2 =
rls.heartbeat(createLocalizerStatus(localizerId2));
// Resource must not have been added to scheduled map
Assert.assertEquals(0, localizerRunner2.scheduled.size());
// No resource is returned in response
Assert.assertEquals(0, response2.getResourceSpecs().size());
// ContainerLocalizer - 1 now sends failed resource heartbeat.
rls.heartbeat(createLocalizerStatusForFailedResource(localizerId1, req));
// Resource Localization should fail and state is modified accordingly.
// Also Local should be release on the LocalizedResource.
Assert
.assertTrue(waitForResourceState(lr, rls, req,
LocalResourceVisibility.PRIVATE, user, appId, ResourceState.FAILED,
200));
Assert.assertTrue(lr.getState().equals(ResourceState.FAILED));
Assert.assertEquals(0, localizerRunner1.scheduled.size());
// Now Container-2 once again sends heart beat to resource localization
// service
// Now container-2 again try to download the resource it should still
// not get the resource as the resource is now not in DOWNLOADING state.
response2 = rls.heartbeat(createLocalizerStatus(localizerId2));
// Resource must not have been added to scheduled map.
// Also as the resource has failed download it will be removed from
// pending list.
Assert.assertEquals(0, localizerRunner2.scheduled.size());
Assert.assertEquals(0, localizerRunner2.pending.size());
Assert.assertEquals(0, response2.getResourceSpecs().size());
} finally {
if (dispatcher1 != null) {
dispatcher1.stop();
}
}
}
@Test(timeout = 10000)
@SuppressWarnings("unchecked")
public void testLocalResourcePath() throws Exception {
// test the local path where application and user cache files will be
// localized.
DrainDispatcher dispatcher1 = null;
try {
dispatcher1 = new DrainDispatcher();
String user = "testuser";
ApplicationId appId = BuilderUtils.newApplicationId(1, 1);
// creating one local directory
List<Path> localDirs = new ArrayList<Path>();
String[] sDirs = new String[1];
for (int i = 0; i < 1; ++i) {
localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
sDirs[i] = localDirs.get(i).toString();
}
conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
LocalDirsHandlerService localDirHandler = new LocalDirsHandlerService();
localDirHandler.init(conf);
// Registering event handlers
EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
dispatcher1.register(ApplicationEventType.class, applicationBus);
EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
dispatcher1.register(ContainerEventType.class, containerBus);
ContainerExecutor exec = mock(ContainerExecutor.class);
DeletionService delService = mock(DeletionService.class);
LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
// initializing directory handler.
dirsHandler.init(conf);
dispatcher1.init(conf);
dispatcher1.start();
ResourceLocalizationService rls =
new ResourceLocalizationService(dispatcher1, exec, delService,
localDirHandler, nmContext);
dispatcher1.register(LocalizationEventType.class, rls);
rls.init(conf);
rls.handle(createApplicationLocalizationEvent(user, appId));
// We need to pre-populate the LocalizerRunner as the
// Resource Localization Service code internally starts them which
// definitely we don't want.
// creating new container and populating corresponding localizer runner
// Container - 1
Container container1 = createMockContainer(user, 1);
String localizerId1 = container1.getContainerId().toString();
rls.getPrivateLocalizers().put(
localizerId1,
rls.new LocalizerRunner(new LocalizerContext(user, container1
.getContainerId(), null), localizerId1));
// Creating two requests for container
// 1) Private resource
// 2) Application resource
LocalResourceRequest reqPriv =
new LocalResourceRequest(new Path("file:///tmp1"), 123L,
LocalResourceType.FILE, LocalResourceVisibility.PRIVATE, "");
List<LocalResourceRequest> privList =
new ArrayList<LocalResourceRequest>();
privList.add(reqPriv);
LocalResourceRequest reqApp =
new LocalResourceRequest(new Path("file:///tmp2"), 123L,
LocalResourceType.FILE, LocalResourceVisibility.APPLICATION, "");
List<LocalResourceRequest> appList =
new ArrayList<LocalResourceRequest>();
appList.add(reqApp);
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> rsrcs =
new HashMap<LocalResourceVisibility, Collection<LocalResourceRequest>>();
rsrcs.put(LocalResourceVisibility.APPLICATION, appList);
rsrcs.put(LocalResourceVisibility.PRIVATE, privList);
dispatcher1.getEventHandler().handle(
new ContainerLocalizationRequestEvent(container1, rsrcs));
// Now waiting for resource download to start. Here actual will not start
// Only the resources will be populated into pending list.
Assert
.assertTrue(waitForPrivateDownloadToStart(rls, localizerId1, 2, 500));
// Validating user and application cache paths
String userCachePath =
StringUtils.join(Path.SEPARATOR, Arrays.asList(localDirs.get(0)
.toUri().getRawPath(), ContainerLocalizer.USERCACHE, user,
ContainerLocalizer.FILECACHE));
String userAppCachePath =
StringUtils.join(Path.SEPARATOR, Arrays.asList(localDirs.get(0)
.toUri().getRawPath(), ContainerLocalizer.USERCACHE, user,
ContainerLocalizer.APPCACHE, appId.toString(),
ContainerLocalizer.FILECACHE));
// Now the Application and private resources may come in any order
// for download.
// For User cahce :
// returned destinationPath = user cache path + random number
// For App cache :
// returned destinationPath = user app cache path + random number
int returnedResources = 0;
boolean appRsrc = false, privRsrc = false;
while (returnedResources < 2) {
LocalizerHeartbeatResponse response =
rls.heartbeat(createLocalizerStatus(localizerId1));
for (ResourceLocalizationSpec resourceSpec : response
.getResourceSpecs()) {
returnedResources++;
Path destinationDirectory =
new Path(resourceSpec.getDestinationDirectory().getFile());
if (resourceSpec.getResource().getVisibility() ==
LocalResourceVisibility.APPLICATION) {
appRsrc = true;
Assert.assertEquals(userAppCachePath, destinationDirectory
.getParent().toUri().toString());
} else if (resourceSpec.getResource().getVisibility() ==
LocalResourceVisibility.PRIVATE) {
privRsrc = true;
Assert.assertEquals(userCachePath, destinationDirectory.getParent()
.toUri().toString());
} else {
throw new Exception("Unexpected resource recevied.");
}
}
}
// We should receive both the resources (Application and Private)
Assert.assertTrue(appRsrc && privRsrc);
} finally {
if (dispatcher1 != null) {
dispatcher1.stop();
}
}
}
private LocalizerStatus createLocalizerStatusForFailedResource(
String localizerId, LocalResourceRequest req) {
LocalizerStatus status = createLocalizerStatus(localizerId);
LocalResourceStatus resourceStatus = new LocalResourceStatusPBImpl();
resourceStatus.setException(SerializedException
.newInstance(new YarnException("test")));
resourceStatus.setStatus(ResourceStatusType.FETCH_FAILURE);
resourceStatus.setResource(req);
status.addResourceStatus(resourceStatus);
return status;
}
private LocalizerStatus createLocalizerStatus(String localizerId1) {
LocalizerStatus status = new LocalizerStatusPBImpl();
status.setLocalizerId(localizerId1);
return status;
}
private LocalizationEvent createApplicationLocalizationEvent(String user,
ApplicationId appId) {
Application app = mock(Application.class);
when(app.getUser()).thenReturn(user);
when(app.getAppId()).thenReturn(appId);
return new ApplicationLocalizationEvent(
LocalizationEventType.INIT_APPLICATION_RESOURCES, app);
}
@Test(timeout = 100000)
@SuppressWarnings("unchecked")
public void testParallelDownloadAttemptsForPublicResource() throws Exception {
DrainDispatcher dispatcher1 = null;
String user = "testuser";
try {
// creating one local directory
List<Path> localDirs = new ArrayList<Path>();
String[] sDirs = new String[1];
for (int i = 0; i < 1; ++i) {
localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
sDirs[i] = localDirs.get(i).toString();
}
conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
// Registering event handlers
EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
dispatcher1 = new DrainDispatcher();
dispatcher1.register(ApplicationEventType.class, applicationBus);
EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
dispatcher1.register(ContainerEventType.class, containerBus);
ContainerExecutor exec = mock(ContainerExecutor.class);
DeletionService delService = mock(DeletionService.class);
LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
// initializing directory handler.
dirsHandler.init(conf);
dispatcher1.init(conf);
dispatcher1.start();
// Creating and initializing ResourceLocalizationService but not starting
// it as otherwise it will remove requests from pending queue.
ResourceLocalizationService rawService =
new ResourceLocalizationService(dispatcher1, exec, delService,
dirsHandler, nmContext);
ResourceLocalizationService spyService = spy(rawService);
dispatcher1.register(LocalizationEventType.class, spyService);
spyService.init(conf);
// Initially pending map should be empty for public localizer
Assert.assertEquals(0, spyService.getPublicLocalizer().pending.size());
LocalResourceRequest req =
new LocalResourceRequest(new Path("/tmp"), 123L,
LocalResourceType.FILE, LocalResourceVisibility.PUBLIC, "");
// Initializing application
ApplicationImpl app = mock(ApplicationImpl.class);
ApplicationId appId = BuilderUtils.newApplicationId(1, 1);
when(app.getAppId()).thenReturn(appId);
when(app.getUser()).thenReturn(user);
dispatcher1.getEventHandler().handle(
new ApplicationLocalizationEvent(
LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
// Container - 1
// container requesting the resource
ContainerImpl container1 = createMockContainer(user, 1);
dispatcher1.getEventHandler().handle(
createContainerLocalizationEvent(container1,
LocalResourceVisibility.PUBLIC, req));
// Waiting for resource to change into DOWNLOADING state.
Assert.assertTrue(waitForResourceState(null, spyService, req,
LocalResourceVisibility.PUBLIC, user, null, ResourceState.DOWNLOADING,
200));
// Waiting for download to start.
Assert.assertTrue(waitForPublicDownloadToStart(spyService, 1, 200));
LocalizedResource lr =
getLocalizedResource(spyService, req, LocalResourceVisibility.PUBLIC,
user, null);
// Resource would now have moved into DOWNLOADING state
Assert.assertEquals(ResourceState.DOWNLOADING, lr.getState());
// pending should have this resource now.
Assert.assertEquals(1, spyService.getPublicLocalizer().pending.size());
// Now resource should have 0 permit.
Assert.assertEquals(0, lr.sem.availablePermits());
// Container - 2
// Container requesting the same resource.
ContainerImpl container2 = createMockContainer(user, 2);
dispatcher1.getEventHandler().handle(
createContainerLocalizationEvent(container2,
LocalResourceVisibility.PUBLIC, req));
// Waiting for download to start. This should return false as new download
// will not start
Assert.assertFalse(waitForPublicDownloadToStart(spyService, 2, 100));
// Now Failing the resource download. As a part of it
// resource state is changed and then lock is released.
ResourceFailedLocalizationEvent locFailedEvent =
new ResourceFailedLocalizationEvent(
req,new Exception("test").toString());
spyService.getLocalResourcesTracker(LocalResourceVisibility.PUBLIC, user,
null).handle(locFailedEvent);
// Waiting for resource to change into FAILED state.
Assert.assertTrue(waitForResourceState(lr, spyService, req,
LocalResourceVisibility.PUBLIC, user, null, ResourceState.FAILED, 200));
// releasing lock as a part of download failed process.
lr.unlock();
// removing pending download request.
spyService.getPublicLocalizer().pending.clear();
// Now I need to simulate a race condition wherein Event is added to
// dispatcher before resource state changes to either FAILED or LOCALIZED
// Hence sending event directly to dispatcher.
LocalizerResourceRequestEvent localizerEvent =
new LocalizerResourceRequestEvent(lr, null,
mock(LocalizerContext.class), null);
dispatcher1.getEventHandler().handle(localizerEvent);
// Waiting for download to start. This should return false as new download
// will not start
Assert.assertFalse(waitForPublicDownloadToStart(spyService, 1, 100));
// Checking available permits now.
Assert.assertEquals(1, lr.sem.availablePermits());
} finally {
if (dispatcher1 != null) {
dispatcher1.stop();
}
}
}
private boolean waitForPrivateDownloadToStart(
ResourceLocalizationService service, String localizerId, int size,
int maxWaitTime) {
List<LocalizerResourceRequestEvent> pending = null;
// Waiting for localizer to be created.
do {
if (service.getPrivateLocalizers().get(localizerId) != null) {
pending = service.getPrivateLocalizers().get(localizerId).pending;
}
if (pending == null) {
try {
maxWaitTime -= 20;
Thread.sleep(20);
} catch (Exception e) {
}
} else {
break;
}
} while (maxWaitTime > 0);
if (pending == null) {
return false;
}
do {
if (pending.size() == size) {
return true;
} else {
try {
maxWaitTime -= 20;
Thread.sleep(20);
} catch (Exception e) {
}
}
} while (maxWaitTime > 0);
return pending.size() == size;
}
private boolean waitForPublicDownloadToStart(
ResourceLocalizationService service, int size, int maxWaitTime) {
Map<Future<Path>, LocalizerResourceRequestEvent> pending = null;
// Waiting for localizer to be created.
do {
if (service.getPublicLocalizer() != null) {
pending = service.getPublicLocalizer().pending;
}
if (pending == null) {
try {
maxWaitTime -= 20;
Thread.sleep(20);
} catch (Exception e) {
}
} else {
break;
}
} while (maxWaitTime > 0);
if (pending == null) {
return false;
}
do {
if (pending.size() == size) {
return true;
} else {
try {
maxWaitTime -= 20;
Thread.sleep(20);
} catch (InterruptedException e) {
}
}
} while (maxWaitTime > 0);
return pending.size() == size;
}
private LocalizedResource getLocalizedResource(
ResourceLocalizationService service, LocalResourceRequest req,
LocalResourceVisibility vis, String user, ApplicationId appId) {
return service.getLocalResourcesTracker(vis, user, appId)
.getLocalizedResource(req);
}
private boolean waitForResourceState(LocalizedResource lr,
ResourceLocalizationService service, LocalResourceRequest req,
LocalResourceVisibility vis, String user, ApplicationId appId,
ResourceState resourceState, long maxWaitTime) {
LocalResourcesTracker tracker = null;
// checking tracker is created
do {
if (tracker == null) {
tracker = service.getLocalResourcesTracker(vis, user, appId);
}
if (tracker != null && lr == null) {
lr = tracker.getLocalizedResource(req);
}
if (lr != null) {
break;
} else {
try {
maxWaitTime -= 20;
Thread.sleep(20);
} catch (InterruptedException e) {
}
}
} while (maxWaitTime > 0);
// this will wait till resource state is changed to (resourceState).
if (lr == null) {
return false;
}
do {
if (!lr.getState().equals(resourceState)) {
try {
maxWaitTime -= 50;
Thread.sleep(50);
} catch (InterruptedException e) {
}
} else {
break;
}
} while (maxWaitTime > 0);
return lr.getState().equals(resourceState);
}
private ContainerLocalizationRequestEvent createContainerLocalizationEvent(
ContainerImpl container, LocalResourceVisibility vis,
LocalResourceRequest req) {
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> reqs =
new HashMap<LocalResourceVisibility, Collection<LocalResourceRequest>>();
List<LocalResourceRequest> resourceList =
new ArrayList<LocalResourceRequest>();
resourceList.add(req);
reqs.put(vis, resourceList);
return new ContainerLocalizationRequestEvent(container, reqs);
}
private ContainerImpl createMockContainer(String user, int containerId) {
ContainerImpl container = mock(ContainerImpl.class);
when(container.getContainerId()).thenReturn(
BuilderUtils.newContainerId(1, 1, 1, containerId));
when(container.getUser()).thenReturn(user);
Credentials mockCredentials = mock(Credentials.class);
when(container.getCredentials()).thenReturn(mockCredentials);
return container;
}
private static URL getPath(String path) {
URL url = BuilderUtils.newURL("file", null, 0, path);
return url;
}
private static LocalResource getMockedResource(Random r,
LocalResourceVisibility vis) {
String name = Long.toHexString(r.nextLong());
URL url = getPath("/local/PRIVATE/" + name);
LocalResource rsrc =
BuilderUtils.newLocalResource(url, LocalResourceType.FILE, vis,
r.nextInt(1024) + 1024L, r.nextInt(1024) + 2048L);
return rsrc;
}
private static LocalResource getAppMockedResource(Random r) {
return getMockedResource(r, LocalResourceVisibility.APPLICATION);
}
private static LocalResource getPublicMockedResource(Random r) {
return getMockedResource(r, LocalResourceVisibility.PUBLIC);
}
private static LocalResource getPrivateMockedResource(Random r) {
return getMockedResource(r, LocalResourceVisibility.PRIVATE);
}
private static Container getMockContainer(ApplicationId appId, int id,
String user) {
Container c = mock(Container.class);
ApplicationAttemptId appAttemptId =
BuilderUtils.newApplicationAttemptId(appId, 1);
ContainerId cId = BuilderUtils.newContainerId(appAttemptId, id);
when(c.getUser()).thenReturn(user);
when(c.getContainerId()).thenReturn(cId);
Credentials creds = new Credentials();
creds.addToken(new Text("tok" + id), getToken(id));
when(c.getCredentials()).thenReturn(creds);
when(c.toString()).thenReturn(cId.toString());
return c;
}
private ResourceLocalizationService createSpyService(
DrainDispatcher dispatcher, LocalDirsHandlerService dirsHandler,
NMStateStoreService stateStore) {
ContainerExecutor exec = mock(ContainerExecutor.class);
LocalizerTracker mockLocalizerTracker = mock(LocalizerTracker.class);
DeletionService delService = mock(DeletionService.class);
NMContext nmContext =
new NMContext(new NMContainerTokenSecretManager(conf),
new NMTokenSecretManagerInNM(), null,
new ApplicationACLsManager(conf), stateStore);
ResourceLocalizationService rawService =
new ResourceLocalizationService(dispatcher, exec, delService,
dirsHandler, nmContext);
ResourceLocalizationService spyService = spy(rawService);
doReturn(mockServer).when(spyService).createServer();
doReturn(mockLocalizerTracker).when(spyService).createLocalizerTracker(
isA(Configuration.class));
doReturn(lfs).when(spyService)
.getLocalFileContext(isA(Configuration.class));
return spyService;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
static Token<? extends TokenIdentifier> getToken(int id) {
return new Token(("ident" + id).getBytes(), ("passwd" + id).getBytes(),
new Text("kind" + id), new Text("service" + id));
}
/*
* Test to ensure ResourceLocalizationService can handle local dirs going bad.
* Test first sets up all the components required, then sends events to fetch
* a private, app and public resource. It then sends events to clean up the
* container and the app and ensures the right delete calls were made.
*/
@Test
@SuppressWarnings("unchecked")
// mocked generics
public void testFailedDirsResourceRelease() throws Exception {
// setup components
File f = new File(basedir.toString());
String[] sDirs = new String[4];
List<Path> localDirs = new ArrayList<Path>(sDirs.length);
for (int i = 0; i < 4; ++i) {
sDirs[i] = f.getAbsolutePath() + i;
localDirs.add(new Path(sDirs[i]));
}
List<Path> containerLocalDirs = new ArrayList<Path>(localDirs.size());
List<Path> appLocalDirs = new ArrayList<Path>(localDirs.size());
List<Path> nmLocalContainerDirs = new ArrayList<Path>(localDirs.size());
List<Path> nmLocalAppDirs = new ArrayList<Path>(localDirs.size());
conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
conf.setLong(YarnConfiguration.NM_DISK_HEALTH_CHECK_INTERVAL_MS, 500);
LocalizerTracker mockLocallilzerTracker = mock(LocalizerTracker.class);
DrainDispatcher dispatcher = new DrainDispatcher();
dispatcher.init(conf);
dispatcher.start();
EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
dispatcher.register(ApplicationEventType.class, applicationBus);
EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
dispatcher.register(ContainerEventType.class, containerBus);
// Ignore actual localization
EventHandler<LocalizerEvent> localizerBus = mock(EventHandler.class);
dispatcher.register(LocalizerEventType.class, localizerBus);
ContainerExecutor exec = mock(ContainerExecutor.class);
LocalDirsHandlerService mockDirsHandler =
mock(LocalDirsHandlerService.class);
doReturn(new ArrayList<String>(Arrays.asList(sDirs))).when(
mockDirsHandler).getLocalDirsForCleanup();
DeletionService delService = mock(DeletionService.class);
// setup mocks
ResourceLocalizationService rawService =
new ResourceLocalizationService(dispatcher, exec, delService,
mockDirsHandler, nmContext);
ResourceLocalizationService spyService = spy(rawService);
doReturn(mockServer).when(spyService).createServer();
doReturn(mockLocallilzerTracker).when(spyService).createLocalizerTracker(
isA(Configuration.class));
doReturn(lfs).when(spyService)
.getLocalFileContext(isA(Configuration.class));
FsPermission defaultPermission =
FsPermission.getDirDefault().applyUMask(lfs.getUMask());
FsPermission nmPermission =
ResourceLocalizationService.NM_PRIVATE_PERM.applyUMask(lfs.getUMask());
final FileStatus fs =
new FileStatus(0, true, 1, 0, System.currentTimeMillis(), 0,
defaultPermission, "", "", localDirs.get(0));
final FileStatus nmFs =
new FileStatus(0, true, 1, 0, System.currentTimeMillis(), 0,
nmPermission, "", "", localDirs.get(0));
final String user = "user0";
// init application
final Application app = mock(Application.class);
final ApplicationId appId =
BuilderUtils.newApplicationId(314159265358979L, 3);
when(app.getUser()).thenReturn(user);
when(app.getAppId()).thenReturn(appId);
when(app.toString()).thenReturn(ConverterUtils.toString(appId));
// init container.
final Container c = getMockContainer(appId, 42, user);
// setup local app dirs
List<String> tmpDirs = mockDirsHandler.getLocalDirs();
for (int i = 0; i < tmpDirs.size(); ++i) {
Path usersdir = new Path(tmpDirs.get(i), ContainerLocalizer.USERCACHE);
Path userdir = new Path(usersdir, user);
Path allAppsdir = new Path(userdir, ContainerLocalizer.APPCACHE);
Path appDir = new Path(allAppsdir, ConverterUtils.toString(appId));
Path containerDir =
new Path(appDir, ConverterUtils.toString(c.getContainerId()));
containerLocalDirs.add(containerDir);
appLocalDirs.add(appDir);
Path sysDir =
new Path(tmpDirs.get(i), ResourceLocalizationService.NM_PRIVATE_DIR);
Path appSysDir = new Path(sysDir, ConverterUtils.toString(appId));
Path containerSysDir =
new Path(appSysDir, ConverterUtils.toString(c.getContainerId()));
nmLocalContainerDirs.add(containerSysDir);
nmLocalAppDirs.add(appSysDir);
}
try {
spyService.init(conf);
spyService.start();
spyService.handle(new ApplicationLocalizationEvent(
LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
dispatcher.await();
// Get a handle on the trackers after they're setup with
// INIT_APP_RESOURCES
LocalResourcesTracker appTracker =
spyService.getLocalResourcesTracker(
LocalResourceVisibility.APPLICATION, user, appId);
LocalResourcesTracker privTracker =
spyService.getLocalResourcesTracker(LocalResourceVisibility.PRIVATE,
user, appId);
LocalResourcesTracker pubTracker =
spyService.getLocalResourcesTracker(LocalResourceVisibility.PUBLIC,
user, appId);
// init resources
Random r = new Random();
long seed = r.nextLong();
r.setSeed(seed);
// Send localization requests, one for each type of resource
final LocalResource privResource = getPrivateMockedResource(r);
final LocalResourceRequest privReq =
new LocalResourceRequest(privResource);
final LocalResource appResource = getAppMockedResource(r);
final LocalResourceRequest appReq = new LocalResourceRequest(appResource);
final LocalResource pubResource = getPublicMockedResource(r);
final LocalResourceRequest pubReq = new LocalResourceRequest(pubResource);
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req =
new HashMap<LocalResourceVisibility, Collection<LocalResourceRequest>>();
req.put(LocalResourceVisibility.PRIVATE,
Collections.singletonList(privReq));
req.put(LocalResourceVisibility.APPLICATION,
Collections.singletonList(appReq));
req
.put(LocalResourceVisibility.PUBLIC, Collections.singletonList(pubReq));
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req2 =
new HashMap<LocalResourceVisibility, Collection<LocalResourceRequest>>();
req2.put(LocalResourceVisibility.PRIVATE,
Collections.singletonList(privReq));
// Send Request event
spyService.handle(new ContainerLocalizationRequestEvent(c, req));
spyService.handle(new ContainerLocalizationRequestEvent(c, req2));
dispatcher.await();
int privRsrcCount = 0;
for (LocalizedResource lr : privTracker) {
privRsrcCount++;
Assert.assertEquals("Incorrect reference count", 2, lr.getRefCount());
Assert.assertEquals(privReq, lr.getRequest());
}
Assert.assertEquals(1, privRsrcCount);
int appRsrcCount = 0;
for (LocalizedResource lr : appTracker) {
appRsrcCount++;
Assert.assertEquals("Incorrect reference count", 1, lr.getRefCount());
Assert.assertEquals(appReq, lr.getRequest());
}
Assert.assertEquals(1, appRsrcCount);
int pubRsrcCount = 0;
for (LocalizedResource lr : pubTracker) {
pubRsrcCount++;
Assert.assertEquals("Incorrect reference count", 1, lr.getRefCount());
Assert.assertEquals(pubReq, lr.getRequest());
}
Assert.assertEquals(1, pubRsrcCount);
// setup mocks for test, a set of dirs with IOExceptions and let the rest
// go through
for (int i = 0; i < containerLocalDirs.size(); ++i) {
if (i == 2) {
Mockito.doThrow(new IOException()).when(spylfs)
.getFileStatus(eq(containerLocalDirs.get(i)));
Mockito.doThrow(new IOException()).when(spylfs)
.getFileStatus(eq(nmLocalContainerDirs.get(i)));
} else {
doReturn(fs).when(spylfs)
.getFileStatus(eq(containerLocalDirs.get(i)));
doReturn(nmFs).when(spylfs).getFileStatus(
eq(nmLocalContainerDirs.get(i)));
}
}
// Send Cleanup Event
spyService.handle(new ContainerLocalizationCleanupEvent(c, req));
verify(mockLocallilzerTracker).cleanupPrivLocalizers(
"container_314159265358979_0003_01_000042");
// match cleanup events with the mocks we setup earlier
for (int i = 0; i < containerLocalDirs.size(); ++i) {
if (i == 2) {
try {
verify(delService).delete(user, containerLocalDirs.get(i));
verify(delService).delete(null, nmLocalContainerDirs.get(i));
Assert.fail("deletion attempts for invalid dirs");
} catch (Throwable e) {
continue;
}
} else {
verify(delService).delete(user, containerLocalDirs.get(i));
verify(delService).delete(null, nmLocalContainerDirs.get(i));
}
}
ArgumentMatcher<ApplicationEvent> matchesAppDestroy =
new ArgumentMatcher<ApplicationEvent>() {
@Override
public boolean matches(Object o) {
ApplicationEvent evt = (ApplicationEvent) o;
return (evt.getType() == ApplicationEventType.APPLICATION_RESOURCES_CLEANEDUP)
&& appId == evt.getApplicationID();
}
};
dispatcher.await();
// setup mocks again, this time throw UnsupportedFileSystemException and
// IOExceptions
for (int i = 0; i < containerLocalDirs.size(); ++i) {
if (i == 3) {
Mockito.doThrow(new IOException()).when(spylfs)
.getFileStatus(eq(appLocalDirs.get(i)));
Mockito.doThrow(new UnsupportedFileSystemException("test"))
.when(spylfs).getFileStatus(eq(nmLocalAppDirs.get(i)));
} else {
doReturn(fs).when(spylfs).getFileStatus(eq(appLocalDirs.get(i)));
doReturn(nmFs).when(spylfs).getFileStatus(eq(nmLocalAppDirs.get(i)));
}
}
LocalizationEvent destroyApp =
new ApplicationLocalizationEvent(
LocalizationEventType.DESTROY_APPLICATION_RESOURCES, app);
spyService.handle(destroyApp);
verify(applicationBus).handle(argThat(matchesAppDestroy));
// verify we got the right delete calls
for (int i = 0; i < containerLocalDirs.size(); ++i) {
if (i == 3) {
try {
verify(delService).delete(user, containerLocalDirs.get(i));
verify(delService).delete(null, nmLocalContainerDirs.get(i));
Assert.fail("deletion attempts for invalid dirs");
} catch (Throwable e) {
continue;
}
} else {
verify(delService).delete(user, appLocalDirs.get(i));
verify(delService).delete(null, nmLocalAppDirs.get(i));
}
}
} finally {
dispatcher.stop();
delService.stop();
}
}
}
|
package com.werb.mycalendardemo;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.werb.mycalendardemo.utils.ApiService;
import com.werb.mycalendardemo.utils.GlobalContants;
import com.werb.mycalendardemo.utils.PrefUtils;
import com.werb.mycalendardemo.utils.StreamFormat;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;
import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
/**
* 闪屏页
*/
public class SplashActivity extends AppCompatActivity {
@Bind(R.id.version_code)
TextView tvVersionCode;
private String mVersionName;//版本名
private int mVersionCode;//版本号
private String mDesc;//版本描述
private String mdownloadUrl;//新版本下载网站
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
ButterKnife.bind(this);//为使用注解进行注册
mVersionName= getVersionName();
mVersionCode= getVersionCode();
tvVersionCode.setText("版本号:" + mVersionName);
checkVersion();
}
/**
* 从获取服务器获取版本信息进行校验
*/
public void checkVersion() {
//利用volley框架进行http请求
RequestQueue requestQueue= Volley.newRequestQueue(SplashActivity.this);
JsonObjectRequest request=new JsonObjectRequest(GlobalContants.SERVER_URL+"update.json", new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
mVersionName = response.getString("versionName");
mVersionCode = response.getInt("versionCode");
mDesc = response.getString("description");
mdownloadUrl = response.getString("downloadUrl");
System.out.println("versionName="+mVersionName+"versionCode"+mVersionCode);
System.out.println("mdownloadUrl------------"+mdownloadUrl);
if(mVersionCode>getVersionCode()){
//如果服务器返回的versionCode大于本地的versionCode,说明有更新
showUpdateDialog();
}else {
//1.5S的延迟
Timer timer =new Timer();
TimerTask task =new TimerTask() {
@Override
public void run() {
jumpToNextPage();
}
};
timer.schedule(task,1500);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//1.5S的延迟
Timer timer =new Timer();
TimerTask task =new TimerTask() {
@Override
public void run() {
jumpToNextPage();
}
};
timer.schedule(task,1500);
}
});
requestQueue.add(request);
}
/**
* 获取版本名称
*
* @return
*/
public String getVersionName() {
PackageManager packageManager = getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
String versionName = packageInfo.versionName;
return versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取版本号
*
* @return
*/
public int getVersionCode() {
PackageManager packageManager = getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
int versionCode = packageInfo.versionCode;
return versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return 0;
}
/**
* 升级对话框
*/
private void showUpdateDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("最新版本:" + mVersionName);
builder.setMessage(mDesc);
builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
System.out.println("立即更新");
//下载APK
downLoadAPK();
}
});
builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//不更新,直接进入主界面
jumpToNextPage();
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
jumpToNextPage();
}
});
builder.show();
}
/**
* 下载APK文件
*/
private void downLoadAPK() {
//OkHttp
//先判断sdcard是否存在
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
final String target= Environment.getExternalStorageDirectory()+"/app-release.apk";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiService.SERVICE_URL)
.build();
ApiService apiService=retrofit.create(ApiService.class);
apiService.dowmApk(mdownloadUrl)
.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
InputStream inputStream = response.body().byteStream();
FileOutputStream fos = null;
File file=null;
//获取字节数组
try {
byte[] getData= StreamFormat.readInputStream(inputStream);
file = new File(target);
fos=new FileOutputStream(file);
fos.write(getData);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("下载成功!");
//跳转至系统安装界面
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
// startActivity(intent);如果用户点取消同样返回主界面
startActivityForResult(intent,0);
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(SplashActivity.this,"下载失败",Toast.LENGTH_SHORT).show();
}
});
}else {
Toast.makeText(SplashActivity.this,"sdcard不存在",Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
jumpToNextPage();
}
/**
* 跳转下一个页面
*/
private void jumpToNextPage(){
//判断之前有没有显示过新手引导
Boolean isFirstIn= PrefUtils.getBoolean(this, "isFirstIn", true);
// 跳转到新手引导页或主页面
if(isFirstIn){
startActivity(new Intent(SplashActivity.this,GuideActivity.class));
}else {
startActivity(new Intent(SplashActivity.this,MainActivity.class));
}
finish();
}
}
|
package depends.extractor.java;
// Generated from C:/Users/y50016379/DevEcoStudioProjects/depends-master/src/main/antlr4/depends/extractor/java\JavaParser.g4 by ANTLR 4.8
import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor;
/**
* This class provides an empty implementation of {@link JavaParserVisitor},
* which can be extended to create a visitor which only needs to handle a subset
* of the available methods.
*
* @param <T> The return type of the visit operation. Use {@link Void} for
* operations with no return type.
*/
public class JavaParserBaseVisitor<T> extends AbstractParseTreeVisitor<T> implements JavaParserVisitor<T> {
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitCompilationUnit(JavaParser.CompilationUnitContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitPackageDeclaration(JavaParser.PackageDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitImportDeclaration(JavaParser.ImportDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTypeDeclaration(JavaParser.TypeDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitModifier(JavaParser.ModifierContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitClassOrInterfaceModifier(JavaParser.ClassOrInterfaceModifierContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitVariableModifier(JavaParser.VariableModifierContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitClassDeclaration(JavaParser.ClassDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTypeParameters(JavaParser.TypeParametersContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTypeParameter(JavaParser.TypeParameterContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTypeBound(JavaParser.TypeBoundContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitEnumDeclaration(JavaParser.EnumDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitEnumConstants(JavaParser.EnumConstantsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitEnumConstant(JavaParser.EnumConstantContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitEnumBodyDeclarations(JavaParser.EnumBodyDeclarationsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitInterfaceDeclaration(JavaParser.InterfaceDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitClassBody(JavaParser.ClassBodyContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitInterfaceBody(JavaParser.InterfaceBodyContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitClassBodyDeclaration(JavaParser.ClassBodyDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitMemberDeclaration(JavaParser.MemberDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitMethodBody(JavaParser.MethodBodyContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTypeTypeOrVoid(JavaParser.TypeTypeOrVoidContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitConstructorDeclaration(JavaParser.ConstructorDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitFieldDeclaration(JavaParser.FieldDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitInterfaceBodyDeclaration(JavaParser.InterfaceBodyDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitInterfaceMemberDeclaration(JavaParser.InterfaceMemberDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitConstDeclaration(JavaParser.ConstDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitConstantDeclarator(JavaParser.ConstantDeclaratorContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitInterfaceMethodDeclaration(JavaParser.InterfaceMethodDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitInterfaceMethodModifier(JavaParser.InterfaceMethodModifierContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitGenericInterfaceMethodDeclaration(JavaParser.GenericInterfaceMethodDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitVariableDeclarators(JavaParser.VariableDeclaratorsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitVariableDeclarator(JavaParser.VariableDeclaratorContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitVariableDeclaratorId(JavaParser.VariableDeclaratorIdContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitVariableInitializer(JavaParser.VariableInitializerContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitArrayInitializer(JavaParser.ArrayInitializerContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitClassOrInterfaceType(JavaParser.ClassOrInterfaceTypeContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTypeArgument(JavaParser.TypeArgumentContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitQualifiedNameList(JavaParser.QualifiedNameListContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitFormalParameters(JavaParser.FormalParametersContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitFormalParameterList(JavaParser.FormalParameterListContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitFormalParameter(JavaParser.FormalParameterContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitLastFormalParameter(JavaParser.LastFormalParameterContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitQualifiedName(JavaParser.QualifiedNameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitLiteral(JavaParser.LiteralContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitIntegerLiteral(JavaParser.IntegerLiteralContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitFloatLiteral(JavaParser.FloatLiteralContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitAnnotation(JavaParser.AnnotationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitElementValuePairs(JavaParser.ElementValuePairsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitElementValuePair(JavaParser.ElementValuePairContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitElementValue(JavaParser.ElementValueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitElementValueArrayInitializer(JavaParser.ElementValueArrayInitializerContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitAnnotationTypeDeclaration(JavaParser.AnnotationTypeDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitAnnotationTypeBody(JavaParser.AnnotationTypeBodyContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitAnnotationTypeElementDeclaration(JavaParser.AnnotationTypeElementDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitAnnotationTypeElementRest(JavaParser.AnnotationTypeElementRestContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitAnnotationMethodOrConstantRest(JavaParser.AnnotationMethodOrConstantRestContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitAnnotationMethodRest(JavaParser.AnnotationMethodRestContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitAnnotationConstantRest(JavaParser.AnnotationConstantRestContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitDefaultValue(JavaParser.DefaultValueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitBlock(JavaParser.BlockContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitBlockStatement(JavaParser.BlockStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitLocalVariableDeclaration(JavaParser.LocalVariableDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitLocalTypeDeclaration(JavaParser.LocalTypeDeclarationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitStatement(JavaParser.StatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitCatchClause(JavaParser.CatchClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitCatchType(JavaParser.CatchTypeContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitFinallyBlock(JavaParser.FinallyBlockContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitResourceSpecification(JavaParser.ResourceSpecificationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitResources(JavaParser.ResourcesContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitResource(JavaParser.ResourceContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitSwitchBlockStatementGroup(JavaParser.SwitchBlockStatementGroupContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitSwitchLabel(JavaParser.SwitchLabelContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitForControl(JavaParser.ForControlContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitForInit(JavaParser.ForInitContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitEnhancedForControl(JavaParser.EnhancedForControlContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitParExpression(JavaParser.ParExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitExpressionList(JavaParser.ExpressionListContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitMethodCall(JavaParser.MethodCallContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitExpression(JavaParser.ExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTypeCast(JavaParser.TypeCastContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitLambdaExpression(JavaParser.LambdaExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitLambdaParameters(JavaParser.LambdaParametersContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitLambdaBody(JavaParser.LambdaBodyContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitPrimary(JavaParser.PrimaryContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitClassType(JavaParser.ClassTypeContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitCreator(JavaParser.CreatorContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitCreatedName(JavaParser.CreatedNameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitInnerCreator(JavaParser.InnerCreatorContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitArrayCreatorRest(JavaParser.ArrayCreatorRestContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitClassCreatorRest(JavaParser.ClassCreatorRestContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitExplicitGenericInvocation(JavaParser.ExplicitGenericInvocationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTypeArgumentsOrDiamond(JavaParser.TypeArgumentsOrDiamondContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitNonWildcardTypeArgumentsOrDiamond(JavaParser.NonWildcardTypeArgumentsOrDiamondContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitNonWildcardTypeArguments(JavaParser.NonWildcardTypeArgumentsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTypeList(JavaParser.TypeListContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTypeType(JavaParser.TypeTypeContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitPrimitiveType(JavaParser.PrimitiveTypeContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTypeArguments(JavaParser.TypeArgumentsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitSuperSuffix(JavaParser.SuperSuffixContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitExplicitGenericInvocationSuffix(JavaParser.ExplicitGenericInvocationSuffixContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitArguments(JavaParser.ArgumentsContext ctx) { return visitChildren(ctx); }
}
|
package io.wren.libs;
import io.wren.utils.Wren;
import io.wren.value.Obj;
import io.wren.value.ObjClass;
import io.wren.value.Value;
import io.wren.vm.WrenVM;
public class WrenObject {
public static boolean not(Value[] stack, int stackStart, int numArgs) {
return Wren.RETURN(stack, stackStart, false);
}
public static boolean eqeq(Value[] stack, int stackStart, int numArgs) {
Value left = stack[stackStart];
Value right = stack[stackStart + 1];
return Wren.RETURN(stack, stackStart, left.equals(right));
}
public static boolean bangeq(Value[] stack, int stackStart, int numArgs) {
Value left = stack[stackStart];
Value right = stack[stackStart + 1];
return Wren.RETURN(stack, stackStart, !left.equals(right));
}
public static boolean is(Value[] stack, int stackStart, int numArgs) {
Value left = stack[stackStart];
Value right = stack[stackStart + 1];
if(!right.isClass()) {
return Wren.RETURN_ERROR("Right operand must be a class.");
}
ObjClass classObj = WrenVM.getInlineClass(left);
ObjClass baseClassObj = right.asClass();
do {
if(baseClassObj == classObj)
return Wren.RETURN(stack, stackStart, true);
classObj = classObj.superclass;
} while(classObj != null);
return Wren.RETURN(stack, stackStart, false);
}
public static boolean to_string(Value[] stack, int stackStart, int numArgs) {
Obj obj = stack[stackStart].asObj();
String string = obj.classObj.toString();
return Wren.RETURN(stack, stackStart, string);
}
public static boolean type(Value[] stack, int stackStart, int numArgs) {
return Wren.RETURN(stack, stackStart, WrenVM.getInlineClass(stack[stackStart]));
}
public static boolean same(Value[] stack, int stackStart, int numArgs) {
Value left = stack[stackStart];
Value right = stack[stackStart + 1];
return Wren.RETURN(stack, stackStart, left.equals(right));
}
}
|
package com.oculussoftware.util;
/**
* $Workfile: MC.java $
* Date: 4/25/00
* Description: MC (mini-CRM) helps get objects with less typing.
*
* Copyright 7-01-2000 Oculus Software. All Rights Reserved.
*
* @author J. Coles
* @version 1.2
*/
/*
* $History: MC.java $
*
* ***************** Version 3 *****************
* User: Jcoles Date: 5/09/00 Time: 4:54p
* Updated in $/Project - Socrates/DevSource1.2/Framework.Java/com/oculussoftware/util
* Added getObj( ) overloads that take string for type instead of IDCONST
* of the class.
*
* ***************** Version 2 *****************
* User: Jcoles Date: 5/01/00 Time: 2:54p
* Updated in $/Project - Socrates/DevSource1.2/Framework.Java/com/oculussoftware/util
* getObj( ) now throws exception if type is null.
*
* ***************** Version 1 *****************
* User: Jcoles Date: 4/28/00 Time: 1:31p
* Created in $/Project - Socrates/DevSource1.2/Framework.Java/com/oculussoftware/util
* Mini-CRM: this class reduces syntax for getting objects.
*
*/
import com.oculussoftware.api.sysi.*;
import com.oculussoftware.api.repi.*;
import com.oculussoftware.ui.*;
import java.util.*;
/**
* Helper for getting objects from CRM with less syntax
*/
public class MC
{
//--------------------------------------------------------------------
// Private instance variables
//--------------------------------------------------------------------
private IObjectContext _context = null;
//--------------------------------------------------------------------
// Public constructor(s)
//--------------------------------------------------------------------
public MC(IObjectContext context)
throws OculusException
{
if (context == null)
throw new OculusException("Null or invalid object context.");
_context = context;
}
//--------------------------------------------------------------------
// Public instance methods
//--------------------------------------------------------------------
/** 'Native' object getter */
public IObject getObj(IDCONST type, IIID iid)
throws OculusException
{
if (type == null) throw new OculusException("null type parameter.");
return _context.getCRM().getCompObject(_context,type.getDirName(), iid);
}
public IObject getObj(IDCONST type, long loid)
throws OculusException
{
return getObj(type, _context.getRepository().makeReposID(loid));
}
public IObject getObj(String strDirName, IIID iid)
throws OculusException
{
if (strDirName == null) throw new OculusException("null type parameter.");
return _context.getCRM().getCompObject(_context, strDirName, iid);
}
public IObject getObj(String strDirName, long loid)
throws OculusException
{
return getObj(strDirName, _context.getRepository().makeReposID(loid));
}
}
|
// ========================================================================
// $Id: MsieSslHandler.java,v 1.3 2005/08/13 00:01:26 gregwilkins Exp $
// Copyright 2003-2004 Mort Bay Consulting Pty. 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 net.lightbody.bmp.proxy.jetty.http.handler;
import net.lightbody.bmp.proxy.jetty.http.HttpException;
import net.lightbody.bmp.proxy.jetty.http.HttpFields;
import net.lightbody.bmp.proxy.jetty.http.HttpRequest;
import net.lightbody.bmp.proxy.jetty.http.HttpResponse;
import net.lightbody.bmp.proxy.jetty.log.LogFactory;
import org.apache.commons.logging.Log;
import java.io.IOException;
/**
* Handler to force MSIE SSL connections to not be persistent to
* work around MSIE5 bug.
*
* @author gregw
* @author chris haynes
*
*/
public class MsieSslHandler extends AbstractHttpHandler
{
private static Log log = LogFactory.getLog(MsieSslHandler.class);
private String userAgentSubString="MSIE 5";
/*
* @see HttpHandler#handle(java.lang.String, java.lang.String, HttpRequest, HttpResponse)
*/
public void handle(
String pathInContext,
String pathParams,
HttpRequest request,
HttpResponse response)
throws HttpException, IOException
{
String userAgent = request.getField(HttpFields.__UserAgent);
if(userAgent != null &&
userAgent.indexOf( userAgentSubString)>=0 &&
HttpRequest.__SSL_SCHEME.equalsIgnoreCase(request.getScheme()))
{
if (log.isDebugEnabled())
log.debug("Force close");
response.setField(HttpFields.__Connection, HttpFields.__Close);
request.getHttpConnection().forceClose();
}
}
/**
* @return The substring to match against the User-Agent field
*/
public String getUserAgentSubString()
{
return userAgentSubString;
}
/**
* @param string The substring to match against the User-Agent field
*/
public void setUserAgentSubString(String string)
{
userAgentSubString= string;
}
}
|
package gulimall.coupon.dao;
import gulimall.coupon.entity.SkuFullReductionEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 商品满减信息
*
* @author lu
* @email 574812239@qq.com
* @date 2022-01-29 13:31:51
*/
@Mapper
public interface SkuFullReductionDao extends BaseMapper<SkuFullReductionEntity> {
}
|
package org.infinispan.server.router.router;
import java.net.InetAddress;
import org.infinispan.server.router.RoutingTable;
/**
* The EndpointRouter interface. Currently the EndpointRouter is coupled closely with the the {@link Protocol} it implements.
*
* @author Sebastian Łaskawiec
*/
public interface EndpointRouter {
/**
* The protocol the router implements.
*/
enum Protocol {
HOT_ROD, SINGLE_PORT, REST
}
/**
* Starts the {@link EndpointRouter}.
*
* @param routingTable {@link RoutingTable} for supplying {@link org.infinispan.server.router.routes.Route}s.
*/
void start(RoutingTable routingTable);
/**
* Stops the {@link EndpointRouter}.
*/
void stop();
/**
* Gets the {@link EndpointRouter}'s host.
*/
String getHost();
/**
* Gets the {@link EndpointRouter}'s IP address.
*/
InetAddress getIp();
/**
* Gets the {@link EndpointRouter}'s port.
*/
Integer getPort();
/**
* Gets {@link Protocol} implemented by this {@link EndpointRouter}.
*/
Protocol getProtocol();
}
|
package org.edx.mobile.view.custom;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import androidx.appcompat.widget.AppCompatTextView;
import org.edx.mobile.R;
import org.edx.mobile.util.UiUtils;
import java.util.List;
public class CustomSelectView<T> extends AppCompatTextView implements View.OnClickListener,
DialogInterface.OnClickListener {
protected List<T> items;
private String hint;
private String prompt;
private T selectedItem;
private int checkedItemIndex = 0;
public CustomSelectView(Context context) {
super(context);
setOnClickListener(this);
setUIParams();
}
public CustomSelectView(Context context, AttributeSet attrs) {
super(context, attrs);
setOnClickListener(this);
setUIParams();
}
public CustomSelectView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setOnClickListener(this);
setUIParams();
}
/**
* This sets the common view parameters for Custom SelectView
*/
private void setUIParams() {
int padding = (int) UiUtils.INSTANCE.getParamsInDP(getResources(), 10);
setPadding(padding, padding, padding, padding);
setGravity(Gravity.START | Gravity.CENTER_VERTICAL);
}
public void setHint(String hint) {
this.hint = hint;
showHint();
}
/**
* Show the hint text on the custom select view
*/
private void showHint() {
setText(hint);
setTextColor(getResources().getColor(R.color.hint_grey_text));
setContentDescription(getResources().getString(R.string.dropdown_list_prefix) + hint);
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
/**
* Set the list of items to be displayed when the selectView is clicked
*
* @param items - List of items
* @param defaultItem - Default item to be shown as selected
*/
public void setItems(List<T> items, T defaultItem) {
this.items = items;
this.selectedItem = defaultItem;
// calculate checkedItemIndex
if (items != null && selectedItem != null) {
int i = 0;
for (T item : items) {
if (item.equals(selectedItem)) {
checkedItemIndex = i;
break;
}
i++;
}
}
}
public boolean has(T item) {
if (item == null || items == null)
return false;
for (T value : items) {
if (item.equals(item))
return true;
}
return false;
}
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
if (prompt != null) builder.setTitle(prompt);
if (items != null) {
builder.setSingleChoiceItems(getItemsAsStringArray(), checkedItemIndex, this);
builder.show();
}
}
@Override
public void onClick(DialogInterface dialog, int which) {
checkedItemIndex = which;
selectedItem = items.get(which);
select(selectedItem);
dialog.dismiss();
}
/**
* Call this function when a value is selected in the Dialog for custom select
*
* @param item - Selected Item
*/
protected void select(T item) {
//Check if the selected options value is empty
//The current json contains '--' as the first value
//and hence show the hint text instead of '--' in the select view
if (TextUtils.isEmpty(item.toString())
|| item.toString().equalsIgnoreCase("--")) {
showHint();
} else {
setText(item.toString());
setTextColor(getResources().getColor(R.color.neutralXXDark));
setContentDescription(getResources().getString(R.string.dropdown_list_prefix) + item.toString());
}
}
public T getSelectedItem() {
return selectedItem;
}
private String[] getItemsAsStringArray() {
if (items != null) {
String[] stringItems = new String[items.size()];
for (int i = 0; i < items.size(); i++) {
stringItems[i] = items.get(i).toString();
}
return stringItems;
}
return null;
}
}
|
package com.app.qunadai.content.presenter.v5;
import com.app.qunadai.bean.BannerBean;
import com.app.qunadai.bean.PersonBean;
import com.app.qunadai.bean.base.BaseBean;
import com.app.qunadai.bean.v5.Floors;
import com.app.qunadai.bean.v5.Products;
import com.app.qunadai.content.contract.v5.Home5Contract;
import com.app.qunadai.content.model.v5.Home5ModelImpl;
/**
* Created by wayne on 2017/9/7.
*/
public class Home5Presenter implements Home5Contract.Presenter {
private Home5Contract.View view;
private Home5Contract.Model model;
public Home5Presenter(Home5Contract.View iview) {
this.view = iview;
model = new Home5ModelImpl(new Home5ModelImpl.OnReturnDataListener() {
@Override
public void getPersonValue(PersonBean bean) {
view.getPersonValue(bean);
}
@Override
public void getPersonValueFail(String error) {
view.getPersonValueFail(error);
}
@Override
public void getBanner(BannerBean bean) {
view.getBanner(bean);
}
@Override
public void getBannerFail(String error) {
view.getBannerFail(error);
}
@Override
public void getHomeFloors(BaseBean<Floors> bean) {
view.getHomeFloors(bean);
}
@Override
public void getHomeFloorsFail(String error) {
view.getHomeFloorsFail(error);
}
@Override
public void getHomeProducts(BaseBean<Products> bean) {
view.getHomeProducts(bean);
}
@Override
public void getHomeProductsFail(String error) {
view.getHomeProductsFail(error);
}
@Override
public void requestStart() {
view.requestStart();
}
@Override
public void requestEnd() {
view.requestEnd();
}
@Override
public void tokenFail() {
}
});
}
@Override
public void getServerData() {
}
@Override
public void getBanner() {
model.getBanner();
}
@Override
public void getHomeFloors() {
model.getHomeFloors();
}
@Override
public void getHomeProducts() {
model.getHomeProducts();
}
@Override
public void requestPersonValue(String token) {
model.requestPersonValue(token);
}
}
|
package uk.ac.cam.cares.jps.setupjob.test;
import org.json.JSONObject;
import org.junit.Test;
import uk.ac.cam.cares.jps.dispersion.episode.EpisodeAgent;
public class SetupJobTest {
@Test
public void testjob() {
JSONObject jo= new JSONObject();
jo.put("runWholeScript",true);
String datapath="C:\\JPS_DATA\\workingdir\\JPS_SCENARIO\\scenario\\base\\localhost_8080\\data\\21afbf75-1d47-407e-9569-505c684f7385";
try {
new EpisodeAgent().setUpJob(jo.toString(),datapath);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
}
}
|
package org.firstinspires.ftc.teamcode.hardwaremaps.motors;
import com.arcrobotics.ftclib.hardware.motors.Motor;
import com.arcrobotics.ftclib.hardware.motors.MotorEx;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.HardwareMap;
public class HowlersMotor implements Motor {
private DcMotor m_motor;
private double resetVal;
public static double TICKS_PER_REV;
public HowlersMotor(HardwareMap hMap, String name, double TPR) {
m_motor = hMap.get(DcMotor.class, name);
TICKS_PER_REV = TPR;
}
@Override
public void set(double speed) {
m_motor.setPower(speed);
}
@Override
public double get() {
return m_motor.getPower();
}
@Override
public void setInverted(boolean isInverted) {
m_motor.setDirection(!isInverted ? DcMotor.Direction.FORWARD : DcMotor.Direction.REVERSE);
}
@Override
public boolean getInverted() {
return m_motor.getDirection() == DcMotor.Direction.REVERSE;
}
@Override
public void disable() {
m_motor.close();
}
@Override
public String getDeviceType() {
return null;
}
@Override
public void pidWrite(double output) {
set(output);
}
@Override
public void stopMotor() {
set(0);
}
public double getEncoderCount() {
return m_motor.getCurrentPosition() - resetVal;
}
public void resetEncoder() {
resetVal += getEncoderCount();
}
public double getNumRevolutions() {
return getEncoderCount() / TICKS_PER_REV;
}
}
|
/*
* Copyright 2011-2016 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.config.model;
/**
* <p>
* The specified delivery channel name is not valid.
* </p>
*/
public class InvalidDeliveryChannelNameException extends com.amazonaws.services.config.model.AmazonConfigException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new InvalidDeliveryChannelNameException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public InvalidDeliveryChannelNameException(String message) {
super(message);
}
}
|
/*
* Copyright 2015-present Facebook, 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.facebook.buck.core.util.immutables;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.immutables.value.Value;
/**
* Tuple-style objects conforming to {@link BuckStyleImmutable} naming style.
*
* <p>Tuple-style objects have all attributes as constructor parameters, and do not have builders.
*
* @see <a href="http://immutables.github.io/immutable.html#tuples">Immutable user guide</a>
*/
@Value.Style(
typeImmutable = "*",
typeAbstract = "Abstract*",
get = {"is*", "get*"},
init = "set*",
visibility = Value.Style.ImplementationVisibility.PUBLIC,
allParameters = true,
defaults = @Value.Immutable(builder = false),
forceJacksonPropertyNames = false,
additionalJsonAnnotations = {JsonNaming.class}
)
@Target({ElementType.TYPE, ElementType.PACKAGE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface BuckStyleTuple {}
|
/**
* Copyright (C) 2019 Expedia 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.hotels.beans.transformer;
import com.hotels.beans.model.FieldMapping;
import com.hotels.beans.model.FieldTransformer;
/**
* Utility methods for populating Mutable, Immutable and Hybrid JavaBeans properties via reflection.
* The implementations are provided by BeanUtils.
*/
public interface Transformer {
/**
* Copies all properties from an object to a new one.
* @param sourceObj the source object
* @param targetClass the destination object class
* @param <T> the Source object type
* @param <K> the target object type
* @return a copy of the source object into the destination object
* @throws IllegalArgumentException if any parameter is invalid
*/
<T, K> K transform(T sourceObj, Class<? extends K> targetClass);
/**
* Copies all properties from an object to a new one.
* @param sourceObj the source object
* @param targetObject the destination object
* @param <T> the Source object type
* @param <K> the target object type
* @throws IllegalArgumentException if any parameter is invalid
*/
<T, K> void transform(T sourceObj, K targetObject);
/**
* Initializes the mapping between fields in the source object and the destination one.
* @param fieldMapping the field mapping
* @return the {@link Transformer} instance
*/
Transformer withFieldMapping(FieldMapping... fieldMapping);
/**
* Removes the field mapping for the given field.
* @param destFieldName the field name in the destination object
*/
void removeFieldMapping(String destFieldName);
/**
* Removes all the configured fields mapping.
*/
void resetFieldsMapping();
/**
* Initializes the field transformer functions. The transformer function returns directly the field value.
* @param fieldTransformer the fields transformer function
* @return the {@link Transformer} instance
*/
Transformer withFieldTransformer(FieldTransformer... fieldTransformer);
/**
* Removes the field transformer for the given field.
* @param destFieldName the field name in the destination object
*/
void removeFieldTransformer(String destFieldName);
/**
* Removes all the configured fields transformer.
*/
void resetFieldsTransformer();
/**
* It allows to configure the transformer in order to set a default value in case some field is missing in the source object.
* If set to true the default value is set, if false if it raises a: {@link com.hotels.beans.error.MissingFieldException} in case of missing fields.
* @param useDefaultValue true in case the default value should be set, false if it should raise a: {@link com.hotels.beans.error.MissingFieldException} in case of missing
* field.
* @return the {@link Transformer} instance
*/
Transformer setDefaultValueForMissingField(boolean useDefaultValue);
/**
* It allows to configure the transformer in order to apply a transformation function on all fields matching the given name without keeping in consideration their full path.
* If set to true the default value is set, if false if it raises a: {@link com.hotels.beans.error.MissingFieldException} in case of missing fields.
* @param useFlatTransformation indicates if the transformer function has to be performed on all fields matching the given name without keeping in consideration their full
* path.
* @return the {@link Transformer} instance
*/
Transformer setFlatFieldNameTransformation(boolean useFlatTransformation);
/**
* It allows to disable the object validation.
* @param validationDisabled if true the validation is skipped.
* @return the {@link Transformer} instance
*/
Transformer setValidationDisabled(boolean validationDisabled);
/**
* Allows to specify all the fields for which the transformation have to be skipped.
* @param fieldName the destination object's field(s) name that have to be skipped
* @return the {@link Transformer} instance
*/
Transformer skipTransformationForField(String... fieldName);
/**
* Removes all the configured fields to skip.
*/
void resetFieldsTransformationSkip();
}
|
package com.codingchili.core.storage.exception;
import com.codingchili.core.configuration.CoreStrings;
import com.codingchili.core.context.CoreException;
import com.codingchili.core.protocol.ResponseStatus;
/**
* Throw when attempting to put-if-absent but value is not absent.
*/
public class ValueAlreadyPresentException extends CoreException {
public ValueAlreadyPresentException(Object key) {
super(CoreStrings.getValueAlreadyPresent(key.toString()), ResponseStatus.CONFLICT);
}
}
|
package Services;
import java.io.*;
public class Subscribers_Handler
{
public static void Subscribers(String subscriber_name,String symbol)
{
String file_name = symbol+".txt";
FileOutputStream details;
try
{
details = new FileOutputStream(file_name,true);
PrintWriter file = new PrintWriter(details);
BufferedWriter store = new BufferedWriter(file);
try
{
store.write(subscriber_name+"\n");
store.newLine();
store.close();
file.close();
System.out.print("Subscription Add");
}
catch (IOException ex)
{
System.out.print("ERROR = "+ex);
}
}
catch (FileNotFoundException ex_02)
{
System.out.print("ERROR = "+ex_02);
}
}
}
|
/**
* 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 com.qlangtech.tis.runtime.pojo;
/**
* @author 百岁(baisui@qlangtech.com)
* @date 2012-5-9
*/
public class Node {
private final String name;
private final Integer pId;
private final Integer id;
public Node(String name, Integer pId, Integer id) {
super();
this.name = name;
this.pId = pId;
this.id = id;
}
public String getName() {
return name;
}
public Integer getpId() {
return pId;
}
public Integer getId() {
return id;
}
}
|
package com.github.seckillsystem.queue.kafka;
import com.github.seckillsystem.common.CommonResult;
import com.github.seckillsystem.common.redis.RedisUtil;
import com.github.seckillsystem.common.webSocket.WebSocketServer;
import com.github.seckillsystem.service.SeckillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class KafKaConsumer {
@Autowired
private SeckillService seckillService;
@Autowired
private RedisUtil redisUtil;
@KafkaListener(topics = {"seckill"})
public void receiveMessage(String message){
//收到通道的消息之后执行秒杀操作
String[] array = message.split(";");
/**
* 这里可以做重复消费的检查,防止重复消费。
* 根据业务要求,是否要求强一致性,如果要求强一致性,则可以根据订单唯一id用流水表记录,持久化到磁盘
* 非强一致性,可以用redis缓存暂时存取,设置失效时间。
*/
CommonResult result = seckillService.startThree(Long.parseLong(array[0]),Long.parseLong(array[1]));
if(result.getCode() == 200){
WebSocketServer.sendInfo(array[0].toString() + " " + "秒杀成功","");
}else{
WebSocketServer.sendInfo(array[0].toString() + " " + "秒杀失败","");
}
}
}
|
package pers.zhc.tools.utils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import pers.zhc.tools.BaseActivity;
import pers.zhc.u.FileU;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ExternalJNI {
private static String downloadURL;
private static String abi;
private static void fetch(Context ctx) throws IOException {
System.out.println("download remote libs");
System.out.println("abi = " + abi);
File libsDir = new File(ctx.getFilesDir(), "libs");
if (!libsDir.exists()) {
System.out.println("libsDir.mkdirs() = " + libsDir.mkdirs());
}
File file = new File(libsDir, "libex1.so");
HttpURLConnection connection = (HttpURLConnection) new URL(downloadURL).openConnection();
if (connection.getResponseCode() == 200) {
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream(file, false);
FileU.StreamWrite(is, os);
os.close();
is.close();
System.out.println("done");
}
}
private static String getABI() {
String[] ABIs = new String[]{
"arm64-v8a",
"armeabi-v7a",
"x86",
"x86_64"
};
List<String> supportedABIs = new ArrayList<>();
String abi = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Collections.addAll(supportedABIs, Build.SUPPORTED_ABIS);
} else {
//noinspection deprecation
supportedABIs.add(Build.CPU_ABI);
//noinspection deprecation
supportedABIs.add(Build.CPU_ABI2);
}
l:
for (String s : ABIs) {
for (String supportedABI : supportedABIs) {
if (s.equals(supportedABI)) {
abi = s;
break l;
}
}
}
return abi;
}
private static boolean check(String downloadURL, File localFile) {
try {
InputStream md5IS = new URL(downloadURL + "&md5").openStream();
InputStreamReader isr = new InputStreamReader(md5IS);
BufferedReader br = new BufferedReader(isr);
String md5 = br.readLine();
br.close();
isr.close();
md5IS.close();
String localMD5 = FileU.getMD5String(localFile);
System.out.println("localMD5 = " + localMD5);
return localMD5.equals(md5);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private static native void ex1(Activity activity);
@SuppressLint("UnsafeDynamicallyLoadedCode")
public static void ex(Activity activity) {
Handler handler = new Handler();
new Thread(() -> {
abi = getABI();
downloadURL = BaseActivity.Infos.ZHC_URL_STRING
+ "/tools_app/jni.zhc?abi=" + abi + "&name=libex1.so";
File libsDir = new File(activity.getFilesDir(), "libs");
if (!libsDir.exists()) {
System.out.println("libsDir.mkdirs() = " + libsDir.mkdirs());
}
File file = new File(libsDir, "libex1.so");
boolean check;
if (!file.exists()) {
check = false;
} else {
check = check(downloadURL, file);
}
try {
if (!check) {
fetch(activity);
}
if (file.exists()) {
try {
System.load(file.getCanonicalPath());
System.out.println("load remote lib");
handler.post(() -> {
try {
ex1(activity);
} catch (Exception e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
System.load(file.getAbsolutePath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
|
/* Copyright (c) 2019 AT&T Intellectual Property. #
# #
# 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.oran.otf.common.model.local;
import org.oran.otf.common.utility.gson.Convert;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
import java.util.Map;
import org.bson.types.ObjectId;
@JsonIgnoreProperties(ignoreUnknown = true)
public class WorkflowRequest implements Serializable {
private static final long serialVersionUID = 1L;
private boolean async = false;
private ObjectId executorId = null;
private ObjectId testInstanceId = null;
private Map<String, ParallelFlowInput> pfloInput = null;
private Map<String, Object> testData = null;
private Map<String, Object> vthInput = null;
private long maxExecutionTimeInMillis = 0L;
public WorkflowRequest() throws Exception {
this.validate();
}
public WorkflowRequest(
boolean async,
ObjectId executorId,
ObjectId testInstanceId,
Map<String, ParallelFlowInput> pfloInput,
Map<String, Object> testData,
Map<String, Object> vthInput,
int maxExecutionTimeInMillis)
throws Exception {
this.async = async;
this.executorId = executorId;
this.testInstanceId = testInstanceId;
this.pfloInput = pfloInput;
this.testData = testData;
this.vthInput = vthInput;
this.maxExecutionTimeInMillis = maxExecutionTimeInMillis;
this.validate();
}
public WorkflowRequest(
boolean async,
String executorId,
String testInstanceId,
Map<String, ParallelFlowInput> pfloInput,
Map<String, Object> testData,
Map<String, Object> vthInput,
int maxExecutionTimeInMillis)
throws Exception {
this.async = async;
this.executorId = new ObjectId(executorId);
this.testInstanceId = new ObjectId(testInstanceId);
this.pfloInput = pfloInput;
this.testData = testData;
this.vthInput = vthInput;
this.maxExecutionTimeInMillis = maxExecutionTimeInMillis;
this.validate();
}
private void validate() throws Exception {
String missingFieldFormat = "Missing required field %s.";
// if (this.async && this.asyncTopic == null) {
// throw new Exception(String.format(missingFieldFormat, "asyncTopic"));
// }
// Only required on the Camunda engine
// if (this.executorId == null) {
// throw new Exception(String.format(missingFieldFormat, "executorId"));
// }
// Only required on the Camunda engine
// if (this.testInstanceId == null) {
// throw new Exception(String.format(missingFieldFormat, "testInstanceId"));
// }
if (this.maxExecutionTimeInMillis < 0L) {
this.maxExecutionTimeInMillis = 0L;
}
}
public boolean isAsync() {
return async;
}
public void setAsync(boolean async) {
this.async = async;
}
public ObjectId getExecutorId() {
return executorId;
}
public void setExecutorId(ObjectId executorId) {
this.executorId = executorId;
}
public ObjectId getTestInstanceId() {
return testInstanceId;
}
public void setTestInstanceId(ObjectId testInstanceId) {
this.testInstanceId = testInstanceId;
}
public Map<String, ParallelFlowInput> getPfloInput() {
return pfloInput;
}
public void setPfloInput(Map<String, ParallelFlowInput> pfloInput) {
this.pfloInput = pfloInput;
}
public Map<String, Object> getTestData() {
return testData;
}
public void setTestData(Map<String, Object> testData) {
this.testData = testData;
}
public Map<String, Object> getVthInput() {
return vthInput;
}
public void setVthInput(Map<String, Object> vthInput) {
this.vthInput = vthInput;
}
public long getMaxExecutionTimeInMillis() {
return maxExecutionTimeInMillis;
}
public void setMaxExecutionTimeInMillis(long maxExecutionTimeInMillis) {
this.maxExecutionTimeInMillis = maxExecutionTimeInMillis;
}
@Override
public String toString() {
return Convert.objectToJson(this);
}
}
|
/**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Mon Nov 30 11:26:26 GMT 2020
*/
package freemind.controller;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
import org.junit.AfterClass;
import org.evosuite.runtime.sandbox.Sandbox;
import org.evosuite.runtime.sandbox.Sandbox.SandboxMode;
@EvoSuiteClassExclude
public class Controller_ESTest_scaffolding {
@org.junit.Rule
public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule();
private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone();
private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000);
@BeforeClass
public static void initEvoSuiteFramework() {
org.evosuite.runtime.RuntimeSettings.className = "freemind.controller.Controller";
org.evosuite.runtime.GuiSupport.initialize();
org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100;
org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000;
org.evosuite.runtime.RuntimeSettings.mockSystemIn = true;
org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED;
org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT();
org.evosuite.runtime.classhandling.JDKClassResetter.init();
setSystemProperties();
initializeClasses();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
}
@AfterClass
public static void clearEvoSuiteFramework(){
Sandbox.resetDefaultSecurityManager();
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
}
@Before
public void initTestCase(){
threadStopper.storeCurrentThreads();
threadStopper.startRecordingTime();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler();
org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode();
setSystemProperties();
org.evosuite.runtime.GuiSupport.setHeadless();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
org.evosuite.runtime.agent.InstrumentingAgent.activate();
}
@After
public void doneWithTestCase(){
threadStopper.killAndJoinClientThreads();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks();
org.evosuite.runtime.classhandling.JDKClassResetter.reset();
resetClasses();
org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode();
org.evosuite.runtime.agent.InstrumentingAgent.deactivate();
org.evosuite.runtime.GuiSupport.restoreHeadlessMode();
}
public static void setSystemProperties() {
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
java.lang.System.setProperty("file.encoding", "UTF-8");
java.lang.System.setProperty("java.awt.headless", "true");
java.lang.System.setProperty("java.io.tmpdir", "/tmp");
java.lang.System.setProperty("user.dir", "/home/ubuntu/termite/projects/105_freemind");
java.lang.System.setProperty("user.home", "/home/ubuntu");
java.lang.System.setProperty("user.language", "en");
java.lang.System.setProperty("user.name", "ubuntu");
java.lang.System.setProperty("user.timezone", "Etc/UTC");
java.lang.System.setProperty("sun.jnu.encoding", "UTF-8");
java.lang.System.setProperty("log4j.configuration", "SUT.log4j.properties");
}
private static void initializeClasses() {
org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(Controller_ESTest_scaffolding.class.getClassLoader() ,
"org.apache.xml.serializer.WriterToUTF8Buffered",
"org.mozilla.javascript.Context$WrapHandlerProxy",
"org.apache.xml.dtm.ref.IncrementalSAXSource",
"freemind.controller.Controller$OptionAntialiasAction",
"org.apache.xpath.objects.XRTreeFrag",
"freemind.controller.MapModuleManager$MapModuleChangeObserverCompound",
"org.apache.batik.dom.svg.SVGDOMImplementation$StyleElementFactory",
"org.apache.xalan.transformer.TransformSnapshot",
"org.hsqldb.lib.HsqlByteArrayOutputStream",
"org.apache.batik.util.EventDispatcher$Dispatcher",
"org.apache.xalan.templates.XSLTVisitor",
"org.apache.xalan.templates.ElemTemplateElement",
"org.apache.xpath.XPath",
"freemind.modes.mindmapmode.MindMapMapModel$LockManager",
"freemind.modes.attributes.ColumnWidthChangeListener",
"org.mozilla.javascript.NotAFunctionException",
"org.apache.xml.dtm.ref.DTMDefaultBaseIterators",
"org.apache.batik.dom.svg.SVGDOMImplementation$FontFaceFormatElementFactory",
"org.apache.fop.pdf.PDFState",
"org.apache.xpath.operations.UnaryOperation",
"org.mozilla.javascript.NativeFunction",
"org.apache.batik.css.engine.value.ShorthandManager$PropertyHandler",
"freemind.controller.actions.generated.instance.CollaborationWrongCredentials",
"freemind.view.mindmapview.MapView",
"org.apache.xalan.templates.ElemOtherwise",
"org.apache.batik.css.engine.value.svg.StrokeDashoffsetManager",
"org.apache.xpath.functions.FunctionMultiArgs",
"freemind.modes.attributes.AttributeRegistryComboBoxColumnModel",
"org.apache.batik.apps.svgbrowser.Main$FontSizeHandler",
"org.apache.batik.dom.svg.SVGOMDocument",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$ChildTraverser",
"org.apache.xalan.processor.ProcessorNamespaceAlias",
"org.apache.batik.gvt.text.Mark",
"org.apache.fop.fonts.FontSetup",
"freemind.view.mindmapview.NodeMotionListenerView",
"org.apache.xml.dtm.ref.DTMDefaultBase",
"org.openstreetmap.gui.jmapviewer.MemoryTileCache$CacheEntry",
"org.apache.batik.css.parser.ExtendedParser",
"org.openstreetmap.gui.jmapviewer.interfaces.Attributed",
"org.mozilla.javascript.tools.shell.ConsoleWriter",
"org.openstreetmap.gui.jmapviewer.tilesources.OsmTileSource$Mapnik",
"org.apache.xml.utils.XMLString",
"org.mozilla.javascript.ClassNameHelper",
"org.hsqldb.TriggerDef$TriggerData",
"org.apache.batik.gvt.RootGraphicsNode",
"org.apache.xml.dtm.DTMAxisTraverser",
"org.apache.log4j.Category",
"org.apache.batik.dom.svg.SVGDOMImplementation$AnimateElementFactory",
"org.apache.xpath.operations.Gt",
"org.apache.fop.fonts.type1.PFBData",
"org.hsqldb.lib.FileAccess",
"freemind.modes.mindmapmode.MindMapController",
"org.apache.xpath.XPathVisitor",
"freemind.controller.Controller$Closer",
"org.openstreetmap.gui.jmapviewer.Demo",
"org.apache.avalon.framework.CascadingThrowable",
"org.mozilla.javascript.Scriptable",
"org.apache.xml.serializer.Encodings",
"freemind.modes.browsemode.BrowseController",
"org.hsqldb.Index",
"org.apache.batik.gvt.renderer.ImageRendererFactory",
"com.jgoodies.forms.layout.CellConstraints$Alignment",
"freemind.main.FreeMindSecurityManager",
"org.openstreetmap.gui.jmapviewer.JMapController",
"org.apache.xml.serializer.ToXMLSAXHandler",
"org.apache.fop.pdf.PDFXObject",
"plugins.collaboration.socket.SocketBasics$UnableToGetLockException",
"org.apache.log4j.spi.NullWriter",
"org.apache.xpath.axes.WalkingIteratorSorted",
"freemind.controller.actions.generated.instance.NewNodeAction",
"org.apache.batik.css.engine.value.svg.ShapeRenderingManager",
"org.apache.xpath.axes.PredicatedNodeTest",
"org.apache.batik.apps.svgbrowser.Main",
"freemind.controller.actions.generated.instance.CollaborationRequireLock",
"org.apache.batik.dom.svg.SVGDOMImplementation$AnimateTransformElementFactory",
"org.apache.batik.swing.svg.SVGLoadEventDispatcherListener",
"org.apache.batik.svggen.SVGColor",
"org.apache.batik.apps.svgbrowser.JAuthenticator",
"org.apache.batik.util.SVGConstants",
"freemind.view.mindmapview.attributeview.AttributeTableModelDecoratorAdapter",
"org.apache.xalan.processor.ProcessorUnknown",
"freemind.controller.NodeDropListener",
"freemind.controller.StructuredMenuHolder$MenuEventSupplier",
"org.apache.batik.dom.svg.SVGDOMImplementation$LinearGradientElementFactory",
"org.apache.log4j.spi.RootCategory",
"org.mozilla.javascript.tools.debugger.FileWindow",
"org.openstreetmap.gui.jmapviewer.interfaces.MapRectangle",
"org.apache.xml.dtm.DTMManager",
"org.apache.batik.dom.AbstractDocument$IdSoftRef",
"org.apache.xalan.templates.ElemMessage",
"org.apache.xpath.objects.DTMXRTreeFrag",
"org.apache.xalan.processor.XSLTElementDef",
"org.apache.fop.fonts.FontDescriptor",
"accessories.plugins.time.TableSorter$2",
"accessories.plugins.time.TableSorter$1",
"org.hsqldb.jdbc.jdbcConnection",
"plugins.collaboration.database.DatabaseStarter$1",
"org.apache.batik.dom.AbstractCharacterData",
"freemind.controller.LastOpenedList",
"org.apache.batik.extension.svg.BatikExtConstants",
"freemind.controller.actions.generated.instance.CollaborationHello",
"org.mozilla.javascript.Function",
"com.jgoodies.forms.layout.ColumnSpec",
"freemind.modes.mindmapmode.actions.MindMapActions",
"plugins.map.MapMarkerBase",
"org.apache.xpath.XPathVisitable",
"org.apache.commons.io.output.CountingOutputStream",
"org.hsqldb.BaseMemoryNode",
"org.jibx.runtime.impl.MarshallingContext",
"org.apache.batik.apps.svgbrowser.AboutDialog",
"freemind.modes.mindmapmode.MindMapController$MindMapControllerPlugin",
"org.apache.batik.svggen.DefaultStyleHandler",
"freemind.controller.Controller$AboutAction",
"freemind.modes.attributes.AttributeController",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeGaussianBlurElementFactory",
"org.hsqldb.View",
"org.apache.xalan.processor.ProcessorText",
"freemind.controller.actions.generated.instance.PatternNodeBackgroundColor",
"org.apache.batik.apps.svgbrowser.JSVGViewerFrame$4",
"org.hsqldb.lib.HashMap",
"org.apache.batik.css.engine.value.css2.FontSizeAdjustManager",
"freemind.modes.FreeMindAwtFileDialog$FileAndDirFilter",
"org.apache.xalan.templates.OutputProperties",
"org.apache.xpath.functions.FuncString",
"org.apache.batik.bridge.UpdateManager$5",
"org.apache.batik.bridge.UpdateManager$4",
"org.apache.batik.bridge.UpdateManager$7",
"org.apache.batik.bridge.UpdateManager$6",
"org.apache.batik.bridge.UpdateManager$9",
"org.apache.batik.bridge.UpdateManager$8",
"org.apache.batik.dom.util.CSSStyleDeclarationFactory",
"org.apache.batik.bridge.ScriptingEnvironment",
"org.mozilla.javascript.optimizer.Codegen",
"org.apache.xpath.objects.GreaterThanComparator",
"org.mozilla.javascript.tools.debugger.ContextWindow",
"org.apache.xpath.objects.GreaterThanOrEqualComparator",
"org.apache.xalan.templates.ElemValueOf",
"org.apache.batik.dom.svg.SVGDOMImplementation$MaskElementFactory",
"freemind.modes.mindmapmode.actions.UseRichFormattingAction",
"freemind.controller.NodeMotionListener",
"org.mozilla.javascript.tools.debugger.SourceInfo",
"org.apache.batik.ext.awt.image.codec.ImageEncodeParam",
"freemind.main.Resources",
"org.apache.xpath.objects.XBoolean",
"freemind.modes.MapRegistry",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$NamespaceDeclsTraverser",
"org.apache.xml.serializer.OutputPropertiesFactory",
"freemind.view.mindmapview.MapView$CheckLaterForCenterNodeTask",
"freemind.controller.Controller$LicenseAction",
"org.hsqldb.Result",
"org.apache.xpath.axes.ChildIterator",
"org.apache.fop.fonts.base14.HelveticaOblique",
"freemind.controller.actions.generated.instance.MapWindowConfigurationStorage",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$PrecedingAndAncestorTraverser",
"org.apache.xalan.templates.ElemFallback",
"org.apache.fop.image.FopImage",
"org.apache.xalan.templates.XSLTVisitable",
"freemind.modes.mindmapmode.MindMapMapModel$DoAutomaticSave",
"org.apache.xml.serializer.EmptySerializer",
"freemind.modes.EdgeAdapter",
"freemind.modes.viewmodes.ViewControllerAdapter",
"org.apache.batik.Version",
"org.mozilla.javascript.ErrorReporter",
"org.apache.batik.css.engine.value.LengthManager",
"freemind.main.Tools$MindMapNodePair",
"freemind.main.FreeMindStarter",
"org.apache.log4j.spi.LoggerRepository",
"org.apache.xalan.templates.ElemAttribute",
"org.apache.batik.ext.awt.image.codec.ImageDecodeParam",
"org.apache.batik.svggen.SVGTransform",
"org.apache.batik.css.engine.value.IdentifierManager",
"org.apache.xml.serializer.ToHTMLStream$Trie$Node",
"org.apache.batik.dom.AbstractChildNode",
"org.apache.fop.fonts.base14.ZapfDingbats",
"org.apache.batik.i18n.LocalizableSupport",
"plugins.collaboration.socket.MindMapMaster$1",
"freemind.modes.LineAdapter",
"org.mozilla.javascript.tools.debugger.FileTextArea",
"org.apache.xpath.operations.Number",
"org.apache.xpath.functions.FuncExtFunctionAvailable",
"org.hsqldb.GrantConstants",
"org.apache.batik.css.engine.value.svg.SpacingManager",
"org.mozilla.javascript.debug.Debugger",
"freemind.controller.actions.generated.instance.Place",
"org.apache.batik.gvt.event.GraphicsNodeChangeAdapter",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeComponentTransferElementFactory",
"org.apache.fop.pdf.StreamCache",
"org.apache.xml.serializer.Serializer",
"freemind.controller.Controller$PageAction",
"org.hsqldb.Row",
"org.apache.xml.dtm.ref.DTMDefaultBaseIterators$DescendantIterator",
"com.jgoodies.forms.layout.FormLayout",
"org.apache.batik.css.engine.value.svg.ColorInterpolationFiltersManager",
"org.mozilla.classfile.JavaVariable",
"org.apache.batik.util.CleanerThread$ReferenceCleared",
"org.apache.batik.svggen.SVGCustomPaint",
"org.apache.log4j.Layout",
"freemind.modes.mindmapmode.actions.SingleNodeOperation",
"org.hsqldb.Table",
"freemind.main.FreeMindMain$VersionInformation",
"org.apache.batik.dom.AbstractNode$1",
"org.apache.xpath.functions.FuncExtFunction",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$AllFromRootTraverser",
"plugins.map.MapDialog",
"freemind.modes.mindmapmode.JAutoScrollBarPane",
"org.apache.batik.dom.svg.SVGDOMImplementation$CursorElementFactory",
"org.apache.xalan.processor.ProcessorAttributeSet",
"org.openstreetmap.gui.jmapviewer.interfaces.TileSource$TileUpdate",
"org.apache.xalan.processor.ProcessorGlobalVariableDecl",
"org.apache.fop.pdf.PDFFormXObject",
"org.apache.batik.svggen.DOMGroupManager",
"org.apache.batik.dom.AbstractNode",
"org.apache.xalan.templates.TemplateSubPatternAssociation",
"org.apache.batik.swing.svg.SVGLoadEventDispatcherEvent",
"freemind.controller.Controller$ShowSelectionAsRectangleAction",
"freemind.modes.mindmapmode.actions.xml.ActorXml",
"freemind.modes.browsemode.BrowseMode",
"freemind.modes.FreeMindAwtFileDialog",
"org.apache.batik.dom.svg.SVGDOMImplementation$MarkerElementFactory",
"org.openstreetmap.gui.jmapviewer.events.JMVCommandEvent",
"org.apache.fop.pdf.PDFState$Data",
"org.apache.batik.gvt.event.GraphicsNodeMouseListener",
"org.mozilla.javascript.FunctionNode",
"freemind.modes.browsemode.BrowseToolBar",
"org.apache.xalan.trace.SelectionEvent",
"org.apache.batik.dom.AbstractDOMImplementation",
"org.apache.fop.pdf.ASCII85Filter",
"org.mozilla.javascript.ClassShutter",
"org.apache.fop.fonts.FontType",
"freemind.controller.Controller$DisposeOnClose",
"org.apache.xalan.transformer.TreeWalker2Result",
"org.apache.batik.gvt.event.SelectionListener",
"org.apache.batik.swing.svg.GVTTreeBuilderEvent",
"freemind.extensions.PermanentNodeHook",
"plugins.map.MapNodePositionHolder",
"freemind.controller.MapMouseWheelListener",
"freemind.controller.FreeMindToolBar",
"org.apache.batik.swing.JSVGCanvas",
"org.apache.xml.serializer.EncodingInfo",
"freemind.modes.filemode.FileToolBar",
"org.apache.batik.util.Service",
"org.apache.batik.dom.svg.SVGDOMImplementation$SwitchElementFactory",
"freemind.view.mindmapview.attributeview.AttributeTable$MyFocusListener",
"org.apache.batik.script.Interpreter",
"freemind.controller.filter.util.SortedListModel",
"org.apache.batik.bridge.GVTBuilder",
"org.hsqldb.DiskNode",
"org.hsqldb.rowio.RowInputText",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeConvolveMatrixElementFactory",
"freemind.controller.filter.Filter",
"org.apache.log4j.spi.LoggerFactory",
"org.apache.batik.dom.events.DocumentEventSupport",
"org.apache.xalan.templates.ElemVariablePsuedo",
"org.apache.xml.dtm.ObjectFactory$ConfigurationError",
"org.apache.batik.svggen.StyleHandler",
"org.apache.batik.css.engine.value.svg.StrokeLinecapManager",
"org.apache.fop.pdf.PDFFilterList",
"org.apache.xpath.objects.Comparator",
"freemind.view.MapModule",
"org.apache.fop.util.ASCII85Constants",
"org.mozilla.javascript.optimizer.OptLocalVariable",
"org.hsqldb.index.RowIterator",
"freemind.controller.Controller$QuitAction",
"org.apache.xpath.functions.FuncLast",
"org.apache.xml.serializer.ToStream$BoolStack",
"org.apache.batik.css.parser.CSSLexicalUnit$StringLexicalUnit",
"org.apache.batik.dom.svg.SVGDOMImplementation$TrefElementFactory",
"org.apache.xml.dtm.ref.DTMDefaultBaseIterators$TypedChildrenIterator",
"freemind.controller.Controller$CloseAction",
"org.apache.xpath.functions.FuncSystemProperty",
"freemind.controller.actions.generated.instance.XmlAction",
"org.hsqldb.lib.ObjectComparator",
"freemind.controller.NodeKeyListener",
"org.hsqldb.BaseTable",
"org.apache.batik.dom.util.DoublyIndexedTable$Entry",
"org.apache.batik.svggen.ImageHandlerBase64Encoder",
"plugins.map.Registration$NodeVisibilityListener",
"org.apache.batik.svggen.SVGFilterDescriptor",
"org.apache.xalan.extensions.ExpressionVisitor",
"com.jgoodies.forms.builder.I15dPanelBuilder",
"org.apache.xalan.templates.ElemAttributeSet",
"org.apache.xml.utils.IntStack",
"org.apache.log4j.DefaultCategoryFactory",
"org.apache.batik.css.engine.value.AbstractValue",
"org.apache.xalan.trace.TraceManager",
"org.apache.xml.serializer.AttributesImplSerializer",
"org.apache.xpath.functions.FuncExtElementAvailable",
"org.apache.xalan.processor.ProcessorTemplate",
"org.apache.batik.dom.svg.SVGDOMImplementation$GElementFactory",
"org.hsqldb.Column",
"org.apache.batik.svggen.SVGRectangle",
"org.apache.xpath.axes.NodeSequence",
"freemind.modes.FreeMindAwtFileDialog$NullFilter",
"org.apache.xml.serializer.SecuritySupport",
"freemind.modes.ArrowLinkAdapter",
"org.apache.avalon.framework.configuration.Configuration",
"org.apache.batik.bridge.CursorManager",
"org.apache.xpath.objects.XNumber",
"org.apache.batik.dom.svg.SVGDOMImplementation$CircleElementFactory",
"org.apache.fop.pdf.PDFGState",
"org.apache.fop.util.CloseBlockerOutputStream",
"freemind.preferences.layout.OptionPanel$OptionPanelFeedback",
"org.apache.batik.css.engine.value.svg.KerningManager",
"freemind.modes.filemode.FileMapModel",
"org.apache.fop.fonts.base14.TimesItalic",
"org.apache.batik.dom.GenericDocumentType",
"org.hsqldb.rowio.RowOutputBase",
"org.apache.xpath.axes.IteratorPool",
"org.apache.batik.css.engine.ImportRule",
"freemind.view.mindmapview.attributeview.ReducedAttributeTableModelDecorator",
"freemind.controller.Controller$ToggleToolbarAction",
"org.apache.xpath.axes.WalkingIterator",
"freemind.controller.Controller$ToggleLeftToolbarAction",
"org.apache.batik.bridge.DocumentJarClassLoader",
"freemind.view.mindmapview.EditNodeBase",
"org.apache.batik.css.engine.value.svg.SVGColorManager",
"org.apache.xml.dtm.ref.sax2dtm.SAX2DTM",
"org.mozilla.javascript.tools.debugger.FileHeader",
"freemind.extensions.PermanentNodeHookAdapter",
"org.apache.batik.svggen.ErrorConstants",
"freemind.controller.filter.FilterInfo",
"org.apache.xalan.processor.ProcessorStylesheetElement",
"org.apache.batik.dom.events.NodeEventTarget",
"org.apache.batik.bridge.Viewport",
"org.apache.xpath.patterns.ContextMatchStepPattern",
"org.apache.xalan.templates.ElemWhen",
"org.apache.batik.util.gui.resource.ResourceFormatException",
"org.apache.fop.pdf.PDFResourceContext",
"org.mozilla.javascript.IRFactory",
"org.apache.batik.css.engine.value.StringMap",
"org.apache.batik.gvt.AbstractGraphicsNode",
"freemind.controller.Controller$DocumentationAction",
"org.apache.batik.util.gui.resource.ActionMap",
"org.apache.batik.swing.svg.GVTTreeBuilder$1",
"org.apache.batik.swing.svg.GVTTreeBuilder$2",
"org.apache.batik.swing.svg.GVTTreeBuilder$3",
"org.apache.batik.swing.svg.GVTTreeBuilder$4",
"org.apache.batik.svggen.SVGGraphics2DRuntimeException",
"freemind.controller.actions.generated.instance.TableColumnSetting",
"org.apache.fop.pdf.PDFEncryptionParams",
"org.apache.batik.svggen.SVGFilterConverter",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers",
"org.apache.xalan.templates.ElemTemplate",
"org.apache.xpath.functions.FuncContains",
"org.apache.batik.css.engine.value.svg.PointerEventsManager",
"com.jgoodies.forms.layout.ConstantSize",
"org.apache.xalan.processor.WhitespaceInfoPaths",
"org.apache.log4j.helpers.LogLog",
"org.apache.batik.gvt.filter.Mask",
"freemind.controller.actions.generated.instance.PatternScript",
"org.apache.batik.extension.svg.BatikDomExtension$FlowDivElementFactory",
"org.apache.xml.serializer.ToTextSAXHandler",
"org.apache.xml.dtm.ref.DTMDefaultBaseIterators$ChildrenIterator",
"org.apache.xpath.functions.FuncLang",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$PrecedingTraverser",
"freemind.modes.MapAdapter$FileChangeInspectorTimerTask",
"org.apache.log4j.or.DefaultRenderer",
"org.apache.xml.utils.IntVector",
"freemind.extensions.HookInstanciationMethod$DefaultDestinationNodesGetter",
"org.apache.batik.svggen.SVGArc",
"org.hsqldb.Expression",
"org.apache.commons.logging.impl.Log4JLogger",
"org.apache.batik.dom.AbstractParentNode$ElementsByTagNameNS",
"org.apache.log4j.Appender",
"org.apache.xalan.templates.ElemComment",
"org.apache.fop.fonts.type1.PFBParser",
"org.apache.batik.css.engine.StyleMap",
"org.apache.fop.pdf.PDFEncoding",
"org.apache.xml.serializer.ToTextStream",
"org.apache.xpath.functions.FuncNamespace",
"org.mozilla.javascript.NativeScript",
"freemind.main.StdFormatter",
"org.apache.log4j.spi.LoggingEvent",
"org.mozilla.javascript.WrapFactory",
"org.apache.batik.gvt.text.TextPaintInfo",
"org.apache.log4j.spi.ThrowableInformation",
"org.apache.xalan.templates.ElemExsltFunction",
"org.apache.batik.util.gui.ExtendedGridBagConstraints",
"org.apache.batik.svggen.SVGClipDescriptor",
"freemind.controller.filter.util.SortedMapListModel",
"org.apache.batik.css.parser.CSSLexicalUnit$PredefinedFunctionLexicalUnit",
"org.apache.batik.dom.svg.SVGDOMImplementation$ColorProfileElementFactory",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeFuncBElementFactory",
"freemind.modes.mindmapmode.MindMapXMLElement",
"freemind.controller.StructuredMenuItemHolder",
"org.apache.xml.res.XMLErrorResources",
"org.apache.batik.apps.svgbrowser.StatusBar$DisplayThread",
"org.apache.batik.bridge.UpdateManagerEvent",
"freemind.modes.mindmapmode.attributeactors.AttributeManagerDialog",
"org.apache.xalan.transformer.MsgMgr",
"org.apache.xml.utils.NamespaceSupport2",
"org.apache.batik.util.HaltingThread",
"freemind.controller.actions.generated.instance.MindmapLastStateStorage",
"org.apache.batik.util.RunnableQueue",
"org.mozilla.javascript.RegExpProxy",
"org.apache.xml.dtm.ref.IncrementalSAXSource_Filter",
"org.apache.batik.swing.svg.JSVGComponent$SVGListener",
"org.apache.xml.utils.SAXSourceLocator",
"org.apache.batik.util.gui.DOMViewer$Panel",
"org.apache.fop.pdf.PDFFunction",
"freemind.modes.browsemode.BrowsePopupMenu",
"plugins.map.FreeMindMapController$TileSourceStore",
"org.mozilla.javascript.optimizer.InvokerImpl",
"org.mozilla.javascript.EcmaError",
"org.mozilla.javascript.ClassRepository",
"org.jibx.runtime.IMarshallable",
"freemind.modes.attributes.AttributeTableLayoutModel",
"org.apache.fop.fonts.base14.CourierBold",
"org.openstreetmap.gui.jmapviewer.interfaces.TileSource",
"org.apache.avalon.framework.Enum",
"freemind.extensions.NodeHook",
"org.apache.batik.css.parser.CSSLexicalUnit$FunctionLexicalUnit",
"org.apache.xml.serializer.NamespaceMappings$MappingRecord",
"org.apache.xpath.functions.FuncNumber",
"org.apache.batik.dom.svg.SVGDOMImplementation$TitleElementFactory",
"org.apache.batik.css.engine.value.svg.SVGValueConstants",
"org.apache.batik.i18n.LocaleGroup",
"org.apache.fop.pdf.PDFFontTrueType",
"freemind.modes.browsemode.BrowseCloudModel",
"org.apache.xml.dtm.ref.DTMAxisIteratorBase",
"freemind.view.mindmapview.attributeview.AttributePopupMenu",
"org.apache.batik.svggen.SVGFontDescriptor",
"freemind.controller.Controller$NavigationNextMapAction",
"freemind.modes.FreeMindFileDialog",
"org.mozilla.javascript.debug.DebuggableObject",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeSpecularLightingElementFactory",
"org.apache.batik.dom.svg.SVGDOMImplementation$LineElementFactory",
"org.openstreetmap.gui.jmapviewer.Tile",
"org.apache.xpath.operations.Gte",
"org.openstreetmap.gui.jmapviewer.tilesources.OsmTileSource$OsmaSource",
"org.apache.batik.extension.svg.BatikDomExtension$FlowRegionElementFactory",
"org.apache.batik.gvt.TextNode",
"org.jibx.runtime.IMarshallingContext",
"org.apache.xml.dtm.ref.ExpandedNameTable$HashEntry",
"org.apache.xalan.templates.StylesheetComposed",
"org.apache.xml.serializer.OutputPropertiesFactory$1",
"org.apache.xalan.templates.TemplateList$TemplateWalker",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeMergeElementFactory",
"freemind.view.mindmapview.attributeview.AttributeView",
"org.apache.xpath.XPathException",
"freemind.modes.mindmapmode.actions.NewChildAction",
"org.apache.batik.css.engine.value.svg.GlyphOrientationHorizontalManager",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeDiffuseLightingElementFactory",
"org.apache.batik.ext.awt.g2d.TransformType",
"org.apache.xpath.Expression",
"freemind.controller.Controller$ShowAllAttributesAction",
"org.apache.batik.util.AbstractParsedURLProtocolHandler",
"org.hsqldb.rowio.RowOutputInterface",
"org.apache.fop.pdf.PDFPattern",
"org.openstreetmap.gui.jmapviewer.interfaces.TileCache",
"org.apache.commons.io.output.ProxyOutputStream",
"org.apache.batik.dom.svg.SVGDOMImplementation$MpathElementFactory",
"org.mozilla.javascript.tools.debugger.JTreeTable",
"com.jgoodies.forms.layout.FormSpec",
"org.jibx.runtime.impl.UnmarshallingContext",
"org.apache.batik.extension.svg.BatikDomExtension$FlowRegionBreakElementFactory",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$FollowingSiblingTraverser",
"org.apache.batik.css.engine.value.svg.ClipPathManager",
"org.apache.xpath.axes.OneStepIterator",
"freemind.controller.Controller$OptionSelectionMechanismAction",
"org.apache.batik.css.engine.value.css2.UnicodeBidiManager",
"org.apache.batik.gvt.PatternPaint",
"freemind.main.LogFileLogHandler$LogReceiver",
"freemind.modes.MindIcon",
"org.apache.batik.swing.gvt.GVTTreeRenderer",
"org.apache.xml.serializer.CharInfo$1",
"plugins.collaboration.database.DatabaseBasics$FormDialogValidator",
"org.apache.batik.dom.util.HashTable$Entry",
"org.apache.xml.serializer.TransformStateSetter",
"org.apache.batik.util.XMLResourceDescriptor",
"org.apache.xpath.patterns.NodeTest",
"freemind.main.ExampleFileFilter",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeColorMatrixElementFactory",
"org.apache.xalan.templates.ElemApplyImport",
"org.apache.batik.dom.svg.SVGDOMImplementation$AltGlyphItemElementFactory",
"org.apache.batik.script.InterpreterPool",
"org.apache.batik.css.engine.value.css2.FontSizeManager",
"freemind.controller.actions.generated.instance.MenuStructure",
"org.apache.fop.pdf.PDFColorSpace",
"org.apache.batik.ext.awt.image.renderable.ClipRable",
"org.apache.xml.serializer.ToUnknownStream",
"org.apache.batik.swing.gvt.JGVTComponent",
"org.apache.avalon.framework.CascadingException",
"freemind.modes.browsemode.BrowseMapModel",
"org.openstreetmap.gui.jmapviewer.DefaultMapController",
"org.apache.xalan.templates.ElemExsltFuncResult",
"org.apache.fop.pdf.PDFShading",
"org.jibx.runtime.impl.BackFillReference",
"org.apache.batik.dom.svg.SVGDOMImplementation$SetElementFactory",
"org.apache.batik.css.engine.value.svg.StrokeLinejoinManager",
"org.apache.batik.dom.svg.SVGDOMImplementation$AltGlyphElementFactory",
"org.apache.xpath.functions.Function2Args",
"org.apache.xml.serializer.SecuritySupport12",
"org.apache.batik.css.engine.CSSStylableElement",
"freemind.controller.actions.generated.instance.CompoundAction",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeMorphologyElementFactory",
"org.apache.batik.util.gui.resource.ResourceManager",
"freemind.modes.ModeController$NodeSelectionListener",
"org.apache.xml.utils.StringVector",
"org.mozilla.javascript.tools.debugger.JTreeTable$TreeTableCellRenderer",
"org.apache.xpath.patterns.UnionPattern",
"org.openstreetmap.gui.jmapviewer.Coordinate",
"org.apache.xml.utils.FastStringBuffer",
"org.apache.batik.css.engine.value.StringValue",
"org.apache.batik.bridge.BridgeExtension",
"org.apache.batik.dom.svg.SVGDOMImplementation$GlyphElementFactory",
"org.apache.xalan.processor.ProcessorCharacters",
"freemind.modes.attributes.AttributeRegistry",
"org.apache.batik.bridge.UserAgent",
"org.hsqldb.PointerNode",
"org.mozilla.javascript.BaseFunction",
"org.apache.batik.css.engine.value.svg.ColorInterpolationManager",
"org.apache.xpath.operations.NotEquals",
"freemind.controller.filter.util.ExtendedComboBoxModel",
"org.apache.batik.css.parser.CSSLexicalUnit$SimpleLexicalUnit",
"freemind.modes.HistoryInformation",
"plugins.collaboration.database.DatabaseBasics",
"org.apache.xalan.extensions.ExtensionHandler",
"freemind.modes.filemode.FileController",
"org.apache.xalan.processor.ProcessorStripSpace",
"freemind.main.FreeMindMain$StartupDoneListener",
"org.apache.batik.gvt.event.GraphicsNodeMouseEvent",
"org.openstreetmap.gui.jmapviewer.tilesources.AbstractTileSource",
"freemind.controller.actions.generated.instance.PatternEdgeWidth",
"org.apache.batik.svggen.SVGHintsDescriptor",
"org.hsqldb.store.BaseHashMap",
"freemind.controller.FreeMindPopupMenu",
"org.apache.xalan.templates.ElemCopyOf",
"org.apache.batik.ext.awt.RadialGradientPaint",
"org.mozilla.javascript.EvaluatorException",
"org.apache.xml.serializer.utils.StringToIntTable",
"org.apache.batik.dom.events.EventSupport",
"org.apache.batik.css.engine.value.css2.DirectionManager",
"org.apache.xpath.objects.LessThanComparator",
"freemind.modes.common.plugins.MapNodePositionHolderBase",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$AncestorOrSelfTraverser",
"freemind.controller.filter.condition.SelectedViewCondition",
"freemind.controller.NodeDragListener",
"org.apache.xalan.templates.FuncKey",
"org.apache.xpath.objects.XRTreeFragSelectWrapper",
"freemind.controller.MapModuleManager$MapModuleChangeObserver",
"org.apache.batik.bridge.svg12.SVG12BridgeExtension",
"org.apache.batik.gvt.CanvasGraphicsNode",
"org.apache.batik.svggen.SVGFont",
"org.apache.xpath.functions.FuncLocalPart",
"org.apache.batik.bridge.UpdateManager$10",
"freemind.main.FeedBack",
"org.apache.xpath.functions.FuncFloor",
"org.apache.xml.serializer.SecuritySupport12$1",
"org.apache.xml.serializer.SecuritySupport12$2",
"org.apache.xml.serializer.SecuritySupport12$6",
"org.apache.xml.serializer.SecuritySupport12$3",
"org.apache.xml.serializer.SecuritySupport12$4",
"org.apache.xml.utils.XMLStringFactory",
"org.apache.xalan.transformer.TransformState",
"org.apache.xml.serializer.ToHTMLStream$Trie",
"org.mozilla.javascript.debug.DebuggableScript",
"org.apache.xml.res.XMLMessages",
"org.apache.batik.css.engine.value.css2.CursorManager",
"org.apache.xml.dtm.ref.DTMDefaultBaseIterators$TypedDescendantIterator",
"freemind.modes.browsemode.BrowseXMLElement",
"org.apache.batik.extension.svg.BatikDomExtension$ColorSwitchElementFactory",
"org.apache.batik.dom.svg.SVGDOMImplementation$PolylineElementFactory",
"org.mozilla.javascript.optimizer.OptClassNameHelper$DefaultRepository",
"org.apache.fop.pdf.PDFFilter",
"org.apache.batik.dom.svg.SVGDOMImplementation$AltGlyphDefElementFactory",
"org.hsqldb.Collation",
"freemind.modes.mindmapmode.actions.xml.AbstractXmlAction",
"org.openstreetmap.gui.jmapviewer.events.JMVCommandEvent$COMMAND",
"org.apache.xpath.XPathProcessorException",
"freemind.controller.StructuredMenuHolder$StructuredMenuListener",
"org.apache.log4j.PropertyConfigurator",
"freemind.controller.actions.generated.instance.PatternEdgeStyle",
"org.apache.batik.svggen.SVGLinearGradient",
"freemind.extensions.NodeHookAdapter",
"org.apache.xml.dtm.SecuritySupport12",
"freemind.modes.mindmapmode.MindMapArrowLinkModel",
"org.mozilla.javascript.IdFunction",
"org.apache.batik.dom.svg.SVGDOMImplementation$FePointLightElementFactory",
"freemind.view.mindmapview.MainView",
"org.apache.xalan.processor.ProcessorPreserveSpace",
"org.apache.fop.util.ASCII85OutputStream",
"org.apache.batik.svggen.DefaultErrorHandler",
"org.apache.fop.pdf.PDFFontType1",
"org.apache.fop.pdf.PDFFontType0",
"freemind.modes.LinkAdapter",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeSpotLightElementFactory",
"org.apache.batik.script.Window$URLResponseHandler",
"org.apache.xpath.objects.XString",
"org.openstreetmap.gui.jmapviewer.OsmTileLoader",
"org.apache.batik.dom.svg.SVGDOMImplementation$TspanElementFactory",
"org.apache.xml.utils.BoolStack",
"org.apache.batik.gvt.event.GraphicsNodeEvent",
"org.apache.batik.ext.awt.geom.RectListManager",
"org.apache.xalan.templates.ElemCallTemplate",
"org.apache.batik.dom.svg.SVGDOMImplementation$StopElementFactory",
"org.hsqldb.SessionManager",
"org.apache.xml.serializer.TreeWalker",
"org.apache.fop.pdf.PDFCMap",
"org.apache.batik.gvt.event.AWTEventDispatcher",
"org.apache.batik.bridge.BridgeException",
"org.apache.xalan.transformer.StackGuard",
"org.apache.batik.swing.svg.SVGLoadEventDispatcher",
"org.apache.xml.serializer.WriterChain",
"org.hsqldb.Select",
"org.apache.xalan.trace.TraceListener",
"freemind.modes.browsemode.EncryptedBrowseNode",
"plugins.collaboration.socket.SocketBasics",
"org.apache.fop.pdf.FlateFilter",
"org.apache.batik.css.parser.CSSLexicalUnit",
"org.apache.xalan.processor.ProcessorKey",
"org.apache.batik.dom.DomExtension",
"org.apache.batik.css.engine.CSSEngine$MainPropertyReceiver",
"org.apache.fop.pdf.PDFInternalLink",
"freemind.modes.ControllerAdapter$OpenAction",
"freemind.view.mindmapview.NodeViewVisitor",
"freemind.modes.mindmapmode.actions.xml.ActionHandler",
"org.apache.batik.script.rhino.RhinoInterpreterFactory",
"org.apache.xpath.compiler.OpMapVector",
"org.apache.batik.svggen.SVGIDGenerator",
"freemind.controller.StructuredMenuHolder$MenuItemAdder",
"org.apache.xml.dtm.DTMConfigurationException",
"org.apache.xml.utils.WrappedRuntimeException",
"org.apache.xml.serializer.ElemContext",
"org.apache.xpath.ExtensionsProvider",
"freemind.controller.actions.generated.instance.CollaborationTransaction",
"org.hsqldb.persist.CachedObject",
"org.apache.batik.css.engine.value.svg.DominantBaselineManager",
"org.apache.batik.dom.AbstractDocument",
"org.apache.fop.fonts.base14.Courier",
"freemind.modes.mindmapmode.actions.xml.ActionPair",
"org.apache.batik.css.engine.value.svg.GlyphOrientationVerticalManager",
"org.apache.xpath.operations.Equals",
"freemind.modes.mindmapmode.actions.xml.UndoActionHandler",
"org.openstreetmap.gui.jmapviewer.JobDispatcher$JobThread",
"org.hsqldb.Grantee",
"org.apache.batik.svggen.SVGEllipse",
"org.apache.xml.utils.Context2",
"freemind.common.PropertyBean",
"org.apache.xml.utils.XMLStringDefault",
"org.apache.batik.swing.svg.LinkActivationEvent",
"org.apache.batik.util.CleanerThread$SoftReferenceCleared",
"org.apache.batik.apps.svgbrowser.XMLPreferenceManager$XMLProperties",
"org.apache.fop.pdf.PDFResources",
"freemind.controller.Controller$PrintPreviewAction",
"org.apache.xpath.axes.PathComponent",
"org.apache.xml.dtm.DTMException",
"org.apache.batik.extension.svg.BatikDomExtension$FlowTextElementFactory",
"org.apache.xml.utils.DOMHelper",
"org.apache.fop.pdf.PDFGoTo",
"org.apache.xpath.functions.FunctionDef1Arg",
"org.apache.xpath.compiler.Keywords",
"org.openstreetmap.gui.jmapviewer.tilesources.AbstractOsmTileSource",
"org.apache.xml.serializer.ExtendedContentHandler",
"org.apache.batik.css.engine.value.css2.SrcManager",
"freemind.controller.LastStateStorageManagement",
"org.apache.xalan.templates.DecimalFormatProperties",
"org.hsqldb.persist.PersistentStore",
"freemind.main.Tools$IntHolder",
"org.apache.batik.dom.util.DoublyIndexedTable",
"org.apache.batik.css.engine.value.svg.TextAnchorManager",
"freemind.view.mindmapview.MultipleImage",
"org.apache.log4j.spi.Configurator",
"org.apache.xalan.templates.XUnresolvedVariableSimple",
"org.apache.xml.serializer.NamespaceMappings",
"org.apache.xml.serializer.utils.WrappedRuntimeException",
"accessories.plugins.time.TableSorter$Row",
"freemind.controller.actions.generated.instance.PatternIcon",
"org.apache.xalan.extensions.ExpressionContext",
"org.hsqldb.store.HashIndex",
"org.apache.xpath.functions.FuncCount",
"org.apache.batik.extension.svg.BatikDomExtension$FlowParaElementFactory",
"org.apache.batik.util.RunnableQueue$Link",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$DescendantOrSelfTraverser",
"org.apache.fop.util.CMYKColorSpace",
"org.hsqldb.lib.FileAccess$FileSync",
"org.apache.xml.serializer.ToXMLStream",
"freemind.extensions.HookAdapter",
"org.apache.batik.dom.svg.SVGDOMImplementation$PathElementFactory",
"org.apache.batik.swing.svg.LinkActivationListener",
"freemind.modes.mindmapmode.actions.NodeColorBlendAction$1",
"freemind.controller.actions.generated.instance.PatternEdgeColor",
"org.apache.batik.swing.svg.SVGUserAgent",
"org.apache.xalan.processor.ProcessorStylesheetDoc",
"org.openstreetmap.gui.jmapviewer.OsmFileCacheTileLoader",
"org.openstreetmap.gui.jmapviewer.AttributionSupport",
"freemind.main.FreeMindCommon",
"org.apache.batik.util.RunnableQueue$LockableLink",
"org.apache.fop.svg.PDFGraphicsConfiguration",
"plugins.collaboration.database.DatabaseStarter",
"org.apache.log4j.LogManager",
"org.apache.batik.apps.svgbrowser.Main$OptionHandler",
"plugins.map.JCursorMapViewer",
"org.apache.xpath.functions.FuncStartsWith",
"org.mozilla.javascript.tools.debugger.ScopeProvider",
"freemind.controller.actions.generated.instance.WindowConfigurationStorage",
"org.apache.batik.dom.svg.SVGDOMImplementation$SvgElementFactory",
"org.apache.xalan.processor.ProcessorLRE",
"org.apache.log4j.or.RendererMap",
"org.apache.batik.dom.svg.SVGDOMImplementation$DefsElementFactory",
"freemind.controller.StructuredMenuHolder$MenuAdderCreator",
"org.apache.batik.gvt.CompositeGraphicsNode",
"org.hsqldb.store.ValuePool",
"org.jibx.runtime.ICharacterEscaper",
"org.apache.xalan.transformer.KeyManager",
"org.apache.xml.dtm.SecuritySupport12$1",
"org.apache.fop.pdf.PDFFontNonBase14",
"org.hsqldb.SubQuery",
"org.apache.batik.dom.AbstractStylableDocument",
"org.jibx.runtime.JiBXException",
"org.apache.xpath.axes.ReverseAxesWalker",
"org.apache.xml.utils.QName",
"org.apache.xml.utils.SuballocatedIntVector",
"org.mozilla.javascript.Script",
"org.apache.xpath.axes.SubContextList",
"org.apache.xml.dtm.ref.DTMTreeWalker",
"org.apache.xml.dtm.DTMIterator",
"freemind.common.NumberProperty",
"org.apache.xpath.axes.LocPathIterator",
"freemind.extensions.HookFactory",
"org.apache.batik.swing.gvt.JGVTComponent$3",
"org.apache.batik.ext.awt.LinearGradientPaint",
"org.apache.batik.css.engine.value.svg.ClipRuleManager",
"org.apache.xml.serializer.ObjectFactory$ConfigurationError",
"freemind.modes.mindmapmode.actions.NodeGeneralAction",
"org.mozilla.javascript.InterpretedFunction",
"freemind.controller.actions.generated.instance.PatternNodeStyle",
"plugins.map.FreeMindMapController$CursorPositionListener",
"org.hsqldb.SessionInterface",
"org.mozilla.javascript.tools.debugger.Menubar",
"org.mozilla.javascript.NativeObject",
"freemind.modes.mindmapmode.MindMapMapModel$ReaderCreator",
"org.apache.batik.css.engine.value.svg.FilterManager",
"org.apache.batik.css.engine.value.svg.GlyphOrientationManager",
"org.apache.xpath.XPathContext",
"org.apache.batik.dom.util.DocumentDescriptor",
"org.apache.batik.css.engine.value.svg.AlignmentBaselineManager",
"freemind.controller.filter.condition.IconNotContainedCondition",
"org.apache.xalan.templates.ElemNumber",
"org.openstreetmap.gui.jmapviewer.tilesources.AbstractTMSTileSource",
"org.apache.xml.dtm.ref.DTMDefaultBaseIterators$InternalAxisIteratorBase",
"org.apache.batik.dom.svg.SVGDOMImplementation$VkernElementFactory",
"freemind.modes.mindmapmode.MindMapNodeModel",
"org.apache.batik.apps.svgbrowser.XMLPreferenceManager",
"org.apache.xml.dtm.ref.DTMManagerDefault",
"org.apache.batik.css.engine.value.svg.MarkerShorthandManager",
"org.apache.batik.svggen.SVGPaint",
"freemind.controller.actions.generated.instance.CollaborationWelcome",
"org.apache.batik.swing.svg.SVGDocumentLoader",
"org.hsqldb.Index$IndexRowIterator",
"org.apache.batik.svggen.SVGGraphicContext",
"freemind.controller.Controller",
"freemind.modes.ControllerAdapter",
"freemind.extensions.ModeControllerHookAdapter",
"org.apache.xpath.axes.NodeSequence$IteratorCache",
"com.jgoodies.forms.builder.DefaultFormBuilder",
"org.apache.xpath.axes.AttributeIterator",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeTileElementFactory",
"org.apache.batik.svggen.SVGBufferedImageOp",
"org.apache.fop.pdf.PDFFont",
"org.apache.log4j.Logger",
"org.apache.batik.css.engine.value.svg.StrokeMiterlimitManager",
"freemind.modes.common.GotoLinkNodeAction",
"freemind.controller.actions.generated.instance.MindmapLastStateMapStorage",
"org.apache.xpath.objects.XNull",
"org.apache.batik.util.Base64EncoderStream",
"org.apache.avalon.framework.configuration.ConfigurationException",
"org.apache.xml.utils.XMLStringFactoryDefault",
"org.apache.xpath.functions.FuncRound",
"org.apache.batik.css.engine.value.svg.OpacityManager",
"org.apache.xml.serializer.SerializerConstants",
"freemind.controller.Controller$ZoomOutAction",
"org.apache.batik.util.BatikSecurityManager",
"org.apache.batik.ext.awt.image.renderable.Filter",
"org.hsqldb.persist.DataFileCache",
"org.apache.batik.svggen.SVGGraphicContextConverter",
"org.apache.batik.swing.gvt.JGVTComponent$Listener",
"org.hsqldb.persist.HsqlDatabaseProperties",
"org.apache.xpath.operations.Mult",
"freemind.controller.actions.generated.instance.Pattern",
"org.apache.xpath.functions.FuncTrue",
"org.apache.xalan.extensions.ExtensionNamespacesManager",
"org.apache.xalan.templates.KeyDeclaration",
"org.apache.batik.css.engine.value.svg.BaselineShiftManager",
"plugins.map.MapDialog$CloseAction",
"freemind.modes.mindmapmode.attributeactors.AttributeRegistryTable$ButtonRenderer",
"org.apache.batik.css.engine.value.css2.FontVariantManager",
"org.openstreetmap.gui.jmapviewer.tilesources.OsmTileSource$CycleMap",
"org.apache.fop.pdf.PDFNumber",
"freemind.controller.actions.generated.instance.PatternNodeColor",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeTurbulenceElementFactory",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeFuncAElementFactory",
"org.apache.fop.util.ASCIIHexOutputStream",
"org.apache.log4j.spi.HierarchyEventListener",
"org.hsqldb.TableFilter",
"org.mozilla.javascript.SecurityController",
"org.apache.batik.swing.svg.JSVGComponent",
"org.apache.fop.pdf.PDFImage",
"org.apache.xml.dtm.SecuritySupport12$6",
"org.apache.xml.dtm.SecuritySupport12$7",
"freemind.controller.actions.generated.instance.PlaceNodeXmlAction",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$AncestorTraverser",
"org.apache.xml.dtm.SecuritySupport12$2",
"org.apache.fop.pdf.PDFFileSpec",
"org.apache.xml.dtm.SecuritySupport12$3",
"org.apache.xml.dtm.SecuritySupport12$4",
"org.openstreetmap.gui.jmapviewer.TileController",
"com.jgoodies.forms.builder.AbstractFormBuilder",
"freemind.controller.Controller$ToggleMenubarAction",
"org.hsqldb.Session",
"freemind.controller.actions.generated.instance.CollaborationGoodbye",
"org.apache.batik.svggen.SVGSyntax",
"org.apache.fop.fonts.base14.CourierBoldOblique",
"org.apache.xalan.transformer.TransformerImpl",
"org.apache.fop.fonts.CIDFont",
"org.apache.batik.dom.svg.SVGDOMImplementation$FontElementFactory",
"freemind.main.Tools$BooleanHolder",
"freemind.controller.actions.generated.instance.CollaborationUserInformation",
"freemind.view.mindmapview.attributeview.AttributeTable",
"org.apache.xml.utils.ObjectStack",
"org.apache.xalan.res.XSLTErrorResources",
"org.apache.xalan.templates.ElemIf",
"freemind.main.Tools",
"org.apache.batik.swing.svg.GVTTreeBuilder",
"org.apache.xalan.extensions.ExtensionsTable",
"freemind.controller.filter.FilterComposerDialog",
"org.openstreetmap.gui.jmapviewer.JobDispatcher",
"freemind.modes.attributes.AttributeRegistryElement",
"freemind.modes.filemode.FileMode",
"org.apache.xpath.compiler.XPathParser",
"org.apache.xpath.objects.XNodeSet",
"org.apache.fop.pdf.PDFLink",
"org.apache.batik.apps.svgbrowser.JSVGViewerFrame",
"org.apache.log4j.spi.Filter",
"plugins.map.TileImage",
"org.apache.xml.serializer.ToHTMLStream",
"org.apache.batik.bridge.RepaintManager",
"org.apache.batik.svggen.AbstractSVGConverter",
"freemind.controller.Controller$OpenURLAction",
"org.hsqldb.lib.IntKeyHashMap",
"org.mozilla.javascript.tools.debugger.JSInternalConsole",
"org.apache.batik.css.engine.value.css2.VisibilityManager",
"freemind.modes.mindmapmode.attributeactors.AttributeRegistryTable",
"org.apache.xalan.transformer.CountersTable",
"org.apache.fop.pdf.PDFAction",
"org.hsqldb.lib.Collection",
"freemind.controller.MenuItemSelectedListener",
"freemind.controller.filter.condition.ConditionFactory",
"freemind.controller.actions.generated.instance.MoveNodesAction",
"org.apache.batik.dom.AbstractParentNode$ElementsByTagName",
"org.openstreetmap.gui.jmapviewer.JMapViewer$3",
"freemind.controller.Controller$1",
"org.openstreetmap.gui.jmapviewer.JMapViewer$2",
"freemind.controller.Controller$4",
"org.openstreetmap.gui.jmapviewer.interfaces.JMapViewerEventListener",
"plugins.map.MapDialog$ResultTableModel",
"org.apache.fop.pdf.NullFilter",
"freemind.controller.Controller$2",
"freemind.controller.Controller$3",
"org.openstreetmap.gui.jmapviewer.JMapViewer",
"org.apache.batik.dom.svg.SVGDOMImplementation$ClipPathElementFactory",
"freemind.controller.MenuItemEnabledListener",
"org.apache.batik.swing.gvt.JGVTComponentListener",
"org.apache.batik.css.engine.value.svg.StrokeWidthManager",
"org.apache.xalan.templates.WhiteSpaceInfo",
"org.apache.xalan.templates.ElemTextLiteral",
"freemind.controller.actions.generated.instance.CollaborationWhoAreYou",
"org.mozilla.javascript.JavaScriptException",
"org.apache.xpath.functions.WrongNumberArgsException",
"org.apache.batik.svggen.SVGAlphaComposite",
"org.apache.batik.svggen.SVGTransform$1",
"org.openstreetmap.gui.jmapviewer.JMapViewer$1",
"org.apache.batik.gvt.filter.GraphicsNodeRable",
"freemind.view.mindmapview.attributeview.AttributeTableCellRenderer",
"org.apache.batik.svggen.SVGCustomComposite",
"org.apache.log4j.helpers.OptionConverter",
"org.apache.batik.gvt.TextPainter",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeFloodElementFactory",
"freemind.controller.NodeMotionListener$NodeMotionAdapter",
"org.openstreetmap.gui.jmapviewer.interfaces.TileLoaderListener",
"com.jgoodies.forms.layout.FormLayout$LayoutInfo",
"freemind.modes.ControllerAdapter$ControllerPopupMenuListener",
"org.apache.xalan.templates.XUnresolvedVariable",
"org.hsqldb.lib.Iterator",
"org.apache.xpath.functions.FuncSum",
"org.apache.batik.svggen.SVGGraphicObjectConverter",
"org.mozilla.javascript.ImporterTopLevel",
"org.apache.batik.apps.svgbrowser.StatusBar",
"org.apache.xalan.templates.ElemSort",
"org.apache.xalan.transformer.DecimalToRoman",
"freemind.modes.MindMapLink",
"freemind.extensions.HookInstanciationMethod$RootDestinationNodesGetter",
"freemind.view.mindmapview.attributeview.ExtendedAttributeTableModelDecorator",
"org.openstreetmap.gui.jmapviewer.interfaces.MapPolygon",
"org.apache.fop.fonts.FontMetrics",
"freemind.modes.MindMapLine",
"org.apache.batik.css.engine.CSSEngine$2",
"org.apache.batik.css.engine.value.svg.MaskManager",
"org.openstreetmap.gui.jmapviewer.interfaces.TileLoader",
"org.apache.batik.svggen.SVGDescriptor",
"freemind.main.FreeMindStarter$ProxyAuthenticator",
"freemind.main.StdFormatter$StdOutErrLevel",
"org.apache.batik.css.parser.CSSLexicalUnit$IntegerLexicalUnit",
"org.apache.batik.dom.svg.SVGDOMImplementation$FontFaceUriElementFactory",
"org.apache.xml.serializer.ElemDesc",
"org.hsqldb.HsqlInternalException",
"org.openstreetmap.gui.jmapviewer.MemoryTileCache$CacheLinkedListElement",
"org.apache.batik.swing.JSVGCanvas$CanvasSVGListener",
"org.jibx.runtime.IUnmarshaller",
"org.apache.xpath.functions.FuncPosition",
"plugins.map.FreeMindMapController$MapEditNoteTextField",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeCompositeElementFactory",
"com.jgoodies.forms.factories.ComponentFactory",
"org.apache.batik.svggen.SVGComposite",
"org.apache.batik.bridge.SVGBridgeExtension",
"freemind.modes.Mode",
"org.apache.batik.gvt.UpdateTracker$ChngSrcRect",
"org.mozilla.javascript.WrappedException",
"freemind.modes.attributes.NodeAttributeTableModel",
"org.apache.batik.swing.svg.SVGLoadEventDispatcher$2",
"org.apache.batik.util.XMLConstants",
"org.apache.batik.swing.svg.SVGLoadEventDispatcher$3",
"org.apache.batik.swing.svg.SVGLoadEventDispatcher$4",
"org.apache.xalan.res.XSLMessages",
"com.jgoodies.forms.builder.PanelBuilder",
"org.mozilla.javascript.NativeCall",
"org.apache.batik.swing.svg.SVGLoadEventDispatcher$1",
"org.apache.fop.pdf.PDFDocument",
"org.apache.batik.util.gui.resource.MissingListenerException",
"org.apache.log4j.spi.AppenderAttachable",
"org.apache.batik.gvt.renderer.RendererFactory",
"org.hsqldb.Result$ResultMetaData",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$DescendantFromRootTraverser",
"org.apache.xpath.operations.Div",
"org.apache.batik.svggen.DOMTreeManager",
"org.apache.fop.fonts.Typeface",
"org.apache.xml.serializer.ToSAXHandler",
"org.mozilla.javascript.ContextListener",
"org.apache.fop.pdf.PDFTTFStream",
"org.apache.xml.utils.res.CharArrayWrapper",
"freemind.controller.filter.condition.ConjunctConditions",
"org.apache.batik.dom.svg.SVGContext",
"org.apache.fop.fonts.FontInfo",
"org.apache.batik.util.gui.LocationBar",
"org.apache.xpath.functions.FuncDoclocation",
"org.mozilla.javascript.Node",
"org.apache.batik.dom.AbstractText",
"org.apache.fop.pdf.PDFICCStream",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeDistantLightElementFactory",
"org.apache.batik.dom.svg.SVGDOMImplementation$RadialGradientElementFactory",
"org.apache.xalan.processor.ProcessorOutputElem",
"freemind.main.FreeMindMain",
"org.apache.xalan.templates.ElemForEach",
"org.apache.xpath.functions.FuncStringLength",
"org.apache.batik.css.engine.value.css2.FontShorthandManager",
"org.apache.batik.util.ParsedURLData",
"org.mozilla.javascript.Undefined",
"org.apache.batik.dom.svg.SVGDOMImplementation$PolygonElementFactory",
"org.openstreetmap.gui.jmapviewer.OsmMercator",
"org.apache.batik.util.ParsedURL",
"freemind.extensions.HookInstanciationMethod",
"freemind.preferences.FreemindPropertyListener",
"freemind.modes.mindmapmode.MindMapEdgeModel",
"org.openstreetmap.gui.jmapviewer.tilesources.OsmTileSource$Maplint",
"org.apache.batik.gvt.text.GVTAttributedCharacterIterator$TextAttribute",
"org.apache.xml.serializer.WriterToASCI",
"org.apache.xpath.operations.Lte",
"freemind.modes.mindmapmode.actions.NodeColorBlendAction",
"org.apache.xalan.processor.TransformerFactoryImpl",
"org.apache.batik.svggen.AbstractImageHandlerEncoder",
"org.apache.xml.dtm.DTMAxisIterator",
"org.mozilla.javascript.debug.DebugReader",
"org.apache.batik.svggen.SVGLine",
"freemind.modes.mindmapmode.actions.FreemindAction",
"org.mozilla.javascript.optimizer.OptFunctionNode",
"org.apache.xalan.templates.ElemText",
"freemind.modes.mindmapmode.attributeactors.ImportAttributesDialog",
"org.apache.fop.pdf.PDFCIDFontDescriptor",
"org.apache.batik.util.RunnableQueue$RunHandler",
"plugins.map.MapNodePositionHolder$MapNodePositionListener",
"org.apache.batik.dom.AbstractParentNode",
"org.apache.batik.util.CSSConstants",
"org.apache.xpath.axes.AxesWalker",
"org.apache.xml.utils.PrefixResolver",
"org.hsqldb.jdbc.Util",
"freemind.controller.filter.FilterController",
"org.hsqldb.lib.IntValueHashMap",
"org.apache.batik.bridge.DocumentLoader",
"org.apache.batik.extension.svg.BatikDomExtension$FlowSpanElementFactory",
"freemind.controller.actions.generated.instance.CollaborationReceiveLock",
"org.apache.xml.utils.UnImplNode",
"org.apache.xpath.functions.FuncCurrent",
"org.apache.fop.svg.PDFGraphics2D",
"org.apache.batik.dom.svg.SVGDOMImplementation$EllipseElementFactory",
"org.apache.batik.svggen.SVGGraphics2DIOException",
"org.apache.xpath.functions.FuncSubstring",
"org.apache.batik.swing.svg.SVGDocumentLoaderListener",
"org.apache.xpath.operations.Operation",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$IndexedDTMAxisTraverser",
"org.apache.fop.svg.PDFGraphicsDevice",
"org.apache.batik.css.engine.MediaRule",
"org.apache.xml.dtm.ref.ExtendedType",
"freemind.controller.Controller$LocalLinkConverter",
"freemind.extensions.HookFactory$RegistrationContainer",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeFuncRElementFactory",
"org.apache.xalan.trace.TracerEvent",
"org.hsqldb.Trace",
"org.apache.xpath.axes.OneStepIteratorForward",
"org.apache.xml.utils.ObjectPool",
"plugins.collaboration.socket.SocketConnectionHook",
"org.apache.batik.gvt.renderer.Renderer",
"org.hsqldb.lib.BaseList",
"org.apache.batik.bridge.FocusManager",
"org.apache.xalan.templates.ElemPI",
"org.apache.batik.script.Window",
"freemind.controller.ColorSwatch",
"freemind.controller.Controller$MoveToRootAction",
"org.apache.batik.css.engine.value.ShorthandManager",
"org.apache.batik.ext.awt.g2d.AbstractGraphics2D",
"freemind.controller.Controller$PrintAction",
"plugins.collaboration.socket.ServerCommunication",
"org.apache.xalan.processor.ProcessorExsltFuncResult",
"freemind.view.mindmapview.MapView$ScrollPane",
"org.apache.xpath.functions.FuncSubstringBefore",
"org.apache.batik.css.engine.value.css2.ClipManager",
"org.apache.batik.bridge.BridgeUpdateHandler",
"org.apache.xalan.templates.StylesheetRoot",
"org.apache.batik.dom.svg.SVGDOMImplementation$GlyphRefElementFactory",
"org.mozilla.javascript.ClassOutput",
"org.apache.fop.pdf.PDFAnnotList",
"freemind.modes.mindmapmode.actions.NodeUpAction",
"org.apache.batik.swing.gvt.GVTTreeRendererListener",
"org.apache.batik.util.ApplicationSecurityEnforcer",
"org.apache.fop.pdf.PDFGoToRemote",
"org.apache.batik.ext.awt.image.codec.ImageEncoder",
"freemind.main.FreeMind",
"org.apache.fop.svg.PDFDocumentGraphics2D",
"org.apache.batik.css.engine.value.svg.FillRuleManager",
"plugins.collaboration.socket.MindMapClient",
"freemind.modes.MindMap$MapSourceChangedObserver",
"freemind.controller.actions.generated.instance.DeleteNodeAction",
"freemind.modes.browsemode.BrowseEdgeModel",
"freemind.modes.schememode.SchemeToolBar",
"org.apache.xml.dtm.DTMFilter",
"org.apache.batik.css.engine.value.StringMap$Entry",
"org.apache.batik.css.engine.value.FloatValue",
"org.apache.batik.svggen.SVGTexturePaint",
"org.apache.batik.css.engine.CSSEngineUserAgent",
"org.apache.batik.swing.svg.SVGDocumentLoaderEvent",
"org.apache.batik.extension.svg.BatikDomExtension$BatikStarElementFactory",
"freemind.modes.mindmapmode.actions.xml.ActionFactory",
"org.apache.batik.svggen.DefaultExtensionHandler",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeMergeNodeElementFactory",
"org.apache.xpath.objects.XObject",
"org.openstreetmap.gui.jmapviewer.MemoryTileCache",
"freemind.modes.mindmapmode.MindMapMapModel$DummyLockManager",
"freemind.modes.common.dialogs.PersistentEditableComboBox",
"org.apache.xpath.axes.SelfIteratorNoPredicate",
"com.jgoodies.forms.layout.FormSpec$DefaultAlignment",
"freemind.modes.MindMapArrowLink",
"org.apache.xpath.WhitespaceStrippingElementMatcher",
"freemind.modes.MindMapEdge",
"freemind.controller.StructuredMenuHolder$SeparatorHolder",
"org.mozilla.javascript.Node$StringNode",
"freemind.controller.MapModuleManager$MapTitleChangeListener",
"org.hsqldb.resources.BundleHandler",
"org.apache.xpath.operations.Mod",
"org.apache.log4j.spi.DefaultRepositorySelector",
"org.apache.avalon.framework.activity.Initializable",
"org.apache.xpath.operations.Variable",
"org.apache.fop.pdf.PDFStream",
"org.apache.batik.ext.awt.g2d.TransformStackElement$5",
"org.apache.batik.css.engine.value.Value",
"org.apache.batik.ext.awt.g2d.TransformStackElement$3",
"org.apache.batik.ext.awt.g2d.TransformStackElement$4",
"org.apache.batik.ext.awt.g2d.TransformStackElement$1",
"org.apache.batik.ext.awt.g2d.TransformStackElement$2",
"org.apache.batik.swing.gvt.GVTTreeRendererEvent",
"org.apache.xpath.operations.Plus",
"accessories.plugins.time.TableSorter$Directive",
"freemind.controller.filter.util.SortedMapVector",
"org.apache.fop.pdf.PDFWArray",
"org.apache.log4j.or.ObjectRenderer",
"org.hsqldb.rowio.RowInputBinary",
"org.hsqldb.lib.HashSet",
"org.apache.batik.bridge.UpdateManagerListener",
"org.hsqldb.lib.HsqlByteArrayInputStream",
"org.jibx.runtime.IXMLWriter",
"freemind.controller.Controller$ZoomInAction",
"org.mozilla.javascript.WrapHandler",
"freemind.modes.MindMapNode",
"freemind.controller.actions.generated.instance.PatternNodeFontSize",
"org.apache.xml.serializer.SerializationHandler",
"org.apache.xalan.templates.ElemApplyTemplates",
"org.apache.xpath.compiler.Lexer",
"freemind.modes.schememode.SchemeMode",
"freemind.modes.mindmapmode.attributeactors.AttributesListener",
"org.hsqldb.CompiledStatement",
"org.apache.xalan.templates.ElemUse",
"org.apache.xpath.functions.FuncCeiling",
"org.mozilla.javascript.VariableTable",
"freemind.view.mindmapview.NodeView",
"org.apache.batik.apps.svgbrowser.SquiggleInputHandler",
"org.apache.fop.pdf.PDFEncryption",
"freemind.modes.common.CommonNodeKeyListener$EditHandler",
"org.mozilla.javascript.tools.debugger.ScriptItem",
"freemind.modes.ControllerAdapter$FileOpener",
"org.apache.batik.dom.svg.SVGDOMImplementation$FontFaceSrcElementFactory",
"org.apache.xpath.axes.ChildTestIterator",
"org.apache.batik.css.engine.CSSContext",
"org.hsqldb.NumberSequence",
"org.apache.batik.dom.svg.SVGDOMImplementation$ForeignObjectElementFactory",
"org.apache.xalan.templates.NamespaceAlias",
"freemind.modes.attributes.Attribute",
"org.apache.batik.svggen.SVGRescaleOp",
"org.apache.batik.svggen.ImageHandlerPNGEncoder",
"org.apache.log4j.spi.LocationInfo",
"org.apache.batik.swing.gvt.GVTTreeRenderer$1",
"org.apache.batik.swing.gvt.GVTTreeRenderer$2",
"org.apache.batik.swing.gvt.GVTTreeRenderer$3",
"org.apache.xml.dtm.ref.sax2dtm.SAX2RTFDTM",
"org.apache.xalan.extensions.ExtensionNamespaceSupport",
"org.apache.batik.svggen.ImageHandler",
"org.apache.batik.swing.gvt.Overlay",
"plugins.collaboration.database.UpdateThread",
"org.hsqldb.GranteeManager",
"org.apache.batik.css.parser.CSSLexicalUnit$FloatLexicalUnit",
"freemind.controller.filter.FilterToolbar",
"org.apache.xpath.functions.FuncSubstringAfter",
"org.mozilla.javascript.ScriptableObject$GetterSlot",
"plugins.collaboration.database.DatabaseConnector",
"org.apache.batik.swing.gvt.GVTTreeRenderer$4",
"org.apache.fop.fonts.base14.TimesRoman",
"org.apache.batik.swing.gvt.GVTTreeRenderer$5",
"org.apache.batik.dom.svg.SVGDocumentFactory",
"org.apache.batik.dom.svg.SVGDOMImplementation",
"org.apache.xpath.compiler.FunctionTable",
"org.apache.xalan.processor.ProcessorTemplateElem",
"org.apache.xml.dtm.ref.DTMDefaultBaseIterators$TypedAncestorIterator",
"freemind.common.TextTranslator",
"org.apache.log4j.Priority",
"org.apache.batik.util.DoublyLinkedList$Node",
"org.apache.batik.svggen.AbstractSVGFilterConverter",
"org.apache.xpath.objects.NotEqualComparator",
"org.apache.batik.bridge.UpdateManager",
"org.apache.xml.utils.ObjectVector",
"org.apache.xml.dtm.ref.DTMDefaultBaseIterators$TypedSingletonIterator",
"org.apache.fop.pdf.PDFRoot",
"org.mozilla.javascript.tools.debugger.SetFilePosition",
"org.apache.batik.i18n.Localizable",
"org.apache.batik.svggen.DefaultImageHandler",
"org.apache.batik.dom.util.DocumentFactory",
"com.jgoodies.forms.layout.CellConstraints",
"org.hsqldb.lib.Set",
"org.mozilla.javascript.optimizer.OptClassNameHelper",
"org.apache.batik.gvt.GraphicsNode",
"org.mozilla.javascript.Wrapper",
"org.apache.fop.fonts.MutableFont",
"org.apache.log4j.CategoryKey",
"org.hsqldb.persist.HsqlProperties",
"freemind.controller.actions.generated.instance.CollaborationUnableToLock",
"freemind.controller.actions.generated.instance.PatternPropertyBase",
"freemind.controller.StructuredMenuHolder$MapTokenPair",
"org.apache.xml.serializer.SerializerTraceWriter",
"org.apache.batik.svggen.SVGBasicStroke",
"org.apache.xml.utils.NodeVector",
"freemind.controller.actions.generated.instance.PatternNodeText",
"org.apache.xalan.trace.ExtensionEvent",
"freemind.modes.NodeAdapter",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeImageElementFactory",
"org.apache.xalan.templates.XMLNSDecl",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$AllFromNodeTraverser",
"org.apache.fop.fonts.base14.TimesBoldItalic",
"org.apache.xpath.patterns.FunctionPattern",
"freemind.extensions.ExportHook",
"freemind.view.mindmapview.attributeview.AttributeTable$HeaderMouseListener",
"org.apache.batik.css.engine.value.svg.WritingModeManager",
"org.apache.batik.dom.util.DocumentDescriptor$Entry",
"org.apache.batik.gvt.event.SelectionEvent",
"org.hsqldb.types.JavaObject",
"org.apache.xalan.processor.XSLTSchema",
"org.apache.fop.fonts.base14.HelveticaBoldOblique",
"org.apache.batik.css.engine.value.svg.ColorManager",
"org.apache.log4j.spi.ErrorHandler",
"org.apache.batik.ext.awt.g2d.GraphicContext",
"org.apache.batik.bridge.DynamicGVTBuilder",
"org.apache.batik.extension.svg.BatikDomExtension$FlowLineElementFactory",
"org.apache.log4j.spi.RendererSupport",
"org.apache.xalan.templates.ElemLiteralResult",
"org.hsqldb.lib.IntLookup",
"tests.freemind.FreeMindMainMock",
"freemind.common.NamedObject",
"org.apache.batik.gvt.event.GraphicsNodeKeyEvent",
"org.mozilla.javascript.ClassDefinitionException",
"org.openstreetmap.gui.jmapviewer.interfaces.MapMarker",
"org.apache.batik.css.engine.value.svg.ImageRenderingManager",
"freemind.modes.browsemode.BrowseArrowLinkModel",
"org.mozilla.javascript.ScriptableObject$Slot",
"freemind.controller.Controller$ShowFilterToolbarAction",
"org.apache.batik.dom.svg.SVGDOMImplementation$AElementFactory",
"org.mozilla.javascript.SecuritySupport",
"org.apache.batik.script.InterpreterException",
"org.apache.fop.fonts.base14.TimesBold",
"org.apache.batik.dom.svg.SVGDOMImplementation$ImageElementFactory",
"org.apache.batik.css.engine.value.InheritValue",
"freemind.modes.schememode.SchemePopupMenu",
"com.jgoodies.forms.layout.FormLayout$Measure",
"org.apache.xalan.templates.FuncDocument",
"org.apache.batik.extension.svg.BatikDomExtension$BatikHistogramNormalizationElementFactory",
"org.apache.xml.utils.DOMBuilder",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeBlendElementFactory",
"org.apache.xml.dtm.ref.DTMDefaultBaseIterators$SingletonIterator",
"org.apache.xpath.axes.MatchPatternIterator",
"org.apache.xpath.functions.FunctionOneArg",
"org.hsqldb.lib.HsqlArrayList",
"freemind.extensions.ModeControllerHook",
"org.apache.batik.svggen.SVGPaintDescriptor",
"freemind.modes.MindMapCloud",
"org.hsqldb.HsqlException",
"freemind.modes.ControllerAdapter$SaveAsAction",
"org.apache.batik.dom.svg.SVGDOMImplementation$RectElementFactory",
"org.apache.xalan.processor.ProcessorImport",
"org.mozilla.javascript.tools.debugger.FilePopupMenu",
"freemind.controller.Controller$ColorTracker",
"freemind.extensions.MindMapHook",
"org.apache.xalan.templates.StylesheetRoot$ComposeState",
"freemind.modes.MindMap",
"org.apache.xalan.processor.XSLTElementProcessor",
"plugins.map.FreeMindMapController$MapQuestOpenMap",
"org.apache.batik.apps.svgbrowser.FindDialog",
"org.apache.xpath.functions.FuncTranslate",
"org.apache.xml.dtm.ref.DTMDefaultBaseIterators$AncestorIterator",
"org.apache.fop.util.Finalizable",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeOffsetElementFactory",
"org.apache.fop.pdf.PDFUri",
"org.apache.fop.pdf.PDFFactory",
"freemind.view.mindmapview.EditNodeBase$EditControl",
"freemind.controller.actions.generated.instance.PatternNodeFontBold",
"org.hsqldb.rowio.RowOutputBinary",
"org.apache.batik.css.engine.value.css2.OverflowManager",
"org.apache.xml.serializer.NamespaceMappings$Stack",
"org.apache.xpath.functions.FuncNot",
"org.hsqldb.Node",
"freemind.modes.mindmapmode.actions.UseRichFormattingAction$1",
"org.apache.batik.dom.svg.SVGDOMImplementation$MetadataElementFactory",
"org.apache.batik.svggen.SVGRenderingHints",
"org.apache.batik.bridge.InterruptedBridgeException",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$AttributeTraverser",
"org.apache.batik.css.engine.value.css2.FontStyleManager",
"org.apache.batik.css.engine.value.css2.FontWeightManager",
"org.apache.batik.dom.StyleSheetFactory",
"freemind.controller.NodeMouseMotionListener",
"freemind.controller.filter.condition.ConditionRenderer",
"org.hsqldb.SchemaManager$Schema",
"org.apache.xpath.axes.BasicTestIterator",
"org.apache.xalan.templates.ElemElement",
"org.jibx.runtime.IBindingFactory",
"org.mozilla.javascript.ObjArray",
"org.apache.batik.bridge.ExternalResourceSecurity",
"org.apache.xml.dtm.ref.CoroutineManager",
"org.apache.fop.pdf.PDFOutline",
"plugins.collaboration.socket.MindMapMaster",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$NamespaceTraverser",
"freemind.modes.schememode.SchemeMapModel",
"freemind.modes.mindmapmode.MindMapMapModel",
"org.apache.fop.fonts.base14.HelveticaBold",
"org.apache.xml.serializer.XSLOutputAttributes",
"freemind.controller.actions.generated.instance.Searchresults",
"org.apache.log4j.Hierarchy",
"freemind.controller.MapMouseMotionListener$MapMouseMotionReceiver",
"org.apache.batik.svggen.SVGCompositeDescriptor",
"org.apache.batik.dom.svg.SVGDOMImplementation$TextElementFactory",
"org.apache.batik.util.PreferenceManager",
"org.apache.batik.util.ParsedURLProtocolHandler",
"freemind.modes.ControllerAdapter$SaveAction",
"org.apache.batik.dom.svg.SVGDOMImplementation$ViewElementFactory",
"org.apache.log4j.spi.OptionHandler",
"org.apache.batik.dom.svg.SVGDOMImplementation$HkernElementFactory",
"org.mozilla.javascript.FunctionObject",
"org.apache.xml.serializer.ToStream",
"freemind.main.XMLElement",
"org.hsqldb.HsqlNameManager$HsqlName",
"freemind.controller.StructuredMenuHolder$PrintMenuAdderCreator",
"org.jibx.runtime.IUnmarshallable",
"freemind.controller.actions.generated.instance.PatternNodeFontName",
"org.apache.xml.serializer.SerializerTrace",
"org.apache.batik.css.engine.value.svg.TextRenderingManager",
"org.apache.xpath.functions.Function3Args",
"freemind.controller.filter.condition.Condition",
"freemind.view.mindmapview.MindMapLayout",
"freemind.modes.IconInformation",
"freemind.main.IFreeMindSplash",
"org.apache.batik.swing.gvt.TextSelectionManager",
"freemind.controller.actions.generated.instance.NodeAction",
"freemind.controller.actions.generated.instance.CollaborationActionBase",
"org.hsqldb.CachedDataRow",
"org.apache.batik.gvt.UpdateTracker",
"org.apache.batik.dom.svg.SVGDOMImplementation$DefinitionSrcElementFactory",
"org.apache.xml.dtm.SecuritySupport",
"freemind.controller.MapModuleManager",
"freemind.main.LoggingOutputStream",
"org.apache.batik.dom.svg.SVGDOMImplementation$ScriptElementFactory",
"freemind.modes.mindmapmode.MindMapCloudModel",
"plugins.map.Registration",
"org.apache.xpath.functions.FuncBoolean",
"org.apache.xalan.templates.ElemExtensionDecl",
"org.apache.xml.serializer.ToStream$WritertoStringBuffer",
"org.apache.batik.script.InterpreterFactory",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$DescendantTraverser",
"org.apache.xalan.processor.ProcessorInclude",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$SelfTraverser",
"org.apache.avalon.framework.CascadingRuntimeException",
"org.apache.batik.dom.svg.SVGDOMImplementation$AnimateColorElementFactory",
"org.apache.batik.css.engine.CSSEngine",
"org.apache.xml.serializer.CharInfo",
"org.apache.batik.ext.awt.geom.RectListManager$RectXComparator",
"org.apache.fop.pdf.PDFPathPaint",
"org.apache.batik.util.gui.DOMViewer",
"freemind.modes.ModeController$NodeLifetimeListener",
"org.apache.batik.svggen.SVGPolygon",
"org.apache.xpath.axes.UnionChildIterator",
"org.apache.batik.ext.awt.MultipleGradientPaint",
"org.hsqldb.rowio.RowInputBase",
"org.apache.batik.css.engine.value.AbstractValueManager",
"accessories.plugins.ClonePlugin",
"org.apache.xalan.processor.ProcessorExsltFunction",
"org.apache.xalan.trace.EndSelectionEvent",
"org.apache.xml.dtm.ObjectFactory",
"org.apache.xpath.objects.LessThanOrEqualComparator",
"org.hsqldb.Database",
"org.mozilla.javascript.Invoker",
"org.apache.batik.gvt.event.GraphicsNodeChangeEvent",
"org.apache.batik.css.engine.value.css2.TextDecorationManager",
"freemind.modes.mindmapmode.MindMapController$NewNodeCreator",
"org.apache.batik.css.engine.value.svg.EnableBackgroundManager",
"org.apache.xpath.objects.XMLStringFactoryImpl",
"org.apache.xml.serializer.ToHTMLSAXHandler",
"org.apache.fop.pdf.PDFT1Stream",
"org.apache.xml.dtm.ref.sax2dtm.SAX2DTM2",
"freemind.controller.Controller$ShowAttributeDialogAction",
"org.hsqldb.lib.FileUtil",
"org.apache.batik.ext.awt.MultipleGradientPaint$CycleMethodEnum",
"freemind.modes.MapAdapter",
"org.apache.batik.dom.svg.SVGDOMImplementation$SymbolElementFactory",
"plugins.collaboration.socket.TerminateableThread",
"org.apache.batik.dom.ExtendedNode",
"org.apache.xpath.objects.EqualComparator",
"org.apache.batik.css.engine.value.AbstractColorManager",
"org.apache.xpath.functions.FuncConcat",
"org.apache.xml.utils.StringToIntTable",
"org.apache.fop.pdf.StreamCacheFactory",
"org.apache.batik.gvt.event.GraphicsNodeChangeListener",
"org.apache.batik.dom.svg.SVGDOMImplementation$TextPathElementFactory",
"freemind.main.FreeMindApplet",
"org.hsqldb.CachedRow",
"org.hsqldb.Record",
"freemind.modes.mindmapmode.MindMapToolBar",
"org.apache.xpath.ExpressionOwner",
"org.apache.batik.bridge.BaseScriptingEnvironment",
"org.apache.batik.bridge.BridgeContext",
"freemind.controller.actions.generated.instance.NodeListMember",
"org.apache.fop.pdf.PDFPages",
"org.apache.fop.fonts.CustomFont",
"org.apache.xpath.domapi.XPathStylesheetDOM3Exception",
"org.apache.xml.utils.NSInfo",
"org.apache.batik.css.engine.value.ListValue",
"org.apache.batik.dom.svg.SVGDOMImplementation$AnimateMotionElementFactory",
"org.apache.batik.svggen.SVGGeneratorContext",
"freemind.controller.MapMouseMotionListener",
"org.apache.batik.css.engine.CSSEngineListener",
"freemind.controller.actions.generated.instance.PatternChild",
"freemind.modes.FreeMindAwtFileDialog$DirFilter",
"org.apache.batik.svggen.SVGGeneratorContext$GraphicContextDefaults",
"org.apache.fop.fonts.base14.CourierOblique",
"freemind.modes.mindmapmode.listeners.MindMapNodeMotionListener",
"org.apache.xpath.ExpressionNode",
"org.apache.batik.css.engine.SVGCSSEngine",
"org.apache.log4j.helpers.Loader",
"org.apache.fop.fonts.BFEntry",
"org.apache.fop.pdf.PDFPage",
"freemind.controller.Controller$NavigationMoveMapLeftAction",
"freemind.modes.mindmapmode.hooks.MindMapHookAdapter",
"org.apache.xpath.SourceTreeManager",
"org.apache.xpath.axes.DescendantIterator",
"org.apache.batik.svggen.SVGPath",
"org.apache.log4j.spi.VectorWriter",
"org.apache.batik.svggen.GenericImageHandler",
"freemind.modes.schememode.SchemeController",
"freemind.common.PropertyControl",
"org.mozilla.javascript.debug.DebugFrame",
"org.apache.xpath.operations.Bool",
"org.apache.batik.bridge.ErrorConstants",
"org.apache.fop.fonts.base14.Helvetica",
"org.apache.batik.svggen.ExtensionHandler",
"org.hsqldb.MemoryNode",
"org.apache.batik.css.parser.CSSLexicalUnit$DimensionLexicalUnit",
"freemind.modes.FreeMindFileDialog$DirectoryResultListener",
"org.apache.xalan.processor.ProcessorGlobalParamDecl",
"org.apache.batik.css.engine.value.ValueConstants",
"freemind.modes.mindmapmode.actions.NodeActorXml",
"freemind.view.mindmapview.attributeview.AttributeViewScrollPane",
"freemind.controller.filter.condition.JCondition",
"org.apache.batik.util.ParsedURLDefaultProtocolHandler",
"freemind.modes.mindmapmode.hooks.PermanentMindMapNodeHookAdapter",
"org.apache.fop.pdf.PDFColor",
"org.apache.batik.css.engine.StyleDeclaration",
"org.apache.fop.pdf.ASCIIHexFilter",
"org.apache.avalon.framework.ValuedEnum",
"plugins.collaboration.database.DatabaseConnectionHook",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$DescendantOrSelfFromRootTraverser",
"freemind.extensions.HookRegistration",
"plugins.collaboration.database.DatabaseBasics$ResultHandler",
"freemind.controller.actions.generated.instance.PatternNodeFontItalic",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$PrecedingSiblingTraverser",
"org.apache.batik.css.engine.value.svg.ColorProfileManager",
"org.apache.xalan.templates.ElemParam",
"freemind.modes.mindmapmode.actions.MindMapActions$MouseWheelEventHandler",
"org.apache.fop.image.JpegImage",
"org.apache.batik.css.engine.value.svg.StrokeDasharrayManager",
"org.apache.fop.fonts.MultiByteFont",
"freemind.controller.ZoomListener",
"org.apache.xalan.templates.ElemVariable",
"freemind.controller.MenuBar",
"freemind.main.Tools$NameMnemonicHolder",
"freemind.controller.filter.util.SortedComboBoxModel",
"org.apache.xml.utils.StopParseException",
"org.apache.batik.css.engine.CSSImportedElementRoot",
"freemind.controller.Controller$ShowSelectedAttributesAction",
"freemind.controller.StructuredMenuHolder$MenuAdder",
"freemind.modes.mindmapmode.MindMapPopupMenu",
"freemind.modes.attributes.ColumnWidthChangeEvent",
"org.apache.batik.css.engine.value.RectManager",
"freemind.main.FreeMindCommon$FreemindResourceBundle",
"org.apache.xpath.axes.FilterExprWalker",
"freemind.controller.Controller$NavigationMoveMapRightAction",
"freemind.controller.NodeMouseMotionListener$NodeMouseMotionObserver",
"freemind.controller.StructuredMenuHolder",
"org.apache.fop.pdf.PDFFontDescriptor",
"freemind.extensions.ExportHook$ImageFilter",
"org.apache.xalan.processor.XSLTAttributeDef",
"org.apache.batik.css.engine.CSSEngineEvent",
"freemind.modes.ModeController",
"freemind.modes.mindmapmode.MindMapController$MindMapFilter",
"freemind.controller.Controller$KeyDocumentationAction",
"freemind.modes.ControllerAdapter$1",
"org.apache.batik.dom.ExtensibleDOMImplementation",
"freemind.controller.Controller$DefaultLocalLinkConverter",
"org.apache.batik.dom.svg.SVGDOMImplementation$UseElementFactory",
"org.apache.xalan.templates.ElemWithParam",
"org.apache.batik.extension.svg.BatikDomExtension$BatikRegularPolygonElementFactory",
"org.apache.fop.pdf.TransitionDictionary",
"org.mozilla.javascript.UniqueTag",
"org.apache.log4j.Level",
"org.apache.batik.swing.svg.GVTTreeBuilderListener",
"org.apache.xml.serializer.SerializerBase",
"org.mozilla.javascript.IdScriptable",
"freemind.extensions.HookInstanciationMethod$DestinationNodesGetter",
"org.openstreetmap.gui.jmapviewer.tilesources.OsmTileSource",
"org.apache.batik.svggen.SVGCustomBufferedImageOp",
"org.mozilla.javascript.tools.debugger.TreeTableModel",
"org.hsqldb.lib.HsqlList",
"org.apache.fop.fonts.base14.Symbol",
"plugins.map.FreeMindMapController$TransportMap",
"freemind.extensions.MindMapHook$PluginBaseClassSearcher",
"org.apache.xpath.operations.Minus",
"org.apache.fop.fonts.CodePointMapping",
"org.apache.batik.dom.svg.SVGDOMImplementation$FilterElementFactory",
"com.jgoodies.forms.layout.RowSpec",
"org.apache.batik.bridge.ScriptSecurity",
"org.apache.fop.svg.GraphicsConfiguration",
"org.apache.batik.css.engine.value.ValueManager",
"org.apache.xml.dtm.ref.IncrementalSAXSource_Filter$StopException",
"freemind.modes.attributes.AttributeTableModel",
"com.jgoodies.forms.layout.ConstantSize$Unit",
"freemind.controller.actions.generated.instance.MapLocationStorage",
"freemind.modes.ControllerAdapter$EditAttributesAction",
"org.apache.batik.ext.awt.g2d.TransformStackElement",
"org.apache.batik.css.engine.Rule",
"org.apache.xpath.compiler.Compiler",
"org.apache.batik.css.engine.StyleSheet",
"org.apache.xml.utils.DefaultErrorHandler",
"org.hsqldb.User",
"org.apache.batik.svggen.SimpleImageHandler",
"org.apache.batik.svggen.ErrorHandler",
"org.jibx.runtime.IUnmarshallingContext",
"org.apache.xpath.axes.UnionPathIterator",
"org.apache.batik.swing.svg.SVGDocumentLoader$2",
"org.apache.batik.swing.svg.SVGDocumentLoader$1",
"org.apache.batik.swing.svg.SVGDocumentLoader$4",
"org.apache.batik.dom.events.DocumentEventSupport$EventFactory",
"org.apache.batik.swing.svg.SVGDocumentLoader$3",
"org.apache.batik.svggen.SVGConvolveOp",
"org.apache.fop.util.FlateEncodeOutputStream",
"plugins.collaboration.socket.ClientCommunication",
"org.apache.batik.css.engine.value.css2.FontFamilyManager",
"plugins.collaboration.socket.SocketBasics$FormDialogValidator",
"org.apache.batik.dom.events.EventListenerList",
"org.apache.batik.svggen.SVGClip",
"org.apache.xpath.functions.FuncNormalizeSpace",
"org.apache.xpath.axes.WalkerFactory",
"org.apache.batik.gvt.event.GraphicsNodeKeyListener",
"freemind.modes.browsemode.BrowseNodeModel",
"org.apache.fop.fonts.CIDFontType",
"org.apache.xpath.patterns.StepPattern",
"org.apache.fop.pdf.InMemoryStreamCache",
"freemind.modes.ModesCreator",
"org.apache.xalan.templates.ElemCopy",
"org.apache.xalan.transformer.TransformerIdentityImpl",
"freemind.modes.mindmapmode.MindMapToolBar$2",
"org.apache.xpath.VariableStack",
"freemind.modes.mindmapmode.MindMapToolBar$1",
"org.mozilla.javascript.tools.debugger.Evaluator",
"org.apache.xml.utils.NodeConsumer",
"org.apache.xpath.XPathContext$XPathExpressionContext",
"freemind.modes.mindmapmode.hooks.MindMapNodeHookAdapter",
"freemind.modes.XMLElementAdapter",
"org.apache.batik.dom.svg.SVGDOMImplementation$DescElementFactory",
"plugins.map.MapSearchMarkerLocation",
"freemind.controller.MapModuleManager$MapTitleContributor",
"org.apache.xpath.functions.FuncFalse",
"plugins.collaboration.socket.CommunicationBase",
"freemind.controller.MainToolBar",
"org.apache.xml.serializer.ExtendedLexicalHandler",
"org.apache.xpath.functions.Function",
"org.apache.fop.image.AbstractFopImage",
"org.xmlpull.v1.XmlPullParserException",
"org.hsqldb.DatabaseURL",
"freemind.modes.FreeMindAwtFileDialog$FileOnlyFilter",
"com.jgoodies.forms.layout.Size",
"org.apache.batik.extension.svg.BatikDomExtension",
"org.apache.xpath.res.XPATHMessages",
"org.apache.fop.pdf.PDFFilterException",
"org.hsqldb.rowio.RowInputInterface",
"org.apache.fop.pdf.AbstractPDFStream",
"freemind.controller.Controller$HideAllAttributesAction",
"freemind.modes.filemode.FilePopupMenu",
"org.apache.xalan.templates.Stylesheet",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$RootTraverser",
"org.apache.xpath.objects.XBooleanStatic",
"org.apache.xml.serializer.EncodingInfo$InEncoding",
"org.mozilla.javascript.InterpreterData",
"org.apache.batik.apps.svgbrowser.AboutDialog$3",
"org.apache.batik.svggen.SVGGraphics2D",
"freemind.modes.CloudAdapter",
"freemind.main.XMLParseException",
"org.apache.xpath.functions.FuncQname",
"org.apache.xalan.templates.ElemExtensionCall",
"org.hsqldb.Constraint",
"org.hsqldb.rowio.RowOutputTextLog",
"freemind.controller.Controller$PropertyAction",
"org.mozilla.javascript.TokenStream",
"freemind.controller.Controller$OptionHTMLExportFoldingAction",
"org.apache.batik.dom.ExtensibleDOMImplementation$ElementFactory",
"org.mozilla.javascript.ScriptableObject",
"org.apache.fop.fonts.Font",
"org.apache.batik.apps.svgbrowser.SVGInputHandler",
"org.hsqldb.TriggerDef",
"org.apache.batik.css.engine.value.svg.ColorRenderingManager",
"org.mozilla.javascript.Interpreter",
"org.apache.batik.css.engine.value.svg.MarkerManager",
"org.apache.xalan.templates.FuncFormatNumb",
"org.apache.xml.serializer.ObjectFactory",
"org.apache.batik.dom.util.HashTable",
"freemind.controller.Controller$BackgroundSwatch",
"org.apache.batik.swing.gvt.Interactor",
"plugins.map.Registration$CachePurger",
"org.mozilla.javascript.tools.debugger.Main",
"org.mozilla.javascript.GeneratedClassLoader",
"freemind.modes.mindmapmode.actions.xml.ActionFilter",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeDisplacementMapElementFactory",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$ParentTraverser",
"org.mozilla.javascript.tools.shell.ConsoleTextArea",
"org.apache.xml.serializer.DOMSerializer",
"org.apache.xpath.compiler.OpMap",
"freemind.controller.actions.generated.instance.EditNoteToNodeAction",
"org.apache.batik.ext.awt.MultipleGradientPaint$ColorSpaceEnum",
"org.apache.batik.bridge.Bridge",
"org.apache.xalan.transformer.XalanTransformState",
"org.apache.xpath.operations.And",
"org.mozilla.javascript.ScriptRuntime",
"org.apache.batik.util.RunnableQueue$RunnableQueueState",
"freemind.modes.attributes.AttributeRegistryTableModel",
"org.apache.batik.gvt.renderer.ImageRenderer",
"org.apache.xalan.templates.AVT",
"org.hsqldb.UserManager",
"org.mozilla.javascript.PropertyException",
"org.apache.batik.dom.svg.SVGDOMImplementation$FeFuncGElementFactory",
"org.mozilla.javascript.IdFunctionMaster",
"org.apache.batik.dom.svg.SVGDOMImplementation$MissingGlyphElementFactory",
"org.apache.xml.utils.DOM2Helper",
"freemind.preferences.FreemindPropertyContributor",
"org.apache.log4j.ProvisionNode",
"org.apache.batik.util.CleanerThread$WeakReferenceCleared",
"freemind.modes.FreeMindJFileDialog",
"org.apache.xalan.processor.StylesheetHandler",
"org.apache.batik.svggen.SVGConverter",
"org.apache.batik.css.engine.value.RGBColorValue",
"org.apache.xml.res.XMLErrorResources_en",
"freemind.controller.filter.FilterToolbar$1",
"org.apache.batik.apps.svgbrowser.Application",
"org.mozilla.javascript.tools.debugger.Main$1",
"freemind.controller.actions.generated.instance.TextNodeAction",
"freemind.controller.StructuredMenuHolder$DefaultMenuAdderCreator",
"org.apache.batik.gvt.event.EventDispatcher",
"freemind.extensions.DontSaveMarker",
"org.mozilla.javascript.Context",
"org.apache.batik.css.engine.value.AbstractValueFactory",
"org.apache.xml.utils.res.XResourceBundle",
"org.apache.batik.dom.svg.SVGDOMImplementation$FontFaceNameElementFactory",
"org.apache.fop.pdf.PDFCIDFont",
"org.apache.xalan.trace.GenerateEvent",
"org.apache.xalan.processor.ProcessorDecimalFormat",
"org.apache.xpath.NodeSetDTM",
"org.apache.xalan.templates.ElemExtensionScript",
"plugins.map.FreeMindMapController",
"org.apache.fop.pdf.PDFObject",
"org.apache.xml.dtm.ref.ExpandedNameTable",
"freemind.modes.MindMapLinkRegistry",
"org.apache.fop.pdf.PDFArray",
"org.apache.fop.pdf.PDFInfo",
"freemind.view.mindmapview.EditNodeTextField",
"org.hsqldb.types.Binary",
"org.apache.batik.svggen.SVGLookupOp",
"org.apache.batik.dom.svg.SVGDOMImplementation$FontFaceElementFactory",
"org.hsqldb.store.ValuePoolHashMap",
"org.apache.batik.css.engine.value.css2.DisplayManager",
"org.jibx.runtime.IMarshaller",
"org.apache.xpath.operations.Or",
"org.mozilla.javascript.tools.debugger.EvalTextArea",
"org.apache.xml.dtm.DTMWSFilter",
"org.apache.batik.css.engine.value.svg.SVGPaintManager",
"org.mozilla.javascript.tools.debugger.FrameHelper",
"org.apache.batik.gvt.Selectable",
"freemind.extensions.HookInstanciationMethod$AllDestinationNodesGetter",
"org.apache.log4j.spi.RepositorySelector",
"org.apache.xalan.templates.TemplateList",
"freemind.modes.mindmapmode.actions.xml.ActionFilter$FinalActionFilter",
"org.mozilla.javascript.optimizer.OptIRFactory",
"org.apache.fop.fonts.truetype.FontFileReader",
"org.apache.batik.util.gui.resource.MenuFactory",
"org.apache.batik.svggen.SVGStrokeDescriptor",
"org.apache.xml.serializer.CharInfo$CharKey",
"org.apache.xalan.templates.ElemUnknown",
"org.apache.xpath.operations.Lt",
"org.apache.batik.dom.svg.SVGDOMImplementation$PatternElementFactory",
"org.apache.xpath.functions.FuncGenerateId",
"org.apache.xpath.functions.FuncUnparsedEntityURI",
"accessories.plugins.time.TableSorter",
"org.apache.xpath.operations.String",
"org.apache.xpath.functions.FuncId",
"freemind.controller.BlindIcon",
"org.mozilla.javascript.tools.debugger.MyTreeTable",
"org.hsqldb.lib.HashMappedList",
"freemind.modes.attributes.AttributeRegistryElement$RegisteredAttributeValues",
"org.apache.batik.css.engine.value.css2.FontStretchManager",
"freemind.main.LogFileLogHandler",
"org.apache.fop.pdf.DCTFilter",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$FollowingTraverser",
"freemind.modes.mindmapmode.MindMapMode",
"org.openstreetmap.gui.jmapviewer.tilesources.OsmTileSource$TilesAtHome",
"org.apache.xalan.templates.ElemChoose",
"org.mozilla.javascript.PreorderNodeIterator",
"org.apache.xalan.res.XSLTErrorResources_en",
"org.apache.batik.apps.svgbrowser.Resources",
"org.apache.xpath.operations.Neg",
"freemind.common.OptionalDontShowMeAgainDialog$DontShowPropertyHandler",
"org.apache.batik.gvt.event.GraphicsNodeInputEvent",
"org.apache.xml.dtm.DTM",
"org.apache.batik.svggen.SVGShape",
"org.apache.avalon.framework.configuration.Configurable",
"freemind.controller.Controller$NavigationPreviousMapAction",
"org.mozilla.javascript.Node$NumberNode"
);
}
private static void resetClasses() {
org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(Controller_ESTest_scaffolding.class.getClassLoader());
org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses(
"freemind.controller.Controller",
"freemind.controller.ColorSwatch",
"freemind.controller.Controller$BackgroundSwatch",
"freemind.controller.Controller$ShowAllAttributesAction",
"freemind.controller.Controller$ShowSelectedAttributesAction",
"freemind.controller.Controller$HideAllAttributesAction",
"freemind.controller.Controller$1",
"freemind.controller.Controller$DefaultLocalLinkConverter",
"freemind.controller.Controller$CloseAction",
"freemind.controller.Controller$PrintAction",
"freemind.controller.Controller$PrintPreviewAction",
"freemind.controller.Controller$PageAction",
"freemind.controller.Controller$QuitAction",
"freemind.controller.Controller$AboutAction",
"freemind.controller.Controller$OpenURLAction",
"freemind.controller.Controller$KeyDocumentationAction",
"freemind.controller.Controller$DocumentationAction",
"freemind.controller.Controller$LicenseAction",
"freemind.controller.Controller$NavigationPreviousMapAction",
"freemind.controller.Controller$NavigationNextMapAction",
"freemind.controller.Controller$NavigationMoveMapLeftAction",
"freemind.controller.Controller$NavigationMoveMapRightAction",
"freemind.controller.Controller$ShowFilterToolbarAction",
"freemind.controller.Controller$ShowAttributeDialogAction",
"freemind.controller.Controller$ToggleMenubarAction",
"freemind.controller.Controller$ToggleToolbarAction",
"freemind.controller.Controller$ToggleLeftToolbarAction",
"freemind.controller.Controller$OptionAntialiasAction",
"freemind.controller.Controller$OptionHTMLExportFoldingAction",
"freemind.controller.Controller$OptionSelectionMechanismAction",
"freemind.controller.Controller$ZoomInAction",
"freemind.controller.Controller$ZoomOutAction",
"freemind.controller.Controller$PropertyAction",
"freemind.controller.Controller$ShowSelectionAsRectangleAction",
"freemind.controller.Controller$MoveToRootAction",
"freemind.controller.Controller$ColorTracker",
"freemind.controller.Controller$Closer",
"freemind.controller.Controller$DisposeOnClose",
"freemind.controller.Controller$2",
"freemind.controller.Controller$3",
"freemind.controller.Controller$4",
"freemind.main.Resources",
"tests.freemind.FreeMindMainMock",
"freemind.main.FreeMindStarter",
"freemind.main.Tools",
"freemind.modes.Mode",
"freemind.modes.browsemode.BrowseMode",
"freemind.modes.ControllerAdapter",
"freemind.modes.viewmodes.ViewControllerAdapter",
"freemind.modes.browsemode.BrowseController",
"freemind.modes.ControllerAdapter$ControllerPopupMenuListener",
"freemind.modes.filemode.FileMode",
"freemind.modes.filemode.FileController",
"freemind.modes.schememode.SchemeMode",
"org.apache.xml.serializer.SerializerBase",
"org.apache.xml.serializer.ToUnknownStream",
"org.apache.xml.serializer.AttributesImplSerializer",
"org.apache.xml.serializer.ElemContext",
"org.apache.xml.serializer.SecuritySupport12",
"org.apache.xml.serializer.SecuritySupport",
"org.apache.xml.serializer.SecuritySupport12$4",
"org.apache.xml.serializer.ToStream",
"org.apache.xml.serializer.ToXMLStream",
"org.apache.xml.serializer.ToStream$BoolStack",
"org.apache.xml.serializer.EncodingInfo",
"org.apache.xml.serializer.CharInfo",
"org.apache.xml.serializer.CharInfo$1",
"org.apache.xml.serializer.CharInfo$CharKey",
"org.apache.xml.serializer.NamespaceMappings",
"org.apache.xml.serializer.NamespaceMappings$Stack",
"org.apache.xml.serializer.NamespaceMappings$MappingRecord",
"freemind.modes.mindmapmode.MindMapMode",
"freemind.main.FreeMindMain$VersionInformation",
"freemind.main.FreeMind",
"freemind.main.FreeMindApplet",
"freemind.extensions.HookAdapter",
"freemind.extensions.NodeHookAdapter",
"freemind.extensions.PermanentNodeHookAdapter",
"freemind.modes.mindmapmode.hooks.PermanentMindMapNodeHookAdapter",
"accessories.plugins.ClonePlugin",
"freemind.modes.mindmapmode.hooks.MindMapNodeHookAdapter",
"plugins.collaboration.database.DatabaseBasics",
"plugins.collaboration.database.DatabaseConnectionHook",
"org.hsqldb.jdbc.jdbcConnection",
"freemind.modes.schememode.SchemeController",
"freemind.extensions.ModeControllerHookAdapter",
"freemind.modes.mindmapmode.hooks.MindMapHookAdapter",
"plugins.map.MapDialog",
"freemind.modes.ModesCreator",
"org.apache.xml.serializer.EmptySerializer",
"org.hsqldb.lib.FileUtil",
"plugins.collaboration.database.DatabaseStarter",
"org.openstreetmap.gui.jmapviewer.OsmTileLoader",
"org.openstreetmap.gui.jmapviewer.OsmFileCacheTileLoader",
"org.openstreetmap.gui.jmapviewer.Demo",
"org.apache.xml.utils.UnImplNode",
"org.apache.xalan.templates.ElemTemplateElement",
"org.apache.xalan.templates.Stylesheet",
"org.apache.xalan.templates.StylesheetComposed",
"org.apache.xalan.templates.StylesheetRoot",
"org.apache.xpath.XPath",
"org.apache.xpath.Expression",
"org.apache.xpath.functions.Function",
"org.apache.xpath.functions.FuncCurrent",
"org.apache.xpath.functions.FuncLast",
"org.apache.xpath.functions.FuncPosition",
"org.apache.xpath.functions.FunctionOneArg",
"org.apache.xpath.functions.FuncCount",
"org.apache.xpath.functions.FuncId",
"org.apache.xpath.functions.Function2Args",
"org.apache.xalan.templates.FuncKey",
"org.apache.xpath.functions.FunctionDef1Arg",
"org.apache.xpath.functions.FuncLocalPart",
"org.apache.xpath.functions.FuncNamespace",
"org.apache.xpath.functions.FuncQname",
"org.apache.xpath.functions.FuncGenerateId",
"org.apache.xpath.functions.FuncNot",
"org.apache.xpath.functions.FuncTrue",
"org.apache.xpath.functions.FuncFalse",
"org.apache.xpath.functions.FuncBoolean",
"org.apache.xpath.functions.FuncLang",
"org.apache.xpath.functions.FuncNumber",
"org.apache.xpath.functions.FuncFloor",
"org.apache.xpath.functions.FuncCeiling",
"org.apache.xpath.functions.FuncRound",
"org.apache.xpath.functions.FuncSum",
"org.apache.xpath.functions.FuncString",
"org.apache.xpath.functions.FuncStartsWith",
"org.apache.xpath.functions.FuncContains",
"org.apache.xpath.functions.FuncSubstringBefore",
"org.apache.xpath.functions.FuncSubstringAfter",
"org.apache.xpath.functions.FuncNormalizeSpace",
"org.apache.xpath.functions.Function3Args",
"org.apache.xpath.functions.FuncTranslate",
"org.apache.xpath.functions.FunctionMultiArgs",
"org.apache.xpath.functions.FuncConcat",
"org.apache.xpath.functions.FuncSystemProperty",
"org.apache.xpath.functions.FuncExtFunctionAvailable",
"org.apache.xpath.functions.FuncExtElementAvailable",
"org.apache.xpath.functions.FuncSubstring",
"org.apache.xpath.functions.FuncStringLength",
"org.apache.xpath.functions.FuncDoclocation",
"org.apache.xpath.functions.FuncUnparsedEntityURI",
"org.apache.xpath.compiler.FunctionTable",
"org.apache.xml.utils.DefaultErrorHandler",
"org.apache.xpath.compiler.XPathParser",
"org.apache.xpath.compiler.OpMap",
"org.apache.xpath.compiler.Compiler",
"org.apache.xml.utils.ObjectVector",
"org.apache.xpath.compiler.Lexer",
"org.apache.xpath.compiler.OpMapVector",
"org.apache.xpath.compiler.Keywords",
"org.apache.xpath.axes.WalkerFactory",
"org.apache.xpath.objects.XObject",
"org.apache.xpath.objects.XNumber",
"org.apache.xpath.patterns.NodeTest",
"org.apache.xpath.axes.PredicatedNodeTest",
"org.apache.xpath.axes.LocPathIterator",
"org.apache.xpath.axes.ChildIterator",
"org.apache.xpath.axes.IteratorPool",
"org.apache.xalan.templates.ElemTemplate",
"org.apache.xpath.patterns.StepPattern",
"org.apache.xalan.templates.ElemForEach",
"org.apache.xalan.templates.ElemCallTemplate",
"org.apache.xalan.templates.ElemApplyTemplates",
"org.apache.xpath.patterns.UnionPattern",
"org.apache.xalan.templates.ElemValueOf",
"org.apache.xpath.axes.SelfIteratorNoPredicate",
"org.apache.xalan.processor.TransformerFactoryImpl",
"org.apache.xalan.processor.StylesheetHandler",
"org.apache.xalan.processor.XSLTElementDef",
"org.apache.xalan.processor.XSLTSchema",
"org.apache.xalan.processor.XSLTAttributeDef",
"org.apache.xml.utils.StringToIntTable",
"org.apache.xalan.processor.XSLTElementProcessor",
"org.apache.xalan.processor.ProcessorCharacters",
"org.apache.xalan.templates.ElemTextLiteral",
"org.apache.xalan.processor.ProcessorTemplateElem",
"org.apache.xalan.processor.ProcessorLRE",
"org.apache.xalan.templates.ElemUse",
"org.apache.xalan.templates.ElemLiteralResult",
"org.apache.xalan.processor.ProcessorUnknown",
"org.apache.xalan.templates.ElemUnknown",
"org.apache.xml.utils.QName",
"org.apache.xalan.templates.ElemCopyOf",
"org.apache.xalan.transformer.DecimalToRoman",
"org.apache.xalan.templates.ElemNumber",
"org.apache.xalan.templates.ElemSort",
"org.apache.xalan.templates.ElemWithParam",
"org.apache.xalan.templates.ElemApplyImport",
"org.apache.xalan.templates.ElemIf",
"org.apache.xalan.templates.ElemWhen",
"org.apache.xalan.templates.ElemOtherwise",
"org.apache.xalan.templates.ElemChoose",
"org.apache.xalan.templates.ElemElement",
"org.apache.xalan.templates.ElemAttribute",
"org.apache.xalan.templates.ElemVariable",
"org.apache.xalan.templates.ElemParam",
"org.apache.xalan.processor.ProcessorText",
"org.apache.xalan.templates.ElemText",
"org.apache.xalan.templates.ElemPI",
"org.apache.xalan.templates.ElemComment",
"org.apache.xalan.templates.ElemCopy",
"org.apache.xalan.templates.ElemMessage",
"org.apache.xalan.templates.ElemFallback",
"org.apache.xalan.processor.ProcessorExsltFunction",
"org.apache.xalan.templates.ElemExsltFunction",
"org.apache.xalan.processor.ProcessorExsltFuncResult",
"org.apache.xalan.templates.ElemExsltFuncResult",
"org.apache.xalan.processor.ProcessorInclude",
"org.apache.xalan.processor.ProcessorImport",
"org.apache.xalan.processor.ProcessorPreserveSpace",
"org.apache.xalan.processor.ProcessorStripSpace",
"org.apache.xalan.processor.ProcessorOutputElem",
"org.apache.xalan.processor.ProcessorKey",
"org.apache.xalan.processor.ProcessorDecimalFormat",
"org.apache.xalan.processor.ProcessorAttributeSet",
"org.apache.xalan.processor.ProcessorGlobalVariableDecl",
"org.apache.xalan.processor.ProcessorGlobalParamDecl",
"org.apache.xalan.processor.ProcessorTemplate",
"org.apache.xalan.processor.ProcessorNamespaceAlias",
"org.apache.xalan.templates.ElemExtensionScript",
"org.apache.xalan.templates.ElemExtensionDecl",
"org.apache.xalan.processor.ProcessorStylesheetElement",
"org.apache.xalan.processor.ProcessorStylesheetDoc",
"org.apache.xml.utils.BoolStack",
"org.apache.xalan.templates.FuncDocument",
"org.apache.xalan.templates.FuncFormatNumb",
"org.apache.xml.utils.NamespaceSupport2",
"org.apache.xml.utils.Context2",
"org.apache.xml.utils.SAXSourceLocator",
"org.apache.xml.res.XMLMessages",
"org.apache.xpath.res.XPATHMessages",
"org.apache.xalan.res.XSLMessages",
"org.apache.xalan.res.XSLTErrorResources",
"org.apache.xalan.res.XSLTErrorResources_en",
"freemind.modes.mindmapmode.actions.NewChildAction",
"freemind.modes.mindmapmode.MindMapController",
"freemind.modes.common.plugins.MapNodePositionHolderBase",
"plugins.map.MapNodePositionHolder",
"org.openstreetmap.gui.jmapviewer.Coordinate",
"org.apache.xml.serializer.ToHTMLStream$Trie",
"org.apache.xml.serializer.ToHTMLStream$Trie$Node",
"org.apache.xml.serializer.ElemDesc",
"org.apache.xml.serializer.utils.StringToIntTable",
"org.apache.xml.serializer.ToHTMLStream",
"org.apache.xalan.transformer.TransformerIdentityImpl",
"org.apache.xalan.templates.OutputProperties",
"org.apache.xml.serializer.OutputPropertiesFactory",
"org.apache.xml.serializer.OutputPropertiesFactory$1",
"freemind.controller.FreeMindToolBar",
"freemind.controller.MainToolBar",
"freemind.modes.mindmapmode.MindMapToolBar",
"freemind.modes.mindmapmode.JAutoScrollBarPane",
"freemind.modes.mindmapmode.MindMapToolBar$1",
"freemind.modes.mindmapmode.MindMapToolBar$2",
"org.apache.batik.util.gui.resource.ResourceManager",
"org.apache.batik.apps.svgbrowser.Main",
"org.apache.batik.apps.svgbrowser.Main$FontSizeHandler",
"org.apache.batik.util.ApplicationSecurityEnforcer",
"org.apache.batik.util.PreferenceManager",
"org.apache.batik.apps.svgbrowser.XMLPreferenceManager",
"org.apache.batik.util.XMLResourceDescriptor",
"org.apache.batik.apps.svgbrowser.XMLPreferenceManager$XMLProperties",
"org.apache.batik.util.AbstractParsedURLProtocolHandler",
"org.apache.batik.util.ParsedURLDefaultProtocolHandler",
"org.apache.batik.Version",
"org.apache.batik.util.ParsedURL",
"org.apache.batik.util.ParsedURLData",
"org.apache.batik.apps.svgbrowser.AboutDialog",
"org.apache.xml.dtm.ref.CoroutineManager",
"org.apache.xml.dtm.ref.IncrementalSAXSource_Filter",
"org.apache.xml.res.XMLErrorResources",
"org.apache.xml.res.XMLErrorResources_en",
"freemind.controller.BlindIcon",
"freemind.controller.StructuredMenuHolder",
"plugins.collaboration.database.DatabaseConnector",
"freemind.view.mindmapview.MultipleImage",
"org.apache.xml.serializer.ToSAXHandler",
"org.apache.xml.serializer.ToHTMLSAXHandler",
"freemind.controller.StructuredMenuHolder$MapTokenPair",
"org.apache.fop.fonts.FontInfo",
"org.apache.fop.pdf.PDFDocument",
"org.apache.commons.logging.impl.Log4JLogger",
"org.apache.log4j.Category",
"org.apache.log4j.Priority",
"org.apache.log4j.Level",
"org.apache.log4j.Logger",
"org.apache.log4j.Hierarchy",
"org.apache.log4j.spi.RootCategory",
"org.apache.log4j.or.DefaultRenderer",
"org.apache.log4j.or.RendererMap",
"org.apache.log4j.DefaultCategoryFactory",
"org.apache.log4j.spi.DefaultRepositorySelector",
"org.apache.log4j.helpers.OptionConverter",
"org.apache.log4j.helpers.Loader",
"org.apache.log4j.helpers.LogLog",
"org.apache.log4j.PropertyConfigurator",
"org.apache.log4j.LogManager",
"org.apache.log4j.CategoryKey",
"org.apache.log4j.ProvisionNode",
"org.apache.fop.pdf.PDFColorSpace",
"org.apache.fop.pdf.PDFFactory",
"org.apache.fop.pdf.PDFObject",
"org.apache.fop.pdf.PDFPages",
"org.apache.fop.pdf.PDFRoot",
"org.apache.fop.pdf.PDFResources",
"org.apache.fop.pdf.PDFInfo",
"org.apache.fop.pdf.PDFResourceContext",
"org.apache.fop.pdf.PDFPage",
"org.apache.batik.ext.awt.g2d.AbstractGraphics2D",
"org.apache.fop.svg.PDFGraphics2D",
"org.apache.fop.pdf.PDFState",
"org.apache.fop.pdf.PDFState$Data",
"org.apache.batik.gvt.AbstractGraphicsNode",
"org.apache.batik.gvt.CompositeGraphicsNode",
"org.apache.batik.gvt.CanvasGraphicsNode",
"org.apache.batik.svggen.DefaultExtensionHandler",
"org.apache.batik.svggen.SVGGraphics2D",
"org.apache.batik.svggen.SVGGeneratorContext",
"org.apache.batik.svggen.SVGIDGenerator",
"org.apache.batik.svggen.SVGGraphics2DRuntimeException",
"freemind.extensions.ExportHook",
"org.apache.xml.serializer.ToTextSAXHandler",
"org.apache.xml.serializer.ObjectFactory",
"org.apache.xml.serializer.SecuritySupport12$1",
"org.apache.xml.serializer.SecuritySupport12$2",
"org.apache.xml.serializer.SecuritySupport12$3",
"org.apache.xml.serializer.SecuritySupport12$6",
"org.apache.xml.serializer.Encodings",
"plugins.collaboration.socket.SocketBasics",
"plugins.collaboration.socket.SocketConnectionHook",
"org.apache.xml.serializer.ToXMLSAXHandler",
"org.hsqldb.persist.HsqlProperties",
"org.apache.fop.pdf.PDFOutline",
"freemind.controller.MapModuleManager",
"freemind.controller.MapModuleManager$MapModuleChangeObserverCompound",
"org.apache.batik.ext.awt.g2d.GraphicContext",
"org.apache.batik.ext.awt.g2d.TransformStackElement",
"org.apache.batik.ext.awt.g2d.TransformStackElement$5",
"org.apache.batik.ext.awt.g2d.TransformType",
"org.apache.batik.svggen.DefaultImageHandler",
"org.apache.batik.svggen.ImageHandlerBase64Encoder",
"org.apache.batik.svggen.SimpleImageHandler",
"org.apache.batik.svggen.DefaultStyleHandler",
"org.apache.batik.svggen.DefaultErrorHandler",
"org.apache.batik.svggen.SVGGraphicObjectConverter",
"org.apache.batik.svggen.SVGShape",
"org.apache.batik.svggen.SVGArc",
"org.apache.batik.svggen.SVGEllipse",
"org.apache.batik.svggen.SVGLine",
"org.apache.batik.svggen.SVGPath",
"org.apache.batik.svggen.SVGPolygon",
"org.apache.batik.svggen.SVGRectangle",
"org.apache.batik.svggen.DOMTreeManager",
"org.apache.xalan.templates.ElemVariablePsuedo",
"org.apache.xml.dtm.DTMManager",
"org.apache.xpath.XPathContext",
"org.apache.xml.utils.IntVector",
"org.apache.xml.utils.IntStack",
"org.apache.xml.utils.XMLStringFactory",
"org.apache.xpath.objects.XMLStringFactoryImpl",
"org.apache.xml.dtm.ObjectFactory",
"org.apache.xml.dtm.SecuritySupport12",
"org.apache.xml.dtm.SecuritySupport",
"org.apache.xml.dtm.SecuritySupport12$4",
"org.apache.xml.dtm.SecuritySupport12$7",
"org.apache.xml.dtm.SecuritySupport12$1",
"org.apache.xml.dtm.SecuritySupport12$2",
"org.apache.xml.dtm.SecuritySupport12$3",
"org.apache.xml.dtm.SecuritySupport12$6",
"org.apache.xml.dtm.ref.DTMManagerDefault",
"org.apache.xml.dtm.ref.ExtendedType",
"org.apache.xml.dtm.ref.ExpandedNameTable",
"org.apache.xml.dtm.ref.ExpandedNameTable$HashEntry",
"org.apache.xml.utils.ObjectStack",
"org.apache.xpath.SourceTreeManager",
"org.apache.xml.utils.NodeVector",
"org.apache.xpath.XPathContext$XPathExpressionContext",
"org.apache.xpath.VariableStack",
"plugins.collaboration.socket.MindMapMaster",
"org.apache.fop.svg.PDFDocumentGraphics2D",
"org.apache.fop.fonts.FontSetup",
"org.apache.fop.fonts.Typeface",
"org.apache.fop.fonts.base14.Helvetica",
"org.apache.fop.fonts.CodePointMapping",
"org.apache.fop.fonts.base14.HelveticaOblique",
"org.apache.fop.fonts.base14.HelveticaBold",
"org.apache.fop.fonts.base14.HelveticaBoldOblique",
"org.apache.fop.fonts.base14.TimesRoman",
"org.apache.fop.fonts.base14.TimesItalic",
"org.apache.fop.fonts.base14.TimesBold",
"org.apache.fop.fonts.base14.TimesBoldItalic",
"org.apache.fop.fonts.base14.Courier",
"org.apache.fop.fonts.base14.CourierOblique",
"org.apache.fop.fonts.base14.CourierBold",
"org.apache.fop.fonts.base14.CourierBoldOblique",
"org.apache.fop.fonts.base14.Symbol",
"org.apache.fop.fonts.base14.ZapfDingbats",
"org.apache.fop.pdf.AbstractPDFStream",
"org.apache.fop.pdf.PDFStream",
"org.apache.fop.pdf.StreamCacheFactory",
"org.apache.fop.pdf.InMemoryStreamCache",
"org.apache.fop.pdf.PDFFilterList",
"org.apache.fop.pdf.PDFFilter",
"org.apache.fop.pdf.FlateFilter",
"freemind.modes.mindmapmode.actions.FreemindAction",
"freemind.modes.mindmapmode.actions.xml.AbstractXmlAction",
"freemind.modes.mindmapmode.actions.NodeGeneralAction",
"freemind.modes.mindmapmode.actions.NodeColorBlendAction",
"freemind.modes.mindmapmode.actions.NodeColorBlendAction$1",
"org.apache.xalan.transformer.TransformerImpl",
"org.apache.xml.utils.ObjectPool",
"org.apache.xml.serializer.ToTextStream",
"org.apache.xalan.transformer.KeyManager",
"org.apache.xalan.trace.TraceManager",
"org.apache.xalan.transformer.StackGuard",
"org.apache.xml.utils.XMLStringDefault",
"org.apache.xml.utils.XMLStringFactoryDefault",
"org.apache.xml.dtm.ref.DTMDefaultBase",
"org.apache.xml.dtm.ref.DTMDefaultBaseTraversers",
"org.apache.xml.dtm.ref.DTMDefaultBaseIterators",
"org.apache.xml.dtm.ref.sax2dtm.SAX2DTM",
"org.apache.xml.dtm.ref.sax2dtm.SAX2DTM2",
"org.apache.xml.utils.SuballocatedIntVector",
"org.apache.fop.svg.GraphicsConfiguration",
"org.apache.fop.svg.PDFGraphicsConfiguration",
"org.hsqldb.lib.HsqlByteArrayInputStream",
"org.hsqldb.rowio.RowInputBase",
"org.hsqldb.rowio.RowInputText",
"freemind.controller.StructuredMenuItemHolder",
"freemind.controller.filter.condition.ConjunctConditions",
"freemind.controller.filter.condition.JCondition",
"freemind.controller.filter.condition.IconNotContainedCondition",
"freemind.modes.MindIcon",
"org.hsqldb.lib.HsqlByteArrayOutputStream",
"org.hsqldb.rowio.RowOutputBase",
"org.hsqldb.rowio.RowOutputTextLog",
"freemind.controller.filter.condition.SelectedViewCondition",
"freemind.controller.filter.condition.ConditionFactory",
"plugins.collaboration.socket.MindMapClient",
"org.openstreetmap.gui.jmapviewer.JMapViewer",
"org.openstreetmap.gui.jmapviewer.MemoryTileCache",
"org.openstreetmap.gui.jmapviewer.MemoryTileCache$CacheLinkedListElement",
"org.openstreetmap.gui.jmapviewer.AttributionSupport",
"org.openstreetmap.gui.jmapviewer.tilesources.AbstractTileSource",
"org.openstreetmap.gui.jmapviewer.tilesources.AbstractTMSTileSource",
"org.openstreetmap.gui.jmapviewer.tilesources.AbstractOsmTileSource",
"org.openstreetmap.gui.jmapviewer.tilesources.OsmTileSource$Mapnik",
"org.openstreetmap.gui.jmapviewer.TileController",
"org.openstreetmap.gui.jmapviewer.JobDispatcher$JobThread",
"org.openstreetmap.gui.jmapviewer.JobDispatcher",
"org.openstreetmap.gui.jmapviewer.JMapViewer$1",
"org.openstreetmap.gui.jmapviewer.JMapViewer$2",
"org.openstreetmap.gui.jmapviewer.JMapViewer$3",
"org.openstreetmap.gui.jmapviewer.OsmMercator",
"org.openstreetmap.gui.jmapviewer.JMapController",
"org.openstreetmap.gui.jmapviewer.DefaultMapController",
"freemind.modes.mindmapmode.actions.UseRichFormattingAction",
"freemind.modes.mindmapmode.actions.UseRichFormattingAction$1",
"org.apache.batik.svggen.AbstractImageHandlerEncoder",
"org.apache.batik.svggen.ImageHandlerPNGEncoder",
"org.hsqldb.DatabaseURL",
"org.hsqldb.jdbc.Util",
"org.hsqldb.store.BaseHashMap",
"org.hsqldb.lib.HashMap",
"org.hsqldb.store.HashIndex",
"org.hsqldb.lib.BaseList",
"org.hsqldb.lib.HsqlArrayList",
"org.hsqldb.resources.BundleHandler",
"org.hsqldb.Trace",
"org.hsqldb.HsqlException",
"freemind.modes.mindmapmode.actions.NodeUpAction",
"org.apache.xalan.transformer.XalanTransformState"
);
}
}
|
package com.raul.libraryproject.app.controller;
import java.util.Map;
import java.util.NoSuchElementException;
import com.raul.libraryproject.model.book.Book;
import com.raul.libraryproject.model.dao.DAO;
import com.raul.libraryproject.model.facades.BookSearcher;
import com.raul.libraryproject.model.facades.QueueManager;
import com.raul.libraryproject.model.facades.ReaderSearcher;
import com.raul.libraryproject.model.junction.JunctionEntity;
import com.raul.libraryproject.model.reader.Reader;
import com.raul.libraryproject.util.datastructure.Queue;
/**
* <p>
* BorrowManagerController can look a little intimidating but actually, it
* only applies the Builder Design Pattern. This controller requires
* many parameter to perform a book being borrowed to the library, the
* update of a borrowing list, the check of a queue to determine if a book
* is available to the reader in queue.
* Any further detail is available in the methods documentation..
* </p>
*
* <p><b>Created at: </b>03/12/2020</p>
*
* @author Raul Macedo Fuzita
*
* @version 1.0.0
*
*/
public class BorrowManagerController {
/*
* All these attributes should not be access.
* If attributes values have to be set it should happen
* thrown the builder pattern.
*/
private Map<Long, Queue<JunctionEntity>> queuesMap;
private DAO<Book> bookDAO;
private DAO<Reader> readerDAO;
private DAO<JunctionEntity> borrowingDAO;
private DAO<JunctionEntity> waitingDAO;
// Builder class
public static class Builder {
private Map<Long, Queue<JunctionEntity>> queuesMap;
private DAO<Book> bookDAO;
private DAO<Reader> readerDAO;
private DAO<JunctionEntity> borrowingDAO;
private DAO<JunctionEntity> waitingDAO;
public Builder() {}
// Chainable methods
/**
* This method sets queue Map
* @param queuesMap is a {@code Map<Long, Queue<JunctionEntity>>}
* @return Builder
*/
public Builder queuesMap(Map<Long, Queue<JunctionEntity>> queuesMap) {
this.queuesMap = queuesMap;
return this;
}
/**
* This method sets a book DAO.
* @param bookDAO is a {@code DAO<Book>}
* @return Builder
*/
public Builder bookDAO(DAO<Book> bookDAO) {
this.bookDAO = bookDAO;
return this;
}
/**
* This method sets a book DAO
* @param readerDAO is a {@code DAO<Reader>}
* @return Builder
*/
public Builder readerDAO(DAO<Reader> readerDAO) {
this.readerDAO = readerDAO;
return this;
}
/**
* This method sets a borrowing DAO
* @param borrowingDAO is a {@code DAO<JunctionEntity>}
* @return Builder
*/
public Builder borrowingDAO(DAO<JunctionEntity> borrowingDAO) {
this.borrowingDAO = borrowingDAO;
return this;
}
/**
* This method sets a waiting DAO
* @param waitingDAO {@code DAO<JunctionEntity>}
* @return Builder
*/
public Builder waitingDAO(DAO<JunctionEntity> waitingDAO) {
this.waitingDAO = waitingDAO;
return this;
}
/* When all parameters are set or the desired ones it should invokes
* method build. */
public BorrowManagerController build() {
return new BorrowManagerController(this);
}
}
// Makes impossible to instance the constructor without using the Builder
private BorrowManagerController(Builder builder) {
queuesMap = builder.queuesMap;
bookDAO = builder.bookDAO;
readerDAO = builder.readerDAO;
borrowingDAO = builder.borrowingDAO;
waitingDAO = builder.waitingDAO;
}
/**
* This method prompts a message and requires inputs to decide
* which reader wants to borrow what book.
*
* BookBorrowingController is instantiated to perform a book borrowing.
*
*/
public void run() {
System.out.println("\n************ BORROW A BOOK **************");
System.out.println("* Search a reader to lend him/her a book*");
System.out.println("* Then search a book to check its *");
System.out.println("* availability. If it's available the *");
System.out.println("* book will be lent by the reader. *");
System.out.println("*****************************************");
QueueManager qm = new QueueManager(queuesMap);
ReaderSearcher readerSearcher = new ReaderSearcher(readerDAO);
BookSearcher bookSearcher = new BookSearcher(bookDAO);
BookBorrowingController bbc =
new BookBorrowingController(borrowingDAO);
Reader reader = null;
Book book = null;
try {
reader = readerSearcher.fetchReader();
book = bookSearcher.fetchBook();
/*
* If books is available book and reader ID will be stored
* in the borrowing list. For further information check out the
* method borroBook documentation. Then the book ID is retrieve
* to update the book list (list in the book DAO)
*/
if (bbc.borrowBook(reader, book)) {
long id = book.getId();
this.bookDAO.update((int)id-1, book);
} else {
/*
* If book is not available then it should be stored in a
* JunctionEntity object and then passed into the QueueManager
* method enqueue to add it to the queue. It is also stored
* in the waiting DAO object for persistence purposes.
*/
System.out.println("\nBook is not available yet");
System.out.println("Reader " + reader.getFullname()
+ " has been enqueued in the waiting list for the book\n");
System.out.println(book.simpleInformation());
JunctionEntity entity =
new JunctionEntity(book.getId(), reader.getId());
qm.enqueue(entity);
this.waitingDAO.add(entity);
}
} catch (NoSuchElementException e) {
System.out.println("\n[No Such a Record]\n");
}
}
}
|
/*
* Copyright 2002-2018 the original author or 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
*
* 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 org.springframework.beans.factory;
import org.springframework.beans.BeansException;
/**
* Defines a factory which can return an Object instance
* (possibly shared or independent) when invoked.
*
* <p>This interface is typically used to encapsulate a generic factory which
* returns a new instance (prototype) of some target object on each invocation.
*
* <p>This interface is similar to {@link FactoryBean}, but implementations
* of the latter are normally meant to be defined as SPI instances in a
* {@link BeanFactory}, while implementations of this class are normally meant
* to be fed as an API to other beans (through injection). As such, the
* {@code getObject()} method has different exception handling behavior.
*
* @author Colin Sampaleanu
* @since 1.0.2
* @param <T> the object type
* @see FactoryBean
* 类似于FactoryBean
*/
@FunctionalInterface
public interface ObjectFactory<T> {
/**
* Return an instance (possibly shared or independent)
* of the object managed by this factory.
* 返回一个实例(可能是共享的或独立的),由该工厂管理的对象。
* 做的事情就是解决循环依赖的第三步操作:将三级缓存中的额bean放入到二级缓存中。(升级过程中可以做一些扩展性的操作)
* @return the resulting instance 返回结果实例
* @throws BeansException in case of creation errors 在创建错误的情况下抛出BeansException
*/
T getObject() throws BeansException;
}
|
package com.networknt.oas.model.impl;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.databind.JsonNode;
import com.networknt.jsonoverlay.Builder;
import com.networknt.jsonoverlay.IJsonOverlay;
import com.networknt.jsonoverlay.JsonOverlay;
import com.networknt.jsonoverlay.OverlayFactory;
import com.networknt.jsonoverlay.PropertiesOverlay;
import com.networknt.jsonoverlay.ReferenceManager;
import com.networknt.jsonoverlay.StringOverlay;
import com.networknt.oas.model.Discriminator;
import com.networknt.oas.model.OpenApi3;
public class DiscriminatorImpl extends PropertiesOverlay<Discriminator> implements Discriminator {
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public DiscriminatorImpl(JsonNode json, JsonOverlay<?> parent, ReferenceManager refMgr) {
super(json, parent, factory, refMgr);
}
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public DiscriminatorImpl(Discriminator discriminator, JsonOverlay<?> parent, ReferenceManager refMgr) {
super(discriminator, parent, factory, refMgr);
}
// PropertyName
@Override
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public String getPropertyName() {
return _get("propertyName", String.class);
}
@Override
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public void setPropertyName(String propertyName) {
_setScalar("propertyName", propertyName, String.class);
}
// Mapping
@Override
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public Map<String, String> getMappings() {
return _getMap("mappings", String.class);
}
@Override
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public Map<String, String> getMappings(boolean elaborate) {
return _getMap("mappings", elaborate, String.class);
}
@Override
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public boolean hasMappings() {
return _isPresent("mappings");
}
@Override
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public boolean hasMapping(String name) {
return _getMap("mappings", String.class).containsKey(name);
}
@Override
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public String getMapping(String name) {
return _get("mappings", name, String.class);
}
@Override
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public void setMappings(Map<String, String> mappings) {
_setMap("mappings", mappings, String.class);
}
@Override
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public void setMapping(String name, String mapping) {
_set("mappings", name, mapping, String.class);
}
@Override
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public void removeMapping(String name) {
_remove("mappings", name, String.class);
}
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public static final String F_propertyName = "propertyName";
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public static final String F_mappings = "mappings";
@Override
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
protected void _elaborateJson() {
super._elaborateJson();
_createScalar("propertyName", "propertyName", StringOverlay.factory);
_createMap("mappings", "mapping", StringOverlay.factory, null);
}
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public static OverlayFactory<Discriminator> factory = new OverlayFactory<Discriminator>() {
@Override
protected Class<? extends JsonOverlay<? super Discriminator>> getOverlayClass() {
return DiscriminatorImpl.class;
}
@Override
public JsonOverlay<Discriminator> _create(Discriminator discriminator, JsonOverlay<?> parent,
ReferenceManager refMgr) {
JsonOverlay<?> overlay;
overlay = new DiscriminatorImpl(discriminator, parent, refMgr);
@SuppressWarnings("unchecked")
JsonOverlay<Discriminator> castOverlay = (JsonOverlay<Discriminator>) overlay;
return castOverlay;
}
@Override
public JsonOverlay<Discriminator> _create(JsonNode json, JsonOverlay<?> parent, ReferenceManager refMgr) {
JsonOverlay<?> overlay;
overlay = new DiscriminatorImpl(json, parent, refMgr);
@SuppressWarnings("unchecked")
JsonOverlay<Discriminator> castOverlay = (JsonOverlay<Discriminator>) overlay;
return castOverlay;
}
@Override
protected boolean isExtendedType() {
return false;
}
};
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
private static Class<? extends Discriminator> getSubtypeOf(Discriminator discriminator) {
return Discriminator.class;
}
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
private static Class<? extends Discriminator> getSubtypeOf(JsonNode json) {
return Discriminator.class;
}
@Override
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public Class<?> _getModelType() {
return OpenApi3.class;
}
@Override
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
protected OverlayFactory<?> _getFactory() {
return factory;
}
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public static <OV extends IJsonOverlay<?>> Builder<Discriminator> builder(OV modelMember) {
return new Builder<Discriminator>(factory, modelMember);
}
@Generated("com.reprezen.jsonoverlay.gen.CodeGenerator")
public static <OV extends IJsonOverlay<?>> Discriminator create(OV modelMember) {
return (Discriminator) builder(modelMember).build();
}
}
|
/*
* Pore
* Copyright (c) 2014-2016, Lapis <https://github.com/LapisBlue>
*
* The MIT License
*
* 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 blue.lapis.pore.converter.type.world;
import blue.lapis.pore.converter.type.TypeConverter;
import com.google.common.base.Converter;
import org.bukkit.WorldType;
import org.spongepowered.api.world.GeneratorType;
import org.spongepowered.api.world.GeneratorTypes;
public final class GeneratorTypeConverter {
private GeneratorTypeConverter() {
}
private static final Converter<WorldType, GeneratorType> CONVERTER =
TypeConverter.builder(WorldType.class, GeneratorType.class)
.add(WorldType.NORMAL, GeneratorTypes.DEFAULT)
.add(WorldType.FLAT, GeneratorTypes.FLAT)
/*.add(WorldType.LARGE_BIOMES, GeneratorTypes.LARGE_BIOME)
.add(WorldType.AMPLIFIED, GeneratorTypes.AMPLIFIED) TODO */
.add(WorldType.CUSTOMIZED, GeneratorTypes.DEBUG) //TODO: no idea whether this is right
.build();
public static GeneratorType of(WorldType worldType) {
return CONVERTER.convert(worldType);
}
public static WorldType of(GeneratorType dimension) {
return CONVERTER.reverse().convert(dimension);
}
}
|
package org.scoalaonline.api.model;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import org.scoalaonline.api.serializer.SongSerializer;
import javax.persistence.*;
import java.util.*;
@Entity
@Table(name = "artist")
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "idArtist")
public class Artist
{
//--------------- Fields ---------------
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator",
parameters = {
@org.hibernate.annotations.Parameter(
name = "uuid_gen_strategy_class",
value = "org.hibernate.id.uuid.CustomVersionOneStrategy"
)
}
)
@Type(type="uuid-char")
@Column(name = "artist_id", updatable = false, nullable = false)
private UUID idArtist;
@Column(name = "artist_name", nullable = false, length = 50)
private String name;
@ManyToMany
@JoinTable(
name = "song_artist",
joinColumns = @JoinColumn(name = "artist_id"),
inverseJoinColumns = @JoinColumn(name = "song_id")
)
@JsonSerialize(using = SongSerializer.class)
private List<Song> songs;
public Artist() {
}
//--------------- Getters ---------------
public UUID getIdArtist() {
return idArtist;
}
public String getName() {
return name;
}
public List<Song> getSongs() {
return new ArrayList<Song>(songs);
}
//--------------- Setters ---------------
public void setIdArtist(UUID idArtist) {
this.idArtist = idArtist;
}
public void setName(String name) {
this.name = name;
}
public void setSongs(List<Song> songs) {
this.songs = new ArrayList<Song>(songs);
}
//--------------- Equals & Hashcode ---------------
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Artist)) return false;
Artist artist = (Artist) o;
return idArtist == artist.idArtist &&
Objects.equals(name, artist.name) &&
Objects.equals(songs, artist.songs);
}
@Override
public int hashCode() {
return Objects.hash(idArtist, name, songs);
}
}
|
/*
* Copyright (c) 2021, the hapjs-platform Project Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.hapjs;
import android.app.Activity;
import android.content.Intent;
public class ActivityHookManager {
private static ActivityHook sActivityHook;
public static void init(ActivityHook activityHook) {
sActivityHook = activityHook;
}
public static boolean onStartActivity(Activity activity, Intent intent) {
if (sActivityHook != null) {
return sActivityHook.onStartActivity(activity, intent);
} else {
return false;
}
}
public interface ActivityHook {
boolean onStartActivity(Activity activity, Intent intent);
}
}
|
/*
* spoonacular API
* The spoonacular Nutrition, Recipe, and Food API allows you to access over 380,000 recipes, thousands of ingredients, 800,000 food products, and 100,000 menu items. Our food ontology and semantic recipe search engine makes it possible to search for recipes using natural language queries, such as \"gluten free brownies without sugar\" or \"low fat vegan cupcakes.\" You can automatically calculate the nutritional information for any recipe, analyze recipe costs, visualize ingredient lists, find recipes for what's in your fridge, find recipes based on special diets, nutritional requirements, or favorite ingredients, classify recipes into types and cuisines, convert ingredient amounts, or even compute an entire meal plan. With our powerful API, you can create many kinds of food and especially nutrition apps. Special diets/dietary requirements currently available include: vegan, vegetarian, pescetarian, gluten free, grain free, dairy free, high protein, whole 30, low sodium, low carb, Paleo, ketogenic, FODMAP, and Primal.
*
* The version of the OpenAPI document: 1.0
* Contact: mail@spoonacular.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.spoonacular.client.model;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.spoonacular.client.model.InlineResponse20035MenuItems;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Model tests for InlineResponse20035
*/
public class InlineResponse20035Test {
private final InlineResponse20035 model = new InlineResponse20035();
/**
* Model tests for InlineResponse20035
*/
@Test
public void testInlineResponse20035() {
// TODO: test InlineResponse20035
}
/**
* Test the property 'menuItems'
*/
@Test
public void menuItemsTest() {
// TODO: test menuItems
}
/**
* Test the property 'totalMenuItems'
*/
@Test
public void totalMenuItemsTest() {
// TODO: test totalMenuItems
}
/**
* Test the property 'type'
*/
@Test
public void typeTest() {
// TODO: test type
}
/**
* Test the property 'offset'
*/
@Test
public void offsetTest() {
// TODO: test offset
}
/**
* Test the property 'number'
*/
@Test
public void numberTest() {
// TODO: test number
}
}
|
/*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.identity.api.server.userstore.v1.core;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.api.server.common.ContextLoader;
import org.wso2.carbon.identity.api.server.common.error.APIError;
import org.wso2.carbon.identity.api.server.common.error.ErrorResponse;
import org.wso2.carbon.identity.api.server.userstore.common.UserStoreConfigServiceHolder;
import org.wso2.carbon.identity.api.server.userstore.common.UserStoreConstants;
import org.wso2.carbon.identity.api.server.userstore.v1.model.AddUserStorePropertiesRes;
import org.wso2.carbon.identity.api.server.userstore.v1.model.Attribute;
import org.wso2.carbon.identity.api.server.userstore.v1.model.AvailableUserStoreClassesRes;
import org.wso2.carbon.identity.api.server.userstore.v1.model.ClaimAttributeMapping;
import org.wso2.carbon.identity.api.server.userstore.v1.model.ConnectionEstablishedResponse;
import org.wso2.carbon.identity.api.server.userstore.v1.model.MetaUserStoreType;
import org.wso2.carbon.identity.api.server.userstore.v1.model.PatchDocument;
import org.wso2.carbon.identity.api.server.userstore.v1.model.PropertiesRes;
import org.wso2.carbon.identity.api.server.userstore.v1.model.RDBMSConnectionReq;
import org.wso2.carbon.identity.api.server.userstore.v1.model.UserStoreAttributeMapping;
import org.wso2.carbon.identity.api.server.userstore.v1.model.UserStoreConfigurationsRes;
import org.wso2.carbon.identity.api.server.userstore.v1.model.UserStoreListResponse;
import org.wso2.carbon.identity.api.server.userstore.v1.model.UserStorePropertiesRes;
import org.wso2.carbon.identity.api.server.userstore.v1.model.UserStoreReq;
import org.wso2.carbon.identity.api.server.userstore.v1.model.UserStoreResponse;
import org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataManagementService;
import org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataClientException;
import org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException;
import org.wso2.carbon.identity.claim.metadata.mgt.model.AttributeMapping;
import org.wso2.carbon.identity.claim.metadata.mgt.model.LocalClaim;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.user.store.configuration.UserStoreConfigService;
import org.wso2.carbon.identity.user.store.configuration.dto.PropertyDTO;
import org.wso2.carbon.identity.user.store.configuration.dto.UserStoreDTO;
import org.wso2.carbon.identity.user.store.configuration.model.UserStoreAttributeDO;
import org.wso2.carbon.identity.user.store.configuration.model.UserStoreAttributeMappings;
import org.wso2.carbon.identity.user.store.configuration.utils.IdentityUserStoreClientException;
import org.wso2.carbon.identity.user.store.configuration.utils.IdentityUserStoreMgtException;
import org.wso2.carbon.identity.user.store.configuration.utils.IdentityUserStoreServerException;
import org.wso2.carbon.user.api.Properties;
import org.wso2.carbon.user.api.Property;
import org.wso2.carbon.user.api.RealmConfiguration;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.UserCoreConstants;
import org.wso2.carbon.user.core.UserStoreConfigConstants;
import org.wso2.carbon.user.core.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tracker.UserStoreManagerRegistry;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import javax.ws.rs.core.Response;
import static org.wso2.carbon.identity.api.server.common.Constants.ERROR_CODE_RESOURCE_LIMIT_REACHED;
import static org.wso2.carbon.identity.api.server.common.Constants.REGEX_COMMA;
import static org.wso2.carbon.identity.api.server.common.Constants.V1_API_PATH_COMPONENT;
import static org.wso2.carbon.identity.api.server.userstore.common.UserStoreConstants.ErrorMessage.ERROR_CODE_USER_STORE_LIMIT_REACHED;
/**
* Call internal osgi services to perform user store related operations.
*/
public class ServerUserStoreService {
private static final Log LOG = LogFactory.getLog(ServerUserStoreService.class);
private static final String DUMMY_MESSAGE_ID = "DUMMY-MESSAGE-ID";
private static boolean isAvailableUserStoreTypes(List<AvailableUserStoreClassesRes> userStoreList, String typeID) {
for (AvailableUserStoreClassesRes userStore : userStoreList) {
if (userStore.getTypeId().equals(typeID)) {
return true;
}
}
return false;
}
/**
* Add a userStore {@link UserStoreReq}.
*
* @param userStoreReq {@link UserStoreReq} to insert.
* @return UserStoreResponse
*/
public UserStoreResponse addUserStore(UserStoreReq userStoreReq) {
try {
validateMandatoryProperties(userStoreReq);
if (!isAvailableUserStoreTypes(getAvailableUserStoreTypes(), userStoreReq.getTypeId())) {
throw handleException(Response.Status.BAD_REQUEST,
UserStoreConstants.ErrorMessage.ERROR_CODE_INVALID_USERSTORE_TYPE);
}
String userstoreDomain = userStoreReq.getName();
String tenantDomain = ContextLoader.getTenantDomainFromContext();
List<LocalClaim> localClaimList = new ArrayList<>();
List<ClaimAttributeMapping> claimAttributeMappingList = userStoreReq.getClaimAttributeMappings();
if (claimAttributeMappingList != null) {
localClaimList = createLocalClaimList(userstoreDomain, claimAttributeMappingList);
validateClaimMappings(tenantDomain, localClaimList);
}
UserStoreConfigService userStoreConfigService = UserStoreConfigServiceHolder.getInstance()
.getUserStoreConfigService();
UserStoreDTO userStoreDTO = createUserStoreDTO(userStoreReq);
userStoreConfigService.addUserStore(userStoreDTO);
if (claimAttributeMappingList != null) {
updateClaimMappings(userstoreDomain, tenantDomain, localClaimList);
}
return buildUserStoreResponseDTO(userStoreReq);
} catch (IdentityUserStoreMgtException e) {
UserStoreConstants.ErrorMessage errorEnum =
UserStoreConstants.ErrorMessage.ERROR_CODE_ERROR_ADDING_USER_STORE;
throw handleIdentityUserStoreMgtException(e, errorEnum);
}
}
/**
* Delete a userStore by its domainId.
*
* @param userstoreDomainId base64 encoded url value of userStore domain Id.
*/
public void deleteUserStore(String userstoreDomainId) {
try {
UserStoreConfigService userStoreConfigService = UserStoreConfigServiceHolder.getInstance().
getUserStoreConfigService();
userStoreConfigService.deleteUserStore(base64URLDecodeId(userstoreDomainId));
} catch (IdentityUserStoreClientException e) {
if (LOG.isDebugEnabled()) {
LOG.debug(e);
}
} catch (IdentityUserStoreMgtException e) {
UserStoreConstants.ErrorMessage errorEnum =
UserStoreConstants.ErrorMessage.ERROR_CODE_ERROR_DELETING_USER_STORE;
throw handleIdentityUserStoreMgtException(e, errorEnum);
}
}
/**
* Update the user store by its domain Id.
*
* @param domainId the domain name to be replaced
* @param userStoreReq {@link UserStoreReq} to edit.
* @return UserStoreResponse.
*/
public UserStoreResponse editUserStore(String domainId, UserStoreReq userStoreReq) {
UserStoreConfigService userStoreConfigService = UserStoreConfigServiceHolder.getInstance().
getUserStoreConfigService();
/*
domainName and typeName are not allowed to edit. iF domain name wanted to update then use
userStoreConfigService.updateUserStoreByDomainName(base64URLDecodeId(domainId),
createUserStoreDTO(userStoreReq, domainId));
*/
try {
validateUserstoreUpdateRequest(domainId, userStoreReq);
userStoreConfigService.updateUserStore(createUserStoreDTO(userStoreReq), false);
return buildUserStoreResponseDTO(userStoreReq);
} catch (IdentityUserStoreMgtException e) {
UserStoreConstants.ErrorMessage errorEnum =
UserStoreConstants.ErrorMessage.ERROR_CODE_ERROR_UPDATING_USER_STORE;
throw handleIdentityUserStoreMgtException(e, errorEnum);
}
}
/**
* To retrieve the available user store classes.
*
* @return List<AvailableUserStoreClassesRes>.
*/
public List<AvailableUserStoreClassesRes> getAvailableUserStoreTypes() {
UserStoreConfigService userStoreConfigService = UserStoreConfigServiceHolder.getInstance().
getUserStoreConfigService();
Set<String> classNames;
try {
classNames = userStoreConfigService.getAvailableUserStoreClasses();
List<AvailableUserStoreClassesRes> propertiesToAdd = new ArrayList<>();
Map<String, Boolean> userStoreManagersType = UserStoreManagerRegistry.getUserStoreManagersType();
for (String className : classNames) {
AvailableUserStoreClassesRes availableUserStoreClassesResDTO = new AvailableUserStoreClassesRes();
String typeId = base64URLEncodeId(Objects.
requireNonNull(getUserStoreTypeName(className)));
availableUserStoreClassesResDTO.setClassName(className);
availableUserStoreClassesResDTO.setTypeName(getUserStoreTypeName(className));
availableUserStoreClassesResDTO.setTypeId(typeId);
availableUserStoreClassesResDTO.setSelf(
ContextLoader.buildURIForBody(String.format(V1_API_PATH_COMPONENT +
UserStoreConstants.USER_STORE_PATH_COMPONENT + "/meta/types/%s", typeId)).toString());
if (userStoreManagersType.containsKey(className)) {
availableUserStoreClassesResDTO
.setIsLocal(userStoreManagersType.get(className));
}
propertiesToAdd.add(availableUserStoreClassesResDTO);
}
return propertiesToAdd;
} catch (IdentityUserStoreMgtException e) {
UserStoreConstants.ErrorMessage errorEnum =
UserStoreConstants.ErrorMessage.ERROR_CODE_RETRIEVING_USER_STORE_TYPE;
throw handleIdentityUserStoreMgtException(e, errorEnum);
}
}
/**
* To retrieve the configured user store lists.
*
* @param limit items per page.
* @param offset 0 based index to get the results starting from this index + 1.
* @param filter to specify the filtering capabilities.
* @param sort to specify the sorting order.
* @return List<UserStoreListResponse>.
*/
public List<UserStoreListResponse> getUserStoreList(Integer limit, Integer offset, String filter, String sort,
String requiredAttributes) {
handleNotImplementedBehaviour(limit, offset, filter, sort);
UserStoreConfigService userStoreConfigService = UserStoreConfigServiceHolder.getInstance()
.getUserStoreConfigService();
try {
UserStoreDTO[] userStoreDTOS = userStoreConfigService.getUserStores();
return buildUserStoreListResponse(userStoreDTOS, requiredAttributes);
} catch (IdentityUserStoreMgtException e) {
UserStoreConstants.ErrorMessage errorEnum =
UserStoreConstants.ErrorMessage.ERROR_CODE_ERROR_RETRIEVING_USER_STORE;
throw handleIdentityUserStoreMgtException(e, errorEnum);
}
}
/**
* Retrieve primary user store.
*
* @return UserStoreConfigurationsRes.
*/
public UserStoreConfigurationsRes getPrimaryUserStore() {
RealmService realmService = UserStoreConfigServiceHolder.getInstance().getRealmService();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
RealmConfiguration realmConfiguration;
try {
realmConfiguration = realmService.getTenantUserRealm(tenantId).getRealmConfiguration();
} catch (UserStoreException exception) {
if (LOG.isDebugEnabled()) {
LOG.debug("Error occurred while getting the RealmConfiguration for tenant: " + tenantId, exception);
}
throw handleException(Response.Status.INTERNAL_SERVER_ERROR, UserStoreConstants.ErrorMessage.
ERROR_CODE_ERROR_RETRIEVING_REALM_CONFIG, Integer.toString(tenantId));
}
if (realmConfiguration == null) {
throw handleException(Response.Status.INTERNAL_SERVER_ERROR, UserStoreConstants.ErrorMessage.
ERROR_CODE_ERROR_RETRIEVING_PRIMARY_USERSTORE);
}
List<AddUserStorePropertiesRes> propertiesTobeAdd = new ArrayList<>();
UserStoreConfigurationsRes primaryUserstoreConfigs = new UserStoreConfigurationsRes();
primaryUserstoreConfigs.setClassName(realmConfiguration.getUserStoreClass());
primaryUserstoreConfigs.setDescription(realmConfiguration.getDescription());
primaryUserstoreConfigs.setName(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME);
primaryUserstoreConfigs.setTypeId(base64URLEncodeId(Objects.requireNonNull
(getUserStoreTypeName(realmConfiguration.getUserStoreClass()))));
primaryUserstoreConfigs.setTypeName(getUserStoreTypeName(realmConfiguration.getUserStoreClass()));
Map<String, String> userstoreProps = realmConfiguration.getUserStoreProperties();
if (MapUtils.isNotEmpty(userstoreProps)) {
for (Map.Entry<String, String> entry : userstoreProps.entrySet()) {
AddUserStorePropertiesRes userStorePropertiesRes = new AddUserStorePropertiesRes();
userStorePropertiesRes.setName(entry.getKey());
if (UserStoreConfigConstants.connectionPassword.equals(entry.getKey())) {
userStorePropertiesRes.setValue(UserStoreConstants.USER_STORE_PROPERTY_MASK);
} else {
userStorePropertiesRes.setValue(entry.getValue());
}
propertiesTobeAdd.add(userStorePropertiesRes);
}
}
primaryUserstoreConfigs.setProperties(propertiesTobeAdd);
try {
primaryUserstoreConfigs.setIsLocal(UserStoreManagerRegistry.
isLocalUserStore(realmConfiguration.getUserStoreClass()));
List<ClaimAttributeMapping> claimAttributeMappings = getClaimAttributeMappings(
ContextLoader.getTenantDomainFromContext(), UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME);
primaryUserstoreConfigs.setClaimAttributeMappings(claimAttributeMappings);
} catch (UserStoreException e) {
LOG.error(String.format("Cannot found user store manager type for user store manager: %s",
getUserStoreType(realmConfiguration.getUserStoreClass())), e);
}
return primaryUserstoreConfigs;
}
/**
* Retrieve user store by its domain id.
*
* @param domainId the user store domain id.
* @return UserStoreConfigurationsRes.
*/
public UserStoreConfigurationsRes getUserStoreByDomainId(String domainId) {
UserStoreConfigService userStoreConfigService = UserStoreConfigServiceHolder.getInstance()
.getUserStoreConfigService();
List<AddUserStorePropertiesRes> propertiesTobeAdd = new ArrayList<>();
try {
UserStoreDTO userStoreDTO = userStoreConfigService.getUserStore(base64URLDecodeId(domainId));
if (userStoreDTO == null) {
throw handleException(Response.Status.NOT_FOUND, UserStoreConstants.ErrorMessage.
ERROR_CODE_NOT_FOUND);
}
List<ClaimAttributeMapping> claimAttributeMappings = getClaimAttributeMappings(
ContextLoader.getTenantDomainFromContext(), base64URLDecodeId(domainId));
UserStoreConfigurationsRes userStoreConfigurations = new UserStoreConfigurationsRes();
userStoreConfigurations.setClassName(userStoreDTO.getClassName());
userStoreConfigurations.setDescription(userStoreDTO.getDescription());
userStoreConfigurations.setName(userStoreDTO.getDomainId());
userStoreConfigurations.setTypeId(base64URLEncodeId(Objects.requireNonNull
(getUserStoreTypeName(userStoreDTO.getClassName()))));
userStoreConfigurations.setTypeName(getUserStoreTypeName(userStoreDTO.getClassName()));
PropertyDTO[] dtoProperties = userStoreDTO.getProperties();
for (PropertyDTO propertyDTO : dtoProperties) {
AddUserStorePropertiesRes userStorePropertiesRes = new AddUserStorePropertiesRes();
userStorePropertiesRes.setName(propertyDTO.getName());
userStorePropertiesRes.setValue(propertyDTO.getValue());
propertiesTobeAdd.add(userStorePropertiesRes);
}
userStoreConfigurations.setProperties(propertiesTobeAdd);
try {
userStoreConfigurations
.setIsLocal(UserStoreManagerRegistry.isLocalUserStore(userStoreDTO.getClassName()));
userStoreConfigurations.setClaimAttributeMappings(claimAttributeMappings);
} catch (UserStoreException e) {
LOG.error(String.format("Cannot found user store manager type for user store manager: %s",
getUserStoreType(userStoreDTO.getClassName())), e);
}
return userStoreConfigurations;
} catch (IdentityUserStoreMgtException e) {
UserStoreConstants.ErrorMessage errorEnum =
UserStoreConstants.ErrorMessage.ERROR_CODE_ERROR_RETRIEVING_USER_STORE_BY_DOMAIN_ID;
throw handleIdentityUserStoreMgtException(e, errorEnum);
}
}
/**
* Retrieve the meta of user store type.
*
* @param typeId the user store type id.
* @return MetaUserStoreType.
*/
public MetaUserStoreType getUserStoreManagerProperties(String typeId) {
UserStoreConfigService userStoreConfigService = UserStoreConfigServiceHolder.getInstance()
.getUserStoreConfigService();
Set<String> classNames;
try {
classNames = userStoreConfigService.getAvailableUserStoreClasses();
if (CollectionUtils.isNotEmpty(classNames) &&
classNames.contains(getUserStoreType(base64URLDecodeId(typeId)))) {
return buildUserStoreMetaResponse(typeId);
} else {
throw handleException(Response.Status.NOT_FOUND, UserStoreConstants.ErrorMessage.
ERROR_CODE_NOT_FOUND);
}
} catch (IdentityUserStoreMgtException e) {
UserStoreConstants.ErrorMessage errorEnum =
UserStoreConstants.ErrorMessage.ERROR_CODE_ERROR_RETRIEVING_USER_STORE;
throw handleIdentityUserStoreMgtException(e, errorEnum);
}
}
/**
* Check the connection heath for JDBC userstores.
*
* @param rdBMSConnectionReq {@link RDBMSConnectionReq}.
* @return ConnectionEstablishedResponse.
*/
public ConnectionEstablishedResponse testRDBMSConnection(RDBMSConnectionReq rdBMSConnectionReq) {
UserStoreConfigService userStoreConfigService = UserStoreConfigServiceHolder.getInstance()
.getUserStoreConfigService();
ConnectionEstablishedResponse connectionEstablishedResponse = new ConnectionEstablishedResponse();
boolean isConnectionEstablished;
connectionEstablishedResponse.setConnection(false);
try {
isConnectionEstablished = userStoreConfigService.testRDBMSConnection(rdBMSConnectionReq.getDomain(),
rdBMSConnectionReq.getDriverName(), rdBMSConnectionReq.getConnectionURL(),
rdBMSConnectionReq.getUsername(), rdBMSConnectionReq.getConnectionPassword(), DUMMY_MESSAGE_ID);
if (isConnectionEstablished) {
connectionEstablishedResponse.setConnection(true);
}
} catch (IdentityUserStoreMgtException e) {
connectionEstablishedResponse.setConnection(false);
}
return connectionEstablishedResponse;
}
/**
* To make a partial update or update the specific property of the user store config.
*
* @param domainId user store domain id
* @param patchDocument patch request
* @return UserStoreResponse
*/
public UserStoreResponse patchUserStore(String domainId, List<PatchDocument> patchDocument) {
List<PatchDocument> supportedPatchOperations = new ArrayList<>();
for (PatchDocument patch : patchDocument) {
//Only the Replace operation supported with PATCH request
PatchDocument.OperationEnum operation = patch.getOperation();
if (operation == PatchDocument.OperationEnum.REPLACE) {
supportedPatchOperations.add(patch);
}
}
if (CollectionUtils.isNotEmpty(supportedPatchOperations)) {
UserStoreDTO userStoreDTO = buildUserStoreForPatch(domainId, supportedPatchOperations);
return performPatchReplace(userStoreDTO);
}
return null;
}
/**
* To make a partial update single or multiple claim attribute mappings of a specific user store.
*
* @param userstoreDomainId user store domain id.
* @param claimAttributeMapping list of claim attribute mappings in patch request.
*/
public void updateClaimAttributeMappings(String userstoreDomainId,
List<ClaimAttributeMapping> claimAttributeMapping) {
if (claimAttributeMapping == null) {
throw handleException(Response.Status.BAD_REQUEST,
UserStoreConstants.ErrorMessage.ERROR_CODE_EMPTY_ATTRIBUTE_MAPPINGS);
}
try {
String userstoreDomain = base64URLDecodeId(userstoreDomainId);
String tenantDomain = ContextLoader.getTenantDomainFromContext();
validateUserstore(userstoreDomainId);
List<LocalClaim> localClaimList = createLocalClaimList(userstoreDomain, claimAttributeMapping);
validateClaimMappings(tenantDomain, localClaimList);
updateClaimMappings(userstoreDomain, tenantDomain, localClaimList);
} catch (UserStoreException e) {
throw handleException(Response.Status.BAD_REQUEST,
UserStoreConstants.ErrorMessage.ERROR_CODE_EMPTY_DOMAIN_ID);
} catch (IdentityUserStoreClientException e) {
throw handleIdentityUserStoreMgtException(e, UserStoreConstants.ErrorMessage.ERROR_CODE_NOT_FOUND);
}
}
/**
* To check whether user store is exist.
*
* @param userStoreDomain user store domain name.
* @return boolean
*/
private boolean isUserStoreExists(String userStoreDomain) throws UserStoreException {
UserStoreManager userStoreManager;
if (IdentityUtil.getPrimaryDomainName().equals(userStoreDomain)) {
return true;
} else {
userStoreManager = ((UserStoreManager) CarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getUserStoreManager()).getSecondaryUserStoreManager(userStoreDomain);
}
return userStoreManager != null;
}
/**
* To handle the patch REPLACE request.
*
* @param userStoreDTO user store dto.
* @return UserStoreResponse
*/
private UserStoreResponse performPatchReplace(UserStoreDTO userStoreDTO) {
UserStoreConfigService userStoreConfigService = UserStoreConfigServiceHolder.getInstance()
.getUserStoreConfigService();
try {
userStoreConfigService.updateUserStore(userStoreDTO, false);
return buildResponseForPatchReplace(userStoreDTO, userStoreDTO.getProperties());
} catch (IdentityUserStoreMgtException e) {
UserStoreConstants.ErrorMessage errorEnum =
UserStoreConstants.ErrorMessage.ERROR_CODE_ERROR_UPDATING_USER_STORE;
throw handleIdentityUserStoreMgtException(e, errorEnum);
}
}
/**
* To list the claim attribute mappings for specific user store domain.
*
* @param tenantDomain the tenant domain.
* @param userstoreDomainName the user store domain name.
* @return List<ClaimAttributeMapping>.
*/
private List<ClaimAttributeMapping> getClaimAttributeMappings(String tenantDomain, String userstoreDomainName) {
ClaimMetadataManagementService claimMetadataManagementService = UserStoreConfigServiceHolder.getInstance()
.getClaimMetadataManagementService();
List<ClaimAttributeMapping> claimAttributeMappingList = new ArrayList<>();
try {
List<LocalClaim> localClaimList = claimMetadataManagementService.getLocalClaims(tenantDomain);
for (LocalClaim localClaim : localClaimList) {
if (localClaim.getMappedAttribute(userstoreDomainName) != null) {
ClaimAttributeMapping mapping = new ClaimAttributeMapping();
mapping.setClaimURI(localClaim.getClaimURI());
mapping.setMappedAttribute(localClaim.getMappedAttribute(userstoreDomainName));
claimAttributeMappingList.add(mapping);
}
}
return claimAttributeMappingList;
} catch (ClaimMetadataException e) {
throw handleClaimManagementException(e,
UserStoreConstants.ErrorMessage.ERROR_CODE_ERROR_RETRIEVING_CLAIM_MAPPING);
}
}
private UserStoreDTO buildUserStoreForPatch(String domainId, List<PatchDocument> patchDocuments) {
UserStoreConfigService userStoreConfigService = UserStoreConfigServiceHolder.getInstance()
.getUserStoreConfigService();
UserStoreDTO userStoreDTO;
try {
userStoreDTO = userStoreConfigService.getUserStore(base64URLDecodeId(domainId));
if (userStoreDTO == null) {
throw handleException(Response.Status.NOT_FOUND, UserStoreConstants.ErrorMessage.ERROR_CODE_NOT_FOUND);
}
PropertyDTO[] propertyDTOS = userStoreDTO.getProperties();
for (PatchDocument patchDocument : patchDocuments) {
String path = patchDocument.getPath();
String value = patchDocument.getValue();
if (StringUtils.isBlank(path)) {
throw handleException(Response.Status.BAD_REQUEST, UserStoreConstants.ErrorMessage
.ERROR_CODE_INVALID_INPUT);
}
if (path.startsWith(UserStoreConstants.USER_STORE_PROPERTIES)) {
String propName = extractPropertyName(path);
if (StringUtils.isNotEmpty(propName)) {
for (PropertyDTO propertyDTO : propertyDTOS) {
if (propName.equals(propertyDTO.getName())) {
propertyDTO.setValue(value);
}
}
}
} else if (path.equals(UserStoreConstants.USER_STORE_DESCRIPTION)) {
userStoreDTO.setDescription(value);
} else {
throw handleException(Response.Status.BAD_REQUEST, UserStoreConstants.ErrorMessage
.ERROR_CODE_INVALID_INPUT);
}
}
userStoreDTO.setProperties(propertyDTOS);
} catch (IdentityUserStoreMgtException e) {
UserStoreConstants.ErrorMessage errorEnum =
UserStoreConstants.ErrorMessage.ERROR_CODE_ERROR_UPDATING_USER_STORE;
throw handleIdentityUserStoreMgtException(e, errorEnum);
}
return userStoreDTO;
}
/**
* Construct the response for patch replace.
*
* @param userStoreDTO {@link UserStoreDTO}.
* @param propertyDTOS array of {@link PropertyDTO}.
* @return UserStoreResponse.
*/
private UserStoreResponse buildResponseForPatchReplace(UserStoreDTO userStoreDTO, PropertyDTO[] propertyDTOS) {
UserStoreResponse userStoreResponseDTO = new UserStoreResponse();
userStoreResponseDTO.setId((base64URLEncodeId(userStoreDTO.getDomainId())));
userStoreResponseDTO.setName(userStoreDTO.getDomainId());
userStoreResponseDTO.setTypeId(base64URLEncodeId(Objects.requireNonNull(getUserStoreTypeName
(userStoreDTO.getClassName()))));
userStoreResponseDTO.setTypeName(getUserStoreTypeName(userStoreDTO.getClassName()));
userStoreResponseDTO.setDescription(userStoreDTO.getDescription());
userStoreResponseDTO.setProperties(patchUserStoreProperties(propertyDTOS));
return userStoreResponseDTO;
}
/**
* Build user store properties response of created or updated user store.
*
* @param userStoreReq {@link UserStoreReq} to insert.
* @return List<AddUserStorePropertiesRes>.
*/
private List<AddUserStorePropertiesRes> buildUserStorePropertiesRes(UserStoreReq userStoreReq) {
List<org.wso2.carbon.identity.api.server.userstore.v1.model.Property> values = userStoreReq.getProperties();
List<AddUserStorePropertiesRes> propertiesToAdd = new ArrayList<>();
for (org.wso2.carbon.identity.api.server.userstore.v1.model.Property value : values) {
AddUserStorePropertiesRes addUserStorePropertiesRes = new AddUserStorePropertiesRes();
addUserStorePropertiesRes.setName(value.getName());
addUserStorePropertiesRes.setValue(value.getValue());
propertiesToAdd.add(addUserStorePropertiesRes);
}
return propertiesToAdd;
}
/**
* To update claim attribute mappings in bulk for specific user store.
*
* @param userstoreDomain user store domain name.
* @param tenantDomain tenant domain name.
* @param localClaimList list of claim attribute mappings.
*/
private void updateClaimMappings(String userstoreDomain, String tenantDomain, List<LocalClaim> localClaimList) {
ClaimMetadataManagementService claimMetadataManagementService = UserStoreConfigServiceHolder.getInstance()
.getClaimMetadataManagementService();
try {
claimMetadataManagementService.validateClaimAttributeMapping(localClaimList, tenantDomain);
claimMetadataManagementService.updateLocalClaimMappings(localClaimList, tenantDomain, userstoreDomain);
} catch (ClaimMetadataException e) {
throw handleClaimManagementException(e,
UserStoreConstants.ErrorMessage.ERROR_CODE_ERROR_UPDATING_CLAIM_MAPPING);
}
}
/**
* To validate claim existence of claim attribute mappings.
*
* @param tenantDomain tenant domain name.
* @param localClaimList list of claim attribute mappings.
*/
private void validateClaimMappings(String tenantDomain, List<LocalClaim> localClaimList) {
ClaimMetadataManagementService claimMetadataManagementService = UserStoreConfigServiceHolder.getInstance()
.getClaimMetadataManagementService();
try {
claimMetadataManagementService.validateClaimAttributeMapping(localClaimList, tenantDomain);
} catch (ClaimMetadataException e) {
throw handleClaimManagementException(e,
UserStoreConstants.ErrorMessage.ERROR_CODE_ERROR_UPDATING_CLAIM_MAPPING);
}
}
/**
* To construct properties list for patch request.
*
* @param propertyDTOS array of {@link PropertyDTO}
* @return List<AddUserStorePropertiesRes>
*/
private List<AddUserStorePropertiesRes> patchUserStoreProperties(PropertyDTO[] propertyDTOS) {
List<AddUserStorePropertiesRes> propertiesToAdd = new ArrayList<>();
for (PropertyDTO propertyDTO : propertyDTOS) {
AddUserStorePropertiesRes patchUserStoreProperties = new AddUserStorePropertiesRes();
patchUserStoreProperties.setName(propertyDTO.getName());
patchUserStoreProperties.setValue(propertyDTO.getValue());
propertiesToAdd.add(patchUserStoreProperties);
}
return propertiesToAdd;
}
/**
* To create UserStoreDTO object for this request.
*
* @param userStoreReq {@link UserStoreReq}.
* @return UserStoreDTO.
*/
private UserStoreDTO createUserStoreDTO(UserStoreReq userStoreReq) {
UserStoreDTO userStoreDTO = new UserStoreDTO();
userStoreDTO.setDomainId(userStoreReq.getName());
userStoreDTO.setClassName(getUserStoreType(base64URLDecodeId(userStoreReq.getTypeId())));
userStoreDTO.setDescription(userStoreReq.getDescription());
userStoreDTO.setProperties(createPropertyListDTO(userStoreReq));
return userStoreDTO;
}
/**
* To create Local claim list from a claim attribute mapping list.
*
* @param userStoreId user store domain Id.
* @param claimAttributeMappingList list of claim attribute mappings.
* @return List<LocalClaim>.
*/
private List<LocalClaim> createLocalClaimList(String userStoreId,
List<ClaimAttributeMapping> claimAttributeMappingList) {
List<LocalClaim> localClaimList = new ArrayList<>();
for (ClaimAttributeMapping claimAttributeMapping : claimAttributeMappingList) {
AttributeMapping attributeMapping = new AttributeMapping(userStoreId,
claimAttributeMapping.getMappedAttribute());
LocalClaim localClaim = new LocalClaim(claimAttributeMapping.getClaimURI());
localClaim.setMappedAttribute(attributeMapping);
localClaimList.add(localClaim);
}
return localClaimList;
}
/**
* Construct response list with configured user stores details.
*
* @param userStoreDTOS array of UserStoreDTO object.
* @return List<UserStoreListResponse>.
*/
private List<UserStoreListResponse> buildUserStoreListResponse(UserStoreDTO[] userStoreDTOS,
String requiredAttributes) {
List<UserStoreListResponse> userStoreListResponseToAdd = new ArrayList<>();
Map<String, Boolean> userStoreManagersType = UserStoreManagerRegistry.getUserStoreManagersType();
if (ArrayUtils.isNotEmpty(userStoreDTOS)) {
for (UserStoreDTO jsonObject : userStoreDTOS) {
UserStoreListResponse userStoreList = new UserStoreListResponse();
userStoreList.setDescription(jsonObject.getDescription());
userStoreList.setName(jsonObject.getDomainId());
userStoreList.setId(base64URLEncodeId(jsonObject.getDomainId()));
userStoreList.setSelf(ContextLoader.buildURIForBody(String.format(V1_API_PATH_COMPONENT +
UserStoreConstants.USER_STORE_PATH_COMPONENT + "/%s",
base64URLEncodeId(jsonObject.getDomainId()))).toString());
userStoreList.setEnabled(jsonObject.getDisabled() != null && !jsonObject.getDisabled());
if (StringUtils.isNotBlank(requiredAttributes)) {
String[] requiredAttributesArray = requiredAttributes.split(REGEX_COMMA);
addUserstoreProperties(jsonObject, userStoreList, Arrays.asList(requiredAttributesArray));
}
if (userStoreManagersType.containsKey(jsonObject.getClassName())) {
userStoreList.setIsLocal(userStoreManagersType.get(jsonObject.getClassName()));
}
userStoreListResponseToAdd.add(userStoreList);
}
}
return userStoreListResponseToAdd;
}
/**
* Add requested user store properties to the response.
*
* @param userStoreDTO userStoreDTO object.
* @param userStoreListResponse userStoreListResponse object.
* @param requestedAttributesList Requested user store properties name list.
*/
private void addUserstoreProperties(UserStoreDTO userStoreDTO, UserStoreListResponse userStoreListResponse,
List<String> requestedAttributesList) {
for (PropertyDTO propertyDTO : userStoreDTO.getProperties()) {
if (requestedAttributesList.contains(propertyDTO.getName()) &&
StringUtils.isNotBlank(propertyDTO.getValue())) {
AddUserStorePropertiesRes addUserStorePropertiesRes = new AddUserStorePropertiesRes();
addUserStorePropertiesRes.setName(propertyDTO.getName());
addUserStorePropertiesRes.setValue(propertyDTO.getValue());
userStoreListResponse.addPropertiesItem(addUserStorePropertiesRes);
}
}
}
/**
* Construct the user store type's meta.
*
* @param typeId the type id of the user store.
* @return MetaUserStoreType.
*/
private MetaUserStoreType buildUserStoreMetaResponse(String typeId) {
String typeName = base64URLDecodeId(typeId);
Properties properties = UserStoreManagerRegistry.getUserStoreProperties(
getUserStoreType(typeName));
MetaUserStoreType metaUserStore = new MetaUserStoreType();
UserStorePropertiesRes userStorePropertiesRes = new UserStorePropertiesRes();
if ((properties != null)) {
userStorePropertiesRes.mandatory(buildPropertiesRes(properties.getMandatoryProperties()));
userStorePropertiesRes.optional(buildPropertiesRes(properties.getOptionalProperties()));
userStorePropertiesRes.advanced(buildPropertiesRes(properties.getAdvancedProperties()));
}
metaUserStore.setProperties(userStorePropertiesRes);
metaUserStore.setTypeId(typeId);
metaUserStore.setTypeName(typeName);
metaUserStore.setClassName(getUserStoreType(typeName));
try {
metaUserStore.setIsLocal(UserStoreManagerRegistry.isLocalUserStore(getUserStoreType(typeName)));
} catch (UserStoreException e) {
LOG.error(String.format("Cannot found user store manager type for user store manager: %s",
getUserStoreType(typeName)), e);
}
return metaUserStore;
}
/**
* Construct properties list in the response.
*
* @param properties array of user store properties.
* @return List<PropertiesRes>.
*/
private List<PropertiesRes> buildPropertiesRes(Property[] properties) {
List<PropertiesRes> propertiesToAdd = new ArrayList<>();
for (Property property : properties) {
PropertiesRes propertiesRes = new PropertiesRes();
propertiesRes.setName(property.getName());
propertiesRes.setDefaultValue(property.getValue());
propertiesRes.setDescription(property.getDescription());
propertiesRes.setAttributes(buildAttributes(property.getChildProperties()));
propertiesToAdd.add(propertiesRes);
}
return propertiesToAdd;
}
/**
* Constructs attributes for individual properties.
*
* @param properties Array of user store properties.
* @return List<Attribute>
*/
private List<Attribute> buildAttributes(Property[] properties) {
if (ArrayUtils.isEmpty(properties)) {
return null;
}
List<Attribute> attributes = new ArrayList<>();
for (Property property : properties) {
Attribute attribute = new Attribute();
attribute.setName(property.getName());
attribute.setValue(property.getValue());
attributes.add(attribute);
}
return attributes;
}
/**
* Retrieve the className for a given type.
*
* @param typeName user store type name.
* @return user store class name.
*/
private String getUserStoreType(String typeName) {
HashMap<String, String> userStoreMap = getHashMap();
for (Map.Entry<String, String> stringEntry : userStoreMap.entrySet()) {
if (typeName.equals(((Map.Entry) stringEntry).getValue())) {
return (String) ((Map.Entry) stringEntry).getKey();
}
}
return null;
}
/**
* Retrieve the user store type name for a given class name.
*
* @param className user store class name.
* @return user store type name.
*/
private String getUserStoreTypeName(String className) {
HashMap<String, String> userStoreMap = getHashMap();
for (Map.Entry<String, String> stringEntry : userStoreMap.entrySet()) {
if (className.equals(((Map.Entry) stringEntry).getKey())) {
return (String) ((Map.Entry) stringEntry).getValue();
}
}
return null;
}
/**
* Construct a map with class name and with the corresponding type name.
*
* @return HashMap.
*/
private HashMap<String, String> getHashMap() {
Set<String> classNames = UserStoreManagerRegistry.getUserStoreManagerClasses();
HashMap<String, String> userStoreMap = new HashMap<>();
for (String className : classNames) {
userStoreMap.put(className, className.substring(className.lastIndexOf('.') + 1));
}
return userStoreMap;
}
/**
* To construct the base 64 url encoded id.
*
* @param id domain name.
* @return encoded string value.
*/
private String base64URLEncodeId(String id) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(id.getBytes(StandardCharsets.UTF_8));
}
/**
* To construct the base 64 url decoded value.
*
* @param id domain name.
* @return decoded string value.
*/
private String base64URLDecodeId(String id) {
return new String(Base64.getUrlDecoder().decode(id), StandardCharsets.UTF_8);
}
/**
* Construct PropertyDTO array for POST request.
*
* @param userStoreReq {@link UserStoreReq}.
* @return PropertyDTO[].
*/
private PropertyDTO[] createPropertyListDTO(UserStoreReq userStoreReq) {
List<org.wso2.carbon.identity.api.server.userstore.v1.model.Property> values = userStoreReq.getProperties();
ArrayList<PropertyDTO> propertiesToAdd = new ArrayList<>();
for (org.wso2.carbon.identity.api.server.userstore.v1.model.Property value : values) {
PropertyDTO propertyDTO = new PropertyDTO();
propertyDTO.setName(value.getName());
propertyDTO.setValue(value.getValue());
propertiesToAdd.add(propertyDTO);
}
return generatePropertiesWithUniqueIDProperty (propertiesToAdd);
}
/**
* Construct PropertyDTO array with UniqueID.
*
* @param propertiesToAdd Array list of properties.
* @return PropertyDTO[].
*/
private PropertyDTO[] generatePropertiesWithUniqueIDProperty(ArrayList<PropertyDTO> propertiesToAdd) {
PropertyDTO propertyDTO = new PropertyDTO();
propertyDTO.setName("UniqueID");
propertyDTO.setValue(UUID.randomUUID().toString());
propertiesToAdd.add(propertyDTO);
return propertiesToAdd.toArray(new PropertyDTO[0]);
}
/**
* To create UserStoreResponse object for the put request.
*
* @param userStoreReq {@link UserStoreReq}.
* @return UserStoreResponse.
*/
private UserStoreResponse buildUserStoreResponseDTO(UserStoreReq userStoreReq) {
UserStoreResponse userStoreResponseDTO = new UserStoreResponse();
userStoreResponseDTO.setId((base64URLEncodeId(userStoreReq.getName())));
userStoreResponseDTO.setName(userStoreReq.getName());
userStoreResponseDTO.setTypeId(userStoreReq.getTypeId());
userStoreResponseDTO.setTypeName(base64URLDecodeId(userStoreReq.getTypeId()));
userStoreResponseDTO.setDescription(userStoreReq.getDescription());
userStoreResponseDTO.setProperties(buildUserStorePropertiesRes(userStoreReq));
return userStoreResponseDTO;
}
/**
* Handle exceptions generated in API.
*
* @param status HTTP Status.
* @param error Error Message information.
* @return APIError.
*/
private APIError handleException(Response.Status status, UserStoreConstants.ErrorMessage error) {
return new APIError(status, getErrorBuilder(error).build());
}
/**
* Handle exceptions generated in API.
*
* @param status HTTP Status.
* @param error Error Message information.
* @param data Additional data.
* @return APIError.
*/
private APIError handleException(Response.Status status, UserStoreConstants.ErrorMessage error, String... data) {
return new APIError(status, getErrorBuilder(error, data).build());
}
/**
* Return error builder.
*
* @param errorMsg Error Message information.
* @param data Error data.
* @return ErrorResponse.Builder.
*/
private ErrorResponse.Builder getErrorBuilder(UserStoreConstants.ErrorMessage errorMsg, String... data) {
return new ErrorResponse.Builder().withCode(errorMsg.getCode()).withMessage(errorMsg.getMessage())
.withDescription(buildErrorDescription(errorMsg, data));
}
/**
* To build error description.
*
* @param errorEnum Error Message information.
* @param data Error data.
* @return ErrorDescription.
*/
private String buildErrorDescription(UserStoreConstants.ErrorMessage errorEnum, String... data) {
String errorDescription;
if (ArrayUtils.isNotEmpty(data)) {
if (data.length == 1) {
errorDescription = String.format(errorEnum.getDescription(), (Object) data);
} else {
errorDescription = String.format(errorEnum.getDescription(), (Object[]) data);
}
} else {
errorDescription = errorEnum.getDescription();
}
return errorDescription;
}
/**
* To return error responses for the input params for the get request which are not yet supported by the server.
*
* @param limit items per page.
* @param offset to specify the offset param.
* @param filter to specify the filtering capabilities.
* @param sort to specify the sorting order.
*/
private void handleNotImplementedBehaviour(Integer limit, Integer offset, String filter, String sort) {
UserStoreConstants.ErrorMessage errorEnum = null;
if (limit != null) {
errorEnum = UserStoreConstants.ErrorMessage.ERROR_CODE_PAGINATION_NOT_IMPLEMENTED;
} else if (offset != null) {
errorEnum = UserStoreConstants.ErrorMessage.ERROR_CODE_PAGINATION_NOT_IMPLEMENTED;
} else if (filter != null) {
errorEnum = UserStoreConstants.ErrorMessage.ERROR_CODE_FILTERING_NOT_IMPLEMENTED;
} else if (sort != null) {
errorEnum = UserStoreConstants.ErrorMessage.ERROR_CODE_SORTING_NOT_IMPLEMENTED;
}
if (errorEnum != null) {
ErrorResponse errorResponse = getErrorBuilder(errorEnum).build(LOG, errorEnum.getDescription());
Response.Status status = Response.Status.NOT_IMPLEMENTED;
throw new APIError(status, errorResponse);
}
}
/**
* To check whether API request has all user store mandatory properties or not.
*
* @param userStoreReq {@link UserStoreReq}
*/
private void validateMandatoryProperties(UserStoreReq userStoreReq) {
String userStoreType = getUserStoreType(base64URLDecodeId(userStoreReq.getTypeId()));
if (StringUtils.isBlank(userStoreType)) {
throw handleException(Response.Status.BAD_REQUEST,
UserStoreConstants.ErrorMessage.ERROR_CODE_INVALID_INPUT);
}
HashMap<String, String> hashMap = new HashMap<String, String>();
Property[] mandatoryProperties = UserStoreManagerRegistry.
getUserStoreProperties(userStoreType).getMandatoryProperties();
for (org.wso2.carbon.identity.api.server.userstore.v1.model.Property property : userStoreReq.getProperties()) {
hashMap.put(property.getName(), property.getValue());
}
for (Property property : mandatoryProperties) {
if (!hashMap.containsKey(property.getName()) || (StringUtils.isEmpty(hashMap.get(property.getName())))) {
UserStoreConstants.ErrorMessage errorEnum =
UserStoreConstants.ErrorMessage.ERROR_CODE_MANDATORY_PROPERTIES_NOT_FOUND;
Response.Status status = Response.Status.NOT_FOUND;
throw handleException(status, errorEnum);
}
}
}
/**
* Handle handleIdentityUserStoreMgtException, ie, handle the appropriate client and server exception and set
* proper API Error Response.
*
* @param exception Exception thrown
* @param errorEnum Corresponding error enum
* @return API Error object.
*/
private APIError handleIdentityUserStoreMgtException(IdentityUserStoreMgtException exception,
UserStoreConstants.ErrorMessage errorEnum) {
Response.Status status;
ErrorResponse errorResponse = getErrorBuilder(errorEnum).build(LOG, exception, errorEnum.getDescription());
if (exception instanceof IdentityUserStoreServerException) {
status = Response.Status.INTERNAL_SERVER_ERROR;
return handleIdentityUserStoreException(exception, errorResponse, status);
} else if (exception instanceof IdentityUserStoreClientException) {
if (ERROR_CODE_RESOURCE_LIMIT_REACHED.equals(exception.getErrorCode())) {
return handleResourceLimitReached();
}
// Send client error with specific error code or as a BAD request.
status = Response.Status.BAD_REQUEST;
return handleIdentityUserStoreException(exception, errorResponse, status);
} else {
// Internal Server error
status = Response.Status.INTERNAL_SERVER_ERROR;
return new APIError(status, errorResponse);
}
}
private APIError handleResourceLimitReached() {
ErrorResponse errorResponse = getErrorBuilder(ERROR_CODE_USER_STORE_LIMIT_REACHED)
.build(LOG, ERROR_CODE_USER_STORE_LIMIT_REACHED.getDescription());
Response.Status status = Response.Status.FORBIDDEN;
return new APIError(status, errorResponse);
}
/**
* Handle handleIdentityUserStoreException, extract the error code and the error message from the corresponding
* exception and set it to the API Error Response.
*
* @param exception Exception thrown
* @param errorResponse Corresponding error response
* @return API Error object.
*/
private APIError handleIdentityUserStoreException(IdentityUserStoreMgtException exception,
ErrorResponse errorResponse, Response.Status status) {
if (exception.getErrorCode() != null) {
String errorCode = exception.getErrorCode();
errorCode = errorCode.contains(UserStoreConstants.SECONDARY_USER_STORE_PREFIX) ?
errorCode : UserStoreConstants.SECONDARY_USER_STORE_PREFIX + errorCode;
errorResponse.setCode(errorCode);
}
errorResponse.setDescription(exception.getMessage());
return new APIError(status, errorResponse);
}
/**
* Handle ClaimManagementException, extract the error code and the error message from the corresponding
* exception and set it to the API Error Response.
*
* @param exception Exception thrown.
* @param errorEnum Corresponding error enum.
* @return API Error object.
*/
private APIError handleClaimManagementException(ClaimMetadataException exception,
UserStoreConstants.ErrorMessage errorEnum) {
Response.Status status;
ErrorResponse errorResponse = getErrorBuilder(errorEnum).build(LOG, exception, errorEnum.getDescription());
if (exception instanceof ClaimMetadataClientException) {
status = Response.Status.BAD_REQUEST;
return handleClaimManagementClientException(exception, errorResponse, status);
} else {
// Internal Server error
status = Response.Status.INTERNAL_SERVER_ERROR;
return new APIError(status, errorResponse);
}
}
/**
* Handle ClaimManagementException, extract the error code and the error message from the corresponding
* exception and set it to the API Error Response.
*
* @param exception Exception thrown.
* @param errorResponse Corresponding error response.
* @param status Corresponding status response.
* @return API Error object.
*/
private APIError handleClaimManagementClientException(ClaimMetadataException exception,
ErrorResponse errorResponse, Response.Status status) {
if (exception.getErrorCode() != null) {
String errorCode = exception.getErrorCode();
errorCode = errorCode.contains(UserStoreConstants.CLAIM_MANAGEMENT_PREFIX) ?
errorCode : UserStoreConstants.CLAIM_MANAGEMENT_PREFIX + errorCode;
errorResponse.setCode(errorCode);
}
errorResponse.setDescription(exception.getMessage());
return new APIError(status, errorResponse);
}
/**
* Validate userstore update request.
*
* @param domainID Userstore domain ID
* @param userStoreReq UserStoreReq object.
* @throws IdentityUserStoreClientException If request is invalid.
*/
private void validateUserstoreUpdateRequest(String domainID, UserStoreReq userStoreReq)
throws IdentityUserStoreClientException {
if (StringUtils.isBlank(domainID)) {
throw new IdentityUserStoreClientException(
UserStoreConstants.ErrorMessage.ERROR_CODE_EMPTY_DOMAIN_ID.getCode(),
UserStoreConstants.ErrorMessage.ERROR_CODE_EMPTY_DOMAIN_ID.getMessage());
}
if (userStoreReq == null) {
throw new IdentityUserStoreClientException(
UserStoreConstants.ErrorMessage.ERROR_CODE_REQUEST_BODY_NOT_FOUND.getCode(),
UserStoreConstants.ErrorMessage.ERROR_CODE_REQUEST_BODY_NOT_FOUND.getMessage());
}
if (StringUtils.isBlank(userStoreReq.getName())) {
throw new IdentityUserStoreClientException(
UserStoreConstants.ErrorMessage.ERROR_CODE_EMPTY_DOMAIN_NAME.getCode(),
UserStoreConstants.ErrorMessage.ERROR_CODE_EMPTY_DOMAIN_NAME.getMessage());
}
if (!userStoreReq.getName().equals(base64URLDecodeId(domainID))) {
throw new IdentityUserStoreClientException(
UserStoreConstants.ErrorMessage.ERROR_CODE_DOMAIN_ID_DOES_NOT_MATCH_WITH_NAME.getCode(),
UserStoreConstants.ErrorMessage.ERROR_CODE_DOMAIN_ID_DOES_NOT_MATCH_WITH_NAME.getMessage());
}
}
/**
* Validate userstore domain Id.
*
* @param userstoreDomainId Userstore domain ID.
* @throws IdentityUserStoreClientException If request is invalid.
*/
private void validateUserstore(String userstoreDomainId) throws UserStoreException,
IdentityUserStoreClientException {
if (StringUtils.isBlank(userstoreDomainId)) {
throw new IdentityUserStoreClientException(
UserStoreConstants.ErrorMessage.ERROR_CODE_EMPTY_DOMAIN_ID.getCode(),
UserStoreConstants.ErrorMessage.ERROR_CODE_EMPTY_DOMAIN_ID.getMessage());
}
if (!isUserStoreExists(base64URLDecodeId(userstoreDomainId))) {
throw handleException(Response.Status.NOT_FOUND, UserStoreConstants.ErrorMessage.ERROR_CODE_NOT_FOUND);
}
}
private String extractPropertyName(String pathProp) {
String name = null;
String[] splittedPath = pathProp.split("/");
if (splittedPath.length > 2) {
name = splittedPath[2];
}
return name;
}
/**
* Get user store attributes mappings for a given user store type id.
*
* @param typeId String user store type id.
* @return UserStoreAttributeMapping user store attribute mappings.
*/
public UserStoreAttributeMapping getUserStoreMappingAttributes(String typeId) {
Set<String> classNames;
String userStoreName = getUserStoreType(base64URLDecodeId(typeId));
if (StringUtils.isBlank(userStoreName)) {
throw handleException(Response.Status.BAD_REQUEST, UserStoreConstants.ErrorMessage.
ERROR_CODE_INVALID_INPUT);
}
try {
UserStoreConfigService userStoreConfigService = UserStoreConfigServiceHolder.getInstance()
.getUserStoreConfigService();
classNames = userStoreConfigService.getAvailableUserStoreClasses();
if (CollectionUtils.isEmpty(classNames) || !classNames.contains(userStoreName)) {
throw handleException(Response.Status.NOT_FOUND, UserStoreConstants.ErrorMessage.
ERROR_CODE_NOT_FOUND);
}
} catch (IdentityUserStoreMgtException e) {
UserStoreConstants.ErrorMessage errorEnum =
UserStoreConstants.ErrorMessage.ERROR_CODE_ERROR_RETRIEVING_USER_STORE;
throw handleIdentityUserStoreMgtException(e, errorEnum);
}
UserStoreAttributeMapping userStoreAttributeMapping = new UserStoreAttributeMapping();
List<UserStoreAttributeDO> attributeMappings = getAttributeMappings(userStoreName);
userStoreAttributeMapping = userStoreAttributeMapping
.attributeMapping(attributeMappings)
.typeId(typeId)
.typeName(userStoreName);
try {
boolean isLocal = UserStoreManagerRegistry.isLocalUserStore(userStoreName);
userStoreAttributeMapping.setIsLocal(isLocal);
} catch (UserStoreException e) {
LOG.error(String.format("Userstore type is not found for %s", userStoreName), e);
}
return userStoreAttributeMapping;
}
/**
* Get user store attribute mappings for a given user store typeId.
*
* @param userStoreName String user store name (base64 decoded user store id).
* @return List of user store attribute mappings for the given typeId.
*/
private List<UserStoreAttributeDO> getAttributeMappings(String userStoreName) {
UserStoreConfigService userStoreConfigService = UserStoreConfigServiceHolder.getInstance().
getUserStoreConfigService();
try {
UserStoreAttributeMappings userStoreAttributeMappings = userStoreConfigService.
getUserStoreAttributeMappings();
Map<String, UserStoreAttributeDO> mapping = userStoreAttributeMappings
.getUserStoreAttributeMappings(userStoreName);
return new ArrayList<>(mapping.values());
} catch (IdentityUserStoreMgtException e) {
LOG.error("Error occurred while retrieving user store attribute metadata", e);
throw handleException(Response.Status.INTERNAL_SERVER_ERROR, UserStoreConstants.ErrorMessage.
ERROR_CODE_ERROR_RETRIEVING_USER_STORE_ATTRIBUTE_METADATA);
}
}
}
|
/*
* Copyright 2017, BAE Systems Limited and GE Aviation Limited.
*
* This software and its outputs are not claimed to be fit or safe for any purpose. Any user should
* satisfy themselves that this software or its outputs are appropriate for its intended purpose.
*/
package com.iawg.ecoa.gui;
import java.awt.Color;
import java.awt.GridLayout;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import com.iawg.ecoa.ECOA_Monitor;
@SuppressWarnings("unused")
public class PDPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = -5925764457795982095L;
private ECOA_Monitor ecoaMonitor;
public PDPanel(ECOA_Monitor ecoaMonitor) {
this.ecoaMonitor = ecoaMonitor;
this.setLayout(new GridLayout(20, 1, 10, 10));
this.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black, 1), "Protection Domains"));
}
public void displayPDs(ArrayList<PDLabel> pdLabelList) {
// Clear the protection domain panel.
if (this.getComponentCount() != 0) {
this.removeAll();
}
for (PDLabel label : pdLabelList) {
this.add(label);
}
// Redraw the panel container.
this.updateUI();
}
}
|
package seedu.address.model.util;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import seedu.address.model.AddressBook;
import seedu.address.model.ReadOnlyAddressBook;
import seedu.address.model.name.Name;
import seedu.address.model.person.Address;
import seedu.address.model.person.Email;
import seedu.address.model.person.Person;
import seedu.address.model.person.Phone;
import seedu.address.model.tag.Tag;
/**
* Contains utility methods for populating {@code AddressBook} with sample data.
*/
public class SampleDataUtil {
public static Person[] getSamplePersons() {
return new Person[] {
new Person(new Name("Alex Yeoh"), new Phone("87438807"), new Email("alexyeoh@example.com"),
new Address("Blk 30 Geylang Street 29, #06-40"),
getTagSet("friends")),
new Person(new Name("Bernice Yu"), new Phone("99272758"), new Email("berniceyu@example.com"),
new Address("Blk 30 Lorong 3 Serangoon Gardens, #07-18"),
getTagSet("colleagues", "friends")),
new Person(new Name("Charlotte Oliveiro"), new Phone("93210283"), new Email("charlotte@example.com"),
new Address("Blk 11 Ang Mo Kio Street 74, #11-04"),
getTagSet("neighbours")),
new Person(new Name("David Li"), new Phone("91031282"), new Email("lidavid@example.com"),
new Address("Blk 436 Serangoon Gardens Street 26, #16-43"),
getTagSet("family")),
new Person(new Name("Irfan Ibrahim"), new Phone("92492021"), new Email("irfan@example.com"),
new Address("Blk 47 Tampines Street 20, #17-35"),
getTagSet("classmates")),
new Person(new Name("Roy Balakrishnan"), new Phone("92624417"), new Email("royb@example.com"),
new Address("Blk 45 Aljunied Street 85, #11-31"),
getTagSet("colleagues"))
};
}
public static ReadOnlyAddressBook getSampleAddressBook() {
AddressBook sampleAb = new AddressBook();
for (Person samplePerson : getSamplePersons()) {
sampleAb.addPerson(samplePerson);
}
return sampleAb;
}
/**
* Returns a tag set containing the list of strings given.
*/
public static Set<Tag> getTagSet(String... strings) {
return Arrays.stream(strings)
.map(Tag::new)
.collect(Collectors.toSet());
}
}
|
package de.srendi.advancedperipherals.common.util;
import de.srendi.advancedperipherals.AdvancedPeripherals;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import java.util.ArrayDeque;
import java.util.Queue;
@Mod.EventBusSubscriber(modid = AdvancedPeripherals.MOD_ID)
public class ServerWorker {
private static final Queue<Runnable> callQueue = new ArrayDeque<>();
public static void add(final Runnable call) {
callQueue.add(call);
}
@SubscribeEvent
public static void serverTick(TickEvent.ServerTickEvent e) {
if (e.phase == TickEvent.Phase.END) {
while (!callQueue.isEmpty()) {
final Runnable runnable = callQueue.poll();
runnable.run();
}
}
}
}
|
package org.apache.spark.deploy;
/**
* Testing class that creates a Spark standalone process in-cluster (that is, running the
* spark.deploy.master.Master and spark.deploy.worker.Workers in the same JVMs). Executors launched
* by the Workers still run in separate JVMs. This can be used to test distributed operation and
* fault recovery without spinning up a lot of processes.
*/
class LocalSparkCluster implements org.apache.spark.internal.Logging {
public LocalSparkCluster (int numWorkers, int coresPerWorker, int memoryPerWorker, org.apache.spark.SparkConf conf) { throw new RuntimeException(); }
private java.lang.String localHostname () { throw new RuntimeException(); }
private scala.collection.mutable.ArrayBuffer<org.apache.spark.rpc.RpcEnv> masterRpcEnvs () { throw new RuntimeException(); }
public int masterWebUIPort () { throw new RuntimeException(); }
public java.lang.String[] start () { throw new RuntimeException(); }
public void stop () { throw new RuntimeException(); }
private scala.collection.mutable.ArrayBuffer<org.apache.spark.rpc.RpcEnv> workerRpcEnvs () { throw new RuntimeException(); }
}
|
package customView;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.Surface;
import android.view.TextureView;
import java.io.IOException;
import Tools.Logger;
public class VideoView extends TextureView implements android.view.TextureView.SurfaceTextureListener {
private MediaPlayer.OnCompletionListener mOnCompletionListener;
private MediaPlayer.OnPreparedListener mOnPreparedListener;
private MediaPlayer.OnErrorListener mOnErrorListener;
private MediaPlayer.OnSeekCompleteListener mOnSeekCompleteListener;
private OnPlayStateListener mOnPlayStateListener;
private MediaPlayer mMediaPlayer = null;
private SurfaceTexture mSurfaceHolder = null;
private static final int STATE_ERROR = -1;
private static final int STATE_IDLE = 0;
private static final int STATE_PREPARING = 1;
private static final int STATE_PREPARED = 2;
private static final int STATE_PLAYING = 3;
private static final int STATE_PAUSED = 4;
/**
* PlaybackCompleted状态:文件正常播放完毕,而又没有设置循环播放的话就进入该状态,
* 并会触发OnCompletionListener的onCompletion
* ()方法。此时可以调用start()方法重新从头播放文件,也可以stop()停止MediaPlayer,或者也可以seekTo()来重新定位播放位置。
*/
private static final int STATE_PLAYBACK_COMPLETED = 5;
/** Released/End状态:通过release()方法可以进入End状态 */
private static final int STATE_RELEASED = 5;
private int mCurrentState = STATE_IDLE;
private int mTargetState = STATE_IDLE;
private int mVideoWidth;
private int mVideoHeight;
// private int mSurfaceWidth;
// private int mSurfaceHeight;
private float mVolumn = -1;
private int mDuration;
private Uri mUri;
// SurfaceTextureAvailable
public VideoView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initVideoView();
}
public VideoView(Context context) {
super(context);
initVideoView();
}
public VideoView(Context context, AttributeSet attrs) {
super(context, attrs);
initVideoView();
}
protected void initVideoView() {
try {
AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mVolumn = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
} catch (UnsupportedOperationException e) {
}
// mTryCount = 0;
mVideoWidth = 0;
mVideoHeight = 0;
setSurfaceTextureListener(this);
// setFocusable(true);
// setFocusableInTouchMode(true);
// requestFocus();
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
public void setOnPreparedListener(MediaPlayer.OnPreparedListener l) {
mOnPreparedListener = l;
}
public void setOnErrorListener(MediaPlayer.OnErrorListener l) {
mOnErrorListener = l;
}
public void setOnPlayStateListener(OnPlayStateListener l) {
mOnPlayStateListener = l;
}
public void setOnSeekCompleteListener(MediaPlayer.OnSeekCompleteListener l) {
mOnSeekCompleteListener = l;
}
public static interface OnPlayStateListener {
public void onStateChanged(boolean isPlaying);
}
public void setOnCompletionListener(MediaPlayer.OnCompletionListener l) {
mOnCompletionListener = l;
}
public void setVideoPath(String path) {
// if (StringUtils.isNotEmpty(path) && MediaUtils.isNative(path)) {
mTargetState = STATE_PREPARED;
openVideo(Uri.parse(path));
// }
}
public int getVideoWidth() {
return mVideoWidth;
}
public int getVideoHeight() {
return mVideoHeight;
}
public void reOpen() {
mTargetState = STATE_PREPARED;
openVideo(mUri);
}
public int getDuration() {
return mDuration;
}
/** 重试 */
private void tryAgain(Exception e) {
mCurrentState = STATE_ERROR;
Logger.e(e);
openVideo(mUri);
}
public void start() {
mTargetState = STATE_PLAYING;
//可用状态{Prepared, Started, Paused, PlaybackCompleted}
if (mMediaPlayer != null && (mCurrentState == STATE_PREPARED || mCurrentState == STATE_PAUSED || mCurrentState == STATE_PLAYING || mCurrentState == STATE_PLAYBACK_COMPLETED)) {
try {
if (!isPlaying())
mMediaPlayer.start();
mCurrentState = STATE_PLAYING;
if (mOnPlayStateListener != null)
mOnPlayStateListener.onStateChanged(true);
} catch (IllegalStateException e) {
tryAgain(e);
} catch (Exception e) {
tryAgain(e);
}
}
}
public void pause() {
mTargetState = STATE_PAUSED;
//可用状态{Started, Paused}
if (mMediaPlayer != null && (mCurrentState == STATE_PLAYING || mCurrentState == STATE_PAUSED)) {
try {
mMediaPlayer.pause();
mCurrentState = STATE_PAUSED;
if (mOnPlayStateListener != null)
mOnPlayStateListener.onStateChanged(false);
} catch (IllegalStateException e) {
tryAgain(e);
} catch (Exception e) {
tryAgain(e);
}
}
}
public void setVolume(float volume) {
//可用状态{Idle, Initialized, Stopped, Prepared, Started, Paused, PlaybackCompleted}
if (mMediaPlayer != null && (mCurrentState == STATE_PREPARED || mCurrentState == STATE_PLAYING || mCurrentState == STATE_PAUSED || mCurrentState == STATE_PLAYBACK_COMPLETED)) {
try {
mMediaPlayer.setVolume(volume, volume);
} catch (Exception e) {
Logger.e(e);
}
}
}
public void setLooping(boolean looping) {
//可用状态{Idle, Initialized, Stopped, Prepared, Started, Paused, PlaybackCompleted}
if (mMediaPlayer != null && (mCurrentState == STATE_PREPARED || mCurrentState == STATE_PLAYING || mCurrentState == STATE_PAUSED || mCurrentState == STATE_PLAYBACK_COMPLETED)) {
try {
mMediaPlayer.setLooping(looping);
} catch (Exception e) {
Logger.e(e);
}
}
}
public void seekTo(int msec) {
//可用状态{Prepared, Started, Paused, PlaybackCompleted}
if (mMediaPlayer != null && (mCurrentState == STATE_PREPARED || mCurrentState == STATE_PLAYING || mCurrentState == STATE_PAUSED || mCurrentState == STATE_PLAYBACK_COMPLETED)) {
try {
if (msec < 0)
msec = 0;
mMediaPlayer.seekTo(msec);
} catch (IllegalStateException e) {
Logger.e(e);
} catch (Exception e) {
Logger.e(e);
}
}
}
/** 获取当前播放位置 */
public int getCurrentPosition() {
int position = 0;
//可用状态{Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted}
if (mMediaPlayer != null) {
switch (mCurrentState) {
case STATE_PLAYBACK_COMPLETED:
position = getDuration();
break;
case STATE_PLAYING:
case STATE_PAUSED:
try {
position = mMediaPlayer.getCurrentPosition();
} catch (IllegalStateException e) {
Logger.e(e);
} catch (Exception e) {
Logger.e(e);
}
break;
}
}
return position;
}
public boolean isPlaying() {
//可用状态{Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted}
if (mMediaPlayer != null && mCurrentState == STATE_PLAYING) {
try {
return mMediaPlayer.isPlaying();
} catch (IllegalStateException e) {
Logger.e(e);
} catch (Exception e) {
Logger.e(e);
}
}
return false;
}
/** 调用release方法以后MediaPlayer无法再恢复使用 */
public void release() {
mTargetState = STATE_RELEASED;
mCurrentState = STATE_RELEASED;
if (mMediaPlayer != null) {
try {
mMediaPlayer.release();
} catch (IllegalStateException e) {
Logger.e(e);
} catch (Exception e) {
Logger.e(e);
}
mMediaPlayer = null;
}
}
public void openVideo(Uri uri) {
if (uri == null || mSurfaceHolder == null || getContext() == null) {
// not ready for playback just yet, will try again later
if (mSurfaceHolder == null && uri != null) {
mUri = uri;
}
return;
}
Logger.e("[LocalVideoView]openVideo...");
mUri = uri;
mDuration = 0;
//Idle 状态:当使用new()方法创建一个MediaPlayer对象或者调用了其reset()方法时,该MediaPlayer对象处于idle状态。
//End 状态:通过release()方法可以进入End状态,只要MediaPlayer对象不再被使用,就应当尽快将其通过release()方法释放掉
//Initialized 状态:这个状态比较简单,MediaPlayer调用setDataSource()方法就进入Initialized状态,表示此时要播放的文件已经设置好了。
//Prepared 状态:初始化完成之后还需要通过调用prepare()或prepareAsync()方法,这两个方法一个是同步的一个是异步的,只有进入Prepared状态,才表明MediaPlayer到目前为止都没有错误,可以进行文件播放。
Exception exception = null;
try {
if (mMediaPlayer == null) {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnPreparedListener(mPreparedListener);
mMediaPlayer.setOnCompletionListener(mCompletionListener);
mMediaPlayer.setOnErrorListener(mErrorListener);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
// mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setVolume(mVolumn, mVolumn);
mMediaPlayer.setSurface(new Surface(mSurfaceHolder));
} else {
mMediaPlayer.reset();
}
mMediaPlayer.setDataSource(getContext(), uri);
// if (mLooping)
// mMediaPlayer.setLooping(true);//循环播放
mMediaPlayer.prepareAsync();
// we don't set the target state here either, but preserve the
// target state that was there before.
mCurrentState = STATE_PREPARING;
} catch (IOException ex) {
exception = ex;
} catch (IllegalArgumentException ex) {
exception = ex;
} catch (Exception ex) {
exception = ex;
}
if (exception != null) {
Logger.e(exception);
mCurrentState = STATE_ERROR;
if (mErrorListener != null)
mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
}
}
private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(android.media.MediaPlayer mp) {
mCurrentState = STATE_PLAYBACK_COMPLETED;
// mTargetState = STATE_PLAYBACK_COMPLETED;
if (mOnCompletionListener != null)
mOnCompletionListener.onCompletion(mp);
}
};
MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(android.media.MediaPlayer mp) {
//必须是正常状态
if (mCurrentState == STATE_PREPARING) {
mCurrentState = STATE_PREPARED;
try {
mDuration = mp.getDuration();
} catch (IllegalStateException e) {
Logger.e(e);
}
try {
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
} catch (IllegalStateException e) {
Logger.e(e);
}
switch (mTargetState) {
case STATE_PREPARED:
if (mOnPreparedListener != null)
mOnPreparedListener.onPrepared(mMediaPlayer);
break;
case STATE_PLAYING:
start();
break;
}
}
}
};
private MediaPlayer.OnSeekCompleteListener mSeekCompleteListener = new MediaPlayer.OnSeekCompleteListener() {
@Override
public void onSeekComplete(MediaPlayer mp) {
if (mOnSeekCompleteListener != null)
mOnSeekCompleteListener.onSeekComplete(mp);
}
};
private MediaPlayer.OnErrorListener mErrorListener = new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(android.media.MediaPlayer mp, int framework_err, int impl_err) {
Logger.e("[VideoView]Error:" + framework_err + "," + impl_err);
mCurrentState = STATE_ERROR;
// mTargetState = STATE_ERROR;
//FIX,可以考虑出错以后重新开始
if (mOnErrorListener != null)
mOnErrorListener.onError(mp, framework_err, impl_err);
return true;
}
};
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
boolean needReOpen = (mSurfaceHolder == null);
mSurfaceHolder = surface;
if (needReOpen) {
reOpen();
}
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
//画布失效
mSurfaceHolder = null;
release();
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
/** 是否可用 */
public boolean isPrepared() {
//|| mCurrentState == STATE_PAUSED || mCurrentState == STATE_PLAYING
return mMediaPlayer != null && (mCurrentState == STATE_PREPARED);
}
// /** 是否能即可播放 */
// public boolean canStart() {
// return mMediaPlayer != null && (mCurrentState == STATE_PREPARED || mCurrentState == STATE_PAUSED);
// }
private static final int HANDLER_MESSAGE_PARSE = 0;
private static final int HANDLER_MESSAGE_LOOP = 1;
private Handler mVideoHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case HANDLER_MESSAGE_PARSE:
pause();
break;
case HANDLER_MESSAGE_LOOP:
if (isPlaying()) {
seekTo(msg.arg1);
sendMessageDelayed(mVideoHandler.obtainMessage(HANDLER_MESSAGE_LOOP, msg.arg1, msg.arg2), msg.arg2);
}
break;
default:
break;
}
super.handleMessage(msg);
}
};
/** 定时暂停 */
public void pauseDelayed(int delayMillis) {
if (mVideoHandler.hasMessages(HANDLER_MESSAGE_PARSE))
mVideoHandler.removeMessages(HANDLER_MESSAGE_PARSE);
mVideoHandler.sendEmptyMessageDelayed(HANDLER_MESSAGE_PARSE, delayMillis);
}
/** 暂停并且清除定时任务 */
public void pauseClearDelayed() {
pause();
if (mVideoHandler.hasMessages(HANDLER_MESSAGE_PARSE))
mVideoHandler.removeMessages(HANDLER_MESSAGE_PARSE);
if (mVideoHandler.hasMessages(HANDLER_MESSAGE_LOOP))
mVideoHandler.removeMessages(HANDLER_MESSAGE_LOOP);
}
/** 区域内循环播放 */
public void loopDelayed(int startTime, int endTime) {
int delayMillis = endTime - startTime;
seekTo(startTime);
if (!isPlaying())
start();
if (mVideoHandler.hasMessages(HANDLER_MESSAGE_LOOP))
mVideoHandler.removeMessages(HANDLER_MESSAGE_LOOP);
mVideoHandler.sendMessageDelayed(mVideoHandler.obtainMessage(HANDLER_MESSAGE_LOOP, getCurrentPosition(), delayMillis), delayMillis);
}
}
|
/*
* 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.opensearch.action.admin.indices.flush;
import org.opensearch.action.ActionType;
public class SyncedFlushAction extends ActionType<SyncedFlushResponse> {
public static final SyncedFlushAction INSTANCE = new SyncedFlushAction();
public static final String NAME = "indices:admin/synced_flush";
private SyncedFlushAction() {
super(NAME, SyncedFlushResponse::new);
}
}
|
/*
* Copyright © 2018 Shaburov Oleg
*
* 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.touchbit.buggy.core.testng;
import org.atteo.classindex.IndexSubclasses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
import org.touchbit.buggy.core.Buggy;
import org.touchbit.buggy.core.exceptions.BuggyConfigurationException;
import org.touchbit.buggy.core.model.Suite;
import org.touchbit.buggy.core.process.Component;
import org.touchbit.buggy.core.process.Interface;
import org.touchbit.buggy.core.process.Service;
import org.touchbit.buggy.core.utils.BuggyUtils;
import java.util.*;
import java.util.stream.Collectors;
import static org.testng.TestNG.DEFAULT_COMMAND_LINE_TEST_NAME;
import static org.testng.xml.XmlSuite.ParallelMode.METHODS;
/**
* Base class of test suite.
* <p>
* Created by Oleg Shaburov on 15.05.2018
* shaburov.o.a@gmail.com
*/
@SuppressWarnings("WeakerAccess")
@IndexSubclasses
public class TestSuite extends XmlSuite {
protected Logger log = LoggerFactory.getLogger(TestSuite.class);
private Suite suite;
private Component component;
private Service service;
private Interface anInterface;
public TestSuite() {
this(Buggy.getPrimaryConfig().getThreads(), METHODS);
}
public TestSuite(Suite suite) {
this(null, Buggy.getPrimaryConfig().getThreads(), METHODS, suite);
}
public TestSuite(int threadCount) {
this(threadCount, METHODS);
}
public TestSuite(int threadCount, ParallelMode parallel) {
this(null, threadCount, parallel);
}
public TestSuite(String name, int threadCount, ParallelMode parallel) {
this(name, threadCount, parallel, null);
}
public TestSuite(String name, int threadCount, ParallelMode parallel, Suite s) {
suite = s;
if (s == null) {
suite = this.getClass().getAnnotation(Suite.class);
}
if (suite == null) {
throw new BuggyConfigurationException("There is no @Suite annotation for " + this.getClass());
}
component = BuggyUtils.getComponent(suite);
service = BuggyUtils.getService(suite);
anInterface = BuggyUtils.getInterface(suite);
if (name == null) {
this.setName(component.getName() + " " + service.getName() + " " + anInterface.getName() + " suite");
} else {
this.setName(name);
}
this.setParallel(parallel);
this.setThreadCount(threadCount);
}
/**
* The method of adding to the test classes {@link XmlClass} in the test package {@link XmlTest}
* @param packageName - name / description of the test package
* @param classes - array of added classes.
*/
public void addTestPackage(String packageName, final Class<?>... classes) {
if (packageName == null || packageName.isEmpty()) {
packageName = DEFAULT_COMMAND_LINE_TEST_NAME;
}
if (classes.length == 0) {
Buggy.incrementBuggyWarns();
log.warn("There are no classes for the test package: {}", packageName);
return;
}
List<Class<?>> classList = new ArrayList<>(Arrays.asList(classes));
removeDuplicatesClasses(classList);
List<XmlClass> xmlClasses = new ArrayList<>();
for (Class<?> aClass : classList) {
xmlClasses.add(new XmlClass(aClass));
}
removeDuplicatesXmlClasses(xmlClasses, this.getTests());
XmlTest testPackage = null;
for (XmlTest t : this.getTests()) {
if (t.getName().equals(packageName)) {
testPackage = t;
break;
}
}
if (!xmlClasses.isEmpty()) {
if (testPackage == null) {
testPackage = new XmlTest(this);
}
testPackage.setName(packageName);
testPackage.getXmlClasses().addAll(xmlClasses);
log.debug("Suite {}. Add test package (XmlTest): {}", this.getName(), packageName);
if (log.isDebugEnabled()) {
StringJoiner stringJoiner = new StringJoiner("\n ", "[\n ", "\n]");
testPackage.getXmlClasses().forEach(c -> stringJoiner.add(c.getName()));
log.debug("{} classes:\n{}", packageName, stringJoiner);
}
} else {
log.debug("The {} test package (XmlTest) does not contain unique test classes " +
"and has not been added to the {} test suite.", packageName, this.getName());
}
}
private void removeDuplicatesClasses(final List<Class<?>> classList) {
Set<Class<?>> hs = new HashSet<>(classList);
if (hs.size() != classList.size()) {
List<Class<?>> duplicates = new ArrayList<>(classList);
hs.forEach(duplicates::remove);
duplicates.forEach(c -> {
classList.remove(c);
Buggy.incrementBuggyWarns();
log.info("TRVariables duplicate has been removed from the class list: {}", c.getTypeName());
});
}
}
private void removeDuplicatesXmlClasses(final List<XmlClass> classesList, List<XmlTest> xmlTests) {
for (XmlTest test : xmlTests) {
List<XmlClass> duplicates = test.getXmlClasses().stream()
.filter(tc -> classesList.stream()
.anyMatch(tc::equals))
.collect(Collectors.toList());
if (!duplicates.isEmpty()) {
duplicates.forEach(c -> {
Buggy.incrementBuggyWarns();
log.info("The test package {} already contains a class: {}", test.getName(), c);
});
}
duplicates.forEach(classesList::remove);
}
}
@Override
public boolean equals(Object obj) {
if (super.equals(obj)) {
TestSuite testSuite = (TestSuite) obj;
return testSuite.suite.equals(suite);
}
return false;
}
@Override
public int hashCode() {
return 31 * super.hashCode() + suite.hashCode();
}
public Suite getSuite() {
return suite;
}
public Component getComponent() {
return component;
}
public Service getService() {
return service;
}
public Interface getInterface() {
return anInterface;
}
public void setLog(Logger logger) {
log = logger;
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.05.26 at 11:27:57 AM PDT
//
package net.authorize.api.contract.v1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{AnetApi/xml/v1/schema/AnetApiSchema.xsd}ANetApiRequest">
* <sequence>
* <element name="searchType" type="{AnetApi/xml/v1/schema/AnetApiSchema.xsd}ARBGetSubscriptionListSearchTypeEnum"/>
* <element name="sorting" type="{AnetApi/xml/v1/schema/AnetApiSchema.xsd}ARBGetSubscriptionListSorting" minOccurs="0"/>
* <element name="paging" type="{AnetApi/xml/v1/schema/AnetApiSchema.xsd}Paging" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"searchType",
"sorting",
"paging"
})
@XmlRootElement(name = "ARBGetSubscriptionListRequest")
public class ARBGetSubscriptionListRequest
extends ANetApiRequest
{
@XmlElement(required = true)
protected ARBGetSubscriptionListSearchTypeEnum searchType;
protected ARBGetSubscriptionListSorting sorting;
protected Paging paging;
/**
* Gets the value of the searchType property.
*
* @return
* possible object is
* {@link ARBGetSubscriptionListSearchTypeEnum }
*
*/
public ARBGetSubscriptionListSearchTypeEnum getSearchType() {
return searchType;
}
/**
* Sets the value of the searchType property.
*
* @param value
* allowed object is
* {@link ARBGetSubscriptionListSearchTypeEnum }
*
*/
public void setSearchType(ARBGetSubscriptionListSearchTypeEnum value) {
this.searchType = value;
}
/**
* Gets the value of the sorting property.
*
* @return
* possible object is
* {@link ARBGetSubscriptionListSorting }
*
*/
public ARBGetSubscriptionListSorting getSorting() {
return sorting;
}
/**
* Sets the value of the sorting property.
*
* @param value
* allowed object is
* {@link ARBGetSubscriptionListSorting }
*
*/
public void setSorting(ARBGetSubscriptionListSorting value) {
this.sorting = value;
}
/**
* Gets the value of the paging property.
*
* @return
* possible object is
* {@link Paging }
*
*/
public Paging getPaging() {
return paging;
}
/**
* Sets the value of the paging property.
*
* @param value
* allowed object is
* {@link Paging }
*
*/
public void setPaging(Paging value) {
this.paging = value;
}
}
|
package net.moddingplayground.thematic.api.item;
import net.minecraft.block.entity.BannerPattern;
import net.minecraft.item.BannerPatternItem;
import net.minecraft.tag.TagKey;
import net.moddingplayground.thematic.api.theme.Theme;
import net.moddingplayground.thematic.api.theme.Themed;
public class ThemedBannerPatternItem extends BannerPatternItem implements Themed {
private final Theme theme;
public ThemedBannerPatternItem(Theme theme, TagKey<BannerPattern> pattern, Settings settings) {
super(pattern, settings);
this.theme = theme;
}
@Override
public Theme getTheme() {
return this.theme;
}
}
|
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2007, 2009, 2010, 2011, 2013, 2014, 2016 Synacor, Inc.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software Foundation,
* version 2 of the License.
*
* 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 GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <https://www.gnu.org/licenses/>.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.server;
import java.nio.ByteBuffer;
import org.apache.mina.core.buffer.IoBuffer;
public final class NioUtil {
public static final byte CR = '\r';
public static final byte LF = '\n';
public static final byte DOT = '.';
public static final int INITIAL_CAPACITY = 32;
/**
* Ensure that specified buffer has at least enough capacity to accommodate 'minSize' additional bytes, but not more
* than 'maxSize' additional bytes. If 'maxSize' is 0, then there is no limit.
*
* @param bb the ByteBuffer to expand, or null to create a new one
* @param minSize minimum additional capacity for resulting byte buffer
* @param maxSize maximum additional capacity, or -1 for no maximum
* @return the resulting, possible expanded, ByteBuffer
*/
public static ByteBuffer expand(ByteBuffer bb, int minSize, int maxSize) {
if (maxSize != -1 && maxSize < minSize) {
throw new IllegalArgumentException("maxSize < minSize");
}
if (bb == null) {
int size = Math.max(minSize, INITIAL_CAPACITY);
if (maxSize != -1 && size > maxSize) size = maxSize;
return ByteBuffer.allocate(size);
}
if (bb.remaining() >= minSize) return bb;
int capacity = Math.max((bb.capacity() * 3) / 2 + 1,
bb.position() + minSize);
if (maxSize != -1) {
capacity = Math.max(capacity, bb.position() + maxSize);
}
ByteBuffer tmp = ByteBuffer.allocate(capacity);
bb.flip();
return tmp.put(bb);
}
public static ByteBuffer expand(ByteBuffer bb, int minSize) {
return expand(bb, minSize, -1);
}
public static String toAsciiString(ByteBuffer bb) {
int len = bb.remaining();
char[] cs = new char[len];
for (int i = 0; i < len; i++) {
cs[i] = (char) (bb.get(i) & 0xff);
}
return new String(cs);
}
public static ByteBuffer toAsciiBytes(String s) {
return put(ByteBuffer.allocate(s.length()), s);
}
public static ByteBuffer put(ByteBuffer bb, String s) {
bb = expand(bb, s.length());
for (int i = 0; i < s.length(); i++) {
bb.put(i, (byte) s.charAt(i));
}
return bb;
}
public static byte[] getBytes(ByteBuffer bb) {
if (bb.hasArray() && bb.arrayOffset() == 0 && bb.position() == 0) {
byte[] b = bb.array();
if (b.length == bb.limit()) return b;
}
byte[] b = new byte[bb.limit() - bb.position()];
bb.duplicate().get(b);
return b;
}
public static IoBuffer toIoBuffer(ByteBuffer bb) {
return IoBuffer.wrap(bb);
}
public static String toHexString(ByteBuffer bb) {
return appendHex(new StringBuilder(), bb).toString();
}
public static StringBuilder appendHex(StringBuilder sb, ByteBuffer bb) {
int limit = bb.limit();
for (int i = bb.position(); i < limit; i++) {
int c = bb.get(i) & 0xff;
sb.append(Character.forDigit(c >> 4, 16));
sb.append(Character.forDigit(c & 0xf, 16));
if (i < limit - 1) sb.append(' ');
}
return sb;
}
}
|
package com.github.wangji92.arthas.plugin.common.command;
import com.github.wangji92.arthas.plugin.common.enums.ShellScriptCommandEnum;
import com.github.wangji92.arthas.plugin.common.enums.ShellScriptVariableEnum;
import com.github.wangji92.arthas.plugin.constants.ArthasCommandConstants;
import com.github.wangji92.arthas.plugin.setting.AppSettingsState;
import com.github.wangji92.arthas.plugin.utils.OgnlPsUtils;
import com.github.wangji92.arthas.plugin.utils.StringUtils;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import java.util.HashMap;
import java.util.Map;
/**
* 命令上下文
*
* @author 汪小哥
* @date 02-06-2021
*/
public class CommandContext {
/**
* 上下文
*/
private Map<String, String> params = new HashMap<>();
private Project project;
private PsiElement psiElement;
/**
* maybe null
*/
private Editor editor;
public CommandContext(AnActionEvent event) {
DataContext dataContext = event.getDataContext();
this.project = CommonDataKeys.PROJECT.getData(dataContext);
this.editor = CommonDataKeys.EDITOR.getData(dataContext);
this.psiElement = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
}
public CommandContext(Project project, PsiElement psiElement) {
this.project = project;
this.psiElement = psiElement;
}
/**
* 获取上下文的信息
*
* @param variableEnum
* @return
*/
public String getKeyValue(ShellScriptVariableEnum variableEnum) {
if (variableEnum == null) {
return "";
}
if (this.params.isEmpty()) {
this.initContextParam();
}
return this.params.get(variableEnum.getEnumMsg());
}
/**
* 初始化上下文信息
*/
private synchronized void initContextParam() {
if (!params.isEmpty()) {
return;
}
AppSettingsState instance = AppSettingsState.getInstance(project);
String methodName = OgnlPsUtils.getMethodName(this.psiElement);
String className = OgnlPsUtils.getCommonOrInnerOrAnonymousClassName(this.psiElement);
String fieldName = OgnlPsUtils.getFieldName(this.psiElement);
String executeInfo = OgnlPsUtils.getExecuteInfo(this.psiElement);
params.put(ShellScriptVariableEnum.PROPERTY_DEPTH.getEnumMsg(), instance.depthPrintProperty);
params.put(ShellScriptVariableEnum.CLASS_NAME.getEnumMsg(), className);
params.put(ShellScriptVariableEnum.METHOD_NAME.getEnumMsg(), methodName);
params.put(ShellScriptVariableEnum.EXECUTE_INFO.getEnumMsg(), executeInfo);
params.put(ShellScriptVariableEnum.FIELD_NAME.getEnumMsg(), fieldName);
params.put(ShellScriptVariableEnum.SPRING_CONTEXT.getEnumMsg(), instance.staticSpringContextOgnl);
params.put(ShellScriptVariableEnum.INVOKE_COUNT.getEnumMsg(), instance.invokeCount);
params.put(ShellScriptVariableEnum.INVOKE_MONITOR_COUNT.getEnumMsg(), instance.invokeMonitorCount);
params.put(ShellScriptVariableEnum.INVOKE_MONITOR_INTERVAL.getEnumMsg(), instance.invokeMonitorInterval);
String skpJdkMethodCommand = instance.traceSkipJdk ? "" : ArthasCommandConstants.DEFAULT_SKIP_JDK_FALSE;
params.put(ShellScriptVariableEnum.SKIP_JDK_METHOD.getEnumMsg(), skpJdkMethodCommand);
String printConditionExpress = instance.printConditionExpress ? "-v" : "";
params.put(ShellScriptVariableEnum.PRINT_CONDITION_RESULT.getEnumMsg(), printConditionExpress);
params.put(ShellScriptVariableEnum.CLASSLOADER_HASH_VALUE.getEnumMsg(), "${CLASSLOADER_HASH_VALUE}");
String methodNameNotStar = "*".equals(methodName) ? "" : methodName;
params.put(ShellScriptVariableEnum.METHOD_NAME_NOT_STAR.getEnumMsg(), methodNameNotStar);
String conditionExpressDisplay = instance.conditionExpressDisplay ? ArthasCommandConstants.DEFAULT_CONDITION_EXPRESS : "";
params.put(ShellScriptVariableEnum.CONDITION_EXPRESS_DEFAULT.getEnumMsg(), conditionExpressDisplay);
String beanName = OgnlPsUtils.getSpringBeanName(this.psiElement);
params.put(ShellScriptVariableEnum.SPRING_BEAN_NAME.getEnumMsg(), beanName);
params.put(ShellScriptVariableEnum.DEFAULT_FIELD_VALUE.getEnumMsg(), OgnlPsUtils.getFieldDefaultValue(this.psiElement));
if (StringUtils.isNotBlank(fieldName)) {
String capitalizeFieldName = StringUtils.capitalize(fieldName);
params.put(ShellScriptVariableEnum.CAPITALIZE_FIELD_VALUE.getEnumMsg(), capitalizeFieldName);
}
}
/**
* 获取代码
*
* @param commandEnum
* @return
*/
public String getCommandCode(ShellScriptCommandEnum commandEnum) {
if (commandEnum == null) {
return "";
}
String codeValue = commandEnum.getCode();
if (this.params.isEmpty()) {
this.initContextParam();
}
return StringUtils.stringSubstitutorFromText(codeValue, this.params);
}
/**
* 或取代码
*
* @param commandCode
* @return
*/
public String getCommandCode(String commandCode) {
if (this.params.isEmpty()) {
this.initContextParam();
}
return StringUtils.stringSubstitutorFromText(commandCode, this.params);
}
public Project getProject() {
return project;
}
public PsiElement getPsiElement() {
return psiElement;
}
public Editor getEditor() {
return editor;
}
}
|
/*
* Copyright 2015-2020 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.accessanalyzer.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Contains information about an archive rule.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ArchiveRuleSummary" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ArchiveRuleSummary implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The time at which the archive rule was created.
* </p>
*/
private java.util.Date createdAt;
/**
* <p>
* A filter used to define the archive rule.
* </p>
*/
private java.util.Map<String, Criterion> filter;
/**
* <p>
* The name of the archive rule.
* </p>
*/
private String ruleName;
/**
* <p>
* The time at which the archive rule was last updated.
* </p>
*/
private java.util.Date updatedAt;
/**
* <p>
* The time at which the archive rule was created.
* </p>
*
* @param createdAt
* The time at which the archive rule was created.
*/
public void setCreatedAt(java.util.Date createdAt) {
this.createdAt = createdAt;
}
/**
* <p>
* The time at which the archive rule was created.
* </p>
*
* @return The time at which the archive rule was created.
*/
public java.util.Date getCreatedAt() {
return this.createdAt;
}
/**
* <p>
* The time at which the archive rule was created.
* </p>
*
* @param createdAt
* The time at which the archive rule was created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ArchiveRuleSummary withCreatedAt(java.util.Date createdAt) {
setCreatedAt(createdAt);
return this;
}
/**
* <p>
* A filter used to define the archive rule.
* </p>
*
* @return A filter used to define the archive rule.
*/
public java.util.Map<String, Criterion> getFilter() {
return filter;
}
/**
* <p>
* A filter used to define the archive rule.
* </p>
*
* @param filter
* A filter used to define the archive rule.
*/
public void setFilter(java.util.Map<String, Criterion> filter) {
this.filter = filter;
}
/**
* <p>
* A filter used to define the archive rule.
* </p>
*
* @param filter
* A filter used to define the archive rule.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ArchiveRuleSummary withFilter(java.util.Map<String, Criterion> filter) {
setFilter(filter);
return this;
}
public ArchiveRuleSummary addFilterEntry(String key, Criterion value) {
if (null == this.filter) {
this.filter = new java.util.HashMap<String, Criterion>();
}
if (this.filter.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.filter.put(key, value);
return this;
}
/**
* Removes all the entries added into Filter.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ArchiveRuleSummary clearFilterEntries() {
this.filter = null;
return this;
}
/**
* <p>
* The name of the archive rule.
* </p>
*
* @param ruleName
* The name of the archive rule.
*/
public void setRuleName(String ruleName) {
this.ruleName = ruleName;
}
/**
* <p>
* The name of the archive rule.
* </p>
*
* @return The name of the archive rule.
*/
public String getRuleName() {
return this.ruleName;
}
/**
* <p>
* The name of the archive rule.
* </p>
*
* @param ruleName
* The name of the archive rule.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ArchiveRuleSummary withRuleName(String ruleName) {
setRuleName(ruleName);
return this;
}
/**
* <p>
* The time at which the archive rule was last updated.
* </p>
*
* @param updatedAt
* The time at which the archive rule was last updated.
*/
public void setUpdatedAt(java.util.Date updatedAt) {
this.updatedAt = updatedAt;
}
/**
* <p>
* The time at which the archive rule was last updated.
* </p>
*
* @return The time at which the archive rule was last updated.
*/
public java.util.Date getUpdatedAt() {
return this.updatedAt;
}
/**
* <p>
* The time at which the archive rule was last updated.
* </p>
*
* @param updatedAt
* The time at which the archive rule was last updated.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ArchiveRuleSummary withUpdatedAt(java.util.Date updatedAt) {
setUpdatedAt(updatedAt);
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 (getCreatedAt() != null)
sb.append("CreatedAt: ").append(getCreatedAt()).append(",");
if (getFilter() != null)
sb.append("Filter: ").append(getFilter()).append(",");
if (getRuleName() != null)
sb.append("RuleName: ").append(getRuleName()).append(",");
if (getUpdatedAt() != null)
sb.append("UpdatedAt: ").append(getUpdatedAt());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ArchiveRuleSummary == false)
return false;
ArchiveRuleSummary other = (ArchiveRuleSummary) obj;
if (other.getCreatedAt() == null ^ this.getCreatedAt() == null)
return false;
if (other.getCreatedAt() != null && other.getCreatedAt().equals(this.getCreatedAt()) == false)
return false;
if (other.getFilter() == null ^ this.getFilter() == null)
return false;
if (other.getFilter() != null && other.getFilter().equals(this.getFilter()) == false)
return false;
if (other.getRuleName() == null ^ this.getRuleName() == null)
return false;
if (other.getRuleName() != null && other.getRuleName().equals(this.getRuleName()) == false)
return false;
if (other.getUpdatedAt() == null ^ this.getUpdatedAt() == null)
return false;
if (other.getUpdatedAt() != null && other.getUpdatedAt().equals(this.getUpdatedAt()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCreatedAt() == null) ? 0 : getCreatedAt().hashCode());
hashCode = prime * hashCode + ((getFilter() == null) ? 0 : getFilter().hashCode());
hashCode = prime * hashCode + ((getRuleName() == null) ? 0 : getRuleName().hashCode());
hashCode = prime * hashCode + ((getUpdatedAt() == null) ? 0 : getUpdatedAt().hashCode());
return hashCode;
}
@Override
public ArchiveRuleSummary clone() {
try {
return (ArchiveRuleSummary) 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.accessanalyzer.model.transform.ArchiveRuleSummaryMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
package com.hryzx.movieapp.ui.home;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import com.hryzx.movieapp.R;
public class HomeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
if (getSupportActionBar() != null) {
getSupportActionBar().setElevation(0);
}
}
}
|
/*
* Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.multimap.impl.client;
import com.hazelcast.client.ClientEndpoint;
import com.hazelcast.client.impl.client.BaseClientAddListenerRequest;
import com.hazelcast.core.EntryAdapter;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.EntryEventType;
import com.hazelcast.core.MapEvent;
import com.hazelcast.map.impl.DataAwareEntryEvent;
import com.hazelcast.multimap.impl.MultiMapPortableHook;
import com.hazelcast.multimap.impl.MultiMapService;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.nio.serialization.PortableReader;
import com.hazelcast.nio.serialization.PortableWriter;
import com.hazelcast.security.permission.ActionConstants;
import com.hazelcast.security.permission.MultiMapPermission;
import com.hazelcast.spi.impl.PortableEntryEvent;
import java.io.IOException;
import java.security.Permission;
public class AddEntryListenerRequest extends BaseClientAddListenerRequest {
String name;
Data key;
boolean includeValue;
public AddEntryListenerRequest() {
}
public AddEntryListenerRequest(String name, Data key, boolean includeValue) {
this.name = name;
this.key = key;
this.includeValue = includeValue;
}
@Override
public Object call() throws Exception {
final ClientEndpoint endpoint = getEndpoint();
final MultiMapService service = getService();
EntryAdapter listener = new EntryAdapter() {
@Override
public void onEntryEvent(EntryEvent event) {
if (endpoint.isAlive()) {
if (!(event instanceof DataAwareEntryEvent)) {
throw new IllegalArgumentException("Expecting: DataAwareEntryEvent, Found: "
+ event.getClass().getSimpleName());
}
DataAwareEntryEvent dataAwareEntryEvent = (DataAwareEntryEvent) event;
Data key = dataAwareEntryEvent.getKeyData();
Data value = dataAwareEntryEvent.getNewValueData();
Data oldValue = dataAwareEntryEvent.getOldValueData();
Data mergingValue = dataAwareEntryEvent.getMergingValueData();
final EntryEventType type = event.getEventType();
final String uuid = event.getMember().getUuid();
PortableEntryEvent portableEntryEvent = new PortableEntryEvent(key, value, oldValue, mergingValue
, type, uuid);
endpoint.sendEvent(key, portableEntryEvent, getCallId());
}
}
@Override
public void onMapEvent(MapEvent event) {
if (endpoint.isAlive()) {
PortableEntryEvent portableEntryEvent = toPortableEntryEvent(event);
endpoint.sendEvent(null, portableEntryEvent, getCallId());
}
}
};
String registrationId = service.addListener(name, listener, key, includeValue, localOnly);
endpoint.addListenerDestroyAction(MultiMapService.SERVICE_NAME, name, registrationId);
return registrationId;
}
private PortableEntryEvent toPortableEntryEvent(MapEvent event) {
final EntryEventType type = event.getEventType();
final String uuid = event.getMember().getUuid();
return new PortableEntryEvent(type, uuid, event.getNumberOfEntriesAffected());
}
@Override
public String getServiceName() {
return MultiMapService.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return MultiMapPortableHook.F_ID;
}
@Override
public int getClassId() {
return MultiMapPortableHook.ADD_ENTRY_LISTENER;
}
@Override
public void write(PortableWriter writer) throws IOException {
super.write(writer);
writer.writeBoolean("i", includeValue);
writer.writeUTF("n", name);
final ObjectDataOutput out = writer.getRawDataOutput();
out.writeData(key);
}
@Override
public void read(PortableReader reader) throws IOException {
super.read(reader);
includeValue = reader.readBoolean("i");
name = reader.readUTF("n");
final ObjectDataInput in = reader.getRawDataInput();
key = in.readData();
}
@Override
public Permission getRequiredPermission() {
return new MultiMapPermission(name, ActionConstants.ACTION_LISTEN);
}
@Override
public String getDistributedObjectName() {
return name;
}
@Override
public String getMethodName() {
return "addEntryListener";
}
@Override
public Object[] getParameters() {
if (key != null) {
return new Object[]{null, key, includeValue};
}
return new Object[]{null, includeValue};
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/vision/v1/product_search_service.proto
package com.google.cloud.vision.v1;
/**
*
*
* <pre>
* Request message for the `ListReferenceImages` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1.ListReferenceImagesRequest}
*/
public final class ListReferenceImagesRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.vision.v1.ListReferenceImagesRequest)
ListReferenceImagesRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListReferenceImagesRequest.newBuilder() to construct.
private ListReferenceImagesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListReferenceImagesRequest() {
parent_ = "";
pageToken_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ListReferenceImagesRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
parent_ = s;
break;
}
case 16:
{
pageSize_ = input.readInt32();
break;
}
case 26:
{
java.lang.String s = input.readStringRequireUtf8();
pageToken_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_ListReferenceImagesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_ListReferenceImagesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1.ListReferenceImagesRequest.class,
com.google.cloud.vision.v1.ListReferenceImagesRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
private volatile java.lang.Object parent_;
/**
*
*
* <pre>
* Resource name of the product containing the reference images.
* Format is
* `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
* </pre>
*
* <code>string parent = 1;</code>
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Resource name of the product containing the reference images.
* Format is
* `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
* </pre>
*
* <code>string parent = 1;</code>
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of items to return. Default 10, maximum 100.
* </pre>
*
* <code>int32 page_size = 2;</code>
*/
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
private volatile java.lang.Object pageToken_;
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This is the value
* of `nextPageToken` returned in a previous reference image list request.
* Defaults to the first page if not specified.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This is the value
* of `nextPageToken` returned in a previous reference image list request.
* Defaults to the first page if not specified.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!getParentBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!getPageTokenBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getParentBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!getPageTokenBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.vision.v1.ListReferenceImagesRequest)) {
return super.equals(obj);
}
com.google.cloud.vision.v1.ListReferenceImagesRequest other =
(com.google.cloud.vision.v1.ListReferenceImagesRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.vision.v1.ListReferenceImagesRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1.ListReferenceImagesRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1.ListReferenceImagesRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1.ListReferenceImagesRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1.ListReferenceImagesRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1.ListReferenceImagesRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1.ListReferenceImagesRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1.ListReferenceImagesRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1.ListReferenceImagesRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1.ListReferenceImagesRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1.ListReferenceImagesRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1.ListReferenceImagesRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.vision.v1.ListReferenceImagesRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request message for the `ListReferenceImages` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1.ListReferenceImagesRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.vision.v1.ListReferenceImagesRequest)
com.google.cloud.vision.v1.ListReferenceImagesRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_ListReferenceImagesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_ListReferenceImagesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1.ListReferenceImagesRequest.class,
com.google.cloud.vision.v1.ListReferenceImagesRequest.Builder.class);
}
// Construct using com.google.cloud.vision.v1.ListReferenceImagesRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_ListReferenceImagesRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.vision.v1.ListReferenceImagesRequest getDefaultInstanceForType() {
return com.google.cloud.vision.v1.ListReferenceImagesRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.vision.v1.ListReferenceImagesRequest build() {
com.google.cloud.vision.v1.ListReferenceImagesRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.vision.v1.ListReferenceImagesRequest buildPartial() {
com.google.cloud.vision.v1.ListReferenceImagesRequest result =
new com.google.cloud.vision.v1.ListReferenceImagesRequest(this);
result.parent_ = parent_;
result.pageSize_ = pageSize_;
result.pageToken_ = pageToken_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.vision.v1.ListReferenceImagesRequest) {
return mergeFrom((com.google.cloud.vision.v1.ListReferenceImagesRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.vision.v1.ListReferenceImagesRequest other) {
if (other == com.google.cloud.vision.v1.ListReferenceImagesRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.vision.v1.ListReferenceImagesRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.vision.v1.ListReferenceImagesRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Resource name of the product containing the reference images.
* Format is
* `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
* </pre>
*
* <code>string parent = 1;</code>
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Resource name of the product containing the reference images.
* Format is
* `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
* </pre>
*
* <code>string parent = 1;</code>
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Resource name of the product containing the reference images.
* Format is
* `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
* </pre>
*
* <code>string parent = 1;</code>
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Resource name of the product containing the reference images.
* Format is
* `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
* </pre>
*
* <code>string parent = 1;</code>
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
onChanged();
return this;
}
/**
*
*
* <pre>
* Resource name of the product containing the reference images.
* Format is
* `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
* </pre>
*
* <code>string parent = 1;</code>
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of items to return. Default 10, maximum 100.
* </pre>
*
* <code>int32 page_size = 2;</code>
*/
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* The maximum number of items to return. Default 10, maximum 100.
* </pre>
*
* <code>int32 page_size = 2;</code>
*/
public Builder setPageSize(int value) {
pageSize_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The maximum number of items to return. Default 10, maximum 100.
* </pre>
*
* <code>int32 page_size = 2;</code>
*/
public Builder clearPageSize() {
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This is the value
* of `nextPageToken` returned in a previous reference image list request.
* Defaults to the first page if not specified.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This is the value
* of `nextPageToken` returned in a previous reference image list request.
* Defaults to the first page if not specified.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This is the value
* of `nextPageToken` returned in a previous reference image list request.
* Defaults to the first page if not specified.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This is the value
* of `nextPageToken` returned in a previous reference image list request.
* Defaults to the first page if not specified.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This is the value
* of `nextPageToken` returned in a previous reference image list request.
* Defaults to the first page if not specified.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.vision.v1.ListReferenceImagesRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.vision.v1.ListReferenceImagesRequest)
private static final com.google.cloud.vision.v1.ListReferenceImagesRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.vision.v1.ListReferenceImagesRequest();
}
public static com.google.cloud.vision.v1.ListReferenceImagesRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListReferenceImagesRequest> PARSER =
new com.google.protobuf.AbstractParser<ListReferenceImagesRequest>() {
@java.lang.Override
public ListReferenceImagesRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ListReferenceImagesRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ListReferenceImagesRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListReferenceImagesRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.vision.v1.ListReferenceImagesRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
package com.boltenkov.Calculator.security;
import com.boltenkov.Calculator.model.User;
import com.boltenkov.Calculator.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(String usernameOrEmail)
throws UsernameNotFoundException {
User user = userRepository.findByUsernameOrEmail(usernameOrEmail, usernameOrEmail)
.orElseThrow(() ->
new UsernameNotFoundException("User not found with username or email : " + usernameOrEmail)
);
return UserPrincipal.create(user);
}
@Transactional
public UserDetails loadUserById(Long id) {
User user = userRepository.findById(id).orElseThrow(
() -> new UsernameNotFoundException("User not found with id : " + id)
);
return UserPrincipal.create(user);
}
}
|
// Copyright © 2008-2011 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://dimdwarf.sourceforge.net/LICENSE
package end2endtests;
import end2endtests.apps.echo.EchoApp;
import end2endtests.runner.*;
import org.junit.*;
public class SessionMessagesTest {
private final ServerRunner server = new ServerRunner();
private final ClientRunner client = new ClientRunner(server).withUsername("user1");
private final ClientRunner client2 = new ClientRunner(server).withUsername("user2");
@After
public void shutdownServer() {
try {
server.assertIsRunning();
} finally {
client2.disconnect();
client.disconnect();
server.shutdown();
}
}
@Test
public void send_and_receive_messages() throws Exception {
server.startApplication(EchoApp.class);
client.login();
client.sendMessage("hello");
client.receivesMessage("hello");
}
// TODO: two clients sending session messages to each other (requires persistence?)
}
|
/*
* Copyright 2002-2013 the original author or 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
*
* 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 org.springframework.web.filter;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.springframework.mock.web.test.MockFilterConfig;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.util.WebUtils;
import static org.mockito.BDDMockito.*;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class CharacterEncodingFilterTests extends TestCase {
private static final String FILTER_NAME = "boot";
private static final String ENCODING = "UTF-8";
public void testForceAlwaysSetsEncoding() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
request.setCharacterEncoding(ENCODING);
given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain filterChain = mock(FilterChain.class);
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setForceEncoding(true);
filter.setEncoding(ENCODING);
filter.init(new MockFilterConfig(FILTER_NAME));
filter.doFilter(request, response, filterChain);
verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
verify(response).setCharacterEncoding(ENCODING);
verify(filterChain).doFilter(request, response);
}
public void testEncodingIfEmptyAndNotForced() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
given(request.getCharacterEncoding()).willReturn(null);
given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setForceEncoding(false);
filter.setEncoding(ENCODING);
filter.init(new MockFilterConfig(FILTER_NAME));
filter.doFilter(request, response, filterChain);
verify(request).setCharacterEncoding(ENCODING);
verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
verify(filterChain).doFilter(request, response);
}
public void testDoesNowtIfEncodingIsNotEmptyAndNotForced() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
given(request.getCharacterEncoding()).willReturn(ENCODING);
given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding(ENCODING);
filter.init(new MockFilterConfig(FILTER_NAME));
filter.doFilter(request, response, filterChain);
verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
verify(filterChain).doFilter(request, response);
}
public void testWithBeanInitialization() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
given(request.getCharacterEncoding()).willReturn(null);
given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding(ENCODING);
filter.setBeanName(FILTER_NAME);
filter.setServletContext(new MockServletContext());
filter.doFilter(request, response, filterChain);
verify(request).setCharacterEncoding(ENCODING);
verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
verify(filterChain).doFilter(request, response);
}
public void testWithIncompleteInitialization() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
given(request.getCharacterEncoding()).willReturn(null);
given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
given(request.getAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding(ENCODING);
filter.doFilter(request, response, filterChain);
verify(request).setCharacterEncoding(ENCODING);
verify(request).setAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
verify(request).removeAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
verify(filterChain).doFilter(request, response);
}
}
|
package remote;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class LaunchServer {
public static void main(String[] args) {
try {
// Export the remote math object to the Java RMI runtime so that it
// can receive incoming remote calls.
// Because RemoteMath extends UnicastRemoteObject, this
// is done automatically when the object is initialized.
//
// RemoteMath obj = new RemoteMath();
// IRemoteMath stub = (IRemoteMath) UnicastRemoteObject.exportObject(obj, 0);
//
WhiteBoardServer server = new WhiteBoardServer("coco");
// Publish the remote object's stub in the registry under the name "Compute"
Registry registry = LocateRegistry.getRegistry();
registry.rebind("WhiteBoardServer", server);
System.out.println("WhiteBoard server ready");
// The server will continue running as long as there are remote objects exported
// into
// the RMI runtime, to re move remote objects from the
// RMI runtime so that they can no longer accept RMI calls you can use:
// UnicastRemoteObject.unexportObject(remoteMath, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
public class VisitorNum extends SimpleNode {
private int value;
public VisitorNum(int id) { super(id); }
public void setValue(String str) {value = Integer.parseInt(str);}
public int getValue() {return value;}
public String toString() { return "Num: " + value; }
public Object jjtAccept(TheGrandFinaleVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
/*
* Copyright 2002-2017 the original author or 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 org.springframework.beans.factory.support;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Executable;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Supplier;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Spring 2.5之前是没有GenericBeanDefinition类的,为了描述BeanDefinition的继承关系,都是使用RootBeanDefinition
* 类定义通用父类的BeanDefinition信息,再使用ChildBeanDefinition继承RootBeanDefinition信息并在ChildBeanDefinition中
* 添加个性化的描述信息
*
* RootBeanDefinition可以作为模板也可以作为真实的BeanDefinition对象,如果是作为模板被ChildBeanDefinition继承,
* 需要使用setAbstract方法来设置为抽象,否则会报错。如果是真实的BeanDefinition对象,需要使用setBeanClass方法来设置
* 这个BeanDefinition描述的Class对象
* A root bean definition represents the merged bean definition that backs
* a specific bean in a Spring BeanFactory at runtime. It might have been created
* from multiple original bean definitions that inherit from each other,
* typically registered as {@link GenericBeanDefinition GenericBeanDefinitions}.
* A root bean definition is essentially the 'unified' bean definition view at runtime.
*
* <p>Root bean definitions may also be used for registering individual bean definitions
* in the configuration phase. However, since Spring 2.5, the preferred way to register
* bean definitions programmatically is the {@link GenericBeanDefinition} class.
* GenericBeanDefinition has the advantage that it allows to dynamically define
* parent dependencies, not 'hard-coding' the role as a root bean definition.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see GenericBeanDefinition
* @see ChildBeanDefinition
*/
@SuppressWarnings("serial")
public class RootBeanDefinition extends AbstractBeanDefinition {
/**
* BeanDefinition的持有者
*/
@Nullable
private BeanDefinitionHolder decoratedDefinition;
@Nullable
private AnnotatedElement qualifiedElement;
boolean allowCaching = true;
boolean isFactoryMethodUnique = false;
@Nullable
volatile ResolvableType targetType;
/** Package-visible field for caching the determined Class of a given bean definition */
@Nullable
volatile Class<?> resolvedTargetType;
/** Package-visible field for caching the return type of a generically typed factory method */
@Nullable
volatile ResolvableType factoryMethodReturnType;
/** Common lock for the four constructor fields below */
final Object constructorArgumentLock = new Object();
/**
* 用于缓存已经解析出的构造函数或工厂方法的包可见字段
*
* 如果BeanDefinition中已经存放了解析出的这个bean的构造方法或工厂方法
* 其中,构造方法用于创建通过@Component等注解标注的bean的初始对象。
* 工厂方法(FactoryMethod)则用于创建通过@Bean注解标注的bean的初始对象,
* 虽然从方法的角度上看,一个是类的构造方法,一个是类的普通方法,但是最终目的都是创建bean对象。
* 所以在创建对象的时候,意义是几乎相同的(在BeanDefinition中存储到了一起)
*/
/** Package-visible field for caching the resolved constructor or factory method */
@Nullable
Executable resolvedConstructorOrFactoryMethod;
/**
* 表示这个BeanDefinition表示的bean的构造方法的参数是否已被解析过
*/
/** Package-visible field that marks the constructor arguments as resolved */
boolean constructorArgumentsResolved = false;
/** Package-visible field for caching fully resolved constructor arguments */
@Nullable
Object[] resolvedConstructorArguments;
/**
* 用于缓存部分准备好的构造函数参数的包可见字段
*/
/** Package-visible field for caching partly prepared constructor arguments */
@Nullable
Object[] preparedConstructorArguments;
/** Common lock for the two post-processing fields below */
final Object postProcessingLock = new Object();
/** Package-visible field that indicates MergedBeanDefinitionPostProcessor having been applied */
boolean postProcessed = false;
/** Package-visible field that indicates a before-instantiation post-processor having kicked in */
@Nullable
volatile Boolean beforeInstantiationResolved;
@Nullable
private Set<Member> externallyManagedConfigMembers;
@Nullable
private Set<String> externallyManagedInitMethods;
@Nullable
private Set<String> externallyManagedDestroyMethods;
/**
* Create a new RootBeanDefinition, to be configured through its bean
* properties and configuration methods.
* @see #setBeanClass
* @see #setScope
* @see #setConstructorArgumentValues
* @see #setPropertyValues
*/
public RootBeanDefinition() {
super();
}
/**
* Create a new RootBeanDefinition for a singleton.
* @param beanClass the class of the bean to instantiate
* @see #setBeanClass
*/
public RootBeanDefinition(@Nullable Class<?> beanClass) {
super();
setBeanClass(beanClass);
}
/**
* Create a new RootBeanDefinition for a singleton bean, constructing each instance
* through calling the given supplier (possibly a lambda or method reference).
* @param beanClass the class of the bean to instantiate
* @param instanceSupplier the supplier to construct a bean instance,
* as an alternative to a declaratively specified factory method
* @since 5.0
* @see #setInstanceSupplier
*/
public <T> RootBeanDefinition(@Nullable Class<T> beanClass, @Nullable Supplier<T> instanceSupplier) {
super();
setBeanClass(beanClass);
setInstanceSupplier(instanceSupplier);
}
/**
* Create a new RootBeanDefinition for a scoped bean, constructing each instance
* through calling the given supplier (possibly a lambda or method reference).
* @param beanClass the class of the bean to instantiate
* @param scope the name of the corresponding scope
* @param instanceSupplier the supplier to construct a bean instance,
* as an alternative to a declaratively specified factory method
* @since 5.0
* @see #setInstanceSupplier
*/
public <T> RootBeanDefinition(@Nullable Class<T> beanClass, String scope, @Nullable Supplier<T> instanceSupplier) {
super();
setBeanClass(beanClass);
setScope(scope);
setInstanceSupplier(instanceSupplier);
}
/**
* Create a new RootBeanDefinition for a singleton,
* using the given autowire mode.
* @param beanClass the class of the bean to instantiate
* @param autowireMode by name or type, using the constants in this interface
* @param dependencyCheck whether to perform a dependency check for objects
* (not applicable to autowiring a constructor, thus ignored there)
*/
public RootBeanDefinition(@Nullable Class<?> beanClass, int autowireMode, boolean dependencyCheck) {
super();
setBeanClass(beanClass);
setAutowireMode(autowireMode);
if (dependencyCheck && getResolvedAutowireMode() != AUTOWIRE_CONSTRUCTOR) {
setDependencyCheck(DEPENDENCY_CHECK_OBJECTS);
}
}
/**
* Create a new RootBeanDefinition for a singleton,
* providing constructor arguments and property values.
* @param beanClass the class of the bean to instantiate
* @param cargs the constructor argument values to apply
* @param pvs the property values to apply
*/
public RootBeanDefinition(@Nullable Class<?> beanClass, @Nullable ConstructorArgumentValues cargs,
@Nullable MutablePropertyValues pvs) {
super(cargs, pvs);
setBeanClass(beanClass);
}
/**
* Create a new RootBeanDefinition for a singleton,
* providing constructor arguments and property values.
* <p>Takes a bean class name to avoid eager loading of the bean class.
* @param beanClassName the name of the class to instantiate
*/
public RootBeanDefinition(String beanClassName) {
setBeanClassName(beanClassName);
}
/**
* Create a new RootBeanDefinition for a singleton,
* providing constructor arguments and property values.
* <p>Takes a bean class name to avoid eager loading of the bean class.
* @param beanClassName the name of the class to instantiate
* @param cargs the constructor argument values to apply
* @param pvs the property values to apply
*/
public RootBeanDefinition(String beanClassName, ConstructorArgumentValues cargs, MutablePropertyValues pvs) {
super(cargs, pvs);
setBeanClassName(beanClassName);
}
/**
* Create a new RootBeanDefinition as deep copy of the given
* bean definition.
* @param original the original bean definition to copy from
*/
public RootBeanDefinition(RootBeanDefinition original) {
super(original);
this.decoratedDefinition = original.decoratedDefinition;
this.qualifiedElement = original.qualifiedElement;
this.allowCaching = original.allowCaching;
this.isFactoryMethodUnique = original.isFactoryMethodUnique;
this.targetType = original.targetType;
}
/**
* Create a new RootBeanDefinition as deep copy of the given
* bean definition.
* @param original the original bean definition to copy from
*/
RootBeanDefinition(BeanDefinition original) {
super(original);
}
@Override
public String getParentName() {
return null;
}
@Override
public void setParentName(@Nullable String parentName) {
if (parentName != null) {
throw new IllegalArgumentException("Root bean cannot be changed into a child bean with parent reference");
}
}
/**
* Register a target definition that is being decorated by this bean definition.
*/
public void setDecoratedDefinition(@Nullable BeanDefinitionHolder decoratedDefinition) {
this.decoratedDefinition = decoratedDefinition;
}
/**
* Return the target definition that is being decorated by this bean definition, if any.
*/
@Nullable
public BeanDefinitionHolder getDecoratedDefinition() {
return this.decoratedDefinition;
}
/**
* Specify the {@link AnnotatedElement} defining qualifiers,
* to be used instead of the target class or factory method.
* @since 4.3.3
* @see #setTargetType(ResolvableType)
* @see #getResolvedFactoryMethod()
*/
public void setQualifiedElement(@Nullable AnnotatedElement qualifiedElement) {
this.qualifiedElement = qualifiedElement;
}
/**
* Return the {@link AnnotatedElement} defining qualifiers, if any.
* Otherwise, the factory method and target class will be checked.
* @since 4.3.3
*/
@Nullable
public AnnotatedElement getQualifiedElement() {
return this.qualifiedElement;
}
/**
* Specify a generics-containing target type of this bean definition, if known in advance.
* @since 4.3.3
*/
public void setTargetType(ResolvableType targetType) {
this.targetType = targetType;
}
/**
* Specify the target type of this bean definition, if known in advance.
* @since 3.2.2
*/
public void setTargetType(@Nullable Class<?> targetType) {
this.targetType = (targetType != null ? ResolvableType.forClass(targetType) : null);
}
/**
* Return the target type of this bean definition, if known
* (either specified in advance or resolved on first instantiation).
* @since 3.2.2
*/
@Nullable
public Class<?> getTargetType() {
if (this.resolvedTargetType != null) {
return this.resolvedTargetType;
}
ResolvableType targetType = this.targetType;
return (targetType != null ? targetType.resolve() : null);
}
/**
* Specify a factory method name that refers to a non-overloaded method.
*/
public void setUniqueFactoryMethodName(String name) {
Assert.hasText(name, "Factory method name must not be empty");
setFactoryMethodName(name);
this.isFactoryMethodUnique = true;
}
/**
* Check whether the given candidate qualifies as a factory method.
*/
public boolean isFactoryMethod(Method candidate) {
return candidate.getName().equals(getFactoryMethodName());
}
/**
* Return the resolved factory method as a Java Method object, if available.
* @return the factory method, or {@code null} if not found or not resolved yet
*/
@Nullable
public Method getResolvedFactoryMethod() {
synchronized (this.constructorArgumentLock) {
Executable candidate = this.resolvedConstructorOrFactoryMethod;
return (candidate instanceof Method ? (Method) candidate : null);
}
}
public void registerExternallyManagedConfigMember(Member configMember) {
synchronized (this.postProcessingLock) {
if (this.externallyManagedConfigMembers == null) {
this.externallyManagedConfigMembers = new HashSet<>(1);
}
this.externallyManagedConfigMembers.add(configMember);
}
}
public boolean isExternallyManagedConfigMember(Member configMember) {
synchronized (this.postProcessingLock) {
return (this.externallyManagedConfigMembers != null &&
this.externallyManagedConfigMembers.contains(configMember));
}
}
public void registerExternallyManagedInitMethod(String initMethod) {
synchronized (this.postProcessingLock) {
if (this.externallyManagedInitMethods == null) {
this.externallyManagedInitMethods = new HashSet<>(1);
}
this.externallyManagedInitMethods.add(initMethod);
}
}
public boolean isExternallyManagedInitMethod(String initMethod) {
synchronized (this.postProcessingLock) {
return (this.externallyManagedInitMethods != null &&
this.externallyManagedInitMethods.contains(initMethod));
}
}
public void registerExternallyManagedDestroyMethod(String destroyMethod) {
synchronized (this.postProcessingLock) {
if (this.externallyManagedDestroyMethods == null) {
this.externallyManagedDestroyMethods = new HashSet<>(1);
}
this.externallyManagedDestroyMethods.add(destroyMethod);
}
}
public boolean isExternallyManagedDestroyMethod(String destroyMethod) {
synchronized (this.postProcessingLock) {
return (this.externallyManagedDestroyMethods != null &&
this.externallyManagedDestroyMethods.contains(destroyMethod));
}
}
@Override
public RootBeanDefinition cloneBeanDefinition() {
return new RootBeanDefinition(this);
}
@Override
public boolean equals(Object other) {
return (this == other || (other instanceof RootBeanDefinition && super.equals(other)));
}
@Override
public String toString() {
return "Root bean: " + super.toString();
}
}
|
package ru.web.adressbook.tests;
import org.testng.annotations.Test;
import ru.web.adressbook.model.GroupData;
public class GroupDeletionTests extends TestBase {
@Test
public void testGroupDeletion() {
app.getNavigationHelper().gotoGroupPage();
if (! app.getGroupHelper().isThereAGroup()) {
app.getGroupHelper().createGroup(new GroupData("group1", null, "test2"));
}
app.getGroupHelper().selectGroup();
app.getGroupHelper().deleteSelectedGroups();
app.getGroupHelper().returntoGroupPage();
}
}
|
package demo.binea.com.drawabledemo.activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.ImageView;
import demo.binea.com.drawabledemo.R;
import demo.binea.com.drawabledemo.widget.CircleImageDrawable;
import demo.binea.com.drawabledemo.widget.RoundImageDrawable;
/**
* Created by xubinggui on 15/3/7.
*/
public class HomeActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test_02);
ImageView iv_01 = (ImageView) findViewById(R.id.iv_01);
iv_01.setImageDrawable(new RoundImageDrawable(bitmap));
ImageView iv_02 = (ImageView) findViewById(R.id.iv_02);
iv_02.setImageDrawable(new CircleImageDrawable(bitmap));
}
public void onDrawableState(View view) {
startActivity(new Intent(this, DrawableStateListActivity.class));
}
}
|
package solace.game;
import solace.io.Config;
import solace.util.*;
import java.util.*;
import java.text.DecimalFormat;
/**
* Represents a shop in the game world.
* @author Ryan Sandor Richards
*/
public class Shop {
Room room;
List<ShopItem> items = new ArrayList<ShopItem>();
String id = null;
String name = "";
Mobile owner = null;
double buyMultiplier = 0.5;
double sellMultiplier = 1.5;
/**
* Creates a new shop.
* @param i The id of the shop.
* @param n The name of the shop.
* @param r Room the shop inhabits.
*/
public Shop(String i, String n, Room r) {
id = i;
name = n;
room = r;
String buyString = Config.get("world.shop.default.buy");
String sellString = Config.get("world.shop.default.sell");
try {
buyMultiplier = Double.parseDouble(buyString);
sellMultiplier = Double.parseDouble(sellString);
}
catch (NumberFormatException e) {
Log.error(String.format(
"Buy or sell modifier in config is not a double: %s, %s",
buyString,
sellString
));
}
}
/**
* Initializes the shop, sets restocking intervals, and sets the owner mobile.
*/
public void initialize() {
// Do not initialize twice
if (owner != null) {
return;
}
// 1. Find the owner mobile in the room
List<Mobile> mobs = room.getMobiles();
synchronized(mobs) {
for (Mobile mob : room.getMobiles()) {
if (mob.ownsShop(id)) {
owner = mob;
break;
}
}
}
// 2. Initialize the shop items in stock
for (ShopItem item : items) {
item.initialize();
}
}
/**
* Tears down the shop removing all global references (such as restock events
* on each item).
*/
public void destroy() {
for (ShopItem item : items) {
item.unregisterRestockEvent();
}
}
/**
* Generates a list of the items in this shop.
* @return [description]
*/
public String list() {
StringBuffer b = new StringBuffer();
// Shop title
b.append(Strings.shopBanner(name));
b.append(String.format(
"| %-9s %11s %-43s %-8s |\n\r",
"Inv#", "Price", "Name", "Qty"
));
b.append(Strings.RULE);
DecimalFormat dec = new DecimalFormat("#,###,###");
int index = 0;
for (ShopItem item : items) {
try {
Item sample = item.getSampleItem();
// This could happen if a reference to a game item was not found by the
// TemplateManager. This item is defunkt, and we should just skip it.
if (sample == null) {
continue;
}
int quantity = item.getQuantity();
b.append(String.format(
"| {c}%-9s{x} {y}%11s{x} %-43s {m}%-8s{x} |\n\r",
"[" + (++index) + "]",
sellPrice(item) + "g",
sample.get("description.inventory"),
(quantity > 0) ? "" + quantity : "--"
));
}
catch (TemplateNotFoundException e) {
// This shouldn't happen because of the check above but here for safety.
Log.error("Shop.list: Item could not be found");
e.printStackTrace();
}
}
b.append(Strings.RULE);
return b.toString();
}
/**
* Determines how much an item sells for.
* @param item Item to be sold.
* @return The price for the item in gold.
* @throws TemplateNotFoundException If the itemId for this shop item is
* invalid.
*/
public long sellPrice(ShopItem item)
throws TemplateNotFoundException
{
Item sample = item.getSampleItem();
// This could happen if the item was not correctly initia
if (sample == null) {
return -1;
}
String value = sample.get("value");
if (value == null) {
value = "1";
}
return (long)(sellMultiplier * Long.parseLong(value));
}
/**
* Determines the amount of gold paid by the shop when selling a given item.
* @param item Item for the shop to buy.
* @return The value in gold the shop will pay for the item.
*/
public long buyPrice(Item item) {
String value = item.get("value");
if (value == null) {
value = "1";
}
return (long)(buyMultiplier * Long.parseLong(value));
}
/**
* @return The multiplier applied to buying items from players.
*/
public double getBuyMultiplier() {
return buyMultiplier;
}
/**
* Sets the buy multiplier for the shop.
* @param d The multiplier to be applied when buying items from players.
*/
public void setBuyMultiplier(double d) {
buyMultiplier = d;
}
/**
* @return The multiplier applied to sellng items to players.
*/
public double getSellMultiplier() {
return sellMultiplier;
}
/**
* Sets the sell multiplier for the shop.
* @param d The multiplier to be applied when selling items to players.
*/
public void setSellMultiplier(double d) {
sellMultiplier = d;
}
/**
* Sets the room for the shop.
* @param r Room to set.
*/
public void setRoom(Room r) {
room = r;
}
/**
* Get's the room the shop inhabits.
* @return The room for the shop.
*/
public Room getRoom() {
return room;
}
/**
* Gets a shop item with the associated index.
* @param index ShopItem index for the item.
* @return The shop item at the given index, or null if the index is out of
* bounds.
*/
public ShopItem getItemByIndex(int index) {
index--;
if (index < 0 || index >= items.size()) {
return null;
}
return items.get(index);
}
/**
* Finds an item shop item with the given name.
* @param name Name of the item
* @return The item with the given name, or null if none was found.
*/
public ShopItem getItemByName(String name) {
for (ShopItem item : items) {
Item sample = item.getSampleItem();
if (sample == null) {
continue;
}
if (sample.hasName(name)) {
return item;
}
}
return null;
}
/**
* Adds a item and puts it up for sale in the shop.
* @param i Item to add.
*/
public void addItem(ShopItem i) {
items.add(i);
}
/**
* Removes an item from sale at the shop.
* @param i Item to remove.
*/
public void removeItem(ShopItem i) {
items.remove(i);
}
/**
* @return The name of the shop.
*/
public String getName() {
return name;
}
/**
* @return The id for this shop.
*/
public String getId() {
return id;
}
/**
* @return The owner mobile for the shop.
*/
public Mobile getOwner() {
return owner;
}
}
|
/*
* Copyright 2013 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.optaplanner.core.api.score.buildin.hardsoftbigdecimal;
import java.math.BigDecimal;
import org.junit.Test;
import org.optaplanner.core.api.score.buildin.AbstractScoreTest;
import org.optaplanner.core.impl.testdata.util.PlannerAssert;
import org.optaplanner.core.impl.testdata.util.PlannerTestUtils;
import static org.junit.Assert.*;
public class HardSoftBigDecimalScoreTest extends AbstractScoreTest {
@Test
public void parseScore() {
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-147.2"), new BigDecimal("-258.3")),
HardSoftBigDecimalScore.parseScore("-147.2hard/-258.3soft"));
assertEquals(HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("-147.2"), new BigDecimal("-258.3")),
HardSoftBigDecimalScore.parseScore("-7init/-147.2hard/-258.3soft"));
}
@Test
public void testToString() {
assertEquals("-147.2hard/-258.3soft",
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-147.2"), new BigDecimal("-258.3")).toString());
assertEquals("-7init/-147.2hard/-258.3soft",
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("-147.2"), new BigDecimal("-258.3")).toString());
}
@Test(expected = IllegalArgumentException.class)
public void parseScoreIllegalArgument() {
HardSoftBigDecimalScore.parseScore("-147.2");
}
@Test
public void toInitializedScore() {
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-147.2"), new BigDecimal("-258.3")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-147.2"), new BigDecimal("-258.3")).toInitializedScore());
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-147.2"), new BigDecimal("-258.3")),
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("-147.2"), new BigDecimal("-258.3")).toInitializedScore());
}
@Test
public void feasible() {
assertScoreNotFeasible(
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-5"), new BigDecimal("-300")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-5"), new BigDecimal("4000")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-0.007"), new BigDecimal("4000")),
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("-5"), new BigDecimal("-300")),
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("0"), new BigDecimal("-300"))
);
assertScoreFeasible(
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("0"), new BigDecimal("-300.007")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("0"), new BigDecimal("-300")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("2"), new BigDecimal("-300")),
HardSoftBigDecimalScore.valueOf(0, new BigDecimal("0"), new BigDecimal("-300"))
);
}
@Test
public void add() {
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("19"), new BigDecimal("-320")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("20"), new BigDecimal("-20")).add(
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-1"), new BigDecimal("-300"))));
assertEquals(HardSoftBigDecimalScore.valueOf(-77, new BigDecimal("19"), new BigDecimal("-320")),
HardSoftBigDecimalScore.valueOf(-70, new BigDecimal("20"), new BigDecimal("-20")).add(
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("-1"), new BigDecimal("-300"))));
}
@Test
public void subtract() {
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("21"), new BigDecimal("280")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("20"), new BigDecimal("-20")).subtract(
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-1"), new BigDecimal("-300"))));
assertEquals(HardSoftBigDecimalScore.valueOf(-63, new BigDecimal("21"), new BigDecimal("280")),
HardSoftBigDecimalScore.valueOf(-70, new BigDecimal("20"), new BigDecimal("-20")).subtract(
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("-1"), new BigDecimal("-300"))));
}
@Test
public void multiply() {
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("6.0"), new BigDecimal("-6.0")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("5.0"), new BigDecimal("-5.0")).multiply(1.2));
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("1.2"), new BigDecimal("-1.2")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("1.0"), new BigDecimal("-1.0")).multiply(1.2));
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("4.8"), new BigDecimal("-4.8")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("4.0"), new BigDecimal("-4.0")).multiply(1.2));
assertEquals(HardSoftBigDecimalScore.valueOf(-14, new BigDecimal("8.6"), new BigDecimal("-10.4")),
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("4.3"), new BigDecimal("-5.2")).multiply(2.0));
}
@Test
public void divide() {
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("5.0"), new BigDecimal("-5.0")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("25.0"), new BigDecimal("-25.0")).divide(5.0));
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("4.2"), new BigDecimal("-4.2")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("21.0"), new BigDecimal("-21.0")).divide(5.0));
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("4.8"), new BigDecimal("-4.8")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("24.0"), new BigDecimal("-24.0")).divide(5.0));
assertEquals(HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("4.3"), new BigDecimal("-5.2")),
HardSoftBigDecimalScore.valueOf(-14, new BigDecimal("8.6"), new BigDecimal("-10.4")).divide(2.0));
}
@Test
public void power() {
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("16.0"), new BigDecimal("25.0")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-4.0"), new BigDecimal("5.0")).power(2.0));
assertEquals(HardSoftBigDecimalScore.valueOf(-343, new BigDecimal("-64.0"), new BigDecimal("125.0")),
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("-4.0"), new BigDecimal("5.0")).power(3.0));
}
@Test
public void negate() {
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-4.0"), new BigDecimal("5.0")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("4.0"), new BigDecimal("-5.0")).negate());
assertEquals(HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("4.0"), new BigDecimal("-5.0")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-4.0"), new BigDecimal("5.0")).negate());
}
@Test
public void equalsAndHashCode() {
assertScoresEqualsAndHashCode(
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-10.0"), new BigDecimal("-200.0")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-10.0"), new BigDecimal("-200.0")),
HardSoftBigDecimalScore.valueOf(0, new BigDecimal("-10.0"), new BigDecimal("-200.0"))
);
assertScoresEqualsAndHashCode(
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("-10.0"), new BigDecimal("-200.0")),
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("-10.0"), new BigDecimal("-200.0"))
);
assertScoresNotEquals(
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-10.0"), new BigDecimal("-200.0")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-30.0"), new BigDecimal("-200.0")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-10.0"), new BigDecimal("-400.0")),
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("-10.0"), new BigDecimal("-200.0"))
);
}
@Test
public void compareTo() {
PlannerAssert.assertCompareToOrder(
HardSoftBigDecimalScore.valueOf(-8, new BigDecimal("0"), new BigDecimal("0")),
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("-20"), new BigDecimal("-20")),
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("-1"), new BigDecimal("-300")),
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("0"), new BigDecimal("0")),
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("0"), new BigDecimal("1")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-20.06"), new BigDecimal("-20")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-20.007"), new BigDecimal("-20")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-20"), new BigDecimal("-20.06")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-20"), new BigDecimal("-20.007")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-20"), new BigDecimal("-20")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-1"), new BigDecimal("-300")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-1"), new BigDecimal("4000")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("0"), new BigDecimal("-1")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("0"), new BigDecimal("0")),
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("0"), new BigDecimal("1"))
);
}
@Test
public void serializeAndDeserialize() {
PlannerTestUtils.serializeAndDeserializeWithAll(
HardSoftBigDecimalScore.valueOfInitialized(new BigDecimal("-12.3"), new BigDecimal("3400.5")),
output -> {
assertEquals(0, output.getInitScore());
assertEquals(new BigDecimal("-12.3"), output.getHardScore());
assertEquals(new BigDecimal("3400.5"), output.getSoftScore());
}
);
PlannerTestUtils.serializeAndDeserializeWithAll(
HardSoftBigDecimalScore.valueOf(-7, new BigDecimal("-12.3"), new BigDecimal("3400.5")),
output -> {
assertEquals(-7, output.getInitScore());
assertEquals(new BigDecimal("-12.3"), output.getHardScore());
assertEquals(new BigDecimal("3400.5"), output.getSoftScore());
}
);
}
}
|
package io.github.ganchix.bitcoinj.properties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* BitcoinJ Properties.
* <p>
* Created by Rafael Ríos.
*/
@Getter
@Setter
@ConfigurationProperties(prefix = "bitcoinj")
public class BitcoinJProperties {
/**
* Network the node is working, main net by default.
*/
private Network network = Network.MAIN_NET;
/**
* Username for rpc.
*/
private String user;
/**
* Password for rpc.
*/
private String password;
/**
* Port used, defaults values: 8332 for main network and 18332 for tests networks .
*/
private Integer port;
/**
* Host, must start with http, localhost for default
*/
private String host = "http://localhost";
}
|
package models;
public class Child {
private String childName;
public String getChildName() {
return childName;
}
public void setChildName(String childName) {
this.childName = childName;
}
}
|
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
/**
* @LoadBalanced注解,表示开启客户端负载均衡
*/
@LoadBalanced
/**
* 实例化RestTemplate
*/
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
}
|
/*
* Copyright 2020, 2021, Ludovic Henry
*
* 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.
*
* Please contact git@ludovic.dev or visit ludovic.dev if you need additional
* information or have any questions.
*/
import dev.ludovic.netlib.LAPACK;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.*;
public class DtgsylTest extends LAPACKTest {
@ParameterizedTest
@MethodSource("LAPACKImplementations")
void testSanity(LAPACK lapack) {
org.junit.jupiter.api.Assumptions.assumeTrue(false);
}
}
|
/**
* 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.mina.codec;
import java.io.IOException;
import java.io.InputStream;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.InvalidMarkException;
import java.nio.ReadOnlyBufferException;
/**
* A proxy class used to manage ByteBuffers as if they were just a big
* ByteBuffer. We can add as many buffers as needed when accumulating data. From
* the user point of view, the methods are the very same as ByteBuffer provides.
*
* <p>
* IoBuffer instances are *not* thread safe.
*
* <p>
* The IoBuffer uses a singly linked list to handle the multiple Buffers. Thus
* sequential access is very efficient and random access is not. It fits well
* with the common usage patterns of IoBuffer.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public final class IoBuffer {
private static final int BYTE_MASK = 0xff;
private static final long BYTE_MASK_L = 0xffL;
/**
* @see ByteBuffer#allocate(int)
*/
public static IoBuffer allocate(int capacity) {
return wrap(ByteBuffer.allocate(capacity));
}
/**
* @see ByteBuffer#allocateDirect(int)
*/
public static IoBuffer allocateDirect(int capacity) {
return wrap(ByteBuffer.allocateDirect(capacity));
}
/**
* Build a new instance of {@link IoBuffer}
*
* @return a new instance of {@link IoBuffer}
*/
public static IoBuffer newInstance() {
return new IoBuffer();
}
/**
* @see ByteBuffer#wrap(byte[])
*/
public static IoBuffer wrap(byte[]... arrays) {
IoBuffer ioBuffer = new IoBuffer();
for (byte[] array : arrays) {
ioBuffer.add(ByteBuffer.wrap(array));
}
return ioBuffer;
}
/**
* @see ByteBuffer#wrap(byte[], int, int)
*/
public static IoBuffer wrap(byte[] array, int offset, int length) {
return wrap(ByteBuffer.wrap(array, offset, length));
}
/**
* Wraps ByteBuffers into a new IoBuffer
*
* @param buffers
* the ByteBuffers to wrap
* @return the new {@link IoBuffer}
*/
public static IoBuffer wrap(ByteBuffer... buffers) {
IoBuffer ioBuffer = new IoBuffer();
for (ByteBuffer b : buffers) {
ioBuffer.add(b);
}
return ioBuffer;
}
private ByteOrder bo = ByteOrder.BIG_ENDIAN;
private int capacity = 0;
private boolean direct = true;
private BufferNode head, tail;
/** The maximal position in the IoBuffer */
private Pointer limit = new Pointer();
/** The current position in the buffer */
private Pointer mark = new Pointer();
/** The marked position, for the next reset() */
private Pointer position = new Pointer();
/** If the buffer is readonly */
private boolean readonly = false;
private IoBuffer() {
limit(0);
position(0);
mark = null;
}
/**
* Add one or more ByteBuffer to the current IoBuffer
*
* @param buffers
* the ByteBuffers to add
* @return the current {@link IoBuffer}
*/
public IoBuffer add(ByteBuffer... buffers) {
for (ByteBuffer buffer : buffers) {
enqueue(buffer.slice());
}
return this;
}
/**
* @see ByteBuffer#array()
*/
public byte[] array() {
if (capacity == 0) {
return new byte[0];
}
if (head.hasNext()) {
throw new UnsupportedOperationException();
}
return head.getBuffer().array();
}
/**
* @see ByteBuffer#arrayOffset()
*/
public int arrayOffset() {
if (capacity == 0) {
return 0;
}
if (head.hasNext()) {
throw new UnsupportedOperationException();
}
return head.getBuffer().arrayOffset();
}
/**
* Provides an input stream which is actually reading the {@link IoBuffer}
* instance.
* <p>
* Further reads on the returned InputStream move the reading head of the
* {@link IoBuffer} instance used for its creation
*
* @return an input stream
*/
public InputStream asInputStream() {
return new InputStream() {
@Override
public int read() throws IOException {
return hasRemaining() ? get() & BYTE_MASK : -1;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (!hasRemaining()) {
return -1;
}
int toRead = Math.min(remaining(), len);
get(b, off, toRead);
return toRead;
}
};
}
/**
* @see ByteBuffer#asReadOnlyBuffer()
*/
public IoBuffer asReadOnlyBuffer() {
IoBuffer buffer = duplicate();
buffer.readonly = true;
return buffer;
}
/**
* @see ByteBuffer#capacity()
*/
public int capacity() {
return capacity;
}
/**
* @see ByteBuffer#clear()
*/
public IoBuffer clear() {
position = getPointerByPosition(0);
limit = getPointerByPosition(capacity);
mark = null;
return this;
}
/**
* @see ByteBuffer#compact()
*/
public IoBuffer compact() {
for (int i = 0; i < remaining(); i++) {
put(i, get(i + position.getPosition()));
}
position(limit() - position());
limit(capacity);
mark = null;
return this;
}
/**
* Returns a copy of the current {@link IoBuffer}, with an independent copy
* of the position, limit and mark.
*
* @return the copied {@link IoBuffer}
*/
public IoBuffer duplicate() {
IoBuffer buffer = new IoBuffer();
for (BufferNode node = head; node != null; node = node.getNext()) {
ByteBuffer byteBuffer = node.getBuffer().duplicate();
byteBuffer.rewind();
buffer.enqueue(byteBuffer);
}
buffer.position(position());
buffer.limit(limit());
buffer.mark = mark != null ? getPointerByPosition(mark.getPosition()) : null;
buffer.readonly = readonly;
return buffer;
}
private void enqueue(ByteBuffer buffer) {
if (buffer.isReadOnly()) {
readonly = true;
}
if (!buffer.isDirect()) {
direct = false;
}
if (buffer.remaining() > 0) {
BufferNode newnode = new BufferNode(buffer, capacity);
capacity += buffer.capacity();
if (head == null) {
head = newnode;
position = getPointerByPosition(0);
} else {
tail.setNext(newnode);
}
tail = newnode;
limit = getPointerByPosition(capacity);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object ob) {
if (this == ob) {
return true;
}
if (!(ob instanceof IoBuffer)) {
return false;
}
IoBuffer that = (IoBuffer) ob;
if (this.remaining() != that.remaining()) {
return false;
}
int p = this.position();
int q = that.position();
while (this.hasRemaining() && that.hasRemaining()) {
if (this.get() != that.get()) {
this.position(p);
that.position(q);
return false;
}
}
this.position(p);
that.position(q);
return true;
}
/**
* Extends the current IoBuffer capacity.
*
* @param size
* the number of bytes to extend the current IoBuffer
* @return the current {@link IoBuffer}
*/
public IoBuffer extend(int size) {
ByteBuffer extension = isDirect() ? ByteBuffer.allocateDirect(size) : ByteBuffer.allocate(size);
add(extension);
return this;
}
/**
* @see ByteBuffer#flip()
*/
public IoBuffer flip() {
limit = position;
position = getPointerByPosition(0);
return this;
}
/**
* @see ByteBuffer#get()
*/
public byte get() {
if (!hasRemaining()) {
throw new BufferUnderflowException();
}
return get(position);
}
/**
* @see ByteBuffer#get(byte[])
*/
public IoBuffer get(byte[] dst) {
get(dst, 0, dst.length);
return this;
}
/**
* @see ByteBuffer#get(byte[], int,int)
*/
public IoBuffer get(byte[] dst, int offset, int length) {
if (remaining() < length) {
throw new BufferUnderflowException();
}
int remainsToCopy = length;
int currentOffset = offset;
while (remainsToCopy > 0) {
position.updatePos();
position.getNode().getBuffer().position(position.getPositionInNode());
ByteBuffer currentBuffer = position.getNode().getBuffer();
int blocksize = Math.min(remainsToCopy, currentBuffer.remaining());
position.getNode().getBuffer().get(dst, currentOffset, blocksize);
currentOffset += blocksize;
remainsToCopy -= blocksize;
position.incrementPosition(blocksize);
position.getNode().getBuffer().position(0);
}
return this;
}
/**
* @see ByteBuffer#get(int)
*/
public byte get(int index) {
if (index >= limit.getPosition()) {
throw new IndexOutOfBoundsException();
}
return get(getPointerByPosition(index));
}
private byte get(Pointer pos) {
pos.updatePos();
byte b = pos.getNode().getBuffer().get(pos.getPositionInNode());
pos.incrPosition();
return b;
}
/**
* @see ByteBuffer#getChar()
*/
public char getChar() {
return getChar(position);
}
/**
* @see ByteBuffer#getChar(int)
*/
public char getChar(int index) {
return getChar(getPointerByPosition(index));
}
private char getChar(Pointer position) {
return (char) getShort(position);
}
/**
* @see ByteBuffer#getDouble()
*/
public double getDouble() {
return Double.longBitsToDouble(getLong());
}
/**
* @see ByteBuffer#getDouble(int)
*/
public double getDouble(int index) {
return getDouble(getPointerByPosition(index));
}
private double getDouble(Pointer pos) {
return Double.longBitsToDouble(getLong(pos));
}
/**
* @see ByteBuffer#getFloat()
*/
public float getFloat() {
return getFloat(position);
}
/**
* @see ByteBuffer#getFloat(int)
*/
public float getFloat(int index) {
return getFloat(getPointerByPosition(index));
}
private float getFloat(Pointer pos) {
return Float.intBitsToFloat(getInt(pos));
}
/**
* @see ByteBuffer#getInt()
*/
public int getInt() {
return getInt(position);
}
/**
* @see ByteBuffer#getInt(int)
*/
public int getInt(int index) {
return getInt(getPointerByPosition(index));
}
private int getInt(Pointer pos) {
if (pos.getPosition() > capacity - Integer.SIZE / Byte.SIZE) {
throw new BufferUnderflowException();
}
int out = 0;
for (int i = 0; i < Integer.SIZE; i += Byte.SIZE) {
out |= (get(pos) & BYTE_MASK) << (bo == ByteOrder.BIG_ENDIAN ? (Integer.SIZE - Byte.SIZE) - i : i);
}
return out;
}
/**
* @see ByteBuffer#getLong()
*/
public long getLong() {
return getLong(position);
}
/**
* @see ByteBuffer#getLong(int)
*/
public long getLong(int index) {
return getLong(getPointerByPosition(index));
}
private long getLong(Pointer pos) {
if (pos.getPosition() > capacity - Long.SIZE / Byte.SIZE) {
throw new BufferUnderflowException();
}
long out = 0;
for (int i = 0; i < Long.SIZE; i += Byte.SIZE) {
out |= (get(pos) & BYTE_MASK_L) << (bo == ByteOrder.BIG_ENDIAN ? (Long.SIZE - Byte.SIZE) - i : i);
}
return out;
}
private Pointer getPointerByPosition(int pos) {
return new Pointer(pos);
}
/**
* @see ByteBuffer#getShort()
*/
public short getShort() {
return getShort(position);
}
/**
* @see ByteBuffer#getShort(int)
*/
public long getShort(int index) {
return getShort(getPointerByPosition(index));
}
private short getShort(Pointer pos) {
if (pos.getPosition() > capacity - Short.SIZE / Byte.SIZE) {
throw new BufferUnderflowException();
}
if (bo == ByteOrder.BIG_ENDIAN) {
return (short) ((get(pos) & BYTE_MASK) << Byte.SIZE | (get(pos) & BYTE_MASK));
} else {
return (short) ((get(pos) & BYTE_MASK) | (get(pos) & BYTE_MASK) << Byte.SIZE);
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int hash = 0;
Pointer oldPos = position.duplicate();
while (hasRemaining()) {
hash *= 31; // NOSONAR, standard way of hashing
hash += get();
}
position = oldPos;
return hash;
}
/**
* @see ByteBuffer#hasRemaining()
*/
public boolean hasRemaining() {
return remaining() > 0;
}
/**
* @see ByteBuffer#isDirect()
*/
public boolean isDirect() {
return direct;
}
/**
* @see ByteBuffer#isReadOnly()
*/
public boolean isReadOnly() {
return readonly;
}
/**
* @see ByteBuffer#limit()
*/
public int limit() {
return limit.getPosition();
}
/**
* @see ByteBuffer#limit(int)
*/
public void limit(int newLimit) {
this.limit = getPointerByPosition(newLimit);
}
/**
* @see ByteBuffer#mark()
*/
public void mark() {
this.mark = position.duplicate();
}
/**
* Returns the byte order used by this IoBuffer when converting bytes
* from/to other primitive types.
* <p>
* The default byte order of byte buffer is always
* {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN}
*
* @return the byte order used by this IoBuffer when converting bytes
* from/to other primitive types.
*
* @see ByteBuffer#order()
*/
public ByteOrder order() {
return bo;
}
/**
* Sets the byte order of this IoBuffer.
*
* @param bo
* the byte order to set. If {@code null} then the order will be
* {@link ByteOrder#LITTLE_ENDIAN LITTLE_ENDIAN}.
* @return this IoBuffer.
* @see ByteBuffer#order(ByteOrder)
*/
public IoBuffer order(ByteOrder bo) {
this.bo = bo != null ? bo : ByteOrder.LITTLE_ENDIAN;
return this;
}
/**
* @see ByteBuffer#position()
*/
public int position() {
return position.getPosition();
}
/**
* @see ByteBuffer#position(int)
*/
public void position(int newPosition) {
if (newPosition > limit() || newPosition < 0) {
throw new IllegalArgumentException();
}
if (mark != null && mark.getPosition() > newPosition) {
mark = null;
}
this.position.setPosition(newPosition);
}
/**
* @see ByteBuffer#put(byte)
*/
public IoBuffer put(byte b) {
if (readonly) {
throw new ReadOnlyBufferException();
}
if (position.getPosition() >= limit.getPosition()) {
throw new BufferUnderflowException();
}
put(position, b);
return this;
}
/**
* @see ByteBuffer#put(byte[])
*/
public IoBuffer put(byte[] src) {
put(src, 0, src.length);
return this;
}
/**
* @see ByteBuffer#put(ByteBuffer)
*/
public IoBuffer put(ByteBuffer src) {
if (remaining() < src.remaining()) {
throw new BufferOverflowException();
}
if (isReadOnly()) {
throw new ReadOnlyBufferException();
}
while (src.hasRemaining()) {
put(src.get());
}
return this;
}
/**
* @see ByteBuffer#put(ByteBuffer)
*/
public IoBuffer put(IoBuffer src) {
if (src == this) { // NOSONAR, checking the instance
throw new IllegalArgumentException();
}
if (remaining() < src.remaining()) {
throw new BufferOverflowException();
}
if (isReadOnly()) {
throw new ReadOnlyBufferException();
}
while (src.hasRemaining()) {
put(src.get());
}
return this;
}
/**
* @see ByteBuffer#put(byte[], int, int)
*/
public IoBuffer put(byte[] src, int offset, int length) {
if (readonly) {
throw new ReadOnlyBufferException();
}
if (remaining() < length) {
throw new BufferUnderflowException();
}
int remainsToCopy = length;
int currentOffset = offset;
position.getNode().getBuffer().position(position.getPositionInNode());
while (remainsToCopy > 0) {
position.updatePos();
ByteBuffer currentBuffer = position.getNode().getBuffer();
int blocksize = Math.min(remainsToCopy, currentBuffer.remaining());
position.getNode().getBuffer().put(src, currentOffset, blocksize);
currentOffset += blocksize;
remainsToCopy -= blocksize;
position.incrementPosition(blocksize);
}
position.getNode().getBuffer().position(0);
return this;
}
/**
* @see ByteBuffer#put(int, byte)
*/
public IoBuffer put(int index, byte value) {
if (index >= limit.getPosition()) {
throw new IndexOutOfBoundsException();
}
Pointer p = getPointerByPosition(index);
put(p, value);
return this;
}
private IoBuffer put(Pointer pos, byte b) {
pos.updatePos();
pos.getNode().getBuffer().put(pos.getPositionInNode(), b);
pos.incrPosition();
return this;
}
/**
* @see ByteBuffer#putChar(char)
*/
public IoBuffer putChar(char value) {
return putChar(position, value);
}
/**
* @see ByteBuffer#putChar(int, char)
*/
public IoBuffer putChar(int index, char value) {
return putChar(getPointerByPosition(index), value);
}
private IoBuffer putChar(Pointer index, char value) {
return putShort(index, (short) value);
}
/**
* @see ByteBuffer#putDouble(double)
*/
public IoBuffer putDouble(double value) {
return putDouble(position, value);
}
/**
* @see ByteBuffer#putDouble(int, double)
*/
public IoBuffer putDouble(int index, double value) {
return putDouble(getPointerByPosition(index), value);
}
private IoBuffer putDouble(Pointer pos, double value) {
return putLong(pos, Double.doubleToLongBits(value));
}
/**
* @see ByteBuffer#putFloat(float)
*/
public IoBuffer putFloat(float value) {
return putFloat(position, value);
}
/**
* @see ByteBuffer#putFloat(int, float)
*/
public IoBuffer putFloat(int index, float value) {
return putFloat(getPointerByPosition(index), value);
}
private IoBuffer putFloat(Pointer pointer, float value) {
return putInt(pointer, Float.floatToIntBits(value));
}
/**
* @see ByteBuffer#putInt(int)
*/
public IoBuffer putInt(int value) {
return putInt(position, value);
}
/**
* @see ByteBuffer#putInt(int, int)
*/
public IoBuffer putInt(int index, int value) {
return putInt(getPointerByPosition(index), value);
}
private IoBuffer putInt(Pointer pointer, int value) {
if (position.getPosition() > pointer.getPosition()
|| pointer.getPosition() > limit.getPosition() - Integer.SIZE / Byte.SIZE) {
throw new BufferUnderflowException();
}
for (int i = 0; i < Integer.SIZE; i += Byte.SIZE) {
put(pointer, (byte) (value >> (bo == ByteOrder.BIG_ENDIAN ? (Integer.SIZE - Byte.SIZE) - i : i)));
}
return this;
}
/**
* @see ByteBuffer#putLong(int, long)
*/
public IoBuffer putLong(int index, long value) {
return putLong(getPointerByPosition(index), value);
}
/**
* @see ByteBuffer#putLong(long)
*/
public IoBuffer putLong(long value) {
return putLong(position, value);
}
private IoBuffer putLong(Pointer pointer, long value) {
if (position.getPosition() > pointer.getPosition()
|| pointer.getPosition() > limit.getPosition() - Long.SIZE / Byte.SIZE) {
throw new BufferUnderflowException();
}
for (int i = 0; i < Long.SIZE; i += Byte.SIZE) {
put(pointer, (byte) (value >> (bo == ByteOrder.BIG_ENDIAN ? (Long.SIZE - Byte.SIZE) - i : i)));
}
return this;
}
/**
* @see ByteBuffer#putShort(int, short)
*/
public IoBuffer putShort(int index, short value) {
return putShort(getPointerByPosition(index), value);
}
private IoBuffer putShort(Pointer pointer, short value) {
if (position.getPosition() > pointer.getPosition()
|| pointer.getPosition() > limit.getPosition() - Short.SIZE / Byte.SIZE) {
throw new BufferUnderflowException();
}
for (int i = 0; i < Short.SIZE; i += Byte.SIZE) {
put(pointer, (byte) (value >> (bo == ByteOrder.BIG_ENDIAN ? Byte.SIZE - i : i)));
}
return this;
}
/**
* @see ByteBuffer#putShort(short)
*/
public IoBuffer putShort(short value) {
return putShort(position, value);
}
/**
* @see ByteBuffer#remaining()
*/
public int remaining() {
return limit() - position();
}
/**
* @see ByteBuffer#reset()
*/
public IoBuffer reset() {
if (mark == null) {
throw new InvalidMarkException();
}
position = mark.duplicate();
return this;
}
/**
* @see ByteBuffer#rewind()
*/
public IoBuffer rewind() {
position(0);
mark = getPointerByPosition(-1);
return this;
}
/**
* @see ByteBuffer#slice()
*/
public IoBuffer slice() {
position.updatePos();
IoBuffer out = new IoBuffer();
out.order(order());
position.getNode().getBuffer().position(position.getPositionInNode());
if (hasRemaining()) {
tail.getBuffer().limit(limit.getPositionInNode());
for (BufferNode node = position.getNode(); node != limit.getNode(); node = node.getNext()) {
if (node != head) { // NOSONAR, check if instances are the same.
node.getBuffer().position(0);
}
out.add(node.getBuffer());
}
if (tail != head) { // NOSONAR, check if instances are the same.
tail.getBuffer().position(0);
}
out.add(tail.getBuffer().slice());
tail.getBuffer().limit(tail.getBuffer().capacity());
}
position.getNode().getBuffer().position(0);
return out;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getName());
sb.append("[pos=");
sb.append(position());
sb.append(" lim=");
sb.append(limit());
sb.append(" cap=");
sb.append(capacity());
sb.append("]");
return sb.toString();
}
private static final class BufferNode {
private final ByteBuffer buffer;
private BufferNode next;
private final int offset;
public BufferNode(ByteBuffer buffer, int offset) {
this.buffer = buffer;
this.offset = offset;
}
public ByteBuffer getBuffer() {
return buffer;
}
public BufferNode getNext() {
return next;
}
public boolean hasNext() {
return next != null;
}
public void setNext(BufferNode next) {
this.next = next;
}
@Override
public String toString() {
return "BufferNode [offset=" + offset + ", buffer=" + buffer + "]";
}
}
private final class Pointer {
private BufferNode node;
private int positionInBuffer;
public Pointer(int position) {
this();
setPosition(position);
}
public Pointer() {
}
public Pointer duplicate() {
return new Pointer(getPosition());
}
public BufferNode getNode() {
return node;
}
public int getPosition() {
return positionInBuffer + (node == null ? 0 : node.offset);
}
public int getPositionInNode() {
updatePos();
return positionInBuffer;
}
public void incrPosition() {
incrementPosition(1);
}
public void setPosition(int newPosition) {
if ((node == null) || (newPosition < node.offset)) {
node = head;
}
positionInBuffer = node == null ? 0 : newPosition - node.offset;
}
public void incrementPosition(int positionIncrement) {
positionInBuffer += positionIncrement;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getName());
sb.append("[pos=");
sb.append(getPosition());
sb.append(", node=");
sb.append(getNode());
sb.append("]");
return sb.toString();
}
public void updatePos() {
while (node != null && positionInBuffer >= node.getBuffer().capacity() && node.hasNext()) {
positionInBuffer -= node.getBuffer().capacity();
node = node.getNext();
}
}
}
}
|
package org.accounting.system.dtos.pagination;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.mongodb.panache.PanacheQuery;
import org.accounting.system.entities.projections.ProjectionQuery;
import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import javax.ws.rs.core.UriInfo;
import java.util.ArrayList;
import java.util.List;
@Schema(name="PageResource", description="An object represents the paginated entities.")
public class PageResource<T, R> {
@Schema(
type = SchemaType.NUMBER,
implementation = Integer.class,
description = "Page size.",
example = "10"
)
@JsonProperty("size_of_page")
public int sizeOfPage;
@Schema(
type = SchemaType.NUMBER,
implementation = Integer.class,
description = "Page number.",
example = "1"
)
@JsonProperty("number_of_page")
public int numberOfPage;
@Schema(
type = SchemaType.NUMBER,
implementation = Long.class,
description = "Total elements.",
example = "15"
)
@JsonProperty("total_elements")
public long totalElements;
@Schema(
type = SchemaType.NUMBER,
implementation = Integer.class,
description = "Total pages.",
example = "2"
)
@JsonProperty("total_pages")
public int totalPages;
@Schema(
type = SchemaType.ARRAY,
implementation = Object.class,
description = "Paginated entities."
)
@JsonProperty("content")
public List<R> content;
@Schema(
type = SchemaType.ARRAY,
implementation = PageLink.class,
description = "Link to paginated entities."
)
@JsonProperty("links")
public List<PageLink> links;
public PageResource() {
}
public PageResource(ProjectionQuery<T> projectionQuery, List<R> content, UriInfo uriInfo){
links = new ArrayList<>();
this.content = content;
this.sizeOfPage = projectionQuery.list.size();
this.numberOfPage = projectionQuery.index+1;
this.totalElements = projectionQuery.count;
this.totalPages = projectionQuery.pageCount();
if(totalPages !=1){
links.add(buildPageLink(uriInfo, 1, sizeOfPage, "first"));
links.add(buildPageLink(uriInfo, totalPages, sizeOfPage, "last"));
links.add(buildPageLink(uriInfo, numberOfPage, sizeOfPage, "self"));
if(projectionQuery.hasPreviousPage() && projectionQuery.list.size()!=0) {
links.add(buildPageLink(uriInfo, numberOfPage -1, sizeOfPage, "prev"));
}
if(projectionQuery.hasNextPage()) {
links.add(buildPageLink(uriInfo, numberOfPage +1, sizeOfPage, "next"));
}
}
}
public PageResource(PanacheQuery<T> panacheQuery, List<R> content, UriInfo uriInfo){
links = new ArrayList<>();
this.content = content;
this.sizeOfPage = panacheQuery.list().size();
this.numberOfPage = panacheQuery.page().index+1;
this.totalElements = panacheQuery.count();
this.totalPages = panacheQuery.pageCount();
if(totalPages !=1){
links.add(buildPageLink(uriInfo, 1, sizeOfPage, "first"));
links.add(buildPageLink(uriInfo, totalPages, sizeOfPage, "last"));
links.add(buildPageLink(uriInfo, numberOfPage, sizeOfPage, "self"));
if(panacheQuery.hasPreviousPage() && panacheQuery.list().size()!=0) {
links.add(buildPageLink(uriInfo, numberOfPage -1, sizeOfPage, "prev"));
}
if(panacheQuery.hasNextPage()) {
links.add(buildPageLink(uriInfo, numberOfPage +1, sizeOfPage, "next"));
}
}
}
private PageLink buildPageLink(UriInfo uriInfo, int page,int size, String rel) {
return PageLink
.builder()
.href(uriInfo.getRequestUriBuilder().replaceQueryParam("page", page).replaceQueryParam("size", size).build().toString())
.rel(rel)
.build();
}
}
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.v7.graphics;
import java.util.Comparator;
// Referenced classes of package android.support.v7.graphics:
// ColorCutQuantizer
static final class ColorCutQuantizer$1
implements Comparator
{
public int compare(ox ox, ox ox1)
{
return ox1.getVolume() - ox.getVolume();
// 0 0:aload_2
// 1 1:invokevirtual #22 <Method int ColorCutQuantizer$Vbox.getVolume()>
// 2 4:aload_1
// 3 5:invokevirtual #22 <Method int ColorCutQuantizer$Vbox.getVolume()>
// 4 8:isub
// 5 9:ireturn
}
public volatile int compare(Object obj, Object obj1)
{
return compare((ox)obj, (ox)obj1);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:checkcast #18 <Class ColorCutQuantizer$Vbox>
// 3 5:aload_2
// 4 6:checkcast #18 <Class ColorCutQuantizer$Vbox>
// 5 9:invokevirtual #25 <Method int compare(ColorCutQuantizer$Vbox, ColorCutQuantizer$Vbox)>
// 6 12:ireturn
}
ColorCutQuantizer$1()
{
// 0 0:aload_0
// 1 1:invokespecial #13 <Method void Object()>
// 2 4:return
}
}
|
package com.ztxue.admin.bean;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* @author:sunping
* @description:人员信息返回实体
* @date:2021-05-18
*/
@Setter
@Getter
public class ResultUser {
/**
* 主键ID
*/
@JSONField(ordinal = 1)
private Integer id;
/**
* 用户名
*/
@JSONField(ordinal = 2)
private String userName;
/**
* 头像地址
*/
@JSONField(ordinal = 3)
private String headImg;
/**
* 组织id
*/
@JSONField(ordinal = 4)
private Integer orgId;
/**
* 机构名称
*/
@JSONField(ordinal = 5)
private String orgName;
/**
* 部门ID
*/
@JSONField(ordinal = 6)
private Integer deptId;
/**
* 部门名称
*/
@JSONField(ordinal = 7)
private String deptName;
/**
* 姓名
*/
@JSONField(ordinal = 8)
private String realName;
/**
* 年龄
*/
@JSONField(ordinal = 9)
private Integer age;
/**
* 性别1表男,2表女
*/
@JSONField(ordinal = 10)
private Integer sex;
/**
* 邮箱
*/
@JSONField(ordinal = 11)
private String email;
/**
* 电话
*/
@JSONField(ordinal = 12)
private String tel;
/**
* 地址
*/
@JSONField(ordinal = 13)
private String address;
/**
* 描述
*/
@JSONField(ordinal = 14)
private String descr;
/**
* 组织机构区划
*/
@JSONField(ordinal = 15)
private String orgArea;
/**
* 区划
*/
@JSONField(ordinal = 16)
private List<String> areas;
}
|
/*-
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. 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.
* ============LICENSE_END=========================================================
*/
package org.openecomp.mso.bpmn.infrastructure.workflow.serviceTask.client.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class ServiceInputParametersEntity {
public List<ParamEntity> getParamList() {
return paramList;
}
public void setParamList(List<ParamEntity> paramList) {
this.paramList = paramList;
}
@JsonProperty("GENERIC-RESOURCE-API:param")
private List<ParamEntity> paramList;
}
|
package com.coolweather.android.db;
import org.litepal.crud.DataSupport;
/**
* Created by jinzhicheng on 2017/10/24.
* 省级表
*/
public class Province extends DataSupport {
private int id;
private String provinceName;
private int provinceCode;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public int getProvinceCode() {
return provinceCode;
}
public void setProvinceCode(int provinceCode) {
this.provinceCode = provinceCode;
}
}
|
/**
* Copyright 2013 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.
*/
package org.apache.aurora.scheduler.storage.log;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.testing.TearDown;
import com.twitter.common.application.ShutdownRegistry;
import com.twitter.common.base.Command;
import com.twitter.common.base.ExceptionalCommand;
import com.twitter.common.quantity.Amount;
import com.twitter.common.quantity.Data;
import com.twitter.common.quantity.Time;
import com.twitter.common.testing.easymock.EasyMockTest;
import org.apache.aurora.codec.ThriftBinaryCodec;
import org.apache.aurora.codec.ThriftBinaryCodec.CodingException;
import org.apache.aurora.gen.AssignedTask;
import org.apache.aurora.gen.Attribute;
import org.apache.aurora.gen.HostAttributes;
import org.apache.aurora.gen.JobConfiguration;
import org.apache.aurora.gen.JobKey;
import org.apache.aurora.gen.Lock;
import org.apache.aurora.gen.LockKey;
import org.apache.aurora.gen.Quota;
import org.apache.aurora.gen.ScheduleStatus;
import org.apache.aurora.gen.ScheduledTask;
import org.apache.aurora.gen.TaskConfig;
import org.apache.aurora.gen.storage.LogEntry;
import org.apache.aurora.gen.storage.Op;
import org.apache.aurora.gen.storage.RemoveJob;
import org.apache.aurora.gen.storage.RemoveLock;
import org.apache.aurora.gen.storage.RemoveQuota;
import org.apache.aurora.gen.storage.RemoveTasks;
import org.apache.aurora.gen.storage.RewriteTask;
import org.apache.aurora.gen.storage.SaveAcceptedJob;
import org.apache.aurora.gen.storage.SaveFrameworkId;
import org.apache.aurora.gen.storage.SaveHostAttributes;
import org.apache.aurora.gen.storage.SaveLock;
import org.apache.aurora.gen.storage.SaveQuota;
import org.apache.aurora.gen.storage.SaveTasks;
import org.apache.aurora.gen.storage.Snapshot;
import org.apache.aurora.gen.storage.Transaction;
import org.apache.aurora.gen.storage.storageConstants;
import org.apache.aurora.scheduler.base.JobKeys;
import org.apache.aurora.scheduler.base.Query;
import org.apache.aurora.scheduler.base.Tasks;
import org.apache.aurora.scheduler.log.Log;
import org.apache.aurora.scheduler.log.Log.Entry;
import org.apache.aurora.scheduler.log.Log.Position;
import org.apache.aurora.scheduler.log.Log.Stream;
import org.apache.aurora.scheduler.storage.SnapshotStore;
import org.apache.aurora.scheduler.storage.Storage.MutableStoreProvider;
import org.apache.aurora.scheduler.storage.Storage.MutateWork;
import org.apache.aurora.scheduler.storage.entities.IJobConfiguration;
import org.apache.aurora.scheduler.storage.entities.IJobKey;
import org.apache.aurora.scheduler.storage.entities.ILock;
import org.apache.aurora.scheduler.storage.entities.ILockKey;
import org.apache.aurora.scheduler.storage.entities.IQuota;
import org.apache.aurora.scheduler.storage.entities.IScheduledTask;
import org.apache.aurora.scheduler.storage.entities.ITaskConfig;
import org.apache.aurora.scheduler.storage.log.LogStorage.SchedulingService;
import org.apache.aurora.scheduler.storage.log.testing.LogOpMatcher;
import org.apache.aurora.scheduler.storage.log.testing.LogOpMatcher.StreamMatcher;
import org.apache.aurora.scheduler.storage.testing.StorageTestUtil;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.Before;
import org.junit.Test;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.notNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class LogStorageTest extends EasyMockTest {
private static final Amount<Long, Time> SNAPSHOT_INTERVAL = Amount.of(1L, Time.MINUTES);
private static final long NOW = 42L;
private LogStorage logStorage;
private Log log;
private Stream stream;
private Position position;
private StreamMatcher streamMatcher;
private ShutdownRegistry shutdownRegistry;
private SchedulingService schedulingService;
private SnapshotStore<Snapshot> snapshotStore;
private StorageTestUtil storageUtil;
@Before
public void setUp() {
log = createMock(Log.class);
shutdownRegistry = createMock(ShutdownRegistry.class);
LogManager logManager = new LogManager(log, Amount.of(1, Data.GB), false, shutdownRegistry);
schedulingService = createMock(SchedulingService.class);
snapshotStore = createMock(new Clazz<SnapshotStore<Snapshot>>() { });
storageUtil = new StorageTestUtil(this);
logStorage =
new LogStorage(logManager,
schedulingService,
snapshotStore,
SNAPSHOT_INTERVAL,
storageUtil.storage,
storageUtil.schedulerStore,
storageUtil.jobStore,
storageUtil.taskStore,
storageUtil.lockStore,
storageUtil.quotaStore,
storageUtil.attributeStore);
stream = createMock(Stream.class);
streamMatcher = LogOpMatcher.matcherFor(stream);
position = createMock(Position.class);
}
@Test
public void testStart() throws Exception {
// We should open the log and arrange for its clean shutdown.
expect(log.open()).andReturn(stream);
Capture<ExceptionalCommand<IOException>> shutdownStream = createCapture();
shutdownRegistry.addAction(capture(shutdownStream));
stream.close();
// Our start should recover the log and then forward to the underlying storage start of the
// supplied initialization logic.
final AtomicBoolean initialized = new AtomicBoolean(false);
MutateWork.NoResult.Quiet initializationLogic = new MutateWork.NoResult.Quiet() {
@Override
protected void execute(MutableStoreProvider provider) {
// Creating a mock and expecting apply(storeProvider) does not work here for whatever
// reason.
initialized.set(true);
}
};
final Capture<MutateWork.NoResult.Quiet> recoverAndInitializeWork = createCapture();
storageUtil.storage.write(capture(recoverAndInitializeWork));
expectLastCall().andAnswer(new IAnswer<Void>() {
@Override
public Void answer() throws Throwable {
recoverAndInitializeWork.getValue().apply(storageUtil.mutableStoreProvider);
return null;
}
});
Entry entry1 = createMock(Entry.class);
Entry entry2 = createMock(Entry.class);
String frameworkId1 = "bob";
LogEntry recoveredEntry1 =
createTransaction(Op.saveFrameworkId(new SaveFrameworkId(frameworkId1)));
String frameworkId2 = "jim";
LogEntry recoveredEntry2 =
createTransaction(Op.saveFrameworkId(new SaveFrameworkId(frameworkId2)));
expect(entry1.contents()).andReturn(ThriftBinaryCodec.encodeNonNull(recoveredEntry1));
expect(entry2.contents()).andReturn(ThriftBinaryCodec.encodeNonNull(recoveredEntry2));
expect(stream.readAll()).andReturn(Iterators.<Entry>forArray(entry1, entry2));
final Capture<MutateWork<Void, RuntimeException>> recoveryWork = createCapture();
expect(storageUtil.storage.write(capture(recoveryWork))).andAnswer(
new IAnswer<Void>() {
@Override
public Void answer() {
recoveryWork.getValue().apply(storageUtil.mutableStoreProvider);
return null;
}
});
storageUtil.schedulerStore.saveFrameworkId(frameworkId1);
storageUtil.schedulerStore.saveFrameworkId(frameworkId2);
final Capture<MutateWork<Void, RuntimeException>> initializationWork = createCapture();
expect(storageUtil.storage.write(capture(initializationWork))).andAnswer(
new IAnswer<Void>() {
@Override
public Void answer() {
initializationWork.getValue().apply(storageUtil.mutableStoreProvider);
return null;
}
});
// We should perform a snapshot when the snapshot thread runs.
Capture<Runnable> snapshotAction = createCapture();
schedulingService.doEvery(eq(SNAPSHOT_INTERVAL), capture(snapshotAction));
Snapshot snapshotContents = new Snapshot()
.setTimestamp(NOW)
.setTasks(ImmutableSet.of(
new ScheduledTask()
.setStatus(ScheduleStatus.RUNNING)
.setAssignedTask(new AssignedTask().setTaskId("task_id"))));
expect(snapshotStore.createSnapshot()).andReturn(snapshotContents);
streamMatcher.expectSnapshot(snapshotContents).andReturn(position);
stream.truncateBefore(position);
final Capture<MutateWork<Void, RuntimeException>> snapshotWork = createCapture();
expect(storageUtil.storage.write(capture(snapshotWork))).andAnswer(
new IAnswer<Void>() {
@Override
public Void answer() {
snapshotWork.getValue().apply(storageUtil.mutableStoreProvider);
return null;
}
}).times(2);
storageUtil.storage.snapshot();
control.replay();
logStorage.prepare();
logStorage.start(initializationLogic);
assertTrue(initialized.get());
assertTrue(snapshotAction.hasCaptured());
// Run the snapshot thread.
snapshotAction.getValue().run();
assertTrue(shutdownStream.hasCaptured());
shutdownStream.getValue().execute();
}
abstract class MutationFixture {
private final AtomicBoolean runCalled = new AtomicBoolean(false);
MutationFixture() {
// Prevent otherwise silent noop tests that forget to call run().
addTearDown(new TearDown() {
@Override
public void tearDown() {
assertTrue(runCalled.get());
}
});
}
void run() throws Exception {
runCalled.set(true);
// Expect basic start operations.
// Open the log stream.
expect(log.open()).andReturn(stream);
shutdownRegistry.addAction(EasyMock.<Command>notNull());
// Replay the log and perform and supplied initializationWork.
// Simulate NOOP initialization work
// Creating a mock and expecting apply(storeProvider) does not work here for whatever
// reason.
MutateWork.NoResult.Quiet initializationLogic = MutateWork.NOOP;
final Capture<MutateWork.NoResult.Quiet> recoverAndInitializeWork = createCapture();
storageUtil.storage.write(capture(recoverAndInitializeWork));
expectLastCall().andAnswer(new IAnswer<Void>() {
@Override
public Void answer() throws Throwable {
recoverAndInitializeWork.getValue().apply(storageUtil.mutableStoreProvider);
return null;
}
});
expect(stream.readAll()).andReturn(Iterators.<Entry>emptyIterator());
final Capture<MutateWork<Void, RuntimeException>> recoveryWork = createCapture();
expect(storageUtil.storage.write(capture(recoveryWork))).andAnswer(
new IAnswer<Void>() {
@Override
public Void answer() {
recoveryWork.getValue().apply(storageUtil.mutableStoreProvider);
return null;
}
});
// Schedule snapshots.
schedulingService.doEvery(eq(SNAPSHOT_INTERVAL), notNull(Runnable.class));
// Setup custom test expectations.
setupExpectations();
control.replay();
// Start the system.
logStorage.prepare();
logStorage.start(initializationLogic);
// Exercise the system.
performMutations();
}
protected abstract void setupExpectations() throws Exception;
protected abstract void performMutations();
}
@Test
public void testSaveFrameworkId() throws Exception {
final String frameworkId = "bob";
new MutationFixture() {
@Override
protected void setupExpectations() throws CodingException {
storageUtil.expectOperations();
storageUtil.schedulerStore.saveFrameworkId(frameworkId);
streamMatcher.expectTransaction(Op.saveFrameworkId(new SaveFrameworkId(frameworkId)))
.andReturn(position);
}
@Override
protected void performMutations() {
logStorage.saveFrameworkId(frameworkId);
}
}.run();
}
@Test
public void testSaveAcceptedJob() throws Exception {
final IJobConfiguration jobConfig =
IJobConfiguration.build(new JobConfiguration().setKey(new JobKey("owner", "env", "jake")));
final String managerId = "CRON";
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
storageUtil.jobStore.saveAcceptedJob(managerId, jobConfig);
streamMatcher.expectTransaction(
Op.saveAcceptedJob(new SaveAcceptedJob(managerId, jobConfig.newBuilder())))
.andReturn(position);
}
@Override
protected void performMutations() {
logStorage.saveAcceptedJob(managerId, jobConfig);
}
}.run();
}
@Test
public void testRemoveJob() throws Exception {
final IJobKey jobKey = JobKeys.from("role", "env", "name");
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
storageUtil.jobStore.removeJob(jobKey);
streamMatcher.expectTransaction(
Op.removeJob(new RemoveJob().setJobKey(jobKey.newBuilder())))
.andReturn(position);
}
@Override
protected void performMutations() {
logStorage.removeJob(jobKey);
}
}.run();
}
@Test
public void testSaveTasks() throws Exception {
final Set<IScheduledTask> tasks = ImmutableSet.of(task("a", ScheduleStatus.INIT));
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
storageUtil.taskStore.saveTasks(tasks);
streamMatcher.expectTransaction(
Op.saveTasks(new SaveTasks(IScheduledTask.toBuildersSet(tasks))))
.andReturn(position);
}
@Override
protected void performMutations() {
logStorage.saveTasks(tasks);
}
}.run();
}
@Test
public void testMutateTasks() throws Exception {
final Query.Builder query = Query.taskScoped("fred");
final Function<IScheduledTask, IScheduledTask> mutation = Functions.identity();
final ImmutableSet<IScheduledTask> mutated =
ImmutableSet.of(task("a", ScheduleStatus.STARTING));
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
expect(storageUtil.taskStore.mutateTasks(query, mutation)).andReturn(mutated);
streamMatcher.expectTransaction(
Op.saveTasks(new SaveTasks(IScheduledTask.toBuildersSet(mutated))))
.andReturn(null);
}
@Override
protected void performMutations() {
assertEquals(mutated, logStorage.mutateTasks(query, mutation));
}
}.run();
}
@Test
public void testUnsafeModifyInPlace() throws Exception {
final String taskId = "wilma";
final String taskId2 = "barney";
final ITaskConfig updatedConfig =
task(taskId, ScheduleStatus.RUNNING).getAssignedTask().getTask();
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
expect(storageUtil.taskStore.unsafeModifyInPlace(taskId2, updatedConfig)).andReturn(false);
expect(storageUtil.taskStore.unsafeModifyInPlace(taskId, updatedConfig)).andReturn(true);
streamMatcher.expectTransaction(
Op.rewriteTask(new RewriteTask(taskId, updatedConfig.newBuilder())))
.andReturn(position);
}
@Override
protected void performMutations() {
logStorage.unsafeModifyInPlace(taskId2, updatedConfig);
logStorage.unsafeModifyInPlace(taskId, updatedConfig);
}
}.run();
}
@Test
public void testNestedTransactions() throws Exception {
final Query.Builder query = Query.taskScoped("fred");
final Function<IScheduledTask, IScheduledTask> mutation = Functions.identity();
final ImmutableSet<IScheduledTask> mutated =
ImmutableSet.of(task("a", ScheduleStatus.STARTING));
final ImmutableSet<String> tasksToRemove = ImmutableSet.of("b");
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
expect(storageUtil.taskStore.mutateTasks(query, mutation)).andReturn(mutated);
storageUtil.taskStore.deleteTasks(tasksToRemove);
streamMatcher.expectTransaction(
Op.saveTasks(new SaveTasks(IScheduledTask.toBuildersSet(mutated))),
Op.removeTasks(new RemoveTasks(tasksToRemove)))
.andReturn(position);
}
@Override
protected void performMutations() {
logStorage.write(new MutateWork.NoResult.Quiet() {
@Override
protected void execute(MutableStoreProvider provider) {
assertEquals(mutated, provider.getUnsafeTaskStore().mutateTasks(query, mutation));
logStorage.write(new MutateWork.NoResult.Quiet() {
@Override
protected void execute(MutableStoreProvider innerProvider) {
innerProvider.getUnsafeTaskStore().deleteTasks(tasksToRemove);
}
});
}
});
}
}.run();
}
@Test
public void testSaveAndMutateTasks() throws Exception {
final Query.Builder query = Query.taskScoped("fred");
final Function<IScheduledTask, IScheduledTask> mutation = Functions.identity();
final Set<IScheduledTask> saved = ImmutableSet.of(task("a", ScheduleStatus.INIT));
final ImmutableSet<IScheduledTask> mutated = ImmutableSet.of(task("a", ScheduleStatus.PENDING));
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
storageUtil.taskStore.saveTasks(saved);
// Nested transaction with result.
expect(storageUtil.taskStore.mutateTasks(query, mutation)).andReturn(mutated);
// Resulting stream operation.
streamMatcher.expectTransaction(Op.saveTasks(
new SaveTasks(IScheduledTask.toBuildersSet(mutated))))
.andReturn(null);
}
@Override
protected void performMutations() {
logStorage.write(new MutateWork.NoResult.Quiet() {
@Override
protected void execute(MutableStoreProvider provider) {
logStorage.saveTasks(saved);
assertEquals(mutated, logStorage.mutateTasks(query, mutation));
}
});
}
}.run();
}
@Test
public void testSaveAndMutateTasksNoCoalesceUniqueIds() throws Exception {
final Query.Builder query = Query.taskScoped("fred");
final Function<IScheduledTask, IScheduledTask> mutation = Functions.identity();
final Set<IScheduledTask> saved = ImmutableSet.of(task("b", ScheduleStatus.INIT));
final ImmutableSet<IScheduledTask> mutated = ImmutableSet.of(task("a", ScheduleStatus.PENDING));
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
storageUtil.taskStore.saveTasks(saved);
// Nested transaction with result.
expect(storageUtil.taskStore.mutateTasks(query, mutation)).andReturn(mutated);
// Resulting stream operation.
streamMatcher.expectTransaction(
Op.saveTasks(new SaveTasks(
ImmutableSet.<ScheduledTask>builder()
.addAll(IScheduledTask.toBuildersList(saved))
.addAll(IScheduledTask.toBuildersList(mutated))
.build())))
.andReturn(position);
}
@Override
protected void performMutations() {
logStorage.write(new MutateWork.NoResult.Quiet() {
@Override
protected void execute(MutableStoreProvider provider) {
logStorage.saveTasks(saved);
assertEquals(mutated, logStorage.mutateTasks(query, mutation));
}
});
}
}.run();
}
@Test
public void testRemoveTasksQuery() throws Exception {
final IScheduledTask task = task("a", ScheduleStatus.FINISHED);
final Set<String> taskIds = Tasks.ids(task);
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
expect(storageUtil.taskStore.fetchTasks(Query.unscoped())).andReturn(ImmutableSet.of(task));
storageUtil.taskStore.deleteTasks(taskIds);
streamMatcher.expectTransaction(Op.removeTasks(new RemoveTasks(taskIds)))
.andReturn(position);
}
@Override
protected void performMutations() {
logStorage.deleteAllTasks();
}
}.run();
}
@Test
public void testRemoveTasksIds() throws Exception {
final Set<String> taskIds = ImmutableSet.of("42");
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
storageUtil.taskStore.deleteTasks(taskIds);
streamMatcher.expectTransaction(Op.removeTasks(new RemoveTasks(taskIds)))
.andReturn(position);
}
@Override
protected void performMutations() {
logStorage.deleteTasks(taskIds);
}
}.run();
}
@Test
public void testSaveQuota() throws Exception {
final String role = "role";
final IQuota quota = IQuota.build(new Quota(1.0, 128L, 1024L));
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
storageUtil.quotaStore.saveQuota(role, quota);
streamMatcher.expectTransaction(Op.saveQuota(new SaveQuota(role, quota.newBuilder())))
.andReturn(position);
}
@Override
protected void performMutations() {
logStorage.saveQuota(role, quota);
}
}.run();
}
@Test
public void testRemoveQuota() throws Exception {
final String role = "role";
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
storageUtil.quotaStore.removeQuota(role);
streamMatcher.expectTransaction(Op.removeQuota(new RemoveQuota(role))).andReturn(position);
}
@Override
protected void performMutations() {
logStorage.removeQuota(role);
}
}.run();
}
@Test
public void testSaveLock() throws Exception {
final ILock lock = ILock.build(new Lock()
.setKey(LockKey.job(JobKeys.from("testRole", "testEnv", "testJob").newBuilder()))
.setToken("testLockId")
.setUser("testUser")
.setTimestampMs(12345L));
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
storageUtil.lockStore.saveLock(lock);
streamMatcher.expectTransaction(Op.saveLock(new SaveLock(lock.newBuilder())))
.andReturn(position);
}
@Override
protected void performMutations() {
logStorage.saveLock(lock);
}
}.run();
}
@Test
public void testRemoveLock() throws Exception {
final ILockKey lockKey =
ILockKey.build(LockKey.job(JobKeys.from("testRole", "testEnv", "testJob").newBuilder()));
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
storageUtil.lockStore.removeLock(lockKey);
streamMatcher.expectTransaction(Op.removeLock(new RemoveLock(lockKey.newBuilder())))
.andReturn(position);
}
@Override
protected void performMutations() {
logStorage.removeLock(lockKey);
}
}.run();
}
@Test
public void testSaveHostAttributes() throws Exception {
final String host = "hostname";
final Set<Attribute> attributes =
ImmutableSet.of(new Attribute().setName("attr").setValues(ImmutableSet.of("value")));
final Optional<HostAttributes> hostAttributes = Optional.of(new HostAttributes()
.setHost(host)
.setAttributes(attributes));
new MutationFixture() {
@Override
protected void setupExpectations() throws Exception {
storageUtil.expectOperations();
expect(storageUtil.attributeStore.getHostAttributes(host))
.andReturn(Optional.<HostAttributes>absent());
// Each logStorage save invokes get, save, get to the underlying attribute store.
storageUtil.attributeStore.saveHostAttributes(hostAttributes.get());
expect(storageUtil.attributeStore.getHostAttributes(host)).andReturn(hostAttributes);
streamMatcher.expectTransaction(
Op.saveHostAttributes(new SaveHostAttributes(hostAttributes.get())))
.andReturn(position);
expect(storageUtil.attributeStore.getHostAttributes(host)).andReturn(hostAttributes);
expect(storageUtil.attributeStore.getHostAttributes(host)).andReturn(hostAttributes);
storageUtil.attributeStore.saveHostAttributes(hostAttributes.get());
expect(storageUtil.attributeStore.getHostAttributes(host)).andReturn(hostAttributes);
expect(storageUtil.attributeStore.getHostAttributes(host)).andReturn(hostAttributes);
}
@Override
protected void performMutations() {
logStorage.saveHostAttributes(hostAttributes.get());
assertEquals(hostAttributes, logStorage.getHostAttributes(host));
logStorage.saveHostAttributes(hostAttributes.get());
assertEquals(hostAttributes, logStorage.getHostAttributes(host));
}
}.run();
}
private LogEntry createTransaction(Op... ops) {
return LogEntry.transaction(
new Transaction(ImmutableList.copyOf(ops), storageConstants.CURRENT_SCHEMA_VERSION));
}
private static IScheduledTask task(String id, ScheduleStatus status) {
return IScheduledTask.build(new ScheduledTask()
.setStatus(status)
.setAssignedTask(new AssignedTask()
.setTaskId(id)
.setTask(new TaskConfig())));
}
}
|
//给你两个整数 memory1 和 memory2 分别表示两个内存条剩余可用内存的位数。现在有一个程序每秒递增的速度消耗着内存。
//
// 在第 i 秒(秒数从 1 开始),有 i 位内存被分配到 剩余内存较多 的内存条(如果两者一样多,则分配到第一个内存条)。如果两者剩余内存都不足 i 位,
//那么程序将 意外退出 。
//
// 请你返回一个数组,包含 [crashTime, memory1crash, memory2crash] ,其中 crashTime是程序意外退出的时间(单
//位为秒), memory1crash 和 memory2crash 分别是两个内存条最后剩余内存的位数。
//
//
//
// 示例 1:
//
// 输入:memory1 = 2, memory2 = 2
//输出:[3,1,0]
//解释:内存分配如下:
//- 第 1 秒,内存条 1 被占用 1 位内存。内存条 1 现在有 1 位剩余可用内存。
//- 第 2 秒,内存条 2 被占用 2 位内存。内存条 2 现在有 0 位剩余可用内存。
//- 第 3 秒,程序意外退出,两个内存条分别有 1 位和 0 位剩余可用内存。
//
//
// 示例 2:
//
// 输入:memory1 = 8, memory2 = 11
//输出:[6,0,4]
//解释:内存分配如下:
//- 第 1 秒,内存条 2 被占用 1 位内存,内存条 2 现在有 10 位剩余可用内存。
//- 第 2 秒,内存条 2 被占用 2 位内存,内存条 2 现在有 8 位剩余可用内存。
//- 第 3 秒,内存条 1 被占用 3 位内存,内存条 1 现在有 5 位剩余可用内存。
//- 第 4 秒,内存条 2 被占用 4 位内存,内存条 2 现在有 4 位剩余可用内存。
//- 第 5 秒,内存条 1 被占用 5 位内存,内存条 1 现在有 0 位剩余可用内存。
//- 第 6 秒,程序意外退出,两个内存条分别有 0 位和 4 位剩余可用内存。
//
//
//
//
// 提示:
//
//
// 0 <= memory1, memory2 <= 231 - 1
//
// Related Topics 模拟
// 👍 4 👎 0
package com.tomster.leetcode.editor.cn;
/**
* @author: tomster
* @data: 2021-10-30 11:48:11
*/
public class IncrementalMemoryLeak {
public static void main(String[] args) {
Solution solution = new IncrementalMemoryLeak().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] memLeak(int memory1, int memory2) {
int time = 1;
long sum = (long) memory1 + memory2;
while (time <= Math.max(sum, 1)) {
int max = Math.max(memory1, memory2);
if (max < time) {
return new int[]{time, memory1, memory2};
}
if (memory1 >= memory2) {
memory1 -= time;
} else {
memory2 -= time;
}
time++;
}
return new int[]{};
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
|
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.cvm.v20170312.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class ModifyImageAttributeResponse extends AbstractModel{
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
@SerializedName("RequestId")
@Expose
private String RequestId;
/**
* 获取唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
public String getRequestId() {
return this.RequestId;
}
/**
* 设置唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
public void setRequestId(String RequestId) {
this.RequestId = RequestId;
}
/**
* 内部实现,用户禁止调用
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
|
/*
* Copyright© 2000 - 2021 SuperMap Software Co.Ltd. All rights reserved.
* This program are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.
*/
package com.supermap.gaf.authority.service;
import com.supermap.gaf.authority.commontype.AuthP3UserMapping;
import com.supermap.gaf.authority.vo.AuthP3UserMappingSelectVo;
import java.util.List;
import java.util.Map;
/**
* @author yangdong
* @date:2021/3/25
* 第三方用户映射表服务类
*/
public interface AuthP3UserMappingQueryService {
/**
* userId查询第三方用户映射表
*
* @return
*/
AuthP3UserMapping getByUserId(String p3ComponentId, String userId);
}
|
package br.com.zup.mercadolivre.exceptions;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import java.time.LocalDateTime;
import java.util.List;
public class ErrorObject {
private LocalDateTime currentTime;
private List<FieldError> message;
private List<ObjectError> messageList;
public ErrorObject(LocalDateTime currentTime, List<FieldError> message, List<ObjectError> messageList) {
this.currentTime = currentTime;
this.message = message;
this.messageList = messageList;
}
public LocalDateTime getCurrentTime() {
return currentTime;
}
public List<FieldError> getMessage() {
return message;
}
public List<ObjectError> getMessageList() {
return messageList;
}
}
|
/*
* Copyright 2011-2016 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.storagegateway.model.transform;
import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.storagegateway.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.protocol.json.*;
/**
* DescribeWorkingStorageRequest Marshaller
*/
public class DescribeWorkingStorageRequestMarshaller implements Marshaller<Request<DescribeWorkingStorageRequest>, DescribeWorkingStorageRequest> {
private final SdkJsonProtocolFactory protocolFactory;
public DescribeWorkingStorageRequestMarshaller(SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DescribeWorkingStorageRequest> marshall(DescribeWorkingStorageRequest describeWorkingStorageRequest) {
if (describeWorkingStorageRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<DescribeWorkingStorageRequest> request = new DefaultRequest<DescribeWorkingStorageRequest>(describeWorkingStorageRequest, "AWSStorageGateway");
request.addHeader("X-Amz-Target", "StorageGateway_20130630.DescribeWorkingStorage");
request.setHttpMethod(HttpMethodName.POST);
request.setResourcePath("");
try {
final StructuredJsonGenerator jsonGenerator = protocolFactory.createGenerator();
jsonGenerator.writeStartObject();
if (describeWorkingStorageRequest.getGatewayARN() != null) {
jsonGenerator.writeFieldName("GatewayARN").writeValue(describeWorkingStorageRequest.getGatewayARN());
}
jsonGenerator.writeEndObject();
byte[] content = jsonGenerator.getBytes();
request.setContent(new ByteArrayInputStream(content));
request.addHeader("Content-Length", Integer.toString(content.length));
request.addHeader("Content-Type", protocolFactory.getContentType());
} catch (Throwable t) {
throw new SdkClientException("Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}
|
/*
* Copyright 2013 the original author or 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 org.springframework.amqp;
/**
* Runtime wrapper for an authentication exception.
*
* @author Gary Russell
* @since 1.2.1
*
*/
@SuppressWarnings("serial")
public class AmqpAuthenticationException extends AmqpException {
public AmqpAuthenticationException(Throwable cause) {
super(cause);
}
}
|
package org.codehaus.mojo.mrm.plugin;
/*
* Copyright 2011 Stephen Connolly
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.commons.lang.StringUtils;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import java.util.Map;
/**
* This goal is used in-situ on a Maven project to allow integration tests based on the Maven Invoker to use a custom
* <code>settings.xml</code> and still work behind a proxy.
*
* @author Stephen Connolly
*
* Starts a mock repository manager as part of a maven build for use by integration tests.
*/
@Mojo( name = "start", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, requiresProject = false, threadSafe = true )
public class StartMojo
extends AbstractStartMojo
{
/**
* The property to set the repository url to.
*/
@Parameter( property = "mrm.propertyName", defaultValue = "mrm.repository.url" )
private String propertyName;
/**
* {@inheritDoc}
*/
@SuppressWarnings( { "rawtypes", "unchecked" } )
public void doExecute()
throws MojoExecutionException, MojoFailureException
{
FileSystemServer mrm = createFileSystemServer( createArtifactStore() );
getLog().info( "Starting Mock Repository Manager" );
mrm.ensureStarted();
String url = mrm.getUrl();
getLog().info( "Mock Repository Manager " + url + " is started." );
if ( !StringUtils.isEmpty( propertyName ) )
{
getLog().info( "Setting property '" + propertyName + "' to '" + url + "'." );
project.getProperties().setProperty( propertyName, url );
}
Map pluginContext = session.getPluginContext( pluginDescriptor, project );
pluginContext.put( getFileSystemServerKey( getMojoExecution() ), mrm );
}
protected static String getFileSystemServerKey( MojoExecution mojoExecution )
{
return FileSystemServer.class.getName() + "@" + mojoExecution.getExecutionId();
}
}
|
/**
* Copyright (c) 2010-2018 Mark Allen, Norbert Bartels.
*
* 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 com.restfb.types;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import com.restfb.AbstractJsonMapperTests;
import com.restfb.json.JsonObject;
import org.junit.Test;
public class JsonObjectTest extends AbstractJsonMapperTests {
@Test
public void issue327Test() {
JsonObject json = createJsonMapper().toJavaObject(jsonFromClasspath("v2_5/issue-327"), JsonObject.class);
assertNotNull(json);
JsonObject picData = json.get("data").asObject();
assertNotNull(picData);
assertFalse(picData.get("is_silhouette").asBoolean());
assertNotNull(picData.get("url").asString());
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.messaging.eventgrid.samples;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.credential.AzureSasCredential;
import com.azure.core.models.CloudEventDataFormat;
import com.azure.core.util.BinaryData;
import com.azure.core.util.serializer.TypeReference;
import com.azure.core.models.CloudEvent;
import com.azure.messaging.eventgrid.EventGridEvent;
import com.azure.messaging.eventgrid.EventGridPublisherAsyncClient;
import com.azure.messaging.eventgrid.EventGridPublisherClient;
import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder;
import com.azure.messaging.eventgrid.SystemEventNames;
import com.azure.messaging.eventgrid.samples.models.User;
import com.azure.messaging.eventgrid.systemevents.AppConfigurationKeyValueDeletedEventData;
import com.azure.messaging.eventgrid.systemevents.AppConfigurationKeyValueModifiedEventData;
import com.azure.messaging.eventgrid.systemevents.StorageBlobCreatedEventData;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS
* ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING
* LINE NUMBERS OF EXISTING CODE SAMPLES.
* <p>
* Code samples for the README.md
*/
public class ReadmeSamples {
private final EventGridPublisherClient<EventGridEvent> eventGridEventClient = new EventGridPublisherClientBuilder()
.buildEventGridEventPublisherClient();
private final EventGridPublisherClient<CloudEvent> cloudEventClient = new EventGridPublisherClientBuilder()
.buildCloudEventPublisherClient();
private final EventGridPublisherClient<BinaryData> customEventClient = new EventGridPublisherClientBuilder()
.buildCustomEventPublisherClient();
private final String jsonData = "Json encoded event";
public void createSharedAccessSignature() {
OffsetDateTime expiration = OffsetDateTime.now().plusMinutes(20);
String sasToken = EventGridPublisherClient
.generateSas("<your event grid endpoint>", new AzureKeyCredential("<key for the endpoint>"), expiration);
}
public void createCloudEventPublisherClient() {
// For CloudEvent
EventGridPublisherClient<CloudEvent> cloudEventClient = new EventGridPublisherClientBuilder()
.endpoint("<endpont of your event grid topic/domain that accepts CloudEvent schema>")
.credential(new AzureKeyCredential("<key for the endpoint>"))
.buildCloudEventPublisherClient();
}
public void createEventGridEventPublisherClient() {
// For EventGridEvent
EventGridPublisherClient<EventGridEvent> eventGridEventClient = new EventGridPublisherClientBuilder()
.endpoint("<endpont of your event grid topic/domain that accepts EventGridEvent schema>")
.credential(new AzureKeyCredential("<key for the endpoint>"))
.buildEventGridEventPublisherClient();
}
public void createCustomEventPublisherClient() {
// For custom event
EventGridPublisherClient<BinaryData> customEventClient = new EventGridPublisherClientBuilder()
.endpoint("<endpont of your event grid topic/domain that accepts custom event schema>")
.credential(new AzureKeyCredential("<key for the endpoint>"))
.buildCustomEventPublisherClient();
}
public void createCloudEventPublisherAsyncClient() {
// For CloudEvent
EventGridPublisherAsyncClient<CloudEvent> cloudEventAsyncClient = new EventGridPublisherClientBuilder()
.endpoint("<endpont of your event grid topic/domain that accepts CloudEvent schema>")
.credential(new AzureKeyCredential("<key for the endpoint>"))
.buildCloudEventPublisherAsyncClient();
}
public void createEventGridEventPublisherAsyncClient() {
// For EventGridEvent
EventGridPublisherAsyncClient<EventGridEvent> eventGridEventAsyncClient = new EventGridPublisherClientBuilder()
.endpoint("<endpont of your event grid topic/domain that accepts EventGridEvent schema>")
.credential(new AzureKeyCredential("<key for the endpoint>"))
.buildEventGridEventPublisherAsyncClient();
}
public void createCustomEventPublisherAsyncClient() {
// For custom event
EventGridPublisherClient<BinaryData> customEventAsyncClient = new EventGridPublisherClientBuilder()
.endpoint("<endpont of your event grid topic/domain that accepts custom event schema>")
.credential(new AzureKeyCredential("<key for the endpoint>"))
.buildCustomEventPublisherClient();
}
public void createPublisherClientWithSas() {
EventGridPublisherClient<CloudEvent> eventGridEventClient = new EventGridPublisherClientBuilder()
.endpoint("<endpont of your event grid topic/domain that accepts CloudEvent schema>")
.credential(new AzureSasCredential("<sas token that can access the endpoint>"))
.buildCloudEventPublisherClient();
}
public void createPublisherClientWithSasAsync() {
EventGridPublisherAsyncClient<CloudEvent> cloudEventAsyncClient = new EventGridPublisherClientBuilder()
.endpoint("<endpont of your event grid topic/domain that accepts CloudEvent schema>")
.credential(new AzureSasCredential("<sas token that can access the endpoint>"))
.buildCloudEventPublisherAsyncClient();
}
public void sendCloudEventsToTopic() {
// Make sure that the event grid topic or domain you're sending to accepts CloudEvent schema.
List<CloudEvent> events = new ArrayList<>();
User user = new User("John", "James");
events.add(new CloudEvent("https://source.example.com", "Com.Example.ExampleEventType",
BinaryData.fromObject(user), CloudEventDataFormat.JSON, "application/json"));
cloudEventClient.sendEvents(events);
}
public void sendEventGridEventsToTopic() {
// Make sure that the event grid topic or domain you're sending to accepts EventGridEvent schema.
List<EventGridEvent> events = new ArrayList<>();
User user = new User("John", "James");
events.add(new EventGridEvent("exampleSubject", "Com.Example.ExampleEventType", BinaryData.fromObject(user), "0.1"));
eventGridEventClient.sendEvents(events);
}
public void sendEventGridEventsToDomain() {
List<EventGridEvent> events = new ArrayList<>();
User user = new User("John", "James");
events.add(new EventGridEvent("com/example", "Com.Example.ExampleEventType", BinaryData.fromObject(user), "1")
.setTopic("yourtopic"));
eventGridEventClient.sendEvents(events);
}
public void sendCustomEventsToTopic() {
// Make sure that the event grid topic or domain you're sending to accepts the custom event schema.
List<BinaryData> events = new ArrayList<>();
events.add(BinaryData.fromObject(new HashMap<String, String>() {
{
put("id", UUID.randomUUID().toString());
put("time", OffsetDateTime.now().toString());
put("subject", "Test");
put("foo", "bar");
put("type", "Microsoft.MockPublisher.TestEvent");
put("data", "example data");
put("dataVersion", "0.1");
}
}));
customEventClient.sendEvents(events);
}
public void deserializeEvents() {
// Deserialize an EventGridEvent
String eventGridEventJsonData = "<your EventGridEvent json String>";
List<EventGridEvent> eventGridEvents = EventGridEvent.fromString(eventGridEventJsonData);
// Deserialize a CloudEvent
String cloudEventJsonData = "<your CloudEvent json String>";
List<CloudEvent> cloudEvents = CloudEvent.fromString(cloudEventJsonData);
}
public void deserializeEventData(EventGridEvent eventGridEvent) {
BinaryData eventData = eventGridEvent.getData();
//Deserialize data to a model class
User dataInModelClass = eventData.toObject(User.class);
//Deserialize data to a Map
Map<String, Object> dataMap = eventData.toObject(new TypeReference<Map<String, Object>>() {
});
//Deserialize Json String to a String
String dataString = eventData.toObject(String.class);
//Deserialize String data to a String
String dataInJsonString = eventData.toString();
//Deserialize data to byte array (byte[])
byte[] dataInBytes = eventData.toBytes();
}
public void systemEventDataSampleCode() {
String eventGridEventJsonData = "<Your event grid event Json data>";
List<EventGridEvent> events = EventGridEvent.fromString(eventGridEventJsonData);
EventGridEvent event = events.get(0);
// Look up the System Event data class
Class<?> eventDataClazz = SystemEventNames.getSystemEventMappings().get(event.getEventType());
// Deserialize the event data to an instance of a specific System Event data class type
BinaryData data = event.getData();
if (data != null) {
StorageBlobCreatedEventData blobCreatedData = data.toObject(StorageBlobCreatedEventData.class);
System.out.println(blobCreatedData.getUrl());
}
}
public void systemEventDifferentEventData() {
List<EventGridEvent> eventGridEvents = EventGridEvent.fromString("<Your EventGridEvent Json String>");
for (EventGridEvent eventGridEvent : eventGridEvents) {
BinaryData binaryData = eventGridEvent.getData();
switch (eventGridEvent.getEventType()) {
case SystemEventNames.APP_CONFIGURATION_KEY_VALUE_DELETED:
AppConfigurationKeyValueDeletedEventData keyValueDeletedEventData =
binaryData.toObject(TypeReference.createInstance(AppConfigurationKeyValueDeletedEventData.class));
System.out.println("Processing the AppConfigurationKeyValueDeletedEventData...");
System.out.printf("The key is: %s%n", keyValueDeletedEventData.getKey());
break;
case SystemEventNames.APP_CONFIGURATION_KEY_VALUE_MODIFIED:
AppConfigurationKeyValueModifiedEventData keyValueModifiedEventData =
binaryData.toObject(TypeReference.createInstance(AppConfigurationKeyValueModifiedEventData.class));
System.out.println("Processing the AppConfigurationKeyValueModifiedEventData...");
System.out.printf("The key is: %s%n", keyValueModifiedEventData.getKey());
break;
default:
System.out.printf("%s isn't an AppConfiguration event data%n", eventGridEvent.getEventType());
break;
}
}
}
}
|
package com.example.mtking.activity;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import com.example.mtking.R;
public class WelcomeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(WelcomeActivity.this, DangNhapActivity.class);
startActivity( intent);
finish();
}
}, 900);
}
}
|
package com.teambition.talk.ui.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.squareup.otto.Subscribe;
import com.talk.dialog.TalkDialog;
import com.teambition.talk.BizLogic;
import com.teambition.talk.BusProvider;
import com.teambition.talk.R;
import com.teambition.talk.adapter.TeamActivitiesAdapter;
import com.teambition.talk.entity.TeamActivity;
import com.teambition.talk.event.NewTeamActivityEvent;
import com.teambition.talk.event.RemoveTeamActivityEvent;
import com.teambition.talk.event.UpdateTeamActivityEvent;
import com.teambition.talk.imageloader.RecyclerViewPauseOnScrollListener;
import com.teambition.talk.presenter.TeamActivitiesPresenter;
import com.teambition.talk.ui.activity.ChatActivity;
import com.teambition.talk.ui.widget.WrapContentLinearLayoutManager;
import com.teambition.talk.util.TransactionUtil;
import com.teambition.talk.view.TeamActivitiesView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import org.parceler.Parcels;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by nlmartian on 3/8/16.
*/
public class TeamActivityFragment extends BaseFragment implements TeamActivitiesView,
TeamActivitiesAdapter.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
@InjectView(R.id.swipe_refresh_layout)
SwipeRefreshLayout swipeRefreshLayout;
@InjectView(R.id.listView)
RecyclerView listView;
@InjectView(R.id.layout_placeholder)
View placeholder;
@InjectView(R.id.progress_bar)
View loadingView;
private TeamActivitiesPresenter presenter;
private LinearLayoutManager layoutManager;
private TeamActivitiesAdapter adapter;
private String maxId;
private boolean canLoadMore;
public static TeamActivityFragment newInstance() {
return new TeamActivityFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BusProvider.getInstance().register(this);
}
@Override
public void onDetach() {
BusProvider.getInstance().unregister(this);
super.onDetach();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_team_activities, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.inject(this, view);
initView();
presenter = new TeamActivitiesPresenter(this);
}
@Override
protected void lazyLoad() {
if (maxId == null) {
swipeRefreshLayout.setRefreshing(true);
presenter.getTeamActivities(BizLogic.getTeamId(), null);
}
}
private void initView() {
layoutManager = new WrapContentLinearLayoutManager(getActivity());
adapter = new TeamActivitiesAdapter(this);
listView.setLayoutManager(layoutManager);
listView.setAdapter(adapter);
listView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity())
.marginResId(R.dimen.contacts_text_left_margin, R.dimen.zero_dp)
.build());
listView.addOnScrollListener(new RecyclerViewPauseOnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (canLoadMore && BizLogic.isNetworkConnected()
&& layoutManager.findLastVisibleItemPosition() > adapter.getItemCount() - 5) {
canLoadMore = false;
adapter.setIsLoading(true);
presenter.getTeamActivities(BizLogic.getTeamId(), maxId);
}
}
});
swipeRefreshLayout.setOnRefreshListener(this);
}
@Override
public void showActivities(List<TeamActivity> activities, boolean refresh) {
swipeRefreshLayout.setRefreshing(false);
loadingView.setVisibility(View.GONE);
if (activities.isEmpty()) {
placeholder.setVisibility(View.VISIBLE);
} else {
listView.setVisibility(View.VISIBLE);
if (refresh) {
adapter.initData(activities);
} else {
adapter.addToEnd(activities);
}
maxId = activities.get(activities.size() - 1).get_id();
canLoadMore = activities.size() >= 30;
adapter.setIsLoading(false);
}
}
@Override
public void showActivitiesFailed() {
swipeRefreshLayout.setRefreshing(false);
adapter.setIsLoading(false);
loadingView.setVisibility(View.GONE);
placeholder.setVisibility(View.VISIBLE);
}
@Override
public void onRefresh() {
maxId = null;
presenter.getTeamActivities(BizLogic.getTeamId(), null);
}
@Override
public void removeActivity(String id) {
adapter.removeActivity(id);
}
@Override
public void onClick(TeamActivity activity) {
Bundle bundle = new Bundle();
if ("room".equals(activity.getType())) {
if (activity.getRoom() != null) {
bundle.putParcelable(ChatActivity.EXTRA_ROOM, Parcels.wrap(activity.getRoom()));
TransactionUtil.goTo(this, ChatActivity.class, bundle);
}
} else if ("story".equals(activity.getType())) {
if (activity.getStory() != null) {
bundle.putParcelable(ChatActivity.EXTRA_STORY, Parcels.wrap(activity.getStory()));
TransactionUtil.goTo(this, ChatActivity.class, bundle);
}
}
}
@Override
public void onLongClick(final TeamActivity activity) {
if (BizLogic.isAdmin() || BizLogic.isMe(activity.get_creatorId())) {
new TalkDialog.Builder(getActivity())
.items(new CharSequence[]{getString(R.string.delete)})
.itemsCallback(new TalkDialog.ListCallback() {
@Override
public void onSelection(TalkDialog dialog, View itemView, int which, CharSequence text) {
presenter.removeTeamActivity(activity.get_id());
}
}).show();
}
}
@Subscribe
public void onNewActivityEvent(NewTeamActivityEvent event) {
adapter.addToTop(event.activity);
}
@Subscribe
public void onUpdateActivityEvent(UpdateTeamActivityEvent event) {
adapter.updateItem(event.activity);
}
@Subscribe
public void onRemoveActivityEvent(RemoveTeamActivityEvent event) {
if (event.activity != null) {
adapter.removeActivity(event.activity.get_id());
}
}
}
|
/**
* Copyright 2009-2017 the original author or 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 org.apache.ibatis.jdbc;
/**
* @author Clinton Begin
*/
public class RuntimeSqlException extends RuntimeException {
private static final long serialVersionUID = 5224696788505678598L;
public RuntimeSqlException() {
super();
}
public RuntimeSqlException(String message) {
super(message);
}
public RuntimeSqlException(String message, Throwable cause) {
super(message, cause);
}
public RuntimeSqlException(Throwable cause) {
super(cause);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.