answer stringlengths 17 10.2M |
|---|
package com.stanfy.views;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class Gallery extends android.widget.Gallery implements Runnable {
/** Fling mode. */
private boolean flingMode = false;
/** Last selected position. */
private int lastSelectedPosition = -1;
public Gallery(final Context context) {
this(context, null);
}
public Gallery(final Context context, final AttributeSet attrs) {
this(context, attrs, android.R.attr.galleryStyle);
}
public Gallery(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onTouchEvent(final MotionEvent event) {
flingMode = false;
final boolean consumed = super.onTouchEvent(event);
final int action = event.getAction();
final int currentPosition = getSelectedItemPosition();
Log.d(VIEW_LOG_TAG, "lastSelectedPosition=" + lastSelectedPosition + ", currentPosiotin=" + currentPosition);
if (action == MotionEvent.ACTION_UP && !flingMode && lastSelectedPosition != currentPosition) {
// lifted finger action
lastSelectedPosition = currentPosition;
Log.d(VIEW_LOG_TAG, "lastSelectedPosition=" + lastSelectedPosition);
final long safeDelay = 50;
postDelayed(this, safeDelay);
}
return consumed;
}
@Override
public boolean onFling(final MotionEvent e1, final MotionEvent e2, final float velocityX, final float velocityY) {
flingMode = true;
return super.onFling(e1, e2, velocityX, velocityY);
}
@Override
public boolean performItemClick(final View view, final int position, final long id) {
lastSelectedPosition = -1;
return super.performItemClick(view, position, id);
}
@Override
public final void run() {
final int current = getSelectedItemPosition();
if (lastSelectedPosition == current) {
performItemClick(null, current, getSelectedItemId());
}
}
} |
package com.github.vbauer.yta.model;
import com.github.vbauer.yta.model.basic.HasCode;
import org.immutables.value.Value.Immutable;
import org.immutables.value.Value.Parameter;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Model which represents language.
*
* @author Vladislav Bauer
*/
@SuppressWarnings("serial")
@Immutable
public abstract class Language implements HasCode<String> {
public static final Language AZ = of("az", "Azerbaijan");
public static final Language SQ = of("sq", "Albanian");
public static final Language AM = of("am", "Amharic");
public static final Language EN = of("en", "English");
public static final Language AR = of("ar", "Arabic");
public static final Language HY = of("hy", "Armenian");
public static final Language AF = of("af", "Afrikaans");
public static final Language EU = of("eu", "Basque");
public static final Language BA = of("ba", "Bashkir");
public static final Language BE = of("be", "Belarusian");
public static final Language BN = of("bn", "Bengali");
public static final Language MY = of("my", "Burmese");
public static final Language BG = of("bg", "Bulgarian");
public static final Language BS = of("bs", "Bosnian");
public static final Language CV = of("cv", "Chuvash");
public static final Language CY = of("cy", "Welsh");
public static final Language HU = of("hu", "Hungarian");
public static final Language VI = of("vi", "Vietnamese");
public static final Language HT = of("ht", "Haitian (Creole)");
public static final Language GL = of("gl", "Galician");
public static final Language NL = of("nl", "Dutch");
public static final Language MRJ = of("mrj", "Hill Mari");
public static final Language EL = of("el", "Greek");
public static final Language KA = of("ka", "Georgian");
public static final Language GU = of("gu", "Gujarati");
public static final Language DA = of("da", "Danish");
public static final Language HE = of("he", "Hebrew");
public static final Language YI = of("yi", "Yiddish");
public static final Language ID = of("id", "Indonesian");
public static final Language GA = of("ga", "Irish");
public static final Language IT = of("it", "Italian");
public static final Language IS = of("is", "Icelandic");
public static final Language ES = of("es", "Spanish");
public static final Language KK = of("kk", "Kazakh");
public static final Language KN = of("kn", "Kannada");
public static final Language CA = of("ca", "Catalan");
public static final Language KY = of("ky", "Kyrgyz");
public static final Language ZH = of("zh", "Chinese");
public static final Language KO = of("ko", "Korean");
public static final Language XH = of("xh", "Xhosa");
public static final Language KM = of("km", "Khmer");
public static final Language LO = of("lo", "Laotian");
public static final Language LA = of("la", "Latin");
public static final Language LV = of("lv", "Latvian");
public static final Language LT = of("lt", "Lithuanian");
public static final Language LB = of("lb", "Luxembourgish");
public static final Language MG = of("mg", "Malagasy");
public static final Language MS = of("ms", "Malay");
public static final Language ML = of("ml", "Malayalam");
public static final Language MT = of("mt", "Maltese");
public static final Language MK = of("mk", "Macedonian");
public static final Language MI = of("mi", "Maori");
public static final Language MR = of("mr", "Marathi");
public static final Language MHR = of("mhr", "Mari");
public static final Language MN = of("mn", "Mongolian");
public static final Language DE = of("de", "German");
public static final Language NE = of("ne", "Nepali");
public static final Language NO = of("no", "Norwegian");
public static final Language PA = of("pa", "Punjabi");
public static final Language PAP = of("pap", "Papiamento");
public static final Language FA = of("fa", "Persian");
public static final Language PL = of("pl", "Polish");
public static final Language PT = of("pt", "Portuguese");
public static final Language RO = of("ro", "Romanian");
public static final Language RU = of("ru", "Russian");
public static final Language CEB = of("ceb", "Cebuano");
public static final Language SR = of("sr", "Serbian");
public static final Language SI = of("si", "Sinhala");
public static final Language SK = of("sk", "Slovakian");
public static final Language SL = of("sl", "Slovenian");
public static final Language SW = of("sw", "Swahili");
public static final Language SU = of("su", "Sundanese");
public static final Language TG = of("tg", "Tajik");
public static final Language TH = of("th", "Thai");
public static final Language TL = of("tl", "Tagalog");
public static final Language TA = of("ta", "Tamil");
public static final Language TT = of("tt", "Tatar");
public static final Language TE = of("te", "Telugu");
public static final Language TR = of("tr", "Turkish");
public static final Language UDM = of("udm", "Udmurt");
public static final Language UZ = of("uz", "Uzbek");
public static final Language UK = of("uk", "Ukrainian");
public static final Language UR = of("ur", "Urdu");
public static final Language FI = of("fi", "Finnish");
public static final Language FR = of("fr", "French");
public static final Language HI = of("hi", "Hindi");
public static final Language HR = of("hr", "Croatian");
public static final Language CS = of("cs", "Czech");
public static final Language SV = of("sv", "Swedish");
public static final Language GD = of("gd", "Scottish");
public static final Language ET = of("et", "Estonian");
public static final Language EO = of("eo", "Esperanto");
public static final Language JV = of("jv", "Javanese");
public static final Language JA = of("ja", "Japanese");
public static final Language EMJ = of("emj", "Emoji");
public static final Map<String, Language> ALL = buildLanguageMap();
/**
* {@inheritDoc}
*/
@Nonnull
@Override
@Parameter(order = 0)
public abstract String code();
/**
* Get language name.
*
* @return language name
*/
@Nonnull
@Parameter(order = 1)
public abstract Optional<String> name();
/**
* A factory method to create language object using code and name.
*
* @param code code value
* @param name language name
* @return language
*/
@Nonnull
public static Language of(@Nonnull final String code, @Nullable final String name) {
return ImmutableLanguage.of(code.toLowerCase(), Optional.ofNullable(name));
}
/**
* Create language object using only code value.
*
* @param code code value
* @return language
*/
@Nonnull
public static Language of(@Nonnull final String code) {
final Language language = ALL.get(code);
return language != null ? language : of(code, null);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return Objects.hashCode(code());
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object another) {
return this == another
|| another instanceof Language && Objects.equals(((Language) another).code(), code());
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return code();
}
private static Map<String, Language> buildLanguageMap() {
final Collection<Language> languages = createLanguageCollection();
return languages.stream().collect(Collectors.toMap(Language::code, Function.identity()));
}
private static Collection<Language> createLanguageCollection() {
return Collections.unmodifiableSet(
new HashSet<>(
Arrays.asList(
AZ, SQ, AM, EN, AR, HY, AF, EU, BA, BE,
BN, MY, BG, BS, CV, CY, HU, VI, HT, GL, NL,
MRJ, EL, KA, GU, DA, HE, YI, ID, GA, IT,
IS, ES, KK, KN, CA, KY, ZH, KO, XH, KM,
LO, LA, LV, LT, LB, MG, MS, ML, MT, MK,
MI, MR, MHR, MN, DE, NE, NO, PA, PAP, FA,
PL, PT, RO, RU, CEB, SR, SI, SK, SL, SW,
SU, TG, TH, TL, TA, TT, TE, TR, UDM, UZ,
UK, UR, FI, FR, HI, HR, CS, SV, GD, ET,
EO, JV, JA, EMJ
)
)
);
}
} |
package com.google.sps.data;
import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
/** SmallCityService object representing all components of the webapp **/
public class SmallCityService {
private User user;
private BusinessesService businessesService;
private List<Listing> businesses = new LinkedList<>();
private PreparedQuery databaseResults;
/** Create a new Small City Service instance
* @param mapLocation geolocation of user
* @return List of small local businesses
**/
public SmallCityService(MapLocation mapLocation) {
this.user = new User(mapLocation);
businessesService = new BusinessesService(businesses);
findAllBusinesses();
parseThroughTheListOfBusinesses();
}
public void findAllBusinesses() {
// TODO: Get businesses from Place API given user location
businesses = new LinkedList<Listing>();
businesses.add(
new Listing("LA Fitness",
new MapLocation(40.457091, -79.915331),
3.9,
null,
"https:
businesses.add(
new Listing("west elm",
new MapLocation(40.456279, -79.915015),
3.6,
null,
"https:
businesses.add(
new Listing("McDonalds",
new MapLocation(40.459450, -79.918479),
2.6,
null,
"https:
businesses.add(
new Listing("East End Brewing Company",
new MapLocation(40.459391, -79.911782),
4.7,
"https:
"www.eastendbrewing.com%2F&psig=AOvVa" +
"w0kX_SAlxhA09EN3cKpt5ik&ust=1593613487774000&source=" +
"images&cd=vfe&ved=0CAIQjRxqFwoTCLDA6oDfqeoCFQAAAAAdAAAAABAD",
"http:
businesses.add(
new Listing("The Shiny Bean Coffee & Tea",
new MapLocation(40.496328, -79.944862),
4.9,
"https://goo.gl/maps/AYH2QCL7pkoMBxHA8",
"https://theshinybean.com/"));
businesses.add(
new Listing("Weisshouse",
new MapLocation(40.456684, -79.925499),
4.3,
"https://goo.gl/maps/7tuXn7QF2hh7ioGYA",
"https:
}
// To be used for unit testing file to be able to
// set any static business LinkedList we want to try to use
public void setAllBusinesses(List<Listing> allBusinesses) {
businessesService.setAllBusinesses(allBusinesses);
}
// To remove the big businesses from the list
// that will be returned from the use of the Places API
public void parseThroughTheListOfBusinesses() {
databaseResults = businessesService.getBigBusinessFromDatabase();
businesses = businessesService.removeBigBusinessesFromResults(databaseResults);
}
public List<Listing> getBusinesses() {
return businesses;
}
} |
package com.home.teamnotifier;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.home.teamnotifier.core.AppServerAvailabilityChecker;
import com.home.teamnotifier.core.NotificationManager;
import com.home.teamnotifier.core.ResourceMonitor;
import com.home.teamnotifier.db.*;
import com.home.teamnotifier.gateways.*;
import com.home.teamnotifier.web.socket.ClientManager;
import javax.inject.Singleton;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
final class NotifierModule extends AbstractModule {
@Override
protected void configure() {
bind(UserGateway.class)
.to(DbUserGateway.class)
.in(Singleton.class);
bind(EnvironmentGateway.class)
.to(DbEnvironmentGateway.class)
.in(Singleton.class);
bind(SharedResourceActionsGateway.class)
.to(DbSharedResourceActionsGateway.class)
.in(Singleton.class);
bind(SubscriptionGateway.class)
.to(DbSubscriptionGateway.class)
.in(Singleton.class);
bind(AppServerGateway.class)
.to(DbAppServerGateway.class)
.in(Singleton.class);
bind(NotificationManager.class)
.to(ClientManager.class)
.in(Singleton.class);
bind(AppServerAvailabilityChecker.class)
.in(Singleton.class);
bind(ClientManager.class)
.in(Singleton.class);
bind(ResourceMonitor.class)
.in(Singleton.class);
bind(TransactionHelper.class)
.in(Singleton.class);
}
@Provides
@Singleton
@SuppressWarnings("unused")
public ExecutorService newExecutor(final NotifierConfiguration configuration) {
return Executors.newFixedThreadPool(
configuration.getExecutorsConfiguration().getPoolSize(),
new ThreadFactoryBuilder().setNameFormat("websocket-pool-%d").build()
);
}
@Provides
@Singleton
@SuppressWarnings("unused")
public ScheduledExecutorService newScheduledExecutor(final NotifierConfiguration configuration) {
return Executors.newScheduledThreadPool(
configuration.getExecutorsConfiguration().getPoolSize(),
new ThreadFactoryBuilder().setNameFormat("url-checker-pool-%d").build()
);
}
} |
public class Deck {
private int[] cards = new int[50];
public void initialize() {
for (int i=0; i<cards.length(); i++) {
cards[i] = i;
}
return true;
}
initialize();
public Deck(int numCards) { /* code not shown */ }
public boolean inOrder() {
int counter = 0;
for (int i=0; i<cards.length()-1; i++) {
if (cards[i] == i) {
counter++;
}
if (counter == cards.length()-1) {
return true;
} else {
return false;
}
}
}
public void shuffle() {
int[] originalOrder = cards;
int[] temp = new int[cards.length()];
int halfway = cards.length() / 2;
for (int i=0; i<cards.length()-1; i++) {
if (i <= halfway) {
temp[i] = cards[i];
temp[i+1] = cards[halfway];
halfway++;
}
}
cards = temp;
}
public int reorderingCount() {
cards = originalOrder;
if (inOrder()) {
System.out.println("Successfully restored!");
}
}
/*
* This code is by no means complete, and if you choose to use it,
* you should use it at your own risk, be it for an actual application
* (which I sincerely hope not) or for learning how to perform a
* particular method for a grade. I am still trying to understand
* myself, so please keep that in mind as well.
*/
} |
package com.openlattice.postgres;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Matthew Tamayo-Rios <matthew@openlattice.com>
*/
public class KeyIterator<T> implements Iterator<T> {
private static final Logger logger = LoggerFactory.getLogger( KeyIterator.class );
private final ResultSet rs;
private final CountdownConnectionCloser closer;
private final Function<ResultSet, T> mapper;
private boolean next;
public KeyIterator( ResultSet rs, CountdownConnectionCloser closer, Function<ResultSet, T> mapper ) {
this.closer = closer;
this.rs = rs;
this.mapper = mapper;
try {
next = rs.next();
countDownIfExhausted();
} catch ( SQLException e ) {
logger.error( "Unable to execute sql for load all keys for data map store" );
throw new IllegalStateException( "Unable to execute sql statement", e );
}
}
@Override public boolean hasNext() {
return next;
}
@Override public T next() {
T key;
if ( next ) {
key = mapper.apply( rs );
} else {
throw new NoSuchElementException( "No more elements available in iterator" );
}
try {
next = rs.next();
} catch ( SQLException e ) {
logger.error( "Unable to retrieve next result from result set." );
next = false;
}
countDownIfExhausted();
return key;
}
public void countDownIfExhausted() {
if ( !next ) {
closer.countDown();
}
}
} |
package com.rmd.personal.projecteuler;
import java.util.LinkedList;
import java.util.Date;
import java.util.List;
public final class Common {
private static final int MAX_PRIME_VALUE = 100000000;
private Common() {
}
private static List<Long> primes;
static {
primes = new LinkedList<Long>();
populatePrimesUpTo(MAX_PRIME_VALUE);
}
protected static List<Long> getPrimes() {
return primes;
}
private static void populatePrimesUpTo(int end) {
System.out.println("populating primes up to: " + end);
Date startTime = new Date();
boolean[] values = new boolean[end];
for (int i = 2; i < end; i++) {
if (!values[i]) {
primes.add((long) i);
for (int j = i; j < end; j += i) {
values[j] = true;
}
}
}
Date endTime = new Date();
System.out.println("done - took " + (endTime.getTime() - startTime.getTime()) + " ms.");
}
protected static long sum(long n) {
return (n * (n + 1)) / 2;
}
} |
package com.royalrangers.service;
import com.royalrangers.model.*;
import com.royalrangers.bean.UserBean;
import com.royalrangers.repository.AuthorityRepository;
import com.royalrangers.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class UserService {
@Autowired
UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthorityRepository authorityRepository;
public void grantAuthority(User user, AuthorityName... roles) {
Set<Authority> authoritySet = new HashSet<>();
for (AuthorityName role : roles) {
Authority authority = authorityRepository.findByName(role);
authoritySet.add(authority);
}
user.setAuthorities(authoritySet);
}
public User createUserFromUserForm(UserBean userBean) {
User user = new User();
user.setUsername(userBean.getUserName());
user.setFirstName(userBean.getFirstName());
user.setLastName(userBean.getLastName());
user.setPassword(passwordEncoder.encode(userBean.getPassword()));
user.setEmail(userBean.getEmail());
user.setEnabled(true);
user.setLastPasswordResetDate(new Date(System.currentTimeMillis()));
user.setGender(userBean.getGender());
user.setTelephoneNumber(userBean.getTelephonNumber());
user.setBirthDate(userBean.getBirthDate());
user.setCountry(new Country(userBean.getCountry()));
user.setCity(new City(user.getCountry(), userBean.getCity()));
user.setGroup(new Group(user.getCity(), userBean.getGroup()));
user.setPlatoon(new Platoon(user.getGroup(), userBean.getPlatoon()));
user.setSection(new Section(user.getPlatoon(), userBean.getSection()));
if (Objects.equals(userBean.getStatus(), "teacher")) {
grantAuthority(user, AuthorityName.ROLE_USER, AuthorityName.ROLE_ADMIN);
} else {
grantAuthority(user, AuthorityName.ROLE_USER);
}
return user;
}
public Boolean isEmailExist(String email) {
return (userRepository.findByEmail(email) != null);
}
public void saveUser(UserBean userBean, User user) {
String password = passwordEncoder.encode(userBean.getPassword());
userBean.setPassword(password);
userRepository.save(user);
}
public User findByUserEmail(String email) {
return userRepository.findByEmail(email);
}
} |
package com.sdl.selenium.extjs3.tab;
import com.sdl.selenium.WebLocatorUtils;
import com.sdl.selenium.extjs3.ExtJsComponent;
import com.sdl.selenium.utils.config.WebDriverConfig;
import com.sdl.selenium.web.SearchType;
import com.sdl.selenium.web.WebLocator;
import com.sdl.selenium.web.XPathBuilder;
import com.sdl.selenium.web.utils.Utils;
import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class TabPanel extends ExtJsComponent {
private static final Logger LOGGER = LoggerFactory.getLogger(TabPanel.class);
private TabPanel() {
setClassName("TabPanel");
setBaseCls("x-tab-panel");
}
public TabPanel(String text) {
this();
setText(text, SearchType.EQUALS);
}
public TabPanel(WebLocator container, String text) {
this(text);
setContainer(container);
}
private String getTitlePath() {
WebLocator header = new WebLocator().setClasses("x-tab-panel-header");
WebLocator locator = new WebLocator().setText(getPathBuilder().getText()).setContainer(header);
locator.setSearchTextType(getPathBuilder().getSearchTextType().toArray(new SearchType[getPathBuilder().getSearchTextType().size()]));
return locator.getXPath();
}
/**
* this method return the path of the main TabPanel (that contains also this Tab/Panel)
*
* @return the path of the main TabPanel
*/
private String getBaseTabPanelPath() {
String selector = getPathBuilder().getBasePath();
WebLocator el = new WebLocator().setText(getPathBuilder().getText(), SearchType.EQUALS);
el.setSearchTextType(getPathBuilder().getSearchTextType().toArray(new SearchType[getPathBuilder().getSearchTextType().size()]));
/**
* this method return the path of only one visible div from the main TabPanel
*
* @param disabled disabled
* @return the path of only one visible div from the main TabPanel
*/
@Override
public String getItemPath(boolean disabled) {
String selector = getBaseTabPanelPath();
selector += "/*/*[contains(@class, 'x-tab-panel-body')]" + //TODO
/**
* After the tab is set to active will wait 300ms to make sure tab is rendered
*
* @return true or false
*/
public boolean setActive() {
/**
* @deprecated use {@link #getTabIndex(String, String)}
* @param nameTab
* @param path
* @return
*/
public int getTabCount(String nameTab, String path) {
return getTabIndex(nameTab, path);
}
} |
package com.socotech.wf4j;
import java.beans.PropertyEditor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* AbstractFormAction
*/
public abstract class AbstractFormAction extends AbstractAction {
/**
* A uniform method for constructing the name used to persist form in session scope
*
* @param form form object
* @return name
*/
protected String getSessionAttributeName(Form form) {
return form.formClass().getName() + "." + form.name().toUpperCase();
}
/**
* Load supporting data into request scope before directing user to form view. This method must be overriden by subclasses. By default, this method returns an empty map.
*
* @param request HTTP request
* @param o form object
* @return map of data
* @throws Exception if something bad happens
*/
protected Map<String, Object> getAuxiliaryData(HttpServletRequest request, Object o) throws Exception {
return Maps.newHashMap();
}
/**
* Constructs a form object and, if specified, stores it in the session for later use
*
* @param req web request
* @return form object
* @throws Exception if object cannot be instantiated
*/
protected Object getFormObject(HttpServletRequest req) throws Exception {
Form form = this.getClass().getAnnotation(Form.class);
Object command, newbie = form.formClass().newInstance();
// as default, assign new instance to command
command = newbie;
// try to load an existing object from the session (optional)
if (form.sessionForm()) {
String sessionName = this.getSessionAttributeName(form);
command = WebUtil.getOrCreateSessionAttribute(req, sessionName, newbie);
}
// If command & newbie reference the same object, either we're not in session form mode or
// there was no existing form found in the session. Either way, form object is a newbie
// and, if bind on new form is 'true', bind request parameters to new form object now.
if (command == newbie && this.bindOnNewForm(req)) {
FormErrors errors = new FormErrors();
// copy bean properties from request params
this.bindFormObject(req, command, errors);
// log binding errors as warnings
for (String code : errors.getCodes()) {
log.warn("Error while binding on new form: " + errors.get(code));
}
// allow for post-binding of new for
this.onBindOnNewForm(req, command, errors);
}
return command;
}
/**
* If the request method is "POST", a form submission is assumed. Sub-classes can override this to use request params.
*
* @param request HTTP request
* @param o form object
* @return true, if form submission is detected
*/
protected boolean isFormSubmission(HttpServletRequest request, Object o) {
return "put".equalsIgnoreCase(request.getMethod()) || "post".equalsIgnoreCase(request.getMethod());
}
/**
* Use request parameters to populate the form object. Any form binders present in the form configuration are applied.
* <p/>
* Enum types are automagically detected and translated from String values to their respective enum type.
*
* @param request incoming HTTP request
* @param o form object
* @param errors error packet
* @throws Exception if unhandled exceptions occur while binding
*/
@SuppressWarnings("unchecked")
protected void bindFormObject(HttpServletRequest request, Object o, FormErrors errors) throws Exception {
// assemble parameter map
Map<String, String[]> parameters = Maps.newHashMap();
if (!ServletFileUpload.isMultipartContent(request)) {
// process as standard request
Enumeration names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String[] values = request.getParameterValues(name);
parameters.put(name, values);
}
} else {
// process as multi-part request
ServletFileUpload fu = new ServletFileUpload(this.getFileItemFactory());
try {
List<FileItem> fitems = fu.parseRequest(request);
for (FileItem fitem : fitems) {
String name = fitem.getFieldName();
if (fitem.isFormField()) {
String value = fitem.getString();
String[] values = parameters.get(name);
if (values == null) {
// Not in parameter map yet, so add as new value.
parameters.put(name, new String[]{value});
} else {
// Multiple field values, so add new value to existing array.
int length = values.length;
String[] newValues = new String[length + 1];
System.arraycopy(values, 0, newValues, 0, length);
newValues[length] = value;
parameters.put(name, newValues);
}
} else {
// bind uploaded files to form object now instead of below
InputStream in = fitem.getInputStream();
try {
byte[] bytes = ByteStreams.toByteArray(in);
BeanUtils.setProperty(o, name, bytes);
} catch (Exception e) {
if (!errors.isSet(name)) { // don't overwrite existing property error
errors.put(name, ExceptionUtils.getRootCauseMessage(e));
}
} finally {
Closeables.close(in, true);
}
}
}
} catch (FileUploadException e) {
log.warn(e.getMessage(), e);
}
}
// copy param keys to list
List<String> paramKeys = Lists.newArrayList(parameters.keySet());
// sort by name so we bind in ancestral order
Collections.sort(paramKeys);
// bind simple form fields to form object
for (String fieldName : paramKeys) {
String fieldPath = fieldName.replaceAll(Patterns.INDEX_REFERENCE.pattern(), "");
String[] valueArray = parameters.get(fieldName);
Field field = Reflect.getDeclaredField(o, fieldName);
if (field != null) {
try {
Class<?> type = field.getType();
// resolve binders based on type and path
Set<FormBinder> binders = this.getBinders(fieldPath);
// re-package array as collection
Set<String> values = Sets.newHashSet(valueArray);
// determine if field is an array
if (type.isArray()) {
// get the underlying class of this array
type = type.getComponentType();
// determine if field is enum
if (type.isEnum()) {
// array of enums; try to resolve value if not blank
Set<Enum> enums = Sets.newHashSet();
for (String value : values) {
if (StringUtils.isNotBlank(value)) {
Class<Enum> ce = (Class<Enum>) type;
Enum e = Enum.valueOf(ce, value);
enums.add(e);
}
}
Object[] array = (Object[]) Array.newInstance(type, enums.size());
Object object = enums.toArray(array);
BeanUtils.setProperty(o, fieldName, object);
} else {
// array of primitive or object types
Set<Object> objects = Sets.newHashSet();
for (String value : values) {
Object obj = value;
// try to match using equality; otherwise, try to match using a regular expression
for (FormBinder binder : binders) {
PropertyEditor pe = this.newPropertyEditor(request, binder);
pe.setAsText(value);
obj = pe.getValue();
}
if (obj.getClass().isArray()) {
// value is delimited array of elements
Object[] array = (Object[]) obj;
objects.addAll(Arrays.asList(array));
} else {
// value is a primitive or object
objects.add(obj);
}
}
Object[] array = (Object[]) Array.newInstance(type, objects.size());
Object object = objects.toArray(array);
BeanUtils.setProperty(o, fieldName, object);
}
} else {
String value = values.iterator().next();
if (!binders.isEmpty()) {
// use form binders to convert...
Object object = value;
for (FormBinder binder : binders) {
PropertyEditor pe = this.newPropertyEditor(request, binder);
pe.setAsText(value);
object = pe.getValue();
}
// set property with no type conversions
PropertyUtils.setProperty(o, fieldName, object);
} else if (StringUtils.isNotBlank(value)) {
if (type.isEnum()) {
Class<Enum> e = (Class<Enum>) type;
Object object = Enum.valueOf(e, value);
// set property with no type conversions
PropertyUtils.setProperty(o, fieldName, object);
} else {
// set property using type conversions if necessary
BeanUtils.setProperty(o, fieldName, value);
}
} else if (StringUtils.isEmpty(value)) {
// per #4408, set value to null
if (type.isPrimitive()) {
// set property using type conversions if necessary
BeanUtils.setProperty(o, fieldName, null);
} else {
// set property with no type conversions
PropertyUtils.setProperty(o, fieldName, null);
}
}
}
} catch (Exception e) {
if (e instanceof IllegalArgumentException) {
// This is a simple IAE: no point in writing out the stack
log.warn(e.getMessage());
} else {
log.warn(e.getMessage(), e);
}
if (!errors.isSet(fieldName)) { // don't overwrite existing property error
errors.put(fieldName, e.getMessage());
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("Writable property \"" + fieldName + "\" not found on form object");
}
}
}
}
/**
* Sub-classes can override to avoid writing to disk, i.e. Google Appengine
*
* @return file item factory
*/
protected FileItemFactory getFileItemFactory() {
return new DiskFileItemFactory();
}
/**
* Extract binders for a specific form property
*
* @param path path to property
* @return set of binders
*/
@SuppressWarnings("unchecked")
private Set<FormBinder> getBinders(String path) {
Set<FormBinder> set = Sets.newHashSet();
FormBinder[] binders = this.getClass().getAnnotation(Form.class).binders();
for (FormBinder binder : binders) {
if (binder.property().equals(path) || Pattern.compile(binder.property()).matcher(path).matches()) {
set.add(binder);
}
}
return set;
}
/**
* Does user meet privilege requirements?
*
* @param request web request
* @param response web response
* @param o web form
* @return true, if user meets privilege requirements
*/
public boolean isAuthorized(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
return true;
}
/**
* Create a new validator. By default, it simply creates a new instance of the class.
* <p>
* Sub-classes can override this method to do something fancier, i.e. instantiate via DI/IoC
*
* @param request web request
* @param form form spec
* @return new form validator instance
*/
protected FormValidator newFormValidator(HttpServletRequest request, Form form) throws Exception {
return (FormValidator) form.validatorClass().newInstance();
}
/**
* Given a form binder, resolve the proper property editor. Sub-classes can override to add specialized handling, i.e. currency editor.
*
* @param request web request
* @param binder form binder
* @return new instance of editor class
* @throws Exception if editor class cannot be instantiated
*/
protected PropertyEditor newPropertyEditor(HttpServletRequest request, FormBinder binder) throws Exception {
return (PropertyEditor) binder.editorClass().newInstance();
}
/**
* Determine whether validation should be skipped. Default is false. Sub-classes should override to customize behavior.
*
* @param request HTTP request
* @param o form object
* @param errors error packet
* @return true, if validation should be skipped
*/
protected boolean suppressValidation(HttpServletRequest request, Object o, FormErrors errors) {
return false;
}
/**
* Determine if we should bind request parameters to a newly instantiated form object
*
* @param req web request
* @return true, if we should bind to new form object
*/
protected boolean bindOnNewForm(HttpServletRequest req) {
return false;
}
/**
* Determine if we should handle binding and validation errors instead of returning to form view
*
* @param request web request
* @param o form object
* @param errors error packet
* @return true, if errors should be handled and avoid returning to form view
*/
protected boolean handleBindingAndValidationErrors(HttpServletRequest request, Object o, FormErrors errors) {
return false;
}
/**
* Handle a form submission which produced errors. The form object is automagically marshaled from either the session or request parameters.
*
* @param request HTTP request
* @param response HTTP response
* @param o form object
* @param errors error packet
* @throws IOException i/o exception
* @throws ServletException servlet problems?
*/
protected void onBindingAndValidationErrors(HttpServletRequest request, HttpServletResponse response, Object o, FormErrors errors) throws Exception {
// noop
}
/**
* After binding, validate the form object
*
* @param request HTTP request
* @param o form object
* @param errors error packet
* @throws Exception if the form type or validator instance cannot be instantiated
*/
protected void validateFormObject(HttpServletRequest request, Object o, FormErrors errors) throws Exception {
Form form = this.getClass().getAnnotation(Form.class);
if (!form.validatorClass().equals(void.class)) {
this.newFormValidator(request, form).validate(o, errors);
}
}
/**
* Handle the default execution method and forward with command object
*
* @param req incoming HTTP request
* @param res incoming HTTP response
* @throws IOException i/o error
* @throws ServletException servlet error
*/
@Override
public final void execute(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
if (!this.redirectRequest(req, res)) {
FormErrors errors = new FormErrors();
try {
Form form = this.getClass().getAnnotation(Form.class);
// get or create a new form
Object o = this.getFormObject(req);
// copy bean properties from request params
this.bindFormObject(req, o, errors);
// Allow actions to do their own work prior to form processing
this.onBind(req, res, o, errors);
// got errors?
if (errors.isEmpty()) {
// Check privileges
if (this.isAuthorized(req, res, o)) {
// is it a form submission?
if (this.isFormSubmission(req, o)) {
// validate the form (optional)
if (!this.suppressValidation(req, o, errors)) {
this.validateFormObject(req, o, errors);
}
// allow for post-binding and post-validation processing
this.onBindAndValidate(req, o, errors);
// still no errors?
if (errors.isEmpty()) {
// no errors, continue to execute
this.handleFormSubmission(req, res, o, errors);
// clean up after successful form submission
if (!form.sessionForm()) {
WebUtil.removeSessionAttribute(req, getSessionAttributeName(form));
}
} else if (this.handleBindingAndValidationErrors(req, o, errors)) {
this.onBindingAndValidationErrors(req, res, o, errors);
} else {
this.showForm(req, res, o, errors);
}
} else {
this.showForm(req, res, o, errors);
}
} else {
this.handleUnauthorized(req, res);
}
} else {
this.showForm(req, res, o, errors);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
this.raiseServerError(req, res, e.getMessage());
}
}
}
/**
* Called early in the execute process.
*
* @param request web request
* @param response web response
* @return true, if you are redirecting the request outside of the process.
* @throws IOException i/o error
* @throws ServletException servlet exception
*/
@Deprecated
protected boolean redirectRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
return false;
}
/**
* Called only after a new form is instantiated and request parameters are bound to it.
*
* @param request web request
* @param o form object
* @param errors error packet
* @throws Exception bad stuff
*/
protected void onBindOnNewForm(HttpServletRequest request, Object o, FormErrors errors) throws Exception {
// noop
}
/**
* Called after form is bound but before it is processed and displayed. return true if you want to bypass subsequent processing
*
* @param request web request
* @param response web response
* @param o form object
* @param errors error packet
* @throws Exception any show stoppers
* @see #onBindAndValidate for preferred usage
*/
protected void onBind(HttpServletRequest request, HttpServletResponse response, Object o, FormErrors errors) throws Exception {
// noop
}
/**
* Called after form is bound to request parameters and validated.
*
* @param request web request
* @param o form object
* @param errors error packet
* @throws Exception bad stuff
*/
protected void onBindAndValidate(HttpServletRequest request, Object o, FormErrors errors) throws Exception {
// noop
}
/**
* Return user to the form view
*
* @param request HTTP request
* @param response HTTP response
* @param o form object
* @param errors error packet
* @throws Exception bad stuff
*/
protected abstract void showForm(HttpServletRequest request, HttpServletResponse response, Object o, FormErrors errors) throws Exception;
/**
* Handle a form submission from user. The form object is automagically marshaled from either the session or request parameters.
*
* @param request HTTP request
* @param response HTTP response
* @param o form object
* @param errors error packet
* @throws IOException i/o exception
* @throws javax.servlet.ServletException servlet problems?
*/
protected abstract void handleFormSubmission(HttpServletRequest request, HttpServletResponse response, Object o, FormErrors errors) throws IOException, ServletException;
/**
* <p/> A logging category for each action. </p>
*/
private static final Logger log = LoggerFactory.getLogger(AbstractFormAction.class);
} |
package com.socotech.wf4j;
import java.beans.PropertyEditor;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* AbstractFormAction
*/
public abstract class AbstractFormAction extends AbstractAction {
/**
* A uniform method for constructing the name used to persist form in session scope
*
* @param form form object
* @return name
*/
protected String getSessionAttributeName(Form form) {
return form.formClass().getName() + "." + form.name().toUpperCase();
}
/**
* Load supporting data into request scope before directing user to form view. This method must be overriden by subclasses. By default, this method returns an empty map.
*
* @param request HTTP request
* @param o form object
* @return map of data
* @throws Exception if something bad happens
*/
protected Map<String, Object> getAuxiliaryData(HttpServletRequest request, Object o) throws Exception {
return Maps.newHashMap();
}
/**
* Constructs a form object and, if specified, stores it in the session for later use
*
* @param req form request
* @return form object
* @throws Exception if object cannot be instantiated
*/
protected Object getFormObject(HttpServletRequest req) throws Exception {
Form form = this.getClass().getAnnotation(Form.class);
Object command, newbie = form.formClass().newInstance();
// as default, assign new instance to command
command = newbie;
// try to load an existing object from the session (optional)
if (form.sessionForm()) {
String sessionName = this.getSessionAttributeName(form);
command = WebUtil.getOrCreateSessionAttribute(req, sessionName, newbie);
}
// If command & newbie reference the same object, either we're not in session form mode or
// there was no existing form found in the session. Either way, form object is a newbie
// and, if bind on new form is 'true', bind request parameters to new form object now.
if (command == newbie && this.bindOnNewForm(req)) {
FormErrors errors = new FormErrors();
// copy bean properties from request params
this.bindFormObject(req, command, errors);
// log binding errors as warnings
for (String code : errors.getCodes()) {
log.warn("Error while binding on new form: " + errors.get(code));
}
// allow for post-binding of new for
this.onBindOnNewForm(req, command, errors);
}
return command;
}
/**
* If the request method is "POST", a form submission is assumed. Sub-classes can override this to use request params.
*
* @param request HTTP request
* @return true, if form submission is detected
*/
protected boolean isFormSubmission(HttpServletRequest request) {
return "POST".equalsIgnoreCase(request.getMethod());
}
/**
* Use request parameters to populate the form object. Any form binders present in the form configuration are applied.
* <p/>
* Enum types are automagically detected and translated from String values to their respective enum type.
*
* @param request incoming HTTP request
* @param o form object
* @param errors error packet
* @throws Exception if unhandled exceptions occur while binding
*/
@SuppressWarnings("unchecked")
protected void bindFormObject(HttpServletRequest request, Object o, FormErrors errors) throws Exception {
// assemble parameter map
Map<String, String[]> parameters = Maps.newHashMap();
if (!ServletFileUpload.isMultipartContent(request)) {
// process as standard request
Enumeration names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String[] values = request.getParameterValues(name);
parameters.put(name, values);
}
} else {
// process as multi-part request
ServletFileUpload fu = new ServletFileUpload(new DiskFileItemFactory());
try {
List<FileItem> fitems = fu.parseRequest(request);
for (FileItem fitem : fitems) {
String name = fitem.getFieldName();
if (fitem.isFormField()) {
String value = fitem.getString();
String[] values = parameters.get(name);
if (values == null) {
// Not in parameter map yet, so add as new value.
parameters.put(name, new String[]{value});
} else {
// Multiple field values, so add new value to existing array.
int length = values.length;
String[] newValues = new String[length + 1];
System.arraycopy(values, 0, newValues, 0, length);
newValues[length] = value;
parameters.put(name, newValues);
}
} else {
// bind uploaded files to form object now instead of below
try {
byte[] bytes = IOUtils.toByteArray(fitem.getInputStream());
BeanUtils.setProperty(o, name, bytes);
} catch (Exception e) {
if (!errors.isSet(name)) { // don't overwrite existing property error
errors.put(name, ExceptionUtils.getRootCauseMessage(e));
}
}
}
}
} catch (FileUploadException e) {
log.warn(e.getMessage(), e);
}
}
// copy param keys to list
List<String> paramKeys = Lists.newArrayList(parameters.keySet());
// sort by name so we bind in ancestral order
Collections.sort(paramKeys);
// bind simple form fields to form object
for (String fieldName : paramKeys) {
String fieldPath = fieldName.replaceAll(Patterns.INDEX_REFERENCE.pattern(), "");
String[] valueArray = parameters.get(fieldName);
Field field = Reflect.getDeclaredField(o, fieldName);
if (field != null) {
try {
Class<?> type = field.getType();
// resolve binders based on type and path
Set<FormBinder> binders = this.getBinders(fieldPath);
// re-package array as collection
Set<String> values = Sets.newHashSet(valueArray);
// determine if field is an array
if (type.isArray()) {
// get the underlying class of this array
type = type.getComponentType();
// determine if field is enum
if (type.isEnum()) {
// array of enums; try to resolve value if not blank
Set<Enum> enums = Sets.newHashSet();
for (String value : values) {
if (StringUtils.isNotBlank(value)) {
Class<Enum> ce = (Class<Enum>) type;
Enum e = Enum.valueOf(ce, value);
enums.add(e);
}
}
Object[] array = (Object[]) Array.newInstance(type, enums.size());
Object object = enums.toArray(array);
BeanUtils.setProperty(o, fieldName, object);
} else {
// array of primitive or object types
Set<Object> objects = Sets.newHashSet();
for (String value : values) {
Object obj = value;
// try to match using equality; otherwise, try to match using a regular expression
for (FormBinder binder : binders) {
PropertyEditor pe = this.newPropertyEditor(request, binder);
pe.setAsText(value);
obj = pe.getValue();
}
if (obj.getClass().isArray()) {
// value is delimited array of elements
Object[] array = (Object[]) obj;
objects.addAll(Arrays.asList(array));
} else {
// value is a primitive or object
objects.add(obj);
}
}
Object[] array = (Object[]) Array.newInstance(type, objects.size());
Object object = objects.toArray(array);
BeanUtils.setProperty(o, fieldName, object);
}
} else {
String value = values.iterator().next();
if (!binders.isEmpty()) {
// use form binders to convert...
Object object = value;
for (FormBinder binder : binders) {
PropertyEditor pe = this.newPropertyEditor(request, binder);
pe.setAsText(value);
object = pe.getValue();
}
// set property with no type conversions
PropertyUtils.setProperty(o, fieldName, object);
} else if (StringUtils.isNotBlank(value)) {
if (type.isEnum()) {
Class<Enum> e = (Class<Enum>) type;
Object object = Enum.valueOf(e, value);
// set property with no type conversions
PropertyUtils.setProperty(o, fieldName, object);
} else {
// set property using type conversions if necessary
BeanUtils.setProperty(o, fieldName, value);
}
} else if (StringUtils.isEmpty(value)) {
// per #4408, set value to null
if (type.isPrimitive()) {
// set property using type conversions if necessary
BeanUtils.setProperty(o, fieldName, null);
} else {
// set property with no type conversions
PropertyUtils.setProperty(o, fieldName, null);
}
}
}
} catch (Exception e) {
if (e instanceof IllegalArgumentException) {
// This is a simple IAE: no point in writing out the stack
log.warn(e.getMessage());
} else {
log.warn(e.getMessage(), e);
}
if (!errors.isSet(fieldName)) { // don't overwrite existing property error
errors.put(fieldName, e.getMessage());
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("Writable property \"" + fieldName + "\" not found on form object");
}
}
}
}
/**
* Extract binders for a specific form property
*
* @param path path to property
* @return set of binders
*/
@SuppressWarnings("unchecked")
private Set<FormBinder> getBinders(String path) {
Set<FormBinder> set = Sets.newHashSet();
FormBinder[] binders = this.getClass().getAnnotation(Form.class).binders();
for (FormBinder binder : binders) {
if (binder.property().equals(path) || Pattern.compile(binder.property()).matcher(path).matches()) {
set.add(binder);
}
}
return set;
}
/**
* Does user meet privilege requirements?
*
* @param request wf4j request
* @param response wf4j response
* @param o wf4j form
* @return true, if user meets privilege requirements
*/
public boolean meetsPrivilegeRequirements(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
return true;
}
/**
* Create a new validator. By default, it simply creates a new instance of the class.
* <p>
* Sub-classes can override this method to do something fancier, i.e. instantiate via DI/IoC
*
* @param request web request
* @param form form spec
* @return new form validator instance
*/
protected FormValidator newFormValidator(HttpServletRequest request, Form form) throws Exception {
return (FormValidator) form.validatorClass().newInstance();
}
/**
* Given a form binder, resolve the proper property editor. Sub-classes can override to add specialized handling, i.e. currency editor.
*
* @param request web request
* @param binder form binder
* @return new instance of editor class
* @throws Exception if editor class cannot be instantiated
*/
protected PropertyEditor newPropertyEditor(HttpServletRequest request, FormBinder binder) throws Exception {
return (PropertyEditor) binder.editorClass().newInstance();
}
/**
* Determine whether binding should be skipped. Default is false. Sub-classes should override to customize behavior.
*
* @param request HTTP request
* @param o form object
* @param errors error packet
* @return true, if binding should be skipped
*/
protected boolean suppressBinding(HttpServletRequest request, Object o, FormErrors errors) {
return false;
}
/**
* Determine whether validation should be skipped. Default is false. Sub-classes should override to customize behavior.
*
* @param request HTTP request
* @param o form object
* @param errors error packet
* @return true, if validation should be skipped
*/
protected boolean suppressValidation(HttpServletRequest request, Object o, FormErrors errors) {
return false;
}
/**
* Determine if we should bind request parameters to a newly instantiated form object
*
* @param req wf4j request
* @return true, if we should bind to new form object
*/
protected boolean bindOnNewForm(HttpServletRequest req) {
return false;
}
/**
* Determine if we should handle binding and validation errors instead of returning to form view
*
* @param request wf4j request
* @param o form object
* @param errors error packet
* @return true, if errors should be handled and avoid returning to form view
*/
protected boolean handleBindingAndValidationErrors(HttpServletRequest request, Object o, FormErrors errors) {
return false;
}
/**
* Handle a form submission which produced errors. The form object is automagically marshaled from either the session or request parameters.
*
* @param request HTTP request
* @param response HTTP response
* @param o form object
* @param errors error packet
* @throws IOException i/o exception
* @throws ServletException servlet problems?
*/
protected void onBindingAndValidationErrors(HttpServletRequest request, HttpServletResponse response, Object o, FormErrors errors) throws Exception {
// noop
}
/**
* After binding, validate the form object
*
* @param request HTTP request
* @param o form object
* @param errors error packet
* @throws Exception if the form type or validator instance cannot be instantiated
*/
protected void validateFormObject(HttpServletRequest request, Object o, FormErrors errors) throws Exception {
Form form = this.getClass().getAnnotation(Form.class);
if (!form.validatorClass().equals(void.class)) {
this.newFormValidator(request, form).validate(o, errors);
}
}
/**
* Handle the default execution method and forward with command object
*
* @param req incoming HTTP request
* @param res incoming HTTP response
* @throws IOException
* @throws ServletException
*/
@Override
public final void execute(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
FormErrors errors = new FormErrors();
try {
// Allow actions to abort the remainder
if (this.redirectRequest(req, res)) {
return;
}
Form form = this.getClass().getAnnotation(Form.class);
// get or create a new form
Object o = this.getFormObject(req);
// bind parameters to the form (optional)
if (!this.suppressBinding(req, o, errors)) {
// copy bean properties from request params
this.bindFormObject(req, o, errors);
// Allow actions to do their own work prior to form processing
if (this.onBind(req, res, o, errors)) {
return;
}
// Check privileges
if (!this.meetsPrivilegeRequirements(req, res, o)) {
this.handleUnauthorized(req, res);
}
}
if (this.isFormSubmission(req)) {
// validate the form (optional)
if (!this.suppressValidation(req, o, errors)) {
this.validateFormObject(req, o, errors);
}
// allow for post-binding and post-validation processing
this.onBindAndValidate(req, o, errors);
// still no errors?
if (errors.isEmpty()) {
// no errors, continue to execute
this.handleFormSubmission(req, res, o, errors);
// clean up after successful form submission
if (form.sessionForm()) {
WebUtil.removeSessionAttribute(req, getSessionAttributeName(form));
}
return; // successful form submission...exit now!
} else if (this.handleBindingAndValidationErrors(req, o, errors)) {
this.onBindingAndValidationErrors(req, res, o, errors);
return; // errors handled...exit now!
}
}
// either not a form submission or unhandled errors produced from binding and validation. In any event, show the form.
this.showForm(req, res, o, errors);
} catch (Exception e) {
log.error(e.getMessage(), e);
this.raiseServerError(req, res, e.getMessage());
}
}
/*
* Called early in the execute process.
* return true if you are redirecting the request outside of the process.
*/
protected boolean redirectRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
return false;
}
/**
* Called only after a new form is instantiated and request parameters are bound to it.
*
* @param request wf4j request
* @param o form object
* @param errors error packet
* @throws Exception bad stuff
*/
protected void onBindOnNewForm(HttpServletRequest request, Object o, FormErrors errors) throws Exception {
// noop
}
/**
* Called after form is bound but before it is processed and displayed. return true if you want to bypass subsequent processing
*
* @param request wf4j request
* @param response wf4j response
* @param o form object
* @param errors error packet
* @return true, if further processing should be halted
* @throws Exception any show stoppers
* @see #onBindAndValidate for preferred usage
*/
protected boolean onBind(HttpServletRequest request, HttpServletResponse response, Object o, FormErrors errors) throws Exception {
return false;
}
/**
* Called after form is bound to request parameters and validated.
*
* @param request wf4j request
* @param o form object
* @param errors error packet
* @throws Exception bad stuff
*/
protected void onBindAndValidate(HttpServletRequest request, Object o, FormErrors errors) throws Exception {
// noop
}
/**
* Return user to the form view
*
* @param request HTTP request
* @param response HTTP response
* @param o form object
* @param errors error packet
* @throws Exception bad stuff
*/
protected abstract void showForm(HttpServletRequest request, HttpServletResponse response, Object o, FormErrors errors) throws Exception;
/**
* Handle a form submission from user. The form object is automagically marshaled from either the session or request parameters.
*
* @param request HTTP request
* @param response HTTP response
* @param o form object
* @param errors error packet
* @throws IOException i/o exception
* @throws javax.servlet.ServletException servlet problems?
*/
protected abstract void handleFormSubmission(HttpServletRequest request, HttpServletResponse response, Object o, FormErrors errors) throws IOException, ServletException;
/**
* <p/> A logging category for each action. </p>
*/
private static final Logger log = LoggerFactory.getLogger(AbstractFormAction.class);
} |
package com.exedio.cope.util;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.exedio.cope.Cope;
import com.exedio.cope.Item;
import com.exedio.cope.Model;
import com.exedio.cope.NoSuchIDException;
import com.exedio.cope.StringField;
import com.exedio.cope.pattern.MapField;
import com.exedio.cope.pattern.Media;
import com.exedio.cope.pattern.MediaFilter;
import com.exedio.cops.Cop;
import com.exedio.cops.CopsServlet;
public abstract class Editor implements Filter
{
private final Model model;
/**
* Subclasses must define a public no-args constructor
* providing the model.
*/
protected Editor(final Model model)
{
if(model==null)
throw new NullPointerException("model was null in " + getClass().getName());
this.model = model;
}
private ConnectToken connectToken = null;
public final void init(final FilterConfig config)
{
connectToken = ServletUtil.connect(model, config, getClass().getName());
}
public final void destroy()
{
connectToken.returnIt();
connectToken = null;
}
/**
* If you want persistent sessions,
* the make implementors of this interface serializable.
*/
public interface Login
{
String getName();
}
protected abstract Login login(String user, String password);
public final void doFilter(
final ServletRequest servletRequest,
final ServletResponse response,
final FilterChain chain) throws IOException, ServletException
{
if(!(servletRequest instanceof HttpServletRequest))
{
chain.doFilter(servletRequest, response);
return;
}
final HttpServletRequest request = (HttpServletRequest)servletRequest;
if(LOGIN_URL_PATH_INFO.equals(request.getPathInfo()))
{
servletRequest.setCharacterEncoding(CopsServlet.ENCODING);
final HttpServletResponse httpResponse = (HttpServletResponse)response;
final HttpSession httpSession = request.getSession(true);
final Object session = httpSession.getAttribute(SESSION);
if(session==null)
doLogin(request, httpSession, httpResponse);
else
doBar(request, httpSession, httpResponse, (Session)session);
return;
}
final HttpSession httpSession = request.getSession(false);
if(httpSession!=null)
{
final Object session = httpSession.getAttribute(SESSION);
if(session!=null)
{
try
{
tls.set(new TL(request, (HttpServletResponse)response, (Session)session));
chain.doFilter(request, response);
}
finally
{
tls.remove();
}
}
else
chain.doFilter(request, response);
}
else
{
chain.doFilter(request, response);
}
}
static final String AVOID_COLLISION = "contentEditorBar823658617";
static final String REFERER = "referer";
static final String TOGGLE_BORDERS = "borders";
static final String LOGOUT = "logout";
static final String SAVE_FEATURE = "feature";
static final String SAVE_ITEM = "item";
static final String SAVE_KIND = "kind";
static final String SAVE_LINE = "line";
static final String SAVE_FILE = "file";
static final String SAVE_AREA = "area";
static final String SAVE_KIND_LINE = "kindLine";
static final String SAVE_KIND_FILE = "kindFile";
static final String SAVE_KIND_AREA = "kindArea";
@SuppressWarnings("deprecation")
private static final boolean isMultipartContent(final HttpServletRequest request)
{
return ServletFileUpload.isMultipartContent(request);
}
private final void doBar(
final HttpServletRequest request,
final HttpSession httpSession,
final HttpServletResponse response,
final Session session)
throws IOException
{
if(Cop.isPost(request))
{
final String referer;
if(isMultipartContent(request))
{
final HashMap<String, String> fields = new HashMap<String, String>();
final HashMap<String, FileItem> files = new HashMap<String, FileItem>();
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding(CopsServlet.ENCODING);
try
{
for(Iterator<?> i = upload.parseRequest(request).iterator(); i.hasNext(); )
{
final FileItem item = (FileItem)i.next();
if(item.isFormField())
fields.put(item.getFieldName(), item.getString(CopsServlet.ENCODING));
else
files.put(item.getFieldName(), item);
}
}
catch(FileUploadException e)
{
throw new RuntimeException(e);
}
final String featureID = fields.get(SAVE_FEATURE);
if(featureID!=null)
{
final Media feature = (Media)model.findFeatureByID(featureID);
if(feature==null)
throw new NullPointerException(featureID);
final String itemID = fields.get(SAVE_ITEM);
final String kind = fields.get(SAVE_KIND);
if(!SAVE_KIND_FILE.equals(kind))
throw new RuntimeException(kind);
final FileItem file = files.get(SAVE_FILE);
try
{
model.startTransaction(getClass().getName() + "#saveFile");
final Item item = model.findByID(itemID);
// TODO use more efficient setter with File or byte[]
feature.set(item, file.getInputStream(), file.getContentType());
model.commit();
}
catch(NoSuchIDException e)
{
throw new RuntimeException(e);
}
finally
{
model.rollbackIfNotCommitted();
}
}
referer = fields.get(REFERER);
}
else // isMultipartContent
{
if(request.getParameter(TOGGLE_BORDERS)!=null)
{
session.borders = !session.borders;
}
else if(request.getParameter(LOGOUT)!=null)
{
httpSession.removeAttribute(SESSION);
}
final String featureID = request.getParameter(SAVE_FEATURE);
if(featureID!=null)
{
final StringField feature = (StringField)model.findFeatureByID(featureID);
if(feature==null)
throw new NullPointerException(featureID);
final String itemID = request.getParameter(SAVE_ITEM);
final String kind = request.getParameter(SAVE_KIND);
final String value;
if(SAVE_KIND_LINE.equals(kind))
value = request.getParameter(SAVE_LINE);
else if(SAVE_KIND_AREA.equals(kind))
value = request.getParameter(SAVE_AREA);
else
throw new RuntimeException(kind);
try
{
model.startTransaction(getClass().getName() + "#save");
final Item item = model.findByID(itemID);
String v = value;
if("".equals(v))
v = null;
feature.set(item, v);
model.commit();
}
catch(NoSuchIDException e)
{
throw new RuntimeException(e);
}
finally
{
model.rollbackIfNotCommitted();
}
}
referer = request.getParameter(REFERER);
}
if(referer!=null)
response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + request.getServletPath() + referer));
}
}
static final String LOGIN_URL = "contentEditorLogin.html";
private static final String LOGIN_URL_PATH_INFO = '/' + LOGIN_URL;
static final String LOGIN = "login";
static final String LOGIN_USER = "user";
static final String LOGIN_PASSWORD = "password";
private final void doLogin(
final HttpServletRequest request,
final HttpSession httpSession,
final HttpServletResponse response)
throws IOException
{
assert httpSession!=null;
PrintStream out = null;
try
{
response.setContentType("text/html; charset="+CopsServlet.ENCODING);
if(Cop.isPost(request) && request.getParameter(LOGIN)!=null)
{
final String user = request.getParameter(LOGIN_USER);
final String password = request.getParameter(LOGIN_PASSWORD);
try
{
model.startTransaction(getClass().getName() + "#login");
final Login login = login(user, password);
if(login!=null)
{
final String name = login.getName();
httpSession.setAttribute(SESSION, new Session(login, name));
response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + request.getServletPath() + '/'));
}
else
{
out = new PrintStream(response.getOutputStream(), false, CopsServlet.ENCODING);
Editor_Jspm.writeLogin(out, response, user);
}
model.commit();
}
finally
{
model.rollbackIfNotCommitted();
}
}
else
{
out = new PrintStream(response.getOutputStream(), false, CopsServlet.ENCODING);
Editor_Jspm.writeLogin(out, response, null);
}
}
finally
{
if(out!=null)
out.close();
}
}
private static final String SESSION = Session.class.getCanonicalName();
static final class Session implements Serializable // for session persistence
{
private static final long serialVersionUID = 1l;
final Login login;
final String loginName;
boolean borders = false;
Session(final Login login, final String loginName)
{
this.login = login;
this.loginName = loginName;
assert login!=null;
}
@Override
public String toString()
{
// must not call login#getName() here,
// because this may require a transaction,
// which may not be present,
// especially when this method is called by lamdba probe.
return
(loginName!=null ? ('"' + loginName + '"') : login.getClass().getName()) +
" borders=" + (borders ? "on" : "off");
}
}
private static final class TL
{
final HttpServletRequest request;
final HttpServletResponse response;
final Session session;
TL(final HttpServletRequest request, final HttpServletResponse response, final Session session)
{
this.request = request;
this.response = response;
this.session = session;
assert request!=null;
assert response!=null;
assert session!=null;
}
}
private static final ThreadLocal<TL> tls = new ThreadLocal<TL>();
public static final boolean isActive()
{
return tls.get()!=null;
}
@SuppressWarnings("cast") // OK: for eclipse because of the javac bug
private static final <K> Item getItem(final MapField<K, String> map, final K key, final Item item)
{
return
(Item)map.getRelationType().searchSingletonStrict( // cast is needed because of a bug in javac
map.getKey().equal(key).and(
Cope.equalAndCast(map.getParent(item.getCopeType().getJavaClass()), item)));
}
public static final <K> String edit(final String content, final MapField<K, String> feature, final Item item, final K key)
{
final TL tl = tls.get();
if(tl==null || !tl.session.borders)
return content;
return edit(
tl, false,
content,
(StringField)feature.getValue(),
getItem(feature, key, item));
}
public static final <K> String editBlock(final String content, final MapField<K, String> feature, final Item item, final K key)
{
final TL tl = tls.get();
if(tl==null || !tl.session.borders)
return content;
return edit(
tl, true,
content,
(StringField)feature.getValue(),
getItem(feature, key, item));
}
public static final String edit(final String content, final StringField feature, final Item item)
{
final TL tl = tls.get();
if(tl==null || !tl.session.borders)
return content;
return edit(tl, false, content, feature, item);
}
static final String EDIT_METHOD = AVOID_COLLISION + "edit";
private static final String edit(final TL tl, final boolean block, final String content, final StringField feature, final Item item)
{
assert tl.session.borders;
assert feature!=null;
assert item!=null;
assert !feature.isFinal();
assert feature.getType().isAssignableFrom(item.getCopeType()) : item.getCopeID()+'-'+feature.getID();
final String tag = block ? "div" : "span";
final StringBuilder bf = new StringBuilder();
bf.append('<').
append(tag).
append(
" class=\"contentEditorLink\"" +
" onclick=\"" +
EDIT_METHOD + "(this,'").
append(feature.getID()).
append("','").
append(item.getCopeID()).
append("','").
append(block ? Cop.encodeXml(feature.get(item)).replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r") : Cop.encodeXml(feature.get(item))).
append("');return false;\"").
append('>').
append(content).
append("</").
append(tag).
append('>');
return bf.toString();
}
public static final String edit(final Media feature, final Item item)
{
final TL tl = tls.get();
if(tl==null || !tl.session.borders)
return "";
assert feature!=null;
assert item!=null;
assert !feature.isFinal();
assert feature.getType().isAssignableFrom(item.getCopeType()) : item.getCopeID()+'-'+feature.getID();
final StringBuilder bf = new StringBuilder();
bf.append(
" class=\"contentEditorLink\"" +
" onclick=\"" +
EDIT_METHOD + "(this,'").
append(feature.getID()).
append("','").
append(item.getCopeID()).
append("','").
append(Cop.encodeXml(feature.getURL(item))).
append("');return false;\"");
return bf.toString();
}
public static final String edit(final MediaFilter feature, final Item item)
{
final TL tl = tls.get();
if(tl==null || !tl.session.borders)
return "";
return edit(feature.getSource(), item);
}
public static final void writeBar(final PrintStream out)
{
final TL tl = tls.get();
if(tl==null)
return;
final HttpServletRequest request = tl.request;
final String queryString = request.getQueryString();
Editor_Jspm.writeBar(out,
tl.response.encodeURL(request.getContextPath() + request.getServletPath() + LOGIN_URL_PATH_INFO),
queryString!=null ? (request.getPathInfo() + '?' + request.getQueryString()) : request.getPathInfo(),
tl.session.borders,
tl.session.login.getName());
}
} |
package com.timepath.hl2.hudeditor;
import com.timepath.Utils;
import com.timepath.hl2.io.RES;
import com.timepath.hl2.io.VMT;
import com.timepath.hl2.io.image.VTF;
import com.timepath.plaf.IconList;
import com.timepath.plaf.x.filechooser.BaseFileChooser;
import com.timepath.plaf.x.filechooser.NativeFileChooser;
import com.timepath.steam.io.VDF;
import com.timepath.steam.io.VDFNode;
import com.timepath.steam.io.VDFNode.VDFProperty;
import com.timepath.steam.io.storage.ACF;
import com.timepath.vfs.provider.local.LocalFileProvider;
import com.timepath.steam.io.storage.VPK;
import com.timepath.vfs.provider.ExtendedVFile;
import com.timepath.vfs.SimpleVFile;
import com.timepath.vgui.Element;
import com.timepath.vgui.VGUIRenderer.ResourceLocator;
import com.timepath.vgui.swing.VGUICanvas;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* @author TimePath
*/
@SuppressWarnings("serial")
public class HUDEditor extends Application {
private static final Logger LOG = Logger.getLogger(HUDEditor.class.getName());
private static final Pattern VDF_PATTERN = Pattern.compile("^\\.(vdf|pop|layout|menu|styles)");
protected EditorMenuBar editorMenuBar;
@Nullable
protected VGUICanvas canvas;
@Nullable
protected File lastLoaded;
protected JSpinner spinnerWidth, spinnerHeight;
@Nullable
protected HyperlinkListener linkListener = Utils.getLinkListener();
public HUDEditor() {
super();
setIconImages(new IconList("/com/timepath/hl2/hudeditor/res/Icon",
"png",
new int[]{16, 22, 24, 32, 40, 48, 64, 128, 512, 1024}).getIcons());
setTitle(Main.getString("Title"));
setJMenuBar(editorMenuBar = new EditorMenuBar(this));
String str = Main.prefs.get("lastLoaded", null);
if (str != null) setLastLoaded(new File(str));
new SwingWorker<Image, Void>() {
@Nullable
@Override
public Image doInBackground() {
return BackgroundLoader.fetch();
}
@Override
public void done() {
try {
canvas.setBackgroundImage(get());
} catch (@NotNull InterruptedException | ExecutionException e) {
LOG.log(Level.SEVERE, null, e);
}
}
}.execute();
mount(440);
GraphicsConfiguration gc = getGraphicsConfiguration();
Rectangle screenBounds = gc.getBounds();
Insets screenInsets = getToolkit().getScreenInsets(gc);
@NotNull Dimension workspace = new Dimension(screenBounds.width - screenInsets.left - screenInsets.right,
screenBounds.height - screenInsets.top - screenInsets.bottom);
setMinimumSize(new Dimension(Math.max(workspace.width / 2, 640), Math.max((3 * workspace.height) / 4, 480)));
setPreferredSize(new Dimension((int) (workspace.getWidth() / 1.5), (int) (workspace.getHeight() / 1.5)));
pack();
setLocationRelativeTo(null);
}
static void analyze(@NotNull DefaultMutableTreeNode top, boolean leaves) {
if (!(top.getUserObject() instanceof ExtendedVFile)) return;
@NotNull ExtendedVFile root = (ExtendedVFile) top.getUserObject();
for (@NotNull SimpleVFile n : root.list()) {
LOG.log(Level.FINE, "Loading {0}", n.getName());
@NotNull DefaultMutableTreeNode child = new DefaultMutableTreeNode(n);
if (n.isDirectory()) {
if (n.list().size() > 0) {
top.add(child);
analyze(child, leaves);
}
} else if (leaves) {
try (@Nullable InputStream is = n.openStream()) {
if (VDF_PATTERN.matcher(n.getName()).matches()) {
child.add(VDF.load(is).toTreeNode());
} else if (n.getName().endsWith(".res")) {
child.add(RES.load(is).toTreeNode());
} else {
continue;
}
top.add(child);
} catch (IOException e) {
LOG.log(Level.SEVERE, null, e);
}
}
}
}
static void recurseDirectoryToNode(ExtendedVFile ar, @NotNull DefaultMutableTreeNode project) {
project.setUserObject(ar);
analyze(project, true);
}
@Override
protected void initComponents() {
super.initComponents();
fileTree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
@NotNull DefaultMutableTreeNode node = fileTree.getLastSelectedPathComponent();
if (node == null) return;
propTable.clear();
@NotNull DefaultTableModel model = propTable.getModel();
Object nodeInfo = node.getUserObject();
// TODO: introspection
if (nodeInfo instanceof VDFNode) {
Element element = Element.importVdf((VDFNode) nodeInfo);
element.setFile(node.getParent().toString()); // TODO
loadProps(element);
canvas.load(element);
}
}
});
canvas = new VGUICanvas() {
@Override
public void placed() {
@NotNull DefaultMutableTreeNode node = fileTree.getLastSelectedPathComponent();
if (node == null) return;
Object nodeInfo = node.getUserObject();
if (nodeInfo instanceof Element) {
@NotNull Element element = (Element) nodeInfo;
loadProps(element);
}
}
};
tabbedContent.add(Main.getString("Canvas"), new JScrollPane(canvas) {{
// setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
getVerticalScrollBar().setBlockIncrement(30);
getVerticalScrollBar().setUnitIncrement(20);
// setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
getHorizontalScrollBar().setBlockIncrement(30);
getHorizontalScrollBar().setUnitIncrement(20);
}});
}
@Override
public void preferences() {
info("No app-specific preferences yet", "Preferences");
}
@Override
public void about() {
@NotNull JEditorPane pane = new JEditorPane("text/html", "");
pane.setEditable(false);
pane.setOpaque(false);
pane.setBackground(new Color(0, 0, 0, 0));
pane.addHyperlinkListener(linkListener);
@NotNull String aboutText = "<html><h2>This is to be a What You See Is What You Get HUD Editor for TF2,</h2>";
aboutText += "for graphically editing TF2 HUDs!";
@NotNull String p1 = aboutText;
pane.setText(p1);
info(pane, "About");
}
@Override
public void fileDropped(File f) {
loadAsync(f);
}
@Override
public Image getDockIconImage() {
URL url = getClass().getResource("/com/timepath/hl2/hudeditor/res/Icon.png");
return Toolkit.getDefaultToolkit().getImage(url);
}
void locateHudDirectory() {
try {
@Nullable File[] selection = new NativeFileChooser().setParent(this)
.setTitle(Main.getString("LoadHudDir"))
.setDirectory(lastLoaded)
.setFileMode(BaseFileChooser.FileMode.DIRECTORIES_ONLY)
.choose();
if (selection != null) loadAsync(selection[0]);
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
void loadAsync(final File f) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
final long start = System.currentTimeMillis();
new SwingWorker<DefaultMutableTreeNode, Void>() {
@Nullable
@Override
public DefaultMutableTreeNode doInBackground() {
return load(f);
}
@Override
protected void done() {
try {
DefaultMutableTreeNode project = get();
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
if (project == null) return;
LOG.log(Level.INFO, "Loaded hud - took {0}ms", System.currentTimeMillis() - start);
fileSystemRoot.add(project);
fileTree.expandPath(new TreePath(project.getPath()));
fileTree.setSelectionRow(fileSystemRoot.getIndex(project));
fileTree.requestFocusInWindow();
} catch (Throwable t) {
LOG.log(Level.SEVERE, null, t);
}
}
}.execute();
}
@Nullable
DefaultMutableTreeNode load(@Nullable File root) {
if (root == null) return null;
if (!root.exists()) {
error(new MessageFormat(Main.getString("FileAccessError")).format(new Object[]{root}));
}
setLastLoaded(root);
LOG.log(Level.INFO, "You have selected: {0}", root.getAbsolutePath());
if (root.isDirectory()) {
@Nullable File[] folders = root.listFiles();
boolean valid = true; // TODO: find resource and scripts if there is a parent directory
for (@NotNull File folder : folders != null ? folders : new File[0]) {
if (folder.isDirectory() &&
("resource".equalsIgnoreCase(folder.getName()) || "scripts".equalsIgnoreCase(folder.getName()))) {
valid = true;
break;
}
}
if (!valid) {
error("Selection not valid. Please choose a folder containing \'resources\' or \'scripts\'.");
locateHudDirectory();
return null;
}
@NotNull DefaultMutableTreeNode project = new DefaultMutableTreeNode(root.getName());
recurseDirectoryToNode(new LocalFileProvider(root), project);
return project;
}
if (root.getName().endsWith("_dir.vpk")) {
@NotNull DefaultMutableTreeNode project = new DefaultMutableTreeNode(root.getName());
recurseDirectoryToNode(VPK.loadArchive(root), project);
return project;
}
return null;
}
void changeResolution() {
spinnerWidth.setEnabled(false);
spinnerHeight.setEnabled(false);
@NotNull final JComboBox<String> dropDown = new JComboBox<>();
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
@NotNull Collection<String> listItems = new LinkedList<>();
for (@NotNull GraphicsDevice device : env.getScreenDevices()) {
for (@NotNull DisplayMode resolution : device.getDisplayModes()) { // TF2 has different resolutions
@NotNull String item = resolution.getWidth() + "x" + resolution.getHeight(); // TODO: Work out aspect ratios
if (!listItems.contains(item)) {
listItems.add(item);
}
}
}
dropDown.addItem("Custom");
for (String listItem : listItems) {
dropDown.addItem(listItem);
}
dropDown.setSelectedIndex(1);
dropDown.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String item = dropDown.getSelectedItem().toString();
boolean isRes = item.contains("x");
spinnerWidth.setEnabled(!isRes);
spinnerHeight.setEnabled(!isRes);
if (isRes) {
@NotNull String[] xy = item.split("x");
spinnerWidth.setValue(Integer.parseInt(xy[0]));
spinnerHeight.setValue(Integer.parseInt(xy[1]));
}
}
});
@NotNull Object[] message = {
"Presets: ", dropDown, "Width: ", spinnerWidth, "Height: ", spinnerHeight
};
@NotNull JOptionPane optionPane = new JOptionPane(message,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION,
null,
null);
JDialog dialog = optionPane.createDialog(this, "Change resolution...");
dialog.setContentPane(optionPane);
dialog.pack();
dialog.setVisible(true);
if (optionPane.getValue() != null) {
int value = ((Number) optionPane.getValue()).intValue();
if (value == JOptionPane.YES_OPTION) {
canvas.setPreferredSize(new Dimension(Integer.parseInt(spinnerWidth.getValue().toString()),
Integer.parseInt(spinnerHeight.getValue().toString())));
}
}
}
void mount(final int appID) {
new SwingWorker<DefaultMutableTreeNode, Void>() {
@Nullable
@Override
protected DefaultMutableTreeNode doInBackground() throws Exception {
LOG.log(Level.INFO, "Mounting {0}", appID);
@Nullable final ExtendedVFile a = ACF.fromManifest(appID);
canvas.getR().registerLocator(new ResourceLocator() {
@Nullable
@Override
public InputStream locate(String path) {
path = path.replace('\\', '/').toLowerCase();
if (path.startsWith("..")) path = "vgui/" + path;
System.out.println("Looking for " + path);
@Nullable SimpleVFile file = a.query("tf/materials/" + path);
if (file == null) return null;
return file.openStream();
}
@Nullable
@Override
public Image locateImage(@NotNull String name) {
@NotNull String vtfName = name;
if (!name.endsWith(".vtf")) { // It could be a vmt
vtfName += ".vtf";
@Nullable InputStream vmtStream = locate(name + ".vmt");
if (vmtStream != null) {
try {
@NotNull VMT.VMTNode vmt = VMT.load(vmtStream);
@NotNull String next = (String) vmt.root.getValue("$baseTexture");
if (!next.equals(name)) return locateImage(next); // Stop recursion
} catch (IOException e) {
LOG.log(Level.SEVERE, null, e);
}
}
}
// It's a vtf
@Nullable InputStream vtfStream = locate(vtfName);
if (vtfStream != null) {
try {
@Nullable VTF vtf = VTF.load(vtfStream);
if (vtf == null) return null;
return vtf.getImage(0);
} catch (IOException e) {
LOG.log(Level.SEVERE, null, e);
}
}
return null;
}
});
@NotNull DefaultMutableTreeNode child = new DefaultMutableTreeNode(a);
recurseDirectoryToNode(a, child);
return child;
}
@Override
protected void done() {
try {
DefaultMutableTreeNode g = get();
if (g != null) {
archiveRoot.add(g);
fileModel.reload(archiveRoot);
LOG.log(Level.INFO, "Mounted {0}", appID);
}
} catch (@NotNull InterruptedException | ExecutionException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
}.execute();
}
void setLastLoaded(@Nullable File root) {
editorMenuBar.reloadItem.setEnabled(root != null);
if ((root == null) || !root.exists()) return;
lastLoaded = root;
Main.prefs.put("lastLoaded", root.getPath());
}
void loadProps(@NotNull Element element) {
propTable.clear();
@NotNull DefaultTableModel model = propTable.getModel();
if (!element.getProps().isEmpty()) {
element.validateDisplay();
for (int i = 0; i < element.getProps().size(); i++) {
VDFProperty entry = element.getProps().get(i);
if ("\\n".equals(entry.getKey())) continue;
model.addRow(new Object[]{entry.getKey(), entry.getValue(), entry.getInfo()});
}
model.fireTableDataChanged();
propTable.repaint();
}
}
} |
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;
import static spark.Spark.get;
public class SignUpServer {
Gson gson = new Gson();
public SignUpServer() {
checkUser();
}
User user = new User();
// set default userlist
String [] userlist = {"a","b","c","d"};
private void checkUser() {
get("/api/checkuser", (req, res) -> {
console.log(req.params);
//String username =request
// Map<String, Object> data = new HashMap<>();
// data.put("title", "Professor");
// data.put("name", "Brian");
// data.put("description", "INFSCI 2560");
// data.put("profession", "Education");
//return data;
}, gson::toJson);
get("/api/time/now", (req, res) -> {
Map<String, Object> data = new HashMap<>();
data.put("currentTime", new Date());
return data;
}, gson::toJson);
get("/api/time/now.xml", (req, res) -> {
Map<String, Object> data = new HashMap<>();
data.put("currentTime", new Date());
return data;
}, gson::toJson);
}
} |
package com.wepay.model.data;
import org.json.*;
public class PrefillInfoData {
public String name;
public String email;
public String phone_number;
public String address;
public String city;
public String state;
public Integer zip;
public String country;
public String region;
public String postcode;
public static JSONObject buildPrefillInfo(PrefillInfoData info) throws JSONException {
JSONObject o = new JSONObject();
o.put("name", info.name);
o.put("email", info.email);
o.put("phone_number", info.phone_number);
o.put("address", info.address);
o.put("city", info.city);
o.put("state", info.state);
o.put("zip", info.zip);
o.put("country", info.country);
o.put("region", info.region);
o.put("postcode", info.postcode);
return o;
}
} |
package utils;
import controllers.UserApp;
import models.User;
import play.api.mvc.PlainResult;
import play.mvc.Http;
import play.mvc.Result;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class AccessLogger {
/**
* {@code value} null "-", .
*
* @param value
* @return {@code value} null {@code "-"}, {@code value}
*/
static private String orHyphen(String value) {
if (value == null || value.isEmpty()) {
return "-";
} else {
return value;
}
}
/**
* {@code value} null "-", .
*
* @param value
* @return {@code value} null {@code "-"}, {@code value}
*/
static private String quotedOrHyphen(String value) {
if (value == null) {
return "-";
} else {
return "\"" + value + "\"";
}
}
public static Result log(Http.Request request, Result result, Long startTimeMillis) {
if (!(result.getWrappedResult() instanceof play.api.mvc.PlainResult)) {
return result;
}
int status = ((PlainResult) result.getWrappedResult()).header().status();
log(request, UserApp.currentUser().loginId, status, startTimeMillis);
return result;
}
public static void log(Http.RequestHeader request, String username, int status) {
log(request, username, status, null);
}
private static void log(Http.RequestHeader request, String username, int status,
Long startTimeMillis) {
if (request == null) {
return;
}
SimpleDateFormat format = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
String time = (startTimeMillis != null) ?
((System.currentTimeMillis() - startTimeMillis) + "ms") : "-";
String uri = request.uri();
String entry = String.format("%s - %s [%s] \"%s %s %s\" %d - %s %s %s",
request.remoteAddress(), orHyphen(username),
format.format(new Date()), request.method(), request.uri(),
request.version(), status,
quotedOrHyphen(request.getHeader("Referer")),
quotedOrHyphen(request.getHeader("User-Agent")),
time);
play.Logger.of("access." + uri).info(entry);
}
} |
package com.wizzardo.http;
import com.wizzardo.epoll.ByteBufferProvider;
import com.wizzardo.epoll.EpollServer;
import com.wizzardo.epoll.IOThread;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public abstract class AbstractHttpServer<T extends HttpConnection> extends EpollServer<T> {
private BlockingQueue<T> queue = new LinkedBlockingQueue<>();
private int workersCount;
private int sessionTimeoutSec = 30 * 60;
protected MimeProvider mimeProvider;
public AbstractHttpServer(int port) {
this(null, port);
}
public AbstractHttpServer(String host, int port) {
this(host, port, 0);
}
public AbstractHttpServer(String host, int port, int workersCount) {
super(host, port);
this.workersCount = workersCount;
System.out.println("worker count: " + workersCount);
for (int i = 0; i < workersCount; i++) {
createWorker(queue, "worker_" + i).start();
}
}
protected Worker<T> createWorker(BlockingQueue<T> queue, String name) {
return new Worker<T>(queue, name) {
@Override
protected void process(T connection) {
if (!connection.processingBy.compareAndSet(null, this))
return;
if (checkData(connection, this))
while (processConnection(connection)) {
}
connection.processingBy.set(null);
}
};
}
@Override
public void run() {
Session.createSessionsHolder(sessionTimeoutSec);
super.run();
}
@Override
protected T createConnection(int fd, int ip, int port) {
return (T) new HttpConnection(fd, ip, port, this);
}
@Override
protected IOThread<T> createIOThread(int number, int divider) {
return new HttpIOThread(number, divider);
}
private class HttpIOThread extends IOThread<T> {
public HttpIOThread(int number, int divider) {
super(number, divider);
}
@Override
public void onRead(T connection) {
if (connection.processInputListener())
return;
process(connection);
}
@Override
public void onDisconnect(T connection) {
super.onDisconnect(connection);
// System.out.println("close " + connection);
}
}
protected boolean checkData(T connection, ByteBufferProvider bufferProvider) {
ByteBuffer b;
try {
while ((b = connection.read(connection.getBufferSize(), bufferProvider)).limit() > 0) {
if (connection.check(b))
break;
}
if (!connection.isRequestReady())
return false;
} catch (IOException e) {
e.printStackTrace();
try {
connection.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return false;
}
return true;
}
private void process(T connection) {
if (workersCount > 0) {
queue.add(connection);
} else if (checkData(connection, this))
while (processConnection(connection)) {
}
}
protected boolean processConnection(T connection) {
try {
handle(connection);
return finishHandling(connection);
} catch (Exception t) {
try {
onError(connection, t);
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
protected abstract void handle(T connection) throws Exception;
protected void onError(T connection, Exception e) {
e.printStackTrace();
//TODO render error page
}
protected boolean finishHandling(T connection) throws IOException {
if (connection.getResponse().isAsync())
return false;
connection.getResponse().commit(connection);
connection.flushOutputStream();
if (!connection.onFinishingHandling())
return false;
if (connection.isRequestReady())
return true;
else if (connection.isReadyToRead() && checkData(connection, (ByteBufferProvider) Thread.currentThread()))
return true;
return false;
}
public void setSessionTimeout(int sec) {
this.sessionTimeoutSec = sec;
}
public MimeProvider getMimeProvider() {
if (mimeProvider == null)
mimeProvider = createMimeProvider();
return mimeProvider;
}
protected MimeProvider createMimeProvider() {
return new MimeProvider();
}
} |
package housing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class Bank {
// General fields
private Config config = Model.config; // Passes the Model's configuration parameters object to a private field
private CentralBank centralBank; // Connection to the central bank to ask for policy
// Bank fields
public HashSet<MortgageAgreement> mortgages; // All unpaid mortgage contracts supplied by the bank
public double interestSpread; // Current mortgage interest spread above base rate (monthly rate*12)
private double monthlyPaymentFactor; // Monthly payment as a fraction of the principal for non-BTL mortgages
private double monthlyPaymentFactorBTL; // Monthly payment as a fraction of the principal for BTL (interest-only) mortgages
// LTI tracking fields
private int nFTBMortOverSoftMaxLTI_New; // Number of new mortgages to first-time buyers over the soft maximum LTI underwritten this month
private int nFTBMortOverSoftMaxLTI_Acc; // Number of mortgages to FTBs over the soft maximum LTI accumulated over (CENTRAL_BANK_LTI_MONTHS_TO_CHECK - 1) months
private ArrayList<Integer> nFTBMortOverSoftMaxLTI_List; // List to store the number of new mortgages to FTBs over the soft maximum LTI for (CENTRAL_BANK_LTI_MONTHS_TO_CHECK - 1) months
private int nFTBMortgages_New; // Total number of new mortgages to first-time buyers
private int nFTBMortgages_Acc; // Total number of mortgages to FTBs accumulated over (CENTRAL_BANK_LTI_MONTHS_TO_CHECK - 1) months
private ArrayList<Integer> nFTBMortgages_List; // List to store the number of new mortgages to FTBs for (CENTRAL_BANK_LTI_MONTHS_TO_CHECK - 1) months
private int nHMMortOverSoftMaxLTI_New; // Number of new mortgages to home movers over the soft maximum LTI
private int nHMMortOverSoftMaxLTI_Acc; // Number of mortgages to HMs over the soft maximum LTI accumulated over (CENTRAL_BANK_LTI_MONTHS_TO_CHECK - 1) months
private ArrayList<Integer> nHMMortOverSoftMaxLTI_List; // List to store the number of new mortgages to HMs over the soft maximum LTI for (CENTRAL_BANK_LTI_MONTHS_TO_CHECK - 1) months
private int nHMMortgages_New; // Total number of new mortgages to home movers
private int nHMMortgages_Acc; // Total number of mortgages to HMs accumulated over (CENTRAL_BANK_LTI_MONTHS_TO_CHECK - 1) months
private ArrayList<Integer> nHMMortgages_List; // List to store the number of new mortgages to HMs for (CENTRAL_BANK_LTI_MONTHS_TO_CHECK - 1) months
// Credit supply strategy fields
private double supplyTarget; // Target supply of mortgage lending (pounds)
private double supplyVal; // Monthly supply of mortgage lending (pounds)
// LTV internal policy thresholds
private double firstTimeBuyerHardMaxLTV; // Loan-To-Value hard maximum for first-time buyer mortgages
private double homeMoverHardMaxLTV; // Loan-To-Value hard maximum for home mover mortgages
private double buyToLetHardMaxLTV; // Loan-To-Value hard maximum for buy-to-let mortgages
// LTI internal policy thresholds
private double firstTimeBuyerHardMaxLTI; // Loan-To-Income hard maximum for first-time buyer mortgages
private double homeMoverHardMaxLTI; // Loan-To-Income hard maximum for home mover mortgages
// Affordability internal policy thresholds
private double hardMaxAffordability; // Affordability hard maximum (monthly mortgage payment / household's monthly net employment income)
// ICR internal policy thresholds
private double hardMinICR; // ICR hard minimum for the ratio of expected rental yield over interest monthly payment
public Bank(CentralBank centralBank) {
this.centralBank = centralBank;
mortgages = new HashSet<>();
nFTBMortOverSoftMaxLTI_List = new ArrayList<>();
nFTBMortgages_List = new ArrayList<>();
nHMMortOverSoftMaxLTI_List = new ArrayList<>();
nHMMortgages_List = new ArrayList<>();
}
void init() {
mortgages.clear();
initLTICounters();
setMortgageInterestRate(config.BANK_INITIAL_RATE); // Central Bank must already be initiated at this point!
resetMonthlyCounters();
// Setup initial LTV internal policy thresholds
firstTimeBuyerHardMaxLTV = config.BANK_LTV_HARD_MAX_FTB;
homeMoverHardMaxLTV = config.BANK_LTV_HARD_MAX_HM;
buyToLetHardMaxLTV = config.BANK_LTV_HARD_MAX_BTL;
// Setup initial LTI internal policy thresholds
firstTimeBuyerHardMaxLTI = config.BANK_LTI_HARD_MAX_FTB;
homeMoverHardMaxLTI = config.BANK_LTI_HARD_MAX_HM;
// Set initial affordability internal policy thresholds
hardMaxAffordability = config.BANK_AFFORDABILITY_HARD_MAX;
// Set initial ICR internal policy thresholds
hardMinICR = config.BANK_ICR_HARD_MIN;
}
private void initLTICounters() {
nFTBMortOverSoftMaxLTI_New = 0;
nFTBMortOverSoftMaxLTI_Acc = 0;
nFTBMortOverSoftMaxLTI_List.clear();
nFTBMortOverSoftMaxLTI_List.addAll(Collections.nCopies(centralBank.getMonthsToCheckLTI() - 1, 0));
nFTBMortgages_New = 0;
nFTBMortgages_Acc = 0;
nFTBMortgages_List.clear();
nFTBMortgages_List.addAll(Collections.nCopies(centralBank.getMonthsToCheckLTI() - 1, 0));
nHMMortOverSoftMaxLTI_New = 0;
nHMMortOverSoftMaxLTI_Acc = 0;
nHMMortOverSoftMaxLTI_List.clear();
nHMMortOverSoftMaxLTI_List.addAll(Collections.nCopies(centralBank.getMonthsToCheckLTI() - 1, 0));
nHMMortgages_New = 0;
nHMMortgages_Acc = 0;
nHMMortgages_List.clear();
nHMMortgages_List.addAll(Collections.nCopies(centralBank.getMonthsToCheckLTI() - 1, 0));
}
/**
* Redo all necessary monthly calculations and reset counters.
*
* @param totalPopulation Current population in the model, needed to scale the target amount of credit
*/
public void step(int totalPopulation) {
supplyTarget = config.BANK_CREDIT_SUPPLY_TARGET * totalPopulation;
setMortgageInterestRate(recalculateInterestRate());
resetMonthlyCounters();
}
/**
* Reset counters for the next month.
*/
private void resetMonthlyCounters() {
// Reset to zero the monthly credit supply counter
supplyVal = 0.0;
// Reset moving counter of first-time buyer mortgages over their soft maximum LTI
nFTBMortOverSoftMaxLTI_Acc -= nFTBMortOverSoftMaxLTI_List.remove(0); // Remove oldest month from list and subtract it from accumulated sum
nFTBMortOverSoftMaxLTI_Acc += nFTBMortOverSoftMaxLTI_New; // Add most recent month to accumulated sum
nFTBMortOverSoftMaxLTI_List.add(nFTBMortOverSoftMaxLTI_New); // Add most recent month to list
nFTBMortOverSoftMaxLTI_New = 0; // Reset new mortgages counter to zero for next time step
// Reset moving counter of first-time buyer mortgages
nFTBMortgages_Acc -= nFTBMortgages_List.remove(0); // Remove oldest month from list and subtract it from accumulated sum
nFTBMortgages_Acc += nFTBMortgages_New; // Add most recent month to accumulated sum
nFTBMortgages_List.add(nFTBMortgages_New); // Add most recent month to list
nFTBMortgages_New = 0; // Reset new mortgages counter to zero for next time step
// Reset moving counter of home mover mortgages over their soft maximum LTI
nHMMortOverSoftMaxLTI_Acc -= nHMMortOverSoftMaxLTI_List.remove(0); // Remove oldest month from list and subtract it from accumulated sum
nHMMortOverSoftMaxLTI_Acc += nHMMortOverSoftMaxLTI_New; // Add most recent month to accumulated sum
nHMMortOverSoftMaxLTI_List.add(nHMMortOverSoftMaxLTI_New); // Add most recent month to list
nHMMortOverSoftMaxLTI_New = 0; // Reset new mortgages counter to zero for next time step
// Reset moving counter of home mover mortgages
nHMMortgages_Acc -= nHMMortgages_List.remove(0); // Remove oldest month from list and subtract it from accumulated sum
nHMMortgages_Acc += nHMMortgages_New; // Add most recent month to accumulated sum
nHMMortgages_List.add(nHMMortgages_New); // Add most recent month to list
nHMMortgages_New = 0; // Reset new mortgages counter to zero for next time step
}
/**
* Calculate the mortgage interest rate for next month based on the rate for this month and the resulting demand for
* credit, which in this model is equivalent to supply. This assumes a linear relationship between interest rate and
* the excess demand for credit over the target level, and aims to bring this excess demand to zero at a speed
* proportional to the excess.
*/
private double recalculateInterestRate() {
// TODO: Remove 1/2 factor and invert parameter BANK_D_DEMAND_D_INTEREST to turn division into product
double rate = getMortgageInterestRate() + 0.5 * (supplyVal - supplyTarget) / config.BANK_D_DEMAND_D_INTEREST;
if (rate < centralBank.getBaseRate()) rate = centralBank.getBaseRate();
return rate;
}
/**
* Get the interest rate on mortgages.
*/
public double getMortgageInterestRate() { return centralBank.getBaseRate() + interestSpread; }
/**
* Set the interest rate on mortgages.
*/
private void setMortgageInterestRate(double rate) {
interestSpread = rate - centralBank.getBaseRate();
recalculateMonthlyPaymentFactor();
}
/**
* Compute the monthly payment factor, i.e., the monthly payment on a mortgage as a fraction of the mortgage
* principal, for both BTL (interest-only) and non-BTL mortgages.
*/
private void recalculateMonthlyPaymentFactor() {
double r = getMortgageInterestRate() / config.constants.MONTHS_IN_YEAR;
monthlyPaymentFactor = r / (1.0 - Math.pow(1.0 + r, -config.derivedParams.N_PAYMENTS));
monthlyPaymentFactorBTL = r;
}
/**
* Get the monthly payment factor, i.e., the monthly payment on a mortgage as a fraction of the mortgage principal.
*/
private double getMonthlyPaymentFactor(boolean isHome) {
if (isHome) {
return monthlyPaymentFactor; // Monthly payment factor to pay off the principal in N_PAYMENTS
} else {
return monthlyPaymentFactorBTL; // Monthly payment factor for interest-only mortgages
}
}
/**
* Arrange a mortgage contract and get a MortgageAgreement object, which is added to the Bank's HashSet of mortgages
* and entered into CreditSupply statistics.
*
* @param h The household requesting the mortgage
* @param housePrice The price of the house that household h wants to buy
* @param isHome True if household h plans to live in the house (non-BTL mortgage)
* @return The MortgageApproval object
*/
MortgageAgreement requestLoan(Household h, double housePrice, double desiredDownPayment, boolean isHome) {
// Request the mortgage and create the MortgageAgreement object with all the required parameters
MortgageAgreement approval = requestApproval(h, housePrice, desiredDownPayment, isHome);
// If this is an actual mortgage, i.e., with a non-zero principal...
if (approval.principal > 0.0) {
// ...add it to the Bank's HashSet of mortgages
mortgages.add(approval);
// ...add the principal to the new supply/demand of credit
supplyVal += approval.principal;
// ...update various statistics at CreditSupply
Model.creditSupply.recordLoan(h, approval);
// ... count the number of non-BTL mortgages over the soft LTI limit imposed by the Central Bank...
if (isHome) {
// ...differentiating between first-time buyers
if (h.isFirstTimeBuyer()) {
++nFTBMortgages_New;
if (approval.principal > h.getAnnualGrossEmploymentIncome()
* centralBank.getFirstTimeBuyerSoftMaxLTI()) {
++nFTBMortOverSoftMaxLTI_New;
}
// ...and home movers
} else {
++nHMMortgages_New;
if (approval.principal > h.getAnnualGrossEmploymentIncome()
* centralBank.getHomeMoverSoftMaxLTI()) {
++nHMMortOverSoftMaxLTI_New;
}
}
}
}
return approval;
}
/**
* Request a mortgage approval without actually signing a mortgage contract, i.e., the returned
* MortgageAgreement object is not added to the Bank's HashSet of mortgages nor entered into CreditSupply
* statistics. This is useful for households to explore the details of the best available mortgage contract before
* deciding whether to actually go ahead and sign it.
*
* @param h The household requesting the mortgage
* @param housePrice The price of the house that household h wants to buy
* @param isHome True if household h plans to live in the house (non-BTL mortgage)
* @return The MortgageApproval object
*/
MortgageAgreement requestApproval(Household h, double housePrice, double desiredDownPayment, boolean isHome) {
// Create a MortgageAgreement object to store and return the new mortgage data
MortgageAgreement approval = new MortgageAgreement(h, !isHome);
/*
* Constraints for all mortgages
*/
// Loan-To-Value (LTV) constraint: it sets a maximum value for the ratio of the principal divided by the house
// price
approval.principal = housePrice * getLoanToValueLimit(h.isFirstTimeBuyer(), isHome);
/*
* Constraints specific to non-BTL mortgages
*/
if (isHome) {
// Affordability constraint: it sets a maximum value for the monthly mortgage payment divided by the
// household's monthly net employment income
double affordable_principal = getHardMaxAffordability() * h.getMonthlyNetEmploymentIncome()
/ getMonthlyPaymentFactor(true);
approval.principal = Math.min(approval.principal, affordable_principal);
// Loan-To-Income (LTI) constraint: it sets a maximum value for the principal divided by the household's
// annual gross employment income
double lti_principal = h.getAnnualGrossEmploymentIncome() * getLoanToIncomeLimit(h.isFirstTimeBuyer());
approval.principal = Math.min(approval.principal, lti_principal);
/*
* Constraints specific to BTL mortgages
*/
} else {
// Interest Coverage Ratio (ICR) constraint: it sets a minimum value for the expected annual rental income
// divided by the annual interest expenses
double icr_principal = Model.rentalMarketStats.getExpAvFlowYield() * housePrice
/ (getHardMinICR() * getMortgageInterestRate());
approval.principal = Math.min(approval.principal, icr_principal);
}
/*
* Compute the down-payment
*/
// Start by assuming the minimum possible down-payment, i.e., that resulting from the above maximisation of the
// principal available to the household, given its chosen house price
approval.downPayment = housePrice - approval.principal;
// Determine the liquid wealth of the household, with no home equity added, as home-movers always sell their
// homes before bidding for new ones
double liquidWealth = h.getBankBalance();
// Ensure desired down-payment is between zero and the house price, capped also by the household's liquid wealth
if (desiredDownPayment < 0.0) desiredDownPayment = 0.0;
if (desiredDownPayment > housePrice) desiredDownPayment = housePrice;
if (desiredDownPayment > liquidWealth) desiredDownPayment = liquidWealth;
// If the desired down-payment is larger than the initially assumed minimum possible down-payment, then set the
// down-payment to the desired value and update the principal accordingly
if (desiredDownPayment > approval.downPayment) {
approval.downPayment = desiredDownPayment;
approval.principal = housePrice - desiredDownPayment;
}
/*
* Set the rest of the variables of the MortgageAgreement object
*/
approval.monthlyPayment = approval.principal * getMonthlyPaymentFactor(isHome);
approval.nPayments = config.derivedParams.N_PAYMENTS;
approval.monthlyInterestRate = getMortgageInterestRate() / config.constants.MONTHS_IN_YEAR;
approval.purchasePrice = approval.principal + approval.downPayment;
// Throw error and stop program if requested mortgage has down-payment larger than household's liquid wealth
if (approval.downPayment > liquidWealth) {
System.out.println("Error at Bank.requestApproval(), down-payment larger than household's bank balance: "
+ "downpayment = " + approval.downPayment + ", bank balance = " + liquidWealth);
System.exit(0);
}
return approval;
}
/**
* Find, for a given household, the maximum house price that this mortgage-lender is willing to approve a mortgage
* for. That is, this method assumes the household will use its total liquid wealth as deposit, thus maximising
* leverage. Regarding the application of the hard/soft LTI limit, there is a further assumption here that the
* household is always bound by the most constraining limit, whether the soft or the hard. This is due to the fact
* that it is impossible to know, at this point, which limit would be applied to this household once a formal
* mortgage is requested.
*
* @param h The household applying for the mortgage
* @param isHome True if household h plans to live in the house (non-BTL mortgage)
* @return A double with the maximum house price that this mortgage-lender is willing to approve a mortgage for
*/
double getMaxMortgagePrice(Household h, boolean isHome) {
// First, maximise leverage by maximising the down-payment, thus using all the liquid wealth of the household
// (except 1 cent to avoid rounding errors), with no home equity added, as home-movers always sell their homes
// before bidding for new ones
double max_downpayment = h.getBankBalance() - 0.01;
/*
* Constraints for all mortgages
*/
// Loan-To-Value (LTV) constraint: it sets a maximum value for the ratio of the principal divided by the house
// price, thus setting a maximum house price given a fixed (maximised) down-payment
double max_price = max_downpayment / (1.0 - getLoanToValueLimit(h.isFirstTimeBuyer(), isHome));
/*
* Constraints specific to non-BTL mortgages
*/
if (isHome) {
// Affordability constraint: it sets a maximum value for the monthly mortgage payment divided by the
// household's monthly net employment income
double affordable_max_price = max_downpayment + getHardMaxAffordability()
* h.getMonthlyNetEmploymentIncome() / getMonthlyPaymentFactor(true);
max_price = Math.min(max_price, affordable_max_price);
// Loan-To-Income (LTI) constraint: it sets a maximum value for the principal divided by the household's
// annual gross employment income. The lowest LTI limit is used, since it is impossible to know yet which
// limit would be applied to this household once a formal mortgage is requested
double lti_max_price = max_downpayment + h.getAnnualGrossEmploymentIncome()
* getLoanToIncomeLowestLimit(h.isFirstTimeBuyer());
max_price = Math.min(max_price, lti_max_price);
/*
* Constraints specific to BTL mortgages
*/
} else {
// Interest Coverage Ratio (ICR) constraint: it sets a minimum value for the expected annual rental income
// divided by the annual interest expenses
double icr_max_price = max_downpayment / (1.0 - Model.rentalMarketStats.getExpAvFlowYield()
/ (getHardMinICR() * getMortgageInterestRate()));
// When the rental yield is larger than the interest rate times the ICR, then the ICR does never constrain
if (icr_max_price < 0.0) icr_max_price = Double.POSITIVE_INFINITY;
max_price = Math.min(max_price, icr_max_price);
}
return max_price;
}
/**
* End a mortgage contract by removing it from the Bank's HashSet of mortgages
*
* @param mortgage The MortgageAgreement object to be removed
*/
void endMortgageContract(MortgageAgreement mortgage) { mortgages.remove(mortgage); }
/**
* Get the Loan-To-Value ratio limit currently applicable to a given type of household (first-time buyer, home mover
* or buy-to-let investor). Note that this limit is defined as the minimum between the private bank self-imposed
* internal policy limit and the central bank mandatory policy limit.
*
* @param isFirstTimeBuyer True if the household is a first-time buyer
* @param isHome True if the mortgage is to buy a home for the household (non-BTL mortgage)
* @return The Loan-To-Value ratio limit applicable to this type of household
*/
private double getLoanToValueLimit(boolean isFirstTimeBuyer, boolean isHome) {
if (isHome) {
if (isFirstTimeBuyer) {
return Math.min(firstTimeBuyerHardMaxLTV, centralBank.getFirstTimeBuyerHardMaxLTV());
} else {
return Math.min(homeMoverHardMaxLTV, centralBank.getHomeMoverHardMaxLTV());
}
}
return Math.min(buyToLetHardMaxLTV, centralBank.getBuyToLetHardMaxLTV());
}
/**
* Get the Loan-To-Income ratio limit currently applicable to a given type of household, whether first-time buyer or
* home mover (that is, this constraint is applicable only to non-BTL mortgages). The private bank always imposes
* its own internal hard limit. Apart from this, it also imposes the Central Bank regulated soft limit, which allows
* for a certain fraction of non-BTL loans to go over this soft limit. This fraction of mortgages allowed to exceed
* the soft limit is measure on a rolling basis with a window of (CENTRAL_BANK_LTI_MONTHS_TO_CHECK - 1) months
* previous to the current one plus the current one.
*
* @param isFirstTimeBuyer True if the household is a first-time buyer
* @return The Loan-To-Income ratio limit currently applicable to this type of household
*/
private double getLoanToIncomeLimit(boolean isFirstTimeBuyer) {
// If the maximum fractions of mortgages over their soft LTI limits allowed by the Central Bank for FTBs and HMs
// are the same, then the quota is shared by FTBs and HMs, instead of having separate quotas
if (centralBank.getFirstTimeBuyerMaxFracOverSoftMaxLTI() == centralBank.getHomeMoverMaxFracOverSoftMaxLTI()) {
// If this mortgage could bring the fraction of mortgages (FTB + HM) underwritten over the Central Bank LTI
// soft limit to exceed the maximum fraction established by the Central Bank (same for FTB and HM)...
if ((double)(nFTBMortOverSoftMaxLTI_Acc + nFTBMortOverSoftMaxLTI_New
+ nHMMortOverSoftMaxLTI_Acc + nHMMortOverSoftMaxLTI_New + 1)
/ (nFTBMortgages_Acc + nFTBMortgages_New
+ nHMMortgages_Acc + nHMMortgages_New + 1)
> centralBank.getFirstTimeBuyerMaxFracOverSoftMaxLTI()) {
// ... then use the minimum between the Central Bank soft limit and the private bank hard limit, for
// either first-time buyers or home movers
if (isFirstTimeBuyer) {
return Math.min(firstTimeBuyerHardMaxLTI, centralBank.getFirstTimeBuyerSoftMaxLTI());
} else {
return Math.min(homeMoverHardMaxLTI, centralBank.getHomeMoverSoftMaxLTI());
}
// ...otherwise...
} else {
// ...simply use the private bank self-imposed hard maximum, for either first-time buyers or home movers
if (isFirstTimeBuyer) {
return firstTimeBuyerHardMaxLTI;
} else {
return homeMoverHardMaxLTI;
}
}
// Otherwise, FTBs and HMs keep separate quotas for mortgages over their respective LTI limits
} else {
// For first-time buyers...
if (isFirstTimeBuyer) {
// ...if this mortgage could bring the fraction of mortgages underwritten over the Central Bank LTI soft
// limit to exceed the maximum fraction established by the Central Bank...
if ((double) (nFTBMortOverSoftMaxLTI_Acc + nFTBMortOverSoftMaxLTI_New + 1)
/ (nFTBMortgages_Acc + nFTBMortgages_New + 1)
> centralBank.getFirstTimeBuyerMaxFracOverSoftMaxLTI()) {
// ... then use the minimum between the Central Bank soft limit and the private bank hard limit
return Math.min(firstTimeBuyerHardMaxLTI, centralBank.getFirstTimeBuyerSoftMaxLTI());
// ...otherwise...
} else {
// ...simply use the private bank self-imposed hard maximum
return firstTimeBuyerHardMaxLTI;
}
// For home movers...
} else {
// ...if this mortgage could bring the fraction of mortgages underwritten over the Central Bank LTI soft
// limit to exceed the maximum fraction established by the Central Bank...
if ((double) (nHMMortOverSoftMaxLTI_Acc + nHMMortOverSoftMaxLTI_New + 1)
/ (nHMMortgages_Acc + nHMMortgages_New + 1)
> centralBank.getHomeMoverMaxFracOverSoftMaxLTI()) {
// ... then use the minimum between the Central Bank soft limit and the private bank hard limit
return Math.min(homeMoverHardMaxLTI, centralBank.getHomeMoverSoftMaxLTI());
// ...otherwise...
} else {
// ...simply use the private bank self-imposed hard maximum
return homeMoverHardMaxLTI;
}
}
}
}
/**
* Get the most constraining Loan-To-Income ratio limit potentially applicable to a given type of household, whether
* first-time buyer or home mover (that is, this constraint is applicable only to non-BTL mortgages). This method is
* used by the bank when computing the maximum mortgage price available to a given household, and the reason to use
* the most constraining (lowest) limit is that, at that point, it is impossible to know which limit (soft or hard)
* will actually apply to the given household when a formal mortgage request is done. Thus, for security, the most
* constraining limit is used.
*
* @param isFirstTimeBuyer True if the household is a first-time buyer
* @return The lowes Loan-To-Income ratio limit potentially applicable to this type of household
*/
private double getLoanToIncomeLowestLimit(boolean isFirstTimeBuyer) {
// For first-time buyers...
if (isFirstTimeBuyer) {
// ...use the minimum between the Central Bank soft limit and the private bank hard limit
return Math.min(firstTimeBuyerHardMaxLTI, centralBank.getFirstTimeBuyerSoftMaxLTI());
// For home movers...
} else {
// ...use the minimum between the Central Bank soft limit and the private bank hard limit
return Math.min(homeMoverHardMaxLTI, centralBank.getHomeMoverSoftMaxLTI());
}
}
/**
* Get the most constraining affordability limit, between the private and the central bank policies
*/
private double getHardMaxAffordability() {
return Math.min(hardMaxAffordability, centralBank.getHardMaxAffordability());
}
/**
* Get the most constraining Interest Coverage Ratio limit, between the private and the central bank policies
*/
private double getHardMinICR() {
return Math.max(hardMinICR, centralBank.getHardMinICR());
}
} |
package de.chandre.quartz.spring;
import java.text.ParseException;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;
public class QuartzUtils {
private QuartzUtils() {}
/**
*
* @return build wrapper for JobDetail
*/
public static QuartzJobBuilder jobBuilder() {
return new QuartzJobBuilder();
}
/**
* build wrapper for JobDetail
* @since 1.0.0
*/
public static class QuartzJobBuilder {
private final JobDetailFactoryBean jobDetailFactoryBean;
public QuartzJobBuilder() {
jobDetailFactoryBean = new JobDetailFactoryBean();
}
/**
* @see JobDetailFactoryBean#setJobClass(Class)
* @param clazz
* @return
*/
public QuartzJobBuilder jobClass(Class<?> clazz) {
jobDetailFactoryBean.setJobClass(clazz);
return this;
}
/**
* @see JobDetailFactoryBean#setBeanName(String)
* @param name
* @return
*/
public QuartzJobBuilder beanName(String beanName) {
jobDetailFactoryBean.setBeanName(beanName);
return this;
}
/**
* @see JobDetailFactoryBean#setName(String)
* @param name
* @return
*/
public QuartzJobBuilder name(String name) {
jobDetailFactoryBean.setName(name);
return this;
}
/**
* @see JobDetailFactoryBean#setGroup(String)
* @param group
* @return
*/
public QuartzJobBuilder group(String group) {
jobDetailFactoryBean.setGroup(group);
return this;
}
/**
* @see JobDetailFactoryBean#setDescription(String)
* @param description
* @return
*/
public QuartzJobBuilder description(String description) {
jobDetailFactoryBean.setDescription(description);
return this;
}
/**
* @see JobDetailFactoryBean#setDurability(boolean)
* @param durability
* @return
*/
public QuartzJobBuilder durability(boolean durability) {
jobDetailFactoryBean.setDurability(durability);
return this;
}
/**
* @see JobDetailFactoryBean#setRequestsRecovery(boolean)
* @param requestRecovery
* @return
*/
public QuartzJobBuilder requestRecovery(boolean requestRecovery) {
jobDetailFactoryBean.setRequestsRecovery(requestRecovery);
return this;
}
/**
* @see JobDetailFactoryBean#setJobDataAsMap(Map)
* @param jobData
* @return
*/
public QuartzJobBuilder putJobData(Map<String, ?> jobData) {
if (null != jobData) {
jobDetailFactoryBean.getJobDataMap().putAll(jobData);
}
return this;
}
/**
* @see JobDetailFactoryBean#setJobDataAsMap(Map)
* @param key
* @param value
* @return
*/
public QuartzJobBuilder addJobData(String key, Object value) {
jobDetailFactoryBean.getJobDataMap().put(key, value);
return this;
}
/**
*
* @return
*/
public JobDetailFactoryBean getJobDetailFactoryBean() {
return jobDetailFactoryBean;
}
/**
*
* @return
*/
public JobDetail build() {
jobDetailFactoryBean.afterPropertiesSet();
return jobDetailFactoryBean.getObject();
}
}
/**
* creates a durable job detail factory bean to put into spring context
* <br><br>
* <code>
* {@literal @}Bean<br>
* public JobDetailFactoryBean simpleJobDetail() {<br>
* return QuartzJobUtils.createJobDetail(SimpleJob.class, "MySimpleJob", null, "Just a Simple Job", null);<br>
* }<br>
* </code>
* Your job class should implement the interface {@link Job}
*
* @param jobClass
* @param jobName (optional)
* @param jobGroup (optional)
* @param jobDdescription (optional)
* @param jobData (optional)
* @return job detail factory
*/
public static JobDetailFactoryBean createJobDetail(Class<?> jobClass, String jobName, String jobGroup,
String jobDdescription, Map<String, ?> jobData) {
return QuartzUtils.jobBuilder().jobClass(jobClass).name(jobName).group(jobGroup).description(jobDdescription)
.putJobData(jobData).durability(true).getJobDetailFactoryBean();
}
/**
* returns a job detail factory bean to put into spring context
*
* <br><br>
* <code>
* {@literal @}Bean<br>
* public JobDetailFactoryBean simpleJobDetail() {<br>
* return QuartzJobUtils.createJobDetail(SimpleJob.class, "MySimpleJob", null, "Just a Simple Job", null, true, false);<br>
* }<br>
* </code>
* Your job class should implement the interface {@link Job}
*
* @param jobClass
* @param jobName (optional)
* @param jobGroup (optional)
* @param jobDdescription (optional)
* @param jobData (optional)
* @param durable
* @param requestsRecovery
*
* @return job detail factory
*/
public static JobDetailFactoryBean createJobDetail(Class<?> jobClass, String jobName, String jobGroup,
String jobDdescription, Map<String, ?> jobData, boolean durable, boolean requestsRecovery) {
return QuartzUtils.jobBuilder().jobClass(jobClass).name(jobName).group(jobGroup).description(jobDdescription)
.putJobData(jobData).durability(durable).requestRecovery(requestsRecovery).getJobDetailFactoryBean();
}
/**
*
* @return build wrapper for simple trigger
*/
public static QuartzSimpleTriggerBuilder simpleTriggerBuilder() {
return new QuartzSimpleTriggerBuilder();
}
/**
* build wrapper for SimpleTrigger
* @since 1.0.0
*/
public static class QuartzSimpleTriggerBuilder {
private final SimpleTriggerFactoryBean triggerFactoryBean;
public QuartzSimpleTriggerBuilder() {
triggerFactoryBean = new SimpleTriggerFactoryBean();
}
/**
* @see SimpleTriggerFactoryBean#setJobDetail(JobDetail)
* @param jobDetail
* @return
*/
public QuartzSimpleTriggerBuilder jobDetail(JobDetail jobDetail) {
triggerFactoryBean.setJobDetail(jobDetail);
return this;
}
/**
* @see SimpleTriggerFactoryBean#setBeanName(String)
* @param name
* @return
*/
public QuartzSimpleTriggerBuilder beanName(String beanName) {
triggerFactoryBean.setBeanName(beanName);
return this;
}
/**
* @see SimpleTriggerFactoryBean#setName(String)
* @param name
* @return
*/
public QuartzSimpleTriggerBuilder name(String name) {
triggerFactoryBean.setName(name);
return this;
}
/**
* @see SimpleTriggerFactoryBean#setGroup(String)
* @param group
* @return
*/
public QuartzSimpleTriggerBuilder group(String group) {
triggerFactoryBean.setGroup(group);
return this;
}
/**
* @see SimpleTriggerFactoryBean#setDescription(String)
* @param description
* @return
*/
public QuartzSimpleTriggerBuilder description(String description) {
triggerFactoryBean.setDescription(description);
return this;
}
/**
* @see SimpleTriggerFactoryBean#setStartDelay(long)
* @param startDelay
* @return
*/
public QuartzSimpleTriggerBuilder startDelay(long startDelay) {
triggerFactoryBean.setStartDelay(startDelay);
return this;
}
/**
* @see SimpleTriggerFactoryBean#setStartTime(Date)
* @param startTime
* @return
*/
public QuartzSimpleTriggerBuilder startTime(Date startTime) {
triggerFactoryBean.setStartTime(startTime);
return this;
}
/**
* @see SimpleTriggerFactoryBean#setMisfireInstruction(int)
* @param misfireInstruction
* @return
*/
public QuartzSimpleTriggerBuilder misfireInstruction(int misfireInstruction) {
triggerFactoryBean.setMisfireInstruction(misfireInstruction);
return this;
}
/**
* @see SimpleTriggerFactoryBean#setMisfireInstructionName(String)
* @param misfireInstructionName
* @return
*/
public QuartzSimpleTriggerBuilder misfireInstructionName(String misfireInstructionName) {
triggerFactoryBean.setMisfireInstructionName(misfireInstructionName);
return this;
}
/**
* @see SimpleTriggerFactoryBean#setPriority(int)
* @param priority
* @return
*/
public QuartzSimpleTriggerBuilder priority(int priority) {
triggerFactoryBean.setPriority(priority);
return this;
}
/**
* @see SimpleTriggerFactoryBean#setRepeatCount(int)
* @param repeatCount
* @return
*/
public QuartzSimpleTriggerBuilder repeatCount(int repeatCount) {
triggerFactoryBean.setRepeatCount(repeatCount);
return this;
}
/**
* @see SimpleTriggerFactoryBean#setRepeatInterval(long)
* @param repeatInterval
* @return
*/
public QuartzSimpleTriggerBuilder repeatInterval(long repeatInterval) {
triggerFactoryBean.setRepeatInterval(repeatInterval);
return this;
}
/**
* @see SimpleTriggerFactoryBean#setJobDataAsMap(Map)
* @param jobData
* @return
*/
public QuartzSimpleTriggerBuilder putJobData(Map<String, ?> jobData) {
if (null != jobData) {
triggerFactoryBean.getJobDataMap().putAll(jobData);
}
return this;
}
/**
* @see SimpleTriggerFactoryBean#setJobDataAsMap(Map)
* @param key
* @param value
* @return
*/
public QuartzSimpleTriggerBuilder addJobData(String key, Object value) {
triggerFactoryBean.getJobDataMap().put(key, value);
return this;
}
public SimpleTriggerFactoryBean getTriggerFactoryBean() {
return triggerFactoryBean;
}
public SimpleTrigger build() throws ParseException {
triggerFactoryBean.afterPropertiesSet();
return triggerFactoryBean.getObject();
}
}
/**
* creates a SimpleTriggerFactoryBean regarding the parameters with {@link SimpleTrigger#REPEAT_INDEFINITELY} and
* {@link SimpleTrigger#MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT}
*
* @see QuartzUtils#createSimpleTrigger(JobDetail, String, String, String, long, long, int, int, Map, int)
*
* @param jobDetail
* @param triggerName (optional)
* @param triggerGroup (optional)
* @param triggerDescription (optional)
* @param startDelay
* @param repeatInterval
* @param jobData (optional)
* @return
*/
public static SimpleTriggerFactoryBean createSimpleTrigger(JobDetail jobDetail, String triggerName,
String triggerGroup, String triggerDescription, long startDelay, long repeatInterval,
Map<String, ?> jobData) {
return QuartzUtils.simpleTriggerBuilder().jobDetail(jobDetail).name(triggerName).group(triggerGroup)
.description(triggerDescription).startDelay(startDelay).repeatInterval(repeatInterval)
.repeatCount(SimpleTrigger.REPEAT_INDEFINITELY)
.misfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT)
.putJobData(jobData).getTriggerFactoryBean();
}
/**
* <br><br>
* <code>
* {@literal @}Bean<br>
* public SimpleTriggerFactoryBean createSimpleTrigger({@literal @}Qualifier("simpleJobDetail") JobDetail jobDetail) {<br>
* return QuartzJobUtils.createSimpleTrigger(jobDetail, null, null, "Simple trigger 1", 5000L, 60000L, SimpleTrigger.REPEAT_INDEFINITELY,
* SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT, null, 1 );<br>
* }<br>
* </code>
*
* @param jobDetail
* @param triggerName (optional)
* @param triggerGroup (optional)
* @param triggerDescription (optional)
* @param startDelay
* @param repeatInterval for infinity: {@link SimpleTrigger#REPEAT_INDEFINITELY}
* @param repeatCount
* @param misfireInstruction {@link SimpleTrigger}
* @param jobData (optional)
* @param priority
* @return
*/
public static SimpleTriggerFactoryBean createSimpleTrigger(
JobDetail jobDetail, String triggerName, String triggerGroup, String triggerDescription,
long startDelay, long repeatInterval, int repeatCount, int misfireInstruction, Map<String, ?> jobData, int priority) {
return QuartzUtils.simpleTriggerBuilder().jobDetail(jobDetail).name(triggerName).group(triggerGroup)
.description(triggerDescription).startDelay(startDelay).repeatInterval(repeatInterval)
.repeatCount(repeatCount).misfireInstruction(misfireInstruction).putJobData(jobData).priority(priority)
.getTriggerFactoryBean();
}
/**
*
* @return build wrapper for cron trigger
*/
public static QuartzCronTriggerBuilder cronTriggerBuilder() {
return new QuartzCronTriggerBuilder();
}
/**
* build wrapper for CronTrigger
* @since 1.0.0
*/
public static class QuartzCronTriggerBuilder {
private final CronTriggerFactoryBean triggerFactoryBean;
public QuartzCronTriggerBuilder() {
triggerFactoryBean = new CronTriggerFactoryBean();
}
/**
* @see CronTriggerFactoryBean#setJobDetail(JobDetail)
* @param jobDetail
* @return
*/
public QuartzCronTriggerBuilder jobDetail(JobDetail jobDetail) {
triggerFactoryBean.setJobDetail(jobDetail);
return this;
}
/**
* @see CronTriggerFactoryBean#setBeanName(String)
* @param name
* @return
*/
public QuartzCronTriggerBuilder beanName(String beanName) {
triggerFactoryBean.setBeanName(beanName);
return this;
}
/**
* @see CronTriggerFactoryBean#setName(String)
* @param name
* @return
*/
public QuartzCronTriggerBuilder name(String name) {
triggerFactoryBean.setName(name);
return this;
}
/**
* @see CronTriggerFactoryBean#setGroup(String)
* @param group
* @return
*/
public QuartzCronTriggerBuilder group(String group) {
triggerFactoryBean.setGroup(group);
return this;
}
/**
* @see CronTriggerFactoryBean#setDescription(String)
* @param description
* @return
*/
public QuartzCronTriggerBuilder description(String description) {
triggerFactoryBean.setDescription(description);
return this;
}
/**
* @see CronTriggerFactoryBean#setCronExpression(String)
* @param cronExpression
* @return
*/
public QuartzCronTriggerBuilder cronExpression(String cronExpression) {
triggerFactoryBean.setCronExpression(cronExpression);
return this;
}
/**
* @see CronTriggerFactoryBean#setStartDelay(long)
* @param startDelay
* @return
*/
public QuartzCronTriggerBuilder startDelay(long startDelay) {
triggerFactoryBean.setStartDelay(startDelay);
return this;
}
/**
* @see CronTriggerFactoryBean#setStartTime(Date)
* @param startTime
* @return
*/
public QuartzCronTriggerBuilder startTime(Date startTime) {
triggerFactoryBean.setStartTime(startTime);
return this;
}
/**
* @see CronTriggerFactoryBean#setMisfireInstruction(int)
* @param misfireInstruction
* @return
*/
public QuartzCronTriggerBuilder misfireInstruction(int misfireInstruction) {
triggerFactoryBean.setMisfireInstruction(misfireInstruction);
return this;
}
/**
* @see CronTriggerFactoryBean#setMisfireInstructionName(String)
* @param misfireInstructionName
* @return
*/
public QuartzCronTriggerBuilder misfireInstructionName(String misfireInstructionName) {
triggerFactoryBean.setMisfireInstructionName(misfireInstructionName);
return this;
}
/**
* @see CronTriggerFactoryBean#setPriority(int)
* @param priority
* @return
*/
public QuartzCronTriggerBuilder priority(int priority) {
triggerFactoryBean.setPriority(priority);
return this;
}
/**
* @see TimeZone#getTimeZone(String)
* @see CronTriggerFactoryBean#setTimeZone(TimeZone)
* @param timeZone
* @return
*/
public QuartzCronTriggerBuilder timeZone(String timeZone) {
return this.timeZone(TimeZone.getTimeZone(timeZone));
}
/**
* @see CronTriggerFactoryBean#setTimeZone(TimeZone)
* @param timeZone
* @return
*/
public QuartzCronTriggerBuilder timeZone(TimeZone timeZone) {
triggerFactoryBean.setTimeZone(timeZone);
return this;
}
/**
* @see CronTriggerFactoryBean#setJobDataAsMap(Map)
* @param jobData
* @return
*/
public QuartzCronTriggerBuilder putJobData(Map<String, ?> jobData) {
if (null != jobData) {
triggerFactoryBean.getJobDataMap().putAll(jobData);
}
return this;
}
/**
* @see CronTriggerFactoryBean#setJobDataAsMap(Map)
* @param key
* @param value
* @return
*/
public QuartzCronTriggerBuilder addJobData(String key, Object value) {
triggerFactoryBean.getJobDataMap().put(key, value);
return this;
}
/**
* @see CronTriggerFactoryBean#setCalendarName(String)
* @param calendarName
* @return
*/
public QuartzCronTriggerBuilder calendarName(String calendarName) {
triggerFactoryBean.setCalendarName(calendarName);
return this;
}
/**
*
* @return
*/
public CronTriggerFactoryBean getTriggerFactoryBean() {
return triggerFactoryBean;
}
/**
*
* @return
* @throws ParseException
*/
public CronTrigger build() throws ParseException {
triggerFactoryBean.afterPropertiesSet();
return triggerFactoryBean.getObject();
}
}
/**
* creates a CronTriggerFactoryBean regarding the parameters with {@link CronTrigger#MISFIRE_INSTRUCTION_DO_NOTHING}
* @see QuartzUtils#createCronTrigger(JobDetail, String, String, String, String, int, Map, long, Date, String, int)
*
* @param jobDetail
* @param triggerName (optional)
* @param triggerGroup (optional)
* @param triggerDescription (optional)
* @param cronExpression
* @param startDelay
* @param jobData (optional)
* @return
*/
public static CronTriggerFactoryBean createCronTrigger(JobDetail jobDetail, String triggerName, String triggerGroup,
String triggerDescription, String cronExpression, long startDelay, Map<String, ?> jobData) {
return QuartzUtils.cronTriggerBuilder().jobDetail(jobDetail).name(triggerName).group(triggerGroup)
.description(triggerDescription).cronExpression(cronExpression).startDelay(startDelay)
.misfireInstruction(CronTrigger.MISFIRE_INSTRUCTION_DO_NOTHING).putJobData(jobData)
.getTriggerFactoryBean();
}
/**
* returns a cron trigger factory bean to put into spring context
*
* @param jobDetail
* @param triggerName (optional)
* @param triggerGroup (optional)
* @param triggerDescription (optional)
* @param cronExpression
* @param misfireInstruction see {@link CronTrigger}
* @param jobData
* @param startDelay if start delay is set, startTime will be ignored
* @param startTime
* @param timeZone
* @param priority
* @return
*/
public static CronTriggerFactoryBean createCronTrigger(JobDetail jobDetail, String triggerName, String triggerGroup,
String triggerDescription, String cronExpression, int misfireInstruction, Map<String, ?> jobData,
long startDelay, Date startTime, String timeZone, int priority) {
return QuartzUtils.cronTriggerBuilder().jobDetail(jobDetail).name(triggerName).group(triggerGroup)
.description(triggerDescription).cronExpression(cronExpression).startDelay(startDelay)
.misfireInstruction(misfireInstruction).putJobData(jobData).timeZone(timeZone).startTime(startTime)
.priority(priority).getTriggerFactoryBean();
}
} |
package de.htw_berlin.HoboOthello.Core;
import java.util.ArrayList;
import java.util.List;
public class Board {
public static final int BOARD_SIZE_EIGHT = 8;
public static final int BOARD_SIZE_SIX = 6;
public static final int BOARD_SIZE_TEN = 10;
private int boardSize;
private Field[][] fields;
/**
* Constructor of Board which declares and constructs an two-dimensional array of fields
* Calls a method to fill the field with default values
* Standard size of Board is 8 x 8
* Small size of Board is 6 x 6
* Large size of Board is 10 x 10
*/
public Board(int i) {
initBoard(i);
}
private void initBoard(int newBoardSize) {
if (isBoardSizeAllowed(newBoardSize)) {
this.boardSize = newBoardSize;
fields = new Field[newBoardSize][newBoardSize];
fields = fillWithDefaultValues(fields);
} else {
throw new IllegalArgumentException("Invalid Board Size!");
}
}
private boolean isBoardSizeAllowed(int boardSize) {
return boardSize == BOARD_SIZE_EIGHT
|| boardSize == BOARD_SIZE_SIX
|| boardSize == BOARD_SIZE_TEN;
}
/**
* Method which iterates through all the fields on the board in this specific order:
* Starts at [0][0], moves down the first vertical vector ([0][++]),
* then moves one column to the right ([1][0]) and down the second vertical vector ([1][++]), etc.
* int i = counter on x-axis
* int j = counter on y-axis
*
* @return listOfFields which is a lists of all fields, in this specific order
*/
public List<Field> iterateThroughAllFields() {
List<Field> listOfFields = new ArrayList<Field>();
for (int i = 0; i < this.fields.length; i++) {
for (int j = 0; j < this.fields.length; j++) {
listOfFields.add(this.fields[i][j]);
}
}
return listOfFields;
}
/**
* Method to check if a field is in the corner of the board
*
* @param field that is being checked
* @return true is field is in the corner of the board
*/
public boolean isCornerField(Field field) {
if (field == this.fields[0][0] ||
field == this.fields[0][fields.length] ||
field == this.fields[fields.length][0] ||
field == this.fields[fields.length][fields.length]) {
return true;
} else {
return false;
}
}
/**
* Method to check if a field is on the side of the board
*
* @param field that is being checked
* @return true is field is on the side of the board
*/
public boolean isSideField(Field field) {
boolean isSideField = false;
int counter = 0;
while (counter < fields.length || isSideField) {
if (field == this.fields[0][counter] ||
field == this.fields[counter][0] ||
field == this.fields[fields.length][counter] ||
field == this.fields[counter][fields.length]) {
isSideField = true;
} else {
counter++;
}
}
return isSideField;
}
public boolean isNotSideMinusOneField(Field field) {
boolean isNotSideMinusOne = false;
int counter = 0;
while (counter < (fields.length - 1) || isNotSideMinusOne) {
if (field.equals(isSideField(field)) ||
field != this.fields[1][counter] ||
field != this.fields[counter][1] ||
field != this.fields[fields.length - 1][counter] ||
field != this.fields[counter][fields.length - 1]) {
isNotSideMinusOne = true;
} else {
counter++;
}
}
return isNotSideMinusOne;
}
/**
* Construct the current Board as a multi-line String for debugging
*
* @return Board overview as a String
*/
public String getBoardOverview() {
String boardOverview = "";
for (int y = 0; y < this.boardSize; y++) {
for (int x = 0; x < this.boardSize; x++) {
char StoneColor = ' ';
if (!this.fields[x][y].isEmpty()) {
switch (this.fields[x][y].getStone().getColor()) {
case BLACK:
StoneColor = 'B';
break;
case WHITE:
StoneColor = 'W';
break;
}
} else if (this.fields[x][y].isPossibleMove()) {
StoneColor = 'x';
}
boardOverview = boardOverview + StoneColor;
}
// next line
boardOverview = boardOverview + String.format("%n");
}
return boardOverview;
}
private Field[][] fillWithDefaultValues(Field[][] fieldsToFill) {
for (int x = 0; x < fieldsToFill.length; x++) {
for (int y = 0; y < fieldsToFill.length; y++) {
fieldsToFill[x][y] = new Field(x, y);
}
}
// add starting stones for both players
Stone stoneBlack = new Stone();
stoneBlack.setColor(Color.BLACK);
Stone stoneWhite = new Stone();
stoneWhite.setColor(Color.WHITE);
int BoardHalfLength = fieldsToFill.length / 2;
int middle_x_left = BoardHalfLength - 1;
int middle_x_right = BoardHalfLength;
int middle_y_up = BoardHalfLength - 1;
int middle_y_down = BoardHalfLength;
fieldsToFill[middle_x_left][middle_y_up].setStone(stoneBlack);
fieldsToFill[middle_x_right][middle_y_up].setStone(stoneWhite);
fieldsToFill[middle_x_left][middle_y_down].setStone(stoneWhite);
fieldsToFill[middle_x_right][middle_y_down].setStone(stoneBlack);
return fieldsToFill;
}
/**
* Method which counts how many fields are occupied by a stone of a certain color
*
* @param colorOfStonesToCount the color of stones which are being counted
* @return int number of fields which are occupied by a stone of that color
*/
private int numberOfFieldsOccupiedByStoneColor(Color colorOfStonesToCount) {
int counterOccupiedByStoneColor = 0;
for (int i = 0; i < fields.length; i++) {
for (int j = 0; j < fields.length; j++) {
if (this.fields[i][j].isOccupiedByStone()) {
if (this.fields[i][j].getStone().getColor() == colorOfStonesToCount)
counterOccupiedByStoneColor++;
}
}
}
return counterOccupiedByStoneColor;
}
/**
* Gets how many fields are occupied by a stone from a specific color
*
* @param stoneColor the color of stones which are being counted
* @return int number of fields which are occupied by a stone of that color
*/
public int getNumberOfFieldsOccupiedByStone(Color stoneColor) {
return numberOfFieldsOccupiedByStoneColor(stoneColor);
}
/**
* Total number of fields which are occupied by a stone
*/
private int numberOfOccupiedFields;
/**
* Gets how many fields are occupied by a stone
*
* @return the total number of fields which are occupied by a stone
*/
public int getNumberOfOccupiedFields() {
this.numberOfOccupiedFields = numberOfFieldsOccupiedByStoneColor(Color.WHITE) + numberOfFieldsOccupiedByStoneColor(Color.BLACK);
return numberOfOccupiedFields;
}
/**
* Boolean to determine is the board is completely filled with stones
*
* @return true if board is completely filled with stones
*/
private boolean boardIsFull() {
int numberOfFieldsOnBoard = boardSize * boardSize;
return (numberOfFieldsOnBoard == this.numberOfOccupiedFields);
}
/**
* Boolean to ask the board if the board is completely filled with stones
*
* @return true if board is completely filled with stones
*/
public boolean getBoardIsFull() {
return boardIsFull();
}
public Field[][] isFields() {
return this.fields;
}
public void setFields(Field[][] newFields) {
this.fields = newFields;
}
public int getBoardSize() {
return this.boardSize;
}
} |
package jena;
import static jena.cmdline.CmdLineUtils.setLog4jConfiguration;
import com.hp.hpl.jena.shared.JenaException ;
import com.hp.hpl.jena.rdf.model.*;
import java.net.*;
import java.io.*;
public class rdfcopy extends java.lang.Object {
static {
setLog4jConfiguration() ;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
if ( ( args.length < 1 ) || ( "-h".equals(args[0]) ) ) {
usage();
System.exit(-1);
}
String in = args[0];
String inlang = "RDF/XML";
int j;
for (j = 1; j < args.length && args[j].indexOf("=") != -1; j++)
{}
int lastInProp = j;
if (j < args.length) {
inlang = args[j];
}
j++;
String outlang = "N-TRIPLE";
for (; j < args.length && args[j].indexOf("=") != -1; j++)
{}
int lastOutProp = j;
if (j < args.length) {
outlang = args[j];
}
if (j + 1 < args.length) {
// System.err.println(j+"<<"+args.length);
usage();
System.exit(-1);
}
try {
Model m = ModelFactory.createDefaultModel();
String base = in ;
RDFReader rdr = m.getReader(inlang);
for (j = 1; j < lastInProp; j++) {
int eq = args[j].indexOf("=");
rdr.setProperty(
args[j].substring(0, eq),
args[j].substring(eq + 1));
}
try {
rdr.read(m, in);
} catch (JenaException ex)
{
if ( ! ( ex.getCause() instanceof MalformedURLException ) )
throw ex ;
// Tried as a URL. Try as a file name.
// Make absolute
File f = new File(in) ;
base = "file:///"+f.getCanonicalPath().replace('\\','/') ;
rdr.read(m, new FileInputStream(in), base) ;
}
//rdr.read(m, in);
RDFWriter w = m.getWriter(outlang);
j++;
for (; j < lastOutProp; j++) {
int eq = args[j].indexOf("=");
w.setProperty(
args[j].substring(0, eq),
args[j].substring(eq + 1));
}
w.write(m,System.out,base);
System.exit(0);
} catch (Exception e) {
System.err.println("Unhandled exception:");
System.err.println(" " + e.toString());
System.exit(-1);
}
}
protected static void usage() {
System.err.println("usage:");
System.err.println(" java jena.rdfcopy in {inprop=inval}* [ inlang {outprop=outval}* outlang]]");
System.err.println();
System.err.println(" in can be a URL or a filename");
System.err.println(" inlang and outlang can take values:");
System.err.println(" RDF/XML");
System.err.println(" RDF/XML-ABBREV");
System.err.println(" N-TRIPLE");
System.err.println(" TURTLE");
System.err.println(" N3");
System.err.println(
" inlang defaults to RDF/XML, outlang to N-TRIPLE");
System.err.println(" The legal values for inprop and outprop depend on inlang and outlang.");
System.err.println(" The legal values for inval and outval depend on inprop and outprop.");
System.err.println();
}
protected static void read(Model model, String in, String lang)
throws java.io.FileNotFoundException {
try {
URL url = new URL(in);
model.read(in, lang);
} catch (java.net.MalformedURLException e) {
model.read(new FileInputStream(in), "", lang);
}
}
} |
package de.themoep.inventorygui;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Nameable;
import org.bukkit.Sound;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDispenseEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerSwapHandItemsEvent;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.MaterialData;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* The main library class that lets you create and manage your GUIs
*/
public class InventoryGui implements Listener {
private final static int[] ROW_WIDTHS = {3, 5, 9};
private final static InventoryType[] INVENTORY_TYPES = {
InventoryType.DISPENSER,
InventoryType.HOPPER,
InventoryType.CHEST
};
private final static Sound CLICK_SOUND;
private final static Map<String, InventoryGui> GUI_MAP = new HashMap<>();
private final static Map<UUID, ArrayDeque<InventoryGui>> GUI_HISTORY = new HashMap<>();
private final static Map<String, Pattern> PATTERN_CACHE = new HashMap<>();
private final JavaPlugin plugin;
private final List<UnregisterableListener> listeners = new ArrayList<>();
private final UnregisterableListener[] optionalListeners = new UnregisterableListener[]{
new ItemSwapGuiListener(this)
};
private InventoryCreator creator;
private String title;
private final char[] slots;
private int width;
private final GuiElement[] elementSlots;
private final Map<Character, GuiElement> elements = new HashMap<>();
private InventoryType inventoryType;
private final Map<UUID, Inventory> inventories = new LinkedHashMap<>();
private InventoryHolder owner;
private boolean listenersRegistered = false;
private final Map<UUID, Integer> pageNumbers = new LinkedHashMap<>();
private final Map<UUID, Integer> pageAmounts = new LinkedHashMap<>();
private GuiElement.Action outsideAction = click -> false;
private CloseAction closeAction = close -> true;
private boolean silent = false;
static {
// Sound names changed, make it compatible with both versions
Sound clickSound = null;
String[] clickSounds = {"UI_BUTTON_CLICK", "CLICK"};
for (String s : clickSounds) {
try {
clickSound = Sound.valueOf(s.toUpperCase());
break;
} catch (IllegalArgumentException ignored) {}
}
if (clickSound == null) {
for (Sound sound : Sound.values()) {
if (sound.name().contains("CLICK")) {
clickSound = sound;
break;
}
}
}
CLICK_SOUND = clickSound;
}
public InventoryGui(JavaPlugin plugin, InventoryCreator creator, InventoryHolder owner, String title, String[] rows, GuiElement... elements) {
this.plugin = plugin;
this.creator = creator;
this.owner = owner;
this.title = title;
listeners.add(new GuiListener(this));
for (UnregisterableListener listener : optionalListeners) {
if (listener.isCompatible()) {
listeners.add(listener);
}
}
width = ROW_WIDTHS[0];
for (String row : rows) {
if (row.length() > width) {
width = row.length();
}
}
for (int i = 0; i < ROW_WIDTHS.length && i < INVENTORY_TYPES.length; i++) {
if (width < ROW_WIDTHS[i]) {
width = ROW_WIDTHS[i];
}
if (width == ROW_WIDTHS[i]) {
inventoryType = INVENTORY_TYPES[i];
break;
}
}
if (inventoryType == null) {
throw new IllegalArgumentException("Could not match row setup to an inventory type!");
}
StringBuilder slotsBuilder = new StringBuilder();
for (String row : rows) {
if (row.length() < width) {
double side = (width - row.length()) / 2.0;
for (int i = 0; i < Math.floor(side); i++) {
slotsBuilder.append(" ");
}
slotsBuilder.append(row);
for (int i = 0; i < Math.ceil(side); i++) {
slotsBuilder.append(" ");
}
} else if (row.length() == width) {
slotsBuilder.append(row);
} else {
slotsBuilder.append(row, 0, width);
}
}
slots = slotsBuilder.toString().toCharArray();
elementSlots = new GuiElement[slots.length];
addElements(elements);
}
public InventoryGui(JavaPlugin plugin, InventoryHolder owner, String title, String[] rows, GuiElement... elements) {
this(plugin, new InventoryCreator(
(gui, who, type) -> plugin.getServer().createInventory(new Holder(gui), type, gui.replaceVars(who, title)),
(gui, who, size) -> plugin.getServer().createInventory(new Holder(gui), size, gui.replaceVars(who, title))),
owner, title, rows, elements);
}
public InventoryGui(JavaPlugin plugin, String title, String[] rows, GuiElement... elements) {
this(plugin, null, title, rows, elements);
}
public InventoryGui(JavaPlugin plugin, InventoryHolder owner, String title, String[] rows, Collection<GuiElement> elements) {
this(plugin, owner, title, rows);
addElements(elements);
}
public void setElement(int slot, GuiElement element) {
if (slot < 0 || slot >= elementSlots.length) {
throw new IllegalArgumentException("Provided slots is outside available slots! (" + elementSlots.length + ")");
}
if (element.getSlots().length > 0 || element.getGui() != null) {
throw new IllegalStateException("Element was already added to a gui!");
}
element.setSlots(new int[] {slot});
element.setGui(this);
elementSlots[slot] = element;
}
/**
* Add an element to the gui with its position directly based on the elements slot char and the gui setup string
* @param element The {@link GuiElement} to add
*/
public void addElement(GuiElement element) {
if (element.getSlots().length > 0 || element.getGui() != null) {
throw new IllegalStateException("Element was already added to a gui!");
}
elements.put(element.getSlotChar(), element);
element.setGui(this);
int[] slots = getSlots(element.getSlotChar());
element.setSlots(slots);
for (int slot : slots) {
elementSlots[slot] = element;
}
}
private int[] getSlots(char slotChar) {
ArrayList<Integer> slotList = new ArrayList<>();
for (int i = 0; i < slots.length; i++) {
if (slots[i] == slotChar) {
slotList.add(i);
}
}
return slotList.stream().mapToInt(Integer::intValue).toArray();
}
/**
* Create and add a {@link StaticGuiElement} in one quick method.
* @param slotChar The character to specify the elements position based on the gui setup string
* @param item The item that should be displayed
* @param action The {@link de.themoep.inventorygui.GuiElement.Action} to run when the player clicks on this element
* @param text The text to display on this element, placeholders are automatically
* replaced, see {@link InventoryGui#replaceVars} for a list of the
* placeholder variables. Empty text strings are also filter out, use
* a single space if you want to add an empty line!<br>
* If it's not set/empty the item's default name will be used
*/
public void addElement(char slotChar, ItemStack item, GuiElement.Action action, String... text) {
addElement(new StaticGuiElement(slotChar, item, action, text));
}
/**
* Create and add a {@link StaticGuiElement} that has no action.
* @param slotChar The character to specify the elements position based on the gui setup string
* @param item The item that should be displayed
* @param text The text to display on this element, placeholders are automatically
* replaced, see {@link InventoryGui#replaceVars} for a list of the
* placeholder variables. Empty text strings are also filter out, use
* a single space if you want to add an empty line!<br>
* If it's not set/empty the item's default name will be used
*/
public void addElement(char slotChar, ItemStack item, String... text) {
addElement(new StaticGuiElement(slotChar, item, null, text));
}
/**
* Create and add a {@link StaticGuiElement} in one quick method.
* @param slotChar The character to specify the elements position based on the gui setup string
* @param materialData The {@link MaterialData} of the item of tihs element
* @param action The {@link de.themoep.inventorygui.GuiElement.Action} to run when the player clicks on this element
* @param text The text to display on this element, placeholders are automatically
* replaced, see {@link InventoryGui#replaceVars} for a list of the
* placeholder variables. Empty text strings are also filter out, use
* a single space if you want to add an empty line!<br>
* If it's not set/empty the item's default name will be used
*/
public void addElement(char slotChar, MaterialData materialData, GuiElement.Action action, String... text) {
addElement(slotChar, materialData.toItemStack(1), action, text);
}
/**
* Create and add a {@link StaticGuiElement}
* @param slotChar The character to specify the elements position based on the gui setup string
* @param material The {@link Material} that the item should have
* @param data The <code>byte</code> representation of the material data of this element
* @param action The {@link GuiElement.Action} to run when the player clicks on this element
* @param text The text to display on this element, placeholders are automatically
* replaced, see {@link InventoryGui#replaceVars} for a list of the
* placeholder variables. Empty text strings are also filter out, use
* a single space if you want to add an empty line!<br>
* If it's not set/empty the item's default name will be used
*/
public void addElement(char slotChar, Material material, byte data, GuiElement.Action action, String... text) {
addElement(slotChar, new MaterialData(material, data), action, text);
}
/**
* Create and add a {@link StaticGuiElement}
* @param slotChar The character to specify the elements position based on the gui setup string
* @param material The {@link Material} that the item should have
* @param action The {@link GuiElement.Action} to run when the player clicks on this element
* @param text The text to display on this element, placeholders are automatically
* replaced, see {@link InventoryGui#replaceVars} for a list of the
* placeholder variables. Empty text strings are also filter out, use
* a single space if you want to add an empty line!<br>
* If it's not set/empty the item's default name will be used
*/
public void addElement(char slotChar, Material material, GuiElement.Action action, String... text) {
addElement(slotChar, material, (byte) 0, action, text);
}
/**
* Add multiple elements to the gui with their position based on their slot character
* @param elements The {@link GuiElement}s to add
*/
public void addElements(GuiElement... elements) {
for (GuiElement element : elements) {
addElement(element);
}
}
/**
* Add multiple elements to the gui with their position based on their slot character
* @param elements The {@link GuiElement}s to add
*/
public void addElements(Collection<GuiElement> elements) {
for (GuiElement element : elements) {
addElement(element);
}
}
/**
* Remove a specific element from this gui.
* @param element The element to remove
* @return Whether or not the gui contained this element and if it was removed
*/
public boolean removeElement(GuiElement element) {
boolean removed = elements.remove(element.getSlotChar(), element);
for (int slot : element.getSlots()) {
if (elementSlots[slot] == element) {
elementSlots[slot] = null;
removed = true;
}
}
return removed;
}
/**
* Remove the element that is currently assigned to a specific slot char from all slots in the gui
* @param slotChar The char of the slot
* @return The element which was in that slot or <code>null</code> if there was none
*/
public GuiElement removeElement(char slotChar) {
GuiElement element = getElement(slotChar);
if (element != null) {
removeElement(element);
}
return element;
}
/**
* Remove the element that is currently in a specific slot. Will not remove that element from other slots
* @param slot The slot
* @return The element which was in that slot or <code>null</code> if there was none
*/
public GuiElement removeElement(int slot) {
if (slot < 0 || slot >= elementSlots.length) {
return null;
}
GuiElement element = elementSlots[slot];
elementSlots[slot] = null;
return element;
}
/**
* Set the filler element for empty slots
* @param item The item for the filler element
*/
public void setFiller(ItemStack item) {
addElement(new StaticGuiElement(' ', item, " "));
}
/**
* Get the filler element
* @return The filler element for empty slots
*/
public GuiElement getFiller() {
return elements.get(' ');
}
/**
* Get the number of the page that this gui is on. zero indexed. Only affects group elements.
* @return The page number
* @deprecated Use {@link #getPageNumber(HumanEntity)}
*/
@Deprecated
public int getPageNumber() {
return getPageNumber(null);
}
/**
* Get the number of the page that this gui is on. zero indexed. Only affects group elements.
* @param player The Player to query the page number for
* @return The page number
*/
public int getPageNumber(HumanEntity player) {
return player != null
? pageNumbers.getOrDefault(player.getUniqueId(), 0)
: pageNumbers.isEmpty() ? 0 : pageNumbers.values().iterator().next();
}
/**
* Set the number of the page that this gui is on for all players. zero indexed. Only affects group elements.
* @param pageNumber The page number to set
*/
public void setPageNumber(int pageNumber) {
for (UUID playerId : inventories.keySet()) {
Player player = plugin.getServer().getPlayer(playerId);
if (player != null) {
setPageNumber(player, pageNumber);
}
}
}
/**
* Set the number of the page that this gui is on for a player. zero indexed. Only affects group elements.
* @param player The player to set the page number for
* @param pageNumber The page number to set
*/
public void setPageNumber(HumanEntity player, int pageNumber) {
setPageNumberInternal(player, pageNumber);
draw(player, false);
}
private void setPageNumberInternal(HumanEntity player, int pageNumber) {
pageNumbers.put(player.getUniqueId(), Math.max(pageNumber, 0));
}
/**
* Get the amount of pages that this GUI has
* @return The amount of pages
* @deprecated Use {@link #getPageAmount(HumanEntity)}
*/
@Deprecated
public int getPageAmount() {
return getPageAmount(null);
}
/**
* Get the amount of pages that this GUI has for a certain player
* @param player The Player to query the page amount for
* @return The amount of pages
*/
public int getPageAmount(HumanEntity player) {
return player != null
? pageAmounts.getOrDefault(player.getUniqueId(), 1)
: pageAmounts.isEmpty() ? 1 : pageAmounts.values().iterator().next();
}
/**
* Set the amount of pages that this GUI has for a certain player
* @param player The Player to query the page amount for
* @param pageAmount The page amount
*/
private void setPageAmount(HumanEntity player, int pageAmount) {
pageAmounts.put(player.getUniqueId(), pageAmount);
}
private void calculatePageAmount(HumanEntity player) {
int pageAmount = 0;
for (GuiElement element : elements.values()) {
int amount = calculateElementSize(player, element);
if (amount > 0 && (pageAmount - 1) * element.getSlots().length < amount && element.getSlots().length > 0) {
pageAmount = (int) Math.ceil((double) amount / element.getSlots().length);
}
}
setPageAmount(player, pageAmount);
if (getPageNumber(player) >= pageAmount) {
setPageNumberInternal(player, Math.min(0, pageAmount - 1));
}
}
private int calculateElementSize(HumanEntity player, GuiElement element) {
if (element instanceof GuiElementGroup) {
return ((GuiElementGroup) element).size();
} else if (element instanceof GuiStorageElement) {
return ((GuiStorageElement) element).getStorage().getSize();
} else if (element instanceof DynamicGuiElement) {
return calculateElementSize(player, ((DynamicGuiElement) element).getCachedElement(player));
}
return 0;
}
private void registerListeners() {
if (listenersRegistered) {
return;
}
for (UnregisterableListener listener : listeners) {
plugin.getServer().getPluginManager().registerEvents(listener, plugin);
}
listenersRegistered = true;
}
private void unregisterListeners() {
for (UnregisterableListener listener : listeners) {
listener.unregister();
}
listenersRegistered = false;
}
/**
* Show this GUI to a player
* @param player The Player to show the GUI to
*/
public void show(HumanEntity player) {
show(player, true);
}
/**
* Show this GUI to a player
* @param player The Player to show the GUI to
* @param checkOpen Whether or not it should check if this gui is already open
*/
public void show(HumanEntity player, boolean checkOpen) {
draw(player);
if (!checkOpen || !this.equals(getOpen(player))) {
InventoryType type = player.getOpenInventory().getType();
if (type != InventoryType.CRAFTING && type != InventoryType.CREATIVE) {
// If the player already has a gui open then we assume that the call was from that gui.
// In order to not close it in a InventoryClickEvent listener (which will lead to errors)
// we delay the opening for one tick to run after it finished processing the event
plugin.getServer().getScheduler().runTask(plugin, () -> {
Inventory inventory = getInventory(player);
if (inventory != null) {
addHistory(player, this);
player.openInventory(inventory);
}
});
} else {
Inventory inventory = getInventory(player);
if (inventory != null) {
clearHistory(player);
addHistory(player, this);
player.openInventory(inventory);
}
}
}
}
/**
* Build the gui
*/
public void build() {
build(owner);
}
/**
* Set the gui's owner and build it
* @param owner The {@link InventoryHolder} that owns the gui
*/
public void build(InventoryHolder owner) {
setOwner(owner);
registerListeners();
}
/**
* Draw the elements in the inventory. This can be used to manually refresh the gui. Updates any dynamic elements.
*/
public void draw() {
for (UUID playerId : inventories.keySet()) {
Player player = plugin.getServer().getPlayer(playerId);
if (player != null) {
draw(player);
}
}
}
/**
* Draw the elements in the inventory. This can be used to manually refresh the gui. Updates any dynamic elements.
* @param who For who to draw the GUI
*/
public void draw(HumanEntity who) {
draw(who, true);
}
/**
* Draw the elements in the inventory. This can be used to manually refresh the gui.
* @param who For who to draw the GUI
* @param updateDynamic Update dynamic elements
*/
public void draw(HumanEntity who, boolean updateDynamic) {
if (updateDynamic) {
updateElements(who, elements.values());
}
calculatePageAmount(who);
Inventory inventory = getInventory(who);
if (inventory == null) {
build();
if (slots.length != inventoryType.getDefaultSize()) {
inventory = getInventoryCreator().getSizeCreator().create(this, who, slots.length);
} else {
inventory = getInventoryCreator().getTypeCreator().create(this, who, inventoryType);
}
inventories.put(who != null ? who.getUniqueId() : null, inventory);
} else {
inventory.clear();
}
for (int i = 0; i < inventory.getSize(); i++) {
GuiElement element = getElement(i);
if (element == null) {
element = getFiller();
}
if (element != null) {
inventory.setItem(i, element.getItem(who, i));
}
}
}
/**
* Update all dynamic elements in a collection of elements.
* @param who The player to update the elements for
* @param elements The elements to update
*/
public static void updateElements(HumanEntity who, Collection<GuiElement> elements) {
for (GuiElement element : elements) {
if (element instanceof DynamicGuiElement) {
((DynamicGuiElement) element).update(who);
} else if (element instanceof GuiElementGroup) {
updateElements(who, ((GuiElementGroup) element).getElements());
}
}
}
/**
* Closes the GUI for everyone viewing it
*/
public void close() {
close(true);
}
/**
* Close the GUI for everyone viewing it
* @param clearHistory Whether or not to close the GUI completely (by clearing the history)
*/
public void close(boolean clearHistory) {
for (Inventory inventory : inventories.values()) {
for (HumanEntity viewer : new ArrayList<>(inventory.getViewers())) {
if (clearHistory) {
clearHistory(viewer);
}
viewer.closeInventory();
}
}
}
/**
* Destroy this GUI. This unregisters all listeners and removes it from the GUI_MAP
*/
public void destroy() {
destroy(true);
}
private void destroy(boolean closeInventories) {
if (closeInventories) {
close();
}
for (Inventory inventory : inventories.values()) {
inventory.clear();
}
inventories.clear();
pageNumbers.clear();
pageAmounts.clear();
unregisterListeners();
removeFromMap();
}
/**
* Add a new history entry to the end of the history
* @param player The player to add the history entry for
* @param gui The GUI to add to the history
*/
public static void addHistory(HumanEntity player, InventoryGui gui) {
GUI_HISTORY.putIfAbsent(player.getUniqueId(), new ArrayDeque<>());
Deque<InventoryGui> history = getHistory(player);
if (history.peekLast() != gui) {
history.add(gui);
}
}
/**
* Get the history of a player
* @param player The player to get the history for
* @return The history as a deque of InventoryGuis;
* returns an empty one and not <code>null</code>!
*/
public static Deque<InventoryGui> getHistory(HumanEntity player) {
return GUI_HISTORY.getOrDefault(player.getUniqueId(), new ArrayDeque<>());
}
/**
* Go back one entry in the history
* @param player The player to show the previous gui to
* @return <code>true</code> if there was a gui to show; <code>false</code> if not
*/
public static boolean goBack(HumanEntity player) {
Deque<InventoryGui> history = getHistory(player);
history.pollLast();
if (history.isEmpty()) {
return false;
}
InventoryGui previous = history.peekLast();
if (previous != null) {
previous.show(player, false);
}
return true;
}
/**
* Clear the history of a player
* @param player The player to clear the history for
* @return The history
*/
public static Deque<InventoryGui> clearHistory(HumanEntity player) {
if (GUI_HISTORY.containsKey(player.getUniqueId())) {
return GUI_HISTORY.remove(player.getUniqueId());
}
return new ArrayDeque<>();
}
/**
* Get the plugin which owns this GUI. Should be the one who created it.
* @return The plugin which owns this GUI
*/
public JavaPlugin getPlugin() {
return plugin;
}
/**
* Get the helper class which will create the custom inventory for this gui.
* Simply uses {@link org.bukkit.Bukkit#createInventory(InventoryHolder, int, String)} by default.
* @return The used inventory creator instance
*/
public InventoryCreator getInventoryCreator() {
return creator;
}
/**
* Set the helper class which will create the custom inventory for this gui.
* Can be used to create more special inventories.
* Simply uses {@link org.bukkit.Bukkit#createInventory(InventoryHolder, int, String)} by default.
* Should return a container inventory that can hold the size. Special inventories will break stuff.
* @param creator The new inventory creator instance
*/
public void setInventoryCreator(InventoryCreator creator) {
this.creator = creator;
}
/**
* Get element in a certain slot
* @param slot The slot to get the element from
* @return The GuiElement or <code>null</code> if the slot is empty/there wasn't one
*/
public GuiElement getElement(int slot) {
return slot < 0 || slot >= elementSlots.length ? null : elementSlots[slot];
}
/**
* Get an element by its character
* @param c The character to get the element by
* @return The GuiElement or <code>null</code> if there is no element for that character
*/
public GuiElement getElement(char c) {
return elements.get(c);
}
/**
* Get all elements of this gui. This collection is immutable, use the addElement and removeElement methods
* to modify the elements in this gui.
* @return An immutable collection of all elements in this group
*/
public Collection<GuiElement> getElements() {
return Collections.unmodifiableCollection(elements.values());
}
/**
* Set the owner of this GUI. Will remove the previous assignment.
* @param owner The owner of the GUI
*/
public void setOwner(InventoryHolder owner) {
removeFromMap();
this.owner = owner;
if (owner instanceof Entity) {
GUI_MAP.put(((Entity) owner).getUniqueId().toString(), this);
} else if (owner instanceof BlockState) {
GUI_MAP.put(((BlockState) owner).getLocation().toString(), this);
}
}
/**
* Get the owner of this GUI. Will be null if th GUI doesn't have one
* @return The InventoryHolder of this GUI
*/
public InventoryHolder getOwner() {
return owner;
}
/**
* Check whether or not the Owner of this GUI is real or fake
* @return <code>true</code> if the owner is a real world InventoryHolder; <code>false</code> if it is null
*/
public boolean hasRealOwner() {
return owner != null;
}
/**
* Get the Action that is run when clicked outside of the inventory
* @return The Action for when the player clicks outside the inventory; can be null
*/
public GuiElement.Action getOutsideAction() {
return outsideAction;
}
/**
* Set the Action that is run when clicked outside of the inventory
* @param outsideAction The Action for when the player clicks outside the inventory; can be null
*/
public void setOutsideAction(GuiElement.Action outsideAction) {
this.outsideAction = outsideAction;
}
/**
* Get the action that is run when this GUI is closed
* @return The action for when the player closes this inventory; can be null
*/
public CloseAction getCloseAction() {
return closeAction;
}
/**
* Set the action that is run when this GUI is closed; it should return true if the GUI should go back
* @param closeAction The action for when the player closes this inventory; can be null
*/
public void setCloseAction(CloseAction closeAction) {
this.closeAction = closeAction;
}
/**
* Get whether or not this GUI should make a sound when interacting with elements that make sound
* @return Whether or not to make a sound when interacted with
*/
public boolean isSilent() {
return silent;
}
/**
* Set whether or not this GUI should make a sound when interacting with elements that make sound
* @param silent Whether or not to make a sound when interacted with
*/
public void setSilent(boolean silent) {
this.silent = silent;
}
private void removeFromMap() {
if (owner instanceof Entity) {
GUI_MAP.remove(((Entity) owner).getUniqueId().toString(), this);
} else if (owner instanceof BlockState) {
GUI_MAP.remove(((BlockState) owner).getLocation().toString(), this);
}
}
/**
* Get the GUI registered to an InventoryHolder
* @param holder The InventoryHolder to get the GUI for
* @return The InventoryGui registered to it or <code>null</code> if none was registered to it
*/
public static InventoryGui get(InventoryHolder holder) {
if (holder instanceof Entity) {
return GUI_MAP.get(((Entity) holder).getUniqueId().toString());
} else if (holder instanceof BlockState) {
return GUI_MAP.get(((BlockState) holder).getLocation().toString());
}
return null;
}
/**
* Get the GUI that a player has currently open
* @param player The Player to get the GUI for
* @return The InventoryGui that the player has open
*/
public static InventoryGui getOpen(HumanEntity player) {
return getHistory(player).peekLast();
}
/**
* Get the title of the gui
* @return The title of the gui
*/
public String getTitle() {
return title;
}
/**
* Set the title of the gui
* @param title The {@link String} that should be the title of the gui
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Play a click sound e.g. when an element acts as a button
*/
public void playClickSound() {
if (isSilent()) return;
for (Inventory inventory : inventories.values()) {
for (HumanEntity humanEntity : inventory.getViewers()) {
if (humanEntity instanceof Player) {
((Player) humanEntity).playSound(humanEntity.getEyeLocation(), CLICK_SOUND, 1, 1);
}
}
}
}
/**
* Get the inventory. Package scope as it should only be used by InventoryGui.Holder
* @return The GUI's generated inventory
*/
Inventory getInventory() {
return getInventory(null);
}
/**
* Get the inventory of a certain player
* @param who The player, if null it will try to return the inventory created first or null if none was created
* @return The GUI's generated inventory, null if none was found
*/
private Inventory getInventory(HumanEntity who) {
return who != null ? inventories.get(who.getUniqueId()) : (inventories.isEmpty() ? null : inventories.values().iterator().next());
}
int getWidth() {
return width;
}
private interface UnregisterableListener extends Listener {
void unregister();
default boolean isCompatible() {
try {
getClass().getMethods();
getClass().getDeclaredMethods();
return true;
} catch (NoClassDefFoundError e) {
return false;
}
}
}
/**
* All the listeners that InventoryGui needs to work
*/
public class GuiListener implements UnregisterableListener {
private final InventoryGui gui;
private GuiListener(InventoryGui gui) {
this.gui = gui;
}
@EventHandler(ignoreCancelled = true)
private void onInventoryClick(InventoryClickEvent event) {
if (event.getInventory().equals(getInventory(event.getWhoClicked()))) {
int slot = -1;
if (event.getRawSlot() < event.getView().getTopInventory().getSize()) {
slot = event.getRawSlot();
} else if (event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) {
slot = event.getInventory().firstEmpty();
}
GuiElement.Action action = null;
GuiElement element = null;
if (slot >= 0) {
element = getElement(slot);
if (element != null) {
action = element.getAction(event.getWhoClicked());
}
} else if (slot == -999) {
action = outsideAction;
} else {
// Click was neither for the top inventory nor outside
// E.g. click is in the bottom inventory
if (event.getAction() == InventoryAction.COLLECT_TO_CURSOR) {
simulateCollectToCursor(new GuiElement.Click(gui, slot, null, event));
}
return;
}
try {
if (action == null || action.onClick(new GuiElement.Click(gui, slot, element, event))) {
event.setCancelled(true);
if (event.getWhoClicked() instanceof Player) {
((Player) event.getWhoClicked()).updateInventory();
}
}
if (action != null) {
// Let's assume something changed and re-draw all currently shown inventories
for (UUID playerId : inventories.keySet()) {
if (!event.getWhoClicked().getUniqueId().equals(playerId)) {
Player player = plugin.getServer().getPlayer(playerId);
if (player != null) {
draw(player, false);
}
}
}
}
} catch (Throwable t) {
event.setCancelled(true);
if (event.getWhoClicked() instanceof Player) {
((Player) event.getWhoClicked()).updateInventory();
}
plugin.getLogger().log(Level.SEVERE, "Exception while trying to run action for click on "
+ (element != null ? element.getClass().getSimpleName() : "empty element")
+ " in slot " + event.getRawSlot() + " of " + gui.getTitle() + " GUI!");
t.printStackTrace();
}
} else if (hasRealOwner() && owner.equals(event.getInventory().getHolder())) {
// Click into inventory by same owner but not the inventory of the GUI
// Assume that the underlying inventory changed and redraw the GUI
plugin.getServer().getScheduler().runTask(plugin, (Runnable) gui::draw);
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onInventoryDrag(InventoryDragEvent event) {
Inventory inventory = getInventory(event.getWhoClicked());
if (event.getInventory().equals(inventory)) {
int rest = 0;
Map<Integer, ItemStack> resetSlots = new HashMap<>();
for (Map.Entry<Integer, ItemStack> items : event.getNewItems().entrySet()) {
if (items.getKey() < inventory.getSize()) {
GuiElement element = getElement(items.getKey());
if (!(element instanceof GuiStorageElement)
|| !((GuiStorageElement) element).setStorageItem(event.getWhoClicked(), items.getKey(), items.getValue())) {
ItemStack slotItem = event.getInventory().getItem(items.getKey());
if (!items.getValue().isSimilar(slotItem)) {
rest += items.getValue().getAmount();
} else if (slotItem != null) {
rest += items.getValue().getAmount() - slotItem.getAmount();
}
//items.getValue().setAmount(0); // can't change resulting items :/
resetSlots.put(items.getKey(), event.getInventory().getItem(items.getKey())); // reset them manually
}
}
}
plugin.getServer().getScheduler().runTask(plugin, () -> {
for (Map.Entry<Integer, ItemStack> items : resetSlots.entrySet()) {
event.getView().getTopInventory().setItem(items.getKey(), items.getValue());
}
});
if (rest > 0) {
int cursorAmount = event.getCursor() != null ? event.getCursor().getAmount() : 0;
if (!event.getOldCursor().isSimilar(event.getCursor())) {
event.setCursor(event.getOldCursor());
cursorAmount = 0;
}
int newCursorAmount = cursorAmount + rest;
if (newCursorAmount <= event.getCursor().getMaxStackSize()) {
event.getCursor().setAmount(newCursorAmount);
} else {
event.getCursor().setAmount(event.getCursor().getMaxStackSize());
ItemStack add = event.getCursor().clone();
int addAmount = newCursorAmount - event.getCursor().getMaxStackSize();
if (addAmount > 0) {
add.setAmount(addAmount);
for (ItemStack drop : event.getWhoClicked().getInventory().addItem(add).values()) {
event.getWhoClicked().getLocation().getWorld().dropItem(event.getWhoClicked().getLocation(), drop);
}
}
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onInventoryClose(InventoryCloseEvent event) {
Inventory inventory = getInventory(event.getPlayer());
if (event.getInventory().equals(inventory)) {
// go back. that checks if the player is in gui and has history
if (gui.equals(getOpen(event.getPlayer()))) {
if (closeAction == null || closeAction.onClose(new Close(event.getPlayer(), gui, event))) {
goBack(event.getPlayer());
} else {
clearHistory(event.getPlayer());
}
}
if (inventories.size() <= 1) {
destroy(false);
} else {
inventory.clear();
for (HumanEntity viewer : inventory.getViewers()) {
if (viewer != event.getPlayer()) {
viewer.closeInventory();
}
}
inventories.remove(event.getPlayer().getUniqueId());
pageAmounts.remove(event.getPlayer().getUniqueId());
pageNumbers.remove(event.getPlayer().getUniqueId());
for (GuiElement element : getElements()) {
if (element instanceof DynamicGuiElement) {
((DynamicGuiElement) element).removeCachedElement(event.getPlayer());
}
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryMoveItem(InventoryMoveItemEvent event) {
if (hasRealOwner() && (owner.equals(event.getDestination().getHolder()) || owner.equals(event.getSource().getHolder()))) {
plugin.getServer().getScheduler().runTask(plugin, (Runnable) gui::draw);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onDispense(BlockDispenseEvent event) {
if (hasRealOwner() && owner.equals(event.getBlock().getState())) {
plugin.getServer().getScheduler().runTask(plugin, (Runnable) gui::draw);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
if (hasRealOwner() && owner.equals(event.getBlock().getState())) {
destroy();
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityDeath(EntityDeathEvent event) {
if (hasRealOwner() && owner.equals(event.getEntity())) {
destroy();
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPluginDisable(PluginDisableEvent event) {
if (event.getPlugin() == plugin) {
destroy();
}
}
public void unregister() {
InventoryClickEvent.getHandlerList().unregister(this);
InventoryDragEvent.getHandlerList().unregister(this);
InventoryCloseEvent.getHandlerList().unregister(this);
InventoryMoveItemEvent.getHandlerList().unregister(this);
BlockDispenseEvent.getHandlerList().unregister(this);
BlockBreakEvent.getHandlerList().unregister(this);
EntityDeathEvent.getHandlerList().unregister(this);
PluginDisableEvent.getHandlerList().unregister(this);
}
}
/**
* Event isn't available on older version so just use a separate listener...
*/
public class ItemSwapGuiListener implements UnregisterableListener {
private final InventoryGui gui;
private ItemSwapGuiListener(InventoryGui gui) {
this.gui = gui;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryMoveItem(PlayerSwapHandItemsEvent event) {
Inventory inventory = getInventory(event.getPlayer());
if (event.getPlayer().getOpenInventory().getTopInventory().equals(inventory)) {
event.setCancelled(true);
}
}
public void unregister() {
PlayerSwapHandItemsEvent.getHandlerList().unregister(this);
}
}
/**
* Fake InventoryHolder for the GUIs
*/
public static class Holder implements InventoryHolder {
private InventoryGui gui;
public Holder(InventoryGui gui) {
this.gui = gui;
}
@Override
public Inventory getInventory() {
return gui.getInventory();
}
public InventoryGui getGui() {
return gui;
}
}
public static interface CloseAction {
/**
* Executed when a player closes a GUI inventory
* @param close The close object holding information about this close
* @return Whether or not the close should go back or not
*/
boolean onClose(Close close);
}
public static class Close {
private final HumanEntity player;
private final InventoryGui gui;
private final InventoryCloseEvent event;
public Close(HumanEntity player, InventoryGui gui, InventoryCloseEvent event) {
this.player = player;
this.gui = gui;
this.event = event;
}
public HumanEntity getPlayer() {
return player;
}
public InventoryGui getGui() {
return gui;
}
public InventoryCloseEvent getEvent() {
return event;
}
}
/**
* Set the text of an item using the display name and the lore.
* Also replaces any placeholders in the text and filters out empty lines.
* Use a single space to create an emtpy line.
* @param item The {@link ItemStack} to set the text for
* @param text The text lines to set
* @deprecated Use {@link #setItemText(HumanEntity, ItemStack, String...)}
*/
@Deprecated
public void setItemText(ItemStack item, String... text) {
setItemText(null, item, text);
}
/**
* Set the text of an item using the display name and the lore.
* Also replaces any placeholders in the text and filters out empty lines.
* Use a single space to create an emtpy line.
* @param player The player viewing the GUI
* @param item The {@link ItemStack} to set the text for
* @param text The text lines to set
*/
public void setItemText(HumanEntity player, ItemStack item, String... text) {
if (item != null && text != null && text.length > 0) {
ItemMeta meta = item.getItemMeta();
if (meta != null) {
String combined = replaceVars(player, Arrays.stream(text)
.map(s -> s == null ? " " : s)
.filter(s -> !s.isEmpty())
.collect(Collectors.joining("\n")));
String[] lines = combined.split("\n");
if (text[0] != null) {
meta.setDisplayName(lines[0]);
}
if (lines.length > 1) {
meta.setLore(Arrays.asList(Arrays.copyOfRange(lines, 1, lines.length)));
} else {
meta.setLore(null);
}
item.setItemMeta(meta);
}
}
}
/**
* Replace some placeholders in the with values regarding the gui's state. Replaced color codes.<br>
* The placeholders are:<br>
* <code>%plugin%</code> - The name of the plugin that this gui is from.<br>
* <code>%owner%</code> - The name of the owner of this gui. Will be an empty string when the owner is null.<br>
* <code>%title%</code> - The title of this GUI.<br>
* <code>%page%</code> - The current page that this gui is on.<br>
* <code>%nextpage%</code> - The next page. "none" if there is no next page.<br>
* <code>%prevpage%</code> - The previous page. "none" if there is no previous page.<br>
* <code>%pages%</code> - The amount of pages that this gui has.
* @param text The text to replace the placeholders in
* @param replacements Additional repplacements. i = placeholder, i+1 = replacements
* @return The text with all placeholders replaced
* @deprecated Use {@link #replaceVars(HumanEntity, String, String...)}
*/
@Deprecated
public String replaceVars(String text, String... replacements) {
return replaceVars(null, text, replacements);
}
/**
* Replace some placeholders in the with values regarding the gui's state. Replaced color codes.<br>
* The placeholders are:<br>
* <code>%plugin%</code> - The name of the plugin that this gui is from.<br>
* <code>%owner%</code> - The name of the owner of this gui. Will be an empty string when the owner is null.<br>
* <code>%title%</code> - The title of this GUI.<br>
* <code>%page%</code> - The current page that this gui is on.<br>
* <code>%nextpage%</code> - The next page. "none" if there is no next page.<br>
* <code>%prevpage%</code> - The previous page. "none" if there is no previous page.<br>
* <code>%pages%</code> - The amount of pages that this gui has.
* @param player The player viewing the GUI
* @param text The text to replace the placeholders in
* @param replacements Additional repplacements. i = placeholder, i+1 = replacements
* @return The text with all placeholders replaced
*/
public String replaceVars(HumanEntity player, String text, String... replacements) {
Map<String, String> map = new LinkedHashMap<>();
for (int i = 0; i + 1 < replacements.length; i += 2) {
map.putIfAbsent(replacements[i], replacements[i + 1]);
}
map.putIfAbsent("plugin", plugin.getName());
try {
map.putIfAbsent("owner", owner instanceof Nameable ? ((Nameable) owner).getCustomName() : "");
} catch (NoSuchMethodError e) {
map.putIfAbsent("owner", owner instanceof Entity ? ((Entity) owner).getCustomName() : "");
}
map.putIfAbsent("title", title);
map.putIfAbsent("page", String.valueOf(getPageNumber(player) + 1));
map.putIfAbsent("nextpage", getPageNumber(player) + 1 < getPageAmount(player) ? String.valueOf(getPageNumber(player) + 2) : "none");
map.putIfAbsent("prevpage", getPageNumber(player) > 0 ? String.valueOf(getPageNumber(player)) : "none");
map.putIfAbsent("pages", String.valueOf(getPageAmount(player)));
return ChatColor.translateAlternateColorCodes('&', replace(text, map));
}
/**
* Replace placeholders in a string
* @param string The string to replace in
* @param replacements What to replace the placeholders with. The n-th index is the placeholder, the n+1-th the value.
* @return The string with all placeholders replaced (using the configured placeholder prefix and suffix)
*/
private String replace(String string, Map<String, String> replacements) {
for (Map.Entry<String, String> entry : replacements.entrySet()) {
if (entry.getKey() == null) {
continue;
}
String placeholder = "%" + entry.getKey() + "%";
Pattern pattern = PATTERN_CACHE.get(placeholder);
if (pattern == null) {
PATTERN_CACHE.put(placeholder, pattern = Pattern.compile(placeholder, Pattern.LITERAL));
}
string = pattern.matcher(string).replaceAll(Matcher.quoteReplacement(entry.getValue() != null ? entry.getValue() : "null"));
}
return string;
}
/**
* Simulate the collecting to the cursor while respecting elements that can't be modified
* @param click The click that startet it all
*/
void simulateCollectToCursor(GuiElement.Click click) {
ItemStack newCursor = click.getEvent().getCursor().clone();
boolean itemInGui = false;
for (int i = 0; i < click.getEvent().getView().getTopInventory().getSize(); i++) {
if (i != click.getEvent().getRawSlot()) {
ItemStack viewItem = click.getEvent().getView().getTopInventory().getItem(i);
if (newCursor.isSimilar(viewItem)) {
itemInGui = true;
}
GuiElement element = getElement(i);
if (element instanceof GuiStorageElement) {
GuiStorageElement storageElement = (GuiStorageElement) element;
ItemStack otherStorageItem = storageElement.getStorageItem(click.getWhoClicked(), i);
if (addToStack(newCursor, otherStorageItem)) {
if (otherStorageItem.getAmount() == 0) {
otherStorageItem = null;
}
storageElement.setStorageItem(i, otherStorageItem);
if (newCursor.getAmount() == newCursor.getMaxStackSize()) {
break;
}
}
}
}
}
if (itemInGui) {
click.getEvent().setCurrentItem(null);
click.getEvent().setCancelled(true);
if (click.getEvent().getWhoClicked() instanceof Player) {
((Player) click.getEvent().getWhoClicked()).updateInventory();
}
if (click.getElement() instanceof GuiStorageElement) {
((GuiStorageElement) click.getElement()).setStorageItem(click.getWhoClicked(), click.getSlot(), null);
}
if (newCursor.getAmount() < newCursor.getMaxStackSize()) {
Inventory bottomInventory = click.getEvent().getView().getBottomInventory();
for (ItemStack bottomIem : bottomInventory) {
if (addToStack(newCursor, bottomIem)) {
if (newCursor.getAmount() == newCursor.getMaxStackSize()) {
break;
}
}
}
}
click.getEvent().setCursor(newCursor);
draw();
}
}
/**
* Add items to a stack up to the max stack size
* @param item The base item
* @param add The item stack to add
* @return <code>true</code> if the stack is finished; <code>false</code> if these stacks can't be merged
*/
private static boolean addToStack(ItemStack item, ItemStack add) {
if (item.isSimilar(add)) {
int newAmount = item.getAmount() + add.getAmount();
if (newAmount >= item.getMaxStackSize()) {
item.setAmount(item.getMaxStackSize());
add.setAmount(newAmount - item.getAmount());
} else {
item.setAmount(newAmount);
add.setAmount(0);
}
return true;
}
return false;
}
public static class InventoryCreator {
private final CreatorImplementation<InventoryType> typeCreator;
private final CreatorImplementation<Integer> sizeCreator;
/**
* A new inventory creator which should be able to create an inventory based on the type and the size.
* <br><br>
* By default the creators are implemented as follows:
* <pre>
* typeCreator = (gui, who, type) -> plugin.getServer().createInventory(new Holder(gui), type, gui.replaceVars(who, title));
* sizeCreator = (gui, who, size) -> plugin.getServer().createInventory(new Holder(gui), size, gui.replaceVars(who, title));
* </pre>
* @param typeCreator The type creator.
* @param sizeCreator The size creator
*/
public InventoryCreator(CreatorImplementation<InventoryType> typeCreator, CreatorImplementation<Integer> sizeCreator) {
this.typeCreator = typeCreator;
this.sizeCreator = sizeCreator;
}
public CreatorImplementation<InventoryType> getTypeCreator() {
return typeCreator;
}
public CreatorImplementation<Integer> getSizeCreator() {
return sizeCreator;
}
public interface CreatorImplementation<T> {
/**
* Creates a new inventory
* @param gui The InventoryGui instance
* @param who The player to create the inventory for
* @param t The size or type of the inventory
* @return The created inventory
*/
Inventory create(InventoryGui gui, HumanEntity who, T t);
}
}
} |
package spimedb;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.encoder.Encoder;
import ch.qos.logback.core.rolling.FixedWindowRollingPolicy;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
import ch.qos.logback.core.util.FileSize;
import com.google.common.io.Files;
import com.uwyn.jhighlight.fastutil.objects.ObjectArrays;
import jcog.Texts;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.eclipse.collections.api.tuple.Pair;
import org.eclipse.collections.impl.tuple.Tuples;
import org.jetbrains.annotations.NotNull;
import org.mockito.internal.util.reflection.BeanPropertySetter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spimedb.io.Crawl;
import spimedb.io.Multimedia;
import spimedb.server.WebServer;
import spimedb.util.Locker;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.function.Function;
public class Main extends FileAlterationListenerAdaptor {
public final static Logger logger = LoggerFactory.getLogger(SpimeDB.class);
private static final ch.qos.logback.classic.Logger LOG;
static {
Thread.currentThread().setName("$");
LOG = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
LoggerContext loggerContext = LOG.getLoggerContext();
loggerContext.reset();
SpimeDB.LOG(Logger.ROOT_LOGGER_NAME, Level.INFO);
}
private final SpimeDB db;
final String dbPathIgnored;
/**
* live objects
*/
final Map<Pair<Class, String>, Object> obj = new ConcurrentHashMap();
final Map<String, Class> klassPath = new ConcurrentHashMap<>();
final Pair<Class, String> key(File f) {
String fileName = f.getName();
if (fileName.startsWith("."))
return null; //ignore hidden files
String absolutePath = f.getAbsolutePath();
if (absolutePath.startsWith(dbPathIgnored))
return null; //ignore index directory, subdirectory of the root
String[] parts = fileName.split(".");
String id;
Class klass;
if (parts.length < 1) {
/** if only one filename component:
* if this string resolves in the klasspath, then that's what it is and also its name
* else default to 'String'
*/
Class specificclass = klassPath.get(fileName);
if (specificclass == null) {
id = fileName;
klass = String.class;
} else {
klass = specificclass;
id = ""; //designated for the singleton
}
} else if (parts.length >= 2) {
String classSting = parts[0];
klass = klass(classSting);
id = parts[1];
} else {
return null;
}
return key(klass, id);
}
public Pair<Class, String> key(Class klass) {
return key(klass, "");
}
@NotNull
public Pair<Class, String> key(Class klass, String id) {
return Tuples.pair(klass, id);
}
public Class klass(String klass) {
return klassPath.get(klass);
}
@Override
public void onFileCreate(File file) {
update(file);
}
@Override
public void onFileChange(File file) {
update(file);
}
private void update(File file) {
Pair<Class, String> k = key(file);
if (k == null)
return;
logger.info("update file://{}", file);
merge(k, build(k, file));
}
@Override
public void onFileDelete(File file) {
Pair<Class, String> k = key(file);
if (k == null)
return;
remove(k);
}
final Locker<Pair<Class,String>> locker = new Locker();
private Object merge(Pair<Class, String> k, Function build) {
Lock l = locker.get(k);
l.lock();
try {
if (build == null) {
Object v = obj.remove(k);
logger.info("remove {}: {}", k, v);
return v;
} else {
return obj.compute(k, (kk, existing) -> build.apply(existing));
}
} finally {
l.unlock();
}
}
/**
* the function returned will accept the previous value (null if there was none) and return a result
*
* @param file
* @param klass
*/
@NotNull
private Function build(Pair<Class, String> id, File file) {
String[] parts = file.getName().split(".");
switch (parts.length) {
case 0:
case 1:
//string
if (id.getOne() == String.class) {
return new TextBuilder(file);
} else {
return buildDefault(id, file);
}
case 2:
//properties file
return buildDefault(id, file);
case 3:
switch (parts[3]) {
case "js": //javascript
break;
case "json":
break;
case "xml":
break;
case "java": //dynamically recompiled java
break;
}
break;
}
return (x) -> {
logger.info("unbuildable: {}", file);
return x;
};
}
@NotNull
private Function buildDefault(Pair<Class, String> id, File file) {
if (id.getOne() == LogConfigurator.class) {
return (Object x) -> {
LogConfigurator newConfig = new LogConfigurator(file);
if (x instanceof LogConfigurator) {
LogConfigurator old = (LogConfigurator) x;
logger.info("stop {}", old.message);
old.stop();
}
logger.info("start {}", newConfig.message);
return newConfig;
};
} else {
return new PropertyBuilder(id, file);
}
}
static final Class[] spimeDBConstructor = new Class[]{SpimeDB.class};
public class PropertyBuilder<X> implements Function<X, X> {
public final File file;
private final Pair<Class, String> id;
public PropertyBuilder(Pair<Class, String> id, File file) {
this.id = id;
this.file = file;
}
@Override
public X apply(X x) {
Class cl = id.getOne();
if (x == null) {
//HACK TODO use some adaptive constructor argument injector
for (Constructor c : cl.getConstructors()) {
Class[] types = c.getParameterTypes();
Object[] param;
if (Arrays.equals(types, spimeDBConstructor)) { //HACK look for spimeDB as the only arg
param = new Object[]{db};
} else {
param = ObjectArrays.EMPTY_ARRAY;
}
try {
x = (X) c.newInstance(param);
} catch (Exception e) {
logger.error("instantiate {} {} {} {}", file, cl, c, e.getMessage());
return null;
}
}
}
Properties p = new Properties();
try {
p.load(new FileInputStream(file));
} catch (IOException e) {
logger.error("properties configure {} {} {}", file, cl, e.getMessage());
}
for (Map.Entry e : p.entrySet()) {
Object k = e.getKey().toString();
Object v = e.getValue();
String field = k.toString();
Field f = field(cl, field);
if (f != null) {
//TODO better type decoding
BeanPropertySetter s = new BeanPropertySetter(x, f);
try {
switch (f.getType().toString()) {
case "float":
v = Texts.f(v.toString());
break;
case "int":
v = Texts.i(v.toString());
break;
}
logger.info("{}.{}={}", x, field, v);
s.set(v);
} catch (IllegalArgumentException aa) {
logger.info("invalid type {} for {}", v.getClass(), f);
}
} else {
logger.info("unknown field {} {}", file, field);
}
}
return x;
}
}
private Field field(Class cl, String field) {
//TODO add a reflection cache
try {
return cl.getDeclaredField(field);
} catch (NoSuchFieldException e) {
return null;
}
}
public <X> Object put(Class k, X v) {
return put(key(k), v);
}
public <X> Object put(Pair<Class, String> k, X v) {
if (v == null) {
return remove(k);
}
Object existing = obj.put(k, v);
if (existing != v) {
logger.info("{} = {}", k, v);
if (existing != null) {
//logger.info("{} = {}", k, v);
} else {
//logger.info("{} = {} <== {}", k, v, existing);
onRemove(k, existing);
}
onAdd(k, existing);
}
return existing;
}
protected void onAdd(Pair<Class, String> k, Object v) {
}
protected void onRemove(Pair<Class, String> k, Object v) {
}
public <X> X get(Pair<Class<? extends X>, String> k) {
if (k == null)
return null;
return (X) obj.get(k);
}
public Object remove(Pair<Class, String> k) {
return merge(k, null);
}
class LogConfigurator {
Appender appender;
String message;
public LogConfigurator(File f) {
Appender appender = null;
if (f!=null) {
try {
String line = Files.readFirstLine(f, Charset.defaultCharset()).trim();
switch (line) {
case "rolling":
String logFile = db.file.toPath().resolve("log").toAbsolutePath().toString();
message = ("log output rolling to {}" + logFile);
RollingFileAppender r = new RollingFileAppender();
r.setFile(logFile);
r.setAppend(true);
SizeBasedTriggeringPolicy triggeringPolicy = new ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy();
triggeringPolicy.setMaxFileSize(FileSize.valueOf("5MB"));
triggeringPolicy.start();
FixedWindowRollingPolicy policy = new FixedWindowRollingPolicy();
policy.setFileNamePattern("log.%i.gz");
policy.setParent(r);
policy.setContext(LOG.getLoggerContext());
policy.start();
r.setEncoder(logEncoder());
r.setRollingPolicy(policy);
r.setTriggeringPolicy(triggeringPolicy);
appender = r;
break;
//TODO TCP/UDP etc
}
} catch (IOException e) {
logger.error("{}", e);
appender = null;
}
}
if (appender == null) {
//default
ConsoleAppender a = new ConsoleAppender();
a.setEncoder(logEncoder());
appender = a;
message = "Console";
}
LOG.detachAndStopAllAppenders();
appender.setContext(LOG.getLoggerContext());
appender.start();
LOG.addAppender(appender);
this.appender = appender;
}
private Encoder logEncoder() {
PatternLayoutEncoder logEncoder = new PatternLayoutEncoder();
logEncoder.setContext(LOG.getLoggerContext());
logEncoder.setPattern("%highlight(%logger{0}) %green(%thread) %message%n");
logEncoder.setImmediateFlush(true);
logEncoder.start();
return logEncoder;
}
public void stop() {
if (appender!=null) {
appender.stop();
appender = null;
}
}
}
public Main(String path) throws Exception {
//setup default klasspath
klassPath.put("http", WebServer.class);
klassPath.put("log", LogConfigurator.class);
//klassPath.put("crawl", Crawl.class);
put(LogConfigurator.class, new LogConfigurator(null) );
db = new SpimeDB(path + "/_");
dbPathIgnored = db.file.getAbsolutePath();
new Multimedia(db);
logger.info("watching: {}", path);
FileAlterationObserver observer = new FileAlterationObserver(path);
int updatePeriodMS = 1000;
FileAlterationMonitor monitor = new FileAlterationMonitor(updatePeriodMS);
observer.addListener(this);
monitor.addObserver(observer);
monitor.start();
//load existing files
for (File f : observer.getDirectory().listFiles()) {
if (f.getName().startsWith("."))
continue; //ignore hidden files
if (f.isFile())
update(f);
else if (f.isDirectory() && !f.getAbsolutePath().equals(db.indexPath)) {
//default: index a directory
Crawl.fileDirectory(f.getAbsolutePath(), db);
}
}
}
public void put(Class c, String id, Object value) {
put(key(c, id), value);
}
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("usage: spime [datapath]");
System.out.println();
return;
}
String dataPath = args[0];
new Main(dataPath);
// try {
// new WebServer(db, port);
// } catch (RuntimeException e) {
// e.printStackTrace();
// return;
// Phex p = Phex.the();
// p.start();
// p.startSearch("kml");
//Crawl.fileDirectory(path, db);
/*
try {
new SpimeJS(db).with("db", db).run(new File("data/climateviewer.js"));
} catch (Exception e) {
e.printStackTrace();
}
*/
/*
new Netention() {
@Override
protected void onTag(String id, String name, List<String> extend) {
NObject n = new NObject(id, name);
if (extend!=null && !extend.isEmpty())
n.setTag(extend.toArray(new String[extend.size()]));
db.put(n);
}
};
*/
//ImportGeoJSON
//ImportSchemaOrg.load(db);
//db.add(GeoJSON.get(eqGeoJson.get(), GeoJSON.baseGeoJSONBuilder));
// db.forEach(x -> {
// System.out.println(x);
//db.find("s*", 32).docs().forEachRemaining(d -> {
// db.forEach((n) -> {
// System.out.println(n);
// Document dd = db.the(n.id());
// System.out.println("\t" + dd);
}
private class TextBuilder implements Function {
private final File file;
public TextBuilder(File file) {
this.file = file;
}
@Override
public Object apply(Object o) {
try {
return Files.toString(file, Charset.defaultCharset());
} catch (IOException e) {
logger.error("reading string: {}", file);
return null;
}
}
}
// final static String cachePath = "cache";
// public static void main(String[] args) throws Exception {
// //new IRCBot(s.db, "RAWinput", "irc.freenode.net", "#netention");
// HttpCache httpCache = new HttpCache(cachePath);
// //Self s = new Self();
// Web j = new Web()
// .add("/wikipedia", new Wikipedia(httpCache))
//// .add("/api/tag", new PathHandler() {
//// @Override
//// public void handleRequest(HttpServerExchange exchange) throws Exception {
//// ArrayList<Object> av = Lists.newArrayList(s.allValues());
//// byte[] b = Core.jsonAnnotated.writeValueAsBytes(av);
//// Web.send(b, exchange, "application/json" );
// .add("/", ClientResources.handleClientResources())
// .start("localhost", 8080);
// SchemaOrg.load(null);
//// logger.info("Loading ClimateViewer (ontology)");
//// new ClimateViewer(s.db);
//// logger.info("Loading Netention (ontology)");
//// NOntology.load(s.db);
// //InfiniPeer.local("i", cachePath, 32000);
// new ClimateViewerSources() {
// @Override
// public void onLayer(String id, String name, String kml, String icon, String currentSection) {
// URLSensor r = new URLSensor(currentSection + "/" + id, name, kml, icon);
// //p.add(r);
// @Override
// public void onSection(String name, String id, String icon) {
//// int webPort = 9090;
//// SpacetimeWebServer s = SpacetimeWebServer(
//// //ElasticSpacetime.temporary("cv", -1),
//// ElasticSpacetime.local("cv", "cache", true),
//// "localhost",
//// webPort);
////// /*"#archlinux", "#jquery"*/).serverChannel
//// /*s.addPrefixPath("/sim", new WebSocketCore(
//// new SimpleSimulation("x")
//// ).handler());*/
} |
package natlab.tame;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import natlab.tame.callgraph.SimpleFunctionCollection;
import natlab.tame.classes.reference.PrimitiveClassReference;
import natlab.tame.valueanalysis.ValueAnalysis;
import natlab.tame.valueanalysis.ValueAnalysisPrinter;
import natlab.tame.valueanalysis.advancedMatrix.AdvancedMatrixValue;
import natlab.tame.valueanalysis.advancedMatrix.AdvancedMatrixValueFactory;
import natlab.tame.valueanalysis.aggrvalue.AggrValue;
import natlab.tame.valueanalysis.value.Args;
import natlab.tame.valueanalysis.value.ValueFactory;
import natlab.toolkits.filehandling.GenericFile;
import natlab.toolkits.path.FileEnvironment;
public class AdvancedTamerTool {
public static void main(String[] args) {
String file = "/media/vineet/19F5-FD4C/Thesis/mclab_git/mclab/languages/Natlab/src/natlab/backends/x10/benchmarks/mc_for_benchmarks/bubble/drv_bubble";
// String file = "/home/2011/vkumar5/for_test";
String fileIn = file + ".m";
GenericFile gFile = GenericFile.create(fileIn);
/* /home/xuli/test/hello.m */
FileEnvironment env = new FileEnvironment(gFile); // get path
// environment obj
AdvancedTamerTool tool = new AdvancedTamerTool();
// System.out.println(args[0]);
tool.analyze(args, env);
}
public ValueAnalysis<AggrValue<AdvancedMatrixValue>> analyze(String[] args,
FileEnvironment env) {
List<AggrValue<AdvancedMatrixValue>> inputValues = getListOfInputValues(args);
SimpleFunctionCollection callgraph = new SimpleFunctionCollection(env); // build
// simple
// callgraph
ValueFactory<AggrValue<AdvancedMatrixValue>> factory = new AdvancedMatrixValueFactory();
Args<AggrValue<AdvancedMatrixValue>> someargs = Args
.<AggrValue<AdvancedMatrixValue>> newInstance(Collections.EMPTY_LIST);
ValueAnalysis<AggrValue<AdvancedMatrixValue>> analysis = new ValueAnalysis<AggrValue<AdvancedMatrixValue>>(
callgraph,
/*
* Args.newInstance((factory.getValuePropagator().call(Builtin.
* getInstance
* ("i"),someargs).get(0).get(PrimitiveClassReference.DOUBLE)))
*/
Args.newInstance(inputValues), factory);
System.out.println(analysis.toString());
for (int i = 0; i < analysis.getNodeList().size(); i++) {
System.out.println(ValueAnalysisPrinter.prettyPrint(analysis
.getNodeList().get(i).getAnalysis()));
}
return analysis;
}
public static List<AggrValue<AdvancedMatrixValue>> getListOfInputValues(
String[] args) {
List<PrimitiveClassReference> ls = new ArrayList<PrimitiveClassReference>(
1);
// ls.add(PrimitiveClassReference.INT8);
// ls.add(PrimitiveClassReference.DOUBLE);
// ArrayList<AggrValue<AdvancedMatrixValue>> list = new
// ArrayList<AggrValue<AdvancedMatrixValue>>(ls.size());
// for (PrimitiveClassReference ref : ls){
// list.add(new AdvancedMatrixValue(ref)); //TODO change to read
// isComplex input from user
ArrayList<AggrValue<AdvancedMatrixValue>> list = new ArrayList<AggrValue<AdvancedMatrixValue>>(
args.length);
for (String argSpecs : args) {
// System.out.println(argSpecs);
String delims = "[\\&]";
String[] specs = argSpecs.split(delims);
/*
* TODO Below is just to test. Add actual code to make sense of the
* argument specs
*/
/* TODO also add code to read INT, FLOAT, etc. */
list.add(new AdvancedMatrixValue("n",
PrimitiveClassReference.DOUBLE, specs[1], specs[2]));
// XU changed here to support initial input shape info.
// @25th,Jul,2012
}
return list;
}
} |
package edu.hm.hafner.analysis;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
import java.nio.file.InvalidPathException;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.input.ReaderInputStream;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.google.errorprone.annotations.MustBeClosed;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import static org.apache.xerces.impl.Constants.*;
/**
* Provides several useful helper methods to read the contents of a resource that is given by a {@link Reader}.
*
* @author Ullrich Hafner
*/
public abstract class ReaderFactory {
private static final Function<String, String> IDENTITY = Function.identity();
private final Charset charset;
private final Function<String, String> lineMapper;
private static final Pattern ANSI_COLOR_CODES
= Pattern.compile("\u001B\\[[;\\d]*[ -/]*[@-~]");
private static final Function<String, String> REMOVE_COLOR_CODES
= string -> ANSI_COLOR_CODES.matcher(string).replaceAll(StringUtils.EMPTY);
/**
* Creates a new factory to read a resource with a given charset.
*
* @param charset
* the charset to use when reading the file
*/
public ReaderFactory(final Charset charset) {
this(charset, IDENTITY);
}
/**
* Creates a new factory to read a resource with a given charset.
*
* @param charset
* the charset to use when reading the file
* @param lineMapper
* provides a mapper to transform each of the resource lines
*/
public ReaderFactory(final Charset charset, final Function<String, String> lineMapper) {
this.charset = charset;
this.lineMapper = REMOVE_COLOR_CODES.compose(lineMapper);
}
/**
* Returns the name of the resource.
*
* @return the file name
*/
public abstract String getFileName();
/**
* Creates a new {@link Reader} for the file.
*
* @return a reader
*/
@MustBeClosed
public abstract Reader create();
/**
* Provides the lines of the file as a {@link Stream} of strings.
*
* @return the file content as stream
* @throws ParsingException
* if the file could not be read
*/
@MustBeClosed
@SuppressWarnings({"MustBeClosedChecker", "PMD.CloseResource"})
@SuppressFBWarnings("OS_OPEN_STREAM")
public Stream<String> readStream() {
try {
BufferedReader reader = new BufferedReader(create());
Stream<String> stringStream = reader.lines().onClose(closeReader(reader));
if (hasLineMapper()) {
return stringStream.map(lineMapper);
}
else {
return stringStream;
}
}
catch (UncheckedIOException e) {
throw new ParsingException(e);
}
}
@SuppressWarnings({"illegalcatch", "PMD.DoNotUseThreads", "PMD.AvoidThrowingRawExceptionTypes"})
private Runnable closeReader(final AutoCloseable closeable) {
return () -> {
try {
closeable.close();
}
catch (Exception e) {
throw new ParsingException(e);
}
};
}
@SuppressWarnings("PMD.CompareObjectsWithEquals")
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "test stub")
private boolean hasLineMapper() {
return lineMapper != null && lineMapper != IDENTITY;
}
/**
* Reads the whole file into a {@link String}.
*
* @return the file content as string
* @throws ParsingException
* if the file could not be read
*/
public String readString() {
try (Stream<String> lines = readStream()) {
return lines.collect(Collectors.joining("\n"));
}
catch (UncheckedIOException e) {
throw new ParsingException(e);
}
}
/**
* Parses the whole file into a {@link Document}.
*
* @return the file content as document
* @throws ParsingException
* if the file could not be parsed
*/
public Document readDocument() {
try (Reader reader = create()) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
setFeature(factory, SAX_FEATURE_PREFIX, DISALLOW_DOCTYPE_DECL_FEATURE, true);
setFeature(factory, SAX_FEATURE_PREFIX, EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
setFeature(factory, SAX_FEATURE_PREFIX, EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
setFeature(factory, SAX_FEATURE_PREFIX, RESOLVE_DTD_URIS_FEATURE, false);
setFeature(factory, SAX_FEATURE_PREFIX, USE_ENTITY_RESOLVER2_FEATURE, false);
setFeature(factory, XERCES_FEATURE_PREFIX, CREATE_ENTITY_REF_NODES_FEATURE, false);
setFeature(factory, XERCES_FEATURE_PREFIX, LOAD_DTD_GRAMMAR_FEATURE, false);
setFeature(factory, XERCES_FEATURE_PREFIX, LOAD_EXTERNAL_DTD_FEATURE, false);
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(new InputSource(new ReaderInputStream(reader, getCharset())));
}
catch (SAXException | IOException | InvalidPathException | ParserConfigurationException e) {
throw new ParsingException(e);
}
}
@SuppressFBWarnings
@SuppressWarnings("illegalcatch")
private void setFeature(final DocumentBuilderFactory factory, final String prefix, final String feature,
final boolean value) {
try {
factory.setFeature(prefix + feature, value);
}
catch (Exception ignored) {
// ignore and continue
}
}
/**
* Returns the character set that is used to read the stream.
*
* @return the character set
*/
public Charset getCharset() {
return charset;
}
} |
package com.coolerfall.download;
import android.os.Process;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.concurrent.BlockingQueue;
import static com.coolerfall.download.DownloadManager.HTTP_ERROR_SIZE;
import static com.coolerfall.download.DownloadManager.HTTP_INVALID;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_PARTIAL;
/**
* Download dispatcher: used to dispatch downloader, this is desinged according to
* NetworkDispatcher in Android-Volley.
*
* @author Vincent Cheung (coolingfall@gmail.com)
*/
final class DownloadDispatcher extends Thread {
private static final String TAG = DownloadDispatcher.class.getSimpleName();
private static final int SLEEP_BEFORE_DOWNLOAD = 1500;
private static final int SLEEP_BEFORE_RETRY = 3500;
private static final int BUFFER_SIZE = 4096;
private static final String END_OF_STREAM = "unexpected end of stream";
private static final String DEFAULT_THREAD_NAME = "DownloadDispatcher";
private static final String IDLE_THREAD_NAME = "DownloadDispatcher-Idle";
private BlockingQueue<DownloadRequest> queue;
private DownloadDelivery delivery;
private long lastProgressTimestamp;
private volatile boolean quit = false;
/**
* Default constructor, with queue and delivery.
*
* @param queue download request queue
* @param delivery download delivery
*/
public DownloadDispatcher(BlockingQueue<DownloadRequest> queue, DownloadDelivery delivery) {
this.queue = queue;
this.delivery = delivery;
/* set thread name to idle */
setName(IDLE_THREAD_NAME);
}
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
DownloadRequest request = null;
while (true) {
try {
setName(IDLE_THREAD_NAME);
request = queue.take();
sleep(SLEEP_BEFORE_DOWNLOAD);
setName(DEFAULT_THREAD_NAME);
/* start download */
executeDownload(request);
} catch (InterruptedException e) {
/* we may have been interrupted because it was time to quit */
if (quit) {
if (request != null) {
request.finish();
}
return;
}
}
}
}
/* update download state */
private void updateState(DownloadRequest request, DownloadState state) {
request.updateDownloadState(state);
}
/* update download start state */
private void updateStart(DownloadRequest request, long totalBytes) {
/* if the request has failed before, donnot deliver callback */
if (request.downloadState() == DownloadState.FAILURE) {
updateState(request, DownloadState.RUNNING);
return;
}
/* set the download state of this request as running */
updateState(request, DownloadState.RUNNING);
delivery.postStart(request, totalBytes);
}
/* update download retrying */
private void updateRetry(DownloadRequest request) {
delivery.postRetry(request);
}
/* update download progress */
private void updateProgress(DownloadRequest request, long bytesWritten, long totalBytes) {
long currentTimestamp = System.currentTimeMillis();
if (bytesWritten != totalBytes &&
currentTimestamp - lastProgressTimestamp < request.progressInterval()) {
return;
}
/* save progress timestamp */
lastProgressTimestamp = currentTimestamp;
if (!request.isCanceled()) {
delivery.postProgress(request, bytesWritten, totalBytes);
}
}
/* update download success */
@SuppressWarnings("ResultOfMethodCallIgnored")
private void updateSuccess(DownloadRequest request) {
updateState(request, DownloadState.SUCCESSFUL);
/* notify the request download finish */
request.finish();
File file = new File(request.tempFilePath());
if (file.exists()) {
file.renameTo(new File(request.destinationFilePath()));
}
/* deliver success message */
delivery.postSuccess(request);
}
/* update download failure */
private void updateFailure(DownloadRequest request, int statusCode, String errMsg) {
updateState(request, DownloadState.FAILURE);
/* if the status code is 0, may be cause by the net error */
if (request.retryTime() >= 0) {
try {
/* sleep a while before retrying */
sleep(SLEEP_BEFORE_RETRY);
} catch (InterruptedException e) {
/* we may have been interrupted because it was time to quit */
if (quit) {
request.finish();
return;
}
}
/* retry downloading */
if (!request.isCanceled()) {
updateRetry(request);
executeDownload(request);
}
return;
}
/* notify the request that downloading has finished */
request.finish();
/* deliver failure message */
delivery.postFailure(request, statusCode, errMsg);
}
/* execute downloading */
private void executeDownload(DownloadRequest request) {
if (Thread.currentThread().isInterrupted()) {
return;
}
Downloader downloader = request.downloader();
RandomAccessFile raf = null;
InputStream is = null;
try {
File file = new File(request.tempFilePath());
raf = new RandomAccessFile(file, "rw");
long breakpoint = file.length();
long bytesWritten = 0;
if (file.exists()) {
/* set the range to continue the downloading */
raf.seek(breakpoint);
bytesWritten = breakpoint;
}
int statusCode = downloader.start(request.uri(), breakpoint);
if (statusCode != HTTP_OK && statusCode != HTTP_PARTIAL) {
throw new DownloadException(statusCode, "download fail");
}
is = downloader.byteStream();
long contentLength = downloader.contentLength();
if (contentLength <= 0 && is == null) {
throw new DownloadException(statusCode, "content length error");
}
contentLength += bytesWritten;
updateStart(request, contentLength);
if (is != null) {
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while (true) {
/* if the request has canceld, stop the downloading */
if (Thread.currentThread().isInterrupted() || request.isCanceled()) {
request.finish();
return;
}
/* if current is not wifi and mobile network is not allowed, stop */
if (request.allowedNetworkTypes() != 0 && !Utils.isWifi(request.context()) &&
(request.allowedNetworkTypes() & DownloadRequest.NETWORK_MOBILE) == 0) {
throw new DownloadException(statusCode, "network error");
}
/* read data into buffer from input stream */
length = readFromInputStream(buffer, is);
long fileSize = raf.length();
long totalBytes = contentLength <= 0 ? fileSize : contentLength;
if (length == -1) {
updateSuccess(request);
return;
} else if (length == Integer.MIN_VALUE) {
throw new DownloadException(statusCode, "transfer data error");
}
bytesWritten += length;
/* write buffer into local file */
raf.write(buffer, 0, length);
/* deliver progress callback */
updateProgress(request, bytesWritten, totalBytes);
}
} else {
throw new DownloadException(statusCode, "input stream error");
}
} catch (IOException e) {
if (e instanceof DownloadException) {
DownloadException exception = (DownloadException) e;
updateFailure(request, exception.getCode(), exception.getMessage());
} else {
updateFailure(request, 0, e.getMessage());
}
} finally {
downloader.close();
silentCloseFile(raf);
silentCloseInputStream(is);
}
}
/* read data from input stream */
int readFromInputStream(byte[] buffer, InputStream is) {
try {
return is.read(buffer);
} catch (IOException e) {
if (END_OF_STREAM.equals(e.getMessage())) {
return -1;
}
return Integer.MIN_VALUE;
}
}
/* a utility function to close a random access file without raising an exception */
static void silentCloseFile(RandomAccessFile raf) {
if (raf != null) {
try {
raf.close();
} catch (IOException ignore) {
}
}
}
/* a utility function to close an input stream without raising an exception */
static void silentCloseInputStream(InputStream is) {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
Log.w(TAG, "cannot close input stream", e);
}
}
/**
* Forces this dispatcher to quit immediately. If any download requests are still in
* the queue, they are not guaranteed to be processed.
*/
void quit() {
quit = true;
/* interrupt current thread */
interrupt();
Log.i(TAG, "download dispatcher has quit");
}
} |
package es.urjc.etsii.mtenrero;
import es.urjc.etsii.mtenrero.ServicioInterno.MailerResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLSocketFactory;
import javax.xml.ws.Response;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
public class Communication {
public void main(String email,String subject,String body) throws UnknownHostException, IOException{
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", email);
map.add("subject", subject);
map.add("body", body);
String requestUrl = "http://"+System.getenv("HAPROXY")+":8083/sendEmail";
System.out.println("REQUESTT_>>>>");
System.out.println(requestUrl);
System.out.println(email);
System.out.println(subject);
System.out.println(body);
ResponseEntity<MailerResponse> response = restTemplate.postForEntity(requestUrl,map,MailerResponse.class);
}
} |
package water;
import java.util.*;
import javassist.*;
import javassist.bytecode.*;
import javassist.bytecode.SignatureAttribute.ClassSignature;
import javassist.bytecode.SignatureAttribute.TypeArgument;
import water.api.Request.API;
import water.util.Log;
import water.util.Log.Tag.Sys;
public class Weaver {
private final ClassPool _pool;
private final CtClass _dtask, _iced, _enum, _freezable;
private final CtClass[] _serBases;
private final CtClass _fielddoc;
private final CtClass _arg;
// Versioning
// private final CtClass _apiSchema;
// private final CtClass _apiAdaptor;
// private final CtClass _apiHandler;
public static Class _typeMap;
public static volatile String[] _packages = new String[] { "water", "hex", "org.junit", "com.oxdata", "ai.h2o" };
Weaver() {
try {
_pool = ClassPool.getDefault();
_pool.insertClassPath(new ClassClassPath(Weaver.class));
_iced = _pool.get("water.Iced"); // Needs serialization
_dtask= _pool.get("water.DTask");// Needs serialization and remote execution
_enum = _pool.get("java.lang.Enum"); // Needs serialization
_freezable = _pool.get("water.Freezable"); // Needs serialization
// _apiSchema = _pool.get("water.api.rest.schemas.ApiSchema");
// _apiAdaptor = _pool.get("water.api.rest.ApiAdaptor");
// _apiHandler = _pool.get("water.api.rest.handlers.AbstractHandler");
//_versioned = _pool.get("water.api.rest.REST$Versioned");
_serBases = new CtClass[] { _iced, _dtask, _enum, _freezable };
for( CtClass c : _serBases ) c.freeze();
_fielddoc = _pool.get("water.api.DocGen$FieldDoc");// Is auto-documentation result
_arg = _pool.get("water.api.RequestArguments$Argument"); // Needs auto-documentation
} catch( NotFoundException e ) {
throw new RuntimeException(e);
}
}
public static void registerPackage(String name) {
synchronized( Weaver.class ) {
String[] a = _packages;
if(Arrays.asList(a).indexOf(name) < 0) {
String[] t = Arrays.copyOf(a, a.length + 1);
t[t.length-1] = name;
_packages = t;
}
}
}
public Class weaveAndLoad(String name, ClassLoader cl) {
try {
CtClass w = javassistLoadClass(name);
if( w == null ) return null;
return w.toClass(cl, null);
} catch( CannotCompileException e ) {
throw new RuntimeException(e);
}
}
// See if javaassist can find this class; if so then check to see if it is a
// subclass of water.DTask, and if so - alter the class before returning it.
private synchronized CtClass javassistLoadClass(String name) {
// Always use this weaver's classloader to preserve correct top-level classloader
// for loading H2O's classes.
// The point is to load all the time weaved classes by the same classloader
// and do not let JavaAssist to use thread context classloader.
// For normal H2O execution it will be always the same classloader
// but for running from 3rd party code, we preserve Boot's parent loader
// for all H2O internal classes.
final ClassLoader ccl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
try {
if( name.equals("water.Boot") ) return null;
CtClass cc = _pool.get(name); // Full Name Lookup
if( cc == null ) return null; // Oops? Try the system loader, but expected to work
if( !inPackages(cc.getPackageName()) ) return null;
for( CtClass base : _serBases )
if( cc.subclassOf(base) )
return javassistLoadClass(cc);
// Subtype of an alternative freezable?
if( cc.subtypeOf( _freezable ) ) {
// Find the alternative freezable base
CtClass xcc = cc;
CtClass ycc = null;
while( xcc.subtypeOf(_freezable) ) { ycc = xcc; xcc = xcc.getSuperclass(); }
if( !ycc.isFrozen() ) ycc.freeze(); // Freeze the alternative base
return cc == ycc ? cc : javassistLoadClass(cc); // And weave the subclass
}
return cc;
} catch( NotFoundException nfe ) {
return null; // Not found? Use the normal loader then
} catch( CannotCompileException e ) { // Expected to compile
throw new RuntimeException(e);
} catch (BadBytecode e) {
throw new RuntimeException(e);
} finally {
// Do not forget to configure classloader back to original value
Thread.currentThread().setContextClassLoader(ccl);
}
}
private static boolean inPackages(String pack) {
if( pack==null ) return false;
String[] p = _packages;
for( int i = 0; i < p.length; i++ )
if( pack.startsWith(p[i]) )
return true;
return false;
}
private synchronized CtClass javassistLoadClass( CtClass cc ) throws NotFoundException, CannotCompileException, BadBytecode {
if( cc.isFrozen() ) return cc;
// serialize parent
javassistLoadClass(cc.getSuperclass());
// Serialize enums first, since we need the raw_enum function for this class
for( CtField ctf : cc.getDeclaredFields() ) {
CtClass base = ctf.getType();
while( base.isArray() ) base = base.getComponentType();
if( base.subclassOf(_enum) && base != cc )
javassistLoadClass(base);
}
CtClass ccr = addSerializationMethods(cc);
ccr.freeze();
return ccr;
}
// Returns true if this method pre-exists *in the local class*.
// Returns false otherwise, which requires a local method to be injected
private static boolean hasExisting( String methname, String methsig, CtBehavior ccms[] ) throws NotFoundException {
for( CtBehavior cm : ccms )
if( cm.getName ().equals(methname) &&
cm.getSignature().equals(methsig ) )
return true;
return false;
}
// This method is handed a CtClass which is known to be a subclass of
// water.DTask. Add any missing serialization methods.
CtClass addSerializationMethods( CtClass cc ) throws CannotCompileException, NotFoundException {
if( cc.subclassOf(_enum) ) exposeRawEnumArray(cc);
if( cc.subclassOf(_iced) ) ensureAPImethods(cc);
if( cc.subclassOf(_iced) ||
cc.subclassOf(_dtask)||
cc.subtypeOf(_freezable)) {
cc.setModifiers(javassist.Modifier.setPublic(cc.getModifiers()));
ensureSerMethods(cc);
ensureNullaryCtor(cc);
ensureNewInstance(cc);
ensureType(cc);
}
return cc;
}
// Expose the raw enum array that all Enums have, so we can directly convert
// ordinal values to enum instances.
private void exposeRawEnumArray(CtClass cc) throws NotFoundException, CannotCompileException {
CtField field;
try {
field = cc.getField("$VALUES");
} catch( NotFoundException nfe ) {
// Eclipse apparently stores this in a different place.
field = cc.getField("ENUM$VALUES");
}
String body = "public static "+cc.getName()+" raw_enum(int i) { return i==255?null:"+field.getName()+"[i]; } ";
try {
cc.addMethod(CtNewMethod.make(body,cc));
} catch( CannotCompileException ce ) {
Log.warn(Sys.WATER,"
throw ce;
}
}
// Create a newInstance call which will rapidly make a new object of a
// particular type *without* Reflection's overheads.
private void ensureNewInstance(CtClass cc) throws NotFoundException, CannotCompileException {
CtMethod ccms[] = cc.getDeclaredMethods();
if( !javassist.Modifier.isAbstract(cc.getModifiers()) &&
!hasExisting("newInstance", "()Lwater/Freezable;", ccms) ) {
cc.addMethod(CtNewMethod.make(
"public water.Freezable newInstance() {\n" +
" return new " +cc.getName()+"();\n" +
"}", cc));
}
}
// Serialized types support a unique dense integer per-class, so we can do
// simple array lookups to get class info. The integer is cluster-wide
// unique and determined lazily.
private void ensureType(CtClass cc) throws NotFoundException, CannotCompileException {
CtMethod ccms[] = cc.getDeclaredMethods();
if( !javassist.Modifier.isAbstract(cc.getModifiers()) &&
!hasExisting("frozenType", "()I", ccms) ) {
// Build a simple field & method returning the type token
cc.addField(new CtField(CtClass.intType, "_frozen$type", cc));
cc.addMethod(CtNewMethod.make("public int frozenType() {" +
" return _frozen$type == 0 ? (_frozen$type=water.TypeMap.onIce(\""+cc.getName()+"\")) : _frozen$type;" +
"}",cc));
}
}
private void ensureVersion(CtClass cc) throws NotFoundException, CannotCompileException, BadBytecode {
CtMethod ccms[] = cc.getDeclaredMethods();
if (!javassist.Modifier.isAbstract(cc.getModifiers())) {
String gsig = cc.getGenericSignature();
ClassSignature csig = SignatureAttribute.toClassSignature(gsig);
// Warning: this is not doing proper parent (superclass/interfaces) traversal
TypeArgument ta = getTypeArg(csig.getSuperClass().getTypeArguments(), "Lwater/api/rest/Version");
if (ta!=null && !hasExisting("getVersion", "()"+ta.getType().encode(), ccms) ) {
String typeName = ta.toString();
String valueName = getValueFromType(typeName);
//cc.addMethod(CtNewMethod.make("public "+typeName+" getVersion() {" +
cc.addMethod(CtNewMethod.make("public water.api.rest.Version getVersion() {" +
" return "+valueName+";" +
"}",cc));
}
}
}
private String getValueFromType(String typeName) {
int idx = typeName.indexOf('$');
String t = typeName.substring(0, idx);
String v = typeName.substring(idx+1).toLowerCase();
return t+"."+v;
}
private TypeArgument getTypeArg(TypeArgument[] args, String prefix) {
for (TypeArgument ta : args)
if (ta.getType().encode().startsWith(prefix)) return ta;
return null;
}
private static abstract class FieldFilter {
abstract boolean filter( CtField ctf ) throws NotFoundException;
}
private void ensureAPImethods(CtClass cc) throws NotFoundException, CannotCompileException {
CtField ctfs[] = cc.getDeclaredFields();
boolean api = false;
for( CtField ctf : ctfs )
if( ctf.getName().equals("API_WEAVER") ) {
api = true; break;
}
if( api == false ) return;
CtField fielddoc=null;
CtField getdoc=null;
boolean callsuper = true;
for( CtClass base : _serBases )
if( cc.getSuperclass() == base ) callsuper = false;
// Auto-gen JSON output to AutoBuffers
make_body(cc,ctfs,callsuper,
"public water.AutoBuffer writeJSONFields(water.AutoBuffer ab) {\n",
" super.writeJSONFields(ab)",
" ab.putJSON%z(\"%s\",%s)",
" ab.putEnumJSON(\"%s\",%s)",
" ab.putJSON%z(\"%s\",%s)",
".put1(',');\n",
";\n return ab;\n}",
new FieldFilter() {
@Override boolean filter(CtField ctf) throws NotFoundException {
API api = null;
try {
api = (API) ctf.getAnnotation(API.class);
} catch( ClassNotFoundException ex) { throw new NotFoundException("getAnnotations throws ", ex); }
return api != null && (api.json() || !isInput(ctf.getType(), api));
}
});
// Auto-gen JSON & Args doc method. Requires a structured java object.
// Every @API annotated field is either a JSON field, an Argument, or both.
// field, and has some associated fields.
// H2OHexKey someField2; // Anything derived from RequestArguments$Argument
// static final String someField2Help = "some help text";
// static final int someField2MinVar = 1, someField2MaxVar = 1;
// String[] someField; // Anything NOT derived from Argument is a JSON field
// static final String someFieldHelp = "some help text";
// static final int someFieldMinVar = 1, someFieldMaxVar = 1;
// xxxMinVar and xxxMaxVar are optional; if xxxMinVar is missing it
// defaults to 1, and if xxxMaxVar is missing it defaults "till now".
StringBuilder sb = new StringBuilder();
sb.append("new water.api.DocGen$FieldDoc[] {");
// Get classes in the hierarchy with marker field
ArrayList<CtClass> classes = new ArrayList<CtClass>();
CtClass current = cc;
while( true ) { // For all self & superclasses
classes.add(current);
current = current.getSuperclass();
api = false;
for( CtField ctf : current.getDeclaredFields() )
if( ctf.getName().equals("API_WEAVER") )
api = true;
if( api == false ) break;
}
// Start with parent classes to get fields in order
Collections.reverse(classes);
boolean first = true;
for(CtClass c : classes) {
for( CtField ctf : c.getDeclaredFields() ) {
int mods = ctf.getModifiers();
if( javassist.Modifier.isStatic(mods) ) {
if( c == cc ) { // Capture the DOC_* fields for self only
if( ctf.getName().equals("DOC_FIELDS") ) fielddoc = ctf;
if( ctf.getName().equals("DOC_GET") ) getdoc = ctf;
}
continue; // Only auto-doc instance fields (not static)
}
first = addDocIfAPI(sb,ctf,cc,first);
}
}
sb.append("}");
if( fielddoc == null ) throw new CannotCompileException("Did not find static final DocGen.FieldDoc[] DOC_FIELDS field;");
if( !fielddoc.getType().isArray() ||
fielddoc.getType().getComponentType() != _fielddoc )
throw new CannotCompileException("DOC_FIELDS not declared static final DocGen.FieldDoc[];");
cc.removeField(fielddoc); // Remove the old one
cc.addField(fielddoc,CtField.Initializer.byExpr(sb.toString()));
cc.addMethod(CtNewMethod.make(" public water.api.DocGen$FieldDoc[] toDocField() { return DOC_FIELDS; }",cc));
if( getdoc != null )
cc.addMethod(CtNewMethod.make(" public String toDocGET() { return DOC_GET; }",cc));
}
private boolean addDocIfAPI( StringBuilder sb, CtField ctf, CtClass cc, boolean first ) throws NotFoundException, CannotCompileException {
String name = ctf.getName();
Object[] as;
try { as = ctf.getAnnotations(); }
catch( ClassNotFoundException ex) { throw new NotFoundException("getAnnotations throws ", ex); }
API api = null;
for(Object o : as) if(o instanceof API) api = (API) o;
if( api != null ) {
String help = api.help();
int min = api.since();
int max = api.until();
if( min < 1 || min > 1000000 ) throw new CannotCompileException("Found field '"+name+"' but 'since' < 1 or 'since' > 1000000");
if( max < min || (max > 1000000 && max != Integer.MAX_VALUE) )
throw new CannotCompileException("Found field '"+name+"' but 'until' < "+min+" or 'until' > 1000000");
if( first ) first = false;
else sb.append(",");
boolean input = isInput(ctf.getType(), api);
sb.append("new water.api.DocGen$FieldDoc(\""+name+"\",\""+help+"\","+min+","+max+","+ctf.getType().getName()+".class,"+input+","+api.required()+",water.api.ParamImportance."+api.importance()+",water.api.Direction."+api.direction()+",\""+api.path()+"\","+ api.type().getName()+".class,\""+api.valid()+"\", \""+api.enabled()+"\",\""+api.visible()+"\")");
}
return first;
}
private final boolean isInput(CtClass fieldType, API api) {
return Request2.Helper.isInput(api) ||
// Legacy
fieldType.subclassOf(_arg);
}
// Support for a nullary constructor, for deserialization.
private void ensureNullaryCtor(CtClass cc) throws NotFoundException, CannotCompileException {
// Build a null-ary constructor if needed
String clzname = cc.getSimpleName();
if( !hasExisting(clzname,"()V",cc.getDeclaredConstructors()) ) {
String body = "public "+clzname+"() { }";
cc.addConstructor(CtNewConstructor.make(body,cc));
} else {
CtConstructor ctor = cc.getConstructor("()V");
ctor.setModifiers(javassist.Modifier.setPublic(ctor.getModifiers()));
}
}
// Serialization methods: read, write & copyOver.
private void ensureSerMethods(CtClass cc) throws NotFoundException, CannotCompileException {
// Check for having "read" and "write". Either All or None of read & write
// must be defined. Note that I use getDeclaredMethods which returns only
// the local methods. The singular getDeclaredMethod searches for a
// specific method *up into superclasses*, which will trigger premature
// loading of those superclasses.
CtMethod ccms[] = cc.getDeclaredMethods();
boolean w = hasExisting("write", "(Lwater/AutoBuffer;)Lwater/AutoBuffer;", ccms);
boolean r = hasExisting("read" , "(Lwater/AutoBuffer;)Lwater/Freezable;" , ccms);
boolean d = cc.subclassOf(_dtask); // Subclass of DTask?
boolean c = hasExisting("copyOver" , "(Lwater/Freezable;)V" , ccms);
if( w && r && (!d || c) ) return;
if( w || r || c )
throw new RuntimeException(cc.getName() +" must implement all of " +
"read(AutoBuffer) and write(AutoBuffer) and copyOver(Freezable) or none");
// Add the serialization methods: read, write.
CtField ctfs[] = cc.getDeclaredFields();
// We cannot call Iced.xxx, as these methods always throw a
// RuntimeException (to make sure we noisily fail instead of silently
// fail). But we DO need to call the super-chain of serialization methods
// - stopping at DTask.
boolean callsuper = true;
// for( CtClass base : _serBases )
// if( cc.getSuperclass() == base ) callsuper = false;
// Running example is:
// class Crunk extends DTask {
// int _x; int _xs[]; double _d;
// Build a write method that looks something like this:
// public AutoBuffer write( AutoBuffer s ) {
// s.put4(_x);
// s.putA4(_xs);
// s.put8d(_d);
// TODO use Freezable.write instead of AutoBuffer.put for final classes
make_body(cc,ctfs,callsuper,
"public water.AutoBuffer write(water.AutoBuffer ab) {\n",
" super.write(ab);\n",
" ab.put%z(%s);\n",
" ab.putEnum(%s);\n",
" ab.put%z(%s);\n",
"",
" return ab;\n" +
"}", null);
// Build a read method that looks something like this:
// public T read( AutoBuffer s ) {
// _x = s.get4();
// _xs = s.getA4();
// _d = s.get8d();
make_body(cc,ctfs,callsuper,
"public water.Freezable read(water.AutoBuffer s) {\n",
" super.read(s);\n",
" %s = s.get%z();\n",
" %s = %c.raw_enum(s.get1());\n",
" %s = (%C)s.get%z(%c.class);\n",
"",
" return this;\n" +
"}", null);
// Build a copyOver method that looks something like this:
// public void copyOver( T s ) {
// _x = s._x;
// _xs = s._xs;
// _d = s._d;
if( d ) make_body(cc,ctfs,callsuper,
"public void copyOver(water.Freezable i) {\n"+
" "+cc.getName()+" s = ("+cc.getName()+")i;\n",
" super.copyOver(s);\n",
" %s = s.%s;\n",
" %s = s.%s;\n",
" %s = s.%s;\n",
"",
"}", null);
}
// Produce a code body with all these fill-ins.
private final void make_body(CtClass cc, CtField[] ctfs, boolean callsuper,
String header,
String supers,
String prims,
String enums,
String freezables,
String field_sep,
String trailer,
FieldFilter ff
) throws CannotCompileException, NotFoundException {
StringBuilder sb = new StringBuilder();
sb.append(header);
if( callsuper ) sb.append(supers);
boolean debug_print = false;
boolean first = !callsuper;
for( CtField ctf : ctfs ) {
int mods = ctf.getModifiers();
if( javassist.Modifier.isTransient(mods) || javassist.Modifier.isStatic(mods) ) {
debug_print |= ctf.getName().equals("DEBUG_WEAVER");
continue; // Only serialize not-transient instance fields (not static)
}
if( ff != null && !ff.filter(ctf) ) continue; // Fails the filter
if( first ) first = false;
else sb.append(field_sep);
CtClass base = ctf.getType();
while( base.isArray() ) base = base.getComponentType();
int ftype = ftype(ctf.getSignature(), cc, ctf ); // Field type encoding
if( ftype%20 == 9 ) {
sb.append(freezables);
} else if( ftype%20 == 10 ) { // Enums
sb.append(enums);
} else {
sb.append(prims);
}
String z = FLDSZ1[ftype % 20];
for(int i = 0; i < ftype / 20; ++i ) z = 'A'+z;
subsub(sb, "%z", z); // %z ==> short type name
subsub(sb, "%s", ctf.getName()); // %s ==> field name
subsub(sb, "%c", base.getName().replace('$', '.')); // %c ==> base class name
subsub(sb, "%C", ctf.getType().getName().replace('$', '.')); // %C ==> full class name
}
sb.append(trailer);
String body = sb.toString();
if( debug_print ) {
System.err.println(cc.getName()+" "+body);
}
try {
cc.addMethod(CtNewMethod.make(body,cc));
} catch( CannotCompileException e ) {
throw Log.err("
}
}
static private final String[] FLDSZ1 = {
"Z","1","2","2","4","4f","8","8d","Str","","Enum" // prims, String, Freezable, Enum
};
// Field types:
// 0-7: primitives
// 8,9, 10: String, Freezable, Enum
// 20-27: array-of-prim
// 28,29, 30: array-of-String, Freezable, Enum
// Barfs on all others (eg Values or array-of-Frob, etc)
private int ftype( String sig, CtClass ct, CtField fld ) throws NotFoundException {
switch( sig.charAt(0) ) {
case 'Z': return 0; // Booleans: I could compress these more
case 'B': return 1; // Primitives
case 'C': return 2;
case 'S': return 3;
case 'I': return 4;
case 'F': return 5;
case 'J': return 6;
case 'D': return 7;
case 'L': // Handled classes
if( sig.equals("Ljava/lang/String;") ) return 8;
String clz = sig.substring(1,sig.length()-1).replace('/', '.');
CtClass argClass = _pool.get(clz);
if( argClass.subtypeOf(_pool.get("water.Freezable")) ) return 9;
if( argClass.subtypeOf(_pool.get("java.lang.Enum")) ) return 10;
break;
case '[': // Arrays
return ftype(sig.substring(1), ct, fld)+20; // Same as prims, plus 20
}
throw barf(ct, fld);
}
// Replace 2-byte strings like "%s" with s2.
static private void subsub( StringBuilder sb, String s1, String s2 ) {
int idx;
while( (idx=sb.indexOf(s1)) != -1 ) sb.replace(idx,idx+2,s2);
}
private static RuntimeException barf( CtClass ct, CtField fld ) throws NotFoundException {
return new RuntimeException(ct.getSimpleName()+"."+fld.getName()+" of type "+(fld.getType().getSimpleName())+": Serialization not implemented; does not extend Iced or DTask");
}
} |
package pl.magosa.microbe;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class TanhTransferFunctionTest {
private static TransferFunction transferFunction;
@BeforeClass
public static void setUp() {
transferFunction = new TanhTransferFunction();
}
@Test
public void testFunction() {
assertEquals(0.76159415595576, transferFunction.function(1.0), 0.001);
assertEquals(0.0, transferFunction.function(0.0), 0.001);
assertEquals(0.46211715726001, transferFunction.function(0.5), 0.001);
assertEquals(-0.76159415595576, transferFunction.function(-1.0), 0.001);
}
@Test
public void testDerivative() {
assertEquals(0.97754116486012, transferFunction.derivative(transferFunction.function(0.151)), 0.001);
assertEquals(0.74120496390821, transferFunction.derivative(transferFunction.function(0.561)), 0.001);
}
@Test
public void testGetUpperLimit() {
assertEquals(1.0, transferFunction.getUpperLimit(), 0.001);
}
@Test
public void testGetLowerLimit() {
assertEquals(-1.0, transferFunction.getLowerLimit(), 0.001);
}
@Test
public void makeArray() {
double[] result = transferFunction.makeArray(5, new int[] { 1, 2 });
assertArrayEquals(new double[] { -1.0, 1.0, 1.0, -1.0, -1.0 }, result, 0.01);
}
@Test
public void normalize() {
assertEquals(-1.0, transferFunction.normalize(0, 0, 5), 0.01);
assertEquals(0.0, transferFunction.normalize(128, 0, 255), 0.01);
assertEquals(-0.5, transferFunction.normalize(250, 0, 1000), 0.01);
assertEquals(1.0, transferFunction.normalize(0, 5, 0), 0.01);
assertEquals(0.0, transferFunction.normalize(128, 255, 0), 0.01);
assertEquals(0.5, transferFunction.normalize(250, 1000, 0), 0.01);
}
} |
// S t e p M e n u //
// Contact author at herve.bitteur@laposte.net to report bugs & suggestions. //
package omr.step;
import omr.Main;
import omr.sheet.Sheet;
import omr.sheet.SheetManager;
import omr.util.Implement;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/**
* Class <code>StepMenu</code> encapsulates the user interface needed to deal
* with application steps. Steps are represented by menu items, each one being
* a check box, to indicate the current status regarding the execution of the
* step (done or not done).
*
* @author Hervé Bitteur
* @version $Id$
*/
public class StepMenu
{
/** The concrete UI menu */
private final JMenu menu;
// StepMenu //
/**
* Generates the sub-menu to be inserted in the application menu hierarchy.
*
* @param label Name for the sub-menu
*/
public StepMenu (String label)
{
menu = new JMenu(label);
menu.setToolTipText("Select processing step for the current sheet");
// List of Steps classes in proper order
for (Step step : Step.values()) {
menu.add(new StepItem(step));
}
// Listener to modify attributes on-the-fly
menu.addMenuListener(new MyMenuListener());
}
// setEnabled //
/**
* Allow to enable or disable this whole menu
* @param bool true to enable, false to disable
*/
public void setEnabled (boolean bool)
{
menu.setEnabled(bool);
}
// getMenu //
/**
* Report the concrete UI menu
*
* @return the menu entity
*/
public JMenu getMenu ()
{
return menu;
}
// StepAction //
/**
* Action to be performed when the related step item is selected
*/
private static class StepAction
extends AbstractAction
{
// The related step
final Step step;
public StepAction (Step step)
{
super(step.toString());
this.step = step;
putValue(SHORT_DESCRIPTION, step.getDescription());
}
@Implement(AbstractAction.class)
public void actionPerformed (ActionEvent e)
{
Sheet sheet = SheetManager.getSelectedSheet();
Main.getGui()
.setTarget(sheet.getPath());
step.performParallel(sheet, null);
}
}
// StepItem //
/**
* Class <code>StepItem</code> implements a menu item linked to a given step
*/
private static class StepItem
extends JCheckBoxMenuItem
{
// StepItem //
public StepItem (Step step)
{
super(new StepAction(step));
}
// displayState //
public void displayState (Sheet sheet)
{
StepAction action = (StepAction) getAction();
if (sheet == null) {
setState(false);
action.setEnabled(false);
} else {
if (sheet.isBusy()) {
setState(false);
setEnabled(false);
} else {
boolean bool = sheet.getSheetSteps()
.isDone(action.step);
setState(bool);
setEnabled(!bool);
}
}
}
}
// MyMenuListener //
/**
* Class <code>MyMenuListener</code> is triggered when the whole sub-menu
* is entered. This is done with respect to currently displayed sheet. The
* steps already done are flagged as such.
*/
private class MyMenuListener
implements MenuListener
{
@Implement(MenuListener.class)
public void menuCanceled (MenuEvent e)
{
}
@Implement(MenuListener.class)
public void menuDeselected (MenuEvent e)
{
}
@Implement(MenuListener.class)
public void menuSelected (MenuEvent e)
{
Sheet sheet = SheetManager.getSelectedSheet();
for (int i = 0; i < menu.getItemCount(); i++) {
StepItem item = (StepItem) menu.getItem(i);
// Adjust the status for each step
item.displayState(sheet);
}
}
}
} |
package fr.insee.stamina.meta;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.jena.datatypes.BaseDatatype;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.vocabulary.DCTerms;
import org.apache.jena.vocabulary.RDFS;
import org.apache.jena.vocabulary.XSD;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import fr.insee.stamina.utils.ADMS;
import fr.insee.stamina.utils.DCAT;
import fr.insee.stamina.utils.Names;
/**
* The <code>ADMSModelMaker</code> creates and saves Jena models corresponding to the ADMS descriptions of the repositories.
*
* @author Franck Cotton
* @version 0.1, 15 Apr 2016
*/
public class ADMSModelMaker {
public static String ADMS_BASE_URI = "http://stamina-project.org/meta/adms/";
public static String ADMS_TURTLE_FILE = "src/main/resources/data/adms.ttl";
/** Log4J2 logger */
private static final Logger logger = LogManager.getLogger(ADMSModelMaker.class);
/** Current Jena model */
private Model admsModel = null;
/** Resource corresponding to the catalog */
Resource repositoryResource = null;
/**
* Main method: basic launcher that produces all the models.
*
* @param args Not used.
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ADMSModelMaker modelMaker = new ADMSModelMaker();
logger.debug("New ISICModelMaker instance created");
modelMaker.createRepositoryModel();
}
/**
* Creates an Jena model corresponding to the ADMS repository and saves it to a Turtle file.
*
* @throws IOException In case of problem saving the file.
*/
private void createRepositoryModel() throws IOException {
logger.debug("Construction of the Jena model for the ADMS repository");
admsModel = ModelFactory.createDefaultModel();
admsModel.setNsPrefix("rdfs", RDFS.getURI());
admsModel.setNsPrefix("xsd", XSD.getURI());
admsModel.setNsPrefix("dcat", DCAT.getURI());
admsModel.setNsPrefix("adms", ADMS.getURI());
admsModel.setNsPrefix("dcterms", DCTerms.getURI());
repositoryResource = admsModel.createResource(ADMS_BASE_URI + "repository", ADMS.AssetRepository);
repositoryResource.addProperty(DCTerms.title, admsModel.createLiteral("The Stamina Catalog", "en"));
repositoryResource.addProperty(DCTerms.description, admsModel.createLiteral("The catalog of all semantic assets created in the Stamina project", "en"));
// There should be a simpler way of doing that
Literal dateLiteral = admsModel.createTypedLiteral((new SimpleDateFormat("yyyy-MM-dd")).format(new Date()), new BaseDatatype(XSD.date.getURI()));
repositoryResource.addProperty(DCTerms.created, dateLiteral);
repositoryResource.addProperty(DCTerms.publisher, admsModel.createResource("http:
// Produce the asset and distribution descriptions for CPC 1.1, CPC 2, CPC 2.1, ISIC 3.1 and 4
this.addISICAssetModel("CPC", "1.1");
this.addISICAssetModel("CPC", "2");
this.addISICAssetModel("CPC", "2.1");
this.addISICAssetModel("ISIC", "3.1");
this.addISICAssetModel("ISIC", "4");
// Write the Turtle file and clear the model
admsModel.write(new FileOutputStream(ADMS_TURTLE_FILE), "TTL");
admsModel.close();
}
/**
* Adds the asset and asset distribution information for a classification in the model.
*
* @param classification Short name of the classification, e.g. "NACE", "ISIC", etc.
* @param version Version of the classification ("4", "2.1", "2008", etc.).
*/
private void addISICAssetModel(String classification, String version) {
Resource csAssetResource = admsModel.createResource(ADMS_BASE_URI + "asset/" + Names.getCSContext(classification, version), ADMS.Asset);
csAssetResource.addProperty(DCTerms.type, ADMS.TaxonomyAssetType); // Or CodeList
csAssetResource.addProperty(ADMS.identifier, Names.getCSShortName(classification, version));
csAssetResource.addProperty(DCTerms.title, Names.getCSLabel(classification, version));
csAssetResource.addProperty(ADMS.status, ADMS.CompletedStatus); // TODO The asset itself is completed, the distribution is under development
// TODO Do we directly take the SKOS ConceptScheme resource as ADMS distribution, or do we define a specific resource?
Resource csDistributionResource = admsModel.createResource(csAssetResource.getURI() + "/skos", ADMS.AssetDistribution);
csDistributionResource.addProperty(ADMS.status, ADMS.UnderDevelopmentStatus);
csDistributionResource.addProperty(ADMS.representationTechnique, ADMS.SKOSRepresentationTechnique);
csDistributionResource.addProperty(ADMS.representationTechnique, ADMS.SPARQLRepresentationTechnique);
csAssetResource.addProperty(DCAT.distribution, csDistributionResource);
repositoryResource.addProperty(ADMS.includedAsset, csAssetResource);
}
} |
package fr.ourten.teabeans.property;
import fr.ourten.teabeans.binding.BidirectionalBinding;
import fr.ourten.teabeans.binding.WeakObservableListener;
import fr.ourten.teabeans.listener.ValueChangeListener;
import fr.ourten.teabeans.listener.ValueInvalidationListener;
import fr.ourten.teabeans.value.ObservableValue;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Property<T> implements IProperty<T>
{
/**
* The list of attached listeners that need to be notified when the value
* change.
*/
protected final List<ValueChangeListener<? super T>> valueChangeListeners;
protected final List<ValueInvalidationListener> valueInvalidationListeners;
private final List<ValueChangeListener<? super T>> valueChangeListenersToRemove = new ArrayList<>(1);
private final List<ValueInvalidationListener> valueInvalidationListenersToRemove = new ArrayList<>(1);
private boolean isPropagatingEvents;
/**
* The listener used to bind this property to another.
*/
private ValueInvalidationListener propertyInvalidator;
private ObservableValue<? extends T> observable;
private boolean isObserving;
protected T value;
protected T oldValue;
private boolean isMuted;
public Property(T value)
{
valueChangeListeners = new ArrayList<>();
valueInvalidationListeners = new ArrayList<>();
isObserving = false;
this.value = value;
oldValue = value;
}
@Override
public void addListener(ValueChangeListener<? super T> listener)
{
if (!isObserving && observable != null)
startObserving();
if (!valueChangeListeners.contains(listener))
valueChangeListeners.add(listener);
}
@Override
public void removeListener(ValueChangeListener<? super T> listener)
{
if (isPropagatingEvents)
{
valueChangeListenersToRemove.add(listener);
return;
}
valueChangeListeners.remove(listener);
if (valueChangeListeners.isEmpty() && observable != null)
stopObserving();
}
@Override
public void addListener(ValueInvalidationListener listener)
{
if (!isObserving && observable != null)
startObserving();
if (!valueInvalidationListeners.contains(listener))
valueInvalidationListeners.add(listener);
}
@Override
public void removeListener(ValueInvalidationListener listener)
{
if (isPropagatingEvents)
{
valueInvalidationListenersToRemove.add(listener);
return;
}
valueInvalidationListeners.remove(listener);
if (valueInvalidationListeners.isEmpty() && observable != null)
stopObserving();
}
@Override
public void mute()
{
isMuted = true;
}
@Override
public void unmute()
{
isMuted = false;
invalidate();
}
@Override
public boolean isMuted()
{
return isMuted;
}
@Override
public T getValue()
{
return observable == null ? value : observable.getValue();
}
@Override
public void setValue(T value)
{
if (isBound())
throw new UnsupportedOperationException("Cannot set the value of a bound property");
setPropertyValue(value);
}
protected void setPropertyValue(T value)
{
this.value = value;
invalidate();
}
@Override
public void invalidate()
{
if (isMuted())
return;
if (!Objects.equals(value, oldValue))
fireChangeListeners(oldValue, value);
fireInvalidationListeners();
oldValue = value;
}
@Override
public void bindProperty(ObservableValue<? extends T> observable)
{
Objects.requireNonNull(observable, "Cannot bind to null");
if (!observable.equals(this.observable))
{
unbind();
this.observable = observable;
if (propertyInvalidator == null)
propertyInvalidator = new WeakObservableListener(this);
if (hasListeners())
startObserving();
if (isMuted())
return;
if (value == null || !value.equals(observable.getValue()))
fireChangeListeners(value, observable.getValue());
fireInvalidationListeners();
}
}
@Override
public void unbind()
{
if (observable != null)
{
value = observable.getValue();
stopObserving();
observable = null;
}
}
@Override
public boolean isBound()
{
return observable != null;
}
@Override
public void bindBidirectional(IProperty<T> other)
{
new BidirectionalBinding<>(this, other);
}
@Override
public void unbindBidirectional(IProperty<T> other)
{
BidirectionalBinding<T> binding = new BidirectionalBinding<>(this, other);
binding.unbind();
}
protected void fireChangeListeners(T oldValue, T newValue)
{
isPropagatingEvents = true;
for (ValueChangeListener<? super T> listener : valueChangeListeners)
listener.valueChanged(this, oldValue, newValue);
isPropagatingEvents = false;
for (ValueChangeListener<? super T> listener : valueChangeListenersToRemove)
valueChangeListeners.remove(listener);
valueChangeListenersToRemove.clear();
}
protected void fireInvalidationListeners()
{
isPropagatingEvents = true;
for (ValueInvalidationListener listener : valueInvalidationListeners)
listener.invalidated(this);
isPropagatingEvents = false;
for (ValueInvalidationListener listener : valueInvalidationListenersToRemove)
valueInvalidationListeners.remove(listener);
valueInvalidationListenersToRemove.clear();
}
protected void startObserving()
{
isObserving = true;
observable.addListener(propertyInvalidator);
}
protected void stopObserving()
{
isObserving = false;
observable.removeListener(propertyInvalidator);
}
protected boolean isObserving()
{
return isObserving;
}
protected boolean hasObservable()
{
return observable != null;
}
protected boolean hasListeners()
{
return !valueInvalidationListeners.isEmpty() || !valueChangeListeners.isEmpty();
}
} |
package liquibase.datatype.core;
import liquibase.database.Database;
import liquibase.database.core.DB2Database;
import liquibase.database.core.MSSQLDatabase;
import liquibase.database.core.MySQLDatabase;
import liquibase.database.core.OracleDatabase;
import liquibase.datatype.DatabaseDataType;
import liquibase.datatype.LiquibaseDataType;
import liquibase.statement.DatabaseFunction;
import java.util.Arrays;
import java.util.Collections;
public class UnknownType extends LiquibaseDataType {
public UnknownType() {
super("UNKNOWN", 0, 2);
}
public UnknownType(String name) {
super(name, 0, 2);
}
public UnknownType(String name, int minParameters, int maxParameters) {
super(name, minParameters, maxParameters);
}
@Override
public DatabaseDataType toDatabaseDataType(Database database) {
int dataTypeMaxParameters;
if (getName().equalsIgnoreCase("enum") || getName().equalsIgnoreCase("set")) {
dataTypeMaxParameters = Integer.MAX_VALUE;
} else {
dataTypeMaxParameters = database.getDataTypeMaxParameters(getName());
}
Object[] parameters = getParameters();
if (database instanceof MySQLDatabase && (
getName().equalsIgnoreCase("TINYBLOB")
|| getName().equalsIgnoreCase("MEDIUMBLOB")
|| getName().equalsIgnoreCase("TINYTEXT")
|| getName().equalsIgnoreCase("MEDIUMTEXT")
|| getName().equalsIgnoreCase("REAL")
)) {
parameters = new Object[0];
}
if (database instanceof DB2Database && (getName().equalsIgnoreCase("REAL") || getName().equalsIgnoreCase("XML"))) {
parameters = new Object[0];
}
if (database instanceof MSSQLDatabase && (
getName().equalsIgnoreCase("REAL")
|| getName().equalsIgnoreCase("XML")
|| getName().equalsIgnoreCase("HIERARCHYID")
|| getName().equalsIgnoreCase("DATETIMEOFFSET")
|| getName().equalsIgnoreCase("IMAGE")
|| getName().equalsIgnoreCase("NTEXT")
|| getName().equalsIgnoreCase("SYSNAME")
|| getName().equalsIgnoreCase("SMALLMONEY")
)) {
parameters = new Object[0];
}
if (database instanceof OracleDatabase) {
if (getName().equalsIgnoreCase("LONG")
|| getName().equalsIgnoreCase("NCLOB")
|| getName().equalsIgnoreCase("BFILE")
|| getName().equalsIgnoreCase("ROWID")
|| getName().equalsIgnoreCase("XMLTYPE")
|| getName().equalsIgnoreCase("ANYDATA")
|| getName().equalsIgnoreCase("SDO_GEOMETRY")
) {
parameters = new Object[0];
} else if (getName().toUpperCase().startsWith("INTERVAL ")) {
return new DatabaseDataType(getName().replaceAll("\\(\\d+\\)", ""));
} else if (((OracleDatabase) database).getUserDefinedTypes().contains(getName().toUpperCase())) {
return new DatabaseDataType(getName().toUpperCase()); //user defined tye
}
}
if (dataTypeMaxParameters < parameters.length) {
parameters = Arrays.copyOfRange(parameters, 0, dataTypeMaxParameters);
}
DatabaseDataType type = new DatabaseDataType(getName().toUpperCase(), parameters);
type.addAdditionalInformation(getAdditionalInformation());
return type;
}
@Override
public String objectToSql(Object value, Database database) {
if (value instanceof DatabaseFunction) {
return super.objectToSql(value, database);
} else {
return "'"+super.objectToSql(value, database)+"'";
}
}
} |
package gov.nasa.jpl.mbee.mdk;
public class DocGen3Profile {
public static final String sectionStereotype = "Dynamic View";
public static final String paragraphStereotype = "Paragraph";
public static final String documentStereotype = "zzDocument";
public static final String imageStereotype = "Image";
public static final String nextStereotype = "Next";
public static final String firstStereotype = "First";
public static final String oldQueriesStereotype = "Queries";
public static final String queriesStereotype = "Expose";
public static final String nosectionStereotype = "NoSection";
public static final String appendixStereotype = "zzAppendix";
public static final String viewpointStereotype = "Viewpoint";
public static final String viewStereotype = "View";
public static final String dgviewStereotype = "view";
public static final String oldDgviewStereotype = "DGView";
public static final String appendixViewStereotype = "AppendixView";
public static final String structuredQueryStereotype = "StructuredQuery";
public static final String tableStereotype = "Table";
public static final String bulletedListStereotype = "BulletedList";
public static final String temporalDiffStereotype = "TemporalDiff";
public static final String combinedMatrixStereotype = "zzCombinedMatrix";
public static final String methodStereotype = "Method";
public static final String tomsawyerDiagramStereotype = "TomSawyerDiagram";
public static final String customTableStereotype = "zzCustomTable";
public static final String tableStructureStereotype = "TableStructure";
public static final String tablePropertyColumnStereotype = "TablePropertyColumn";
public static final String tableExpressionColumnStereotype = "TableExpressionColumn";
public static final String tableAttributeColumnStereotype = "TableAttributeColumn";
public static final String tableSumRowStereotype = "TableSumRow";
public static final String tableColumnStereotype = "TableColumn";
public static final String dependencyMatrixStereotype = "zzDependencyMatrix";
public static final String genericTableStereotype = "GenericTable";
public static final String hierarchicalPropertiesTableStereotype = "HierarchicalPropertiesTable";
public static final String propertiesTableByAttributesStereotype = "PropertiesTableByAttributes";
public static final String viewpointConstraintStereotype = "ViewpointConstraint";
public static final String userScriptStereotype = "UserScript";
public static final String userScriptCFStereotype = "Collect/Filter UserScript";
public static final String validationScriptStereotype = "ValidationScript";
public static final String missionMappingStereotype = "MissionMapping";
public static final String libraryChooserStereotype = "LibraryMapping";
public static final String javaExtensionStereotype = "JavaExtension";
public static final String collectionStereotype = "CollectionAndFilterGroup";
public static final String documentMetaStereotype = "DocumentMeta";
public static final String documentViewStereotype = "Product";
public static final String accountableForStereotype = "accountableFor";
public static final String approvesStereotype = "approves";
public static final String concursStereotype = "concurs";
public static final String projectStaffStereotype = "ProjectStaff";
public static final String roleStereotype = "Role";
public static final String filterDiagramTypeStereotype = "FilterByDiagramType";
public static final String filterNameStereotype = "FilterByNames";
public static final String filterMetaclassStereotype = "FilterByMetaclasses";
public static final String filterStereotypeStereotype = "FilterByStereotypes";
public static final String filterExpressionStereotype = "FilterByExpression";
public static final String collectRelMetaclassStereotype = "CollectByDirectedRelationshipMetaclasses";
public static final String collectRelStereotypeStereotype = "CollectByDirectedRelationshipStereotypes";
public static final String collectStereotypePropStereotype = "CollectByStereotypeProperties";
public static final String collectOwnedElementStereotype = "CollectOwnedElements";
public static final String collectOwnerStereotype = "CollectOwners";
public static final String collectAssociationStereotype = "CollectByAssociation";
public static final String collectTypeStereotype = "CollectTypes";
public static final String collectDiagram = "CollectThingsOnDiagram";
public static final String collectClassifierAttributes = "CollectClassifierAttributes";
public static final String collectExpressionStereotype = "CollectByExpression";
public static final String associationChoosable = "AssociationTypeChoosable";
public static final String depthChoosable = "DepthChoosable";
public static final String derivedChoosable = "ConsiderDerivedChoosable";
public static final String directionChoosable = "DirectionChoosable";
public static final String stereotypeChoosable = "StereotypeChoosable";
public static final String metaclassChoosable = "MetaclassChoosable";
public static final String includeChoosable = "IncludeChoosable";
public static final String nameChoosable = "NameChoosable";
public static final String diagramTypeChoosable = "DiagramTypeChoosable";
public static final String expressionChoosable = "ExpressionChoosable";
public static final String expression = "Expression";
public static final String sortable = "Sortable";
public static final String propertyChoosable = "PropertyChoosable";
public static final String attributeChoosable = "AttributeChoosable";
public static final String editableChoosable = "EditableChoosable";
public static final String expressionLibrary = "ExpressionLibrary";
public static final String stereotypePropertyChoosable = "StereotypePropertiesChoosable";
public static final String documentationChoosable = "DocumentationChoosable";
public static final String headersChoosable = "HeadersChoosable";
public static final String stereotypedRelChoosable = "StereotypedRelationshipsChoosable";
public static final String precisionChoosable = "PrecisionChoosable";
public static final String inheritedChoosable = "IncludeInheritedChoosable";
public static final String hasCaptions = "HasCaptions";
public static final String docSkippable = "DocumentationSkippable";
public static final String parallel = "Parallel";
public static final String intersection = "Intersection";
public static final String union = "Union";
public static final String removeDuplicates = "RemoveDuplicates";
public static final String sortByName = "SortByName";
public static final String sortByAttribute = "SortByAttribute";
public static final String sortByProperty = "SortByProperty";
public static final String sortByExpression = "SortByExpression";
public static final String conformStereotype = "Conforms";
public static final String templateStereotype = "FormattingAndDisplayTemplate";
public static final String collectFilterStereotype = "CollectOrFilter";
public static final String ignorableStereotype = "Ignorable";
public static final String editableTableStereotype = "EditableTable";
public static final String sysmlProfile = "SysML";
public static final String documentCommentStereotype = "DocumentComment";
public static final String viewCommentStereotype = "ViewComment";
public static final String constraintStereotype = "Constraint";
} |
package imagej.patcher;
import ij.Macro;
import ij.gui.DialogListener;
import ij.plugin.filter.PlugInFilterRunner;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.FocusEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
* Rump implementation of a pseudo dialog intended to stand in for the
* {@link ij.gui.GenericDialog} in headless mode.
*
* @author Johannes Schindelin
*/
@SuppressWarnings("unused")
public class HeadlessGenericDialog {
protected List<Double> numbers;
protected List<String> strings;
protected List<Boolean> checkboxes;
protected List<String> choices;
protected List<Integer> choiceIndices;
protected String textArea1, textArea2;
protected List<String> radioButtons;
protected int numberfieldIndex = 0, stringfieldIndex = 0, checkboxIndex = 0, choiceIndex = 0, textAreaIndex = 0, radioButtonIndex = 0;
protected boolean invalidNumber;
protected String errorMessage;
public HeadlessGenericDialog() {
if (Macro.getOptions() == null)
throw new RuntimeException("Cannot instantiate headless dialog except in macro mode");
numbers = new ArrayList<Double>();
strings = new ArrayList<String>();
checkboxes = new ArrayList<Boolean>();
choices = new ArrayList<String>();
choiceIndices = new ArrayList<Integer>();
radioButtons = new ArrayList<String>();
}
public void addCheckbox(String label, boolean defaultValue) {
checkboxes.add(getMacroParameter(label, defaultValue));
}
public void addCheckboxGroup(int rows, int columns, String[] labels, boolean[] defaultValues) {
for (int i = 0; i < labels.length; i++)
addCheckbox(labels[i], defaultValues[i]);
}
public void addCheckboxGroup(int rows, int columns, String[] labels, boolean[] defaultValues, String[] headings) {
addCheckboxGroup(rows, columns, labels, defaultValues);
}
public void addChoice(String label, String[] items, String defaultItem) {
String item = getMacroParameter(label, defaultItem);
int index = 0;
for (int i = 0; i < items.length; i++)
if (items[i].equals(item)) {
index = i;
break;
}
choiceIndices.add(index);
choices.add(items[index]);
}
public void addNumericField(String label, double defaultValue, int digits) {
numbers.add(getMacroParameter(label, defaultValue));
}
public void addNumericField(String label, double defaultValue, int digits, int columns, String units) {
addNumericField(label, defaultValue, digits);
}
public void addSlider(String label, double minValue, double maxValue, double defaultValue) {
numbers.add(getMacroParameter(label, defaultValue));
}
public void addStringField(String label, String defaultText) {
strings.add(getMacroParameter(label, defaultText));
}
public void addStringField(String label, String defaultText, int columns) {
addStringField(label, defaultText);
}
public void addTextAreas(String text1, String text2, int rows, int columns) {
textArea1 = text1;
textArea2 = text2;
}
public boolean getNextBoolean() {
return checkboxes.get(checkboxIndex++);
}
public String getNextChoice() {
return choices.get(choiceIndex++);
}
public int getNextChoiceIndex() {
return choiceIndices.get(choiceIndex++);
}
public double getNextNumber() {
return numbers.get(numberfieldIndex++);
}
/** Returns the contents of the next text field. */
public String getNextString() {
return strings.get(stringfieldIndex++);
}
public String getNextText() {
switch (textAreaIndex++) {
case 0:
return textArea1;
case 1:
return textArea2;
}
return null;
}
/** Adds a radio button group. */
public void addRadioButtonGroup(String label, String[] items, int rows, int columns, String defaultItem) {
radioButtons.add(getMacroParameter(label, defaultItem));
}
public List<String> getRadioButtonGroups() {
return radioButtons;
}
/** Returns the selected item in the next radio button group. */
public String getNextRadioButton() {
return radioButtons.get(radioButtonIndex++);
}
public boolean invalidNumber() {
boolean wasInvalid = invalidNumber;
invalidNumber = false;
return wasInvalid;
}
public void showDialog() {
if (Macro.getOptions() == null)
throw new RuntimeException("Cannot run dialog headlessly");
numberfieldIndex = 0;
stringfieldIndex = 0;
checkboxIndex = 0;
choiceIndex = 0;
textAreaIndex = 0;
}
public boolean wasCanceled() {
return false;
}
public boolean wasOKed() {
return true;
}
public void dispose() {}
public void addDialogListener(DialogListener dl) {}
public void addHelp(String url) {}
public void addMessage(String text) {}
public void addMessage(String text, Font font) {}
public void addMessage(String text, Font font, Color color) {}
public void addPanel(Panel panel) {}
public void addPanel(Panel panel, int contraints, Insets insets) {}
public void addPreviewCheckbox(PlugInFilterRunner pfr) {}
public void addPreviewCheckbox(PlugInFilterRunner pfr, String label) {}
public void centerDialog(boolean b) {}
public void setSmartRecording(boolean smartRecording) {}
public void enableYesNoCancel() {}
public void enableYesNoCancel(String yesLabel, String noLabel) {}
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) {}
public Button[] getButtons() { return null; }
public Vector<?> getCheckboxes() { return null; }
public Vector<?> getChoices() { return null; }
public String getErrorMessage() { return errorMessage; }
public Insets getInsets() { return null; }
public Component getMessage() { return null; }
public Vector<?> getNumericFields() { return null; }
public Checkbox getPreviewCheckbox() { return null; }
public Vector<?> getSliders() { return null; }
public Vector<?> getStringFields() { return null; }
public TextArea getTextArea1() { return null; }
public TextArea getTextArea2() { return null; }
public void hideCancelButton() {}
public void previewRunning(boolean isRunning) {}
public void setEchoChar(char echoChar) {}
public void setHelpLabel(String label) {}
public void setInsets(int top, int left, int bottom) {}
public void setOKLabel(String label) {}
protected void setup() {}
public void accessTextFields() {}
public void showHelp() {}
/**
* Gets a macro parameter of type <i>boolean</i>.
*
* @param label
* the name of the macro parameter
* @param defaultValue
* the default value
* @return the boolean value
*/
private static boolean getMacroParameter(String label, boolean defaultValue) {
return findBooleanMacroParameter(label) || defaultValue;
}
/**
* Looks whether a boolean was specified in the macro parameters.
*
* @param label
* the label to look for
* @return whether the label was found
*/
private static boolean findBooleanMacroParameter(final String labelString) {
final String optionsString = Macro.getOptions();
if (optionsString == null) {
return false;
}
final char[] options = optionsString.toCharArray();
final char[] label = Macro.trimKey(labelString).toCharArray();
for (int i = 0; i < options.length; i++) {
boolean match = true;
// match at start or after space
for (char c : label) {
if (c != options[i]) {
match = false;
break;
}
i++;
}
if (match && (i >= options.length || options[i] == ' ')) {
return true;
}
// look for next space
while (i < options.length && options[i] != ' ') {
// skip literal
if (options[i] == '[') {
while (i < options.length && options[i] != ']') {
i++;
}
}
i++;
}
}
return false;
}
/**
* Gets a macro parameter of type <i>double</i>.
*
* @param label
* the name of the macro parameter
* @param defaultValue
* the default value
* @return the double value
*/
private static double getMacroParameter(String label, double defaultValue) {
String value = Macro.getValue(Macro.getOptions(), label, null);
return value != null ? Double.parseDouble(value) : defaultValue;
}
/**
* Gets a macro parameter of type {@link String}.
*
* @param label
* the name of the macro parameter
* @param defaultValue
* the default value
* @return the value
*/
private static String getMacroParameter(String label, String defaultValue) {
return Macro.getValue(Macro.getOptions(), label, defaultValue);
}
} |
package io.cogswell.sdk.pubsub;
import android.net.Uri;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import io.cogswell.sdk.utils.Duration;
/**
* Holds initialization options to use when first connect to Cogswell Pub/Sub
*/
public class PubSubOptions {
/**
* The default url to the production server.
*/
private static final String PRODUCTION_URL = "https://api.cogswell.io/pubsub";
/**
* The default timeout for connections.
*/
private static final Duration DEFAULT_TIMEOUT = Duration.of(30, TimeUnit.SECONDS);
/**
* The url used for connecting to the Pub/Sub service
*/
private Uri uri;
/**
* True if connection should auto-reconnect when dropped
*/
private final boolean autoReconnect;
/**
* The amount of time, in milliseconds, when a connection attempt should timeout
*/
private final Duration connectTimeout;
/**
* Holds UUID of the session to be restored if a session restore is requested.
*/
private final UUID sessionUuid;
/**
* Initializes this PubSubOptions with all default values
*/
public PubSubOptions () {
this(PRODUCTION_URL, true, DEFAULT_TIMEOUT, null);
}
public PubSubOptions (String url) {
this(url, true, DEFAULT_TIMEOUT, null);
}
/**
* Static instance of PubSubOptions that contains all default values.
*/
public static final PubSubOptions DEFAULT_OPTIONS = new PubSubOptions();
/**
* Initializes this PubSubOptions with the given options, filling in null values with defaults.
*
* @param url URL to which to connect (Deafult: "wss://api.cogswell.io/pubsub").
* @param autoReconnect True if connection should attempt to reconnect when disconnected (Default: true).
* @param connectTimeout Duration before connection should timeout (Default: 30 seconds).
* @param sessionUuid UUID of session to restore, if requested (Default: null).
*/
public PubSubOptions(String url, Boolean autoReconnect, Duration connectTimeout, UUID sessionUuid) {
this.uri = (url == null) ? Uri.parse(PRODUCTION_URL) : Uri.parse(url);
this.autoReconnect = (autoReconnect == null) ? false : autoReconnect;
this.connectTimeout = (connectTimeout == null) ? Duration.of(30, TimeUnit.SECONDS) : connectTimeout;
this.sessionUuid = sessionUuid;
}
/**
* Gets the url represented in this PubSubOptions for a connection.
*
* @return Uri The uri represented in this PubSubOptions instance.
*/
public Uri getUri() {
return uri;
}
/**
* Gets whether these options represent the request to auto-reconnect.
*
* @return boolean True if auto-reconnect was set, false otherwise
*/
public boolean getAutoReconnect() {
return autoReconnect;
}
/**
* Gets the time, in milliseconds, before a connection attempt should fail.
* @return long Time, in milliseconds, before connection attempt should fail.
*/
public Duration getConnectTimeout() {
return connectTimeout;
}
/**
* Gets the UUID of the session requested to be re-established using this PubSubOptions instance.
* @return UUID UUID of session requested to be re-established.
*/
public UUID getSessionUuid() {
return sessionUuid;
}
} |
package io.redis.client;
import static org.testng.Assert.assertEquals;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
/**
* ShardedJedisPoolTest.java{@link ShardedJedisPool} tutorial
*
* @author huagang.li 20141113 4:06:19
*/
public class ShardedJedisPoolTest {
private static final Logger logger = LoggerFactory.getLogger(ShardedJedisPoolTest.class);
private static final String DEFAULT_HOST = "127.0.0.1";
private static final int DEFAULT_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(1L);
private ShardedJedisPool pool;
@BeforeClass
public void init() {
// twemproxy
List<HostAndPort> hosts = this.getHostList(ServerFlag.TWEMPROXY);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(hosts.size());
for (HostAndPort hostInfo : hosts) {
JedisShardInfo shardInfo = new JedisShardInfo(hostInfo.getHost(), hostInfo.getPort(), DEFAULT_TIMEOUT);
shards.add(shardInfo);
}
GenericObjectPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(65536);
poolConfig.setMaxIdle(65536);
poolConfig.setMinIdle(3);
poolConfig.setBlockWhenExhausted(false);
poolConfig.setMaxWaitMillis(TimeUnit.MILLISECONDS.toMillis(30L));
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
this.pool = new ShardedJedisPool(poolConfig, shards);
}
private enum ServerFlag {
REDIS, TWEMPROXY
}
private List<HostAndPort> getHostList(ServerFlag serverFlag) {
int[] ports = null;
switch (serverFlag) {
case REDIS:
// Redis servers
ports = new int[] { 6379, 6380, 6381 };
break;
case TWEMPROXY:
// Twemproxy servers
ports = new int[] { 10001 };
break;
default:
throw new IllegalArgumentException("Not has this server flag: " + serverFlag);
}
List<HostAndPort> hosts = new ArrayList<HostAndPort>(ports.length);
for (int port : ports) {
hosts.add(new HostAndPort(DEFAULT_HOST, port));
}
return hosts;
}
private static final String TWEMPROXY_FILE = "twemproxy.txt";
private static final String DEFAUL_VALUE = "1";
private static final String RET_OK = "OK";
private static final int SIZE = 10;
private AtomicInteger counter = new AtomicInteger(1);
/**
*
* <p>
* Twemproxyredis
*/
@Test(invocationCount = 20000, threadPoolSize = 1024)
public void highConcurrencyStressTest() {
long start = System.currentTimeMillis();
// Redis
ShardedJedis jedis = this.pool.getResource();
// SET
String key = "st_" + counter.getAndIncrement();
String statusCode = jedis.set(key, DEFAUL_VALUE);
assertEquals(statusCode, RET_OK);
this.pool.returnResource(jedis);
long runTime = System.currentTimeMillis() - start;
if (runTime > 10) {
logger.info("{}'s run time: {}", key, runTime);
}
}
/**
* Twemproxy "Shard data automatically across multiple servers ()"
* <p>
* <font color="red">({@link #SIZE})1000</font>
*
* @throws IOException
*/
@Test
public void sharding() {
ShardedJedis jedis = this.pool.getResource();
PrintWriter writer = null;
try {
writer = new PrintWriter(new FileWriter(TWEMPROXY_FILE));
Random rand = new Random();
for (int i = 0; i < SIZE; i++) {
int v = rand.nextInt();
String key = Integer.toString(v);
writer.println(key);
// SET
jedis.set(key, DEFAUL_VALUE);
}
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
writer.close();
}
}
}
/**
* Twemproxy ""
* <p>
* Keys ""Key
*
* @throws IOException
*/
@Test
public void checkSharding() throws IOException {
// Key
File file = new File(TWEMPROXY_FILE);
List<String> keys = FileUtils.readLines(file);
/*
* 1. redis 2. redis Key GET
*/
List<HostAndPort> hostList = this.getHostList(ServerFlag.REDIS);
for (HostAndPort hostInfo : hostList) {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(1);
JedisShardInfo shardInfo = new JedisShardInfo(hostInfo.getHost(), hostInfo.getPort(), DEFAULT_TIMEOUT);
shards.add(shardInfo);
GenericObjectPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(10);
poolConfig.setMaxIdle(10);
poolConfig.setMinIdle(3);
poolConfig.setMaxWaitMillis(TimeUnit.SECONDS.toMillis(1L));
poolConfig.setTestOnBorrow(true);
ShardedJedisPool jedisPool = new ShardedJedisPool(poolConfig, shards);
try {
ShardedJedis jedis = jedisPool.getResource();
int hits = 0;
for (String key : keys) {
String value = jedis.get(key);
if (!StringUtils.isEmpty(value)) {
++hits;
jedis.del(key);
}
}
if (logger.isInfoEnabled()) {
logger.info("Host {}'s hit ratio: {}", hostInfo, hits);
}
} finally {
jedisPool.close();
}
}
}
/**
* Twemproxy "auto-failover"
* <p>
* Twemproxy Twemproxy
* <p>
* Keys {@link #sharding()} {@link #TWEMPROXY_FILE} <br>
* <font color="red">({@link #SIZE})20</font>
*/
@Test
public void autoFailover() {
ShardedJedis jedis = null;
String[] keys = { "-640595852", // 6379
"563752978", // 6379
"1297026184", // 6380
"843626243", // 6380, 6379
"579761811", // 6379
"-1148481590", // 6379
"-1653107798", // 6381
"1208161125", // 6380, 6381
"549094194", // 6381
"1082579570", // 6380, 6381
};
String statusCode = null;
for (String key : keys) {
try {
// Redis
jedis = this.pool.getResource();
// SET
statusCode = jedis.set(key, DEFAUL_VALUE);
assertEquals(statusCode, RET_OK);
this.pool.returnResourceObject(jedis);
} catch (Exception e) {
logger.error("Set key error: {}", key);
}
}
}
@AfterClass
public void destroy() {
if (this.pool != null) {
this.pool.close();
}
}
} |
package jenkins.plugins.coverity;
import com.coverity.ws.v6.*;
import com.coverity.ws.v9.SnapshotScopeSpecDataObj;
import hudson.model.Hudson;
import hudson.util.FormValidation;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.Handler;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Represents one Coverity Integrity Manager server. Abstracts functions like getting streams and defects.
*/
public class CIMInstance {
public static final String COVERITY_V5_NAMESPACE = "http://ws.coverity.com/v6";
public static final String COVERITY_V9_NAMESPACE = "http://ws.coverity.com/v9";
public static final String CONFIGURATION_SERVICE_V5_WSDL = "/ws/v6/configurationservice?wsdl";
public static final String DEFECT_SERVICE_V5_WSDL = "/ws/v6/defectservice?wsdl";
public static final String CONFIGURATION_SERVICE_V9_WSDL = "/ws/v9/configurationservice?wsdl";
public static final String DEFECT_SERVICE_V9_WSDL = "/ws/v9/defectservice?wsdl";
/**
* Pattern to ignore streams - this is used to filter out internal DA streams, which are irrelevant to this plugin
*/
public static final String STREAM_NAME_IGNORE_PATTERN = "__internal_.*";
/**
* The id for this instance, used as a key in CoverityPublisher
*/
private final String name;
/**
* The host name for the CIM server
*/
private final String host;
/**
* The port for the CIM server (this is the HTTP port and not the data port)
*/
private final int port;
/**
* The commit port for the CIM server. This is only for cov-commit-defects.
*/
private final int dataPort;
/**
* Username for connecting to the CIM server
*/
private final String user;
/**
* Password for connecting to the CIM server
*/
private final String password;
/**
* Use SSL
*/
private final boolean useSSL;
/**
* cached webservice port for Defect service
*/
private transient com.coverity.ws.v6.DefectServiceService defectServiceService;
/**
* cached webservice port for Configuration service
*/
private transient com.coverity.ws.v6.ConfigurationServiceService configurationServiceService;
/**
* cached webservice port for Defect service for Indio
*/
private transient com.coverity.ws.v9.DefectServiceService defectServiceServiceIndio;
/**
* cached webservice port for Configuration service for Indio
*/
private transient com.coverity.ws.v9.ConfigurationServiceService configurationServiceServiceIndio;
@DataBoundConstructor
public CIMInstance(String name, String host, int port, String user, String password, boolean useSSL, int dataPort) {
this.name = name;
this.host = host;
this.port = port;
this.user = user;
this.password = password;
this.useSSL = useSSL;
this.dataPort = dataPort;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public String getName() {
return name;
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
public boolean isUseSSL() {
return useSSL;
}
public int getDataPort() {
return dataPort;
}
/**
* The root URL for the CIM instance
*
* @return a url
* @throws MalformedURLException should not happen if host is valid
*/
public URL getURL() throws MalformedURLException {
return new URL(isUseSSL() ? "https" : "http", host, port, "/");
}
/**
* Returns a Defect service client using v6 web services.
*/
public com.coverity.ws.v6.DefectService getDefectService() throws IOException {
synchronized(this) {
if(defectServiceService == null) {
defectServiceService = new com.coverity.ws.v6.DefectServiceService(
new URL(getURL(), DEFECT_SERVICE_V5_WSDL),
new QName(COVERITY_V5_NAMESPACE, "DefectServiceService"));
}
}
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
com.coverity.ws.v6.DefectService defectService = defectServiceService.getDefectServicePort();
attachAuthenticationHandler((BindingProvider) defectService);
return defectService;
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
/**
* Returns a Defect service client using v9 web services.
*/
public com.coverity.ws.v9.DefectService getDefectServiceIndio() throws IOException {
synchronized(this) {
if(defectServiceServiceIndio == null) {
defectServiceServiceIndio = new com.coverity.ws.v9.DefectServiceService(
new URL(getURL(), DEFECT_SERVICE_V9_WSDL),
new QName(COVERITY_V9_NAMESPACE, "DefectServiceService"));
}
}
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
com.coverity.ws.v9.DefectService defectService = defectServiceServiceIndio.getDefectServicePort();
attachAuthenticationHandler((BindingProvider) defectService);
return defectService;
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
/**
* Attach an authentication handler to the web service, that uses the configured user and password
*/
private void attachAuthenticationHandler(BindingProvider service) {
service.getBinding().setHandlerChain(Arrays.<Handler>asList(new ClientAuthenticationHandlerWSS(user, password)));
}
/**
* Returns a Configuration service client using v6 web services.
*/
public ConfigurationService getConfigurationService() throws IOException {
synchronized(this) {
if(configurationServiceService == null) {
// Create a Web Services port to the server
configurationServiceService = new ConfigurationServiceService(
new URL(getURL(), CONFIGURATION_SERVICE_V5_WSDL),
new QName(COVERITY_V5_NAMESPACE, "ConfigurationServiceService"));
}
}
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
ConfigurationService configurationService = configurationServiceService.getConfigurationServicePort();
attachAuthenticationHandler((BindingProvider) configurationService);
return configurationService;
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
/**
* Returns a Configuration service client using v9 web services.
*/
public com.coverity.ws.v9.ConfigurationService getConfigurationServiceIndio() throws IOException {
synchronized(this) {
if(configurationServiceServiceIndio == null) {
// Create a Web Services port to the server
configurationServiceServiceIndio = new com.coverity.ws.v9.ConfigurationServiceService(
new URL(getURL(), CONFIGURATION_SERVICE_V9_WSDL),
new QName(COVERITY_V9_NAMESPACE, "ConfigurationServiceService"));
}
}
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
com.coverity.ws.v9.ConfigurationService configurationService = configurationServiceServiceIndio.getConfigurationServicePort();
attachAuthenticationHandler((BindingProvider) configurationService);
return configurationService;
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
public String getWsVersion(){
com.coverity.ws.v9.ConfigurationService simpleWsCall = null;
// Set the default ws version value to v6.
String wsVersion = "v6";
try {
String testMessage = this.getConfigurationServiceIndio().getVersion().getExternalVersion();
if(testMessage != null){
wsVersion = "v9";
}
} catch (Exception e) {
}
return wsVersion;
}
public List<com.coverity.ws.v9.MergedDefectDataObj> getDefectsIndio(String streamId, List<Long> defectIds) throws IOException, com.coverity.ws.v9.CovRemoteServiceException_Exception {
com.coverity.ws.v9.MergedDefectFilterSpecDataObj filterSpec = new com.coverity.ws.v9.MergedDefectFilterSpecDataObj();
com.coverity.ws.v9.StreamIdDataObj stream = new com.coverity.ws.v9.StreamIdDataObj();
stream.setName(streamId);
List<com.coverity.ws.v9.StreamIdDataObj> streamList = new ArrayList<com.coverity.ws.v9.StreamIdDataObj>();
streamList.add(stream);
com.coverity.ws.v9.PageSpecDataObj pageSpec = new com.coverity.ws.v9.PageSpecDataObj();
pageSpec.setPageSize(2500);
SnapshotScopeSpecDataObj snapshotScopeSpecDataObj = new SnapshotScopeSpecDataObj();
List<com.coverity.ws.v9.MergedDefectDataObj> result = new ArrayList<com.coverity.ws.v9.MergedDefectDataObj>();
int defectCount = 0;
com.coverity.ws.v9.MergedDefectsPageDataObj defects = null;
do {
pageSpec.setStartIndex(defectCount);
defects = getDefectServiceIndio().getMergedDefectsForStreams(streamList, filterSpec, pageSpec, snapshotScopeSpecDataObj);
for(com.coverity.ws.v9.MergedDefectDataObj defect : defects.getMergedDefects()) {
if(defectIds.contains(defect.getCid())) {
result.add(defect);
}
}
defectCount += defects.getMergedDefects().size();
} while(defectCount < defects.getTotalNumberOfRecords());
return result;
}
public List<MergedDefectDataObj> getDefects(String streamId, List<Long> defectIds) throws IOException, CovRemoteServiceException_Exception {
MergedDefectFilterSpecDataObj filterSpec1 = new MergedDefectFilterSpecDataObj();
StreamIdDataObj stream = new StreamIdDataObj();
stream.setName(streamId);
PageSpecDataObj pageSpec = new PageSpecDataObj();
pageSpec.setPageSize(2500);
List<MergedDefectDataObj> result = new ArrayList<MergedDefectDataObj>();
int defectCount = 0;
MergedDefectsPageDataObj defects = null;
do {
pageSpec.setStartIndex(defectCount);
defects = getDefectService().getMergedDefectsForStreams(Arrays.asList(stream), filterSpec1, pageSpec);
for(MergedDefectDataObj defect : defects.getMergedDefects()) {
if(defectIds.contains(defect.getCid())) {
result.add(defect);
}
}
defectCount += defects.getMergedDefects().size();
} while(defectCount < defects.getTotalNumberOfRecords());
return result;
}
public ProjectDataObj getProject(String projectId) throws IOException, CovRemoteServiceException_Exception {
ProjectFilterSpecDataObj filterSpec = new ProjectFilterSpecDataObj();
filterSpec.setNamePattern(projectId);
List<ProjectDataObj> projects = getConfigurationService().getProjects(filterSpec);
if(projects.size() == 0) {
return null;
} else {
return projects.get(0);
}
}
private transient Map<String, Long> projectKeys;
public Long getProjectKey(String projectId) throws IOException, CovRemoteServiceException_Exception {
if(projectKeys == null) {
projectKeys = new ConcurrentHashMap<String, Long>();
}
Long result = projectKeys.get(projectId);
if(result == null) {
result = getProject(projectId).getProjectKey();
projectKeys.put(projectId, result);
}
return result;
}
public List<ProjectDataObj> getProjects() throws IOException, CovRemoteServiceException_Exception {
return getConfigurationService().getProjects(new ProjectFilterSpecDataObj());
}
public List<StreamDataObj> getStaticStreams(String projectId) throws IOException, CovRemoteServiceException_Exception {
/*
to get a list of all static streams for one project,
- get a list of streams for the project
- get a list of all static streams
- compute the intersection
there should be a better way, but I can't see it.
you can't filter on project, and StreamDataObj does not have project or type information
*/
ProjectDataObj project = getProject(projectId);
List<StreamDataObj> result = new ArrayList<StreamDataObj>();
for(StreamDataObj stream : project.getStreams()) {
if(!stream.getId().getName().matches(STREAM_NAME_IGNORE_PATTERN)) {
result.add(stream);
}
}
return result;
}
/**
* Returns a StreamDataObj for a given streamId. This object must be not null in order to avoid null pointer exceptions.
* If the stream is not found an exception explaining the issue is raised.
*/
public StreamDataObj getStream(String streamId) throws IOException, CovRemoteServiceException_Exception {
StreamFilterSpecDataObj filter = new StreamFilterSpecDataObj();
filter.setNamePattern(streamId);
List<StreamDataObj> streams = getConfigurationService().getStreams(filter);
if(streams == null || streams.isEmpty()) {
throw new IOException("An error occurred while retrieving streams for the given project. Could not find stream: " + streamId);
} else {
StreamDataObj streamDataObj = streams.get(0);
if(streamDataObj == null){
throw new IOException("An error occurred while retrieving streams for the given project. Could not find stream: " + streamId);
} else {
return streams.get(0);
}
}
}
/**
* Returns a StreamDataObj for a given streamId. This object must be not null in order to avoid null pointer exceptions.
* If the stream is not found an exception explaining the issue is raised.
*/
public com.coverity.ws.v9.StreamDataObj getStreamIndio(String streamId) throws IOException, com.coverity.ws.v9.CovRemoteServiceException_Exception {
com.coverity.ws.v9.StreamFilterSpecDataObj filter = new com.coverity.ws.v9.StreamFilterSpecDataObj();
filter.setNamePattern(streamId);
List<com.coverity.ws.v9.StreamDataObj> streams = getConfigurationServiceIndio().getStreams(filter);
if(streams == null || streams.isEmpty()) {
throw new IOException("An error occurred while retrieving streams for the given project. Could not find stream: " + streamId);
} else {
com.coverity.ws.v9.StreamDataObj streamDataObj = streams.get(0);
if(streamDataObj == null){
throw new IOException("An error occurred while retrieving streams for the given project. Could not find stream: " + streamId);
} else {
return streams.get(0);
}
}
}
public FormValidation doCheck() throws IOException {
try {
URL url = getURL();
// Fix:77968 by using different wsdl for v9 and v6.
if(this.getWsVersion().equals("v9")){
int responseCode = getURLResponseCode(new URL(url, CONFIGURATION_SERVICE_V9_WSDL));
if(responseCode != 200) {
return FormValidation.error("Connected successfully, but Coverity web services were not detected.");
}
getConfigurationServiceIndio().getServerTime();
return FormValidation.ok("Successfully connected to the instance.");
} else {
int responseCode = getURLResponseCode(new URL(url, CONFIGURATION_SERVICE_V5_WSDL));
if(responseCode != 200) {
return FormValidation.error("Connected successfully, but Coverity web services were not detected.");
}
getConfigurationService().getServerTime();
return FormValidation.ok("Successfully connected to the instance.");
}
} catch(UnknownHostException e) {
return FormValidation.error("Host name unknown");
} catch(ConnectException e) {
return FormValidation.error("Connection refused");
} catch(SocketException e) {
return FormValidation.error("Error connecting to CIM. Please check your connection settings.");
} catch(Throwable e) {
String javaVersion = System.getProperty("java.version");
if(javaVersion.startsWith("1.6.0_")) {
int patch = Integer.parseInt(javaVersion.substring(javaVersion.indexOf('_') + 1));
if(patch < 26) {
return FormValidation.error(e, "Please use Java 1.6.0_26 or later to run Jenkins.");
}
}
return FormValidation.error(e, "An unexpected error occurred.");
}
}
private FormValidation error(Throwable t) {
if(Hudson.getInstance().hasPermission(Hudson.ADMINISTER)) {
return FormValidation.error(t, t.getMessage());
} else {
return FormValidation.error(t.getMessage());
}
}
private int getURLResponseCode(URL url) throws IOException {
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
conn.getInputStream();
return conn.getResponseCode();
} catch(FileNotFoundException e) {
return 404;
}
}
public String getCimInstanceCheckers() {
List<String> checkers = new ArrayList<String>();
if(this.getWsVersion().equals("v9")){
try {
checkers.addAll(this.getConfigurationServiceIndio().getCheckerNames());
} catch(Exception e) {
}
} else{
try {
CheckerPropertyFilterSpecDataObj checkerPropFilter = new CheckerPropertyFilterSpecDataObj();
List<CheckerPropertyDataObj> checkerPropertyList = this.getConfigurationService().getCheckerProperties(checkerPropFilter);
for(CheckerPropertyDataObj checkerProp : checkerPropertyList){
CheckerSubcategoryIdDataObj checkerSub = checkerProp.getCheckerSubcategoryId();
if(!checkers.contains(checkerSub.getCheckerName())){
checkers.add(checkerSub.getCheckerName());
}
}
} catch(Exception e) {
}
}
Collections.sort(checkers);
return StringUtils.join(checkers, '\n');
}
} |
package jenkins.plugins.git;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials;
import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.EnvVars;
import hudson.Extension;
import hudson.model.Item;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.plugins.git.BranchSpec;
import hudson.plugins.git.GitException;
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.GitTool;
import hudson.plugins.git.UserRemoteConfig;
import hudson.remoting.VirtualChannel;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.security.ACL;
import hudson.util.LogTaskListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.scm.api.SCMFile;
import jenkins.scm.api.SCMFileSystem;
import jenkins.scm.api.SCMHead;
import jenkins.scm.api.SCMRevision;
import jenkins.scm.api.SCMSource;
import jenkins.scm.api.SCMSourceDescriptor;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.URIish;
import org.jenkinsci.plugins.gitclient.ChangelogCommand;
import org.jenkinsci.plugins.gitclient.Git;
import org.jenkinsci.plugins.gitclient.GitClient;
/**
* Base implementation of {@link SCMFileSystem}.
*
* @since 3.0.2
*/
public class GitSCMFileSystem extends SCMFileSystem {
/**
* Our logger.
*/
private static final Logger LOGGER = Logger.getLogger(GitSCMFileSystem.class.getName());
private final String cacheEntry;
private final TaskListener listener;
private final String remote;
private final String head;
private final GitClient client;
private final ObjectId commitId;
/**
* Constructor.
*
* @param client the client
* @param remote the remote GIT URL
* @param head identifier for the head commit to be referenced
* @param rev the revision.
* @throws IOException on I/O error
* @throws InterruptedException on thread interruption
*/
protected GitSCMFileSystem(GitClient client, String remote, final String head, @CheckForNull
AbstractGitSCMSource.SCMRevisionImpl rev) throws IOException, InterruptedException {
super(rev);
this.remote = remote;
this.head = head;
cacheEntry = AbstractGitSCMSource.getCacheEntry(remote);
listener = new LogTaskListener(LOGGER, Level.FINER);
this.client = client;
commitId = rev == null ? invoke((Repository repository) -> repository.findRef(head).getObjectId()) : ObjectId.fromString(rev.getHash());
}
@Override
public AbstractGitSCMSource.SCMRevisionImpl getRevision() {
return (AbstractGitSCMSource.SCMRevisionImpl) super.getRevision();
}
@Override
public long lastModified() throws IOException, InterruptedException {
return invoke((Repository repository) -> {
try (RevWalk walk = new RevWalk(repository)) {
RevCommit commit = walk.parseCommit(commitId);
return TimeUnit.SECONDS.toMillis(commit.getCommitTime());
}
});
}
@NonNull
@Override
public SCMFile getRoot() {
return new GitSCMFile(this);
}
/*package*/ ObjectId getCommitId() {
return commitId;
}
/**
* Called with an {@link FSFunction} callback with a singleton repository
* cache lock.
*
* An example usage might be:
*
* <pre>{@code
* return fs.invoke(new GitSCMFileSystem.FSFunction<byte[]>() {
* public byte[] invoke(Repository repository) throws IOException, InterruptedException {
* Git activeRepo = getClonedRepository(repository);
* File repoDir = activeRepo.getRepository().getDirectory().getParentFile();
* System.out.println("Repo cloned to: " + repoDir.getCanonicalPath());
* try {
* File f = new File(repoDir, filePath);
* if (f.canRead()) {
* return IOUtils.toByteArray(new FileInputStream(f));
* }
* return null;
* } finally {
* FileUtils.deleteDirectory(repoDir);
* }
* }
* });
* }</pre>
*
* @param <V> return type
* @param function callback executed with a locked repository
* @return whatever you return from the provided function
* @throws IOException if there is an I/O error
* @throws InterruptedException if interrupted
*/
public <V> V invoke(final FSFunction<V> function) throws IOException, InterruptedException {
Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry);
cacheLock.lock();
try {
File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry);
if (cacheDir == null || !cacheDir.isDirectory()) {
throw new IOException("Closed");
}
return client.withRepository((Repository repository, VirtualChannel virtualChannel) -> function.invoke(repository));
} finally {
cacheLock.unlock();
}
}
@Override
public boolean changesSince(@CheckForNull SCMRevision revision, @NonNull OutputStream changeLogStream)
throws UnsupportedOperationException, IOException, InterruptedException {
AbstractGitSCMSource.SCMRevisionImpl rev = getRevision();
if (Objects.equals(rev, revision)) {
// special case where somebody is asking one of two stupid questions:
// 1. what has changed between the latest and the latest
// 2. what has changed between the current revision and the current revision
return false;
}
Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry);
cacheLock.lock();
try {
File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry);
if (cacheDir == null || !cacheDir.isDirectory()) {
throw new IOException("Closed");
}
boolean executed = false;
ChangelogCommand changelog = client.changelog();
try (Writer out = new OutputStreamWriter(changeLogStream, StandardCharsets.UTF_8)) {
changelog.includes(commitId);
ObjectId fromCommitId;
if (revision instanceof AbstractGitSCMSource.SCMRevisionImpl) {
fromCommitId = ObjectId.fromString(((AbstractGitSCMSource.SCMRevisionImpl) revision).getHash());
changelog.excludes(fromCommitId);
} else {
fromCommitId = null;
}
changelog.to(out).max(GitSCM.MAX_CHANGELOG).execute();
executed = true;
return !commitId.equals(fromCommitId);
} catch (GitException ge) {
throw new IOException("Unable to retrieve changes", ge);
} finally {
if (!executed) {
changelog.abort();
}
changeLogStream.close();
}
} finally {
cacheLock.unlock();
}
}
/**
* Simple callback that is used with
* {@link #invoke(jenkins.plugins.git.GitSCMFileSystem.FSFunction)}
* in order to provide a locked view of the Git repository
* @param <V> the return type
*/
public interface FSFunction<V> {
/**
* Called with a lock on the repository in order to perform some
* operations that might result in changes and necessary re-indexing
* @param repository the bare git repository
* @return value to return from {@link #invoke(jenkins.plugins.git.GitSCMFileSystem.FSFunction)}
* @throws IOException if there is an I/O error
* @throws InterruptedException if interrupted
*/
V invoke(Repository repository) throws IOException, InterruptedException;
}
@Extension(ordinal = Short.MIN_VALUE)
public static class BuilderImpl extends SCMFileSystem.Builder {
@Override
public boolean supports(SCM source) {
return source instanceof GitSCM
&& ((GitSCM) source).getUserRemoteConfigs().size() == 1
&& ((GitSCM) source).getBranches().size() == 1
&& !((GitSCM) source).getBranches().get(0).getName().equals("*") // JENKINS-57587
&& (
((GitSCM) source).getBranches().get(0).getName().matches(
"^((\\Q" + Constants.R_HEADS + "\\E.*)|([^/]+)|(\\*/[^/*]+(/[^/*]+)*))$"
)
|| ((GitSCM) source).getBranches().get(0).getName().matches(
"^((\\Q" + Constants.R_TAGS + "\\E.*)|([^/]+)|(\\*/[^/*]+(/[^/*]+)*))$"
)
);
// we only support where the branch spec is obvious and not a wildcard
}
@Override
public boolean supports(SCMSource source) {
return source instanceof AbstractGitSCMSource;
}
@Override
public boolean supportsDescriptor(SCMDescriptor descriptor) {
return descriptor instanceof GitSCM.DescriptorImpl;
}
@Override
public boolean supportsDescriptor(SCMSourceDescriptor descriptor) {
return AbstractGitSCMSource.class.isAssignableFrom(descriptor.clazz);
}
static class HeadNameResult {
final String headName;
final String prefix;
private HeadNameResult(String headName, String prefix) {
this.headName = headName;
this.prefix = prefix;
}
static HeadNameResult calculate(@NonNull BranchSpec branchSpec,
@CheckForNull SCMRevision rev,
@CheckForNull EnvVars env) {
String branchSpecExpandedName = branchSpec.getName();
if (env != null) {
branchSpecExpandedName = env.expand(branchSpecExpandedName);
}
String prefix = Constants.R_HEADS;
if (branchSpecExpandedName.startsWith(Constants.R_TAGS)) {
prefix = Constants.R_TAGS;
}
String headName;
if (rev != null) {
headName = env.expand(rev.getHead().getName());
} else {
if (branchSpecExpandedName.startsWith(prefix)) {
headName = branchSpecExpandedName.substring(prefix.length());
} else if (branchSpecExpandedName.startsWith("*/")) {
headName = branchSpecExpandedName.substring(2);
} else {
headName = branchSpecExpandedName;
}
}
return new HeadNameResult(headName, prefix);
}
}
@Override
public SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, @CheckForNull SCMRevision rev)
throws IOException, InterruptedException {
return build(owner, scm, rev, null);
}
@Override
public SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, @CheckForNull SCMRevision rev,
@CheckForNull Run<?,?> _build)
throws IOException, InterruptedException {
if (rev != null && !(rev instanceof AbstractGitSCMSource.SCMRevisionImpl)) {
return null;
}
if (!(scm instanceof GitSCM)) {
return null; // Spotbugs warns about unchecked cast without this check
}
GitSCM gitSCM = (GitSCM) scm;
UserRemoteConfig config = gitSCM.getUserRemoteConfigs().get(0);
BranchSpec branchSpec = gitSCM.getBranches().get(0);
String remote = config.getUrl();
TaskListener listener = new LogTaskListener(LOGGER, Level.FINE);
if (remote == null) {
listener.getLogger().println("Git remote url is null");
return null;
}
EnvVars env = null;
if (_build != null) {
env = _build.getEnvironment(listener);
}
String cacheEntry = AbstractGitSCMSource.getCacheEntry(remote);
Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry);
cacheLock.lock();
try {
File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry);
Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir);
GitTool tool = gitSCM.resolveGitTool(listener);
if (tool != null) {
git.using(tool.getGitExe());
}
GitClient client = git.getClient();
String credentialsId = config.getCredentialsId();
if (credentialsId != null) {
StandardCredentials credential = CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(
StandardUsernameCredentials.class,
owner,
ACL.SYSTEM,
URIRequirementBuilder.fromUri(remote).build()
),
CredentialsMatchers.allOf(
CredentialsMatchers.withId(credentialsId),
GitClient.CREDENTIALS_MATCHER
)
);
client.addDefaultCredentials(credential);
CredentialsProvider.track(owner, credential);
}
if (!client.hasGitRepo(false)) {
listener.getLogger().println("Creating git repository in " + cacheDir);
client.init();
}
GitHooksConfiguration.configure(client, GitHooksConfiguration.get().isAllowedOnController());
String remoteName = StringUtils.defaultIfBlank(config.getName(), Constants.DEFAULT_REMOTE_NAME);
listener.getLogger().println("Setting " + remoteName + " to " + remote);
client.setRemoteUrl(remoteName, remote);
listener.getLogger().println("Fetching & pruning " + remoteName + "...");
URIish remoteURI = null;
try {
remoteURI = new URIish(remoteName);
} catch (URISyntaxException ex) {
listener.getLogger().println("URI syntax exception for '" + remoteName + "' " + ex);
}
HeadNameResult headNameResult = HeadNameResult.calculate(branchSpec, rev, env);
client.fetch_().prune(true).from(remoteURI, Collections.singletonList(new RefSpec(
"+" + headNameResult.prefix + headNameResult.headName + ":" + Constants.R_REMOTES + remoteName + "/"
+ headNameResult.headName))).execute();
listener.getLogger().println("Done.");
return new GitSCMFileSystem(client, remote, Constants.R_REMOTES + remoteName + "/" + headNameResult.headName, (AbstractGitSCMSource.SCMRevisionImpl) rev);
} finally {
cacheLock.unlock();
}
}
@Override
public SCMFileSystem build(@NonNull SCMSource source, @NonNull SCMHead head, @CheckForNull SCMRevision rev)
throws IOException, InterruptedException {
if (rev != null && !(rev instanceof AbstractGitSCMSource.SCMRevisionImpl)) {
return null;
}
TaskListener listener = new LogTaskListener(LOGGER, Level.FINE);
AbstractGitSCMSource gitSCMSource = (AbstractGitSCMSource) source;
GitSCMBuilder<?> builder = gitSCMSource.newBuilder(head, rev);
String cacheEntry = gitSCMSource.getCacheEntry();
Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry);
cacheLock.lock();
try {
File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry);
Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir);
GitTool tool = gitSCMSource.resolveGitTool(builder.gitTool(), listener);
if (tool != null) {
git.using(tool.getGitExe());
}
GitClient client = git.getClient();
client.addDefaultCredentials(gitSCMSource.getCredentials());
if (!client.hasGitRepo(false)) {
listener.getLogger().println("Creating git repository in " + cacheDir);
client.init();
}
GitHooksConfiguration.configure(client, GitHooksConfiguration.get().isAllowedOnController());
String remoteName = builder.remoteName();
listener.getLogger().println("Setting " + remoteName + " to " + gitSCMSource.getRemote());
client.setRemoteUrl(remoteName, gitSCMSource.getRemote());
listener.getLogger().println("Fetching & pruning " + remoteName + "...");
URIish remoteURI = null;
try {
remoteURI = new URIish(remoteName);
} catch (URISyntaxException ex) {
listener.getLogger().println("URI syntax exception for '" + remoteName + "' " + ex);
}
client.fetch_().prune(true).from(remoteURI, builder.asRefSpecs()).execute();
listener.getLogger().println("Done.");
return new GitSCMFileSystem(client, gitSCMSource.getRemote(), Constants.R_REMOTES+remoteName+"/"+head.getName(),
(AbstractGitSCMSource.SCMRevisionImpl) rev);
} finally {
cacheLock.unlock();
}
}
}
} |
package lemming.table;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
/**
* A TextFilteredColumn enabling row selection.
*
* @param <T> object type
* @param <F> filter model type
* @param <S> sort property type
*/
public class GenericRowSelectColumn<T,F,S> extends TextFilterColumn<T,F,S> {
/**
* Determines if a deserialized file is compatible with this class.
*/
private static final long serialVersionUID = 1L;
/**
* Creates a row selection column.
*
* @param displayModel title of a column
* @param propertyExpression property expression of a column
*/
public GenericRowSelectColumn(IModel<String> displayModel, String propertyExpression) {
super(displayModel, propertyExpression);
}
/**
* Creates a row selection column.
*
* @param displayModel model of a column
* @param sortProperty sort property of a column
* @param propertyExpression property expression of a column
*/
public GenericRowSelectColumn(IModel<String> displayModel, S sortProperty, String propertyExpression) {
super(displayModel, sortProperty, propertyExpression);
}
/**
* Populates the current table cell item.
*
* @param item item representing the current table cell being rendered
* @param componentId id of the component used to render the cell
* @param rowModel model of the row item being rendered
*/
@Override
public void populateItem(Item<ICellPopulator<T>> item, String componentId, IModel<T> rowModel) {
item.add(new CheckboxPanel(componentId, rowModel));
}
/**
* A panel used to display a checkbox.
*/
private class CheckboxPanel<T> extends Panel {
/**
* Determines if a deserialized file is compatible with this class.
*/
private static final long serialVersionUID = 1L;
/**
* Creates a panel.
*
* @param id ID of the panel
* @param model row model
*/
public CheckboxPanel(String id, IModel<T> model) {
super(id, model);
CheckBox checkBox = new CheckBox("selected", new PropertyModel<Boolean>(model, getPropertyExpression()));
checkBox.add(new AjaxFormComponentUpdatingBehavior("change") {
@Override
protected void onUpdate(AjaxRequestTarget target) {
}
});
add(checkBox);
}
}
} |
package mekfarm.containers;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.items.IItemHandler;
public class CropFarmContainer extends FarmContainer {
public CropFarmContainer(IInventory playerInventory, TileEntity te) {
super(playerInventory, te);
}
@Override
protected Slot createInputSlot(IItemHandler itemHandler, int slotIndex, int xPosition, int yPosition) {
return new TexturedSlot(itemHandler, slotIndex, xPosition, yPosition, 117, 226, 5);
}
} |
package mx.nic.rdap.server;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import mx.nic.rdap.core.catalog.Role;
import mx.nic.rdap.db.RdapUser;
import mx.nic.rdap.db.exception.InitializationException;
import mx.nic.rdap.db.exception.RdapDataAccessException;
import mx.nic.rdap.db.service.DataAccessService;
import mx.nic.rdap.db.spi.RdapUserDAO;
import mx.nic.rdap.server.catalog.OperationalProfile;
/**
* Class containing the configuration of the rdap server
*/
public class RdapConfiguration {
private static Properties systemProperties;
// property keys
private static final String LANGUAGE_KEY = "language";
private static final String ZONE_KEY = "zones";
private static final String MINIMUN_SEARCH_PATTERN_LENGTH_KEY = "minimum_search_pattern_length";
private static final String MAX_NUMBER_OF_RESULTS_FOR_AUTHENTICATED_USER = "max_number_result_authenticated_user";
private static final String MAX_NUMBER_OF_RESULTS_FOR_UNAUTHENTICATED_USER = "max_number_result_unauthenticated_user";
private static final String OWNER_ROLES_KEY = "owner_roles";
private static final String IS_REVERSE_IPV4_ENABLED_KEY = "is_reverse_ipv4_enabled";
private static final String IS_REVERSE_IPV6_ENABLED_KEY = "is_reverse_ipv6_enabled";
private static final String OPERATIONAL_PROFILE_KEY = "operational_profile";
private static final String ANONYMOUS_USERNAME_KEY = "anonymous_username";
private static final String ALLOW_WILDCARDS_KEY = "allow_search_wildcards_anywhere";
// Settings values
private static String serverLanguage;
private static Integer minimumSearchPatternLength;
private static Integer maxNumberOfResultsForAuthenticatedUser;
private static Integer maxNumberOfResultsForUnauthenticatedUser;
private static Set<Role> objectOwnerRoles;
private static OperationalProfile operationalProfile;
private static String anonymousUsername;
private static Set<String> validZones;
private static boolean allowSearchWilcardsAnywhere;
private static String REVERSE_IP_V4 = "in-addr.arpa";
private static String REVERSE_IP_V6 = "ip6.arpa";
private RdapConfiguration() {
// no code.
}
/**
* Load the parameters defined in the configuration file
*
* @param systemProperties
* the systemProperties to set
*/
public static void loadSystemProperties(Properties systemProperties) {
RdapConfiguration.systemProperties = systemProperties;
}
/**
* Return the list of zones defined in the configuration file
*
* @return
*/
private static List<String> getServerZones() {
if (systemProperties.containsKey(ZONE_KEY)) {
String zones[] = systemProperties.getProperty(ZONE_KEY).trim().split(",");
List<String> trimmedZones = new ArrayList<String>();
for (String zone : zones) {
zone = zone.trim();
if (zone.isEmpty())
continue;
if (zone.endsWith("."))
zone = zone.substring(0, zone.length() - 1);
if (zone.startsWith("."))
zone = zone.substring(1);
trimmedZones.add(zone);
}
return trimmedZones;
}
return Collections.emptyList();
}
/**
* Validate if the configured zones are in the database
*/
public static void validateConfiguredZones() {
List<String> propertiesZone = RdapConfiguration.getServerZones();
validZones = new HashSet<>(propertiesZone);
// Configure reverse zones
if (Boolean.parseBoolean(systemProperties.getProperty(IS_REVERSE_IPV4_ENABLED_KEY))) {
validZones.add(REVERSE_IP_V4);
} else {
validZones.remove(REVERSE_IP_V4);
}
if (Boolean.parseBoolean(systemProperties.getProperty(IS_REVERSE_IPV6_ENABLED_KEY))) {
validZones.add(REVERSE_IP_V6);
} else {
validZones.remove(REVERSE_IP_V6);
}
}
public static void validateConfiguredRoles() throws InitializationException {
String ownerRoles = systemProperties.getProperty(OWNER_ROLES_KEY);
if (ownerRoles == null) {
throw new InitializationException("property '" + OWNER_ROLES_KEY + "' is not configured");
}
String[] split = ownerRoles.split(",");
objectOwnerRoles = new HashSet<Role>();
for (String role : split) {
role = role.trim();
if (role.isEmpty())
continue;
Role rolEnum = Role.getByName(role);
if (rolEnum == null) {
throw new InitializationException("unknown role in property '" + OWNER_ROLES_KEY + "': " + role);
}
objectOwnerRoles.add(rolEnum);
}
}
public static boolean isRoleAnOwner(Role role) {
return objectOwnerRoles.contains(role);
}
public static void validateRdapConfiguration() throws InitializationException {
boolean isValid = true;
List<String> invalidProperties = new ArrayList<>();
List<Exception> exceptions = new ArrayList<>();
if (systemProperties.getProperty(LANGUAGE_KEY) == null
|| systemProperties.getProperty(LANGUAGE_KEY).trim().isEmpty()) {
isValid = false;
invalidProperties.add(LANGUAGE_KEY);
}
serverLanguage = systemProperties.getProperty(LANGUAGE_KEY).trim();
if (systemProperties.getProperty(MINIMUN_SEARCH_PATTERN_LENGTH_KEY) == null) {
isValid = false;
invalidProperties.add(MINIMUN_SEARCH_PATTERN_LENGTH_KEY);
} else {
try {
minimumSearchPatternLength = Integer
.parseInt(systemProperties.getProperty(MINIMUN_SEARCH_PATTERN_LENGTH_KEY).trim());
} catch (NumberFormatException e) {
isValid = false;
invalidProperties.add(MINIMUN_SEARCH_PATTERN_LENGTH_KEY);
exceptions.add(e);
}
}
if (systemProperties.getProperty(MAX_NUMBER_OF_RESULTS_FOR_AUTHENTICATED_USER) == null) {
isValid = false;
invalidProperties.add(MAX_NUMBER_OF_RESULTS_FOR_AUTHENTICATED_USER);
} else {
try {
maxNumberOfResultsForAuthenticatedUser = Integer
.parseInt(systemProperties.getProperty(MAX_NUMBER_OF_RESULTS_FOR_AUTHENTICATED_USER).trim());
} catch (NumberFormatException e) {
isValid = false;
invalidProperties.add(MAX_NUMBER_OF_RESULTS_FOR_AUTHENTICATED_USER);
exceptions.add(e);
}
}
if (systemProperties.getProperty(MAX_NUMBER_OF_RESULTS_FOR_UNAUTHENTICATED_USER) == null) {
isValid = false;
invalidProperties.add(MAX_NUMBER_OF_RESULTS_FOR_UNAUTHENTICATED_USER);
} else {
try {
maxNumberOfResultsForUnauthenticatedUser = Integer
.parseInt(systemProperties.getProperty(MAX_NUMBER_OF_RESULTS_FOR_UNAUTHENTICATED_USER).trim());
} catch (NumberFormatException e) {
isValid = false;
invalidProperties.add(MAX_NUMBER_OF_RESULTS_FOR_UNAUTHENTICATED_USER);
exceptions.add(e);
}
}
if (systemProperties.getProperty(OWNER_ROLES_KEY) == null) {
isValid = false;
invalidProperties.add(OWNER_ROLES_KEY);
}
if (systemProperties.getProperty(OPERATIONAL_PROFILE_KEY) != null) {
String property = systemProperties.getProperty(OPERATIONAL_PROFILE_KEY).trim();
try {
operationalProfile = OperationalProfile.valueOf(property.toUpperCase());
switch (operationalProfile) {
case REGISTRAR:
break;
case REGISTRY:
break;
case NONE:
break;
default:
isValid = false;
invalidProperties.add(OPERATIONAL_PROFILE_KEY);
}
} catch (IllegalArgumentException iae) {
isValid = false;
invalidProperties.add(OPERATIONAL_PROFILE_KEY);
}
}
if (systemProperties.getProperty(ANONYMOUS_USERNAME_KEY) == null) {
isValid = false;
invalidProperties.add(ANONYMOUS_USERNAME_KEY);
} else {
anonymousUsername = systemProperties.getProperty(ANONYMOUS_USERNAME_KEY).trim();
}
String allowWildcardProperty = systemProperties.getProperty(ALLOW_WILDCARDS_KEY);
if (allowWildcardProperty == null || allowWildcardProperty.trim().isEmpty()) {
isValid = false;
invalidProperties.add(ALLOW_WILDCARDS_KEY);
} else {
allowWildcardProperty = allowWildcardProperty.trim();
if (allowWildcardProperty.equalsIgnoreCase("true")) {
allowSearchWilcardsAnywhere = true;
} else if (allowWildcardProperty.equalsIgnoreCase("false")) {
allowSearchWilcardsAnywhere = false;
} else {
isValid = false;
invalidProperties.add(ALLOW_WILDCARDS_KEY);
}
}
if (!isValid) {
InitializationException invalidValueException = new InitializationException(
"The following required properties were not found or are invalid values in configuration file : "
+ invalidProperties.toString());
for (Exception exception : exceptions) {
invalidValueException.addSuppressed(exception);
}
throw invalidValueException;
}
}
/**
* @return the server language defined in the configuration file
*/
public static String getServerLanguage() {
return serverLanguage;
}
/**
* @return the minimum search pattern length defined in configuration file
*/
public static int getMinimumSearchPatternLength() {
return minimumSearchPatternLength;
}
/**
* @return the max number of results for the authenticated user
*/
private static int getMaxNumberOfResultsForAuthenticatedUser() {
return maxNumberOfResultsForAuthenticatedUser;
}
/**
* Return the max number of results for the authenticated user
*
*/
private static int getMaxNumberOfResultsForUnauthenticatedUser() {
return maxNumberOfResultsForUnauthenticatedUser;
}
/**
* Return the profile configured for the server
*/
public static OperationalProfile getServerProfile() {
return operationalProfile;
}
/**
* Return if the server supports wildcards in the end of the searches.
*/
public static boolean allowSearchWildcardsAnywhere() {
return allowSearchWilcardsAnywhere;
}
/**
* Get the max search results number allowed for the user
*
* @return
* @throws SQLException
* @throws IOException
*/
public static int getMaxNumberOfResultsForUser(String username) throws RdapDataAccessException {
if (username != null) {
// Find if the user has a custom limit.
Integer limit = null;
RdapUserDAO dao = DataAccessService.getRdapUserDAO();
if (dao != null) {
RdapUser user = dao.getByUsername(username);
if (user != null) {
limit = user.getMaxSearchResults();
}
}
if (limit != null && limit != 0) {
return limit;
} else {
// return server configuration.
return getMaxNumberOfResultsForAuthenticatedUser();
}
}
return getMaxNumberOfResultsForUnauthenticatedUser();
}
/**
* @param username
* username to evaluate if it is an anonymous username
* @return <code>true</code> if username is anonymous or null, otherwise
* <code>false</code>
*/
public static boolean isAnonymousUsername(String username) {
return (username == null || anonymousUsername.equalsIgnoreCase(username));
}
public static boolean isValidZone(String domain) {
// TODO test works as expected, comitting just to create branch
if (isReverseAddress(domain))
return isValidReverseAddress(domain);
String[] split = domain.split("\\.", 2);
String zone = split[1].trim().toLowerCase();
if (zone.endsWith(".")) {
zone = zone.substring(0, zone.length() - 1);
}
return validZones.contains(zone);
}
// Validates if a reverse address is a valid zone
private static boolean isValidReverseAddress(String domain) {
if (domain.endsWith(REVERSE_IP_V4))
return validZones.contains(REVERSE_IP_V4);
if (domain.endsWith(REVERSE_IP_V6))
return validZones.contains(REVERSE_IP_V6);
return false;
}
/**
* validate if a address is in reverse lookup
*
*/
private static boolean isReverseAddress(String address) {
return address.trim().endsWith(REVERSE_IP_V4) || address.trim().endsWith(REVERSE_IP_V6);
}
public static boolean hasZoneConfigured() {
if (validZones == null || validZones.isEmpty()) {
return false;
}
return true;
}
} |
package net.imagej.ops;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import net.imagej.ops.convert.ConvertNamespace;
import net.imagej.ops.copy.CopyNamespace;
import net.imagej.ops.create.CreateNamespace;
import net.imagej.ops.deconvolve.DeconvolveNamespace;
import net.imagej.ops.features.haralick.HaralickNamespace;
import net.imagej.ops.features.lbp2d.LBPNamespace;
import net.imagej.ops.features.tamura2d.TamuraNamespace;
import net.imagej.ops.features.zernike.ZernikeNamespace;
import net.imagej.ops.filter.FilterNamespace;
import net.imagej.ops.geom.GeomNamespace;
import net.imagej.ops.image.ImageNamespace;
import net.imagej.ops.imagemoments.ImageMomentsNamespace;
import net.imagej.ops.labeling.LabelingNamespace;
import net.imagej.ops.logic.LogicNamespace;
import net.imagej.ops.map.neighborhood.CenterAwareComputerOp;
import net.imagej.ops.math.MathNamespace;
import net.imagej.ops.stats.StatsNamespace;
import net.imagej.ops.thread.ThreadNamespace;
import net.imagej.ops.threshold.ThresholdNamespace;
import net.imglib2.IterableInterval;
import net.imglib2.RandomAccessible;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.algorithm.neighborhood.Shape;
import net.imglib2.type.Type;
import org.scijava.AbstractContextual;
import org.scijava.command.CommandInfo;
import org.scijava.command.CommandService;
import org.scijava.module.Module;
import org.scijava.module.ModuleItem;
import org.scijava.plugin.Parameter;
/**
* Abstract superclass for {@link OpEnvironment} implementations.
*
* @author Curtis Rueden
*/
public abstract class AbstractOpEnvironment extends AbstractContextual
implements OpEnvironment
{
@Parameter
private CommandService commandService;
@Parameter
private OpMatchingService matcher;
@Parameter
private NamespaceService namespaceService;
// -- OpEnvironment methods --
@Override
public Object run(final String name, final Object... args) {
return run(module(name, args));
}
@Override
public <OP extends Op> Object run(final Class<OP> type, final Object... args)
{
return run(module(type, args));
}
@Override
public Object run(final Op op, final Object... args) {
return run(module(op, args));
}
@Override
public Op op(final String name, final Object... args) {
return OpUtils.unwrap(module(name, args), Op.class, null);
}
@Override
public <OP extends Op> OP op(final Class<OP> type, final Object... args) {
return OpUtils.unwrap(module(type, args), type, null);
}
@Override
@SuppressWarnings("unchecked")
public <I, O, OP extends Op> ComputerOp<I, O> computer(
final Class<OP> opType, final Class<O> outType, final Class<I> inType,
final Object... otherArgs)
{
final Object[] args = args2(outType, inType, otherArgs);
return (ComputerOp<I, O>) specialOp(opType, ComputerOp.class, null, args);
}
@Override
@SuppressWarnings("unchecked")
public <I, O, OP extends Op> ComputerOp<I, O> computer(
final Class<OP> opType, final Class<O> outType, final I in,
final Object... otherArgs)
{
final Object[] args = args2(outType, in, otherArgs);
return (ComputerOp<I, O>) specialOp(opType, ComputerOp.class, null, args);
}
@Override
@SuppressWarnings("unchecked")
public <I, O, OP extends Op> ComputerOp<I, O> computer(
final Class<OP> opType, final O out, final I in, final Object... otherArgs)
{
final Object[] args = args2(out, in, otherArgs);
return (ComputerOp<I, O>) specialOp(opType, ComputerOp.class, null, args);
}
@Override
@SuppressWarnings("unchecked")
public <I, O, OP extends Op> FunctionOp<I, O> function(
final Class<OP> opType, final Class<O> outType, final Class<I> inType,
final Object... otherArgs)
{
final Object[] args = args1(inType, otherArgs);
return (FunctionOp<I, O>) specialOp(opType, FunctionOp.class, outType, args);
}
@Override
@SuppressWarnings("unchecked")
public <I, O, OP extends Op> FunctionOp<I, O> function(
final Class<OP> opType, final Class<O> outType, final I in,
final Object... otherArgs)
{
final Object[] args = args1(in, otherArgs);
return (FunctionOp<I, O>) specialOp(opType, FunctionOp.class, outType, args);
}
@Override
@SuppressWarnings("unchecked")
public <I, O, OP extends Op> HybridOp<I, O> hybrid(final Class<OP> opType,
final Class<O> outType, final Class<I> inType, final Object... otherArgs)
{
final Object[] args = args2(outType, inType, otherArgs);
return (HybridOp<I, O>) specialOp(opType, HybridOp.class, null, args);
}
@Override
@SuppressWarnings("unchecked")
public <I, O, OP extends Op> HybridOp<I, O> hybrid(final Class<OP> opType,
final Class<O> outType, final I in, final Object... otherArgs)
{
final Object[] args = args2(outType, in, otherArgs);
return (HybridOp<I, O>) specialOp(opType, HybridOp.class, null, args);
}
@Override
@SuppressWarnings("unchecked")
public <I, O, OP extends Op> HybridOp<I, O> hybrid(final Class<OP> opType,
final O out, final I in, final Object... otherArgs)
{
final Object[] args = args2(out, in, otherArgs);
return (HybridOp<I, O>) specialOp(opType, HybridOp.class, null, args);
}
@Override
@SuppressWarnings("unchecked")
public <A, OP extends Op> InplaceOp<A> inplace(final Class<OP> opType,
final Class<A> argType, final Object... otherArgs)
{
final Object[] args = args1(argType, otherArgs);
return (InplaceOp<A>) specialOp(opType, InplaceOp.class, null, args);
}
@Override
@SuppressWarnings("unchecked")
public <A, OP extends Op> InplaceOp<A> inplace(final Class<OP> opType,
final A arg, final Object... otherArgs)
{
final Object[] args = args1(arg, otherArgs);
return (InplaceOp<A>) specialOp(opType, InplaceOp.class, null, args);
}
@Override
public Module module(final String name, final Object... args) {
return matcher.findModule(this, new OpRef<Op>(name, args));
}
@Override
public <OP extends Op> Module module(final Class<OP> type,
final Object... args)
{
return matcher.findModule(this, new OpRef<OP>(type, args));
}
@Override
public Module module(final Op op, final Object... args) {
final Module module = info(op).createModule(op);
getContext().inject(module.getDelegateObject());
return matcher.assignInputs(module, args);
}
@Override
public Collection<String> ops() {
// collect list of unique operation names
final HashSet<String> operations = new HashSet<String>();
for (final CommandInfo info : infos()) {
final String name = info.getName();
if (name != null && !name.isEmpty()) operations.add(info.getName());
}
// convert the set into a sorted list
final ArrayList<String> sorted = new ArrayList<String>(operations);
Collections.sort(sorted);
return sorted;
}
@Override
public <NS extends Namespace> NS namespace(final Class<NS> nsClass) {
return namespaceService.create(nsClass, this);
}
// -- Operation shortcuts - global namespace --
@Override
public Object eval(final Object... args) {
return run(Ops.Eval.NAME, args);
}
@Override
public Object eval(final String expression) {
final Object result =
run(net.imagej.ops.eval.DefaultEval.class, expression);
return result;
}
@Override
public Object eval(final String expression, final Map<String, Object> vars) {
final Object result =
run(net.imagej.ops.eval.DefaultEval.class, expression, vars);
return result;
}
@Override
public Object help(final Object... args) {
return run(Ops.Help.NAME, args);
}
@Override
public String help(final Op op) {
final String result = (String) run(net.imagej.ops.help.HelpForOp.class, op);
return result;
}
@Override
public String help(final Namespace namespace) {
final String result =
(String) run(net.imagej.ops.help.HelpForNamespace.class, namespace);
return result;
}
@Override
public String help() {
final String result =
(String) run(net.imagej.ops.help.HelpCandidates.class);
return result;
}
@Override
public String help(final String name) {
final String result =
(String) run(net.imagej.ops.help.HelpCandidates.class, name);
return result;
}
@Override
public String help(final String name, final Class<? extends Op> opType) {
final String result =
(String) run(net.imagej.ops.help.HelpCandidates.class, name, opType);
return result;
}
@Override
public Object identity(final Object... args) {
return run(Ops.Identity.NAME, args);
}
@Override
public <A> A identity(final A arg) {
@SuppressWarnings("unchecked")
final A result =
(A) run(net.imagej.ops.identity.DefaultIdentity.class, arg);
return result;
}
@Override
public Object join(final Object... args) {
return run(Ops.Join.NAME, args);
}
@Override
public <A, B, C> C join(final C out, final A in, final ComputerOp<A, B> first,
final ComputerOp<B, C> second)
{
@SuppressWarnings("unchecked")
final C result =
(C) run(net.imagej.ops.join.DefaultJoinComputerAndComputer.class, out,
in, first, second);
return result;
}
@Override
public <A, B, C> C join(final C out, final A in, final ComputerOp<A, B> first,
final ComputerOp<B, C> second, final BufferFactory<A, B> bufferFactory)
{
@SuppressWarnings("unchecked")
final C result =
(C) run(net.imagej.ops.join.DefaultJoinComputerAndComputer.class, out,
in, first, second, bufferFactory);
return result;
}
@Override
public <A> A join(final A arg, final InplaceOp<A> first,
final InplaceOp<A> second)
{
@SuppressWarnings("unchecked")
final A result =
(A) run(net.imagej.ops.join.DefaultJoinInplaceAndInplace.class, arg,
first, second);
return result;
}
@Override
public <A> A join(final A out, final A in,
final List<? extends ComputerOp<A, A>> ops,
final BufferFactory<A, A> bufferFactory)
{
@SuppressWarnings("unchecked")
final A result =
(A) run(net.imagej.ops.join.DefaultJoinComputers.class, out, in,
ops, bufferFactory);
return result;
}
@Override
public <A> A join(final A arg, final List<InplaceOp<A>> ops) {
@SuppressWarnings("unchecked")
final A result =
(A) run(net.imagej.ops.join.DefaultJoinInplaces.class, arg, ops);
return result;
}
@Override
public <A, B> B join(final B out, final A in, final InplaceOp<A> first,
final ComputerOp<A, B> second)
{
@SuppressWarnings("unchecked")
final B result =
(B) run(net.imagej.ops.join.DefaultJoinInplaceAndComputer.class, out, in,
first, second);
return result;
}
@Override
public <A, B> B join(final B out, final A in, final InplaceOp<A> first,
final ComputerOp<A, B> second, final BufferFactory<A, A> bufferFactory)
{
@SuppressWarnings("unchecked")
final B result =
(B) run(net.imagej.ops.join.DefaultJoinInplaceAndComputer.class, out, in,
first, second, bufferFactory);
return result;
}
@Override
public <A, B> B join(final B out, final A in, final ComputerOp<A, B> first,
final InplaceOp<B> second)
{
@SuppressWarnings("unchecked")
final B result =
(B) run(net.imagej.ops.join.DefaultJoinComputerAndInplace.class, out, in,
first, second);
return result;
}
@Override
public <A, B> B join(final B out, final A in, final ComputerOp<A, B> first,
final InplaceOp<B> second, final BufferFactory<A, B> bufferFactory)
{
@SuppressWarnings("unchecked")
final B result =
(B) run(net.imagej.ops.join.DefaultJoinComputerAndInplace.class, out, in,
first, second, bufferFactory);
return result;
}
@Override
public Object loop(final Object... args) {
return run(Ops.Loop.NAME, args);
}
@Override
public <I> I loop(final I arg, final ComputerOp<I, I> op, final int n) {
@SuppressWarnings("unchecked")
final I result =
(I) run(net.imagej.ops.loop.DefaultLoopInplace.class, arg, op, n);
return result;
}
@Override
public <A> A loop(final A out, final A in, final ComputerOp<A, A> op,
final BufferFactory<A, A> bufferFactory, final int n)
{
@SuppressWarnings("unchecked")
final A result =
(A) run(net.imagej.ops.loop.DefaultLoopComputer.class, out, in, op,
bufferFactory, n);
return result;
}
@Override
public Object map(final Object... args) {
return run(Ops.Map.NAME, args);
}
@Override
public <A, B extends Type<B>> RandomAccessibleInterval<B> map(
final RandomAccessibleInterval<A> input, final ComputerOp<A, B> op,
final B type)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<B> result =
(RandomAccessibleInterval<B>) run(
net.imagej.ops.map.MapConvertRAIToRAI.class, input, op, type);
return result;
}
@Override
public <A, B extends Type<B>> RandomAccessible<B> map(
final RandomAccessible<A> input, final ComputerOp<A, B> op, final B type)
{
@SuppressWarnings("unchecked")
final RandomAccessible<B> result =
(RandomAccessible<B>) run(
net.imagej.ops.map.MapConvertRandomAccessToRandomAccess.class, input,
op, type);
return result;
}
@Override
public <A, B extends Type<B>> IterableInterval<B> map(
final IterableInterval<A> input, final ComputerOp<A, B> op, final B type)
{
@SuppressWarnings("unchecked")
final IterableInterval<B> result =
(IterableInterval<B>) run(
net.imagej.ops.map.MapIterableIntervalToView.class, input, op,
type);
return result;
}
@Override
public <A> IterableInterval<A> map(final IterableInterval<A> arg,
final InplaceOp<A> op)
{
@SuppressWarnings("unchecked")
final IterableInterval<A> result =
(IterableInterval<A>) run(net.imagej.ops.map.MapParallel.class, arg, op);
return result;
}
@Override
public <A, B> IterableInterval<B> map(final IterableInterval<B> out,
final IterableInterval<A> in, final ComputerOp<A, B> op)
{
// net.imagej.ops.map.MapIterableToIterableParallel.class
// net.imagej.ops.map.MapIterableIntervalToIterableInterval.class
@SuppressWarnings("unchecked")
final IterableInterval<B> result =
(IterableInterval<B>) run(net.imagej.ops.Ops.Map.class, out, in, op);
return result;
}
@Override
public <A, B> RandomAccessibleInterval<B> map(
final RandomAccessibleInterval<B> out, final IterableInterval<A> in,
final ComputerOp<A, B> op)
{
// net.imagej.ops.map.MapIterableToRAIParallel.class
// net.imagej.ops.map.MapIterableIntervalToRAI.class
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<B> result =
(RandomAccessibleInterval<B>) run(net.imagej.ops.Ops.Map.class, out, in,
op);
return result;
}
@Override
public <A> Iterable<A> map(final Iterable<A> arg, final InplaceOp<A> op) {
@SuppressWarnings("unchecked")
final Iterable<A> result =
(Iterable<A>) run(net.imagej.ops.map.MapIterableInplace.class, arg, op);
return result;
}
@Override
public <A, B> IterableInterval<B> map(final IterableInterval<B> out,
final RandomAccessibleInterval<A> in, final ComputerOp<A, B> op)
{
@SuppressWarnings("unchecked")
final IterableInterval<B> result =
(IterableInterval<B>) run(
net.imagej.ops.map.MapRAIToIterableInterval.class, out, in, op);
return result;
}
@Override
public <I, O> RandomAccessibleInterval<O> map(
final RandomAccessibleInterval<O> out,
final RandomAccessibleInterval<I> in, final ComputerOp<Iterable<I>, O> op,
final Shape shape)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<O> result =
(RandomAccessibleInterval<O>) run(
net.imagej.ops.map.neighborhood.MapNeighborhood.class, out, in, op, shape);
return result;
}
@Override
public <I, O> RandomAccessibleInterval<O> map(
final RandomAccessibleInterval<O> out,
final RandomAccessibleInterval<I> in,
final CenterAwareComputerOp<Iterable<I>, O> func, final Shape shape)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<O> result =
(RandomAccessibleInterval<O>) run(
net.imagej.ops.map.neighborhood.MapNeighborhoodWithCenter.class, out, in, func, shape);
return result;
}
@Override
public <A, B> Iterable<B> map(final Iterable<B> out, final Iterable<A> in,
final ComputerOp<A, B> op)
{
@SuppressWarnings("unchecked")
final Iterable<B> result =
(Iterable<B>) run(net.imagej.ops.map.MapIterableToIterable.class, out,
in, op);
return result;
}
@Override
public Object slicewise(final Object... args) {
return run(Ops.Slicewise.NAME, args);
}
@Override
public <I, O> RandomAccessibleInterval<O> slicewise(
final RandomAccessibleInterval<O> out,
final RandomAccessibleInterval<I> in, final ComputerOp<I, O> op,
final int... axisIndices)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<O> result =
(RandomAccessibleInterval<O>) run(
net.imagej.ops.slicewise.SlicewiseRAI2RAI.class, out, in, op,
axisIndices);
return result;
}
@Override
public <I, O> RandomAccessibleInterval<O> slicewise(
final RandomAccessibleInterval<O> out,
final RandomAccessibleInterval<I> in, final ComputerOp<I, O> op,
final int[] axisIndices, final boolean dropSingleDimensions)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<O> result =
(RandomAccessibleInterval<O>) run(
net.imagej.ops.slicewise.SlicewiseRAI2RAI.class, out, in, op,
axisIndices, dropSingleDimensions);
return result;
}
// -- Operation shortcuts - other namespaces --
@Override
public CopyNamespace copy() {
return namespace(CopyNamespace.class);
}
@Override
public ConvertNamespace convert() {
return namespace(ConvertNamespace.class);
}
@Override
public CreateNamespace create() {
return namespace(CreateNamespace.class);
}
@Override
public DeconvolveNamespace deconvolve() {
return namespace(DeconvolveNamespace.class);
}
@Override
public FilterNamespace filter() {
return namespace(FilterNamespace.class);
}
@Override
public GeomNamespace geom() {
return namespace(GeomNamespace.class);
}
@Override
public HaralickNamespace haralick() {
return namespace(HaralickNamespace.class);
}
@Override
public ImageNamespace image() {
return namespace(ImageNamespace.class);
}
@Override
public ImageMomentsNamespace imagemoments() {
return namespace(ImageMomentsNamespace.class);
}
@Override
public LabelingNamespace labeling() {
return namespace(LabelingNamespace.class);
}
@Override
public LBPNamespace lbp() {
return namespace(LBPNamespace.class);
}
@Override
public LogicNamespace logic() {
return namespace(LogicNamespace.class);
}
@Override
public MathNamespace math() {
return namespace(MathNamespace.class);
}
@Override
public StatsNamespace stats() {
return namespace(StatsNamespace.class);
}
@Override
public TamuraNamespace tamura() {
return namespace(TamuraNamespace.class);
}
@Override
public ThreadNamespace thread() {
return namespace(ThreadNamespace.class);
}
@Override
public ThresholdNamespace threshold() {
return namespace(ThresholdNamespace.class);
}
@Override
public ZernikeNamespace zernike() {
return namespace(ZernikeNamespace.class);
}
// -- Helper methods --
private Object run(final Module module) {
module.run();
return result(module);
}
private Object result(final Module module) {
final List<Object> outputs = new ArrayList<Object>();
for (final ModuleItem<?> output : module.getInfo().outputs()) {
final Object value = output.getValue(module);
outputs.add(value);
}
return outputs.size() == 1 ? outputs.get(0) : outputs;
}
/**
* Looks up an op of the given type, similar to {@link #op(Class, Object...)},
* but with an additional type constraint—e.g., matches could be
* restricted to {@link ComputerOp}s.
*
* @param opType The type of op to match.
* @param specialType The additional constraint (e.g., {@link ComputerOp}).
* @param outType The type of the op's primary output, or null for any type.
* @param args The arguments to use when matching.
* @return The matched op.
*/
private <OP extends Op> OP specialOp(final Class<OP> opType,
final Class<?> specialType, final Class<?> outType, final Object... args)
{
final OpRef<OP> ref =
new OpRef<OP>(Collections.singleton(specialType), opType, args);
if (outType != null) ref.setOutputs(Collections.singleton(outType));
final Module module = matcher.findModule(this, ref);
return OpUtils.unwrap(module, ref);
}
private Object[] args1(final Object o0, final Object... more) {
final Object[] result = new Object[1 + more.length];
result[0] = o0;
int i = 1;
for (final Object o : more) {
result[i++] = o;
}
return result;
}
private Object[]
args2(final Object o0, final Object o1, final Object... more)
{
final Object[] result = new Object[2 + more.length];
result[0] = o0;
result[1] = o1;
int i = 2;
for (final Object o : more) {
result[i++] = o;
}
return result;
}
} |
package net.networkdowntime.search.trie;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import gnu.trove.map.hash.TCharObjectHashMap;
public abstract class Trie {
private static final Logger LOGGER = LogManager.getLogger(Trie.class.getName());
protected boolean createFullTrie = true;
protected TrieNode rootNode = new TrieNode();
/**
* Default constructor generates a full suffix trie
*/
public Trie() {
}
/**
* Allows the creator to create either a full of non-full trie
*
* @param createFullTrie
*/
public Trie(boolean createFullTrie) {
this.createFullTrie = createFullTrie;
}
/**
* Gets either the beginning or ending character from the word.
* Beginning character for a Suffix, ending for a Prefix
*
* @param word
* @return
*/
protected abstract char getChar(String word);
/**
* Gets the character from the opposite end of the word than getChar()
*
* @param word
* @return
*/
protected abstract char getOppositeChar(String word);
/**
* Removes a character from a end of the string and returns the substring.
* Remove the beginning character for a Suffix, ending for a Prefix
*
* @param word
* @return
*/
protected abstract String getSubstring(String word);
/**
* Concatenates the character and the wordPart and returns the new string.
* wordPart + c for Suffix, c + wordPart for Prefix
* @param c
* @param wordPart
* @return
*/
protected abstract String addCharToWordPart(char c, String wordPart);
/**
* Gets a char[] in the correct order for node traversal to find completions.
* left to right for Suffix, reverse order for prefix
*
* @param word
* @return
*/
protected abstract char[] getCharArr(String word);
/**
* Adds a word to the trie
*
* @param word
*/
public void add(String word) {
addInternal(rootNode, word, true);
}
/**
* Private internal method to recursively add the wordPart the trie structure
*
* @param wordPart Prefix to be added to the trie
*/
private void addInternal(TrieNode node, String wordPart, boolean isFullWord) {
int length = wordPart.length();
node.children = (node.children != null) ? node.children : new TCharObjectHashMap<TrieNode>(1, 0.9f);
char c = getChar(wordPart);
TrieNode child = node.children.get(c);
if (child == null) {
child = new TrieNode(c);
node.children.put(c, child);
}
if (length == 1) { // This is the end of the string and not on the root node, add a child marker to denote end of suffix
child.isEnd = true;
child.isFullWordEnd = child.isFullWordEnd || isFullWord;
} else {
String subString = getSubstring(wordPart);
addInternal(child, subString, isFullWord);
if (createFullTrie && node.c == 0) { // full tree and root node
addInternal(node, subString, false);
}
}
}
/**
* Remove a word from the trie. Much more expensive than adding a word because the entire trie has
* to be walked to ensure nodes needed to ensure the integrity of the trie are not pruned.
*
* @param wordToRemove
*/
public void remove(String wordToRemove) {
Set<String> wordsToPreserve = new HashSet<String>();
if (createFullTrie) { // have to account for all words that share a character with wordToRemove
getFullWordsForRemoval(rootNode, wordToRemove, wordsToPreserve, "");
wordsToPreserve.remove(wordToRemove);
}
removeInternal(rootNode, wordToRemove, true, wordsToPreserve);
}
/**
* Private internal method to recursively remove the wordPart the trie structure
*
* @param node
* @param wordPart
* @param isFullWord
* @param wordsToPreserve
*/
private void removeInternal(TrieNode node, String wordPart, boolean isFullWord, Set<String> wordsToPreserve) {
int length = wordPart.length();
char c = getChar(wordPart);
TrieNode child = node.children.get(c);
boolean isRootNode = node.c == 0;
boolean isPartOfWordToPreserve = false;
for (String wordToPreserve : wordsToPreserve) {
isPartOfWordToPreserve = isPartOfWordToPreserve || child.c == getOppositeChar(wordToPreserve);
}
if (length == 1) {
child.isFullWordEnd = child.isFullWordEnd && !isFullWord;
if (!isPartOfWordToPreserve || !createFullTrie) {
child.isEnd = false;
}
if (!child.isEnd && !child.isFullWordEnd && child.children == null) {
node.children.remove(c);
}
} else {
String subString = getSubstring(wordPart);
removeInternal(child, subString, isFullWord, wordsToPreserve);
if (createFullTrie && isRootNode) { // full tree and root node
removeInternal(node, subString, false, wordsToPreserve);
}
if (child.children.isEmpty() && !child.isEnd) {
node.children.remove(child.c);
}
}
}
/**
* Gets the completions from the trie for the given word part up to the limit.
* Walks the trie until it finds the last node for the word part and then
* calls getCompletionsInternal() to find the completions.
*
* @param wordPart The word part to find completions for.
* @param limit Max number of results to return
* @return A list of the completed words.
*/
public List<String> getCompletions(String wordPart, int limit) {
List<String> completions = new ArrayList<String>();
TrieNode currentNode = rootNode;
for (char c : getCharArr(wordPart)) {
if (currentNode != null && currentNode.children != null) {
currentNode = currentNode.children.get(c);
} else {
currentNode = null;
}
if (currentNode == null) { // no match
return completions;
}
}
getCompletionsInternal(currentNode, completions, wordPart, 0, limit);
return completions;
}
/**
* Private internal method to walk the trie and find the completions, this is called from the last matching node
* of the suffix
*
* @param node The current node
* @param completions The list of completed words
* @param wordPart The word being build up from walking the trie
* @param size Tracks the number of found completions
* @param limit Max number of results to return
* @return the current number of completions
*/
private int getCompletionsInternal(TrieNode node, List<String> completions, String wordPart, int size, int limit) {
int newSize = size;
if (node.isEnd) {
completions.add(wordPart);
newSize++;
}
if (node.children != null && size <= limit) {
for (Object obj : node.children.values()) {
TrieNode child = (TrieNode) obj;
newSize = getCompletionsInternal(child, completions, addCharToWordPart(child.c, wordPart), newSize, limit);
if (newSize == limit) {
break;
}
}
}
return newSize;
}
/**
* Special method needed to support removing words from a non-partial (full) trie. For a given full word to remove, finds all of the
* words that could be impacted and need to be preserved.
*
* @param node The current node
* @param wordToRemove A full word that is part of the trie to be removed
* @param completions A list of the complete words that need to be preserved
* @param wordBeingBuilt The word being build up from walking the trie
*/
private void getFullWordsForRemoval(TrieNode node, String wordToRemove, Set<String> completions, String wordBeingBuilt) {
if (node.isFullWordEnd && node.isEnd && wordBeingBuilt.contains(wordToRemove)) {
completions.add(wordBeingBuilt);
}
if (node.children != null) {
if (node.c == 0 && wordBeingBuilt.length() > 0) { // root node
TrieNode child = node.children.get(getChar(wordBeingBuilt));
if (child != null) {
getFullWordsForRemoval(child, wordToRemove, completions, wordBeingBuilt);
}
} else {
for (Object obj : node.children.values()) {
TrieNode child = (TrieNode) obj;
getFullWordsForRemoval(child, wordToRemove, completions, addCharToWordPart(child.c, wordBeingBuilt));
}
}
}
}
/**
* Checks if the parameter is a known full word in the trie.
*
* @param wordCharArr The word to check if it is a known full word in the trie in getCharArr() ordering
* @return true if the word is a known full word otherwise false
*/
public boolean containsWord(char[] wordCharArr, boolean fullWordMatch) {
TrieNode currentNode = rootNode;
for (char c : wordCharArr) {
if (currentNode != null && currentNode.children != null) {
currentNode = currentNode.children.get(c);
} else {
currentNode = null;
}
if (currentNode == null) { // no match
return false;
}
}
return !fullWordMatch || currentNode.isFullWordEnd;
}
/**
* Implements a spelling check for words with a Damerau-Levenshtein distance of 1
*
* @param word
* @return
*/
public Set<String> getFuzzyCompletions(String word) {
Set<String> completions = new HashSet<String>();
completions.addAll(getMissingInsertions(word));
completions.addAll(getMissingDeletions(word));
completions.addAll(getMissingSubstitutions(word));
completions.addAll(getMissingTranspositions(word));
return completions;
}
private Set<String> getMissingInsertions(String word) {
Set<String> completions = new HashSet<String>();
char[] charArr = getCharArr(word);
char[] newCharArr = new char[charArr.length + 1];
newCharArr[0] = Character.MAX_VALUE;
for (int i = 1; i < newCharArr.length; i++) {
newCharArr[i] = charArr[i - 1];
}
int i = 0;
do {
for (char c : getChildrenForKnownPartOfWord(newCharArr)) {
newCharArr[i] = c;
String currentWord = new String(getCharArr(new String(newCharArr)));
if (containsWord(newCharArr, true)) {
completions.add(currentWord);
}
}
newCharArr[i] = Character.MAX_VALUE;
if (i < newCharArr.length - 1) {
char tmp = newCharArr[i];
newCharArr[i] = newCharArr[i + 1];
newCharArr[i + 1] = tmp;
}
i++;
} while (i < newCharArr.length);
return completions;
}
private Set<String> getMissingDeletions(String word) {
Set<String> completions = new HashSet<String>();
char[] charArr = word.toCharArray();
char[] delCharArr = new char[charArr.length - 1];
int i = 0;
do {
int charIndex = 0;
for (int j = 0; j < charArr.length; j++) { // j represents the char to skip
if (j == i) { // skip this character
} else {
delCharArr[charIndex] = charArr[j];
charIndex++;
}
}
String currentWord = new String(delCharArr);
if (containsWord(getCharArr(currentWord), true)) {
completions.add(currentWord);
}
i++;
} while (i < charArr.length);
return completions;
}
private Set<String> getMissingSubstitutions(String word) {
Set<String> completions = new HashSet<String>();
char[] charArr = getCharArr(word);
char[] newCharArr = new char[charArr.length];
for (int i = 0; i < newCharArr.length; i++) {
newCharArr[i] = charArr[i];
}
int i = 0;
do {
char tmp = newCharArr[i];
newCharArr[i] = Character.MAX_VALUE;
for (char c : getChildrenForKnownPartOfWord(newCharArr)) {
newCharArr[i] = c;
String currentWord = new String(getCharArr(new String(newCharArr)));
if (containsWord(newCharArr, true)) {
completions.add(currentWord);
}
}
newCharArr[i] = tmp;
i++;
} while (i < newCharArr.length);
return completions;
}
private Set<String> getMissingTranspositions(String word) {
Set<String> completions = new HashSet<String>();
if (word.length() > 1) {
char[] charArr = getCharArr(word);
int i = 1;
do {
// transpose
char tmp = charArr[i - 1];
charArr[i - 1] = charArr[i];
charArr[i] = tmp;
if (containsWord(charArr, true)) {
String currentWord = new String(getCharArr(new String(charArr)));
completions.add(currentWord);
}
// undo transpose
charArr[i] = charArr[i - 1];
charArr[i - 1] = tmp;
i++;
} while (i < charArr.length);
}
return completions;
}
private char[] getChildrenForKnownPartOfWord(char[] wordCharArr) {
TrieNode currentNode = rootNode;
int i = 0;
do {
char c = wordCharArr[i];
if (currentNode.children.contains(c)) {
currentNode = currentNode.children.get(c);
} else {
return currentNode.children.keys();
}
i++;
} while (currentNode != null && currentNode.children != null && i < wordCharArr.length);
return new char[0];
}
/**
* Gets the specified number of tabs as a string.
*
* @param tabSpaces
* @return
*/
private String getTabs(int tabSpaces) {
String tabs = "";
for (int i = 0; i < tabSpaces; i++) {
tabs = tabs + "\t";
}
return tabs;
}
/**
* Prints the trie structure for inspection.
*/
public void print() {
List<String> trace = getTrace();
for (String s : trace)
LOGGER.info(s);
}
/**
* Gets the trie structure as a list of strings. Used in the print() method and for unit testing.
* @return
*/
public List<String> getTrace() {
return getTrace(rootNode, 0);
}
/**
* Internal method to walk the trie and build up a readable string representation.
*
* @param node The current node
* @param tabSpaces The number of tab spaces to track indentation
* @return The trie structure as a list of strings
*/
private List<String> getTrace(TrieNode node, int tabSpaces) {
List<String> trace = new ArrayList<String>();
String tabs = getTabs(tabSpaces);
if (node.c == 0) {
boolean isFirst = true;
StringBuilder buff = new StringBuilder(tabs + "Root Node: " + node.children.size() + " children [");
for (Object obj : node.children.values()) {
buff.append(addCommaIfNeeded(isFirst));
buff.append(((TrieNode) obj).c);
isFirst = false;
}
buff.append("]");
trace.add(buff.toString());
} else {
StringBuilder buff = new StringBuilder(tabs + "Child Node: " + node.c + ": " + ((node.children == null) ? "0" : node.children.size()) + " children [");
boolean isFirst = true;
if (node.children != null) {
for (Object obj : node.children.values()) {
buff.append(addCommaIfNeeded(isFirst));
buff.append(((TrieNode) obj).c);
isFirst = false;
}
}
if (node.isEnd) {
buff.append(addCommaIfNeeded(isFirst));
buff.append(Character.MAX_VALUE);
isFirst = false;
}
if (node.isFullWordEnd) {
buff.append(addCommaIfNeeded(isFirst));
buff.append("FWE");
isFirst = false;
}
buff.append("]");
trace.add(buff.toString());
}
if (node.children != null) {
for (Object obj : node.children.values()) {
trace.addAll(getTrace((TrieNode) obj, tabSpaces + 1));
}
}
return trace;
}
private String addCommaIfNeeded(boolean isFirst) {
return (isFirst) ? "" : ", ";
}
} |
package exh3y.telebot;
import java.util.HashMap;
import javax.naming.directory.InvalidAttributesException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import exh3y.telebot.actions.TelegramActionHandler;
public class TeleBot extends Thread {
private final String endpoint;
private final String token;
private final String botName;
private long pollingIntervall = 1000;
private HashMap<String, TelegramActionHandler> actionConnector;
private TelegramActionHandler defaultAction = null;
public TeleBot(String endpoint, String token) {
this.endpoint = endpoint;
this.token = token;
String botName = "unknown";
try {
botName = getBotName();
} catch (JSONException | UnirestException e) {
e.printStackTrace();
}
this.botName = botName;
System.out.println(this.botName);
actionConnector = new HashMap<String, TelegramActionHandler>();
}
/**
* @param token
* @since 0.0.1
*/
public TeleBot(String token) {
this("https://api.telegram.org/bot", token);
}
/**
* <p>
* Registers a new action to be executed on receiving the given command.
* </p>
*
* @param command
* The command to link to the action
* @param action
* The action
* @throws InvalidAttributesException
* @since 0.0.1
*/
public void registerCommandAction(String command, TelegramActionHandler action) throws InvalidAttributesException {
if (actionConnector.containsKey(command)) {
throw new InvalidAttributesException("Command already registered!");
}
actionConnector.put(command, action);
}
/**
* <p>
* Unregisters a command.
* </p>
*
* @param command
* The command to delete
* @since 0.0.1
*/
public void unregisterCommandAction(String command) {
if (actionConnector.containsKey(command)) {
actionConnector.remove(command);
}
}
/**
* <p>
* Registers a action handler to handle all unknown text messages.
* </p>
*
* @param action
* The action to register
* @since 0.0.1
*/
public void registerDefaultTextAction(TelegramActionHandler action) {
defaultAction = action;
}
/**
* <p>
* Sends a message to the given chat.
* </p>
*
* @param chatId
* The chat's id
* @param text
* The message to send
* @return The servers response
* @throws UnirestException
* @since 0.0.1
*/
public HttpResponse<JsonNode> sendMessage(Integer chatId, String text) throws UnirestException {
return Unirest.post(endpoint + token + "/sendMessage").field("chat_id", chatId).field("text", text).asJson();
}
/**
* <p>
* Returns all unprocessed messages.
* </p>
*
* @param offset
* @return
* @throws UnirestException
* @since 0.0.1
*/
public HttpResponse<JsonNode> getUpdates(Integer offset) throws UnirestException {
return Unirest.post(endpoint + token + "/getUpdates").field("offset", offset).asJson();
}
/**
* <p>
* Requests the getMe method.
* </p>
*
* @return
* @throws UnirestException
*/
public HttpResponse<JsonNode> getMe() throws UnirestException {
return Unirest.post(endpoint + token + "/getMe").asJson();
}
/**
* <p>
* Sets the time to wait between update requests.
* </p>
*
* @param millis
* Milliseconds to wait.
*/
public void setPollingIntervall(long millis) {
this.pollingIntervall = millis;
}
private String getBotName() throws JSONException, UnirestException {
return getMe().getBody().getObject().getJSONObject("result").getString("username");
}
@Override
public void run() {
int lastUpdateId = 0;
System.out.println("Listening...");
HttpResponse<JsonNode> response;
while (true) {
try {
response = getUpdates(lastUpdateId++);
if (response.getStatus() == 200) {
JSONArray jsonResponse = response.getBody().getObject().getJSONArray("result");
if (jsonResponse.isNull(0)) {
continue;
} else {
lastUpdateId = jsonResponse.getJSONObject(jsonResponse.length() - 1).getInt("update_id") + 1;
}
for (int i = 0; i < jsonResponse.length(); i++) {
// Iterate over the messages in the last update
JSONObject message = jsonResponse.getJSONObject(i).getJSONObject("message");
int chatId = message.getJSONObject("chat").getInt("id");
if (message.has("text")) {
String command[] = message.getString("text").split(" ");
String cmd = "";
if (command[0].contains("@")) {
command = command[0].split("@");
if (command[1] == botName) {
cmd = command[0];
}
} else {
cmd = command[0];
}
if (actionConnector.containsKey(cmd)) {
TelegramActionHandler action = actionConnector.get(cmd);
action.onCommandReceive(chatId, message);
} else if (defaultAction != null) {
defaultAction.onCommandReceive(chatId, message);
}
}
}
}
} catch (UnirestException e) {
try {
sleep(this.pollingIntervall);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
} |
package net.zomis.calculator.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ShuntYard {
private final CalcContext context;
public ShuntYard(CalcContext context) {
this.context = context;
}
public List<Token> tokenize(String data) {
List<Token> results = new ArrayList<>();
int i = 0;
while (i < data.length()) {
// find the first operator or function call
// extract a token out of it
// move i to the new position
// example token separators: '+', 'mod', 'func(', '(', ')'
int end = i;
for (; end < data.length(); end++) {
int opLength = -1;
for (Operator op : context.operators) {
opLength = match(data, end, op.getKey()) ? op.getKey().length() : opLength;
}
for (String op : context.functions.keySet()) {
opLength = match(data, end, op) && data.charAt(end + op.length()) == '('
? op.length() + 1 : opLength;
}
if (data.charAt(end) == ',') {
opLength = 1;
}
if (data.charAt(end) == ')') {
opLength = 1;
}
if (opLength > 0) {
results.add(new Token(data.substring(i, end).trim(), false));
String valueString = data.substring(end, end + opLength).trim();
if (!valueString.isEmpty()) {
results.add(new Token(valueString, true));
}
end += opLength;
i = end;
}
}
results.add(new Token(data.substring(i).trim(), true));
}
return results;
}
private boolean match(String data, int pos, String key) {
return data.regionMatches(pos, key, 0, key.length());
}
public List<String> convert(String data) {
List<String> results = new ArrayList<>();
return results;
}
} |
package com.ev3;
import static io.undertow.Handlers.path;
import static io.undertow.Handlers.websocket;
import io.undertow.Undertow;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Arrays;
import java.util.Enumeration;
import lejos.hardware.Button;
import lejos.hardware.motor.*;
import lejos.hardware.sensor.EV3ColorSensor;
import lejos.hardware.port.MotorPort;
import lejos.hardware.port.Port;
import lejos.hardware.port.SensorPort;
import lejos.robotics.RegulatedMotor;
import lejos.robotics.SampleProvider;
public class BrickServer {
private static Port colorSensorPort = SensorPort.S2;
private static EV3ColorSensor colorSensor;
private static SampleProvider sampleProvider;
private static int sampleSize;
private static RegulatedMotor lm = new EV3LargeRegulatedMotor(MotorPort.B);
private static RegulatedMotor rm = new EV3LargeRegulatedMotor(MotorPort.C);
public static void main(String[] args) {
// wait for exit
Thread thread = new Thread(){
public void run(){
System.out.print("Thread started");
if (Button.waitForAnyPress() == Button.ID_ESCAPE) {
System.exit(0);
}
}
};
thread.start();
HelloWorld();
//startWebSocketServer();
find_path(1,1);
System.exit(0);
//MotorForward();
}
private static float[] getSample() {
// Initializes the array for holding samples
float[] sample = new float[sampleSize];
// Gets the sample an returns it
sampleProvider.fetchSample(sample, 0);
return sample;
}
private static void find_path(int x, int y)
{
colorSensor = new EV3ColorSensor(colorSensorPort);
sampleProvider = colorSensor.getRedMode();
sampleSize = sampleProvider.sampleSize();
// sample spam and motor work
int i = 0;
float threshold = (float)0.25;
while(true) {
float[] sample = getSample();
System.out.println("N=" + i + " Sample=" + Arrays.toString(sample));
if (sample[0] < threshold)
{
System.out.println("grem levo");
lm.setSpeed(540);
lm.backward();
rm.setSpeed(0);
rm.stop();
}
else
{
System.out.println("grem desno");
lm.setSpeed(0);
lm.stop();
rm.setSpeed(540);
rm.backward();
}
if (i == 100000)
System.exit(0);
i++;
}
}
private static void startWebSocketServer() {
WebSocketCallback callback = new WebSocketCallback();
String ip = "0.0.0.0";
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface
.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
// filters out 127.0.0.1 and inactive interfaces
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
ip = addr.getHostAddress();
Log.info(iface.getDisplayName() + " " + ip);
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
Log.info("Starting server...");
final String host = "0.0.0.0";
Undertow server = Undertow.builder().addHttpListener(8081, host)
.setHandler(path().addPrefixPath("/ev3", websocket(callback)))
.build();
server.start();
Log.info("Server started.");
Log.info("Listening on " + ip + ":8081/ev3");
Thread thread = new Thread(){
public void run(){
System.out.print("Thread started");
if (Button.waitForAnyPress() == Button.ID_ESCAPE) {
System.exit(0);
}
}
};
thread.start();
}
private static void HelloWorld(){
System.out.print("Hello World!");
}
private static void MotorForward(){
Motor.A.forward();
}
} |
package io.norberg.rut;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.List;
import io.norberg.rut.RadixTrie.Node;
import static java.lang.Math.max;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
public class RadixTrieTest {
@Rule public ExpectedException exception = ExpectedException.none();
@Test
public void testSingleRoot() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("a", "a")
.build();
assertThat(rdx.lookup("a"), is("a"));
}
@Test
public void testSingleRootNoMatch() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("aaa", "aaa")
.build();
assertThat(rdx.lookup("aa"), is(nullValue()));
}
@Test
public void testCaptureSuffixMismatch() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("aaa<value>bbb", "foobar")
.build();
assertThat(rdx.lookup("aaabb"), is(nullValue()));
}
@Test
public void testCaptureNoMatchCaptorValueThrows() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("aaa<value>bbb", "foobar")
.build();
final RadixTrie.Captor captor = rdx.captor();
rdx.lookup("aaabb", captor);
exception.expect(IllegalStateException.class);
captor.value("aaabb", 0);
}
@Test
public void testCaptureNoMatchCaptorValueStartThrows() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("aaa<value>bbb", "foobar")
.build();
final RadixTrie.Captor captor = rdx.captor();
rdx.lookup("aaabb", captor);
exception.expect(IllegalStateException.class);
captor.valueStart(0);
}
@Test
public void testCaptureNoMatchCaptorValueEndThrows() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("aaa<value>bbb", "foobar")
.build();
final RadixTrie.Captor captor = rdx.captor();
rdx.lookup("aaabb", captor);
exception.expect(IllegalStateException.class);
captor.valueEnd(0);
}
@Test
public void testCaptureMatchCaptorValueIndexOutOfBoundsThrows() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("a<value>b", "foobar")
.build();
final RadixTrie.Captor captor = rdx.captor();
rdx.lookup("afoob", captor);
exception.expect(IndexOutOfBoundsException.class);
captor.value("afoob", 1);
}
@Test
public void testCaptureMatchCaptorValueStartIndexOutOfBoundsThrows() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("a<value>b", "foobar")
.build();
final RadixTrie.Captor captor = rdx.captor();
rdx.lookup("afoob", captor);
exception.expect(IndexOutOfBoundsException.class);
captor.valueStart(1);
}
@Test
public void testCaptureMatchCaptorValueEndIndexOutOfBoundsThrows() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("a<value>b", "foobar")
.build();
final RadixTrie.Captor captor = rdx.captor();
rdx.lookup("afoob", captor);
exception.expect(IndexOutOfBoundsException.class);
captor.valueEnd(1);
}
@Test
public void testSingleRootCapture() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("<a>", "<a>")
.build();
assertThat(rdx.lookup("foobar"), is("<a>"));
}
@Test
public void testTwoRoots() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("a", "a")
.insert("b", "b")
.build();
assertThat(rdx.lookup("a"), is("a"));
assertThat(rdx.lookup("b"), is("b"));
}
@Test
public void testOneRootOneEdge() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("a", "a")
.insert("ab", "ab")
.build();
assertThat(rdx.lookup("a"), is("a"));
assertThat(rdx.lookup("ab"), is("ab"));
}
@Test
public void testOneRootTwoEdges() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("a", "a")
.insert("ab", "ab")
.insert("ac", "ac")
.build();
assertThat(rdx.lookup("a"), is("a"));
assertThat(rdx.lookup("ab"), is("ab"));
assertThat(rdx.lookup("ac"), is("ac"));
}
@Test
public void testOneRootOneEdgeSplit() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("a", "a")
.insert("abbb", "abbb")
.insert("abcc", "abcc")
.build();
assertThat(rdx.lookup("a"), is("a"));
assertThat(rdx.lookup("abbb"), is("abbb"));
assertThat(rdx.lookup("abcc"), is("abcc"));
}
@Test
public void testOneRootOneEdgeReverse() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("ab", "ab")
.insert("a", "a")
.build();
assertThat(rdx.lookup("a"), is("a"));
assertThat(rdx.lookup("ab"), is("ab"));
}
@Test
public void testQueryAtSplitDoesNotMatch() {
RadixTrie<String> rdx = RadixTrie.builder(String.class)
.insert("a1", "a1")
.insert("a2", "a2")
.build();
final RadixTrie.Captor captor = rdx.captor();
assertThat(rdx.lookup("a?q", captor), is(nullValue()));
assertThat(captor.isMatch(), is(false));
}
@Test(expected = IllegalArgumentException.class)
public void verifyUnclosedCaptureFails() {
RadixTrie.builder(String.class)
.insert("a<", "a<");
}
@Test(expected = IllegalArgumentException.class)
public void verifyEmptyPathFails() {
RadixTrie.builder(String.class)
.insert("", "");
}
@Test(expected = IllegalArgumentException.class)
public void verifyUnorderedSiblingsThrow() {
final Node<String> sibling = new Node<String>((byte) 1, null, null, null, "foo");
new Node<String>((byte) 2, null, sibling, null, "bar");
}
@Test(expected = IllegalArgumentException.class)
public void verifyTerminalNodeWithoutValueThrows() {
new Node<String>((byte) 1, null, null, null, null);
}
@Test(expected = IllegalArgumentException.class)
public void verifyNonAsciiInsertThrows() {
RadixTrie.builder(String.class).insert("" + (char) 128, "foo");
}
@Test
public void testPaths() {
final List<String> paths = asList(
"/a",
"/aa",
"/ab",
"/a/b",
"/a/<b>",
"/a/<b>/c",
"/bb/c",
"/b/c",
"/c/<d>",
"/c/d/e",
"/<a>/b/<c>/<d>/e",
"<foo>/bar"
);
RadixTrie.Builder<String> rdx = RadixTrie.builder();
for (int i = 0; i < paths.size(); i++) {
final String path = paths.get(i);
rdx = rdx.insert(path, path);
assertThat(rdx.toString(), not(isEmptyOrNullString()));
verifyPaths(rdx.build(), paths.subList(0, i + 1));
}
}
private void verifyPaths(final RadixTrie<String> rdx, final List<String> paths) {
for (final String path : paths) {
final RadixTrie.Captor captor = rdx.captor();
assertThat(rdx.lookup(path), is(path));
assertThat(rdx.lookup(path, captor), is(path));
assertThat(captor.isMatch(), is(true));
assertThat(captor.queryStart(), is(-1));
assertThat(captor.queryEnd(), is(-1));
assertThat(captor.query(path), is(nullValue()));
final String pathWithSlash = path + '/';
assertThat(rdx.lookup(pathWithSlash), is(nullValue()));
final String query = "query";
final String pathWithQuery = path + "?" + query;
assertThat(rdx.lookup(pathWithQuery), is(path));
assertThat(rdx.lookup(pathWithQuery, captor), is(path));
assertThat(captor.isMatch(), is(true));
assertThat(captor.queryStart(), is(path.length() + 1));
assertThat(captor.queryEnd(), is(pathWithQuery.length()));
final CharSequence queryParams = captor.query(pathWithQuery);
assertNotNull(queryParams);
assertThat(queryParams.toString(), is(query));
assertThat(rdx.captures(), is(captures(paths)));
assertThat(rdx.toString(), not(isEmptyOrNullString()));
}
}
private static int captures(final List<String> paths) {
int maxCaptures = 0;
for (final String path : paths) {
maxCaptures = max(maxCaptures, captures(path));
}
return maxCaptures;
}
private static int captures(final String path) {
int count = 0;
for (int i = 0; i < path.length(); i++) {
if (path.charAt(i) == '<') {
count++;
}
}
return count;
}
} |
package yuku.alkitab.base.ac;
import android.app.*;
import android.content.*;
import android.database.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.*;
import java.io.*;
import java.util.*;
import org.xml.sax.*;
import org.xml.sax.ext.*;
import org.xmlpull.v1.*;
import yuku.alkitab.*;
import yuku.alkitab.base.*;
import yuku.alkitab.base.dialog.*;
import yuku.alkitab.base.dialog.LabelEditorDialog.OkListener;
import yuku.alkitab.base.model.*;
import yuku.alkitab.base.storage.*;
public class BukmakActivity extends ListActivity {
// out
public static final String EXTRA_ariTerpilih = "ariTerpilih"; //$NON-NLS-1$
private static final int REQCODE_bukmakList = 1;
BukmakFilterAdapter adapter;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
S.siapinKitab();
S.bacaPengaturan();
setContentView(R.layout.activity_bukmak);
setTitle(R.string.judul_bukmak_activity);
adapter = new BukmakFilterAdapter();
adapter.reload();
ListView listView = getListView();
listView.setAdapter(adapter);
registerForContextMenu(listView);
}
private void bikinMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.activity_bukmak, menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
bikinMenu(menu);
return true;
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
if (menu != null) {
bikinMenu(menu);
}
return true;
}
void msgbox(String title, String message) {
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok, null)
.show();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menuImpor) {
final File f = getFileBackup();
new AlertDialog.Builder(this)
.setTitle(R.string.impor_judul)
.setMessage(getString(R.string.impor_pembatas_buku_dan_catatan_dari_tanya, f.getAbsolutePath()))
.setNegativeButton(R.string.no, null)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!f.exists() || !f.canRead()) {
msgbox(getString(R.string.impor_judul), getString(R.string.file_tidak_bisa_dibaca_file, f.getAbsolutePath()));
return;
}
new AlertDialog.Builder(BukmakActivity.this)
.setTitle(R.string.impor_judul)
.setMessage(R.string.apakah_anda_mau_menumpuk_pembatas_buku_dan_catatan_tanya)
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
impor(false);
}
})
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
impor(true);
}
})
.show();
}
})
.show();
return true;
} else if (item.getItemId() == R.id.menuEkspor) {
new AlertDialog.Builder(this)
.setTitle(R.string.ekspor_judul)
.setMessage(R.string.ekspor_pembatas_buku_dan_catatan_tanya)
.setNegativeButton(R.string.no, null)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ekspor();
}
})
.show();
return true;
}
return false;
}
File getFileBackup() {
File dir = new File(Environment.getExternalStorageDirectory(), "bible"); //$NON-NLS-1$
if (!dir.exists()) {
dir.mkdir();
}
return new File(dir, getPackageName() + "-backup.xml"); //$NON-NLS-1$
}
public void impor(boolean tumpuk) {
new AsyncTask<Boolean, Integer, Object>() {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(BukmakActivity.this);
dialog.setTitle(R.string.impor_judul);
dialog.setMessage(getString(R.string.mengimpor_titiktiga));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
@Override
protected Object doInBackground(Boolean... params) {
final List<Bukmak2> list = new ArrayList<Bukmak2>();
final boolean tumpuk = params[0];
final int[] c = new int[1];
try {
File in = getFileBackup();
FileInputStream fis = new FileInputStream(in);
Xml.parse(fis, Xml.Encoding.UTF_8, new DefaultHandler2() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (!localName.equals(Bukmak2.XMLTAG_Bukmak2)) {
return;
}
Bukmak2 bukmak2 = Bukmak2.dariAttributes(attributes);
list.add(bukmak2);
c[0]++;
}
});
fis.close();
} catch (Exception e) {
return e;
}
S.getDb().importBukmak(list, tumpuk);
return c[0];
}
@Override
protected void onPostExecute(Object result) {
dialog.dismiss();
if (result instanceof Integer) {
msgbox(getString(R.string.impor_judul), getString(R.string.impor_berhasil_angka_diproses, result));
} else if (result instanceof Exception) {
msgbox(getString(R.string.impor_judul), getString(R.string.terjadi_kesalahan_ketika_mengimpor_pesan, ((Exception) result).getMessage()));
}
adapter.reload();
}
}.execute((Boolean)tumpuk);
}
public void ekspor() {
new AsyncTask<Void, Integer, Object>() {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(BukmakActivity.this);
dialog.setTitle(R.string.ekspor_judul);
dialog.setMessage(getString(R.string.mengekspor_titiktiga));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
@Override
protected Object doInBackground(Void... params) {
File out = getFileBackup();
try {
FileOutputStream fos = new FileOutputStream(out);
XmlSerializer xml = Xml.newSerializer();
xml.setOutput(fos, "utf-8"); //$NON-NLS-1$
xml.startDocument("utf-8", null); //$NON-NLS-1$
xml.startTag(null, "backup"); //$NON-NLS-1$
Cursor cursor = S.getDb().listSemuaBukmak();
while (cursor.moveToNext()) {
Bukmak2.dariCursor(cursor).writeXml(xml);
}
cursor.close();
xml.endTag(null, "backup"); //$NON-NLS-1$
xml.endDocument();
fos.close();
return out.getAbsolutePath();
} catch (Exception e) {
return e;
}
}
@Override
protected void onPostExecute(Object result) {
dialog.dismiss();
if (result instanceof String) {
msgbox(getString(R.string.ekspor_judul), getString(R.string.ekspor_berhasil_file_yang_dihasilkan_file, result));
} else if (result instanceof Exception) {
msgbox(getString(R.string.ekspor_judul), getString(R.string.terjadi_kesalahan_ketika_mengekspor_pesan, ((Exception) result).getMessage()));
}
}
}.execute();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent;
if (position == 0) {
intent = BukmakListActivity.createIntent(this, Db.Bukmak2.jenis_bukmak, 0);
} else if (position == 1) {
intent = BukmakListActivity.createIntent(this, Db.Bukmak2.jenis_catatan, 0);
} else if (position == 2) {
intent = BukmakListActivity.createIntent(this, Db.Bukmak2.jenis_stabilo, 0);
} else if (position == 3) {
intent = BukmakListActivity.createIntent(this, Db.Bukmak2.jenis_bukmak, BukmakListActivity.LABELID_noLabel);
} else {
Label label = adapter.getItem(position);
if (label != null) {
intent = BukmakListActivity.createIntent(this, Db.Bukmak2.jenis_bukmak, label._id);
} else {
return;
}
}
startActivityForResult(intent, REQCODE_bukmakList);
}
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.context_bukmak, menu);
MenuItem menuRenameLabel = menu.findItem(R.id.menuRenameLabel);
MenuItem menuDeleteLabel = menu.findItem(R.id.menuDeleteLabel);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
if (info.position < 4) {
menuRenameLabel.setEnabled(false);
menuDeleteLabel.setEnabled(false);
} else {
menuRenameLabel.setEnabled(true);
menuDeleteLabel.setEnabled(true);
}
}
@Override public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int itemId = item.getItemId();
if (itemId == R.id.menuRenameLabel) {
final Label label = adapter.getItem(info.position);
if (label == null) {
return true;
}
LabelEditorDialog.show(this, label.judul, getString(R.string.rename_label_title), new OkListener() {
@Override public void onOk(String judul) {
S.getDb().renameLabel(label, judul);
adapter.reload();
}
});
return true;
} else if (itemId == R.id.menuDeleteLabel) {
final Label label = adapter.getItem(info.position);
if (label == null) {
return true;
}
int nbukmak = S.getDb().countBukmakDenganLabel(label);
if (nbukmak == 0) {
// tiada, langsung hapus aja!
S.getDb().hapusLabelById(label._id);
adapter.reload();
} else {
new AlertDialog.Builder(this)
.setTitle(R.string.delete_label_title)
.setMessage(getString(R.string.are_you_sure_you_want_to_delete_the_label_label, label.judul, nbukmak))
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
S.getDb().hapusLabelById(label._id);
adapter.reload();
}
})
.show();
}
return true;
}
return false;
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQCODE_bukmakList) {
if (resultCode == RESULT_OK) {
int ari = data.getIntExtra(BukmakActivity.EXTRA_ariTerpilih, 0);
if (ari != 0) { // 0 berarti ga ada apa2, karena ga ada pasal 0 ayat 0
Intent res = new Intent();
res.putExtra(EXTRA_ariTerpilih, ari);
setResult(RESULT_OK, res);
finish();
}
}
}
adapter.reload();
}
class BukmakFilterAdapter extends BaseAdapter {
// 0. [icon] All bookmarks
// 1. [icon] Notes
// 2. [icon] Highlights
// 3. Unlabeled bookmarks
// 4. dst label2
List<Label> labels;
private String[] presetCaptions = {
getString(R.string.bmcat_all_bookmarks),
getString(R.string.bmcat_notes),
getString(R.string.bmcat_highlights),
getString(R.string.bmcat_unlabeled_bookmarks),
};
private boolean hasLabels() {
return labels != null && labels.size() > 0;
}
@Override public int getCount() {
return 3 + (hasLabels()? 1 + labels.size(): 0);
}
@Override public Label getItem(int position) {
if (position < 4) return null;
return labels.get(position - 4);
}
@Override public long getItemId(int position) {
return position;
}
@Override public View getView(int position, View convertView, ViewGroup parent) {
View res = convertView != null? convertView: getLayoutInflater().inflate(R.layout.item_bukmakfilter, null);
ImageView imgFilterIcon = U.getView(res, R.id.imgFilterIcon);
if (position < 3) {
imgFilterIcon.setVisibility(View.VISIBLE);
imgFilterIcon.setImageResource(position == 0? R.drawable.jenis_bukmak: position == 1? R.drawable.jenis_catatan: position == 2? R.drawable.warnastabilo_checked: 0);
imgFilterIcon.setBackgroundColor(position == 2? 0xffffff00: 0);
} else {
imgFilterIcon.setVisibility(View.GONE);
}
TextView lFilterCaption = U.getView(res, R.id.lFilterCaption);
if (position < 4) {
lFilterCaption.setVisibility(View.VISIBLE);
lFilterCaption.setText(presetCaptions[position]);
} else {
lFilterCaption.setVisibility(View.GONE);
}
TextView lFilterLabel = U.getView(res, R.id.lFilterLabel);
if (position < 4) {
lFilterLabel.setVisibility(View.GONE);
} else {
Label label = getItem(position);
lFilterLabel.setVisibility(View.VISIBLE);
lFilterLabel.setText(label.judul);
}
return res;
}
private void reload() {
labels = S.getDb().listSemuaLabel();
notifyDataSetChanged();
}
}
} |
package nl.lumc.nanopub.store.dao;
import java.net.URI;
import java.util.List;
import ch.tkuhn.nanopub.Nanopub;
/**
*
* @author Eelke, Mark, Reinout, Rajaram
* @since 30-10-2013
* @version 0.1
*/
public interface NanopubDao {
public URI storeNanopub(Nanopub nanopub);
public Nanopub retrieveNanopub(URI uri);
public List<URI> listNanopubs();
} |
package org.jetbrains.plugins.scala.project;
import com.intellij.lang.Language;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.scala.Scala3Language;
import org.jetbrains.plugins.scala.ScalaLanguage;
import scala.Option;
import scala.math.Ordered;
import java.util.Arrays;
import java.util.regex.Pattern;
public enum ScalaLanguageLevel implements Ordered<ScalaLanguageLevel> {
Scala_2_9("2.9"),
Scala_2_10("2.10"),
Scala_2_11("2.11"),
Scala_2_12("2.12"),
Scala_2_13("2.13"),
Scala_3_0("3.0"),
Scala_3_1("3.1"),
Scala_3_2("3.2"),
//not yet released scala versions
//(added in order Scala SDK is properly created for new major release candidate versions of the scala compiler)
Scala_3_3("3.3"),
Scala_3_4("3.4"),
;
public boolean isScala3() {
return this.compare(Scala_3_0) >= 0;
}
public boolean isScala2() {
return this.compare(Scala_3_0) < 0;
}
public Language getLanguage() {
return isScala3() ? Scala3Language.INSTANCE : ScalaLanguage.INSTANCE;
}
public static final ScalaLanguageLevel latestPublishedVersion = Scala_3_2;
public static final ScalaLanguageLevel[] publishedVersions;
static {
publishedVersions = Arrays.stream(values()).takeWhile(x -> x.ordinal() <= latestPublishedVersion.ordinal()).toArray(ScalaLanguageLevel[]::new);
}
@NotNull
private final String myVersion;
@NotNull
private final String myPattern;
public static final Key<ScalaLanguageLevel> KEY = Key.create("SCALA_LANGUAGE_LEVEL");
ScalaLanguageLevel(@NotNull String version) {
this(version, Pattern.quote(version) + ".*");
}
ScalaLanguageLevel(@NotNull String version, @NotNull String pattern) {
myVersion = version;
myPattern = pattern;
}
@NotNull
public String getVersion() {
return myVersion;
}
@Override
public int compare(@NotNull ScalaLanguageLevel that) {
return super.compareTo(that);
}
@NotNull
public static ScalaLanguageLevel getDefault() {
return Scala_2_12;
}
@NotNull
public static Option<ScalaLanguageLevel> findByVersion(@NotNull String version) {
for (ScalaLanguageLevel languageLevel : values()) {
if (version.matches(languageLevel.myPattern)) {
return Option.apply(languageLevel);
}
}
return Option.empty();
}
} |
package be.billington.rob;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.ConsoleAppender;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import okio.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainSWT {
private Shell shell;
private Text txtOwner, txtRepo, txtApi, txtPrefix, txtBranch, txtConsole, txtFilePath;
private DateTime dateFrom, dateTo;
private Combo profilesCombo;
private Logger logger;
private File configFile, profileFile;
private List<Profile> profiles;
private ExecutorService pool = Executors.newFixedThreadPool(4);
private Map<String, String> config = new HashMap<>();
public MainSWT(Display display) {
LoggerContext context = new LoggerContext();
logger = context.getLogger(MainSWT.class);
shell = new Shell(display);
shell.setText("Rob");
initConfig();
initProfiles();
initUI();
initUIProfiles(false);
initLogger(context);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
private void initUIProfiles(boolean last) {
int pos = 0;
if (last){
pos = profiles.size() - 1;
}
if (profiles != null) {
profilesCombo.removeAll();
profiles.forEach((p) -> profilesCombo.add(p.getTitle()));
profilesCombo.select(pos);
}
bindProfile(pos);
}
private void initLogger(LoggerContext context) {
ConsoleAppender consoleAppender = new ConsoleAppender<>();
UIAppender uiAppender = new UIAppender(txtConsole);
PatternLayoutEncoder pa = new PatternLayoutEncoder();
pa.setPattern("%r %5p %c [%t] - %m%n");
pa.setContext(context);
pa.start();
uiAppender.setEncoder(pa);
uiAppender.setContext(context);
uiAppender.start();
consoleAppender.setEncoder(pa);
consoleAppender.setContext(context);
consoleAppender.start();
logger.addAppender(uiAppender);
//logger.addAppender(consoleAppender);
}
private void initConfig() {
configFile = new File("./rob.conf");
try {
if (!readConfig()) {
createConfig();
}
} catch (IOException e) {
logger.error("IOException: " + e.getMessage(), e);
}
}
private void initProfiles() {
profileFile = new File("./rob.profiles");
try {
Gson gson = new Gson();
Source source = Okio.source(profileFile);
BufferedSource profileGsonSource = Okio.buffer(source);
Type listType = new TypeToken<ArrayList<Profile>>() {}.getType();
profiles = gson.fromJson(profileGsonSource.readUtf8(), listType);
profileGsonSource.close();
source.close();
} catch (IOException e) {
logger.error("IOException: " + e.getMessage(), e);
}
}
private void writeConfig() throws IOException {
Sink sink = Okio.sink(configFile);
BufferedSink bufferedSink = Okio.buffer(sink);
this.config.forEach((k, v) -> {
try {
bufferedSink.writeUtf8(k + "=" + v + "\n");
} catch (IOException e) {
logger.error("IOException: " + e.getMessage(), e);
}
});
bufferedSink.close();
sink.close();
}
private boolean readConfig() throws IOException {
if (!configFile.exists()) {
return false;
}
boolean simpleCheckatLeastOneLine = false;
Source source = Okio.source(configFile);
BufferedSource bufferedSource = Okio.buffer(source);
String line = bufferedSource.readUtf8Line();
while (line != null) {
if (line.contains("=")) {
String[] values = line.split("=");
if (values.length > 1) {
this.config.put(values[0], values[1]);
}
}
line = bufferedSource.readUtf8Line();
simpleCheckatLeastOneLine = true;
}
bufferedSource.close();
source.close();
return simpleCheckatLeastOneLine;
}
private void createConfig() {
ConfigDialog configDialog = new ConfigDialog(shell, config);
config = configDialog.open();
try {
writeConfig();
} catch (IOException e) {
logger.error("IOException: " + e.getMessage(), e);
}
}
public void initUI() {
shell.setLayout(new FillLayout());
Composite inputContainer = new Composite(shell, SWT.BORDER);
inputContainer.setLayout(new RowLayout(SWT.VERTICAL));
ToolBar bar = new ToolBar (inputContainer, SWT.FLAT | SWT.BORDER);
initToolBar(bar);
profilesCombo = new Combo(inputContainer, SWT.PUSH);
profilesCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
super.widgetSelected(e);
bindProfile(profilesCombo.getSelectionIndex());
}
});
//1st column
Composite container = new Composite(inputContainer, SWT.PUSH);
GridLayout layout = new GridLayout(2, false);
layout.marginWidth = 10;
container.setLayout(layout);
Label lblRepo = new Label(container, SWT.NONE);
lblRepo.setText("Repository name:");
txtRepo = new Text(container, SWT.BORDER);
txtRepo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblOwner = new Label(container, SWT.NONE);
GridData gd_lblNewLabel = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_lblNewLabel.horizontalIndent = 1;
lblOwner.setLayoutData(gd_lblNewLabel);
lblOwner.setText("Owner:");
txtOwner = new Text(container, SWT.BORDER);
txtOwner.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblApi = new Label(container, SWT.NONE);
lblApi.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
lblApi.setText("API:");
txtApi = new Text(container, SWT.BORDER);
txtApi.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblPrefix = new Label(container, SWT.NONE);
lblPrefix.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
lblPrefix.setText("Jira Prefix:");
txtPrefix = new Text(container, SWT.BORDER);
txtPrefix.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblBranch = new Label(container, SWT.NONE);
lblBranch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
lblBranch.setText("Branch:");
txtBranch = new Text(container, SWT.BORDER);
txtBranch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblFilePath = new Label(container, SWT.NONE);
lblFilePath.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
lblFilePath.setText("File Path:");
txtFilePath = new Text(container, SWT.BORDER);
txtFilePath.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblFromDate = new Label(container, SWT.NONE);
lblFromDate.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
lblFromDate.setText("From date:");
dateFrom = new DateTime(container, SWT.BORDER | SWT.DATE | SWT.DROP_DOWN);
Label lblToDate = new Label(container, SWT.NONE);
lblToDate.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
lblToDate.setText("To date:");
dateTo = new DateTime(container, SWT.BORDER | SWT.DATE | SWT.DROP_DOWN);
//2nd column
Composite rightContainer = new Composite(shell, SWT.BORDER);
rightContainer.setLayout(new FillLayout());
txtConsole = new Text(rightContainer, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI);
txtConsole.setEditable(false);
}
private void initToolBar(ToolBar bar) {
ToolItem generate = new ToolItem(bar, SWT.PUSH);
generate.setText("Generate");
generate.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
robIt();
}
});
new ToolItem(bar, SWT.SEPARATOR);
ToolItem output = new ToolItem(bar, SWT.PUSH);
output.setText("Display output");
output.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
loadGeneratedFile();
}
});
new ToolItem(bar, SWT.SEPARATOR);
ToolItem settings = new ToolItem(bar, SWT.PUSH);
settings.setText("Settings");
settings.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
createConfig();
}
});
new ToolItem(bar, SWT.SEPARATOR);
ToolItem saveProfile = new ToolItem(bar, SWT.PUSH);
saveProfile.setText("Save/Add profile");
saveProfile.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
saveProfile();
}
});
new ToolItem(bar, SWT.SEPARATOR);
ToolItem removeProfile = new ToolItem(bar, SWT.PUSH);
removeProfile.setText("Remove current profile");
removeProfile.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
removeCurrentProfile();
}
});
new ToolItem(bar, SWT.SEPARATOR);
ToolItem quit = new ToolItem(bar, SWT.PUSH);
quit.setText("Quit");
quit.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
shell.getDisplay().dispose();
System.exit(0);
}
});
}
private void bindProfile(int pos) {
if (profiles == null || profiles.isEmpty()) {
txtApi.setText("bitbucket");
txtOwner.setText("afrogleap");
txtRepo.setText("wecycle-android-recyclemanager");
txtPrefix.setText("WEC");
txtBranch.setText("development");
txtFilePath.setText("./target/changelog.txt");
} else {
Profile profile = profiles.get(pos);
txtApi.setText(profile.getApi());
txtOwner.setText(profile.getOwner());
txtRepo.setText(profile.getRepo());
txtPrefix.setText(profile.getPrefix());
txtBranch.setText(profile.getBranch());
txtFilePath.setText(profile.getFilePath());
if (profile.getFromDate() != null && !profile.getFromDate().isEmpty()) {
LocalDate date = LocalDate.parse(profile.getFromDate());
dateFrom.setDate(date.getYear(), date.getMonthValue() - 1, date.getDayOfMonth());
}
if (profile.getToDate() != null && !profile.getToDate().isEmpty()) {
LocalDate date = LocalDate.parse(profile.getToDate());
dateTo.setDate(date.getYear(), date.getMonthValue() - 1, date.getDayOfMonth());
}
}
}
private void removeCurrentProfile(){
profiles.remove(profilesCombo.getSelectionIndex());
initUIProfiles(true);
}
private String convertDateToStr(DateTime dateTime){
LocalDate date = LocalDate.of(dateTime.getYear(), dateTime.getMonth() + 1, dateTime.getDay());
return date.toString();
}
private void saveProfile() {
String dateFromStr = convertDateToStr(dateFrom);
String dateToStr = convertDateToStr(dateTo);
if (dateFromStr.equals(dateToStr)){
dateFromStr = "";
}
Profile profile = new Profile(txtApi.getText(), txtOwner.getText(), txtRepo.getText(),
txtPrefix.getText(), txtBranch.getText(), "", txtFilePath.getText(),
dateFromStr, dateToStr);
if (profiles == null){
profiles = new ArrayList<>();
}
profiles.add(profile);
initUIProfiles(true);
try {
Sink sink = Okio.sink(profileFile);
BufferedSink bufferedSink = Okio.buffer(sink);
Gson gson = new Gson();
bufferedSink.writeUtf8(gson.toJson(profiles));
bufferedSink.close();
sink.close();
} catch (IOException e) {
logger.error("IOException: " + e.getMessage(), e);
}
}
private void robIt() {
String dateFromStr = convertDateToStr(dateFrom);
String dateToStr = convertDateToStr(dateTo);
if (dateFromStr.equals(dateToStr)){
dateFromStr = "";
}
pool.execute( new RobRunnable(logger, txtApi.getText(), txtOwner.getText(), txtRepo.getText(),
txtPrefix.getText(), txtBranch.getText(), txtFilePath.getText(),
dateFromStr, dateToStr, config) );
}
private void loadGeneratedFile() {
try {
Source source = Okio.source(new File(txtFilePath.getText()));
BufferedSource bufferedSource = Okio.buffer(source);
String content = bufferedSource.readUtf8();
txtConsole.setText(content);
bufferedSource.close();
source.close();
} catch (IOException e) {
logger.error("IOException: " + e.getMessage(), e);
}
}
public void center(Shell shell) {
Rectangle bds = shell.getDisplay().getBounds();
Point p = shell.getSize();
int nLeft = (bds.width - p.x) / 2;
int nTop = (bds.height - p.y) / 2;
shell.setBounds(nLeft, nTop, p.x, p.y);
}
public static void main(String[] args) {
Display display = new Display();
new MainSWT(display);
display.dispose();
}
} |
package SW9.controllers;
import SW9.HUPPAAL;
import SW9.abstractions.*;
import SW9.backend.UPPAALDriver;
import SW9.code_analysis.CodeAnalysis;
import SW9.presentations.*;
import SW9.utility.UndoRedoStack;
import SW9.utility.colors.Color;
import SW9.utility.helpers.BindingHelper;
import SW9.utility.helpers.Circular;
import SW9.utility.helpers.ItemDragHelper;
import SW9.utility.helpers.SelectHelper;
import SW9.utility.keyboard.Keybind;
import SW9.utility.keyboard.KeyboardTracker;
import SW9.utility.mouse.MouseTracker;
import com.jfoenix.controls.JFXPopup;
import com.jfoenix.controls.JFXRippler;
import com.jfoenix.controls.JFXTextField;
import javafx.animation.Interpolator;
import javafx.animation.Transition;
import javafx.application.Platform;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.ListChangeListener;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;
import org.fxmisc.richtext.LineNumberFactory;
import org.fxmisc.richtext.StyleClassedTextArea;
import java.net.URL;
import java.util.*;
import java.util.function.Consumer;
import static SW9.presentations.CanvasPresentation.GRID_SIZE;
public class ComponentController implements Initializable, SelectHelper.ColorSelectable {
private static final Map<Component, Timer> COMPONENT_SUBCOMPONENT_NAME_CHECK_TIMER_MAP = new HashMap<>();
private static final Map<Component, ListChangeListener<Location>> locationListChangeListenerMap = new HashMap<>();
private static Location placingLocation = null;
private final ObjectProperty<Component> component = new SimpleObjectProperty<>(null);
private final Map<Edge, EdgePresentation> edgePresentationMap = new HashMap<>();
private final Map<Location, LocationPresentation> locationPresentationMap = new HashMap<>();
private final Map<SubComponent, SubComponentPresentation> subComponentPresentationMap = new HashMap<>();
private final Map<Jork, JorkPresentation> jorkPresentationMap = new HashMap<>();
public BorderPane toolbar;
public Rectangle background;
public StyleClassedTextArea declaration;
public JFXRippler toggleDeclarationButton;
public BorderPane frame;
public JFXTextField name;
public StackPane root;
public Line line1;
public Line line2;
public Label x;
public Label y;
public Pane defaultLocationsContainer;
public Rectangle rightAnchor;
public Rectangle bottomAnchor;
public Pane modelContainerSubComponent;
public Pane modelContainerLocation;
public Pane modelContainerEdge;
public Pane modelContainerJork;
private MouseTracker mouseTracker;
private DropDownMenu dropDownMenu;
private Circle dropDownMenuHelperCircle;
public static boolean isPlacingLocation() {
return placingLocation != null;
}
public static void setPlacingLocation(final Location placingLocation) {
ComponentController.placingLocation = placingLocation;
}
@Override
public void initialize(final URL location, final ResourceBundle resources) {
declaration.setParagraphGraphicFactory(LineNumberFactory.get(declaration));
// Register a keybind for adding new locations
KeyboardTracker.registerKeybind(KeyboardTracker.ADD_NEW_LOCATION, new Keybind(new KeyCodeCombination(KeyCode.L), () -> {
if (isPlacingLocation()) return;
final Location newLocation = new Location();
setPlacingLocation(newLocation);
UndoRedoStack.push(() -> { // Perform
component.get().addLocation(newLocation);
}, () -> { // Undo
component.get().removeLocation(newLocation);
}, "Added new location: " + newLocation.getNickname(), "add-circle");
CanvasController.activeComponentProperty().addListener((observable, oldValue, newValue) -> {
if(!newValue.equals(getComponent())) {
if (isPlacingLocation()) {
component.get().removeLocation(placingLocation);
ComponentController.setPlacingLocation(null);
UndoRedoStack.forget();
}
}
});
newLocation.setColorIntensity(getComponent().getColorIntensity());
newLocation.setColor(getComponent().getColor());
KeyboardTracker.registerKeybind(KeyboardTracker.ABANDON_LOCATION, new Keybind(new KeyCodeCombination(KeyCode.ESCAPE), () -> {
if (isPlacingLocation()) {
component.get().removeLocation(placingLocation);
ComponentController.setPlacingLocation(null);
UndoRedoStack.forget();
}
}));
}));
component.addListener((obs, oldComponent, newComponent) -> {
// Bind the width and the height of the abstraction to the values in the view todo: reflect the height and width from the presentation into the abstraction
// Bind the position of the abstraction to the values in the view
// Ensure that the component snaps to the grid
if(newComponent.getX() == 0 && newComponent.getY() == 0) {
newComponent.setX(GRID_SIZE * 0.5);
newComponent.setY(GRID_SIZE * 0.5);
}
root.layoutXProperty().set(newComponent.getX());
root.layoutYProperty().set(newComponent.getY());
newComponent.xProperty().bindBidirectional(root.layoutXProperty());
newComponent.yProperty().bindBidirectional(root.layoutYProperty());
// Bind the declarations of the abstraction the the view
declaration.replaceText(0, declaration.getLength(), newComponent.getDeclarations());
declaration.textProperty().addListener((observable, oldDeclaration, newDeclaration) -> newComponent.setDeclarations(newDeclaration));
final boolean[] first = {true};
newComponent.declarationsProperty().addListener((observable, oldValue, newValue) -> {
if (!first[0]) return;
first[0] = false;
declaration.replaceText(0, declaration.getLength(), newValue);
});
initializeEdgeHandling(newComponent);
initializeLocationHandling(newComponent);
initializeSubComponentHandling(newComponent);
initializeJorkHandling(newComponent);
// When we update the color of the component, also update the color of the initial and final locations if the colors are the same
newComponent.colorProperty().addListener((obs1, oldColor, newColor) -> {
final Location initialLocation = newComponent.getInitialLocation();
if (initialLocation.getColor().equals(oldColor)) {
initialLocation.setColorIntensity(newComponent.getColorIntensity());
initialLocation.setColor(newColor);
}
final Location finalLocation = newComponent.getFinalLocation();
if (finalLocation.getColor().equals(oldColor)) {
finalLocation.setColorIntensity(newComponent.getColorIntensity());
finalLocation.setColor(newColor);
}
});
});
// The root view have been inflated, initialize the mouse tracker on it
mouseTracker = new MouseTracker(root);
initializeDropDownMenu();
initializeSubComponentUniqueNameError();
}
private void initializeJorkHandling(final Component newComponent) {
final Consumer<Jork> handleAddedJork = newJork -> {
final JorkPresentation jorkPresentation = new JorkPresentation(newJork, newComponent);
jorkPresentationMap.put(newJork, jorkPresentation);
modelContainerJork.getChildren().add(jorkPresentation);
};
// React on addition of jorks to the component
newComponent.getJorks().addListener(new ListChangeListener<Jork>() {
@Override
public void onChanged(final Change<? extends Jork> c) {
if (c.next()) {
// Edges are added to the component
c.getAddedSubList().forEach(handleAddedJork::accept);
// Edges are removed from the component
c.getRemoved().forEach(edge -> {
final JorkPresentation jorkPresentation = jorkPresentationMap.get(edge);
modelContainerJork.getChildren().remove(jorkPresentation);
jorkPresentationMap.remove(edge);
});
}
}
});
newComponent.getJorks().forEach(handleAddedJork);
}
private void initializeSubComponentUniqueNameError() {
final HashMap<String, ArrayList<CodeAnalysis.Message>> errorsMap = new HashMap<>();
final Runnable checkNames = () -> {
final HashMap<String, Integer> occurrences = new HashMap<>();
subComponentPresentationMap.keySet().forEach(subComponent -> {
// Check if we have seen the identifier of the sub component before
final String identifier = subComponent.getIdentifier();
if (occurrences.containsKey(identifier)) {
occurrences.put(identifier, occurrences.get(identifier) + 1);
} else {
occurrences.put(identifier, 0);
}
});
// Check if we have previously added an error for each of the found duplicates
occurrences.keySet().forEach(id -> {
if (!errorsMap.containsKey(id)) {
errorsMap.put(id, new ArrayList<>());
}
final ArrayList<CodeAnalysis.Message> messages = errorsMap.get(id);
final int addedErrors = messages.size();
final int foundErrors = occurrences.get(id);
if (addedErrors > foundErrors) { // There are too many errors in the view
final CodeAnalysis.Message messageToRemove = messages.get(0);
messages.remove(messageToRemove);
Platform.runLater(() -> CodeAnalysis.removeMessage(getComponent(), messageToRemove));
} else if (addedErrors < foundErrors) { // There are too few errors in the view
final CodeAnalysis.Message identifierIsNotUnique = new CodeAnalysis.Message("Identifier '" + id + "' is multiply defined", CodeAnalysis.MessageType.ERROR);
messages.add(identifierIsNotUnique);
Platform.runLater(() -> CodeAnalysis.addMessage(getComponent(), identifierIsNotUnique));
}
});
// Remove any messages that are no longer found
errorsMap.keySet().forEach(id -> {
if (!occurrences.containsKey(id)) {
errorsMap.get(id).forEach(message -> Platform.runLater(() -> CodeAnalysis.removeMessage(getComponent(), message)));
errorsMap.put(id, new ArrayList<>());
}
});
};
// Wait until component is not null
component.addListener((obs, oldComponent, newComponent) -> {
if (!COMPONENT_SUBCOMPONENT_NAME_CHECK_TIMER_MAP.containsKey(newComponent)) {
TimerTask reachabilityCheckTask = new TimerTask() {
@Override
public void run() {
if (getComponent() == null) return;
checkNames.run();
}
};
final int interval = 2000;
final Timer timer = new Timer();
timer.schedule(reachabilityCheckTask, 0, interval);
COMPONENT_SUBCOMPONENT_NAME_CHECK_TIMER_MAP.put(getComponent(), timer);
}
});
// Cancel timers when the component is removed
HUPPAAL.getProject().getComponents().addListener(new ListChangeListener<Component>() {
@Override
public void onChanged(Change<? extends Component> c) {
while (c.next()) {
c.getRemoved().forEach(removedComponent -> {
if (COMPONENT_SUBCOMPONENT_NAME_CHECK_TIMER_MAP.containsKey(removedComponent)) {
COMPONENT_SUBCOMPONENT_NAME_CHECK_TIMER_MAP.get(removedComponent).cancel();
}
});
}
}
});
}
private void initializeDropDownMenu() {
dropDownMenuHelperCircle = new Circle(5);
dropDownMenuHelperCircle.setOpacity(0);
dropDownMenuHelperCircle.setMouseTransparent(true);
root.getChildren().add(dropDownMenuHelperCircle);
final Consumer<Component> initializeDropDownMenu = (component) -> {
if (component == null) {
return;
}
dropDownMenu = new DropDownMenu(root, dropDownMenuHelperCircle, 230, true);
dropDownMenu.addClickableListElement("Add Location", event -> {
dropDownMenu.close();
final Location newLocation = new Location();
double x = DropDownMenu.x - LocationPresentation.RADIUS / 2;
x = Math.round(x / GRID_SIZE) * GRID_SIZE;
newLocation.setX(x);
double y = DropDownMenu.y - LocationPresentation.RADIUS / 2;
y = Math.round(y / GRID_SIZE) * GRID_SIZE;
newLocation.setY(y);
newLocation.setColorIntensity(component.getColorIntensity());
newLocation.setColor(component.getColor());
// Add a new location
UndoRedoStack.push(() -> { // Perform
component.addLocation(newLocation);
}, () -> { // Undo
component.removeLocation(newLocation);
}, "Added location '" + newLocation.toString() + "' to component '" + component.getName() + "'", "add-circle");
});
dropDownMenu.addClickableListElement("Add Fork", event -> {
dropDownMenu.close();
final Jork newJork = new Jork(Jork.Type.FORK);
double x = DropDownMenu.x - LocationPresentation.RADIUS / 2;
x = Math.round(x / GRID_SIZE) * GRID_SIZE;
newJork.setX(x);
double y = DropDownMenu.y - LocationPresentation.RADIUS / 2;
y = Math.round(y / GRID_SIZE) * GRID_SIZE;
newJork.setY(y);
// Add a new location
UndoRedoStack.push(() -> { // Perform
component.addJork(newJork);
}, () -> { // Undo
component.removeJork(newJork);
}, "Added fork '" + newJork.toString() + "' to component '" + component.getName() + "'", "add-circle");
});
dropDownMenu.addClickableListElement("Add Join", event -> {
dropDownMenu.close();
final Jork newJork = new Jork(Jork.Type.JOIN);
double x = DropDownMenu.x - LocationPresentation.RADIUS / 2;
x = Math.round(x / GRID_SIZE) * GRID_SIZE;
newJork.setX(x);
double y = DropDownMenu.y - LocationPresentation.RADIUS / 2;
y = Math.round(y / GRID_SIZE) * GRID_SIZE;
newJork.setY(y);
// Add a new location
UndoRedoStack.push(() -> { // Perform
component.addJork(newJork);
}, () -> { // Undo
component.removeJork(newJork);
}, "Added join '" + newJork.toString() + "' to component '" + component.getName() + "'", "add-circle");
});
final DropDownMenu subMenu = new DropDownMenu(root, dropDownMenuHelperCircle, 150, false);
HUPPAAL.getProject().getComponents().forEach(c -> {
if (!c.equals(component)) {
subMenu.addClickableListElement(c.getName(), event -> {
dropDownMenu.close();
final SubComponent newSubComponent = new SubComponent(c);
double x = DropDownMenu.x - newSubComponent.getWidth() / 2;
x -= x % GRID_SIZE;
newSubComponent.setX(x);
double y = DropDownMenu.y - newSubComponent.getHeight() / 4;
y -= y % GRID_SIZE;
newSubComponent.setY(y);
// Add a new sub-component
UndoRedoStack.push(() -> { // Perform
component.addSubComponent(newSubComponent);
}, () -> { // Undo
component.removeSubComponent(newSubComponent);
}, "Added sub-component '" + newSubComponent.toString() + "' to component '" + component.getName() + "'", "add-circle");
});
}
});
dropDownMenu.addSubMenu("Add Subcomponent", subMenu, 3 * 35);
dropDownMenu.addSpacerElement();
dropDownMenu.addClickableListElement("Contains deadlock?", event -> {
dropDownMenu.close();
// Generate the query
final String deadlockQuery = UPPAALDriver.getExistDeadlockQuery(getComponent());
// Add proper comment
final String deadlockComment = "Does " + component.getName() + " contain a deadlock?";
// Add new query for this component
HUPPAAL.getProject().getQueries().add(new Query(deadlockQuery, deadlockComment, QueryState.UNKNOWN));
dropDownMenu.close();
});
dropDownMenu.addSpacerElement();
dropDownMenu.addListElement("Color");
dropDownMenu.addColorPicker(component, component::color);
};
component.addListener((obs, oldComponent, newComponent) -> {
initializeDropDownMenu.accept(newComponent);
});
HUPPAAL.getProject().getComponents().addListener(new ListChangeListener<Component>() {
@Override
public void onChanged(final Change<? extends Component> c) {
initializeDropDownMenu.accept(getComponent());
}
});
initializeDropDownMenu.accept(getComponent());
}
private void initializeLocationHandling(final Component newComponent) {
final Consumer<Location> handleAddedLocation = (loc) -> {
// Create a new presentation, and register it on the map
final LocationPresentation newLocationPresentation = new LocationPresentation(loc, newComponent);
locationPresentationMap.put(loc, newLocationPresentation);
// Add it to the view
modelContainerLocation.getChildren().add(newLocationPresentation);
// Bind the newly created location to the mouse and tell the ui that it is not placed yet
if (loc.getX() == 0) {
newLocationPresentation.setPlaced(false);
BindingHelper.bind(loc, newComponent.xProperty(), newComponent.yProperty());
}
};
if(locationListChangeListenerMap.containsKey(newComponent)) {
newComponent.getLocations().removeListener(locationListChangeListenerMap.get(newComponent));
}
final ListChangeListener<Location> locationListChangeListener = c -> {
if (c.next()) {
// Locations are added to the component
c.getAddedSubList().forEach(handleAddedLocation::accept);
// Locations are removed from the component
c.getRemoved().forEach(location -> {
final LocationPresentation locationPresentation = locationPresentationMap.get(location);
modelContainerLocation.getChildren().remove(locationPresentation);
locationPresentationMap.remove(location);
});
}
};
newComponent.getLocations().addListener(locationListChangeListener);
locationListChangeListenerMap.put(newComponent, locationListChangeListener);
newComponent.getLocations().forEach(handleAddedLocation);
}
private void initializeEdgeHandling(final Component newComponent) {
final Consumer<Edge> handleAddedEdge = edge -> {
final EdgePresentation edgePresentation = new EdgePresentation(edge, newComponent);
edgePresentationMap.put(edge, edgePresentation);
modelContainerEdge.getChildren().add(edgePresentation);
final Consumer<Circular> updateMouseTransparency = (newCircular) -> {
if (newCircular == null) {
edgePresentation.setMouseTransparent(true);
} else {
edgePresentation.setMouseTransparent(false);
}
};
edge.targetCircularProperty().addListener((obs1, oldTarget, newTarget) -> updateMouseTransparency.accept(newTarget));
updateMouseTransparency.accept(edge.getTargetCircular());
};
// React on addition of edges to the component
newComponent.getEdges().addListener(new ListChangeListener<Edge>() {
@Override
public void onChanged(final Change<? extends Edge> c) {
if (c.next()) {
// Edges are added to the component
c.getAddedSubList().forEach(handleAddedEdge::accept);
// Edges are removed from the component
c.getRemoved().forEach(edge -> {
final EdgePresentation edgePresentation = edgePresentationMap.get(edge);
modelContainerEdge.getChildren().remove(edgePresentation);
edgePresentationMap.remove(edge);
});
}
}
});
newComponent.getEdges().forEach(handleAddedEdge);
}
private void initializeSubComponentHandling(final Component newSubComponent) {
final Consumer<SubComponent> handleAddedSubComponent = subComponent -> {
final SubComponentPresentation subComponentPresentation = new SubComponentPresentation(subComponent, getComponent());
subComponentPresentationMap.put(subComponent, subComponentPresentation);
modelContainerSubComponent.getChildren().add(subComponentPresentation);
};
// React on addition of sub components to the component
newSubComponent.getSubComponents().addListener(new ListChangeListener<SubComponent>() {
@Override
public void onChanged(final Change<? extends SubComponent> c) {
if (c.next()) {
// SubComponents are added to the component
c.getAddedSubList().forEach(handleAddedSubComponent::accept);
// SubComponents are removed from the component
c.getRemoved().forEach(subComponent -> {
final SubComponentPresentation subComponentPresentation = subComponentPresentationMap.get(subComponent);
modelContainerSubComponent.getChildren().remove(subComponentPresentation);
});
}
}
});
newSubComponent.getSubComponents().forEach(handleAddedSubComponent);
makeDraggable();
}
public void toggleDeclaration(final MouseEvent mouseEvent) {
declaration.setVisible(true);
final Circle circle = new Circle(0);
circle.setCenterX(component.get().getWidth() - (toggleDeclarationButton.getWidth() - mouseEvent.getX()));
circle.setCenterY(-1 * mouseEvent.getY());
final ObjectProperty<Node> clip = new SimpleObjectProperty<>(circle);
declaration.clipProperty().bind(clip);
final Transition rippleEffect = new Transition() {
private final double maxRadius = Math.sqrt(Math.pow(getComponent().getWidth(), 2) + Math.pow(getComponent().getHeight(), 2));
{
setCycleDuration(Duration.millis(500));
}
protected void interpolate(final double fraction) {
if (getComponent().isDeclarationOpen()) {
circle.setRadius(fraction * maxRadius);
} else {
circle.setRadius(maxRadius - fraction * maxRadius);
}
clip.set(circle);
}
};
final Interpolator interpolator = Interpolator.SPLINE(0.785, 0.135, 0.15, 0.86);
rippleEffect.setInterpolator(interpolator);
rippleEffect.play();
getComponent().declarationOpenProperty().set(!getComponent().isDeclarationOpen());
}
public Component getComponent() {
return component.get();
}
public void setComponent(final Component component) {
this.component.set(component);
}
public ObjectProperty<Component> componentProperty() {
return component;
}
@FXML
private void modelContainerPressed(final MouseEvent event) {
event.consume();
final Edge unfinishedEdge = getComponent().getUnfinishedEdge();
if (event.isSecondaryButtonDown() && unfinishedEdge == null) {
dropDownMenuHelperCircle.setLayoutX(event.getX());
dropDownMenuHelperCircle.setLayoutY(event.getY());
DropDownMenu.x = event.getX();
DropDownMenu.y = event.getY();
dropDownMenu.show(JFXPopup.PopupVPosition.TOP, JFXPopup.PopupHPosition.LEFT, 0, 0);
} else {
// We are drawing an edge
if (unfinishedEdge != null) {
// Calculate the position for the new nail (based on the component position and the canvas mouse tracker)
final DoubleBinding x = CanvasPresentation.mouseTracker.gridXProperty().subtract(getComponent().xProperty());
final DoubleBinding y = CanvasPresentation.mouseTracker.gridYProperty().subtract(getComponent().yProperty());
// Create the abstraction for the new nail and add it to the unfinished edge
final Nail newNail = new Nail(x, y);
unfinishedEdge.addNail(newNail);
}
}
}
public MouseTracker getMouseTracker() {
return mouseTracker;
}
@Override
public void color(final Color color, final Color.Intensity intensity) {
final Component component = getComponent();
final Color componentColor = component.getColor();
final Consumer<Location> locationPainter = location -> {
if (!location.getColor().equals(componentColor)) return; // Do not color something of a different color
location.setColorIntensity(intensity);
location.setColor(color);
};
// Set the color for all locations that are of the same color
component.getLocations().forEach(locationPainter);
locationPainter.accept(component.getInitialLocation());
locationPainter.accept(component.getFinalLocation());
// Set the color of the component
component.setColorIntensity(intensity);
component.setColor(color);
}
@Override
public Color getColor() {
return getComponent().getColor();
}
@Override
public Color.Intensity getColorIntensity() {
return getComponent().getColorIntensity();
}
@Override
public void select() {
((SelectHelper.Selectable) root).select();
final Consumer<Node> selectLocations = node -> {
if (node instanceof LocationPresentation) {
SelectHelper.addToSelection(((LocationPresentation) node).getController());
}
};
modelContainerLocation.getChildren().forEach(selectLocations);
defaultLocationsContainer.getChildren().forEach(selectLocations);
}
@Override
public void deselect() {
((SelectHelper.Selectable) root).deselect();
}
private void makeDraggable() {
ItemDragHelper.makeDraggable(
root,
toolbar,
() -> CanvasPresentation.mouseTracker.getGridX(),
() -> CanvasPresentation.mouseTracker.getGridY(),
(event) -> {
event.consume();
SelectHelper.select(this);
},
() -> {},
() -> {}
);
}
} |
package au.com.tyo.common.ui;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.FrameLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
public class CommonListView extends RelativeLayout implements OnScrollListener {
protected ListView list;
private int lastVisible;
private onLastItemVisibleListener lastItemVisibleListener;
public CommonListView(Context context) {
super(context);
init(context);
}
public CommonListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
@SuppressLint("NewApi")
public CommonListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
// createListView();
lastItemVisibleListener = null;
}
public static interface onLastItemVisibleListener {
public void onLastItemVisible();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
}
public void setOnLastItemVisibleListener(onLastItemVisibleListener listener) {
this.lastItemVisibleListener = listener;
}
public ListAdapter getAdapter() {
return list.getAdapter();
}
public void setAdapter(ListAdapter adapter) {
list.invalidateViews();
list.setAdapter(adapter);
}
public void createListView() {
list = createListView(this.getContext(), this);
list.requestFocus();
list.setOnScrollListener(this);
}
public boolean lookForListView(int resId) {
list = (ListView) findViewById(resId);
if (null != list)
list.setOnScrollListener(this);
return list != null;
}
public static ListView createListView(Context context, ViewGroup parent) {
LayoutInflater factory = LayoutInflater.from(context);
ListView list = (ListView) factory.inflate(R.layout.common_list_view, null);
if (null != parent)
parent.addView(list);
// list = (ListView) findViewById(R.id.common_list_view);
// list = new ListView(context);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// params.gravity = Gravity.CENTER_HORIZONTAL;
list.setLayoutParams(params);
// list.setOnTouchListener(new View.OnTouchListener() {
// public boolean onTouch(View v, MotionEvent event) {
// return (event.getAction() == MotionEvent.ACTION_MOVE);
return list;
}
// @Override
// protected void onFinishInflate() {
// super.onFinishInflate();
//// list = (ListView) findViewById(R.id.common_list_view);
//// this.addContentView(list);
public static boolean doesItemsFitInScreen(ListView list) {
if (list.getChildCount() == 0)
return true;
int last = list.getLastVisiblePosition();
return isLastItemVisible(list.getCount(), last) && isLastItemVisible(list);
}
public static boolean isLastItemVisible(ListView list) {
return list.getChildAt(list.getLastVisiblePosition()).getBottom() <= list.getHeight();
}
public static boolean isLastItemVisible(int numberOfItems, int lastVisible) {
return (lastVisible == numberOfItems - 1);
}
public boolean doesItemsFitInScreen() {
lastVisible = list.getLastVisiblePosition();
return isLastItemVisible(list.getCount(), lastVisible) && isLastItemVisible(list);
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView lv, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
switch(lv.getId()) {
case android.R.id.list:
lastVisible = list.getLastVisiblePosition();
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {
if (null != lastItemVisibleListener)
lastItemVisibleListener.onLastItemVisible();
}
break;
}
}
public void removeDivider() {
list.setDivider(null);
list.setDividerHeight(0);
}
public void refresh() {
list.invalidateViews();
list.refreshDrawableState();
}
public ListView getListView() {
return list;
}
public void setSingleChoiceModeOn() {
if (null != list)
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
// @Override
// public boolean onTouchEvent(MotionEvent ev) {
// for(int i = 0; i < this.getChildCount(); i++){
// this.getChildAt(i).dispatchTouchEvent(ev);
// return true;
} |
package org.commcare.modern.database;
import org.commcare.modern.models.EncryptedModel;
import org.commcare.modern.util.Pair;
import org.javarosa.core.services.storage.IMetaData;
import org.javarosa.core.services.storage.Persistable;
import org.javarosa.core.util.externalizable.Externalizable;
import java.util.*;
/**
* Setup of platform-agnostic DB helper functions IE for generating SQL
* statements, args, content values, etc.
*
* @author wspride
*/
public class DatabaseHelper {
public static final String ID_COL = "commcare_sql_id";
public static final String DATA_COL = "commcare_sql_record";
public static final String FILE_COL = "commcare_sql_file";
public static final String AES_COL = "commcare_sql_aes";
public static Pair<String, String[]> createWhere(String[] fieldNames, Object[] values, Persistable p) throws IllegalArgumentException {
return createWhere(fieldNames, values, null, p);
}
public static Pair<String, String[]> createWhere(String[] fieldNames, Object[] values, EncryptedModel em, Persistable p) throws IllegalArgumentException {
Set<String> fields = null;
if(p instanceof IMetaData) {
IMetaData m = (IMetaData)p;
String[] thefields = m.getMetaDataFields();
fields = new HashSet<>();
for(String s : thefields) {
fields.add(TableBuilder.scrubName(s));
}
}
if(em instanceof IMetaData) {
IMetaData m = (IMetaData)em;
String[] thefields = m.getMetaDataFields();
fields = new HashSet<>();
for(String s : thefields) {
fields.add(TableBuilder.scrubName(s));
}
}
StringBuilder stringBuilder = new StringBuilder();
ArrayList<String> arguments = new ArrayList<>();
boolean set = false;
for(int i = 0 ; i < fieldNames.length; ++i) {
String columnName = TableBuilder.scrubName(fieldNames[i]);
if(fields != null) {
if(!fields.contains(columnName)) {
continue;
}
}
if(set){
stringBuilder.append(" AND ");
}
stringBuilder.append(columnName);
stringBuilder.append("=?");
arguments.add(values[i].toString());
set = true;
}
// we couldn't match any of the fields to our columns
if(!set){
throw new IllegalArgumentException("Unable to match provided fields with columns.");
}
String[] retArray = new String[arguments.size()];
arguments.toArray(retArray);
return new Pair<>(stringBuilder.toString(), retArray);
}
public static HashMap<String, Object> getMetaFieldsAndValues(Externalizable e) {
HashMap<String, Object> values = getNonDataMetaEntries(e);
addDataToValues(values, e);
return values;
}
private static void addDataToValues(HashMap<String, Object> values,
Externalizable e) {
byte[] blob = TableBuilder.toBlob(e);
if (blob.length > 1000000) {
throw new RecordTooLargeException(blob.length / 1000000);
}
values.put(DATA_COL, blob);
}
public static HashMap<String, Object> getNonDataMetaEntries(Externalizable e) {
HashMap<String, Object> values = new HashMap<>();
if (e instanceof IMetaData) {
IMetaData m = (IMetaData)e;
for (String key : m.getMetaDataFields()) {
Object o = m.getMetaData(key);
if (o == null) {
continue;
}
String scrubbedKey = TableBuilder.scrubName(key);
if (o instanceof Date) {
// store date as seconds since epoch
values.put(scrubbedKey, ((Date)o).getTime());
} else {
values.put(scrubbedKey, o.toString());
}
}
}
return values;
}
public static String getTableCreateString(String storageKey, Persistable p){
TableBuilder mTableBuilder = new TableBuilder(storageKey);
mTableBuilder.addData(p);
return mTableBuilder.getTableCreateString();
}
public static Pair<String, List<Object>> getTableInsertData(String storageKey, Persistable p){
TableBuilder mTableBuilder = new TableBuilder(storageKey);
mTableBuilder.addData(p);
return mTableBuilder.getTableInsertData(p);
}
} |
package bbm.actions.impl;
import bbm.actions.Action;
import bbm.actions.ActionResolver;
import static bbm.actions.ActionResolver.ActionType.*;
public class ActionResolverImpl implements ActionResolver{
@Override
public Action resolveAction(ActionType type, String branchName) {
switch (type){
case MONITOR:
return new MonitorAction(branchName);
case UNMONITOR:
return new UnmonitorAction(branchName);
case RETURN_CREDENTIALS:
return new ReceiveCredentialsAction(branchName);
}
throw new IllegalStateException("type not implemented");
}
} |
package br.com.caelum.parsac.util;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class ParserAfc {
private List<String> linguagens = new ArrayList<String>();
public ParserAfc() {
linguagens.add("java");
linguagens.add("xml");
linguagens.add("html");
linguagens.add("ruby");
linguagens.add("js");
linguagens.add("sql");
linguagens.add("css");
linguagens.add("bash");
linguagens.add("c
}
public String parseia(String string){
for (String linguagem : linguagens) {
string = string.replaceAll(Pattern.quote("[") + "(" + linguagem + ")" + Pattern.quote("]"), "[code " + linguagem + "]");
string = string.replaceAll(Pattern.quote("[/") + "(" + linguagem + ")" + Pattern.quote("]"), "[/code]");
}
string = string.replaceAll("<(b|strong|u)>", "**");
string = string.replaceAll("</(b|strong|u)>", "**");
string = string.replaceAll("<em>", "::");
string = string.replaceAll("</em>", "::");
return string;
}
} |
/*
Leetcode Problem 450: Delete Node in a BST
Given a root node reference of a BST and a key, delete the node with the given key in the BST.
Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Note: Time complexity should be O(height of tree).
Example:
root = [5,3,6,2,4,null,7]
key = 3
5
/ \
3 6
/ \ \
2 4 7
Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is [5,4,6,2,null,null,7], shown in the following BST.
5
/ \
4 6
/ \
2 7
Another valid answer is [5,2,6,null,4,null,7].
5
/ \
2 6
\ \
4 7
*/
public class DeleteNode {
public static class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int x) {
val = x;
}
}
// Recursive Solution: O(h) runtime and O(h) space complexities, where h = height of tree = log(n); n = number of tree elements
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return root;
if (key < root.val) {
root.left = deleteNode(root.left, key);
} else if (key > root.val) {
root.right = deleteNode(root.right, key);
} else { // key = root.val
if (root.left == null) return root.right;
else if (root.right == null) return root.left;
else { // Both left and rigth children are non null; so we first find the successor node,
// which is the node with the minimum value in the right subtree
TreeNode successorNode = findMinNode(root.right);
// We then replace the current node value with that of the successor node.
root.val = successorNode.val;
// Finally, we remove the successor node
root.right = deleteNode(root.right, successorNode.val); // remove the successor node
}
}
return root;
}
private TreeNode findMinNode(TreeNode node) {
while (node.left != null) {
node = node.left;
}
return node;
}
}
/*
// Iterative solution: O(log n) runtime and O(1) space complexities.
public TreeNode deleteNode(TreeNode root, int key) {
TreeNode currentNode = root, parentNode = root;
boolean isLeftChild = false; // will be set to true if the node to be deleted is a left child of its parent, and false otherwise
// We first find the node to be deleted, that is the node whose value is equal to key
while (currentNode != null && currentNode.val != key) {
parentNode = currentNode;
if (key < currentNode.val) {
currrentNode = currentNode.left;
isLeftChild = true;
} else {
currentNode = currentNode.right;
isLeftChild = false;
}
}
// if no node with a value of key is found, we return null since there is nothing to be deleted in such case
if (currrentNode == null) return null;
TreeNode deletionNode = currentNode, deletionNodeParent = parentNode;
// We now use Hibbard's Algorithm
// Case 1: The deletion node has no subtree, i.e. it is a leaf node
if (deletionNode.left == null && deletionNode.right == null) {
if (deletionNode == root) return null; // if deletionNode is the root node, we delete it by returning null
// Now, if the deletion node is a left (respectively right) child of its parent node,
// we just set the left (respectively right) child of parent node to null;
if (isLeftChild) deletionNodeParent.left = null;
else deletionNodeParent.right = null;
}
// Case 2: THE DELETION NODE HAS ONLY 1 CHILD (SUBTREE)
// Case 2a: THE DELETION NODE HAS ONLY 1 LEFT SUBTREE
else if (deletionNode.right == null) {
// If the deletion node is the root node, we just set it to its left child
if (deletionNode == root) root = root.left;
// If the deletion node is a left child of its parent, we make the parent node's left child point to the left subtree
// of the deletion node (remember the deletion node has only a left subree).
else if (isLeftChild) {
deletionNodeParent.left = deletionNode.left;
} else { / Otherwise, we make the parent node's right child point to the left subtree of the deletion node
deletionNodeParent.right = deletionNode.left;
}
}
// Case 2b: THE DELETION NODE HAS ONLY 1 RIGHT SUBTREE
else if (deletionNode.left == null) {
// If the deletion node is the root node, we just set it to its right child
if (deletionNode == root) root = root.right;
// If the deletion node is a left child of its parent, we make the parent node's left child point to the right subtree
// of the deletion node (remember the deletion node has only a right subree).
else if (isLeftChild) {
deletionNodeParent.left = deletionNode.right;
} else { // Otherwise, we make the parent node's right child point to the right subtree of the deletion node
deletionNodeParent.right = deletionNode.right;
}
}
// Case 3: THE DELETION NODE HAS 2 CHILDREN
else {
// We first find the successor node of the deletion node. The successor node is the smallest element to its right;
// So we go 1 step right, and then all the way left. The successor node cannot have a left child.
TreeNode successorNode = deletionNode.right, successorParentNode = deletionNode;
while (successorNode.left != null) {
successorParentNode = successorNode;
successorNode = successorNode.left;
}
// Special Case: the right node of the deletion node is its successor, i.e. the rigth subtree of deletion node
// has no left branch
if (successorNode == deletionNode.right) { // i.e deletionNode.right.left is null
// we replace the value of deletion node by that of its successor, and make its right child
// point to the right child of its successor
deletionNode.val = successorNode.val; // same as deletionNode.val = deletionNode.right.val
deletionNode.right = successorNode.right; // same as deletionNode.right = deletionNode.right.right
} else {
// We remove the deletion node by first replacing its value by that of its successor, and then making
// the left child of successorParentNode point to the successor's right subtree.
deletionNode.val = successorNode.val; // replace deletion node's value by that of its successor
successorParentNode.left = successorNode.right; // make the left child of successor's parent point to successor's right subtree.
}
}
return root;
}
*/ |
package br.uff.ic.provviewer.Filter;
import br.uff.ic.utility.graph.Edge;
import br.uff.ic.provviewer.GraphFrame;
import br.uff.ic.provviewer.VariableNames;
import br.uff.ic.provviewer.Variables;
import br.uff.ic.utility.Utils;
import br.uff.ic.utility.graph.AgentVertex;
import br.uff.ic.utility.graph.EntityVertex;
import br.uff.ic.utility.graph.Vertex;
import edu.uci.ics.jung.algorithms.filters.EdgePredicateFilter;
import edu.uci.ics.jung.algorithms.filters.Filter;
import edu.uci.ics.jung.algorithms.filters.VertexPredicateFilter;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.graph.DirectedGraph;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import java.util.List;
import org.apache.commons.collections15.Predicate;
/**
* Class to filter information
*
* @author Kohwalter
*/
public class Filters {
/**
* Variable FilteredGraph
*/
public DirectedGraph<Object, Edge> filteredGraph;
/**
* Variable EdgeFilter
*/
public Filter<Object, Edge> EdgeFilter;
/**
* Variable VertexFilter
*/
public Filter<Object, Edge> VertexFilter;
/**
* Initialize filters
*/
// public void FilterInit() {
public void Filters() {
//All vertices are visiable
VertexFilter = new VertexPredicateFilter<>(new Predicate<Object>() {
@Override
public boolean evaluate(Object vertex) {
return true;
}
});
//All edges are visible
EdgeFilter = new EdgePredicateFilter<>(new Predicate<Edge>() {
@Override
public boolean evaluate(Edge edge) {
return true;
}
});
}
/**
* Method for filtering the Graph
*
* @param variables Variables type
* @param hiddenEdges Boolean used to decide if hidden (original edges that
* composes the collapsed edge) edges will be filtered
*/
public void Filters(Variables variables, boolean hiddenEdges) {
variables.filter.filterVerticesAndEdges(variables.view,
variables.layout,
variables.collapsedGraph,
hiddenEdges, variables.config.timeScale, variables.selectedTimeScale, variables.numberOfGraphs);
}
/**
* Overload of the Filters method. hiddenEdges is always set as true,
* filtering the edges that composes the collapsed one
*
* @param variables Variables type
*/
public void Filters(Variables variables) {
Filters(variables, true);
}
/**
* Method to apply filters after an operation
*
* @param variables
*/
public void AddFilters(Variables variables) {
GraphFrame.edgeFilterList.setSelectedIndex(0);
GraphFrame.vertexFilterList.setSelectedIndex(0);
// GraphFrame.edgeFilterList.setSelectionInterval(0, variables.config.edgetype.size() - 1);
// GraphFrame.vertexFilterList.setSelectionInterval(0, variables.config.vertexLabelFilter.size() - 1);
Filters(variables, false);
}
/**
* Method to remove filters before an operation, avoiding the loss of
* information
*
* @param variables
*/
public void RemoveFilters(Variables variables) {
GraphFrame.edgeFilterList.setSelectedIndex(0);
GraphFrame.vertexFilterList.setSelectedIndex(0);
GraphFrame.hideAgentEdgesButton.setSelected(false);
GraphFrame.hideAgentVerticesButton.setSelected(false);
GraphFrame.hideEntityVerticesButton.setSelected(false);
GraphFrame.hideLonelyVerticesButton.setSelected(false);
GraphFrame.TemporalFilterToggle.setSelected(false);
Filters(variables);
}
/**
* Method to use filters (Vertex and Edge)
*
* @param view VisualizationViewer<Object, Edge> view
* @param layout Layout<Object, Edge> layout
* @param collapsedGraph DirectedGraph<Object,Edge> collapsedGraph
* @param hiddenEdges Boolean (filter original edges that composes a
* collapsed one or not?)
* @param timeScale is the default time scale from the config.xml file
* @param selectedTimeScale is the time scale selected in the interface
*/
public void filterVerticesAndEdges(VisualizationViewer<Object, Edge> view,
Layout<Object, Edge> layout,
DirectedGraph<Object, Edge> collapsedGraph,
boolean hiddenEdges, String timeScale, String selectedTimeScale, int numberOfGraphs) {
filteredGraph = collapsedGraph;
EdgeFilter = filterEdges(hiddenEdges);
VertexFilter = filterVertex(timeScale, selectedTimeScale, numberOfGraphs);
filteredGraph = (DirectedGraph<Object, Edge>) EdgeFilter.transform(filteredGraph);
filteredGraph = (DirectedGraph<Object, Edge>) VertexFilter.transform(filteredGraph);
// Filter Lonely Vertices. Had to be seperated otherwise it would not work
VertexFilter = filterLonelyVertex();
filteredGraph = (DirectedGraph<Object, Edge>) VertexFilter.transform(filteredGraph);
layout.setGraph(filteredGraph);
view.repaint();
}
/**
* Method to hide all edges that has the hidden parameter. This is used after an operation to hide the edges that are supposed to be hidden
* @param view
* @param layout
*/
public void filterHiddenEdges(VisualizationViewer<Object, Edge> view, Layout<Object, Edge> layout) {
EdgeFilter = filterEdges(true);
filteredGraph = (DirectedGraph<Object, Edge>) layout.getGraph();
filteredGraph = (DirectedGraph<Object, Edge>) EdgeFilter.transform(filteredGraph);
layout.setGraph(filteredGraph);
view.repaint();
}
/**
* Method to unhide the edges that are supposed to be hidden to not incur in lost of information
* @param view
* @param layout
*/
public void showHiddenEdges(VisualizationViewer<Object, Edge> view, Layout<Object, Edge> layout) {
EdgeFilter = filterEdges(false);
filteredGraph = (DirectedGraph<Object, Edge>) layout.getGraph();
filteredGraph = (DirectedGraph<Object, Edge>) EdgeFilter.transform(filteredGraph);
layout.setGraph(filteredGraph);
view.repaint();
}
/**
* Method for filtering edges
*
* @param hiddenEdges Boolean (consider hidden edges or not?)
* @return new EdgePredicateFilter<Object, Edge>(new Predicate<Edge>()
*/
private Filter<Object, Edge> filterEdges(final boolean hiddenEdges) {
Filter<Object, Edge> filterEdge = new EdgePredicateFilter<>(new Predicate<Edge>() {
@Override
public boolean evaluate(Edge edge) {
if (hiddenEdges) {
if (edge.isHidden()) {
return false;
}
}
if (edgeTypeFilter(edge)) {
return false;
}
return !edgeAgentFilter(edge);
}
});
return filterEdge;
}
/**
* Edge filter to show only edges from the selected type or label
*
* @param edge
* @return if the edge will be hidden
*/
private boolean edgeTypeFilter(Edge edge) {
List filtersL = GraphFrame.edgeFilterList.getSelectedValuesList();
for (Object filtersL1 : filtersL) {
String filter = (String) filtersL1;
if (filter.equalsIgnoreCase(VariableNames.FilterAllEdges)) {
return false;
}
if (edge.getLabel().contains(filter) || edge.getType().contains(filter)) {
return false;
}
}
return true;
}
/**
* Method to filter edges that connect to agents
*
* @param edge
* @return if the edge will be hidden
*/
private boolean edgeAgentFilter(Edge edge) {
if (GraphFrame.hideAgentEdgesButton.isSelected()) {
if (filteredGraph.getDest(edge) instanceof AgentVertex) {
return true;
}
}
return false;
}
/**
* Vertex filter method
*
* @return if the vertex will be hidden
*/
private Filter<Object, Edge> filterVertex(final String timeScale, final String selectedTimeScale, final int numberOfGraphs) {
Filter<Object, Edge> filterVertex = new VertexPredicateFilter<>(new Predicate<Object>() {
@Override
public boolean evaluate(Object vertex) {
if (vertexTypeFilter(vertex, numberOfGraphs)) {
return false;
}
// if (vertexLonelyFilter(vertex)) {
// return false;
if (vertexAttributeFilter(vertex)) {
return false;
}
return !vertexTemporalFilter(vertex, timeScale, selectedTimeScale);
}
});
return filterVertex;
}
/**
* Function to hide vertices without any visible edge
*
* @return if the vertex will be hidden or not
*/
private Filter<Object, Edge> filterLonelyVertex() {
Filter<Object, Edge> filterVertex = new VertexPredicateFilter<>(new Predicate<Object>() {
@Override
public boolean evaluate(Object vertex) {
return !vertexLonelyFilter(vertex);
}
});
return filterVertex;
}
/**
* Vertex filter for filtering lonely vertices (vertices without edges)
*
* @param vertex is the vertex being evaluated
* @return if the vertex will be hidden
*/
private boolean vertexLonelyFilter(Object vertex) {
if (GraphFrame.hideLonelyVerticesButton.isSelected()) {
final Graph test = filteredGraph;
if (test.getNeighborCount(vertex) == 0) {
return true;
}
}
return false;
}
/**
* Vertex filter to filter vertices of the selected type
*
* @param vertex is the vertex being evaluated
* @return if the vertex will be hidden
*/
private boolean vertexTypeFilter(Object vertex, int numberOfGraphs) {
if (GraphFrame.hideAgentVerticesButton.isSelected()) {
if (vertex instanceof AgentVertex) {
return true;
}
}
if (GraphFrame.hideEntityVerticesButton.isSelected()) {
if (vertex instanceof EntityVertex) {
return true;
}
}
if (GraphFrame.hideMergedVerticesButton.isSelected()) {
if(((Vertex)vertex).getAttributeValues(VariableNames.GraphFile).length == numberOfGraphs)
return true;
}
return false;
}
/**
* Filter to hide all vertices that has the selected attribute with the
* selected value
*
* @param vertex is the vertex being evaluated
* @return true to show the vertex and false to hide it
*/
private boolean vertexAttributeFilter(Object vertex) {
List filtersL = GraphFrame.vertexFilterList.getSelectedValuesList();
for (Object filtersL1 : filtersL) {
String filter = (String) filtersL1;
if (filter.equalsIgnoreCase(VariableNames.FilterAllVertices)) {
return false;
}
if (vertex instanceof Vertex) {
String name;
String value;
name = filter.split(": ")[0];
value = filter.split(": ")[1];
if (((Vertex) vertex).getAttributeValue(name).equalsIgnoreCase(value)) {
return false;
}
}
}
return true;
}
/**
* Vertex filter to filter vertices that is outside the desired temporal
* range
*
* @param vertex
* @return if the vertex will be hidden
*/
private boolean vertexTemporalFilter(Object vertex, String timeScale, String selectedTimeScale) {
if (GraphFrame.TemporalFilterToggle.isSelected()) {
if (!(vertex instanceof AgentVertex)) {
double timeDate = ((Vertex) vertex).getTime();
double time = ((Vertex) vertex).getNormalizedTime();
time = Utils.convertTime(timeScale, time, selectedTimeScale);
if (Utils.tryParseFloat(GraphFrame.FilterVertexMinValue.getText())) {
double minTime = Float.parseFloat(GraphFrame.FilterVertexMinValue.getText());
if (time < minTime) {
return true;
}
} else if (Utils.tryParseDate(GraphFrame.FilterVertexMinValue.getText())) {
double minTime = Utils.convertStringDateToFloat(GraphFrame.FilterVertexMinValue.getText());
if (timeDate < minTime) {
return true;
}
}
if (Utils.tryParseFloat(GraphFrame.FilterVertexMaxValue.getText())) {
double maxTime;
maxTime = Float.parseFloat(GraphFrame.FilterVertexMaxValue.getText());
if (time > maxTime) {
return true;
}
} else if (Utils.tryParseDate(GraphFrame.FilterVertexMaxValue.getText())) {
double maxTime = Utils.convertStringDateToFloat(GraphFrame.FilterVertexMaxValue.getText());
if (timeDate > maxTime) {
return true;
}
}
}
}
return false;
}
} |
package br.uff.ic.provviewer.GUI;
import br.uff.ic.provviewer.Variables;
import br.uff.ic.utility.graph.Edge;
import static br.uff.ic.provviewer.GraphFrame.StatusFilterBox;
import br.uff.ic.provviewer.Layout.Temporal_Layout;
import br.uff.ic.provviewer.Layout.OneDimensional_Layout;
import br.uff.ic.utility.graph.AgentVertex;
import br.uff.ic.provviewer.Vertex.ColorScheme.VertexPainter;
import br.uff.ic.utility.IO.PROVNWriter;
import br.uff.ic.utility.IO.XMLWriter;
import br.uff.ic.utility.graph.GraphVertex;
import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.EdgeShape;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import edu.uci.ics.jung.visualization.picking.PickedInfo;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import org.apache.commons.collections15.Transformer;
/**
* Class responsible for implementing each GUI button
* @author Kohwalter
*/
public class GuiButtons {
/**
* Method to exit the application
*/
public static void Exit() {
System.exit(0);
}
/**
* Method to expand a previously collapsed vertex
* @param variables
*/
public static void Expand(Variables variables) {
Collection picked = new HashSet(variables.view.getPickedVertexState().getPicked());
variables.collapser.Expander(variables, picked);
}
/**
* Method to collapse a set of selected vertices
* @param variables
*/
public static void Collapse(Variables variables) {
Collection picked = new HashSet(variables.view.getPickedVertexState().getPicked());
variables.collapser.Collapse(variables, picked, true);
}
/**
* Method to rollback to the original graph
* @param variables
*/
public static void Reset(Variables variables) {
variables.collapser.ResetGraph(variables);
variables.config.resetVertexModeInitializations();
}
/**
* Method to select the mouse modes (Picking or Transforming)
* @param mouse
* @param MouseModes
*/
public static void MouseModes(DefaultModalGraphMouse mouse, JComboBox MouseModes) {
String mode = (String) MouseModes.getSelectedItem();
if (mode.equalsIgnoreCase("Picking")) {
mouse.setMode(ModalGraphMouse.Mode.PICKING);
}
if (mode.equalsIgnoreCase("Transforming")) {
mouse.setMode(ModalGraphMouse.Mode.TRANSFORMING);
}
}
/**
* Method to collapse all vertices from each agent
* @param variables
*/
public static void CollapseAgent(Variables variables) {
PickedInfo<Object> picked_state;
picked_state = variables.view.getPickedVertexState();
Object node = null;
//Get the selected node
for (Object z : variables.layout.getGraph().getVertices()) {
if (picked_state.isPicked(z)) {
node = z;
}
}
//Select the node and its neighbors to be collapsed
if (variables.layout.getGraph().getNeighbors(node) != null) {
Collection picked = new HashSet();
for(Object v : variables.layout.getGraph().getNeighbors(node)) {
if(v instanceof GraphVertex) {
boolean hasAgent = false;
if(((GraphVertex)v).hasAttribute("Agents"))
hasAgent = true;
if(!hasAgent)
picked.add(v);
}
else if(!(v instanceof AgentVertex))
picked.add(v);
}
// Collection picked = new HashSet(variables.layout.getGraph().getNeighbors(node));
picked.add(node);
if (!(node instanceof AgentVertex)) {
picked.removeAll(picked);
}
variables.collapser.Collapse(variables, picked, true);
}
}
/**
* Method to apply edge filters
* @param variables
*/
public static void Filter(Variables variables) {
variables.filter.Filters(variables);
}
/**
* Method to define the overall edge arrow format
* @param EdgeLineShapeSelection
* @param variables
*/
public static void EdgeLineMode(JComboBox EdgeLineShapeSelection, Variables variables) {
String mode = (String) EdgeLineShapeSelection.getSelectedItem();
if (mode.equalsIgnoreCase("QuadCurve")) {
variables.view.getRenderContext().setEdgeShapeTransformer(new EdgeShape.QuadCurve<Object, Edge>());
}
if (mode.equalsIgnoreCase("Line")) {
variables.view.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line<Object, Edge>());
}
variables.view.repaint();
}
/**
* Method to change the vertex coloring according to the selected attribute
* @param variables
*/
public static void StatusFilter(Variables variables) {
VertexPainter.VertexPainter((String) StatusFilterBox.getSelectedItem(), variables.view, variables);
variables.view.repaint();
}
/**
* method to display edge label
* @param variables
* @param ShowEdgeTextButton
*/
public static void EdgeTextDisplay(Variables variables, Boolean ShowEdgeTextButton) {
if (ShowEdgeTextButton) {
variables.view.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller<Edge>());
} else {
//Show nothing
variables.view.getRenderContext().setEdgeLabelTransformer(new Transformer<Edge, String>() {
@Override
public String transform(Edge i) {
return "";
}
});
}
variables.view.repaint();
}
/**
* Method to change the graph layout
* @param variables
* @param Layouts
*/
public static void LayoutSelection(Variables variables, JComboBox Layouts) {
String layout = (String) Layouts.getSelectedItem();
variables.newLayout(layout);
variables.guiBackground.InitBackground(variables, Layouts);
variables.view.setGraphLayout(variables.layout);
variables.view.repaint();
GuiFunctions.PanCameraToFirstVertex(variables);
}
public static void setVariableLayouts(Variables variables, boolean b, JComboBox Layouts) {
variables.allowVariableLayout = b;
if(!variables.allowVariableLayout)
LayoutSelection(variables, Layouts);
}
/**
* Method to update the layouts that use the vertex's time as X position since the user can alter the timescale
* @param variables
* @param Layouts
*/
public static void UpdateTemporalLayout(Variables variables, JComboBox Layouts) {
String layout = (String) Layouts.getSelectedItem();
if (layout.equalsIgnoreCase(variables.layout_temporal)) {
variables.layout = new Temporal_Layout<>(variables.layout.getGraph(), variables);
variables.guiBackground.InitBackground(variables, Layouts);
variables.view.setGraphLayout(variables.layout);
variables.view.repaint();
}
if (layout.equalsIgnoreCase(variables.layout_One_Dimensional)) {
variables.layout = new OneDimensional_Layout<>(variables.layout.getGraph(), variables);
variables.guiBackground.InitBackground(variables, Layouts);
variables.view.setGraphLayout(variables.layout);
variables.view.repaint();
}
}
public static void AutoDetectEdge(Variables variables, boolean selected) {
if(selected)
variables.config.DetectEdges(variables.graph.getEdges());
variables.ComputeEdgeTypeValues();
}
public static void AutoDetectVertexModes(Variables variables, boolean selected) {
if(selected)
variables.config.DetectVertexModes(variables.graph.getVertices());
}
// public static void AutoDetectVertexLabels(Variables variables, boolean selected) {
// if(selected)
// variables.config.DetectVertexAttributeFilterValues(variables.graph.getVertices());
public static void VertexLabel(Variables variables, boolean agentLabel, boolean activityLabel, boolean entityLabel, boolean timeLabel, boolean showID) {
GuiFunctions.VertexLabel(variables, agentLabel, activityLabel, entityLabel, timeLabel, showID);
variables.view.repaint();
}
public static void ExportPROVN(Variables variables) {
// Collection<Vertex> vertices = new ArrayList<Vertex>();
// for(Object v : variables.graph.getVertices()) {
// vertices.add((Vertex)v);
PROVNWriter provnWriter = new PROVNWriter(variables.graph.getVertices(), variables.graph.getEdges());
XMLWriter xmlWriter = new XMLWriter(variables.graph.getVertices(), variables.graph.getEdges());
XMLWriter xmlWriter_collapsed = new XMLWriter(variables.collapsedGraph.getVertices(), variables.graph.getEdges());
try {
provnWriter.saveToProvn("PROVN_Export_Test");
xmlWriter.saveToXML("XML_Export_Test");
xmlWriter_collapsed.saveToXML("XML_Collapsed_Export_Test");
} catch (IOException ex) {
Logger.getLogger(GuiButtons.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void TemporalLayoutGranularity(String selectedTime, Variables variables,
boolean nanoseconds,
boolean microseconds,
boolean milliseconds,
boolean seconds,
boolean minutes,
boolean hours,
boolean days,
boolean weeks,
JComboBox Layouts,
JCheckBoxMenuItem temporalNanosecondsButton,
JCheckBoxMenuItem temporalMicrosecondsButton,
JCheckBoxMenuItem temporalMillisecondsButton,
JCheckBoxMenuItem temporalSecondsButton,
JCheckBoxMenuItem temporalMinutesButton,
JCheckBoxMenuItem temporalHoursButton,
JCheckBoxMenuItem temporalDaysButton,
JCheckBoxMenuItem temporalWeeksButton) {
variables.selectedTimeScale = selectedTime;
temporalNanosecondsButton.setSelected(nanoseconds);
temporalMicrosecondsButton.setSelected(microseconds);
temporalMillisecondsButton.setSelected(milliseconds);
temporalSecondsButton.setSelected(seconds);
temporalMinutesButton.setSelected(minutes);
temporalHoursButton.setSelected(hours);
temporalDaysButton.setSelected(days);
temporalWeeksButton.setSelected(weeks);
GuiButtons.UpdateTemporalLayout(variables, Layouts);
}
public static void derivateScheme(Variables variables, boolean doDerivate) {
variables.doDerivate = doDerivate;
StatusFilter(variables);
}
public static void removeOutliersDerivateScheme(Variables variables, boolean removeOutliers) {
variables.removeDerivateOutliers = removeOutliers;
variables.changedOutliersOption = true;
StatusFilter(variables);
}
public static void selectVertexShape(Variables variables, String selectedMode, String attribute) {
GuiFunctions.VertexShape(variables, selectedMode, attribute);
}
} |
package catastrophe.discovery;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import com.ecwid.consul.transport.TransportException;
import com.ecwid.consul.v1.ConsistencyMode;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.catalog.model.CatalogService;
public class ServiceFinder {
private static final QueryParams QUERY_PARAMS = new QueryParams(ConsistencyMode.DEFAULT);
private static final Random RANDOM = new Random();
private static final String CONSUL_HOST = System.getenv("CONSUL_HOST");
private static final int CONSUL_PORT = Integer.valueOf(System.getenv("CONSUL_PORT"));
Set<String> serviceIds = new HashSet<String>();
final ConsulClient client;
public ServiceFinder() {
// This entry needs to be in /etc/hosts, pointing to the IP address
// of the docker container
client = new ConsulClient(CONSUL_HOST, CONSUL_PORT);
}
public String getHostAndPort(String serviceName) {
serviceName = serviceName.replaceAll("/", "");
// Check environment variables first, in case we have consul problems
Map<String, String> env = System.getenv();
// Prefer an environment variable if one is set
String key = "SERVICE_" + serviceName.replace('.', '-');
System.out.println("Checking environment for " + key);
String value = env.get(key);
if (value != null) {
System.out.println("Using environment variable: " + value);
return value;
}
try {
Response<List<CatalogService>> r = client.getCatalogService(serviceName, QUERY_PARAMS);
List<CatalogService> list = r.getValue();
int numberOfServices = list.size();
if (numberOfServices > 0) {
// Do a simple random-robin :)
int index = RANDOM.nextInt(numberOfServices);
System.out.println("Choosing service " + index + " of " + numberOfServices);
CatalogService service = list.get(index);
// Massive temporary hack
if (!service.getServiceAddress().startsWith("169.")) {
return service.getServiceAddress() + ":" + service.getServicePort();
} else {
// Use hard-coded values to work out the secure gateway path
// This is the opposite of service discovery, of course
int port = service.getServicePort();
if (port == 8085) { // users, pi2
return "cap-sg-prd-5.integration.ibmcloud.com:17926";
} else if (port == 8082) { // cats, red pi
return "cap-sg-prd-5.integration.ibmcloud.com:16451";
} else if (port == 8081) { // scoring, localhost
return "cap-sg-prd-5.integration.ibmcloud.com:16193";
} else {
System.out.println("Could not unmap " + service.getServiceAddress());
return "unknown:8080";
}
}
} else {
System.out.println("No services available with name " + serviceName);
}
} catch (
TransportException e) {
System.out.println(e + CONSUL_HOST);
}
return null;
}
} |
package org.helm.notation.demo.tools;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.helm.notation.MonomerFactory;
import org.helm.notation.model.Monomer;
import org.helm.notation.model.PolymerNode;
import org.helm.notation.tools.ComplexNotationParser;
import org.helm.notation.tools.MonomerParser;
import org.helm.notation.tools.SimpleNotationParser;
import org.jdom.output.XMLOutputter;
public class xHELMSample {
public static void main(String[] args) {
// Load HELM and convert to xHELM
try {
//MonomerFactory.getInstance();
String notation = "PEPTIDE1{A.G.G.G.C.C.K.K.K.K}|CHEM1{MCC}$PEPTIDE1,CHEM1,10:R3-1:R1$$$";
//String notation = "PEPTIDE1{Q.A.Q.L.Q.E.S.G.P.G.L.A.K.P.S.E.T.L.S.L.T.C.T.A.S.G.G.S.I.S.G.Y.Y.W.S.W.I.R.Q.P.V.G.K.G.L.E.W.I.G.R.I.Y.T.S.G.S.T.N.Y.N.P.S.L.K.S.R.A.T.M.S.A.D.T.S.K.N.Q.F.S.L.K.L.S.S.A.T.V.V.D.T.V.A.Y.Y.C.V.R.G.R.F.T.Y.F.D.Y.W.G.Q.G.T.L.A.T.A.S.S.V.S.T.K.G.P.S.A.F.P.L.V.P.S.S.K.S.T.S.G.G.T.V.V.L.G.C.L.A.K.D.Y.F.P.E.P.A.T.A.S.W.N.S.G.V.L.T.S.G.A.H.T.F.P.V.A.L.Q.S.S.G.L.Y.S.L.S.S.A.A.T.A.P.S.S.S.L.G.T.Q.T.Y.I.C.N.A.N.H.K.P.S.N.T.K.A.D.K.K.A.E.P.K.S.C.D.K.T.H.T.C.P.P.C.P.V.P.E.L.L.G.G.P.S.A.F.L.F.P.P.K.P.K.D.T.L.M.I.S.R.T.P.E.A.T.C.A.A.A.D.A.S.H.E.D.P.E.A.K.F.N.W.Y.A.D.G.A.E.A.H.N.V.K.T.K.P.R.E.E.Q.Y.N.S.T.Y.R.A.A.S.A.L.T.A.L.H.Q.D.W.L.N.G.K.E.Y.K.C.K.A.S.N.K.V.L.P.V.P.I.E.K.T.I.S.K.V.K.G.Q.P.R.E.P.Q.A.Y.T.L.P.P.S.R.D.E.L.T.K.N.Q.A.S.L.T.C.L.A.K.G.F.Y.P.S.D.I.V.A.E.W.E.S.N.G.Q.P.E.N.N.Y.K.T.T.P.P.A.L.D.S.D.G.S.F.F.L.Y.S.K.L.T.A.D.K.S.R.W.Q.Q.G.N.A.F.S.C.S.A.M.H.E.V.L.H.N.H.Y.T.Q.K.S.L.S.L.S.P.G.K}|PEPTIDE2{Q.A.Q.L.Q.E.S.G.P.G.L.A.K.P.S.E.T.L.S.L.T.C.T.A.S.G.G.S.I.S.G.Y.Y.W.S.W.I.R.Q.P.V.G.K.G.L.E.W.I.G.R.I.Y.T.S.G.S.T.N.Y.N.P.S.L.K.S.R.A.T.M.S.A.D.T.S.K.N.Q.F.S.L.K.L.S.S.A.T.V.V.D.T.V.A.Y.Y.C.V.R.G.R.F.T.Y.F.D.Y.W.G.Q.G.T.L.A.T.A.S.S.V.S.T.K.G.P.S.A.F.P.L.V.P.S.S.K.S.T.S.G.G.T.V.V.L.G.C.L.A.K.D.Y.F.P.E.P.A.T.A.S.W.N.S.G.V.L.T.S.G.A.H.T.F.P.V.A.L.Q.S.S.G.L.Y.S.L.S.S.A.A.T.A.P.S.S.S.L.G.T.Q.T.Y.I.C.N.A.N.H.K.P.S.N.T.K.A.D.K.K.A.E.P.K.S.C.D.K.T.H.T.C.P.P.C.P.V.P.E.L.L.G.G.P.S.A.F.L.F.P.P.K.P.K.D.T.L.M.I.S.R.T.P.E.A.T.C.A.A.A.D.A.S.H.E.D.P.E.A.K.F.N.W.Y.A.D.G.A.E.A.H.N.V.K.T.K.P.R.E.E.Q.Y.N.S.T.Y.R.A.A.S.A.L.T.A.L.H.Q.D.W.L.N.G.K.E.Y.K.C.K.A.S.N.K.V.L.P.V.P.I.E.K.T.I.S.K.V.K.G.Q.P.R.E.P.Q.A.Y.T.L.P.P.S.R.D.E.L.T.K.N.Q.A.S.L.T.C.L.A.K.G.F.Y.P.S.D.I.V.A.E.W.E.S.N.G.Q.P.E.N.N.Y.K.T.T.P.P.A.L.D.S.D.G.S.F.F.L.Y.S.K.L.T.A.D.K.S.R.W.Q.Q.G.N.A.F.S.C.S.A.M.H.E.V.L.H.N.H.Y.T.Q.K.S.L.S.L.S.P.G.K}|PEPTIDE3{E.I.A.L.T.Q.S.P.V.T.L.S.L.S.P.G.E.R.V.T.L.S.C.R.V.S.Q.I.A.S.S.V.Y.L.V.W.Y.Q.Q.K.P.G.Q.V.P.R.L.L.M.F.G.S.S.S.R.V.T.G.I.P.D.R.F.S.G.S.G.S.G.T.D.F.T.L.T.I.S.R.L.E.P.E.D.F.V.A.Y.Y.C.Q.Q.Y.G.S.S.Q.G.T.F.G.P.G.T.K.A.D.I.K.R.T.A.V.V.P.S.A.F.I.F.P.P.S.D.E.Q.L.K.S.G.T.V.S.A.A.C.L.L.N.N.F.Y.P.R.E.V.K.A.Q.W.K.A.D.N.V.L.Q.S.G.N.S.Q.E.S.A.T.E.Q.D.S.K.D.S.T.Y.S.L.S.S.T.L.T.L.S.K.V.D.Y.E.K.H.K.A.Y.V.C.E.A.T.H.Q.G.L.S.S.P.A.T.K.S.F.N.R.G.E.C}|PEPTIDE4{E.I.A.L.T.Q.S.P.V.T.L.S.L.S.P.G.E.R.V.T.L.S.C.R.V.S.Q.I.A.S.S.V.Y.L.V.W.Y.Q.Q.K.P.G.Q.V.P.R.L.L.M.F.G.S.S.S.R.V.T.G.I.P.D.R.F.S.G.S.G.S.G.T.D.F.T.L.T.I.S.R.L.E.P.E.D.F.V.A.Y.Y.C.Q.Q.Y.G.S.S.Q.G.T.F.G.P.G.T.K.A.D.I.K.R.T.A.V.V.P.S.A.F.I.F.P.P.S.D.E.Q.L.K.S.G.T.V.S.A.A.C.L.L.N.N.F.Y.P.R.E.V.K.A.Q.W.K.A.D.N.V.L.Q.S.G.N.S.Q.E.S.A.T.E.Q.D.S.K.D.S.T.Y.S.L.S.S.T.L.T.L.S.K.V.D.Y.E.K.H.K.A.Y.V.C.E.A.T.H.Q.G.L.S.S.P.A.T.K.S.F.N.R.G.E.C}$PEPTIDE1,PEPTIDE1,22:R3-95:R3|PEPTIDE1,PEPTIDE1,143:R3-199:R3|PEPTIDE1,PEPTIDE3,219:R3-215:R3|PEPTIDE1,PEPTIDE2,225:R3-225:R3|PEPTIDE1,PEPTIDE2,228:R3-228:R3|PEPTIDE1,PEPTIDE1,260:R3-320:R3|PEPTIDE1,PEPTIDE1,366:R3-424:R3|PEPTIDE2,PEPTIDE2,22:R3-95:R3|PEPTIDE2,PEPTIDE2,143:R3-199:R3|PEPTIDE2,PEPTIDE4,219:R3-215:R3|PEPTIDE2,PEPTIDE2,260:R3-320:R3|PEPTIDE2,PEPTIDE2,366:R3-424:R3|PEPTIDE3,PEPTIDE3,23:R3-89:R3|PEPTIDE3,PEPTIDE3,135:R3-195:R3|PEPTIDE4,PEPTIDE4,23:R3-89:R3|PEPTIDE4,PEPTIDE4,135:R3-195:R3$$$";
System.out.println("Edge String: " + ComplexNotationParser.getAllEdgeString(notation));
//get all simple polymers
Set<Monomer> set = new HashSet<Monomer>();
List<PolymerNode> simplePolymers = ComplexNotationParser.getPolymerNodeList(notation);
for (PolymerNode node: simplePolymers) {
System.out.println(node.getId() + ": " + node.getLabel() + "(" + node.getType() + ")");
List<Monomer> monomers = SimpleNotationParser.getMonomerList(node.getLabel(), node.getType());
for (Monomer subnode: monomers) {
System.out.println(subnode.getName() +" | " + subnode.getAlternateId());
set.add(subnode);
}
}
//Distinct monomers
System.out.println("\n Distinct monomers");
for (Monomer distinctmonomer: set) {
System.out.println(distinctmonomer.getName() +" | " + distinctmonomer.getAlternateId());
XMLOutputter outp = new XMLOutputter();
String s = outp.outputString(MonomerParser.getMonomerElement(distinctmonomer));
System.out.println(s);
}
} catch (Exception ex) {
Logger.getLogger(ComplexNotationSample.class.getName()).log(Level.SEVERE, null, ex);
}
}
} |
/**
* Finds the longest repeated substring(s) of a string.
*
* Time complexity: O(nlogn), bounded by suffix array construction
*
* @author William Fiset, william.alexandre.fiset@gmail.com
**/
import java.util.*;
public class LongestRepeatedSubstring {
// Example usage
public static void main(String[] args) {
String str = "ABC$BCA$CAB";
SuffixArray sa = new SuffixArray(str);
System.out.printf("LRS(s) of %s is/are: %s\n", str, sa.lrs());
str = "aaaaa";
sa = new SuffixArray(str);
System.out.printf("LRS(s) of %s is/are: %s\n", str, sa.lrs());
str = "abcde";
sa = new SuffixArray(str);
System.out.printf("LRS(s) of %s is/are: %s\n", str, sa.lrs());
}
}
class SuffixArray {
// ALPHABET_SZ is the default alphabet size, this may need to be much
// larger if you're using the LCS method with multiple sentinels
int ALPHABET_SZ = 256, N;
int[] T, lcp, sa, sa2, rank, tmp, c;
public SuffixArray(String str) {
this(toIntArray(str));
}
private static int[] toIntArray(String s) {
int[] text = new int[s.length()];
for(int i=0;i<s.length();i++)text[i] = s.charAt(i);
return text;
}
// Designated constructor
public SuffixArray(int[] text) {
T = text;
N = text.length;
sa = new int[N];
sa2 = new int[N];
rank = new int[N];
c = new int[Math.max(ALPHABET_SZ, N)];
construct();
kasai();
}
private void construct() {
int i, p, r;
for (i=0; i<N; ++i) c[rank[i] = T[i]]++;
for (i=1; i<ALPHABET_SZ; ++i) c[i] += c[i-1];
for (i=N-1; i>=0; --i) sa[--c[T[i]]] = i;
for (p=1; p<N; p <<= 1) {
for (r=0, i=N-p; i<N; ++i) sa2[r++] = i;
for (i=0; i<N; ++i) if (sa[i] >= p) sa2[r++] = sa[i] - p;
Arrays.fill(c, 0, ALPHABET_SZ, 0);
for (i=0; i<N; ++i) c[rank[i]]++;
for (i=1; i<ALPHABET_SZ; ++i) c[i] += c[i-1];
for (i=N-1; i>=0; --i) sa[--c[rank[sa2[i]]]] = sa2[i];
for (sa2[sa[0]] = r = 0, i=1; i<N; ++i) {
if (!(rank[sa[i-1]] == rank[sa[i]] &&
sa[i-1]+p < N && sa[i]+p < N &&
rank[sa[i-1]+p] == rank[sa[i]+p])) r++;
sa2[sa[i]] = r;
} tmp = rank; rank = sa2; sa2 = tmp;
if (r == N-1) break; ALPHABET_SZ = r + 1;
}
}
// Use Kasai algorithm to build LCP array
private void kasai() {
lcp = new int[N];
int [] inv = new int[N];
for (int i = 0; i < N; i++) inv[sa[i]] = i;
for (int i = 0, len = 0; i < N; i++) {
if (inv[i] > 0) {
int k = sa[inv[i]-1];
while( (i + len < N) && (k + len < N) && T[i+len] == T[k+len] ) len++;
lcp[inv[i]-1] = len;
if (len > 0) len
}
}
}
// Finds the LRS(s) (Longest Repeated Substring) that occurs in a string.
// Traditionally we are only interested in substrings that appear at
// least twice, so this method returns an empty set if this is the case.
// @return an ordered set of longest repeated substrings
public TreeSet <String> lrs() {
int max_len = 0;
TreeSet <String> lrss = new TreeSet<>();
for (int i = 0; i < N; i++) {
if (lcp[i] > 0 && lcp[i] >= max_len) {
// We found a longer LRS
if ( lcp[i] > max_len )
lrss.clear();
// Append substring to the list and update max
max_len = lcp[i];
lrss.add( new String(T, sa[i], max_len) );
}
}
return lrss;
}
public void display() {
System.out.printf("
for(int i = 0; i < N; i++) {
int suffixLen = N - sa[i];
String suffix = new String(T, sa[i], suffixLen);
System.out.printf("% 7d % 7d % 7d %s\n", i, sa[i],lcp[i], suffix );
}
}
} |
package ch.liquidmind.inflection;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import __java.lang.__Class;
import __java.lang.reflect.__Field;
import ch.liquidmind.inflection.exception.ExceptionWrapper;
import ch.liquidmind.inflection.loader.TaxonomyLoader;
import ch.liquidmind.inflection.model.external.Taxonomy;
import ch.liquidmind.inflection.model.external.View;
import ch.liquidmind.inflection.proxy.Proxy;
import ch.liquidmind.inflection.proxy.ProxyRegistry;
import ch.liquidmind.inflection.proxy.Tuples.ObjectType;
import ch.liquidmind.inflection.util.InflectionPrinter;
public class Inflection
{
private static Map< Class< ? >, Taxonomy > taxonomyCache = new HashMap< Class< ? >, Taxonomy >();
private static Map< Class< ? >, View > viewCache = new HashMap< Class< ? >, View >();
public static Taxonomy getTaxonomy( Class< ? extends Proxy > proxyClass )
{
Taxonomy taxonomy = taxonomyCache.get( proxyClass );
if ( taxonomy == null )
{
Field field = __Class.getDeclaredField( proxyClass, "TAXONOMY" );
field.setAccessible( true );
taxonomy = (Taxonomy)__Field.get( field, null );
taxonomyCache.put( proxyClass, taxonomy );
}
return taxonomy;
}
public static View getView( Class< ? extends Proxy > proxyClass )
{
View view = viewCache.get( proxyClass );
if ( view == null )
{
Field field = __Class.getDeclaredField( proxyClass, "VIEW" );
field.setAccessible( true );
view = (View)__Field.get( field, null );
viewCache.put( proxyClass, view );
}
return view;
}
public static Taxonomy getTaxonomy( Proxy proxy )
{
return getTaxonomy( proxy.getClass() );
}
public static View getView( Proxy proxy )
{
return getView( proxy.getClass() );
}
public static < T > T cast( Taxonomy taxonomy, Class< T > theClass, Object object )
{
ObjectType targetObjectType = determineObjectType( theClass );
T targetObject = ProxyRegistry.getContextProxyRegistry().getObject( taxonomy, targetObjectType, object );
return targetObject;
}
public static < T > T cast( Class< T > theClass, Object object )
{
Taxonomy targetTaxonomy = determineTaxonomy( theClass );
Taxonomy sourceTaxonomy = determineTaxonomy( object.getClass() );
Taxonomy taxonomy = ( targetTaxonomy == null ? sourceTaxonomy : targetTaxonomy );
if ( taxonomy == null )
throw new IllegalStateException( "taxonomy should never be null." );
return cast( taxonomy, theClass, object );
}
@SuppressWarnings( "unchecked" )
private static Taxonomy determineTaxonomy( Class< ? > aClass )
{
Taxonomy taxonomy;
if ( Proxy.class.isAssignableFrom( aClass ) )
{
taxonomy = getTaxonomy( (Class< Proxy >)aClass );
}
else
{
Auxiliary auxiliary = aClass.getAnnotation( Auxiliary.class );
if ( auxiliary != null )
taxonomy = TaxonomyLoader.getContextTaxonomyLoader().loadTaxonomy( auxiliary.value() );
else
taxonomy = null;
}
return taxonomy;
}
private static ObjectType determineObjectType( Class< ? > aClass )
{
ObjectType objectType;
if ( Proxy.class.isAssignableFrom( aClass ) )
{
objectType = ObjectType.Proxy;
}
else
{
Auxiliary auxiliary = aClass.getAnnotation( Auxiliary.class );
if ( auxiliary != null )
objectType = ObjectType.Auxiliary;
else
objectType = ObjectType.Object;
}
return objectType;
}
public static < T extends Object > T cast( String taxonomy, Object object )
{
return cast( TaxonomyLoader.getContextTaxonomyLoader().loadTaxonomy( taxonomy ), ObjectType.Proxy, object );
}
public static < T extends Object > T cast( Taxonomy taxonomy, Object object )
{
return cast( taxonomy, ObjectType.Proxy, object );
}
public static < T extends Object > T cast( Taxonomy taxonomy, ObjectType objectType, Object object )
{
return ProxyRegistry.getContextProxyRegistry().getObject( taxonomy, objectType, object );
}
public static < T extends Object > T cast( Proxy proxy )
{
return cast( ObjectType.Object, proxy );
}
public static < T extends Object > T cast( ObjectType objectType, Proxy proxy )
{
return ProxyRegistry.getContextProxyRegistry().getObject( getTaxonomy( proxy ), objectType, proxy );
}
public static String viewToString( Proxy proxy )
{
StringWriter stringWriter = new StringWriter();
InflectionPrinter.printView( getTaxonomy( proxy ), getView( proxy ), stringWriter, true, false );
String s = stringWriter.toString();
return s;
}
public static String valueToString( Proxy proxy )
{
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
String s = ExceptionWrapper.ObjectWriter_writeValueAsString( writer, proxy );
return s;
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.sf.jaer.hardwareinterface.udp;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
import net.sf.jaer.eventio.*;
import net.sf.jaer.hardwareinterface.*;
import net.sf.jaer.hardwareinterface.udp.smartEyeTDS.SmartEyeTDS;
/**
* Simple interface factory for the UDP devices.
*
* @author braendch
*/
public class UDPInterfaceFactory implements HardwareInterfaceFactoryInterface {
//TODO Implement a nice way to build the list of available UDPInterfaces
private static final Logger log = Logger.getLogger("USBIOHardwareInterfaceFactory");
private ArrayList<String> availableInterfaces = new ArrayList<String>();
private static UDPInterfaceFactory instance = new UDPInterfaceFactory();
private byte[] buf = null; // init when needed, null afterward
private DatagramPacket packet = null; // init when needed
//private static UDPInterfaceFactory instance = null;
private UDPInterfaceFactory() {
buildUdpIoList();
}
/** @return singleton instance */
public static HardwareInterfaceFactoryInterface instance() {
return instance;
}
/** returns the first interface in the list
*@return reference to the first interface in the list
*/
@Override
synchronized public UDPInterface getFirstAvailableInterface() {
return getInterface(0);
}
/** returns the n-th interface in the list
*
*@param n the number to instance (0 based)
*/
@Override
synchronized public UDPInterface getInterface(int n) {
buildUdpIoList();
int numAvailable=getNumInterfacesAvailable();
if(n>numAvailable-1){
if(numAvailable>0){ // warn if there is at least one available but we asked for one higher than we have
log.warning("only "+numAvailable+" interfaces available but you asked for number "+n);
}
return null;
}
if(n==0){
return new SmartEyeTDS(0);
} else {
return null;
}
}
private void buildUdpIoList(){
try {
DatagramSocket socket = new DatagramSocket(SmartEyeTDS.STREAM_PORT);
socket.setReuseAddress(true);
if(buf==null) buf= new byte[AENetworkInterfaceConstants.DATAGRAM_BUFFER_SIZE_BYTES];
if(packet==null) packet=new DatagramPacket(buf, buf.length);
packet.setData(buf);
try {
socket.setSoTimeout(100);
socket.receive(packet);
if(packet != null && !availableInterfaces.contains("SmartEyeTDS")){
availableInterfaces.add("SmartEyeTDS");
buf=null; // reclaim memory
packet=null;
log.info("UDP Interface 'SmartEyeTDS' found");
}
} catch (IOException ex) {
//TODO:ugly exception handling
}
socket.close();
socket=null; // garbage collect, don't allow weak references to build up
} catch (SocketException ex) {
//TODO:ugly exception handling
}
}
/** @return the number of compatible monitor/sequencer attached to the driver
*/
@Override
synchronized public int getNumInterfacesAvailable() {
buildUdpIoList();
return availableInterfaces.size();
}
@Override
public String getGUID() {
return null;
}
} |
package cn.lambdalib.util.datapart;
import cn.lambdalib.networkcall.s11n.StorageOption.RangedTarget;
import cpw.mods.fml.common.FMLCommonHandler;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import cn.lambdalib.annoreg.core.Registrant;
import cn.lambdalib.networkcall.RegNetworkCall;
import cn.lambdalib.networkcall.s11n.InstanceSerializer;
import cn.lambdalib.networkcall.s11n.RegSerializable;
import cn.lambdalib.networkcall.s11n.SerializationManager;
import cn.lambdalib.networkcall.s11n.StorageOption.Data;
import cpw.mods.fml.relauncher.Side;
/**
* DataPart represents a single tickable data-storage object attached on an Entity.
* It is driven by the {@link EntityData} of this entity. <br>
*
* The DataPart is attached statically via {@link EntityData#register}
* method or @RegDataPart annotation (This should be done at init stages), and is automatically constructed
* on <em>first time querying</em>. At server, the {@link DataPart#fromNBT(NBTTagCompound)}
* method will be called right away, and the NBT will be sync to client ASAP. <br>
*
* Also when the world is being saved, the {@link DataPart#toNBT()} will be called to save stuffs
* in server. <br>
*
* A simple sync helper is provided. You can use sync() in both CLIENT and SERVER side to make a new NBT
* synchronization. However, for complex syncs you might want to consider using NetworkCall. <br>
*
* DataPart supports ticking by nature. Use setTick() to enable it. <br>
*
* For DataPart of EntityPlayer, all DataParts are kept except for those who called {@link DataPart#clearOnDeath()}
* in their ctor when player is respawned.
*
* @author WeAthFolD
*/
@Registrant
@RegSerializable(instance = DataPart.Serializer.class)
public abstract class DataPart<Ent extends Entity> {
// API
/**
* The default constructor must be kept for subclasses, for using reflections to create instance.
*/
public DataPart() {}
/**
* Invoked every tick if setTick() is called
*/
public void tick() {}
/**
* Set this DataPart to need ticking. Called in ctor.
*/
public final void setTick() {
tick = true;
}
/**
* Set this DataPart to be reset when entity is dead. Effective for EntityPlayer only. Called in ctor.
* (Other entities don't revive)
*/
public final void clearOnDeath() {
keepOnDeath = false;
}
/**
* Restore data of this DataPart from the NBT. Will be called externally only for world saving
*/
public abstract void fromNBT(NBTTagCompound tag);
/**
* Convert data of this DataPart to a NBT. Will be called externally only for world saving
*/
public abstract NBTTagCompound toNBT();
/**
* Same as fromNBT, but only get called when synchronizing across network.
*/
public void fromNBTSync(NBTTagCompound tag) { fromNBT(tag); }
/**
* Same as toNBT, but only get called when synchronizing across network.
*/
public NBTTagCompound toNBTSync() { return toNBT(); }
public Ent getEntity() {
return data.entity;
}
public boolean isRemote() {
return getEntity().worldObj.isRemote;
}
public <T extends DataPart> T getPart(String name) {
return data.getPart(name);
}
public <T extends DataPart> T getPart(Class<T> type) {
return data.getPart(type);
}
public String getName() {
return data.getName(this);
}
// Utils
protected void assertSide(Side side) {
if (FMLCommonHandler.instance().getEffectiveSide() != side) {
throw new RuntimeException("Invalid side, should be " + side);
}
}
// Internal
/**
* Internal sync flag, used to determine whether this part is init in client.
*/
boolean dirty = true;
int tickUntilQuery = 0;
/**
* The player instance when this data is available. Do NOT modify this field!
*/
EntityData<Ent> data;
boolean tick = false, keepOnDeath = true;
/**
* Return true if this data has received the initial sync.
* ALWAYS true in server.
*/
protected boolean isSynced() {
return !dirty;
}
protected void sync() {
if(isRemote()) {
syncFromClient(toNBTSync());
} else {
syncFromServer(getEntity(), toNBTSync());
}
}
@RegNetworkCall(side = Side.SERVER)
private void syncFromClient(@Data NBTTagCompound tag) {
fromNBTSync(tag);
}
@RegNetworkCall(side = Side.CLIENT)
private void syncFromServer(@RangedTarget(range = 10) Entity player, @Data NBTTagCompound tag) {
fromNBTSync(tag);
}
protected void checkSide(boolean isRemote) {
if(isRemote ^ isRemote()) {
throw new IllegalStateException("Wrong side: " + isRemote());
}
}
public static class Serializer implements InstanceSerializer<DataPart> {
InstanceSerializer entitySer = SerializationManager.INSTANCE.getInstanceSerializer(Entity.class);
@Override
public DataPart readInstance(NBTBase nbt) throws Exception {
NBTTagCompound tag = (NBTTagCompound) nbt;
NBTBase entityTag = tag.getTag("e");
if(entityTag != null) {
Entity e = (Entity) entitySer.readInstance(entityTag);
EntityData data = EntityData.get(e);
if(data != null) {
return data.getPart(tag.getString("n"));
}
}
return null;
}
@Override
public NBTBase writeInstance(DataPart obj) throws Exception {
NBTTagCompound ret = new NBTTagCompound();
NBTBase entityTag = entitySer.writeInstance(obj.getEntity());
ret.setTag("e", entityTag);
ret.setString("n", obj.getName());
return ret;
}
}
} |
package org.springframework.roo.model;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.roo.support.util.Assert;
import org.springframework.roo.support.util.StringUtils;
public final class JavaSymbolName implements Comparable<JavaSymbolName> {
/** Constant for keyword "true" */
public static final JavaSymbolName TRUE = new JavaSymbolName("true");
/** Constant for keyword "false" */
public static final JavaSymbolName FALSE = new JavaSymbolName("false");
private String symbolName;
public JavaSymbolName(String symbolName) {
Assert.hasText(symbolName, "Fully qualified type name required");
assertJavaNameLegal(symbolName);
this.symbolName = symbolName;
}
/**
* @return the symbol name (never null or empty)
*/
public String getSymbolName() {
return symbolName;
}
/**
* @return the symbol name, capitalising the first letter (never null or empty)
*/
public String getSymbolNameCapitalisedFirstLetter() {
return StringUtils.capitalize(symbolName);
}
/**
* @return the symbol name in human readable form
*/
public String getReadableSymbolName() {
String camelCase = symbolName;
return getReadableSymbolName(camelCase);
}
/**
* @return a camel case string in human readable form
*/
public static String getReadableSymbolName(String camelCase) {
Pattern p = Pattern.compile("[A-Z][^A-Z]*");
Matcher m = p.matcher(StringUtils.capitalize(camelCase));
StringBuilder string = new StringBuilder();
while (m.find()) {
string.append(m.group()).append(" ");
}
return string.toString().trim();
}
public final int hashCode() {
return this.symbolName.hashCode();
}
public final boolean equals(Object obj) {
// NB: Not using the normal convention of delegating to compareTo (for efficiency reasons)
return obj != null && obj instanceof JavaSymbolName && this.symbolName.equals(((JavaSymbolName) obj).symbolName);
}
public final int compareTo(JavaSymbolName o) {
// NB: If adding more fields to this class ensure the equals(Object) method is updated accordingly
if (o == null) return -1;
return this.symbolName.compareTo(o.symbolName);
}
public final String toString() {
return symbolName;
}
public static final void assertJavaNameLegal(String name) {
if (name == null) {
throw new IllegalArgumentException("Name required");
}
char[] value = name.toCharArray();
for (int i = 0; i < value.length; i++) {
char c = value[i];
if ('/' == c || ' ' == c || '*' == c || '>' == c || '<' == c || '!' == c || '@' == c || '%' == c || '^' == c ||
'?' == c || '(' == c || ')' == c || '~' == c || '`' == c || '{' == c || '}' == c || '[' == c || ']' == c ||
'|' == c || '\\' == c || '\'' == c || '+' == c) {
throw new IllegalArgumentException("Illegal name '" + name + "' (illegal character)");
}
if (i == 0) {
if ('1' == c || '2' == c || '3' == c || '4' == c || '5' == c || '6' == c || '7' == c || '8' == c || '9' == c || '0' == c) {
throw new IllegalArgumentException("Illegal name '" + name + "' (cannot start with a number)");
}
}
if (i + 1 == value.length || i == 0) {
if ('.' == c) {
throw new IllegalArgumentException("Illegal name '" + name + "' (cannot start or end with a period)");
}
}
}
}
} |
package net.somethingdreadful.MAL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import net.somethingdreadful.MAL.SearchActivity.networkThread;
import net.somethingdreadful.MAL.api.BaseMALApi;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.record.AnimeRecord;
import net.somethingdreadful.MAL.record.MangaRecord;
import net.somethingdreadful.MAL.sql.MALSqlHelper;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.sherlock.navigationdrawer.compat.SherlockActionBarDrawerToggle;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
public class Home extends BaseActionBarSearchView
implements ActionBar.TabListener, ItemGridFragment.IItemGridFragment,
LogoutConfirmationDialogFragment.LogoutConfirmationDialogListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
* sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will
* keep every loaded fragment in memory. If this becomes too memory intensive, it may be best
* to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
HomeSectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
Context context;
PrefManager mPrefManager;
public MALManager mManager;
private boolean init = false;
ItemGridFragment af;
ItemGridFragment mf;
public boolean instanceExists;
boolean networkAvailable;
BroadcastReceiver networkReceiver;
MenuItem searchItem;
int AutoSync = 0; //run or not to run.
static final String state_sync = "AutoSync"; //to solve bugs.
static final String state_mylist = "myList";
int listType = 0; //remembers the list_type.
private DrawerLayout mDrawerLayout;
private ListView listView;
private SherlockActionBarDrawerToggle mDrawerToggle;
private ActionBarHelper mActionBar;
View mActiveView;
View mPreviousView;
boolean myList = true; //tracks if the user is on 'My List' or not
public static final String[] DRAWER_OPTIONS =
{
"My List",
"Top Rated",
"Most Popular"
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
mPrefManager = new PrefManager(context);
init = mPrefManager.getInit();
//The following is state handling code
instanceExists = savedInstanceState != null && savedInstanceState.getBoolean("instanceExists", false);
networkAvailable = savedInstanceState == null || savedInstanceState.getBoolean("networkAvailable", true);
if (savedInstanceState != null) {
AutoSync = savedInstanceState.getInt(state_sync);
listType = savedInstanceState.getInt(state_mylist);
}
if (init) {
setContentView(R.layout.activity_home);
// Creates the adapter to return the Animu and Mango fragments
mSectionsPagerAdapter = new HomeSectionsPagerAdapter(getSupportFragmentManager());
mDrawerLayout= (DrawerLayout)findViewById(R.id.drawer_layout);
listView = (ListView)findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerListener(new DemoDrawerListener());
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
HomeListViewArrayAdapter adapter = new HomeListViewArrayAdapter(this,R.layout.list_item,DRAWER_OPTIONS);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new DrawerItemClickListener());
listView.setCacheColorHint(0);
listView.setScrollingCacheEnabled(false);
listView.setScrollContainer(false);
listView.setFastScrollEnabled(true);
listView.setSmoothScrollbarEnabled(true);
mActionBar = createActionBarHelper();
mActionBar.init();
mDrawerToggle = new SherlockActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer_light, R.string.drawer_open, R.string.drawer_close);
mDrawerToggle.syncState();
mManager = new MALManager(context);
if (!instanceExists) {
}
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setPageMargin(32);
// When swiping between different sections, select the corresponding
// tab.
// We can also use ActionBar.Tab#select() to do this if we have a
// reference to the
// Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// Add tabs for the animu and mango lists
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title
// defined by the adapter.
// Also specify this Activity object, which implements the
// TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
networkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
checkNetworkAndDisplayCrouton();
}
};
} else { //If the app hasn't been configured, take us to the first run screen to sign in.
Intent firstRunInit = new Intent(this, FirstTimeInit.class);
firstRunInit.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(firstRunInit);
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_home, menu);
searchItem = menu.findItem(R.id.action_search);
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public BaseMALApi.ListType getCurrentListType() {
String listName = getSupportActionBar().getSelectedTab().getText().toString();
return BaseMALApi.getListTypeByString(listName);
}
public boolean isConnectedWifi() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo Wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (Wifi.isConnected()&& mPrefManager.getonly_wifiEnabled() ) {
return true;
} else {
return false;
}
}
public void autosynctask(){
try {
if (AutoSync == 0 && isNetworkAvailable() && networkAvailable == true && mPrefManager.getsynchronisationEnabled()){
if (mPrefManager.getsynchronisationEnabled() && mPrefManager.getonly_wifiEnabled() == false){ //connected to Wi-Fi and sync only on Wi-Fi checked.
af.getRecords(af.currentList, "anime", true, this.context);
mf.getRecords(af.currentList, "manga", true, this.context);
syncNotify();
AutoSync = 1;
}else if (mPrefManager.getonly_wifiEnabled() && isConnectedWifi() && mPrefManager.getsynchronisationEnabled()){ //connected and sync always.
af.getRecords(af.currentList, "anime", true, this.context);
mf.getRecords(af.currentList, "manga", true, this.context);
syncNotify();
AutoSync = 1;
}
}else{
//will do nothing, sync is turned off or (sync only on Wi-Fi checked) and there is no Wi-Fi.
}
}catch (Exception e){
Crouton.makeText(this, "Error: autosynctask faild!", Style.ALERT).show();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.menu_settings:
startActivity(new Intent(this, Settings.class));
break;
case R.id.menu_logout:
showLogoutDialog();
break;
case R.id.menu_about:
startActivity(new Intent(this, AboutActivity.class));
break;
case R.id.listType_all:
if (af != null && mf != null) {
af.getRecords(0, "anime", false, this.context);
mf.getRecords(0, "manga", false, this.context);
listType = 0;
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_inprogress:
if (af != null && mf != null) {
af.getRecords(1, "anime", false, this.context);
mf.getRecords(1, "manga", false, this.context);
listType = 1;
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_completed:
if (af != null && mf != null) {
af.getRecords(2, "anime", false, this.context);
mf.getRecords(2, "manga", false, this.context);
listType = 2;
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_onhold:
if (af != null && mf != null) {
af.getRecords(3, "anime", false, this.context);
mf.getRecords(3, "manga", false, this.context);
listType = 3;
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_dropped:
if (af != null && mf != null) {
af.getRecords(4, "anime", false, this.context);
mf.getRecords(4, "manga", false, this.context);
listType = 4;
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_planned:
if (af != null && mf != null) {
af.getRecords(5, "anime", false, this.context);
mf.getRecords(5, "manga", false, this.context);
listType = 5;
supportInvalidateOptionsMenu();
}
break;
case R.id.forceSync:
if (af != null && mf != null) {
af.getRecords(af.currentList, "anime", true, this.context);
mf.getRecords(af.currentList, "manga", true, this.context);
syncNotify();
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResume() {
super.onResume();
/*if (instanceExists) {
af.getRecords(af.currentList, "anime", false, this.context);
mf.getRecords(af.currentList, "manga", false, this.context);
}*/
checkNetworkAndDisplayCrouton();
registerReceiver(networkReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
if (mSearchView != null) {
mSearchView.clearFocus();
mSearchView.setFocusable(false);
mSearchView.setQuery("", false);
searchItem.collapseActionView();
}
}
@Override
public void onPause() {
super.onPause();
instanceExists = true;
unregisterReceiver(networkReceiver);
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void fragmentReady() {
//Interface implementation for knowing when the dynamically created fragment is finished loading
//We use instantiateItem to return the fragment. Since the fragment IS instantiated, the method returns it.
af = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0);
mf = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 1);
listType = mPrefManager.getDefaultList(); //get chosen list :D
try { // if a error comes up it will not force close
getIntent().removeExtra("net.somethingdreadful.MAL.firstSync");
autosynctask();
}catch (Exception e){
}
}
@Override
public void onSaveInstanceState(Bundle state) {
//This is telling out future selves that we already have some things and not to do them
state.putBoolean("instanceExists", true);
state.putBoolean("networkAvailable", networkAvailable);
state.putInt(state_sync, AutoSync);
state.putInt(state_mylist, listType);
super.onSaveInstanceState(state);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.menu_listType);
if(!myList){//if not on my list then disable menu items like listType, etc
item.setEnabled(false);
item.setVisible(false);
}
else{
item.setEnabled(true);
item.setVisible(true);
}
if (af != null) {
//All this is handling the ticks in the switch list menu
switch (af.currentList) {
case 0:
menu.findItem(R.id.listType_all).setChecked(true);
break;
case 1:
menu.findItem(R.id.listType_inprogress).setChecked(true);
break;
case 2:
menu.findItem(R.id.listType_completed).setChecked(true);
break;
case 3:
menu.findItem(R.id.listType_onhold).setChecked(true);
break;
case 4:
menu.findItem(R.id.listType_dropped).setChecked(true);
break;
case 5:
menu.findItem(R.id.listType_planned).setChecked(true);
}
}
if (networkAvailable) {
if (myList){
menu.findItem(R.id.forceSync).setVisible(true);
}else{
menu.findItem(R.id.forceSync).setVisible(false);
}
menu.findItem(R.id.action_search).setVisible(true);
}
else {
menu.findItem(R.id.forceSync).setVisible(false);
menu.findItem(R.id.action_search).setVisible(false);
AutoSync = 1;
}
return true;
}
@SuppressLint("NewApi")
@Override
public void onLogoutConfirmed() {
mPrefManager.setInit(false);
mPrefManager.setUser("");
mPrefManager.setPass("");
mPrefManager.commitChanges();
context.deleteDatabase(MALSqlHelper.getHelper(context).getDatabaseName());
new ImageDownloader(context).wipeCache();
startActivity(new Intent(this, Home.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
finish();
}
private void syncNotify() {
Crouton.makeText(this, R.string.toast_SyncMessage, Style.INFO).show();
Intent notificationIntent = new Intent(context, Home.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification syncNotification = new NotificationCompat.Builder(context).setOngoing(true)
.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.icon)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.toast_SyncMessage))
.getNotification();
nm.notify(R.id.notification_sync, syncNotification);
myList = true;
supportInvalidateOptionsMenu();
}
private void showLogoutDialog() {
FragmentManager fm = getSupportFragmentManager();
LogoutConfirmationDialogFragment lcdf = new LogoutConfirmationDialogFragment();
if (Build.VERSION.SDK_INT >= 11) {
lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Dialog);
} else {
lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, 0);
}
lcdf.show(fm, "fragment_LogoutConfirmationDialog");
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
else {
return false;
}
}
public void checkNetworkAndDisplayCrouton() {
if (!isNetworkAvailable() && networkAvailable == true) {
Crouton.makeText(this, R.string.crouton_noConnectivityOnRun, Style.ALERT).show();
}
if (isNetworkAvailable() && networkAvailable == false) {
Crouton.makeText(this, R.string.crouton_connectionRestored, Style.INFO).show();
//TODO: Sync here, but first sync any records marked DIRTY
af.getRecords(af.currentList, "anime", true, this.context);
mf.getRecords(af.currentList, "manga", true, this.context);
syncNotify();
}
if (!isNetworkAvailable()) {
networkAvailable = false;
}
else {
networkAvailable = true;
}
supportInvalidateOptionsMenu();
}
/* thread & methods to fetch most popular anime/manga*/
//in order to reuse the code , 1 signifies a getPopular job and 2 signifies a getTopRated job. Probably a better way to do this
public void getMostPopular(BaseMALApi.ListType listType){
networkThread animethread = new networkThread(1);
animethread.setListType(BaseMALApi.ListType.ANIME);
animethread.execute(query);
/*networkThread mangathread = new networkThread(1);
mangathread.setListType(BaseMALApi.ListType.MANGA);
mangathread.execute(query);*/
//API doesn't support getting popular manga :/
}
public void getTopRated(BaseMALApi.ListType listType){
networkThread animethread = new networkThread(2);
animethread.setListType(BaseMALApi.ListType.ANIME);
animethread.execute(query);
/*networkThread mangathread = new networkThread(2);
mangathread.setListType(BaseMALApi.ListType.MANGA);
mangathread.execute(query);*/
//API doesn't support getting top rated manga :/
}
public class networkThread extends AsyncTask<String, Void, Void> {
JSONArray _result;
int job;
public networkThread(int job){
this.job = job;
}
public MALApi.ListType getListType() {
return listType;
}
public void setListType(MALApi.ListType listType) {
this.listType = listType;
}
MALApi.ListType listType;
@Override
protected Void doInBackground(String... params) {
try{
String query = params[0];
MALApi api = new MALApi(context);
switch (job){
case 1:
_result = api.getMostPopular(getListType(),1); //if job == 1 then get the most popular
break;
case 2:
_result = api.getTopRated(getListType(),1); //if job == 2 then get the top rated
break;
}
}catch (Exception e){
}
return null;
}
@Override
protected void onPostExecute(Void result) {
String type = MALApi.getListTypeString(getListType());
try {
switch (listType) {
case ANIME: {
ArrayList<AnimeRecord> list = new ArrayList<AnimeRecord>();
if (_result.length() == 0) {
System.out.println("No records");//TODO shouldnt return nothing, but...
}
else {
for (int i = 0; i < _result.length(); i++) {
JSONObject genre = (JSONObject) _result.get(i);
AnimeRecord record = new AnimeRecord(mManager.getRecordDataFromJSONObject(genre, type));
list.add(record);
}
}
af.setAnimeRecords(list);
break;
}
case MANGA: {
ArrayList<MangaRecord> list = new ArrayList<MangaRecord>();
if (_result.length() == 0) {
System.out.println("No records");//TODO shouldnt return nothing, but...
}
else {
for (int i = 0; i < _result.length(); i++) {
JSONObject genre = (JSONObject) _result.get(i);
MangaRecord record = new MangaRecord(mManager.getRecordDataFromJSONObject(genre, type));
list.add(record);
}
}
mf.setMangaRecords(list);
break;
}
}
} catch (JSONException e) {
Log.e(SearchActivity.class.getName(), Log.getStackTraceString(e));
}
Home.this.af.scrollListener.notifyMorePages();
}
}
/*private classes for nav drawer*/
private ActionBarHelper createActionBarHelper() {
return new ActionBarHelper();
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/* do stuff when drawer item is clicked here */
af.scrollToTop();
mf.scrollToTop();
switch (position){
case 0:
af.getRecords(listType, "anime", false, Home.this.context);
mf.getRecords(listType, "manga", false, Home.this.context);
myList = true;
af.setMode(0);
mf.setMode(0);
break;
case 1:
getTopRated(BaseMALApi.ListType.ANIME);
mf.setMangaRecords(new ArrayList<MangaRecord>()); ////basically, since you can't get popular manga this is just a temporary measure to make the manga set empty, otherwise it would continue to display YOUR manga list
myList = false;
af.setMode(1);
mf.setMode(1);
af.scrollListener.resetPageNumber();
mf.scrollListener.resetPageNumber();
break;
case 2:
getMostPopular(BaseMALApi.ListType.ANIME);
mf.setMangaRecords(new ArrayList<MangaRecord>()); //basically, since you can't get popular manga this is just a temporary measure to make the manga set empty, otherwise it would continue to display YOUR manga list
myList = false;
af.setMode(2);
mf.setMode(2);
af.scrollListener.resetPageNumber();
mf.scrollListener.resetPageNumber();
break;
}
//af.scrollToTop();
//mf.scrollToTop();
Home.this.supportInvalidateOptionsMenu();
//This part is for figuring out which item in the nav drawer is selected and highlighting it with colors
mPreviousView = mActiveView;
if (mPreviousView != null)
mPreviousView.setBackgroundColor(Color.parseColor("#333333")); //dark color
mActiveView = view;
mActiveView.setBackgroundColor(Color.parseColor("#38B2E1")); //blue color
mDrawerLayout.closeDrawer(listView);
}
}
private class DemoDrawerListener implements DrawerLayout.DrawerListener {
final ActionBar actionBar = getSupportActionBar();
@Override
public void onDrawerOpened(View drawerView) {
mDrawerToggle.onDrawerOpened(drawerView);
mActionBar.onDrawerOpened();
}
@Override
public void onDrawerClosed(View drawerView) {
mDrawerToggle.onDrawerClosed(drawerView);
mActionBar.onDrawerClosed();
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
mDrawerToggle.onDrawerSlide(drawerView, slideOffset);
}
@Override
public void onDrawerStateChanged(int newState) {
mDrawerToggle.onDrawerStateChanged(newState);
}
}
private class ActionBarHelper {
private final ActionBar mActionBar;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private ActionBarHelper() {
mActionBar = getSupportActionBar();
}
public void init() {
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setHomeButtonEnabled(true);
mTitle = mDrawerTitle = getTitle();
}
/**
* When the drawer is closed we restore the action bar state reflecting
* the specific contents in view.
*/
public void onDrawerClosed() {
mActionBar.setTitle(mTitle);
}
/**
* When the drawer is open we set the action bar to a generic title. The
* action bar should only contain data relevant at the top level of the
* nav hierarchy represented by the drawer, as the rest of your content
* will be dimmed down and non-interactive.
*/
public void onDrawerOpened() {
mActionBar.setTitle(mDrawerTitle);
}
public void setTitle(CharSequence title) {
mTitle = title;
}
}
} |
package co.phoenixlab.discord;
import com.google.gson.Gson;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sx.blah.discord.DiscordClient;
import sx.blah.discord.handle.IDispatcher;
import sx.blah.discord.handle.IListener;
import sx.blah.discord.handle.impl.events.MessageReceivedEvent;
import sx.blah.discord.handle.impl.events.ReadyEvent;
import sx.blah.discord.handle.obj.Message;
import java.io.IOException;
import java.io.Reader;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class VahrhedralBot implements Runnable {
public static final Logger LOGGER = LoggerFactory.getLogger("VahrhedralBot");
public static void main(String[] args) {
LOGGER.info("Starting Vahrhedral bot");
try {
VahrhedralBot bot = new VahrhedralBot();
bot.run();
} catch (Exception e) {
LOGGER.error("Fatal error while starting bot", e);
}
}
private DiscordClient discord;
private Configuration config;
public VahrhedralBot() {
discord = DiscordClient.get();
}
@Override
public void run() {
// TODO
// Load Config
try {
config = loadConfiguration(Paths.get("config/config.json"));
} catch (IOException e) {
LOGGER.error("Unable to load configuration", e);
return;
}
// Register our event listeners first
registerEventListeners();
LOGGER.info("Logging in using {}", config.getEmail());
try {
discord.login(config.getEmail(), config.getPassword());
} catch (IOException | ParseException | URISyntaxException e) {
LOGGER.error("Unable to log in", e);
return;
}
if (!discord.isReady()) {
LOGGER.error("Discord client is not ready");
return;
}
}
private Configuration loadConfiguration(Path path) throws IOException {
Gson configGson = new Gson();
try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
return configGson.fromJson(reader, Configuration.class);
}
}
private void registerEventListeners() {
IDispatcher dispatcher = discord.getDispatcher();
dispatcher.registerListener((IListener<ReadyEvent>)this::onReadyEvent);
dispatcher.registerListener((IListener<MessageReceivedEvent>)this::onMessageRecievedEvent);
}
private void onReadyEvent(ReadyEvent event) {
LOGGER.info("Successfully connected as {}", discord.getOurUser().getName());
}
private void onMessageRecievedEvent(MessageReceivedEvent event) {
Message msg = event.getMessage();
LOGGER.info("Message from {}
msg.getChannel().getParent().getName(),
msg.getChannel().getName(),
msg.getAuthor().getName(),
msg.getContent());
}
} |
package net.somethingdreadful.MAL;
import android.annotation.SuppressLint;
import android.app.FragmentManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.SearchView;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import net.somethingdreadful.MAL.account.AccountService;
import net.somethingdreadful.MAL.adapters.IGFPagerAdapter;
import net.somethingdreadful.MAL.adapters.NavigationDrawerAdapter;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.dialog.LogoutConfirmationDialogFragment;
import net.somethingdreadful.MAL.dialog.UpdatePasswordDialogFragment;
import net.somethingdreadful.MAL.sql.MALSqlHelper;
import net.somethingdreadful.MAL.tasks.APIAuthenticationErrorListener;
import net.somethingdreadful.MAL.tasks.TaskJob;
public class Home extends ActionBarActivity implements SwipeRefreshLayout.OnRefreshListener, IGFCallbackListener, APIAuthenticationErrorListener {
IGF af;
IGF mf;
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
* sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will
* keep every loaded fragment in memory. If this becomes too memory intensive, it may be best
* to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
IGFPagerAdapter mIGFPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
Context context;
PrefManager mPrefManager;
Menu menu;
BroadcastReceiver networkReceiver;
DrawerLayout DrawerLayout;
ListView DrawerList;
ActionBarDrawerToggle mDrawerToggle;
View mPreviousView;
ActionBar actionBar;
NavigationDrawerAdapter mNavigationDrawerAdapter;
SearchView searchView;
boolean instanceExists;
boolean networkAvailable;
boolean myList = true; //tracks if the user is on 'My List' or not
boolean callbackAnimeError = false;
boolean callbackMangaError = false;
int callbackCounter = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
if (AccountService.getAccount(context) != null) {
mPrefManager = new PrefManager(context);
actionBar = getSupportActionBar();
//setSupportActionBar(toolbar);
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
//actionBar.setHomeButtonEnabled(true);
}
//The following is state handling code
instanceExists = savedInstanceState != null && savedInstanceState.getBoolean("instanceExists", false);
networkAvailable = savedInstanceState == null || savedInstanceState.getBoolean("networkAvailable", true);
if (savedInstanceState != null) {
myList = savedInstanceState.getBoolean("myList");
}
setContentView(R.layout.activity_home);
// Creates the adapter to return the Animu and Mango fragments
mIGFPagerAdapter = new IGFPagerAdapter(getFragmentManager());
DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
DrawerLayout.setDrawerListener(new DemoDrawerListener());
DrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
DrawerList = (ListView) findViewById(R.id.left_drawer);
NavigationItems mNavigationContent = new NavigationItems();
mNavigationDrawerAdapter = new NavigationDrawerAdapter(this, mNavigationContent.ITEMS);
DrawerList.setAdapter(mNavigationDrawerAdapter);
DrawerList.setOnItemClickListener(new DrawerItemClickListener());
DrawerList.setCacheColorHint(0);
DrawerList.setScrollingCacheEnabled(false);
DrawerList.setScrollContainer(false);
DrawerList.setFastScrollEnabled(true);
DrawerList.setSmoothScrollbarEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, DrawerLayout, R.string.drawer_open, R.string.drawer_close);
mDrawerToggle.syncState();
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mIGFPagerAdapter);
mViewPager.setPageMargin(32);
networkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
checkNetworkAndDisplayCrouton();
}
};
} else {
Intent firstRunInit = new Intent(this, FirstTimeInit.class);
startActivity(firstRunInit);
finish();
}
NfcHelper.disableBeam(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_home, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
ComponentName cn = new ComponentName(this, SearchActivity.class);
searchView.setSearchableInfo(searchManager.getSearchableInfo(cn));
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.menu_settings:
startActivity(new Intent(this, Settings.class));
break;
case R.id.menu_logout:
showLogoutDialog();
break;
case R.id.menu_about:
startActivity(new Intent(this, AboutActivity.class));
break;
case R.id.listType_all:
if (af != null && mf != null) {
af.getRecords(true, TaskJob.GETLIST, 0);
mf.getRecords(true, TaskJob.GETLIST, 0);
setChecked(item);
}
break;
case R.id.listType_inprogress:
if (af != null && mf != null) {
af.getRecords(true, TaskJob.GETLIST, 1);
mf.getRecords(true, TaskJob.GETLIST, 1);
setChecked(item);
}
break;
case R.id.listType_completed:
if (af != null && mf != null) {
af.getRecords(true, TaskJob.GETLIST, 2);
mf.getRecords(true, TaskJob.GETLIST, 2);
setChecked(item);
}
break;
case R.id.listType_onhold:
if (af != null && mf != null) {
af.getRecords(true, TaskJob.GETLIST, 3);
mf.getRecords(true, TaskJob.GETLIST, 3);
setChecked(item);
}
break;
case R.id.listType_dropped:
if (af != null && mf != null) {
af.getRecords(true, TaskJob.GETLIST, 4);
mf.getRecords(true, TaskJob.GETLIST, 4);
setChecked(item);
}
break;
case R.id.listType_planned:
if (af != null && mf != null) {
af.getRecords(true, TaskJob.GETLIST, 5);
mf.getRecords(true, TaskJob.GETLIST, 5);
setChecked(item);
}
break;
case R.id.forceSync:
synctask(true);
break;
case R.id.menu_inverse:
if (af != null && mf != null) {
af.inverse();
mf.inverse();
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResume() {
super.onResume();
checkNetworkAndDisplayCrouton();
registerReceiver(networkReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
}
@SuppressLint("NewApi")
@Override
public void onPause() {
super.onPause();
if (menu != null)
menu.findItem(R.id.action_search).collapseActionView();
instanceExists = true;
unregisterReceiver(networkReceiver);
}
public void synctask(boolean clear) {
if (af != null && mf != null) {
af.getRecords(clear, TaskJob.FORCESYNC, af.list);
mf.getRecords(clear, TaskJob.FORCESYNC, mf.list);
syncNotify();
}
}
@Override
public void onSaveInstanceState(Bundle state) {
//This is telling out future selves that we already have some things and not to do them
state.putBoolean("instanceExists", true);
state.putBoolean("networkAvailable", networkAvailable);
state.putBoolean("myList", myList);
super.onSaveInstanceState(state);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
this.menu = menu;
myListChanged();
if (af != null) {
//All this is handling the ticks in the switch list menu
switch (af.list) {
case 0:
setChecked(menu.findItem(R.id.listType_all));
break;
case 1:
setChecked(menu.findItem(R.id.listType_inprogress));
break;
case 2:
setChecked(menu.findItem(R.id.listType_completed));
break;
case 3:
setChecked(menu.findItem(R.id.listType_onhold));
break;
case 4:
setChecked(menu.findItem(R.id.listType_dropped));
break;
case 5:
setChecked(menu.findItem(R.id.listType_planned));
}
}
return true;
}
public void setChecked(MenuItem item) {
item.setChecked(true);
}
public void myListChanged() {
MenuItem item = menu.findItem(R.id.menu_listType);
if (!myList) {//if not on my list then disable menu items like listType, etc
item.setEnabled(false);
item.setVisible(false);
} else {
item.setEnabled(true);
item.setVisible(true);
}
if (networkAvailable) {
if (myList) {
menu.findItem(R.id.menu_inverse).setVisible(true);
menu.findItem(R.id.forceSync).setVisible(true);
} else {
menu.findItem(R.id.menu_inverse).setVisible(false);
menu.findItem(R.id.forceSync).setVisible(false);
}
menu.findItem(R.id.action_search).setVisible(true);
} else {
menu.findItem(R.id.forceSync).setVisible(false);
menu.findItem(R.id.action_search).setVisible(false);
}
}
@SuppressLint("NewApi")
public void onLogoutConfirmed() {
if (af != null)
af.cancelNetworkTask();
if (mf != null)
mf.cancelNetworkTask();
MALSqlHelper.getHelper(context).deleteDatabase(context);
AccountService.deleteAccount(context);
startActivity(new Intent(this, Home.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
finish();
}
private void syncNotify() {
Intent notificationIntent = new Intent(context, Home.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder syncNotificationBuilder = new Notification.Builder(context).setOngoing(true)
.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.icon)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.toast_info_SyncMessage));
Notification syncNotification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
syncNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
}
syncNotification = syncNotificationBuilder.build();
} else {
syncNotification = syncNotificationBuilder.getNotification();
}
nm.notify(R.id.notification_sync, syncNotification);
}
private void showLogoutDialog() {
FragmentManager fm = getFragmentManager();
LogoutConfirmationDialogFragment lcdf = new LogoutConfirmationDialogFragment();
lcdf.show(fm, "fragment_LogoutConfirmationDialog");
}
public void checkNetworkAndDisplayCrouton() {
if (MALApi.isNetworkAvailable(context) && !networkAvailable) {
synctask(false);
}
networkAvailable = MALApi.isNetworkAvailable(context);
}
@Override
public void onRefresh() {
if (networkAvailable)
synctask(false);
else {
if (af != null && mf != null) {
af.toggleSwipeRefreshAnimation(false);
mf.toggleSwipeRefreshAnimation(false);
}
Toast.makeText(context, R.string.toast_error_noConnectivity, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onIGFReady(IGF igf) {
igf.setUsername(AccountService.getUsername(context));
if (igf.listType.equals(MALApi.ListType.ANIME))
af = igf;
else
mf = igf;
// do forced sync after FirstInit
if (mPrefManager.getForceSync()) {
if (af != null && mf != null) {
mPrefManager.setForceSync(false);
mPrefManager.commitChanges();
synctask(true);
}
} else {
if (igf.taskjob == null) {
igf.getRecords(true, TaskJob.GETLIST, mPrefManager.getDefaultList());
}
}
}
@Override
public void onRecordsLoadingFinished(MALApi.ListType type, TaskJob job, boolean error, boolean resultEmpty, boolean cancelled) {
if (cancelled && !job.equals(TaskJob.FORCESYNC)) {
return;
}
callbackCounter++;
if (type.equals(MALApi.ListType.ANIME))
callbackAnimeError = error;
else
callbackMangaError = error;
if (callbackCounter >= 2) {
callbackCounter = 0;
if (job.equals(TaskJob.FORCESYNC)) {
NotificationManager nm = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(R.id.notification_sync);
if (callbackAnimeError && callbackMangaError) // the sync failed completely
Toast.makeText(context, R.string.toast_error_SyncFailed, Toast.LENGTH_SHORT).show();
else if (callbackAnimeError || callbackMangaError) // one list failed to sync
Toast.makeText(context, callbackAnimeError ? R.string.toast_error_Anime_Sync : R.string.toast_error_Manga_Sync, Toast.LENGTH_SHORT).show();
} else {
if (callbackAnimeError && callbackMangaError) // the sync failed completely
Toast.makeText(context, R.string.toast_error_Records, Toast.LENGTH_SHORT).show();
else if (callbackAnimeError || callbackMangaError) // one list failed to sync
Toast.makeText(context, callbackAnimeError ? R.string.toast_error_Anime_Records : R.string.toast_error_Manga_Records, Toast.LENGTH_SHORT).show();
// no else here, there is nothing to be shown when everything went well
}
}
}
@Override
public void onAPIAuthenticationError(MALApi.ListType type, TaskJob job) {
// check if it is already showing
if (getFragmentManager().findFragmentByTag("fragment_updatePassword") == null) {
FragmentManager fm = getFragmentManager();
UpdatePasswordDialogFragment passwordFragment = new UpdatePasswordDialogFragment();
passwordFragment.show(fm, "fragment_updatePassword");
}
}
public class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!networkAvailable && position > 2) {
position = 1;
Toast.makeText(context, R.string.toast_error_noConnectivity, Toast.LENGTH_SHORT).show();
}
myList = ((position <= 2 && myList) || position == 1);
myListChanged();
// disable swipeRefresh for other lists
af.setSwipeRefreshEnabled(myList);
mf.setSwipeRefreshEnabled(myList);
switch (position) {
case 0:
Intent Profile = new Intent(context, net.somethingdreadful.MAL.ProfileActivity.class);
Profile.putExtra("username", AccountService.getUsername(context));
startActivity(Profile);
break;
case 1:
af.getRecords(true, TaskJob.GETLIST, af.list);
mf.getRecords(true, TaskJob.GETLIST, mf.list);
break;
case 2:
Intent Friends = new Intent(context, net.somethingdreadful.MAL.FriendsActivity.class);
startActivity(Friends);
break;
case 3:
af.getRecords(true, TaskJob.GETTOPRATED, af.list);
mf.getRecords(true, TaskJob.GETTOPRATED, mf.list);
break;
case 4:
af.getRecords(true, TaskJob.GETMOSTPOPULAR, af.list);
mf.getRecords(true, TaskJob.GETMOSTPOPULAR, mf.list);
break;
case 5:
af.getRecords(true, TaskJob.GETJUSTADDED, af.list);
mf.getRecords(true, TaskJob.GETJUSTADDED, mf.list);
break;
case 6:
af.getRecords(true, TaskJob.GETUPCOMING, af.list);
mf.getRecords(true, TaskJob.GETUPCOMING, mf.list);
break;
}
/*
* This part is for figuring out which item in the nav drawer is selected and highlighting it with colors.
*/
if (position != 0 && position != 2) {
if (mPreviousView != null)
mPreviousView.setBackgroundColor(getResources().getColor(R.color.bg_dark)); //normal color
view.setBackgroundColor(getResources().getColor(android.R.color.black)); // dark color
mPreviousView = view;
} else {
view.setBackgroundColor(getResources().getColor(R.color.bg_dark));
}
DrawerLayout.closeDrawer(DrawerList);
}
}
private class DemoDrawerListener implements DrawerLayout.DrawerListener {
@Override
public void onDrawerOpened(View drawerView) {
mDrawerToggle.onDrawerOpened(drawerView);
actionBar.setTitle(getTitle());
}
@Override
public void onDrawerClosed(View drawerView) {
mDrawerToggle.onDrawerClosed(drawerView);
actionBar.setTitle(getTitle());
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
mDrawerToggle.onDrawerSlide(drawerView, slideOffset);
}
@Override
public void onDrawerStateChanged(int newState) {
mDrawerToggle.onDrawerStateChanged(newState);
}
}
} |
package application;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Set;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.chart.AreaChart;
import javafx.scene.chart.PieChart;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import java.util.ArrayList;
import java.util.HashSet;
/**
* Controller for GPA-Calculator
* Last modified: 4/26/17
* @author GPA-Calculator Team
* This program calculates your GPA based on credits/grade. Also has graph/chart feature.
*/
public class Controller implements Initializable
{
@FXML
private GridPane inputGrid;
@FXML
private Text text0;
@FXML
private TextField creditsInput0;
@FXML
private Text text00;
@FXML
private ComboBox<String> gradeInput0;
@FXML
private Button removeButton0;
@FXML
private Text text1;
@FXML
private TextField creditsInput1;
@FXML
private Text text11;
@FXML
private ComboBox<String> gradeInput1;
@FXML
private Button removeButton1;
@FXML
private Text text2;
@FXML
private TextField creditsInput2;
@FXML
private Text text22;
@FXML
private ComboBox<String> gradeInput2;
@FXML
private Button removeButton2;
@FXML
private Text gpaOutput;
@FXML
private Text cumGPAOutput;
@FXML
private Button calcButton;
@FXML
private Button addButton;
@FXML
private Button saveButton;
@FXML
private Button newButton;
@FXML
private AreaChart<String, Double> graph;
@FXML
private PieChart pieChart;
private final Model model = new Model();
private Text creditsName;
private TextField creditsInput;
private Text gradeName;
private ComboBox<String> gradeInput;
private Button removeButton;
private ArrayList<TextField> listOfCredits = new ArrayList<TextField>();
private ArrayList<ComboBox<String>> listOfGrades = new ArrayList<ComboBox<String>>();
//Written by: Elizabeth Nondorf and Emily Black
@FXML
private void calculateGPA(ActionEvent e)
{
//If we have no fields
if(model.getNumOfRows() == 0)
{
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("ERROR: NO FIELD(S) FOUND.");
alert.setContentText("Please make sure you have at least one row filled out before calculating your GPA.");
alert.showAndWait();
return;
}
//If any input fields are empty
for(int i = 0; i < model.getNumOfRows(); i++)
{
if(listOfCredits.get(i).getText().equals("") || listOfGrades.get(i).getValue() == null)
{
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("ERROR: EMPTY FIELD(S).");
alert.setContentText("Please make sure you have completely filled out the form before calculating your GPA.");
alert.showAndWait();
return;
}
}
saveButton.setDisable(false);
newButton.setDisable(false);
/*Gives the calculator all of the credits*/
model.setCredits(listOfCredits);
/*Gvies the calculator all of the values from the grades*/
model.setGradeList(listOfGrades);
/*Calculate the gpa after error checking*/
model.calculateGPA();
/*Makes the data visible*/
gpaOutput.setText(model.getCurrGpa() + "");
cumGPAOutput.setText(model.getCumGpa() + "");
}
//Written by: Emily Black
@SuppressWarnings({ "unchecked" })
@FXML
private void addRow(ActionEvent e)
{
saveButton.setDisable(true);
newButton.setDisable(true);
creditsName = new Text("Credits:");
creditsName.fontProperty().setValue(new Font(15));
creditsName.setId("text" + model.getNumOfRows());
creditsInput = new TextField();
creditsInput.addEventFilter(KeyEvent.KEY_TYPED , numericalValue(2));
creditsInput.setPromptText("Ex: 3");
listOfCredits.add(creditsInput);
creditsInput.setId("creditsInput" + model.getNumOfRows());
gradeName = new Text("Grade:");
gradeName.fontProperty().setValue(new Font(15));
gradeName.setId("text" + model.getNumOfRows() + "" + model.getNumOfRows());
gradeInput = new ComboBox<String>();
gradeInput.getItems().addAll("A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F");
listOfGrades.add(gradeInput);
gradeInput.setId("gradeInput" + model.getNumOfRows());
removeButton = new Button("-");
removeButton.fontProperty().setValue(new Font(15));
removeButton.setId("removeButton" + model.getNumOfRows());
removeButton.setOnAction(event1 -> {
removeRow(event1);
});
inputGrid.add(creditsName, 0, model.getNumOfRows());
inputGrid.add(creditsInput, 1, model.getNumOfRows());
inputGrid.add(gradeName, 2, model.getNumOfRows());
inputGrid.add(gradeInput, 3, model.getNumOfRows());
inputGrid.add(removeButton, 4, model.getNumOfRows());
model.setNumOfRows(model.getNumOfRows()+1);
}
//Written by: Emily Black and Elizabeth Nondorf and Stephanie Whitworth
@SuppressWarnings("unchecked")
@FXML
private void saveSemester(ActionEvent e)
{
//Check for input
if(gpaOutput.getText() == null)
{
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("ERROR: EMPTY GPA");
alert.setContentText("Please make sure you calculate your GPA before saving your semester.");
alert.showAndWait();
return;
}
else
{
//create the series data
model.setSeries(Double.parseDouble(gpaOutput.getText()));
//increment the number of semesters
model.incrementSemesters();
graph.getData().clear(); //clears data so we dont add duplicates
graph.getData().addAll(model.getSeries());
graph.setLegendVisible(false);
//we let model know that it is saved
model.setSaved(true);
pieChart.setData(model.createPieData());
pieChart.setLegendVisible(false);
}
}
//Written by: Elizabeth Nondorf and Stephanie Whitworth
@SuppressWarnings("unchecked")
@FXML
private void newSemester(ActionEvent e)
{
// save semester & clear elements if we have gpa to save
if(gpaOutput.getText() == null)
{
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("ERROR: EMPTY GPA");
alert.setContentText("Please make sure you calculate your GPA before saving your semester.");
alert.showAndWait();
return;
}
else
{
//If we havent saved
if(model.isSaved() == false)
{
//create the series data
model.setSeries(Double.parseDouble(gpaOutput.getText()));
//increment the number of semesters
model.incrementSemesters();
graph.getData().clear(); //clears data so we dont add duplicates
graph.getData().addAll(model.getSeries());
graph.setLegendVisible(false);
//we let model know that it is saved
model.setSaved(true);
pieChart.setData(model.createPieData());
pieChart.setLegendVisible(false);
}
//If we have saved
if(model.isSaved() == true)
{
// clear grid
for(int i = model.getNumOfRows(); i > 2; i
{
int row = i;
Set<Node> deleteNodes = new HashSet<>(5);
for (Node child : inputGrid.getChildren()) {
// get index from child
Integer rowIndex = GridPane.getRowIndex(child);
// handle null values for index=0
int r = rowIndex == null ? 0 : rowIndex;
if (r > row) {
// decrement rows for rows after the deleted row
GridPane.setRowIndex(child, r-1);
} else if (r == row) {
// collect matching rows for deletion
deleteNodes.add(child);
child.setManaged(false);
}
}
// remove nodes from row
inputGrid.getChildren().removeAll(deleteNodes);
}
//Remove extra rows from list
for(int j = model.getNumOfRows()-1; j > 3; j
{
listOfCredits.remove(listOfCredits.get(j));
listOfGrades.remove(listOfGrades.get(j));
}
model.setNumOfRows(3);
//Clear first 3 rows
for(int k = 0; k < model.getNumOfRows(); k++)
{
listOfCredits.get(k).clear();
listOfGrades.get(k).valueProperty().set(null);
}
//Clear the data in the model
model.clearData();
}
gpaOutput.setText("");
model.setSaved(false);
saveButton.setDisable(true);
newButton.setDisable(true);
}
}
//Written by: Emily Black
@FXML
private void removeRow(ActionEvent event)
{
@SuppressWarnings("static-access")
int row = inputGrid.getRowIndex((Node) event.getSource());
ArrayList<Node> deleteNodes = new ArrayList<Node>(5);
for (Node child : inputGrid.getChildren()) {
// get index from child
Integer rowIndex = GridPane.getRowIndex(child);
// handle null values for index=0
int r = rowIndex == null ? 0 : rowIndex;
if (r > row) {
// decrement rows for rows after the deleted row
GridPane.setRowIndex(child, r-1);
} else if (r == row) {
// collect matching rows for deletion
deleteNodes.add(child);
child.setManaged(false);
}
}
inputGrid.getChildren().removeAll(deleteNodes);
model.setNumOfRows(model.getNumOfRows()-1);
listOfGrades.remove(row);
model.setGradeList(listOfGrades);
listOfCredits.remove(row);
for(int i = 0; i < listOfCredits.size(); i++)
{
System.out.println(listOfCredits.get(i).getText());
}
model.setCredits(listOfCredits);
}
//Written by: Emily Black and Elizabeth Nondorf
@SuppressWarnings({ "unchecked" })
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
saveButton.setDisable(true);
newButton.setDisable(true);
listOfCredits.add(creditsInput0);
gradeInput0.getItems().addAll("A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F");
listOfGrades.add(gradeInput0);
listOfCredits.add(creditsInput1);
gradeInput1.getItems().addAll("A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F");
listOfGrades.add(gradeInput1);
listOfCredits.add(creditsInput2);
gradeInput2.getItems().addAll("A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F");
listOfGrades.add(gradeInput2);
creditsInput0.addEventFilter(KeyEvent.KEY_TYPED , numericalValue(2));
creditsInput1.addEventFilter(KeyEvent.KEY_TYPED , numericalValue(2));
creditsInput2.addEventFilter(KeyEvent.KEY_TYPED , numericalValue(2));
}
//Written by: Emily Black
@SuppressWarnings("rawtypes")
private EventHandler numericalValue(int maxLength)
{
return new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent e) {
TextField txt_TextField = (TextField) e.getSource();
if (txt_TextField.getText().length() >= maxLength) {
e.consume();
}
if(e.getCharacter().matches("[0-9]")){
if(txt_TextField.getText().contains(".") && e.getCharacter().matches("[.]")){
e.consume();
}else if(txt_TextField.getText().length() == 0 && e.getCharacter().matches("[.]")){
e.consume();
}
}else{
e.consume();
}
}
};
}
} |
package com.almasb.fxgl.app;
import com.almasb.fxeventbus.EventBus;
import com.almasb.fxgl.asset.AssetLoader;
import com.almasb.fxgl.audio.AudioPlayer;
import com.almasb.fxgl.event.FXGLEvent;
import com.almasb.fxgl.gameplay.AchievementManager;
import com.almasb.fxgl.gameplay.NotificationService;
import com.almasb.fxgl.input.Input;
import com.almasb.fxgl.logging.Logger;
import com.almasb.fxgl.logging.SystemLogger;
import com.almasb.fxgl.scene.Display;
import com.almasb.fxgl.settings.GameSettings;
import com.almasb.fxgl.settings.ReadOnlyGameSettings;
import com.almasb.fxgl.time.MasterTimer;
import com.almasb.fxgl.util.ExceptionHandler;
import com.almasb.fxgl.util.FXGLCheckedExceptionHandler;
import com.almasb.fxgl.util.Version;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.stage.Stage;
import java.io.IOException;
import java.io.InputStream;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
/**
* General FXGL application that configures services for all parts to use.
*
* @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com)
*/
public abstract class FXGLApplication extends Application {
/**
* We use system logger because logger service is not yet ready.
*/
private static final Logger log = SystemLogger.INSTANCE;
static {
Version.print();
setDefaultCheckedExceptionHandler(new FXGLCheckedExceptionHandler());
}
private static ExceptionHandler defaultCheckedExceptionHandler;
/**
* @return handler for checked exceptions
*/
public static ExceptionHandler getDefaultCheckedExceptionHandler() {
return defaultCheckedExceptionHandler;
}
/**
* Set handler for checked exceptions.
*
* @param handler exception handler
*/
public static final void setDefaultCheckedExceptionHandler(ExceptionHandler handler) {
defaultCheckedExceptionHandler = error -> {
log.warning("Checked Exception:");
log.warning(SystemLogger.INSTANCE.errorTraceAsString(error));
handler.handle(error);
};
}
@Override
public final void init() throws Exception {
log.debug("Initializing FXGL");
}
@Override
public void start(Stage stage) throws Exception {
log.debug("Starting FXGL");
initSystemProperties();
initUserProperties();
initAppSettings();
FXGL.configure(this, stage);
log.debug("FXGL configuration complete");
}
@Override
public final void stop() {
log.debug("Exiting FXGL");
}
/**
* Pause the application.
*/
protected void pause() {
log.debug("Pausing main loop");
getEventBus().fireEvent(FXGLEvent.pause());
}
/**
* Resume the application.
*/
protected void resume() {
log.debug("Resuming main loop");
getEventBus().fireEvent(FXGLEvent.resume());
}
/**
* Reset the application.
*/
protected void reset() {
log.debug("Resetting FXGL application");
getEventBus().fireEvent(FXGLEvent.reset());
}
/**
* Exit the application.
* Safe to call this from a paused state.
*/
protected void exit() {
log.debug("Exiting Normally");
getEventBus().fireEvent(FXGLEvent.exit());
log.close();
stop();
Platform.exit();
System.exit(0);
}
/**
* Load FXGL system properties.
*/
private void initSystemProperties() {
log.debug("Initializing system properties");
ResourceBundle props = ResourceBundle.getBundle("com.almasb.fxgl.app.system");
props.keySet().forEach(key -> {
Object value = props.getObject(key);
FXGL.setProperty(key, value);
log.debug(key + " = " + value);
});
}
/**
* Load user defined properties to override FXGL system properties.
*/
private void initUserProperties() {
log.debug("Initializing user properties");
// services are not ready yet, so load manually
try (InputStream is = getClass().getResource("/assets/properties/system.properties").openStream()) {
ResourceBundle props = new PropertyResourceBundle(is);
props.keySet().forEach(key -> {
Object value = props.getObject(key);
FXGL.setProperty(key, value);
log.debug(key + " = " + value);
});
} catch (NullPointerException npe) {
log.info("User properties not found. Using system");
} catch (IOException e) {
log.warning("Loading user properties failed: " + e.getMessage());
}
}
/**
* Take app settings from user.
*/
private void initAppSettings() {
log.debug("Initializing app settings");
GameSettings localSettings = new GameSettings();
initSettings(localSettings);
settings = localSettings.toReadOnly();
}
/**
* Settings for this game instance. This is an internal copy
* of the settings so that they will not be modified during game lifetime.
*/
private ReadOnlyGameSettings settings;
/**
* @return read only copy of game settings
*/
public final ReadOnlyGameSettings getSettings() {
return settings;
}
/**
* Initialize app settings.
*
* @param settings app settings
*/
protected abstract void initSettings(GameSettings settings);
/**
* Returns target width of the application. This is the
* width that was set using GameSettings.
* Note that the resulting
* width of the scene might be different due to end user screen, in
* which case transformations will be automatically scaled down
* to ensure identical image on all screens.
*
* @return target width
*/
public final double getWidth() {
return getSettings().getWidth();
}
/**
* Returns target height of the application. This is the
* height that was set using GameSettings.
* Note that the resulting
* height of the scene might be different due to end user screen, in
* which case transformations will be automatically scaled down
* to ensure identical image on all screens.
*
* @return target height
*/
public final double getHeight() {
return getSettings().getHeight();
}
/**
* Returns the visual area within the application window,
* excluding window borders. Note that it will return the
* rectangle with set target width and height, not actual
* screen width and height. Meaning on smaller screens
* the area will correctly return the GameSettings' width and height.
* <p>
* Equivalent to new Rectangle2D(0, 0, getWidth(), getHeight()).
*
* @return screen bounds
*/
public final Rectangle2D getScreenBounds() {
return new Rectangle2D(0, 0, getWidth(), getHeight());
}
/**
* @return current tick
*/
public final long getTick() {
return getMasterTimer().getTick();
}
/**
* @return current time since start of game in nanoseconds
*/
public final long getNow() {
return getMasterTimer().getNow();
}
/**
* @return event bus
*/
public final EventBus getEventBus() {
return FXGL.getEventBus();
}
/**
* @return display service
*/
public final Display getDisplay() {
return FXGL.getDisplay();
}
/**
* @return input service
*/
public final Input getInput() {
return FXGL.getInput();
}
/**
* @return audio player
*/
public final AudioPlayer getAudioPlayer() {
return FXGL.getAudioPlayer();
}
/**
* @return asset loader
*/
public final AssetLoader getAssetLoader() {
return FXGL.getAssetLoader();
}
/**
* @return master timer
*/
public final MasterTimer getMasterTimer() {
return FXGL.getMasterTimer();
}
/**
* @return notification service
*/
public final NotificationService getNotificationService() {
return FXGL.getNotificationService();
}
/**
* @return achievement manager
*/
public final AchievementManager getAchievementManager() {
return FXGL.getAchievementManager();
}
} |
package org.objectweb.asm.attrs;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ByteVector;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
public class SourceDebugExtensionAttribute extends Attribute {
private String debugExtension;
public SourceDebugExtensionAttribute() {
super( "SourceDebugExtension");
}
public SourceDebugExtensionAttribute( String debugExtension) {
this();
this.debugExtension = debugExtension;
}
public String getDebugExtension() {
return debugExtension;
}
protected Attribute read(ClassReader cr, int off, int len, char[] buf, int codeOff, Label[] labels) {
return new SourceDebugExtensionAttribute( cr.readUTF8( off, buf));
}
protected ByteVector write(ClassWriter cw, byte[] code, int len, int maxStack, int maxLocals) {
return new ByteVector().putUTF8( debugExtension);
}
} |
package erogenousbeef.bigreactors.common;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import appeng.api.Util;
import thermalexpansion.api.crafting.CraftingHelpers;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.oredict.OreDictionary;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.ReflectionHelper;
import cpw.mods.fml.relauncher.Side;
import erogenousbeef.bigreactors.gui.BigReactorsGUIHandler;
import erogenousbeef.bigreactors.common.item.ItemIngot;
public class CommonProxy {
public void preInit() {
}
public void init() {
BigReactors.registerTileEntities();
NetworkRegistry.instance().registerGuiHandler(BRLoader.instance, new BigReactorsGUIHandler());
BigReactors.tickHandler = new BigReactorsTickHandler();
TickRegistry.registerTickHandler(BigReactors.tickHandler, Side.SERVER);
}
public void postInit() {
BRConfig.CONFIGURATION.load();
boolean autoAddUranium = BRConfig.CONFIGURATION.get("Compatibility", "autoAddUranium",
true,
"If true, automatically adds all "
+"unregistered ingots found as clones"
+"of standard yellorium fuel").getBoolean(true);
if(autoAddUranium) {
List<ItemStack> candidates = OreDictionary.getOres("ingotUranium");
for(ItemStack candidate : candidates) {
// If they're already registered, this will NOT overwrite the existing registration
BRRegistry.registerFuel(new ReactorFuel(candidate, BigReactors.defaultLiquidColorFuel));
}
}
BRConfig.CONFIGURATION.save();
ItemIngot ingotGeneric = ((ItemIngot)BigReactors.ingotGeneric);
ItemStack yelloriteOre = new ItemStack(BigReactors.blockYelloriteOre, 1);
ItemStack ingotYellorium= ingotGeneric.getItemStackForType("ingotYellorium");
ItemStack ingotCyanite = ingotGeneric.getItemStackForType("ingotCyanite");
ItemStack ingotGraphite = ingotGeneric.getItemStackForType("ingotGraphite");
ItemStack ingotBlutonium= ingotGeneric.getItemStackForType("ingotBlutonium");
ItemStack dustYellorium = ingotGeneric.getItemStackForType("dustYellorium");
ItemStack dustCyanite = ingotGeneric.getItemStackForType("dustCyanite");
ItemStack dustGraphite = ingotGeneric.getItemStackForType("dustGraphite");
ItemStack dustBlutonium = ingotGeneric.getItemStackForType("dustBlutonium");
// Some mods make me do this myself. :V
ItemStack doubledYelloriumDust = dustYellorium.copy();
doubledYelloriumDust.stackSize = 2;
if(Loader.isModLoaded("ThermalExpansion")) {
if(yelloriteOre != null && ingotYellorium != null) {
CraftingHelpers.addSmelterOreToIngotsRecipe(yelloriteOre.copy(), ingotYellorium.copy());
}
if(yelloriteOre != null && dustYellorium != null) {
CraftingHelpers.addPulverizerOreToDustRecipe(yelloriteOre.copy(), dustYellorium.copy());
}
if(ingotYellorium != null && dustYellorium != null) {
CraftingHelpers.addPulverizerIngotToDustRecipe(ingotYellorium.copy(), dustYellorium.copy());
CraftingHelpers.addSmelterDustToIngotsRecipe(dustYellorium.copy(), ingotYellorium.copy());
}
if(ingotCyanite != null && dustCyanite != null) {
CraftingHelpers.addPulverizerIngotToDustRecipe(ingotCyanite.copy(), dustCyanite.copy());
CraftingHelpers.addSmelterDustToIngotsRecipe(dustCyanite.copy(), ingotCyanite.copy());
}
if(ingotGraphite != null && dustGraphite != null) {
CraftingHelpers.addPulverizerIngotToDustRecipe(ingotGraphite.copy(), dustGraphite.copy());
CraftingHelpers.addSmelterDustToIngotsRecipe(dustGraphite.copy(), ingotGraphite.copy());
}
if(ingotBlutonium != null && dustBlutonium != null) {
CraftingHelpers.addPulverizerIngotToDustRecipe(ingotBlutonium.copy(), dustBlutonium.copy());
CraftingHelpers.addSmelterDustToIngotsRecipe(dustBlutonium.copy(), ingotBlutonium.copy());
}
}
if(Loader.isModLoaded("AppliedEnergistics")) {
appeng.api.IGrinderRecipeManager grinderRM = appeng.api.Util.getGrinderRecipeManage();
if(grinderRM != null) {
if(yelloriteOre != null && dustYellorium != null) {
grinderRM.addRecipe(yelloriteOre.copy(), doubledYelloriumDust.copy(), 4);
}
if(ingotYellorium != null && dustYellorium != null) {
grinderRM.addRecipe(ingotYellorium.copy(), dustYellorium.copy(), 2);
}
if(ingotCyanite != null && dustCyanite != null) {
grinderRM.addRecipe(ingotCyanite.copy(), dustCyanite.copy(), 2);
}
if(ingotGraphite != null && dustGraphite != null) {
grinderRM.addRecipe(ingotGraphite.copy(), dustGraphite.copy(), 2);
}
if(ingotBlutonium != null && dustBlutonium != null) {
grinderRM.addRecipe(ingotBlutonium.copy(), dustBlutonium.copy(), 2);
}
}
}
if(Loader.isModLoaded("Mekanism")) {
if(yelloriteOre != null && dustYellorium != null) {
addMekanismEnrichmentChamberRecipe(yelloriteOre.copy(), doubledYelloriumDust.copy());
addMekanismCombinerRecipe(dustYellorium.copy(), yelloriteOre.copy());
}
if(ingotYellorium != null && dustYellorium != null) {
addMekanismCrusherRecipe(ingotYellorium.copy(), dustYellorium.copy());
}
if(ingotCyanite != null && dustCyanite != null) {
addMekanismCrusherRecipe(ingotCyanite.copy(), dustCyanite.copy());
}
if(ingotGraphite != null && dustGraphite != null) {
addMekanismCrusherRecipe(ingotGraphite.copy(), dustGraphite.copy());
}
if(ingotBlutonium != null && dustBlutonium != null) {
addMekanismCrusherRecipe(dustGraphite.copy(), dustBlutonium.copy());
}
}
}
/// Mekanism Compat - taken from Mekanism's API. Extracted to allow compat with last known green build.
/**
* Add an Enrichment Chamber recipe. (Ore -> 2 Dust)
* @param input - input ItemStack
* @param output - output ItemStack
*/
public static void addMekanismEnrichmentChamberRecipe(ItemStack input, ItemStack output)
{
try {
Class recipeClass = Class.forName("mekanism.common.RecipeHandler");
Method m = recipeClass.getMethod("addEnrichmentChamberRecipe", ItemStack.class, ItemStack.class);
m.invoke(null, input, output);
} catch(Exception e) {
System.err.println("[Mekanism] Error while adding recipe: " + e.getMessage());
}
}
/**
* Add a Combiner recipe. (2 Dust + Cobble -> Ore)
* @param input - input ItemStack
* @param output - output ItemStack
*/
public static void addMekanismCombinerRecipe(ItemStack input, ItemStack output)
{
try {
Class recipeClass = Class.forName("mekanism.common.RecipeHandler");
Method m = recipeClass.getMethod("addCombinerRecipe", ItemStack.class, ItemStack.class);
m.invoke(null, input, output);
} catch(Exception e) {
System.err.println("[Mekanism] Error while adding recipe: " + e.getMessage());
}
}
/**
* Add a Crusher recipe. (Ingot -> Dust)
* @param input - input ItemStack
* @param output - output ItemStack
*/
public static void addMekanismCrusherRecipe(ItemStack input, ItemStack output)
{
try {
Class recipeClass = Class.forName("mekanism.common.RecipeHandler");
Method m = recipeClass.getMethod("addCrusherRecipe", ItemStack.class, ItemStack.class);
m.invoke(null, input, output);
} catch(Exception e) {
System.err.println("[Mekanism] Error while adding recipe: " + e.getMessage());
}
}
} |
package com.almasb.fxgl.app;
import com.almasb.fxeventbus.Subscriber;
import com.almasb.fxgl.devtools.profiling.Profiler;
import com.almasb.fxgl.event.IntroFinishedEvent;
import com.almasb.fxgl.gameplay.GameWorld;
import com.almasb.fxgl.io.DataFile;
import com.almasb.fxgl.logging.Logger;
import com.almasb.fxgl.logging.SystemLogger;
import com.almasb.fxgl.physics.PhysicsWorld;
import com.almasb.fxgl.scene.*;
import com.almasb.fxgl.scene.menu.MenuEventListener;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.concurrent.Task;
/**
* To use FXGL extend this class and implement necessary methods.
* The initialization process can be seen below (irrelevant phases are omitted):
* <p>
* <ol>
* <li>Instance fields of YOUR subclass of GameApplication</li>
* <li>initSettings()</li>
* <li>Services configuration (after this you can safely call FXGL.getService())</li>
* <li>initAchievements()</li>
* <li>initInput()</li>
* <li>preInit()</li>
* <p>The following phases are NOT executed on UI thread</p>
* <li>initAssets()</li>
* <li>initGame() OR loadState()</li>
* <li>initPhysics()</li>
* <li>initUI()</li>
* <li>Start of main game loop execution on UI thread</li>
* </ol>
* <p>
* Unless explicitly stated, methods are not thread-safe and must be
* executed on the JavaFX Application (UI) Thread.
* By default all callbacks are executed on the JavaFX Application (UI) Thread.
* <p>
* Callback / listener notes: instance of GameApplication will always be
* notified last along the chain of callbacks.
* However, as per documentation, events are always fired after listeners.
* </p>
*
* @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com)
*/
public abstract class GameApplication extends FXGLApplication {
private Logger log = SystemLogger.INSTANCE;
{
log.debug("Starting JavaFX");
}
private ObjectProperty<ApplicationState> state = new SimpleObjectProperty<>(ApplicationState.STARTUP);
/**
* @return current application state
*/
public final ApplicationState getState() {
return state.get();
}
/**
* Set application state.
* Setting a state will also trigger scene change associated
* with that state.
*
* @param appState application state
*/
void setState(ApplicationState appState) {
log.debug("State: " + getState() + " -> " + appState);
state.set(appState);
switch (appState) {
case INTRO:
getDisplay().setScene(introScene);
introFinishedSubscriber = getEventBus().addEventHandler(IntroFinishedEvent.ANY, e -> onIntroFinished());
introScene.startIntro();
break;
case LOADING:
getDisplay().setScene(loadingScene);
break;
case MAIN_MENU:
getDisplay().setScene(mainMenuScene);
if (!menuHandler.isProfileSelected())
menuHandler.showProfileDialog();
break;
case GAME_MENU:
getDisplay().setScene(gameMenuScene);
break;
case PLAYING:
getDisplay().setScene(getGameScene());
break;
case PAUSED:
// no need to do anything
break;
default:
log.warning("Attempted to set illegal state: " + appState);
break;
}
}
/**
* @return game world
*/
public final GameWorld getGameWorld() {
return gameWorld;
}
/**
* @return physics world
*/
public final PhysicsWorld getPhysicsWorld() {
return physicsWorld;
}
/**
* @return game scene
*/
public final GameScene getGameScene() {
return gameScene;
}
/**
* Override to provide custom intro/loading/menu scenes.
*
* @return scene factory
*/
protected SceneFactory initSceneFactory() {
return new SceneFactory();
}
/* The following fields are injected by tasks */
GameWorld gameWorld;
PhysicsWorld physicsWorld;
GameScene gameScene;
/**
* Intro scene, this is shown when the application started,
* before menus and game.
*/
IntroScene introScene;
/**
* This scene is shown during app initialization,
* i.e. when assets / game are loaded on bg thread.
*/
LoadingScene loadingScene;
/**
* Main menu, this is the menu shown at the start of game.
*/
FXGLMenu mainMenuScene;
/**
* In-game menu, this is shown when menu key pressed during the game.
*/
FXGLMenu gameMenuScene;
/**
* Handler for menu events.
*/
private MenuEventHandler menuHandler;
/**
* Main game profiler.
*/
Profiler profiler;
/**
* Override to register your achievements.
*
* <pre>
* Example:
*
* AchievementManager am = getAchievementManager();
* am.registerAchievement(new Achievement("Score Master", "Score 20000 points"));
* </pre>
*/
protected void initAchievements() {
}
/**
* Initialize input, i.e. bind key presses, bind mouse buttons.
*
* <p>
* Note: This method is called prior to any game init to
* register input mappings in the menus.
* </p>
* <pre>
* Example:
*
* Input input = getInput();
* input.addAction(new UserAction("Move Left") {
* protected void onAction() {
* playerControl.moveLeft();
* }
* }, KeyCode.A);
* </pre>
*/
protected abstract void initInput();
/**
* This is called after core services are initialized
* but before any game init.
* Called only once per application lifetime.
*/
protected void preInit() {
}
/**
* Initialize game assets, such as Texture, Sound, Music, etc.
*/
protected abstract void initAssets();
/**
* Called when MenuEvent.SAVE occurs.
* Note: if you enable menus, you are responsible for providing
* appropriate serialization of your game state.
* Otherwise an exception will be thrown when save is called.
*
* @return data with required info about current state
* @throws UnsupportedOperationException if was not overridden
*/
protected DataFile saveState() {
log.warning("Called saveState(), but it wasn't overridden!");
throw new UnsupportedOperationException("Default implementation is not available");
}
/**
* Called when MenuEvent.LOAD occurs.
* Note: if you enable menus, you are responsible for providing
* appropriate deserialization of your game state.
* Otherwise an exception will be thrown when load is called.
*
* @param dataFile previously saved data
* @throws UnsupportedOperationException if was not overridden
*/
protected void loadState(DataFile dataFile) {
log.warning("Called loadState(), but it wasn't overridden!");
throw new UnsupportedOperationException("Default implementation is not available");
}
/**
* Initialize game objects.
*/
protected abstract void initGame();
/**
* Initialize collision handlers, physics properties.
*/
protected abstract void initPhysics();
/**
* Initialize UI objects.
*/
protected abstract void initUI();
/**
* Main loop update phase, most of game logic.
*
* @param tpf time per frame
*/
protected abstract void onUpdate(double tpf);
/**
* Called after main loop tick has been completed.
* It can be used to de-register callbacks / listeners
* and call various methods that otherwise might interfere
* with main loop.
*
* @param tpf time per frame (same as main update tpf)
*/
protected void onPostUpdate(double tpf) {
}
/**
* @return true if any menu is open
*/
public boolean isMenuOpen() {
return getState() == ApplicationState.GAME_MENU
|| getState() == ApplicationState.MAIN_MENU;
}
/**
* @return true if game is paused or menu is open
*/
public boolean isPaused() {
return isMenuOpen() || getState() == ApplicationState.PAUSED;
}
private Subscriber introFinishedSubscriber;
private void onIntroFinished() {
if (getSettings().isMenuEnabled()) {
setState(ApplicationState.MAIN_MENU);
} else {
startNewGame();
}
if (introFinishedSubscriber != null) {
introFinishedSubscriber.unsubscribe();
// we no longer need intro, mark for cleanup
introScene = null;
introFinishedSubscriber = null;
}
}
@Override
void configureApp() {
// services are now ready, switch to normal logger
log = FXGL.getLogger(GameApplication.class);
log.debug("Configuring GameApplication");
long start = System.nanoTime();
runTask(PreInitTask.class);
runTask(InitScenesTask.class);
runTask(InitEventHandlersTask.class);
runTask(InitProfilerTask.class);
// intro runs async so we have to wait with a callback
// Stage -> (Intro) -> (Menu) -> Game
// if not enabled, call finished directly
if (getSettings().isIntroEnabled()) {
setState(ApplicationState.INTRO);
} else {
onIntroFinished();
}
SystemLogger.INSTANCE.infof("Game configuration took: %.3f sec", (System.nanoTime() - start) / 1000000000.0);
}
/**
* Initialize user application.
*/
private void initApp(Task<?> initTask) {
log.debug("Initializing App");
// on first run this is no-op, as for rest this ensures
// that even without menus and during direct calls to start*Game()
// the system is clean, also reset performs System.gc() to clear stuff we used in init
pause();
reset();
setState(ApplicationState.LOADING);
loadingScene.bind(initTask);
getExecutor().execute(initTask);
}
/**
* (Re-)initializes the user application as new and starts the game.
* Note: cannot be called during callbacks.
*/
protected void startNewGame() {
log.debug("Starting new game");
initApp(new InitAppTask(this));
}
/**
* (Re-)initializes the user application from the given data file and starts the game.
* Note: cannot be called during callbacks.
*
* @param dataFile save data to load from
*/
protected void startLoadedGame(DataFile dataFile) {
log.debug("Starting loaded game");
initApp(new InitAppTask(this, dataFile));
}
public MenuEventListener getMenuListener() {
if (menuHandler == null)
menuHandler = new MenuEventHandler(this);
return menuHandler;
}
} |
package org.opencms.ade.detailpage;
import org.opencms.ade.config.CmsADEConfigurationManager;
import org.opencms.ade.config.CmsSitemapConfigurationData;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.main.CmsException;
import org.opencms.main.OpenCms;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* This class uses information from the detail page information stored in the sitemap to find the detail page for
* a given resource.<p>
*
* @author Georg Westenberger
*
* @version $Revision: 1.5 $
*
* @since 8.0.0
*/
public class CmsSitemapDetailPageFinder implements I_CmsDetailPageFinder {
/**
* @see org.opencms.ade.detailpage.I_CmsDetailPageFinder#getAllDetailPages(org.opencms.file.CmsObject, org.opencms.file.CmsResource)
*/
public Collection<String> getAllDetailPages(CmsObject cms, CmsResource res) throws CmsException {
CmsADEConfigurationManager confManager = OpenCms.getADEConfigurationManager();
String typeName = OpenCms.getResourceManager().getResourceType(res.getTypeId()).getTypeName();
Map<String, List<CmsDetailPageInfo>> bestDetailPagesByType = confManager.getAllDetailPages(cms);
List<CmsDetailPageInfo> pageInfos = bestDetailPagesByType.get(typeName);
if (pageInfos == null) {
return Collections.<String> emptyList();
}
List<String> result = new ArrayList<String>();
for (CmsDetailPageInfo pageInfo : pageInfos) {
String uri = pageInfo.getUri();
if (!CmsResource.isFolder(uri)) {
uri = CmsResource.getFolderPath(uri);
}
result.add(uri);
}
return result;
}
/**
* @see org.opencms.ade.detailpage.I_CmsDetailPageFinder#getDetailPage(org.opencms.file.CmsObject, java.lang.String, java.lang.String)
*/
public String getDetailPage(CmsObject cms, String rootPath, String linkSource) throws CmsException {
String folder = CmsResource.getFolderPath(rootPath);
if (rootPath.endsWith(".jsp") || rootPath.startsWith(CmsResource.VFS_FOLDER_SYSTEM + "/")) {
// exclude these for performance reasons
return null;
}
if (folder == null) {
return null;
}
Map<String, String> folderTypes = OpenCms.getADEConfigurationManager().getFolderTypes(cms);
String folderType = folderTypes.get(folder);
if (folderType == null) {
return null;
}
CmsADEConfigurationManager confManager = OpenCms.getADEConfigurationManager();
String rootLinkSource = cms.getRequestContext().addSiteRoot(linkSource);
CmsSitemapConfigurationData sitemapConf = confManager.getSitemapConfiguration(cms, rootLinkSource);
String typeName = folderType;
List<CmsDetailPageInfo> pageInfos = sitemapConf.getDetailPageInfo().get(typeName);
if ((pageInfos == null) || pageInfos.isEmpty()) {
return null;
}
CmsDetailPageInfo info = pageInfos.get(0);
String detailPageUri = info.getUri();
if (!CmsResource.isFolder(detailPageUri)) {
detailPageUri = CmsResource.getFolderPath(detailPageUri);
}
return detailPageUri;
}
} |
package org.codice.nitf.filereader;
public class RGBColour {
private byte red = 0x00;
private byte green = 0x00;
private byte blue = 0x00;
private static final int UNSIGNED_BYTE_MASK = 0xFF;
public RGBColour(final byte[] rgb) {
// TODO: check array length = 3;
red = rgb[0];
green = rgb[1];
blue = rgb[2];
}
public final byte getRed() {
return red;
}
public final byte getGreen() {
return green;
}
public final byte getBlue() {
return blue;
}
@Override
public final String toString() {
return String.format("[0x%02x,0x%02x,0x%02x]",
(int) (red & UNSIGNED_BYTE_MASK),
(int) (green & UNSIGNED_BYTE_MASK),
(int) (blue & UNSIGNED_BYTE_MASK));
}
} |
// This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
package org.sosy_lab.java_smt.solvers.cvc5;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import io.github.cvc5.CVC5ApiException;
import io.github.cvc5.Kind;
import io.github.cvc5.Op;
import io.github.cvc5.Pair;
import io.github.cvc5.Solver;
import io.github.cvc5.Sort;
import io.github.cvc5.Term;
import io.github.cvc5.Triplet;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.sosy_lab.common.rationals.Rational;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType;
import org.sosy_lab.java_smt.api.FormulaType.FloatingPointType;
import org.sosy_lab.java_smt.api.FunctionDeclarationKind;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier;
import org.sosy_lab.java_smt.api.RegexFormula;
import org.sosy_lab.java_smt.api.StringFormula;
import org.sosy_lab.java_smt.api.visitors.FormulaVisitor;
import org.sosy_lab.java_smt.basicimpl.FormulaCreator;
import org.sosy_lab.java_smt.basicimpl.FunctionDeclarationImpl;
import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5ArrayFormula;
import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5BitvectorFormula;
import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5BooleanFormula;
import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5FloatingPointFormula;
import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5FloatingPointRoundingModeFormula;
import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5IntegerFormula;
import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5RationalFormula;
import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5RegexFormula;
import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5StringFormula;
public class CVC5FormulaCreator extends FormulaCreator<Term, Sort, Solver, Term> {
/** CVC5 does not allow using some key-functions from SMTLIB2 as identifiers. */
private static final ImmutableSet<String> UNSUPPORTED_IDENTIFIERS = ImmutableSet.of("let");
// private static final Pattern FLOATING_POINT_PATTERN = Pattern.compile("^\\(fp #b(?<sign>\\d)
// #b(?<exp>\\d+) #b(?<mant>\\d+)$");
private final Map<String, Term> variablesCache = new HashMap<>();
private final Map<String, Term> functionsCache = new HashMap<>();
private final Solver solver;
protected CVC5FormulaCreator(Solver pSolver) {
super(
pSolver,
pSolver.getBooleanSort(),
pSolver.getIntegerSort(),
pSolver.getRealSort(),
pSolver.getStringSort(),
pSolver.getRegExpSort());
solver = pSolver;
}
@Override
public Term makeVariable(Sort sort, String name) {
checkSymbol(name);
Term exp = variablesCache.computeIfAbsent(name, n -> solver.mkConst(sort, name));
Preconditions.checkArgument(
sort.equals(exp.getSort()),
"symbol name already in use for different Type %s",
exp.getSort());
return exp;
}
/**
* Makes a bound copy of a variable for use in quantifier. Note that all occurrences of the free
* var have to be substituted by the bound once it exists.
*
* @param var Variable you want a bound copy of.
* @return Bound Variable
*/
public Term makeBoundCopy(Term var) {
Sort sort = var.getSort();
String name = getName(var);
Term boundCopy = solver.mkVar(sort, name);
return boundCopy;
}
@Override
public Sort getBitvectorType(int pBitwidth) {
try {
return solver.mkBitVectorSort(pBitwidth);
} catch (CVC5ApiException e) {
throw new IllegalArgumentException(
"You tried creating a invalid bitvector sort with size " + pBitwidth + ".", e);
}
}
@Override
public Sort getFloatingPointType(FloatingPointType pType) {
try {
// plus sign bit
return solver.mkFloatingPointSort(pType.getExponentSize(), pType.getMantissaSize() + 1);
} catch (CVC5ApiException e) {
throw new IllegalArgumentException(
"You tried creating a invalid floatingpoint sort with exponent size "
+ pType.getExponentSize()
+ " and mantissa "
+ pType.getMantissaSize()
+ ".",
e);
}
}
@Override
public Sort getArrayType(Sort pIndexType, Sort pElementType) {
return solver.mkArraySort(pIndexType, pElementType);
}
@Override
public Term extractInfo(Formula pT) {
return CVC5FormulaManager.getCVC5Term(pT);
}
@Override
@SuppressWarnings("MethodTypeParameterName")
protected <TD extends Formula, TR extends Formula> FormulaType<TR> getArrayFormulaElementType(
ArrayFormula<TD, TR> pArray) {
return ((CVC5ArrayFormula<TD, TR>) pArray).getElementType();
}
@Override
@SuppressWarnings("MethodTypeParameterName")
protected <TD extends Formula, TR extends Formula> FormulaType<TD> getArrayFormulaIndexType(
ArrayFormula<TD, TR> pArray) {
return ((CVC5ArrayFormula<TD, TR>) pArray).getIndexType();
}
@SuppressWarnings("unchecked")
@Override
public <T extends Formula> FormulaType<T> getFormulaType(T pFormula) {
Sort cvc5sort = extractInfo(pFormula).getSort();
if (pFormula instanceof BitvectorFormula) {
checkArgument(
cvc5sort.isBitVector(), "BitvectorFormula with actual Type %s: %s", cvc5sort, pFormula);
return (FormulaType<T>) getFormulaType(extractInfo(pFormula));
} else if (pFormula instanceof FloatingPointFormula) {
checkArgument(
cvc5sort.isFloatingPoint(),
"FloatingPointFormula with actual Type %s: %s",
cvc5sort,
pFormula);
return (FormulaType<T>)
FormulaType.getFloatingPointType(
cvc5sort.getFloatingPointExponentSize(),
cvc5sort.getFloatingPointSignificandSize() - 1); // TODO: check for sign bit
} else if (pFormula instanceof ArrayFormula<?, ?>) {
FormulaType<T> arrayIndexType = getArrayFormulaIndexType((ArrayFormula<T, T>) pFormula);
FormulaType<T> arrayElementType = getArrayFormulaElementType((ArrayFormula<T, T>) pFormula);
return (FormulaType<T>) FormulaType.getArrayType(arrayIndexType, arrayElementType);
}
return super.getFormulaType(pFormula);
}
@Override
public FormulaType<?> getFormulaType(Term pFormula) {
return getFormulaTypeFromTermType(pFormula.getSort());
}
private FormulaType<?> getFormulaTypeFromTermType(Sort sort) {
if (sort.isBoolean()) {
return FormulaType.BooleanType;
} else if (sort.isInteger()) {
return FormulaType.IntegerType;
} else if (sort.isBitVector()) {
return FormulaType.getBitvectorTypeWithSize(sort.getBitVectorSize());
} else if (sort.isFloatingPoint()) {
// CVC5 wants the sign bit as part of the mantissa. We add that manually in creation.
return FormulaType.getFloatingPointType(
sort.getFloatingPointExponentSize(), sort.getFloatingPointSignificandSize() - 1);
} else if (sort.isRoundingMode()) {
return FormulaType.FloatingPointRoundingModeType;
} else if (sort.isReal()) {
// The theory REAL in CVC5 is the theory of (infinite precision!) real numbers.
// As such, the theory RATIONAL is contained in REAL.
return FormulaType.RationalType;
} else if (sort.isArray()) {
FormulaType<?> indexType = getFormulaTypeFromTermType(sort.getArrayIndexSort());
FormulaType<?> elementType = getFormulaTypeFromTermType(sort.getArrayElementSort());
return FormulaType.getArrayType(indexType, elementType);
} else if (sort.isString()) {
return FormulaType.StringType;
} else if (sort.isRegExp()) {
return FormulaType.RegexType;
} else if (sort.isFunction()) {
return getFormulaTypeFromTermType(sort.getFunctionCodomainSort());
} else {
throw new AssertionError(String.format("Encountered unhandled Type '%s'.", sort));
}
}
@SuppressWarnings("unchecked")
@Override
public <T extends Formula> T encapsulate(FormulaType<T> pType, Term pTerm) {
assert pType.equals(getFormulaType(pTerm))
|| (pType.equals(FormulaType.RationalType)
&& getFormulaType(pTerm).equals(FormulaType.IntegerType))
: String.format(
"Trying to encapsulate formula %s of Type %s as %s",
pTerm, getFormulaType(pTerm), pType);
if (pType.isBooleanType()) {
return (T) new CVC5BooleanFormula(pTerm);
} else if (pType.isIntegerType()) {
return (T) new CVC5IntegerFormula(pTerm);
} else if (pType.isRationalType()) {
return (T) new CVC5RationalFormula(pTerm);
} else if (pType.isArrayType()) {
ArrayFormulaType<?, ?> arrFt = (ArrayFormulaType<?, ?>) pType;
return (T) new CVC5ArrayFormula<>(pTerm, arrFt.getIndexType(), arrFt.getElementType());
} else if (pType.isBitvectorType()) {
return (T) new CVC5BitvectorFormula(pTerm);
} else if (pType.isFloatingPointType()) {
return (T) new CVC5FloatingPointFormula(pTerm);
} else if (pType.isFloatingPointRoundingModeType()) {
return (T) new CVC5FloatingPointRoundingModeFormula(pTerm);
} else if (pType.isStringType()) {
return (T) new CVC5StringFormula(pTerm);
} else if (pType.isRegexType()) {
return (T) new CVC5RegexFormula(pTerm);
}
throw new IllegalArgumentException("Cannot create formulas of Type " + pType + " in CVC5");
}
private Formula encapsulate(Term pTerm) {
return encapsulate(getFormulaType(pTerm), pTerm);
}
@Override
public BooleanFormula encapsulateBoolean(Term pTerm) {
assert getFormulaType(pTerm).isBooleanType()
: String.format(
"%s is not boolean, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm));
return new CVC5BooleanFormula(pTerm);
}
@Override
public BitvectorFormula encapsulateBitvector(Term pTerm) {
assert getFormulaType(pTerm).isBitvectorType()
: String.format("%s is no BV, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm));
return new CVC5BitvectorFormula(pTerm);
}
@Override
protected FloatingPointFormula encapsulateFloatingPoint(Term pTerm) {
assert getFormulaType(pTerm).isFloatingPointType()
: String.format("%s is no FP, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm));
return new CVC5FloatingPointFormula(pTerm);
}
@Override
@SuppressWarnings("MethodTypeParameterName")
protected <TI extends Formula, TE extends Formula> ArrayFormula<TI, TE> encapsulateArray(
Term pTerm, FormulaType<TI> pIndexType, FormulaType<TE> pElementType) {
assert getFormulaType(pTerm).equals(FormulaType.getArrayType(pIndexType, pElementType))
: String.format(
"%s is no array, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm));
return new CVC5ArrayFormula<>(pTerm, pIndexType, pElementType);
}
@Override
protected StringFormula encapsulateString(Term pTerm) {
assert getFormulaType(pTerm).isStringType()
: String.format(
"%s is no String, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm));
return new CVC5StringFormula(pTerm);
}
@Override
protected RegexFormula encapsulateRegex(Term pTerm) {
assert getFormulaType(pTerm).isRegexType();
return new CVC5RegexFormula(pTerm);
}
private String getName(Term e) {
checkState(!e.isNull());
String repr = e.toString();
try {
if (e.getKind() == Kind.APPLY_UF) {
e = e.getChild(0);
}
} catch (CVC5ApiException e1) {
// Fallback is the String of the original term
}
if (e.hasSymbol()) {
return e.getSymbol();
} else if (repr.startsWith("(")) {
// Some function
// Functions are packaged like this: (functionName arg1 arg2 ...)
// But can use |(name)| to enable () inside of the variable name
// TODO what happens for function names containing whitepsace?
String dequoted = dequote(repr);
return Iterables.get(Splitter.on(' ').split(dequoted.substring(1)), 0);
} else {
return dequote(repr);
}
}
@Override
public <R> R visit(FormulaVisitor<R> visitor, Formula formula, final Term f) {
checkState(!f.isNull());
Sort sort = f.getSort();
try {
if (f.isBooleanValue()) {
return visitor.visitConstant(formula, f.getBooleanValue());
} else if (f.isStringValue()) {
return visitor.visitConstant(formula, f.getStringValue());
} else if (f.isRealValue()) {
Pair<BigInteger, BigInteger> realValue = f.getRealValue();
return visitor.visitConstant(formula, Rational.of(realValue.first, realValue.second));
} else if (f.isIntegerValue()) {
return visitor.visitConstant(formula, f.getIntegerValue());
} else if (f.isBitVectorValue()) {
return visitor.visitConstant(formula, f.getBitVectorValue());
} else if (f.isFloatingPointValue()) {
// String is easier to parse here
return visitor.visitConstant(formula, f.toString());
} else if (f.getKind() == Kind.CONST_ROUNDINGMODE) {
return visitor.visitConstant(formula, f.toString());
} else if (f.getKind() == Kind.VARIABLE) {
// BOUND vars are used for all vars that are bound to a quantifier in CVC5.
// We resubstitute them back to the original free.
// CVC5 doesn't give you the de-brujin index
Term originalVar = variablesCache.get(dequote(formula.toString()));
return visitor.visitBoundVariable(encapsulate(originalVar), 0);
} else if (f.getKind() == Kind.FORALL || f.getKind() == Kind.EXISTS) {
// QUANTIFIER: replace bound variable with free variable for visitation
assert f.getNumChildren() == 2;
Term body = f.getChild(1);
List<Formula> freeVars = new ArrayList<>();
for (Term boundVar : f.getChild(0)) { // unpack grand-children of f.
String name = getName(boundVar);
Term freeVar = Preconditions.checkNotNull(variablesCache.get(name));
body = body.substitute(boundVar, freeVar);
freeVars.add(encapsulate(freeVar));
}
BooleanFormula fBody = encapsulateBoolean(body);
Quantifier quant = f.getKind() == Kind.EXISTS ? Quantifier.EXISTS : Quantifier.FORALL;
return visitor.visitQuantifier((BooleanFormula) formula, quant, freeVars, fBody);
} else if (f.getKind() == Kind.CONSTANT) {
return visitor.visitFreeVariable(formula, dequote(f.toString()));
} else {
// Term expressions like uninterpreted function calls (Kind.APPLY_UF) or operators (e.g.
// Kind.AND).
// These are all treated like operators, so we can get the declaration by f.getOperator()!
ImmutableList.Builder<Formula> argsBuilder = ImmutableList.builder();
List<FormulaType<?>> argsTypes = new ArrayList<>();
// Term operator = normalize(f.getSort());
Kind kind = f.getKind();
if (sort.isFunction() || kind == Kind.APPLY_UF) {
// The arguments are all children except the first one
for (int i = 1; i < f.getNumChildren(); i++) {
argsTypes.add(getFormulaTypeFromTermType(f.getChild(i).getSort()));
// CVC5s first argument in a function/Uf is the declaration, we don't need that here
argsBuilder.add(encapsulate(f.getChild(i)));
}
} else {
for (Term arg : f) {
argsTypes.add(getFormulaType(arg));
argsBuilder.add(encapsulate(arg));
}
}
// TODO some operations (BV_SIGN_EXTEND, BV_ZERO_EXTEND, maybe more) encode information as
// part of the operator itself, thus the arity is one too small and there might be no
// possibility to access the information from user side. Should we encode such information
// as additional parameters? We do so for some methods of Princess.
if (sort.isFunction()) {
return visitor.visitFunction(
formula,
argsBuilder.build(),
FunctionDeclarationImpl.of(
getName(f), getDeclarationKind(f), argsTypes, getFormulaType(f), normalize(f)));
} else if (kind == Kind.APPLY_UF) {
return visitor.visitFunction(
formula,
argsBuilder.build(),
FunctionDeclarationImpl.of(
getName(f),
getDeclarationKind(f),
argsTypes,
getFormulaType(f),
normalize(f.getChild(0))));
} else {
// TODO: check if the below is correct
return visitor.visitFunction(
formula,
argsBuilder.build(),
FunctionDeclarationImpl.of(
getName(f), getDeclarationKind(f), argsTypes, getFormulaType(f), normalize(f)));
}
}
} catch (CVC5ApiException e) {
throw new IllegalArgumentException("Failure visiting the Term '" + f + "'.", e);
}
}
/**
* CVC5 returns new objects when querying operators for UFs. The new operator has to be translated
* back to a common one.
*/
private Term normalize(Term operator) {
Term function = functionsCache.get(getName(operator));
if (function != null) {
checkState(
function.getId() == operator.getId(),
"operator '%s' with ID %s differs from existing function '%s' with ID '%s'.",
operator,
operator.getId(),
function,
function.getId());
return function;
}
return operator;
}
// see src/theory/*/kinds in CVC5 sources for description of the different CVC5 kinds ;)
private static final ImmutableMap<Kind, FunctionDeclarationKind> KIND_MAPPING =
ImmutableMap.<Kind, FunctionDeclarationKind>builder()
.put(Kind.EQUAL, FunctionDeclarationKind.EQ)
.put(Kind.DISTINCT, FunctionDeclarationKind.DISTINCT)
.put(Kind.NOT, FunctionDeclarationKind.NOT)
.put(Kind.AND, FunctionDeclarationKind.AND)
.put(Kind.IMPLIES, FunctionDeclarationKind.IMPLIES)
.put(Kind.OR, FunctionDeclarationKind.OR)
.put(Kind.XOR, FunctionDeclarationKind.XOR)
.put(Kind.ITE, FunctionDeclarationKind.ITE)
.put(Kind.APPLY_UF, FunctionDeclarationKind.UF)
.put(Kind.ADD, FunctionDeclarationKind.ADD)
.put(Kind.MULT, FunctionDeclarationKind.MUL)
.put(Kind.SUB, FunctionDeclarationKind.SUB)
.put(Kind.DIVISION, FunctionDeclarationKind.DIV)
.put(Kind.LT, FunctionDeclarationKind.LT)
.put(Kind.LEQ, FunctionDeclarationKind.LTE)
.put(Kind.GT, FunctionDeclarationKind.GT)
.put(Kind.GEQ, FunctionDeclarationKind.GTE)
// Bitvector theory
.put(Kind.BITVECTOR_ADD, FunctionDeclarationKind.BV_ADD)
.put(Kind.BITVECTOR_SUB, FunctionDeclarationKind.BV_SUB)
.put(Kind.BITVECTOR_MULT, FunctionDeclarationKind.BV_MUL)
.put(Kind.BITVECTOR_AND, FunctionDeclarationKind.BV_AND)
.put(Kind.BITVECTOR_OR, FunctionDeclarationKind.BV_OR)
.put(Kind.BITVECTOR_XOR, FunctionDeclarationKind.BV_XOR)
.put(Kind.BITVECTOR_SLT, FunctionDeclarationKind.BV_SLT)
.put(Kind.BITVECTOR_ULT, FunctionDeclarationKind.BV_ULT)
.put(Kind.BITVECTOR_SLE, FunctionDeclarationKind.BV_SLE)
.put(Kind.BITVECTOR_ULE, FunctionDeclarationKind.BV_ULE)
.put(Kind.BITVECTOR_SGT, FunctionDeclarationKind.BV_SGT)
.put(Kind.BITVECTOR_UGT, FunctionDeclarationKind.BV_UGT)
.put(Kind.BITVECTOR_SGE, FunctionDeclarationKind.BV_SGE)
.put(Kind.BITVECTOR_UGE, FunctionDeclarationKind.BV_UGE)
.put(Kind.BITVECTOR_SDIV, FunctionDeclarationKind.BV_SDIV)
.put(Kind.BITVECTOR_UDIV, FunctionDeclarationKind.BV_UDIV)
.put(Kind.BITVECTOR_SREM, FunctionDeclarationKind.BV_SREM)
// TODO: find out where Kind.BITVECTOR_SMOD fits in here
.put(Kind.BITVECTOR_UREM, FunctionDeclarationKind.BV_UREM)
.put(Kind.BITVECTOR_NOT, FunctionDeclarationKind.BV_NOT)
.put(Kind.BITVECTOR_NEG, FunctionDeclarationKind.BV_NEG)
.put(Kind.BITVECTOR_EXTRACT, FunctionDeclarationKind.BV_EXTRACT)
.put(Kind.BITVECTOR_CONCAT, FunctionDeclarationKind.BV_CONCAT)
.put(Kind.BITVECTOR_SIGN_EXTEND, FunctionDeclarationKind.BV_SIGN_EXTENSION)
.put(Kind.BITVECTOR_ZERO_EXTEND, FunctionDeclarationKind.BV_ZERO_EXTENSION)
// Floating-point theory
.put(Kind.TO_INTEGER, FunctionDeclarationKind.FLOOR)
.put(Kind.TO_REAL, FunctionDeclarationKind.TO_REAL)
.put(Kind.FLOATINGPOINT_TO_SBV, FunctionDeclarationKind.FP_CASTTO_SBV)
.put(Kind.FLOATINGPOINT_TO_UBV, FunctionDeclarationKind.FP_CASTTO_UBV)
.put(Kind.FLOATINGPOINT_TO_FP_FROM_FP, FunctionDeclarationKind.FP_CASTTO_FP)
.put(Kind.FLOATINGPOINT_TO_FP_FROM_SBV, FunctionDeclarationKind.BV_SCASTTO_FP)
.put(Kind.FLOATINGPOINT_TO_FP_FROM_UBV, FunctionDeclarationKind.BV_UCASTTO_FP)
.put(Kind.FLOATINGPOINT_IS_NAN, FunctionDeclarationKind.FP_IS_NAN)
.put(Kind.FLOATINGPOINT_IS_NEG, FunctionDeclarationKind.FP_IS_NEGATIVE)
.put(Kind.FLOATINGPOINT_IS_INF, FunctionDeclarationKind.FP_IS_INF)
.put(Kind.FLOATINGPOINT_IS_NORMAL, FunctionDeclarationKind.FP_IS_NORMAL)
.put(Kind.FLOATINGPOINT_IS_SUBNORMAL, FunctionDeclarationKind.FP_IS_SUBNORMAL)
.put(Kind.FLOATINGPOINT_IS_ZERO, FunctionDeclarationKind.FP_IS_ZERO)
.put(Kind.FLOATINGPOINT_EQ, FunctionDeclarationKind.FP_EQ)
.put(Kind.FLOATINGPOINT_ABS, FunctionDeclarationKind.FP_ABS)
.put(Kind.FLOATINGPOINT_MAX, FunctionDeclarationKind.FP_MAX)
.put(Kind.FLOATINGPOINT_MIN, FunctionDeclarationKind.FP_MIN)
.put(Kind.FLOATINGPOINT_SQRT, FunctionDeclarationKind.FP_SQRT)
.put(Kind.FLOATINGPOINT_ADD, FunctionDeclarationKind.FP_ADD)
.put(Kind.FLOATINGPOINT_SUB, FunctionDeclarationKind.FP_SUB)
.put(Kind.FLOATINGPOINT_MULT, FunctionDeclarationKind.FP_MUL)
.put(Kind.FLOATINGPOINT_DIV, FunctionDeclarationKind.FP_DIV)
.put(Kind.FLOATINGPOINT_LT, FunctionDeclarationKind.FP_LT)
.put(Kind.FLOATINGPOINT_LEQ, FunctionDeclarationKind.FP_LE)
.put(Kind.FLOATINGPOINT_GT, FunctionDeclarationKind.FP_GT)
.put(Kind.FLOATINGPOINT_GEQ, FunctionDeclarationKind.FP_GE)
.put(Kind.FLOATINGPOINT_RTI, FunctionDeclarationKind.FP_ROUND_TO_INTEGRAL)
.put(Kind.FLOATINGPOINT_TO_FP_FROM_IEEE_BV, FunctionDeclarationKind.FP_FROM_IEEEBV)
// String and Regex theory
.put(Kind.STRING_CONCAT, FunctionDeclarationKind.STR_CONCAT)
.put(Kind.STRING_PREFIX, FunctionDeclarationKind.STR_PREFIX)
.put(Kind.STRING_SUFFIX, FunctionDeclarationKind.STR_SUFFIX)
.put(Kind.STRING_CONTAINS, FunctionDeclarationKind.STR_CONTAINS)
.put(Kind.STRING_SUBSTR, FunctionDeclarationKind.STR_SUBSTRING)
.put(Kind.STRING_REPLACE, FunctionDeclarationKind.STR_REPLACE)
.put(Kind.STRING_REPLACE_ALL, FunctionDeclarationKind.STR_REPLACE_ALL)
.put(Kind.STRING_CHARAT, FunctionDeclarationKind.STR_CHAR_AT)
.put(Kind.STRING_LENGTH, FunctionDeclarationKind.STR_LENGTH)
.put(Kind.STRING_INDEXOF, FunctionDeclarationKind.STR_INDEX_OF)
.put(Kind.STRING_TO_REGEXP, FunctionDeclarationKind.STR_TO_RE)
.put(Kind.STRING_IN_REGEXP, FunctionDeclarationKind.STR_IN_RE)
.put(Kind.STRING_FROM_INT, FunctionDeclarationKind.INT_TO_STR)
.put(Kind.STRING_TO_INT, FunctionDeclarationKind.STR_TO_INT)
.put(Kind.STRING_LT, FunctionDeclarationKind.STR_LT)
.put(Kind.STRING_LEQ, FunctionDeclarationKind.STR_LE)
.put(Kind.REGEXP_PLUS, FunctionDeclarationKind.RE_PLUS)
.put(Kind.REGEXP_STAR, FunctionDeclarationKind.RE_STAR)
.put(Kind.REGEXP_OPT, FunctionDeclarationKind.RE_OPTIONAL)
.put(Kind.REGEXP_CONCAT, FunctionDeclarationKind.RE_CONCAT)
.put(Kind.REGEXP_UNION, FunctionDeclarationKind.RE_UNION)
.put(Kind.REGEXP_RANGE, FunctionDeclarationKind.RE_RANGE)
.put(Kind.REGEXP_INTER, FunctionDeclarationKind.RE_INTERSECT)
.put(Kind.REGEXP_COMPLEMENT, FunctionDeclarationKind.RE_COMPLEMENT)
.put(Kind.REGEXP_DIFF, FunctionDeclarationKind.RE_DIFFERENCE)
.build();
private FunctionDeclarationKind getDeclarationKind(Term f) {
try {
Kind kind = f.getKind();
// special case: IFF for Boolean, EQ for all other Types
if (kind == Kind.EQUAL && Iterables.all(f, child -> child.getSort().isBoolean())) {
return FunctionDeclarationKind.IFF;
}
return KIND_MAPPING.getOrDefault(kind, FunctionDeclarationKind.OTHER);
} catch (CVC5ApiException e) {
throw new IllegalArgumentException("Failure trying to get the KIND of Term '" + f + "'.", e);
}
}
@Override
protected Term getBooleanVarDeclarationImpl(Term pTFormulaInfo) {
try {
Kind kind = pTFormulaInfo.getKind();
// CONSTANTS are "variables" and Kind.VARIABLEs are bound variables in for example quantifiers
assert kind == Kind.APPLY_UF || kind == Kind.CONSTANT : pTFormulaInfo.getKind();
if (kind == Kind.APPLY_UF) {
// TODO: Test this, this is the old internal implementation
return pTFormulaInfo.getChild(0);
// old
// return pTFormulaInfo.getOperator();
} else {
return pTFormulaInfo;
}
} catch (CVC5ApiException e) {
throw new IllegalArgumentException(
"You tried reading a bool variable potentially in a UF application that failed. Checked"
+ " term: "
+ pTFormulaInfo
+ ".",
e);
}
}
@Override
public Term callFunctionImpl(final Term pDeclaration, final List<Term> pArgs) {
if (pArgs.isEmpty()) {
// CVC5 does not allow argumentless functions! We use variables as a workaround.
return pDeclaration;
} else {
if (pDeclaration.hasOp()) {
Op op = pDeclaration.getOp();
return solver.mkTerm(op, pArgs.toArray(new Term[] {}));
} else {
try {
Sort[] paramSorts = pDeclaration.getSort().getFunctionDomainSorts();
List<Term> args = castToParamTypeIfRequired(pArgs, paramSorts);
Kind kind = pDeclaration.getKind();
if (kind == Kind.CONSTANT) {
// For UF application, we need the declaration of the UF as first argument!
kind = Kind.APPLY_UF;
args.add(0, pDeclaration);
}
return solver.mkTerm(kind, args.toArray(new Term[] {}));
} catch (CVC5ApiException e) {
throw new IllegalArgumentException(
"Failure when building the UF '"
+ pDeclaration
+ "'"
+ " with arguments '"
+ pArgs
+ "'.",
e);
}
}
}
}
/**
* CVC5 does not allow subtyping for INT and REAL/RATIONAL, but requires a cast. This method
* inserts a cast, if required by the parameter type.
*
* @param pArgs input arguments to be casted.
* @param pParamSorts target type for all arguments.
* @return a list of potentially casted arguments.
*/
private List<Term> castToParamTypeIfRequired(List<Term> pArgs, Sort[] pParamSorts) {
final List<Term> args = new ArrayList<>();
for (int i = 0; i < pArgs.size(); i++) {
args.add(
castToParamTypeIfRequired(pArgs.get(i), pParamSorts.length > i ? pParamSorts[i] : null));
}
return args;
}
private Term castToParamTypeIfRequired(Term input, @Nullable Sort targetSort) {
if (input.getSort().isInteger() && targetSort.isReal()) {
return solver.mkTerm(Kind.TO_REAL, input);
}
return input;
}
private void checkSymbol(String symbol) {
checkArgument(
!UNSUPPORTED_IDENTIFIERS.contains(symbol),
"CVC5 does not support %s as identifier.",
symbol);
}
@Override
public Term declareUFImpl(String pName, Sort pReturnType, List<Sort> pArgTypes) {
checkSymbol(pName);
Term exp = functionsCache.get(pName);
if (exp == null) {
// Ufs in CVC5 can't have 0 arity. We just use a variable as a workaround.
Sort sort =
pArgTypes.isEmpty()
? pReturnType
: solver.mkFunctionSort(pArgTypes.toArray(new Sort[0]), pReturnType);
exp = solver.mkConst(sort, pName);
functionsCache.put(pName, exp);
} else {
Preconditions.checkArgument(
exp.getSort().equals(exp.getSort()),
"Symbol %s already in use for different return type %s",
exp,
exp.getSort());
for (int i = 1; i < exp.getNumChildren(); i++) {
// CVC5s first argument in a function/Uf is the declaration, we don't need that here
try {
Preconditions.checkArgument(
pArgTypes.get(i).equals(exp.getChild(i).getSort()),
"Argument %s with type %s does not match expected type %s",
i - 1,
pArgTypes.get(i),
exp.getChild(i).getSort());
} catch (CVC5ApiException e) {
throw new IllegalArgumentException(
"Failure visiting the Term '" + exp + "' at index " + i + ".", e);
}
}
}
return exp;
}
@Override
public Object convertValue(Term expForType, Term value) {
final Sort type = expForType.getSort();
final Sort valueType = value.getSort();
// Variables are Kind.CONSTANT and can't be check with isIntegerValue() or getIntegerValue()
// etc. but only with solver.getValue() and its String serialization
try {
if (value.getKind() == Kind.VARIABLE) {
// VARIABLE == bound variables
// CVC5 does not allow model values for bound vars; just return the name
return value.getSymbol();
} else if (value.isIntegerValue()) {
if (type.isReal()) { // real-based integers like "12.0" are returned as Rationals.
return Rational.ofBigInteger(value.getIntegerValue());
} else {
return value.getIntegerValue();
}
} else if (value.isRealValue()) {
Pair<BigInteger, BigInteger> realValue = value.getRealValue();
return Rational.of(realValue.first, realValue.second);
} else if (value.isBitVectorValue()) {
String bitvectorValue = value.getBitVectorValue();
return new BigInteger(bitvectorValue, 2);
} else if (value.isFloatingPointNaN()) {
return Float.NaN;
} else if (value.isFloatingPointNegInf()) {
return Float.NEGATIVE_INFINITY;
} else if (value.isFloatingPointPosInf()) {
return Float.POSITIVE_INFINITY;
} else if (value.isFloatingPointPosZero()) {
return BigDecimal.ZERO;
} else if (value.isFloatingPointValue()) {
// Negative zero falls under this category
// String valueString =
// solver.getValue(solver.mkTerm(Kind.FLOATINGPOINT_TO_REAL, fpTerm)).toString();
// return new BigDecimal(valueString).stripTrailingZeros();
final Triplet<Long, Long, Term> fpValue = value.getFloatingPointValue();
final long expWidth = fpValue.first;
final long mantWidth = fpValue.second - 1; // CVC5 also counts the sign-bit in the mantissa
final Term bvValue = fpValue.third;
Preconditions.checkState(bvValue.isBitVectorValue());
BigInteger bits = new BigInteger(bvValue.getBitVectorValue(), 2);
if (expWidth == 11 && mantWidth == 52) { // standard IEEE double type with 64 bits
return Double.longBitsToDouble(bits.longValue());
} else if (expWidth == 8 && mantWidth == 23) { // standard IEEE float type with 32 bits
return Float.intBitsToFloat(bits.intValue());
} else {
// TODO to be fully correct, we would need to interpret the BV as FP or Rational
return value.toString(); // returns a BV representation of the FP
}
} else if (value.isBooleanValue()) {
return value.getBooleanValue();
} else if (value.isStringValue()) {
return value.getStringValue();
} else {
// String serialization for Strings and unknown terms.
return value.toString();
}
} catch (CVC5ApiException e) {
throw new IllegalArgumentException(
String.format(
"Failure trying to convert constant %s with type %s to type %s.",
value, valueType, type),
e);
}
}
} |
package org.dannil.httpdownloader.model;
import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedList;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.springframework.stereotype.Component;
@Component
@Entity
@Table(name = "users")
public class User implements Serializable {
private static final long serialVersionUID = 5312673884211830942L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "UserID")
@JoinColumn(name = "UserID")
private Long id;
@Column(name = "Email")
@NotNull
private String email;
@Column(name = "Password")
@NotNull
private String password;
@Column(name = "Firstname")
@NotNull
private String firstname;
@Column(name = "Lastname")
@NotNull
private String lastname;
@OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
private Collection<Download> downloads;
/**
* Default constructor
*/
public User() {
}
/**
* Overloaded constructor
*
* @param email
* the user's email
* @param password
* the user's password
* @param firstname
* the user's firstname
* @param lastname
* the user's lastname
*/
public User(final String email, final String password, final String firstname, final String lastname) {
this();
this.email = email;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
}
/**
* Overloaded constructor
*
* @param email
* the user's email
* @param password
* the user's password
* @param firstname
* the user's firstname
* @param lastname
* the user's lastname
* @param downloads
* the user's downloads
*/
public User(final String email, final String password, final String firstname, final String lastname, final LinkedList<Download> downloads) {
this(email, password, firstname, lastname);
this.downloads = new LinkedList<Download>(downloads);
}
/**
* Copy constructor
*
* @param user
* the object to copy
*/
public User(final User user) {
this(user.getEmail(), user.getPassword(), user.getFirstname(), user.getLastname(), new LinkedList<Download>(user.getDownloads()));
this.id = user.getId();
}
public final Long getId() {
return this.id;
}
public final void setId(final long id) {
this.id = id;
}
public final String getEmail() {
return this.email;
}
public final void setEmail(final String email) {
this.email = email;
}
public final String getPassword() {
return this.password;
}
public final void setPassword(final String password) {
this.password = password;
}
public final String getFirstname() {
return this.firstname;
}
public final void setFirstname(final String firstname) {
this.firstname = firstname;
}
public final String getLastname() {
return this.lastname;
}
public final void setLastname(final String lastname) {
this.lastname = lastname;
}
public final LinkedList<Download> getDownloads() {
return new LinkedList<Download>(this.downloads);
}
// public final void setDownloads(final List<Download> downloads) {
// this.downloads = downloads;
/**
* Add a download to the user. Performs a null check on the download
* before adding it.
*
* @param download
* the download to add
*/
public final void addDownload(final Download download) {
if (download == null) {
return;
}
if (this.downloads == null) {
this.downloads = new LinkedList<Download>();
}
download.setUser(new User(this));
this.downloads.add(download);
}
/**
* Delete the specified download from the user's downloads list. Performs a
* null check on the download before searching the list for it.
*
* @param download
* the download to delete
*/
public final void deleteDownload(final Download download) {
if (download == null || this.downloads == null || this.downloads.size() <= 0) {
return;
}
for (Download temp : this.downloads) {
if (temp.getId().equals(download.getId())) {
this.downloads.remove(temp);
break;
}
}
}
/**
* Return a download with the specified download ID. Performs a null check
* on the user's downloads list before fetching from it.
*
* @param id
* the id of the download
*
* @return a download with the specified id
*/
public final Download getDownload(final long id) {
if (this.downloads == null || this.downloads.size() <= 0) {
return null;
}
for (Download temp : this.downloads) {
if (temp.getId().equals(id)) {
return new Download(temp);
}
}
return null;
}
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
final String NEW_LINE = System.getProperty("line.separator");
result.append(this.getClass().getName() + " - " + this.getClass().getSuperclass().getName() + " {" + NEW_LINE);
result.append("\tID: " + this.id + NEW_LINE);
result.append("\tE-mail: " + this.email + NEW_LINE);
result.append("\tPassword: " + "[OMITTED]" + NEW_LINE);
result.append("\tFirstname: " + this.firstname + NEW_LINE);
result.append("\tLastname: " + this.lastname + NEW_LINE);
result.append("}");
return result.toString();
}
} |
package com.cisco.trex.stateless;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.pcap4j.packet.ArpPacket;
import org.pcap4j.packet.Dot1qVlanTagPacket;
import org.pcap4j.packet.EthernetPacket;
import org.pcap4j.packet.IcmpV4CommonPacket;
import org.pcap4j.packet.IcmpV4EchoPacket;
import org.pcap4j.packet.IcmpV4EchoReplyPacket;
import org.pcap4j.packet.IllegalRawDataException;
import org.pcap4j.packet.IpV4Packet;
import org.pcap4j.packet.IpV4Rfc791Tos;
import org.pcap4j.packet.Packet;
import org.pcap4j.packet.namednumber.ArpHardwareType;
import org.pcap4j.packet.namednumber.ArpOperation;
import org.pcap4j.packet.namednumber.EtherType;
import org.pcap4j.packet.namednumber.IcmpV4Code;
import org.pcap4j.packet.namednumber.IcmpV4Type;
import org.pcap4j.packet.namednumber.IpNumber;
import org.pcap4j.packet.namednumber.IpVersion;
import org.pcap4j.util.ByteArrays;
import org.pcap4j.util.MacAddress;
import com.cisco.trex.ClientBase;
import com.cisco.trex.stateless.exception.ServiceModeRequiredException;
import com.cisco.trex.stateless.exception.TRexConnectionException;
import com.cisco.trex.stateless.model.ApiVersion;
import com.cisco.trex.stateless.model.Ipv6Node;
import com.cisco.trex.stateless.model.Port;
import com.cisco.trex.stateless.model.PortStatus;
import com.cisco.trex.stateless.model.Stream;
import com.cisco.trex.stateless.model.StreamMode;
import com.cisco.trex.stateless.model.StreamModeRate;
import com.cisco.trex.stateless.model.StreamRxStats;
import com.cisco.trex.stateless.model.StreamVM;
import com.cisco.trex.stateless.model.TRexClientResult;
import com.cisco.trex.stateless.model.port.PortVlan;
import com.cisco.trex.stateless.model.stats.ActivePGIds;
import com.cisco.trex.stateless.model.stats.ActivePGIdsRPCResult;
import com.cisco.trex.stateless.model.stats.PGIdStatsRPCResult;
import com.cisco.trex.stateless.model.vm.VMInstruction;
import com.google.common.collect.Lists;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class TRexClient extends ClientBase {
private static final EtherType QInQ = new EtherType((short) 0x88a8, "802.1Q Provider Bridge (Q-in-Q)");
private static Integer API_VERSION_MAJOR = 4;
private static Integer API_VERSION_MINOR = 0;
private Integer session_id = 123456789;
public TRexClient(String host, String port, String userName) {
this.host = host;
this.port = port;
this.userName = userName;
supportedCmds.add("api_sync");
supportedCmds.add("get_supported_cmds");
EtherType.register(QInQ);
}
@Override
protected void serverAPISync() throws TRexConnectionException {
LOGGER.info("Sync API with the TRex");
Map<String, Object> apiVers = new HashMap<>();
apiVers.put("type", "core");
apiVers.put("major", API_VERSION_MAJOR);
apiVers.put("minor", API_VERSION_MINOR);
Map<String, Object> parameters = new HashMap<>();
parameters.put("api_vers", Arrays.asList(apiVers));
TRexClientResult<ApiVersion> result = callMethod("api_sync", parameters, ApiVersion.class);
if (result.get() == null) {
TRexConnectionException e = new TRexConnectionException(
"Unable to connect to TRex server. Required API version is " + API_VERSION_MAJOR + "."
+ API_VERSION_MINOR);
LOGGER.error("Unable to sync client with TRex server due to: API_H is null.", e.getMessage());
throw e;
}
apiH = result.get().getApiH();
LOGGER.info("Received api_H: {}", apiH);
}
@Override
public PortStatus acquirePort(int portIndex, Boolean force) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("session_id", session_id);
payload.put("user", userName);
payload.put("force", force);
String json = callMethod("acquire", payload);
JsonElement response = new JsonParser().parse(json);
String handler = response.getAsJsonArray().get(0).getAsJsonObject().get("result").getAsString();
portHandlers.put(portIndex, handler);
return getPortStatus(portIndex).get();
}
public void resetPort(int portIndex) {
acquirePort(portIndex, true);
stopTraffic(portIndex);
removeAllStreams(portIndex);
removeRxQueue(portIndex);
serviceMode(portIndex, false);
releasePort(portIndex);
}
private Map<String, Object> createPayload(int portIndex) {
Map<String, Object> payload = new HashMap<>();
payload.put("port_id", portIndex);
payload.put("api_h", apiH);
String handler = portHandlers.get(portIndex);
if (handler != null) {
payload.put("handler", handler);
}
return payload;
}
@Override
public PortStatus releasePort(int portIndex) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("user", userName);
callMethod("release", payload);
portHandlers.remove(portIndex);
return getPortStatus(portIndex).get();
}
public PortStatus serviceMode(int portIndex, Boolean isOn) {
LOGGER.info("Set service mode : {}", isOn ? "on" : "off");
Map<String, Object> payload = createPayload(portIndex);
payload.put("enabled", isOn);
callMethod("service", payload);
return getPortStatus(portIndex).get();
}
public void addStream(int portIndex, Stream stream) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("stream_id", stream.getId());
payload.put("stream", stream);
callMethod("add_stream", payload);
}
public void addStream(int portIndex, int streamId, JsonObject stream) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("stream_id", streamId);
payload.put("stream", stream);
callMethod("add_stream", payload);
}
public Stream getStream(int portIndex, int streamId) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("get_pkt", true);
payload.put("stream_id", streamId);
String json = callMethod("get_stream", payload);
JsonElement response = new JsonParser().parse(json);
JsonObject stream = response.getAsJsonArray().get(0)
.getAsJsonObject().get("result")
.getAsJsonObject().get("stream")
.getAsJsonObject();
return GSON.fromJson(stream, Stream.class);
}
public void removeStream(int portIndex, int streamId) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("stream_id", streamId);
callMethod("remove_stream", payload);
}
public void removeAllStreams(int portIndex) {
Map<String, Object> payload = createPayload(portIndex);
callMethod("remove_all_streams", payload);
}
public List<Stream> getAllStreams(int portIndex) {
Map<String, Object> payload = createPayload(portIndex);
String json = callMethod("get_all_streams", payload);
JsonElement response = new JsonParser().parse(json);
JsonObject streams = response.getAsJsonArray().get(0)
.getAsJsonObject().get("result")
.getAsJsonObject().get("streams")
.getAsJsonObject();
ArrayList<Stream> streamList = new ArrayList<>();
for (Map.Entry<String, JsonElement> stream : streams.entrySet()) {
streamList.add(GSON.fromJson(stream.getValue(), Stream.class));
}
return streamList;
}
public List<Integer> getStreamIds(int portIndex) {
Map<String, Object> payload = createPayload(portIndex);
String json = callMethod("get_stream_list", payload);
JsonElement response = new JsonParser().parse(json);
JsonArray ids = response.getAsJsonArray().get(0).getAsJsonObject().get("result").getAsJsonArray();
return StreamSupport.stream(ids.spliterator(), false)
.map(JsonElement::getAsInt)
.collect(Collectors.toList());
}
public void pauseStreams(int portIndex, List<Integer> streams) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("stream_ids", streams);
callMethod("pause_streams", payload);
}
public void resumeStreams(int portIndex, List<Integer> streams) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("stream_ids", streams);
callMethod("resume_streams", payload);
}
public void updateStreams(int portIndex, List<Integer> streams, boolean force,
Map<String, Object> multiplier) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("force", force);
payload.put("mul", multiplier);
payload.put("stream_ids", streams);
callMethod("update_streams", payload);
}
public ActivePGIds getActivePgids() {
Map<String, Object> parameters = new HashMap<>();
parameters.put("pgids", "");
return callMethod("get_active_pgids", parameters, ActivePGIdsRPCResult.class).get().getIds();
}
public PGIdStatsRPCResult getPgidStats(int[] ids) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("pgids", ids);
return callMethod("get_pgid_stats", parameters, PGIdStatsRPCResult.class).get();
}
public void startTraffic(int portIndex, double duration, boolean force, Map<String, Object> mul, int coreMask) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("core_mask", coreMask);
payload.put("mul", mul);
payload.put("duration", duration);
payload.put("force", force);
callMethod("start_traffic", payload);
}
public void pauseTraffic(int portIndex) {
Map<String, Object> payload = createPayload(portIndex);
callMethod("pause_traffic", payload);
}
public void resumeTraffic(int portIndex) {
Map<String, Object> payload = createPayload(portIndex);
callMethod("resume_traffic", payload);
}
public void setRxQueue(int portIndex, int size) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("type", "queue");
payload.put("enabled", true);
payload.put("size", size);
callMethod("set_rx_feature", payload);
}
public void removeRxQueue(int portIndex) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("type", "queue");
payload.put("enabled", false);
callMethod("set_rx_feature", payload);
}
synchronized public void sendPacket(int portIndex, Packet pkt) {
Stream stream = build1PktSingleBurstStream(pkt);
removeAllStreams(portIndex);
addStream(portIndex, stream);
Map<String, Object> mul = new HashMap<>();
mul.put("op", "abs");
mul.put("type", "pps");
mul.put("value", 1.0);
startTraffic(portIndex, 1, true, mul, 1);
}
synchronized public void startStreamsIntermediate(int portIndex, List<Stream> streams) {
removeRxQueue(portIndex);
setRxQueue(portIndex, 1000);
removeAllStreams(portIndex);
streams.forEach(s -> addStream(portIndex, s));
Map<String, Object> mul = new HashMap<>();
mul.put("op", "abs");
mul.put("type", "percentage");
mul.put("value", 100);
startTraffic(portIndex, -1, true, mul, 1);
}
synchronized public void sendPackets(int portIndex, List<Packet> pkts) {
removeAllStreams(portIndex);
for (Packet pkt : pkts) {
addStream(portIndex, build1PktSingleBurstStream(pkt));
}
Map<String, Object> mul = new HashMap<>();
mul.put("op", "abs");
mul.put("type", "pps");
mul.put("value", 1.0);
startTraffic(portIndex, 1, true, mul, 1);
stopTraffic(portIndex);
}
public String resolveArp(int portIndex, String srcIp, String dstIp) {
removeRxQueue(portIndex);
setRxQueue(portIndex, 1000);
String srcMac = getPortByIndex(portIndex).hw_mac;
PortVlan vlan = getPortStatus(portIndex).get().getAttr().getVlan();
EthernetPacket pkt = buildArpPkt(srcMac, srcIp, dstIp, vlan);
sendPacket(portIndex, pkt);
Predicate<EthernetPacket> arpReplyFilter = etherPkt -> {
Queue<Integer> vlanTags = new LinkedList<>(vlan.getTags());
Packet next_pkt = etherPkt;
boolean vlanOutsideMatches = true;
if (etherPkt.getHeader().getType() == QInQ) {
try {
Dot1qVlanTagPacket QInQPkt = Dot1qVlanTagPacket.newPacket(etherPkt.getRawData(),
etherPkt.getHeader().length(), etherPkt.getPayload().length());
vlanOutsideMatches = QInQPkt.getHeader().getVidAsInt() == vlanTags.poll();
next_pkt = QInQPkt.getPayload();
} catch (IllegalRawDataException e) {
return false;
}
}
boolean vlanInsideMatches = true;
if (next_pkt.contains(Dot1qVlanTagPacket.class)) {
Dot1qVlanTagPacket dot1qVlanTagPacket = next_pkt.get(Dot1qVlanTagPacket.class);
vlanInsideMatches = dot1qVlanTagPacket.getHeader().getVid() == vlanTags.poll();
}
if (next_pkt.contains(ArpPacket.class)) {
ArpPacket arp = next_pkt.get(ArpPacket.class);
ArpOperation arpOp = arp.getHeader().getOperation();
String replyDstMac = arp.getHeader().getDstHardwareAddr().toString();
boolean arpMatches = ArpOperation.REPLY.equals(arpOp) && replyDstMac.equals(srcMac);
return arpMatches && vlanOutsideMatches && vlanInsideMatches;
}
return false;
};
List<org.pcap4j.packet.Packet> pkts = new ArrayList<>();
try {
int steps = 10;
while (steps > 0) {
steps -= 1;
Thread.sleep(500);
pkts.addAll(getRxQueue(portIndex, arpReplyFilter));
if (!pkts.isEmpty()) {
ArpPacket arpPacket = getArpPkt(pkts.get(0));
if (arpPacket != null) {
return arpPacket.getHeader().getSrcHardwareAddr().toString();
}
}
}
LOGGER.info("Unable to get ARP reply in {} seconds", steps);
} catch (InterruptedException ignored) {} finally {
removeRxQueue(portIndex);
if (getPortStatus(portIndex).get().getState().equals("TX")) {
stopTraffic(portIndex);
}
removeAllStreams(portIndex);
}
return null;
}
private static ArpPacket getArpPkt(Packet pkt) {
if (pkt.contains(ArpPacket.class)) {
return pkt.get(ArpPacket.class);
}
try {
Dot1qVlanTagPacket unwrapedFromVlanPkt = Dot1qVlanTagPacket.newPacket(pkt.getRawData(),
pkt.getHeader().length(), pkt.getPayload().length());
return unwrapedFromVlanPkt.get(ArpPacket.class);
} catch (IllegalRawDataException ignored) {}
return null;
}
private static EthernetPacket buildArpPkt(String srcMac, String srcIp, String dstIp, PortVlan vlan) {
ArpPacket.Builder arpBuilder = new ArpPacket.Builder();
MacAddress srcMacAddress = MacAddress.getByName(srcMac);
try {
arpBuilder
.hardwareType(ArpHardwareType.ETHERNET)
.protocolType(EtherType.IPV4)
.hardwareAddrLength((byte) MacAddress.SIZE_IN_BYTES)
.protocolAddrLength((byte) ByteArrays.INET4_ADDRESS_SIZE_IN_BYTES)
.operation(ArpOperation.REQUEST)
.srcHardwareAddr(srcMacAddress)
.srcProtocolAddr(InetAddress.getByName(srcIp))
.dstHardwareAddr(MacAddress.getByName("00:00:00:00:00:00"))
.dstProtocolAddr(InetAddress.getByName(dstIp));
} catch (UnknownHostException e) {
throw new IllegalArgumentException(e);
}
AbstractMap.SimpleEntry<EtherType, Packet.Builder> payload = new AbstractMap.SimpleEntry<>(EtherType.ARP,
arpBuilder);
if (!vlan.getTags().isEmpty()) {
payload = buildVlan(arpBuilder, vlan);
}
EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder();
etherBuilder.dstAddr(MacAddress.ETHER_BROADCAST_ADDRESS)
.srcAddr(srcMacAddress)
.type(payload.getKey())
.payloadBuilder(payload.getValue())
.paddingAtBuild(true);
return etherBuilder.build();
}
private static AbstractMap.SimpleEntry<EtherType, Packet.Builder> buildVlan(ArpPacket.Builder arpBuilder,
PortVlan vlan) {
Queue<Integer> vlanTags = new LinkedList<>(Lists.reverse(vlan.getTags()));
Packet.Builder resultPayloadBuilder = arpBuilder;
EtherType resultEtherType = EtherType.ARP;
if (vlanTags.peek() != null) {
Dot1qVlanTagPacket.Builder vlanInsideBuilder = new Dot1qVlanTagPacket.Builder();
vlanInsideBuilder.type(EtherType.ARP)
.vid(vlanTags.poll().shortValue())
.payloadBuilder(arpBuilder);
resultPayloadBuilder = vlanInsideBuilder;
resultEtherType = EtherType.DOT1Q_VLAN_TAGGED_FRAMES;
if (vlanTags.peek() != null) {
Dot1qVlanTagPacket.Builder vlanOutsideBuilder = new Dot1qVlanTagPacket.Builder();
vlanOutsideBuilder.type(EtherType.DOT1Q_VLAN_TAGGED_FRAMES)
.vid(vlanTags.poll().shortValue())
.payloadBuilder(vlanInsideBuilder);
resultPayloadBuilder = vlanOutsideBuilder;
resultEtherType = QInQ;
}
}
return new AbstractMap.SimpleEntry<>(resultEtherType, resultPayloadBuilder);
}
private static Stream build1PktSingleBurstStream(Packet pkt) {
int stream_id = (int) (Math.random() * 1000);
return new Stream(
stream_id,
true,
3,
0.0,
new StreamMode(
2,
2,
1,
1.0,
new StreamModeRate(
StreamModeRate.Type.pps,
1.0),
StreamMode.Type.single_burst),
-1,
pkt,
new StreamRxStats(true, true, true, stream_id),
new StreamVM("", Collections.<VMInstruction> emptyList()),
true,
false,
null,
-1);
}
public List<EthernetPacket> getRxQueue(int portIndex, Predicate<EthernetPacket> filter) {
Map<String, Object> payload = createPayload(portIndex);
String json = callMethod("get_rx_queue_pkts", payload);
JsonElement response = new JsonParser().parse(json);
JsonArray pkts = response.getAsJsonArray().get(0)
.getAsJsonObject().get("result")
.getAsJsonObject()
.getAsJsonArray("pkts");
return StreamSupport.stream(pkts.spliterator(), false)
.map(this::buildEthernetPkt)
.filter(filter)
.collect(Collectors.toList());
}
private EthernetPacket buildEthernetPkt(JsonElement jsonElement) {
try {
byte[] binary = Base64.getDecoder().decode(jsonElement.getAsJsonObject().get("binary").getAsString());
EthernetPacket pkt = EthernetPacket.newPacket(binary, 0, binary.length);
LOGGER.info("Received pkt: {}", pkt.toString());
return pkt;
} catch (IllegalRawDataException e) {
return null;
}
}
public boolean setL3Mode(int portIndex, String nextHopMac, String sourceIp, String destinationIp) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("src_addr", sourceIp);
payload.put("dst_addr", destinationIp);
if (nextHopMac != null) {
payload.put("resolved_mac", nextHopMac);
}
payload.put("block", false);
callMethod("set_l3", payload);
return true;
}
public void updatePortHandler(int portID, String handler) {
portHandlers.put(portID, handler);
}
public void invalidatePortHandler(int portID) {
portHandlers.remove(portID);
}
// TODO: move to upper layer
public EthernetPacket sendIcmpEcho(int portIndex, String host, int reqId, int seqNumber, long waitResponse)
throws UnknownHostException {
Port port = getPortByIndex(portIndex);
PortStatus portStatus = getPortStatus(portIndex).get();
String srcIp = portStatus.getAttr().getLayerConiguration().getL3Configuration().getSrc();
EthernetPacket icmpRequest = buildIcmpV4Request(port.hw_mac, port.dst_macaddr, srcIp, host, reqId, seqNumber);
removeAllStreams(portIndex);
setRxQueue(portIndex, 1000);
sendPacket(portIndex, icmpRequest);
try {
Thread.sleep(waitResponse);
} catch (InterruptedException ignored) {}
try {
List<EthernetPacket> receivedPkts = getRxQueue(portIndex,
etherPkt -> etherPkt.contains(IcmpV4EchoReplyPacket.class));
if (!receivedPkts.isEmpty()) {
return receivedPkts.get(0);
}
return null;
} finally {
removeRxQueue(portIndex);
}
}
// TODO: move to upper layer
private EthernetPacket buildIcmpV4Request(String srcMac, String dstMac, String srcIp, String dstIp, int reqId,
int seqNumber) throws UnknownHostException {
IcmpV4EchoPacket.Builder icmpReqBuilder = new IcmpV4EchoPacket.Builder();
icmpReqBuilder.identifier((short) reqId);
icmpReqBuilder.sequenceNumber((short) seqNumber);
IcmpV4CommonPacket.Builder icmpv4CommonPacketBuilder = new IcmpV4CommonPacket.Builder();
icmpv4CommonPacketBuilder.type(IcmpV4Type.ECHO)
.code(IcmpV4Code.NO_CODE)
.correctChecksumAtBuild(true)
.payloadBuilder(icmpReqBuilder);
IpV4Packet.Builder ipv4Builder = new IpV4Packet.Builder();
ipv4Builder.version(IpVersion.IPV4)
.tos(IpV4Rfc791Tos.newInstance((byte) 0))
.ttl((byte) 64)
.protocol(IpNumber.ICMPV4)
.srcAddr((Inet4Address) Inet4Address.getByName(srcIp))
.dstAddr((Inet4Address) Inet4Address.getByName(dstIp))
.correctChecksumAtBuild(true)
.correctLengthAtBuild(true)
.payloadBuilder(icmpv4CommonPacketBuilder);
EthernetPacket.Builder eb = new EthernetPacket.Builder();
eb.srcAddr(MacAddress.getByName(srcMac))
.dstAddr(MacAddress.getByName(dstMac))
.type(EtherType.IPV4)
.paddingAtBuild(true)
.payloadBuilder(ipv4Builder);
return eb.build();
}
public void stopTraffic(int portIndex) {
Map<String, Object> payload = createPayload(portIndex);
callMethod("stop_traffic", payload);
}
public Map<String, Ipv6Node> scanIPv6(int portIndex) throws ServiceModeRequiredException {
return new IPv6NeighborDiscoveryService(this).scan(portIndex, 10, null, null);
}
public EthernetPacket sendIcmpV6Echo(int portIndex, String dstIp, int icmpId, int icmpSeq, int timeOut)
throws ServiceModeRequiredException {
return new IPv6NeighborDiscoveryService(this).sendIcmpV6Echo(portIndex, dstIp, icmpId, icmpSeq, timeOut);
}
} |
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc5933.Caroline.subsystems;
import org.usfirst.frc5933.Caroline.RobotMap;
import org.usfirst.frc5933.Caroline.commands.*;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.command.Subsystem;
public class RoboRioSystem extends Subsystem {
private final DigitalInput[] dIP_Array_ = { //just add more dIPs to this and the code will adapt.
RobotMap.roboRioSystemDIP1,
RobotMap.roboRioSystemDIP2,
RobotMap.roboRioSystemDIP3,
RobotMap.roboRioSystemDIP4
};
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
//the set of DIPs below is actually unnecessary as long as there are the same ones referenced above.
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
private final DigitalInput dIP1 = RobotMap.roboRioSystemDIP1;
private final DigitalInput dIP2 = RobotMap.roboRioSystemDIP2;
private final DigitalInput dIP3 = RobotMap.roboRioSystemDIP3;
private final DigitalInput dIP4 = RobotMap.roboRioSystemDIP4;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
// setDefaultCommand(new MySpecialCommand());
}
public void robotInit() {
}
public void teleopInit() {
}
public void autonomousInit() {
}
public void teleopPeriodic() {
}
public void autonomousPeriodic() {
}
/*
* The getDIP() method reads the Digital Input pins on the roboRIO
* and returns an integer based on how many switches are flipped.
* For example, if the set of switches is 0011101
* where 0 is closed and 1 is open, this strikingly binary system
* is transformed into 29 and returned.
*/
public int getDIP() {
int bit_field = 0;
int count = 0; //the effective index of dIP_Array_
for(DigitalInput dIP : dIP_Array_){
if(dIP.get()){ //if switched on,
bit_field += Math.pow(2, count); //increment the sum by 2^count
} //so, the above code will take a dIP array of any length and turn it into an integer.
count ++; //next index...
}
return bit_field; //spit the int out.
}
} |
package org.dyfaces.renderer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.application.ResourceDependencies;
import javax.faces.application.ResourceDependency;
import javax.faces.component.UIComponent;
import javax.faces.component.behavior.ClientBehaviorContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.event.ComponentSystemEventListener;
import javax.faces.event.ListenerFor;
import javax.faces.event.PostAddToViewEvent;
import javax.faces.render.FacesRenderer;
import javax.faces.render.Renderer;
import org.dyfaces.DyAttributes;
import org.dyfaces.DyCallbacks;
import org.dyfaces.DyConstants;
import org.dyfaces.DyConstants.Callback;
import org.dyfaces.Version;
import org.dyfaces.component.Dygraph;
import org.dyfaces.data.api.AnnotationConfigurations;
import org.dyfaces.data.api.AnnotationPoint;
import org.dyfaces.data.api.DataModel;
import org.dyfaces.data.api.DataSeries;
import org.dyfaces.data.api.GridOptions;
import org.dyfaces.data.api.GridOptions.Axes;
import org.dyfaces.data.api.GridOptions.PerAxis;
import org.dyfaces.data.api.HighlightRegion;
import org.dyfaces.data.api.Point;
import org.dyfaces.data.api.SeriesColorOptions;
import org.dyfaces.data.api.impl.DyDataModel;
import org.dyfaces.utils.DyUtils;
import org.dyfaces.utils.DyfacesUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@FacesRenderer(componentFamily = Dygraph.COMPONENT_FAMILY, rendererType = DygraphRenderer.RENDERER_TYPE)
@ResourceDependencies({
@ResourceDependency(name = "jsf.js", target = "head", library = "javax.faces"),
@ResourceDependency(library = "webjars", name = Version.DYGRAPH_RESOURCES
+ "/dygraph-combined.js", target = "head"),
@ResourceDependency(library = "webjars", name = Version.DYGRAPH_RESOURCES
+ "/dygraph-interaction-model.js", target = "head"),
@ResourceDependency(library = "webjars", name = Version.UNDERSCORE_RESOURCES
+ "/underscore-min.js", target = "head"),
@ResourceDependency(library = "webjars", name = Version.MOMENT_RESOURCES
+ "/moment.js", target = "head"),
@ResourceDependency(library = "dyfaces", name = "js/dyfaces.js")})
@ListenerFor(systemEventClass = PostAddToViewEvent.class)
public class DygraphRenderer extends Renderer implements ComponentSystemEventListener{
public static final String RENDERER_TYPE = "org.dyfaces.component.graph.renderer";
private static final Gson gson = new Gson();
private static final GsonBuilder builder = new GsonBuilder();
private static final Gson gsonExopse = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
@Override
public void decode(FacesContext context, UIComponent component) {
super.decode(context, component);
}
@Override
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
super.encodeBegin(context, component);
}
@Override
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
/* super.encodeEnd(context, component); */
dygraphMarkup(context, component);
}
private void dygraphMarkup(FacesContext context, UIComponent component) throws IOException {
Dygraph dygraph = (Dygraph) component;
ResponseWriter writer = context.getResponseWriter();
String graphJSVar = dygraph.getClientId(context).replace(":", "_dy");
/*
* start Dygraph creation inside <script> tag
*/
writer.startElement("script", dygraph);
writer.writeAttribute("type", "text/javascript", null);
String dyvar = dygraph.getVar();
String dyjsVar = "";
if(dyvar != null && !dyvar.isEmpty()){
dyjsVar = "var "+dyvar+"=";
}
/*
* assign Dygraph object to javascript variable defined with 'var' attribute
*/
StringBuilder graphBuilder = new StringBuilder(dyjsVar).append("(function () {var "+graphJSVar+"= new Dygraph(");
graphBuilder.append("document.getElementById(\"").append(graphJSVar).append("\"),");
/*
* get Dygraph data defined with either value or model attribute
*/
Map<String,Object> datamodelAttributes = new HashMap<String, Object>(3);
StringBuilder data = getDyGraphData(dygraph,datamodelAttributes);
graphBuilder.append(data.toString());
/*
* get Dygraph attributes
*/
String dygraphAttributes = getDygraphAttribures(dygraph,datamodelAttributes);
/*
* append graph attributes to Dygraph
*/
graphBuilder.append(dygraphAttributes);
graphBuilder.append(");");
/*
* write all Dygraph script to response
*/
writer.write(graphBuilder.toString());
/*
*Add annotations if exists
*/
List<AnnotationPoint> annotations = dygraph.getAnnotations();
if(annotations != null && !annotations.isEmpty()){
addDyAnnotations(context,graphJSVar,dygraph);
}
/*
*Dygraph callback options
*/
bindDyCallbacks(context,graphJSVar,dygraph);
String sync= dygraph.getSynchronize();
if(sync != null && !sync.isEmpty()){
syncDygraphs(sync,context,graphJSVar);
}
writer.write("return "+graphJSVar+"})();");
writer.endElement("script");
}
private void bindDyCallbacks(FacesContext context,String graphJSVar,Dygraph dygraph) throws IOException {
String callbacks = getDygraphCallbacks(dygraph);
ResponseWriter writer = context.getResponseWriter();
StringBuilder graphBuilder = new StringBuilder();
Map<String,Object> callBackMap = gson.fromJson(callbacks, Map.class);
List<HighlightRegion> highlightRegions = dygraph.getHghlightRegions();
if(highlightRegions != null && !highlightRegions.isEmpty()){
String hData = gson.toJson(highlightRegions).replaceAll("\"", "'");
graphBuilder.append("var hd=").append(hData).append(";");
String dyunderlayCallback = "''";
if(callBackMap.containsKey(Callback.UnderlayCallback)){
dyunderlayCallback = "'"+callBackMap.get(Callback.UnderlayCallback)+"'";
}
callBackMap.put(Callback.UnderlayCallback, "dyHighlightRegionFn(hd,"+dyunderlayCallback+")");
}
Boolean graphClickedBehavior = dygraph.getClientBehaviors().containsKey(Dygraph.DEFAULT_EVENT);
if(graphClickedBehavior){
String dyclickCallback = "''";
if(callBackMap.containsKey(Callback.ClickCallback)){
dyclickCallback = "'"+callBackMap.get(Callback.ClickCallback)+"'";
}
String click = getScript(context, dygraph, Dygraph.DEFAULT_EVENT, graphJSVar);
callBackMap.put(Callback.ClickCallback, "dyClickCallbackFn("+dyclickCallback+",\""+click+"\",'"+graphJSVar+"')");
}
Boolean pointClickedBehavior = dygraph.getClientBehaviors().containsKey(Dygraph.EVENT_POINTCLICKED);
if(pointClickedBehavior){
String dyclickCallback = "''";
if(callBackMap.containsKey(Callback.PointClickCallback)){
dyclickCallback = "'"+callBackMap.get(Callback.PointClickCallback)+"'";
}
String pointclick = getScript(context, dygraph, Dygraph.EVENT_POINTCLICKED, graphJSVar);
callBackMap.put(Callback.PointClickCallback, "dyPointClickCallbackFn("+dyclickCallback+",\""+pointclick+"\",'"+graphJSVar+"')");
}
Boolean zoomBehavior = dygraph.getClientBehaviors().containsKey(Dygraph.EVENT_GRAPHZOOMED);
if(zoomBehavior){
String dyzoomCallback = "''";
if(callBackMap.containsKey(Callback.ZoomCallback)){
dyzoomCallback = "'"+callBackMap.get(Callback.ZoomCallback)+"'";
}
String zoom = getScript(context, dygraph, Dygraph.EVENT_GRAPHZOOMED, graphJSVar);
callBackMap.put(Callback.ZoomCallback, "dyZoomCallbackFn("+dyzoomCallback+",\""+zoom+"\",'"+graphJSVar+"')");
}
if(callBackMap == null){
callBackMap = new HashMap<String, Object>();
}
Map<String,Object> annoConfig= bindAnnotationConfiurations(context, graphJSVar, dygraph);
if(annoConfig != null && !annoConfig.isEmpty()){
callBackMap.putAll(annoConfig);
}
Map<String,Object> seriesColorOptions= bindSeriesColorOptions(context, graphJSVar, dygraph);
if(seriesColorOptions != null && !seriesColorOptions.isEmpty()){
callBackMap.putAll(seriesColorOptions);
}
Map<String,Object> gridOptions= bindGridOptions(context, graphJSVar, dygraph);
if(gridOptions != null && !gridOptions.isEmpty()){
callBackMap.putAll(gridOptions);
}
if(!callBackMap.isEmpty()){
graphBuilder.append(graphJSVar).append(".updateOptions(").append(gson.toJsonTree(callBackMap)).append(");");
String updateOptions = graphBuilder.toString().replaceAll("\"", "");
writer.write(updateOptions.replaceAll("\\\\", "\""));
}else if(annoConfig != null && !annoConfig.isEmpty()){
graphBuilder.append(graphJSVar).append(".updateOptions(").append(gson.toJsonTree(annoConfig)).append(");");
String updateOptions = graphBuilder.toString().replaceAll("\"", "");
writer.write(updateOptions.replaceAll("\\\\", "\""));
}
}
private Map<String, Object> bindGridOptions(FacesContext context,
String graphJSVar, Dygraph dygraph) {
Map<String, Object> map = new HashMap<String, Object>();
GridOptions gridOptions = null;
Object dataModel= dygraph.getDyDataModel();
if(dataModel instanceof DataModel){
DataModel dyDataModel = (DyDataModel) dataModel;
if(dyDataModel != null){
//TODO Handle for X, Y and Y2
gridOptions = dyDataModel.getGridOptions();
setGridOptions(gridOptions, map);
}
}else if(dataModel instanceof DataSeries){
DataSeries dataseries = (DataSeries) dataModel;
if(dataseries != null){
gridOptions = dataseries.getGridOptions();
setGridOptions(gridOptions, map);
}
}
return map;
}
private void setGridOptions(GridOptions gridOptions, Map<String, Object> map){
map.put("drawGrid", gridOptions.getDrawGrid());
if(gridOptions.getDrawGrid()){
if(!gridOptions.getDrawXGrid()){
map.put("drawXGrid", gridOptions.getDrawXGrid());
}
if(!gridOptions.getDrawYGrid()){
map.put("drawYGrid", gridOptions.getDrawYGrid());
}
}
map.put("gridLineColor", gridOptions.getGridLineColor());
/*
* check per axes options
*/
List<PerAxis> perAxesList = gridOptions.getAxisGridOptions();
if(perAxesList != null){
Map<Axes,PerAxis> tmp = new HashMap<Axes, PerAxis>(3);
for (PerAxis perAxis : perAxesList) {
tmp.put(perAxis.getAxis(), perAxis);
}
if(!tmp.isEmpty()){
map.put("axes",gson.toJson(tmp).replaceAll("\"", "'"));
}
}
}
private Map<String, Object> bindAnnotationConfiurations(FacesContext context,String graphJSVar,Dygraph dygraph) {
Map<String, Object> map = new HashMap<String, Object>();
AnnotationConfigurations configurations = null;
Object dataModel= dygraph.getDyDataModel();
if(dataModel instanceof DataModel){
DataModel dyDataModel = (DyDataModel) dataModel;
if(dyDataModel != null){
configurations = dyDataModel.getAnnotationConfigurations();
}
}else if(dataModel instanceof DataSeries){
DataSeries dataseries = (DataSeries) dataModel;
if(dataseries != null){
configurations = dataseries.getAnnotationConfigurations();
}
}
if(configurations != null){
String clickHandler = configurations.getClickHandler();
if(clickHandler != null && !clickHandler.isEmpty()){
String annoClick = getScript(context, dygraph, Dygraph.EVENT_ANNOCLICKED, graphJSVar);
map.put("annotationClickHandler", "dyAnnotationClickHandlerFn('"+clickHandler+"',\""+annoClick+"\",'"+graphJSVar+"')");
}
String dblClickHandler = configurations.getDblClickHandler();
if(dblClickHandler != null && !dblClickHandler.isEmpty()){
String dblclick = getScript(context, dygraph, Dygraph.EVENT_ANNODBLCLICKED, graphJSVar);
map.put("annotationDblClickHandler", "dyAnnotationDblClickHandlerFn('"+clickHandler+"',\""+dblclick+"\",'"+graphJSVar+"')");
}
String mouseOutHandler = configurations.getMouseOutHandler();
if(mouseOutHandler != null && !mouseOutHandler.isEmpty()){
map.put("annotationMouseOutHandler", "dyAnnotationMouseOutHandlerFn('"+clickHandler+"')");
}
String mouseOverHandler = configurations.getMouseOverHandler();
if(mouseOverHandler != null && !mouseOverHandler.isEmpty()){
map.put("annotationMouseOverHandler", "dyannotationMouseOverHandlerFn('"+clickHandler+"')");
}
map.put("displayAnnotations", configurations.getShowAnnotations());
}
return map;
}
private Map<String, Object> bindSeriesColorOptions(FacesContext context,
String graphJSVar, Dygraph dygraph) {
Map<String, Object> map = new HashMap<String, Object>();
SeriesColorOptions colorOptions = null;
Object dataModel= dygraph.getDyDataModel();
if(dataModel instanceof DataModel){
DataModel dyDataModel = (DyDataModel) dataModel;
if(dyDataModel != null){
colorOptions = dyDataModel.getSeriesColorOptions();
}
}else if(dataModel instanceof DataSeries){
DataSeries dataseries = (DataSeries) dataModel;
if(dataseries != null){
colorOptions = dataseries.getSeriesColorOptions();
}
}
if(colorOptions != null){
String color = colorOptions.getColor();
if(color != null && !color.isEmpty()){
map.put("color", "'"+color+"'");
}
Float colorValue = colorOptions.getColorValue();
map.put("colorValue", colorValue);
Float fillAlpha = colorOptions.getFillAlpha();
map.put("fillAlpha", fillAlpha);
Float colorSaturation = colorOptions.getColorSaturation();
map.put("colorSaturation ", colorSaturation);
}
return map;
}
private void addDyAnnotations(FacesContext context, String graphJSVar,
Dygraph dygraph) throws IOException {
ResponseWriter writer = context.getResponseWriter();
List<AnnotationPoint> annotations = dygraph.getAnnotations();
StringBuilder graphBuilder = new StringBuilder("var annotations = ");
graphBuilder.append(gson.toJson(annotations)).append(";");
graphBuilder.append(graphJSVar).append(".setAnnotations(annotations);");
writer.write(graphBuilder.toString());
}
/**
*
* @param dygraph
* @return parsed Dygraph data
*/
private StringBuilder getDyGraphData(Dygraph dygraph,Map<String,Object> datamodelAttributes) {
Object dataModel= dygraph.getDyDataModel();
Map<Object,List<Number>> seriesMap = new HashMap<Object, List<Number>>();
StringBuilder data = new StringBuilder("[");
if(dataModel instanceof DataModel){
DataModel dyDataModel = (DyDataModel) dataModel;
if(dyDataModel != null){
if(dyDataModel.getGraphTitle() != null){
datamodelAttributes.put("title", dyDataModel.getGraphTitle());
}
if(dyDataModel.getxAxisLable() != null){
datamodelAttributes.put("xlabel", dyDataModel.getxAxisLable());
}
if(dyDataModel.getyAxisLable() != null){
datamodelAttributes.put("ylabel", dyDataModel.getyAxisLable());
}
List<String> seriesLabels = new ArrayList<String>(dyDataModel.getDataSeries().size());
seriesLabels.add("");
for (DataSeries series : dyDataModel.getDataSeries()) {
String name = series.getSeries();
if(name != null && !name.isEmpty()){
seriesLabels.add(name);
}
List<Point> points = series.getDataPoints();
for (Point point : points) {
if(seriesMap.containsKey(point.getxValue())){
List<Number> tmp = seriesMap.get(point.getxValue());
tmp.add(point.getyValue());
}else{
List<Number> tmp = new ArrayList<Number>();
tmp.add(point.getyValue());
seriesMap.put(point.getxValue(), tmp);
}
}
}
if(!seriesLabels.isEmpty()){
datamodelAttributes.put("labels", seriesLabels);
}
}
List<List<Object>> mergedSerieses = new ArrayList<List<Object>>();
if(!seriesMap.isEmpty()){
for(Map.Entry<Object, List<Number>> entry : seriesMap.entrySet()){
Object key = entry.getKey();
List<Number> value = entry.getValue();
List<Object> dydata= new ArrayList<Object>();
dydata.add(0, key);
for (int i = 1; i <= value.size(); i++) {
dydata.add(i, value.get(i-1));
}
mergedSerieses.add(dydata);
}
}
Collections.sort(mergedSerieses, new Comparator<List<Object>>() {
@Override
public int compare(List<Object> d1, List<Object> d2) {
Object index1 = d1.get(0);
Object index2 = d2.get(0);
if(index1 instanceof Number && index2 instanceof Number){
Number no1 = (Number) index1;
Number no2 = (Number) index2;
if (no1.doubleValue() > no2.doubleValue()) {
return 1;
} else if (no1.doubleValue() < no2.doubleValue()) {
return -1;
} else {
return 0;
}
}else if(index1 instanceof Date && index2 instanceof Date){
Date no1 = (Date) index1;
Date no2 = (Date) index2;
if (no1.before(no2)) {
return 1;
} else if (no1.after(no2)) {
return -1;
} else {
return 0;
}
}
return 0;
}
});
for (List<Object> list : mergedSerieses) {
data.append(list).append(",");
}
}else if(dataModel instanceof List){
/*
* Single Dygraph series with a List<DyPoint>
*/
List<Point> points = (List<Point>) dataModel;
if(points != null && !points.isEmpty()){
/*
* sorted on X axis ascending
*/
Collections.sort(points);
for (Point point : points) {
if(point.getxValue() instanceof Date){
data.append(Arrays.asList(DyUtils.getJSDyDate(point.getxValue()),point.getyValue())).append(",");
}else{
data.append(Arrays.asList(point.getxValue(),point.getyValue())).append(",");
}
}
}
}else if(dataModel instanceof DataSeries){
DataSeries dataseries = (DataSeries) dataModel;
List<String> seriesLabels = new ArrayList<String>(dataseries.getDataPoints().size());
seriesLabels.add("");
if(dataseries != null){
String name = dataseries.getSeries();
if(name != null && !name.isEmpty()){
seriesLabels.add(name);
}
List<Point> points = dataseries.getDataPoints();
Collections.sort(points);
for (Point point : points) {
if(point.getxValue() instanceof Date){
data.append(Arrays.asList(DyUtils.getJSDyDate(point.getxValue()),point.getyValue())).append(",");
}else{
data.append(Arrays.asList(point.getxValue(),point.getyValue())).append(",");
}
}
if(!seriesLabels.isEmpty()){
datamodelAttributes.put("labels", seriesLabels);
}
List<AnnotationPoint> annotationPoints = dataseries.getAnnotations();
if(annotationPoints != null && !annotationPoints.isEmpty()){
dygraph.setAnnotations(annotationPoints);
}
List<HighlightRegion> highlightRegions = dataseries.getHighlightRegions();
if(highlightRegions != null && !highlightRegions.isEmpty()){
dygraph.setHighlightRegions(highlightRegions);
}
}
}
data.append("],");
return data;
}
/**
*
* @param dygraph
* @return Json string of Dygraph attributes
*/
private String getDygraphAttribures(Dygraph dygraph,Map<String,Object> datamodelAttributes) {
Map<String,Object> attr = dygraph.getAttributes();
DyAttributes attributes = builder.create().fromJson(gson.toJson(attr), DyAttributes.class);
if(!datamodelAttributes.isEmpty()){
if(datamodelAttributes.containsKey("title")){
attributes.setTitle((String) datamodelAttributes.get("title"));
}
if (datamodelAttributes.containsKey("xlabel")) {
attributes.setXlabel((String) datamodelAttributes.get("xlabel"));
}
if (datamodelAttributes.containsKey("ylabel")) {
attributes.setYlabel((String) datamodelAttributes.get("ylabel"));
}
if (datamodelAttributes.containsKey("labels")) {
List<String> labels = List.class.cast(datamodelAttributes.get("labels"));
if(labels.size() > 1){
attributes.setLabels(labels);
}
}
}
return gson.toJson(attributes);
}
/**
*
* @param dygraph
* @return Json string of Dygraph callback function name
*/
private String getDygraphCallbacks(Dygraph dygraph) {
Map<String,Object> attr = dygraph.getAttributes();
DyCallbacks attributes = builder.create().fromJson(gson.toJson(attr), DyCallbacks.class);
return gson.toJson(attributes).replaceAll("\"", "");
}
private void syncDygraphs(String sync,FacesContext context,String dygraph) throws IOException {
ResponseWriter writer = context.getResponseWriter();
sync=sync+","+dygraph;
String[] graphs = sync.split(",");
StringBuilder graphBuilder = new StringBuilder("var sgs = ");
graphBuilder.append(Arrays.toString(graphs)).append(";");
graphBuilder.append("var sync = Dygraph.synchronize(sgs,{ selection: false, zoom: true})").append(";");
writer.write(graphBuilder.toString());
}
private void initTooltip(FacesContext context,String dygraph) throws IOException{
ResponseWriter writer = context.getResponseWriter();
StringBuilder graphBuilder = new StringBuilder("var tooltip = $('#").append(dygraph).append("').qtip({id: '").append(dygraph).append("',prerender: true,content: ' ',position: {target: 'mouse',viewport: $('#").append(dygraph).append("'),adjust: { x: 5, y: 5 } }, show: false,});");
writer.write(graphBuilder.toString());
}
@Override
public void processEvent(ComponentSystemEvent event)
throws AbortProcessingException {
/*
* dynamic resource loading
*/
if (event instanceof PostAddToViewEvent) {
final FacesContext context = FacesContext.getCurrentInstance();
addScript(context,event);
}
}
private void addScript(FacesContext context,ComponentSystemEvent event) {
/*
* check if jquery is required
*/
Dygraph dygraph = (Dygraph) event.getSource();
UIComponent head = context.getViewRoot().getFacet("javax_faces_location_HEAD");
if (head == null) {
return;
}
boolean jqueryAdded = true;
for (UIComponent c : head.getChildren()) {
if (c.getAttributes().get("name").toString().endsWith("jquery.js")) {
jqueryAdded = false;
}
}
if (jqueryAdded) {
DyfacesUtils.addScriptResource(context, "dyfaces-jquery", Version.JQUERY_RESOURCES+"/jquery.min.js");
}
boolean addQtip = false;
if(dygraph.isTooltip() != null && dygraph.isTooltip() == true){
addQtip = true;
}
if(addQtip){
DyfacesUtils.addStyleResource(context, "dyfaces-qtip2css", Version.QTIP2_RESOURCES+"/jquery.qtip.min.css");
DyfacesUtils.addScriptResource(context, "dyfaces-qtip2js", Version.QTIP2_RESOURCES+"/jquery.qtip.min.js");
}
boolean addSyncjs = false;
if(dygraph.getSynchronize() != null && !dygraph.getSynchronize().isEmpty()){
addSyncjs = true;
}
if(addSyncjs){
DyfacesUtils.addScriptResource(context, "dyfaces-sync", "synchronizer.js","dygraph");
}
}
public String getScript(FacesContext context, Dygraph dygraph, String event, String graphJSVar){
ClientBehaviorContext behaviorContext = ClientBehaviorContext.createClientBehaviorContext(context, dygraph, event, graphJSVar, null);
String eventJs = dygraph.getClientBehaviors().get(event).get(0).getScript(behaviorContext);
return eventJs;
}
} |
package com.constantcontact;
import com.constantcontact.components.accounts.AccountInfo;
import com.constantcontact.components.accounts.VerifiedEmailAddress;
import com.constantcontact.components.activities.contacts.request.AddContactsRequest;
import com.constantcontact.components.activities.contacts.request.ClearListsRequest;
import com.constantcontact.components.activities.contacts.request.ExportContactsRequest;
import com.constantcontact.components.activities.contacts.request.RemoveContactsRequest;
import com.constantcontact.components.activities.contacts.response.ContactsResponse;
import com.constantcontact.components.activities.contacts.response.DetailedStatusReport;
import com.constantcontact.components.activities.contacts.response.SummaryReport;
import com.constantcontact.components.common.tracking.TrackingBase;
import com.constantcontact.components.contacts.Contact;
import com.constantcontact.components.contacts.ContactList;
import com.constantcontact.components.contacts.tracking.TrackingContactsBase;
import com.constantcontact.components.contacts.tracking.bounces.ContactTrackingBounce;
import com.constantcontact.components.contacts.tracking.clicks.ContactTrackingClick;
import com.constantcontact.components.contacts.tracking.forwards.ContactTrackingForward;
import com.constantcontact.components.contacts.tracking.opens.ContactTrackingOpen;
import com.constantcontact.components.contacts.tracking.reports.summary.ContactTrackingSummaryByCampaignReport;
import com.constantcontact.components.contacts.tracking.reports.summary.ContactTrackingSummaryReport;
import com.constantcontact.components.contacts.tracking.sends.ContactTrackingSend;
import com.constantcontact.components.contacts.tracking.unsubscribes.ContactTrackingUnsubscribe;
import com.constantcontact.components.emailcampaigns.EmailCampaignBase;
import com.constantcontact.components.emailcampaigns.EmailCampaignRequest;
import com.constantcontact.components.emailcampaigns.EmailCampaignResponse;
import com.constantcontact.components.emailcampaigns.schedules.EmailCampaignSchedule;
import com.constantcontact.components.emailcampaigns.tracking.bounces.EmailCampaignTrackingBounce;
import com.constantcontact.components.emailcampaigns.tracking.clicks.EmailCampaignTrackingClick;
import com.constantcontact.components.emailcampaigns.tracking.forwards.EmailCampaignTrackingForward;
import com.constantcontact.components.emailcampaigns.tracking.opens.EmailCampaignTrackingOpen;
import com.constantcontact.components.emailcampaigns.tracking.reports.summary.EmailCampaignTrackingSummary;
import com.constantcontact.components.emailcampaigns.tracking.sends.EmailCampaignTrackingSend;
import com.constantcontact.components.emailcampaigns.tracking.unsubscribes.EmailCampaignTrackingUnsubscribe;
import com.constantcontact.components.eventspot.*;
import com.constantcontact.components.eventspot.Registrant.Registrant;
import com.constantcontact.components.eventspot.Registrant.RegistrantDetails;
import com.constantcontact.components.generic.response.Pagination;
import com.constantcontact.components.generic.response.ResultSet;
import com.constantcontact.components.library.file.FileType;
import com.constantcontact.components.library.file.ImageSource;
import com.constantcontact.components.library.file.MyLibraryFile;
import com.constantcontact.components.library.folder.MyLibraryFolder;
import com.constantcontact.components.library.folder.MyLibraryFolder.FolderSortOptions;
import com.constantcontact.components.library.info.MoveResults;
import com.constantcontact.components.library.info.MyLibrarySummary;
import com.constantcontact.components.library.info.UploadStatus;
import com.constantcontact.exceptions.ConstantContactException;
import com.constantcontact.exceptions.service.ConstantContactServiceException;
import com.constantcontact.pagination.PaginationHelperService;
import com.constantcontact.services.accounts.AccountService;
import com.constantcontact.services.accounts.IAccountService;
import com.constantcontact.services.activities.BulkActivitiesService;
import com.constantcontact.services.activities.IBulkActivitiesService;
import com.constantcontact.services.contactlists.ContactListService;
import com.constantcontact.services.contactlists.IContactListService;
import com.constantcontact.services.contacts.ContactService;
import com.constantcontact.services.contacts.IContactService;
import com.constantcontact.services.contacts.tracking.ContactTrackingService;
import com.constantcontact.services.contacts.tracking.IContactTrackingService;
import com.constantcontact.services.emailcampaigns.EmailCampaignService;
import com.constantcontact.services.emailcampaigns.IEmailCampaignService;
import com.constantcontact.services.emailcampaigns.schedule.EmailCampaignScheduleService;
import com.constantcontact.services.emailcampaigns.schedule.IEmailCampaignScheduleService;
import com.constantcontact.services.emailcampaigns.tracking.EmailCampaignTrackingService;
import com.constantcontact.services.emailcampaigns.tracking.IEmailCampaignTrackingService;
import com.constantcontact.services.eventspot.EventSpotService;
import com.constantcontact.services.eventspot.IEventSpotService;
import com.constantcontact.services.library.IMyLibraryService;
import com.constantcontact.services.library.MyLibraryService;
import com.constantcontact.util.Config;
import com.constantcontact.util.Config.Errors;
import com.constantcontact.util.http.MultipartBody;
import com.constantcontact.util.http.MultipartBuilder;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Main Constant Contact class.<br/>
* This is meant to be used by users to access Constant Contact API functionality.<br/>
* <ul>
* <li>{@link ContactService}</li>
* <li>{@link ContactListService}</li>
* <li>{@link EmailCampaignService}</li>
* <li>{@link AccountService}</li>
* <li>{@link EmailCampaignScheduleService}</li>
* <li>{@link EmailCampaignTrackingService}</li>
* <li>{@link ContactTrackingService}</li>
* <li>{@link BulkActivitiesService}</li>
* </ul>
*
* @author ConstantContact
*/
public class ConstantContact {
private String accessToken;
public static String API_KEY;
private IContactService contactService;
private IContactListService contactListService;
private IEmailCampaignService emailCampaignService;
private IAccountService accountService;
private IEmailCampaignScheduleService emailCampaignScheduleService;
private IEmailCampaignTrackingService emailCampaignTrackingService;
private IContactTrackingService contactTrackingService;
private IBulkActivitiesService bulkActivitiesService;
private IMyLibraryService myLibraryService;
private IEventSpotService eventSpotService;
private PaginationHelperService paginationHelperService;
/**
* Custom Class constructor.<br/>
* Initializes all Services;
*
* @param apiKey The API key provided by Constant Contact.
* @param accessToken The access token provided by Constant Contact Authentication workflow.
*/
public ConstantContact(String apiKey, String accessToken) {
this.accessToken = accessToken;
ConstantContact.API_KEY = apiKey;
this.setContactService(new ContactService());
this.setListService(new ContactListService());
this.setEmailCampaignService(new EmailCampaignService());
this.setAccountService(new AccountService());
this.setEmailCampaignScheduleService(new EmailCampaignScheduleService());
this.setEmailCampaignTrackingService(new EmailCampaignTrackingService());
this.setContactTrackingService(new ContactTrackingService());
this.setBulkActivitiesService(new BulkActivitiesService());
this.setMyLibraryService(new MyLibraryService());
this.setEventSpotService(new EventSpotService());
this.setPaginationHelperService(new PaginationHelperService());
}
/**
* Get the access token.<br/>
*
* @return The access token.
*/
public String getAccessToken() {
return accessToken;
}
/**
* Get the Contact service.
*
* @return The Contact service.
*/
public IContactService getContactService() {
return contactService;
}
/**
* Set the Contact service.
*
* @param contactService The Contact service.
*/
public void setContactService(IContactService contactService) {
this.contactService = contactService;
}
/**
* Get the List service.
*
* @return The List service.
*/
public IContactListService getListService() {
return contactListService;
}
/**
* Set the List service.
*
* @param contactListService The List service.
*/
public void setListService(IContactListService contactListService) {
this.contactListService = contactListService;
}
/**
* Set the {@link EmailCampaignService}
*
* @param emailCampaignService The {@link EmailCampaignService}
*/
public void setEmailCampaignService(IEmailCampaignService emailCampaignService) {
this.emailCampaignService = emailCampaignService;
}
/**
* Get the {@link EmailCampaignService}
*
* @return The {@link EmailCampaignService}
*/
public IEmailCampaignService getEmailCampaignService() {
return emailCampaignService;
}
/**
* Set the {@link AccountService}
*
* @param accountService The {@link AccountService}
*/
public void setAccountService(IAccountService accountService) {
this.accountService = accountService;
}
/**
* Get the {@link AccountService}
*
* @return The {@link AccountService}
*/
public IAccountService getAccountService() {
return accountService;
}
/**
* Set the {@link MyLibraryService}
*
* @param myLibraryService The {@link MyLibraryService}
*/
public void setMyLibraryService(IMyLibraryService myLibraryService) {
this.myLibraryService = myLibraryService;
}
/**
* Get the {@link MyLibraryService}
*
* @return The {@link MyLibraryService}
*/
public IMyLibraryService getMyLibraryService() {
return myLibraryService;
}
/**
* Set the {@link EmailCampaignScheduleService}
*
* @param emailCampaignScheduleService The {@link EmailCampaignScheduleService}
*/
public void setEmailCampaignScheduleService(IEmailCampaignScheduleService emailCampaignScheduleService) {
this.emailCampaignScheduleService = emailCampaignScheduleService;
}
/**
* Get the {@link EmailCampaignScheduleService}
*
* @return The {@link EmailCampaignScheduleService}
*/
public IEmailCampaignScheduleService getEmailCampaignScheduleService() {
return emailCampaignScheduleService;
}
/**
* Set the {@link EmailCampaignTrackingService}
*
* @param emailCampaignTrackingSummaryService The {@link EmailCampaignTrackingService}
*/
public void setEmailCampaignTrackingService(IEmailCampaignTrackingService emailCampaignTrackingSummaryService) {
this.emailCampaignTrackingService = emailCampaignTrackingSummaryService;
}
/**
* Get the {@link EmailCampaignTrackingService}
*
* @return The {@link EmailCampaignTrackingService}
*/
public IEmailCampaignTrackingService getEmailCampaignTrackingService() {
return emailCampaignTrackingService;
}
/**
* Set the {@link ContactTrackingService}
*
* @param contactTrackingService The {@link ContactTrackingService}
*/
public void setContactTrackingService(IContactTrackingService contactTrackingService) {
this.contactTrackingService = contactTrackingService;
}
/**
* Get the {@link ContactTrackingService}
*
* @return The {@link ContactTrackingService}
*/
public IContactTrackingService getContactTrackingService() {
return contactTrackingService;
}
/**
* Set the {@link BulkActivitiesService}
*
* @param bulkActivitiesService The {@link BulkActivitiesService}
*/
public void setBulkActivitiesService(IBulkActivitiesService bulkActivitiesService) {
this.bulkActivitiesService = bulkActivitiesService;
}
/**
* Get the {@link BulkActivitiesService}
*
* @return The {@link BulkActivitiesService}
*/
public IBulkActivitiesService getBulkActivitiesService() {
return bulkActivitiesService;
}
/**
* Get the {@link EventSpotService}
*
* @return The {@link EventSpotService}
*/
public IEventSpotService getEventSpotService() {
return eventSpotService;
}
/**
* Set the {@link EventSpotService}
*
* @param eventSpotService The {@link EventSpotService}
*/
public void setEventSpotService(IEventSpotService eventSpotService) {
this.eventSpotService = eventSpotService;
}
/**
* Get the {@link PaginationHelperService}
*
* @return The {@link PaginationHelperService}
*/
public PaginationHelperService getPaginationHelperService(){
return paginationHelperService;
}
/**
* Set the {@link PaginationHelperService}
*
* @param paginationHelperService The {@link PaginationHelperService}
*/
public void setPaginationHelperService(PaginationHelperService paginationHelperService) {
this.paginationHelperService = paginationHelperService;
}
/**
* Get contacts API. <br/>
* Details in : {@link ContactService#getContacts(String, Integer, String)}
*
* @param limit The maximum number of results to return - can be null.
* @param modifiedSinceTimestamp This time stamp is an ISO-8601 ordinal date supporting offset. <br/>
* It will return only the contacts modified since the supplied date. <br/>
* If you want to bypass this filter set modifiedSinceTimestamp to null.
* @param status Return only records with the given status. Does not support VISITOR or NON_SUBSCRIBER
* @return The contacts.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public ResultSet<Contact> getContacts(Integer limit, String modifiedSinceTimestamp, Contact.Status status) throws ConstantContactServiceException {
if (status != null && (status.equals(Contact.Status.VISITOR) || status.equals(Contact.Status.NON_SUBSCRIBER))){
throw new IllegalArgumentException(Config.Errors.STATUS + " ACTIVE, OPTOUT, REMOVED, UNCONFIRMED.");
}
return contactService.getContacts(this.getAccessToken(), limit, modifiedSinceTimestamp, status);
}
public ResultSet<Contact> getContacts(Pagination pagination) throws ConstantContactServiceException,
IllegalArgumentException {
if(pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, Contact.class);
}
/**
* Get contact API.<br/>
* Details in : {@link ContactService#getContact(String, String)}
*
* @param contactId The contact id.
* @return The contact.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public Contact getContact(String contactId) throws ConstantContactServiceException {
return contactService.getContact(this.getAccessToken(), contactId);
}
/**
* Get Contact By Email API.<br/>
* Details in : {@link ContactService#getContactByEmail(String, String)}
*
* @param email The email address.
* @return A {@link ResultSet} of {@link Contact}.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public ResultSet<Contact> getContactByEmail(String email) throws ConstantContactServiceException {
String encodedEmail = null;
try
{
encodedEmail = URLEncoder.encode(email, "UTF-8");
}
catch(UnsupportedEncodingException ex)
{
throw new IllegalStateException(ex);
}
return contactService.getContactByEmail(this.getAccessToken(), encodedEmail);
}
/**
* Add Contact API.<br/>
* Details in : {@link ContactService#addContact(String, Contact, Boolean)}
*
* @param contact The {@link Contact} to add.
* @return The added contact.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public Contact addContact(Contact contact, Boolean actionByVisitor) throws ConstantContactServiceException {
return contactService.addContact(this.getAccessToken(), contact, actionByVisitor.booleanValue());
}
/**
* Add Contact API.<br/>
* Details in : {@link ContactService#addContact(String, Contact, Boolean)}
*
* @param contact The {@link Contact} to add.
* @return The added contact.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public Contact addContact(Contact contact) throws ConstantContactServiceException {
return contactService.addContact(this.getAccessToken(), contact, false);
}
public boolean deleteContact(Contact contact) throws IllegalArgumentException, ConstantContactServiceException {
if (contact == null) {
throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID);
}
return deleteContact(contact.getId());
}
public boolean deleteContact(String contactId) throws IllegalArgumentException, ConstantContactServiceException {
try {
int nContactId = Integer.parseInt(contactId);
if (nContactId < 1) {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID);
}
return contactService.deleteContact(this.getAccessToken(), contactId);
}
public boolean deleteContactFromLists(String contactId) throws IllegalArgumentException, ConstantContactServiceException {
try {
int nContactId = Integer.parseInt(contactId);
if (nContactId < 1) {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID);
}
return contactService.deleteContactFromLists(this.getAccessToken(), contactId);
}
/**
* Delete Contact From Lists API.<br/>
* Details in : {@link ContactService#deleteContactFromLists(String, String)}
*
* @param contact The Contact to delete. Match is done on id.
* @return true in case of success, an exception is thrown otherwise.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public boolean deleteContactFromLists(Contact contact) throws ConstantContactServiceException {
if (contact == null) {
throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID);
}
return contactService.deleteContactFromLists(this.getAccessToken(), contact.getId());
}
public boolean deleteContactFromList(Contact contact, ContactList list) throws IllegalArgumentException, ConstantContactServiceException {
if (contact == null) {
throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID);
}
if (list == null) {
throw new IllegalArgumentException(Config.Errors.LIST_OR_ID);
}
return contactService.deleteContactFromList(this.getAccessToken(), contact.getId(), list.getId());
}
public boolean deleteContactFromList(String contactId, String listId) throws IllegalArgumentException, ConstantContactServiceException {
try {
int nContactId = Integer.parseInt(contactId);
if (nContactId < 1) {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID);
}
try {
int nListId = Integer.parseInt(listId);
if (nListId < 1) {
throw new NumberFormatException();
}
} catch (Exception e) {
throw new IllegalArgumentException(Config.Errors.LIST_OR_ID);
}
return contactService.deleteContactFromList(this.getAccessToken(), contactId, listId);
}
public Contact updateContact(Contact contact) throws IllegalArgumentException, ConstantContactServiceException {
if (contact == null) {
throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID);
}
if (contact.getId() == null || !(contact.getId().length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return contactService.updateContact(this.getAccessToken(), contact, false);
}
public Contact updateContact(Contact contact, Boolean actionByVisitor) throws IllegalArgumentException, ConstantContactServiceException {
if (contact == null) {
throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID);
}
if (contact.getId() == null || !(contact.getId().length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return contactService.updateContact(this.getAccessToken(), contact, actionByVisitor.booleanValue());
}
/**
* Get Contact Lists API.<br/>
* Details in : {@link ContactListService#getLists(String, String)}
*
* @param modifiedSinceTimestamp This time stamp is an ISO-8601 ordinal date supporting offset. <br/>
* It will return only the contact lists modified since the supplied date. <br/>
* If you want to bypass this filter set modifiedSinceTimestamp to null.
*
* @return The Contact Lists in case of success; an exception is thrown otherwise.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public List<ContactList> getLists(String modifiedSinceTimestamp) throws ConstantContactServiceException {
return contactListService.getLists(this.getAccessToken(), modifiedSinceTimestamp);
}
public ContactList getList(String listId) throws IllegalArgumentException, ConstantContactServiceException {
try {
int nListId = Integer.parseInt(listId);
if (nListId < 1) {
throw new NumberFormatException();
}
} catch (Exception e) {
throw new IllegalArgumentException(Config.Errors.LIST_OR_ID);
}
return contactListService.getList(this.getAccessToken(), listId);
}
public ContactList addList(ContactList list) throws IllegalArgumentException, ConstantContactServiceException {
try {
return contactListService.addList(this.getAccessToken(), list);
} catch (ConstantContactServiceException e) {
throw new ConstantContactServiceException(e);
}
}
public ResultSet<Contact> getContactsFromList(ContactList list) throws IllegalArgumentException, ConstantContactServiceException {
if (list == null) {
throw new IllegalArgumentException(Config.Errors.LIST_OR_ID);
}
return contactListService.getContactsFromList(this.getAccessToken(), list.getId(), null, null);
}
public ResultSet<Contact> getContactsFromList(String listId) throws IllegalArgumentException, ConstantContactServiceException {
try {
int nListId = Integer.parseInt(listId);
if (nListId < 1) {
throw new NumberFormatException();
}
} catch (Exception e) {
throw new IllegalArgumentException(Config.Errors.LIST_OR_ID);
}
try {
return contactListService.getContactsFromList(this.getAccessToken(), listId, null, null);
} catch (ConstantContactServiceException e) {
throw new ConstantContactServiceException(e);
}
}
public ResultSet<Contact> getContactsFromList(ContactList list, Integer limit, String modifiedSinceTimestamp) throws IllegalArgumentException,
ConstantContactServiceException {
if (list == null) {
throw new IllegalArgumentException(Config.Errors.LIST_OR_ID);
}
return contactListService.getContactsFromList(this.getAccessToken(), list.getId(), limit, modifiedSinceTimestamp);
}
public ResultSet<Contact> getContactsFromList(Pagination pagination)
throws IllegalArgumentException, ConstantContactServiceException {
if (pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, Contact.class);
}
public ResultSet<EmailCampaignResponse> getEmailCampaigns() throws IllegalArgumentException, ConstantContactServiceException {
return emailCampaignService.getCampaigns(this.getAccessToken(), null, null);
}
public ResultSet<EmailCampaignResponse> getEmailCampaigns(Integer limit, String modifiedSinceTimestamp) throws IllegalArgumentException,
ConstantContactServiceException {
return emailCampaignService.getCampaigns(this.getAccessToken(), limit, modifiedSinceTimestamp);
}
public ResultSet<EmailCampaignResponse> getEmailCampaigns(Pagination pagination) throws IllegalArgumentException,
ConstantContactServiceException, IllegalArgumentException {
if(pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignResponse.class);
}
public EmailCampaignResponse getEmailCampaign(String campaignId) throws IllegalArgumentException, ConstantContactServiceException {
if (campaignId == null || !(campaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignService.getCampaign(this.getAccessToken(), campaignId);
}
public EmailCampaignResponse updateEmailCampaign(EmailCampaignRequest emailCampaign) throws IllegalArgumentException, ConstantContactServiceException {
if (emailCampaign == null || !(emailCampaign.getId().length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignService.updateCampaign(this.getAccessToken(), emailCampaign);
}
public EmailCampaignResponse addEmailCampaign(EmailCampaignRequest emailCampaign) throws IllegalArgumentException, ConstantContactServiceException {
if (emailCampaign == null) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignService.addCampaign(this.getAccessToken(), emailCampaign);
}
/**
*
* Delete Email Campaign API.<br/>
* Details in : {@link EmailCampaignService#deleteCampaign(String)}
*
* @param emailCampaignId The Email Campaign to delete
* @return True in case of success; an exception is thrown otherwise.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public boolean deleteEmailCampaign(String emailCampaignId) throws ConstantContactServiceException {
return emailCampaignService.deleteCampaign(this.getAccessToken(), emailCampaignId);
}
public List<VerifiedEmailAddress> getVerifiedEmailAddresses(String status) throws IllegalArgumentException, ConstantContactServiceException {
if (status != null && status.length() > 0) {
if (!status.equals(VerifiedEmailAddress.Status.CONFIRMED) && !status.equals(VerifiedEmailAddress.Status.UNCONFIRMED))
throw new IllegalArgumentException(Config.Errors.STATUS + VerifiedEmailAddress.Status.CONFIRMED + ", " + VerifiedEmailAddress.Status.CONFIRMED);
}
return accountService.getVerifiedEmailAddresses(this.getAccessToken(), status);
}
public List<EmailCampaignSchedule> getEmailCampaignSchedules(String campaignId) throws IllegalArgumentException, ConstantContactServiceException {
if (campaignId == null || !(campaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignScheduleService.getSchedules(this.getAccessToken(), campaignId);
}
public EmailCampaignSchedule getEmailCampaignSchedule(String campaignId, String scheduleId) throws IllegalArgumentException,
ConstantContactServiceException {
if (campaignId == null || !(campaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
if (scheduleId == null || !(campaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignScheduleService.getSchedule(this.getAccessToken(), campaignId, scheduleId);
}
public boolean deleteEmailCampaignSchedule(String campaignId, String scheduleId) throws IllegalArgumentException, ConstantContactServiceException {
if (campaignId == null || !(campaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
if (scheduleId == null || !(campaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignScheduleService.deleteSchedule(this.getAccessToken(), campaignId, scheduleId);
}
public EmailCampaignSchedule addEmailCampaignSchedule(String campaignId, EmailCampaignSchedule emailCampaignSchedule) throws IllegalArgumentException,
ConstantContactServiceException {
if (campaignId == null || !(campaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
if (emailCampaignSchedule == null) {
throw new IllegalArgumentException(Config.Errors.EMAIL_CAMPAIGN_SCHEDULE_NULL);
}
return emailCampaignScheduleService.addSchedule(this.getAccessToken(), campaignId, emailCampaignSchedule);
}
public EmailCampaignSchedule updateEmailCampaignSchedule(String emailCampaignId, String scheduleId, EmailCampaignSchedule emailCampaignSchedule)
throws IllegalArgumentException, ConstantContactServiceException {
if (emailCampaignId == null || !(emailCampaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
if (emailCampaignSchedule == null) {
throw new IllegalArgumentException(Config.Errors.EMAIL_CAMPAIGN_SCHEDULE_NULL);
}
return emailCampaignScheduleService.updateSchedule(this.getAccessToken(), emailCampaignId, scheduleId, emailCampaignSchedule);
}
public EmailCampaignTrackingSummary getEmailCampaignTrackingSummary(String emailCampaignId, String createdSinceTimestamp) throws IllegalArgumentException,
ConstantContactServiceException {
if (emailCampaignId == null || !(emailCampaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignTrackingService.getSummary(this.getAccessToken(), emailCampaignId, createdSinceTimestamp);
}
public ResultSet<EmailCampaignTrackingBounce> getEmailCampaignTrackingBounces(String emailCampaignId, Integer limit)
throws ConstantContactServiceException, IllegalArgumentException {
if (emailCampaignId == null || !(emailCampaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignTrackingService.getBounces(this.getAccessToken(), emailCampaignId, limit);
}
public ResultSet<EmailCampaignTrackingBounce> getEmailCampaignTrackingBounces(Pagination pagination) throws ConstantContactServiceException,
IllegalArgumentException {
if (pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingBounce.class);
}
public ResultSet<EmailCampaignTrackingClick> getEmailCampaignTrackingClicks(String emailCampaignId, Integer limit, String createdSinceTimestamp) throws ConstantContactServiceException,
IllegalArgumentException {
if (emailCampaignId == null || !(emailCampaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignTrackingService.getClicks(this.getAccessToken(), emailCampaignId, limit, createdSinceTimestamp);
}
public ResultSet<EmailCampaignTrackingClick> getEmailCampaignTrackingClicks(Pagination pagination) throws ConstantContactServiceException,
IllegalArgumentException {
if (pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingClick.class);
}
public ResultSet<EmailCampaignTrackingForward> getEmailCampaignTrackingForwards(String emailCampaignId, Integer limit, String createdSinceTimestamp)
throws ConstantContactServiceException, IllegalArgumentException {
if (emailCampaignId == null || !(emailCampaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignTrackingService.getForwards(this.getAccessToken(), emailCampaignId, limit, createdSinceTimestamp);
}
public ResultSet<EmailCampaignTrackingForward> getEmailCampaignTrackingForwards(Pagination pagination)
throws ConstantContactServiceException, IllegalArgumentException {
if (pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingForward.class);
}
public ResultSet<EmailCampaignTrackingOpen> getEmailCampaignTrackingOpens(String emailCampaignId, Integer limit, String createdSinceTimestamp) throws ConstantContactServiceException,
IllegalArgumentException {
if (emailCampaignId == null || !(emailCampaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignTrackingService.getOpens(this.getAccessToken(), emailCampaignId, limit, createdSinceTimestamp);
}
public ResultSet<EmailCampaignTrackingOpen> getEmailCampaignTrackingOpens(Pagination pagination) throws ConstantContactServiceException,
IllegalArgumentException {
if (pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingOpen.class);
}
public ResultSet<EmailCampaignTrackingSend> getEmailCampaignTrackingSends(String emailCampaignId, Integer limit, String createdSinceTimestamp) throws ConstantContactServiceException,
IllegalArgumentException {
if (emailCampaignId == null || !(emailCampaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignTrackingService.getSends(this.getAccessToken(), emailCampaignId, limit,
createdSinceTimestamp);
}
public ResultSet<EmailCampaignTrackingSend> getEmailCampaignTrackingSends(Pagination pagination) throws ConstantContactServiceException,
IllegalArgumentException {
if (pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingSend.class);
}
public ResultSet<EmailCampaignTrackingUnsubscribe> getEmailCampaignTrackingUnsubscribes(String emailCampaignId, Integer limit, String createdSinceTimestamp)
throws ConstantContactServiceException, IllegalArgumentException {
if (emailCampaignId == null || !(emailCampaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignTrackingService.getUnsubscribes(this.getAccessToken(), emailCampaignId, limit, createdSinceTimestamp);
}
public ResultSet<EmailCampaignTrackingUnsubscribe> getEmailCampaignTrackingUnsubscribes(Pagination pagination)
throws ConstantContactServiceException, IllegalArgumentException {
if (pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingUnsubscribe.class);
}
public ResultSet<EmailCampaignTrackingClick> getEmailCampaignTrackingClicksByLink(String emailCampaignId, String linkId, Integer limit, String createdSinceTimestamp)
throws ConstantContactServiceException, IllegalArgumentException {
if (emailCampaignId == null || !(emailCampaignId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return emailCampaignTrackingService.getClicksByLinkId(this.getAccessToken(), emailCampaignId, linkId, limit, createdSinceTimestamp);
}
public ResultSet<EmailCampaignTrackingClick> getEmailCampaignTrackingClicksByLink(Pagination pagination)
throws ConstantContactServiceException, IllegalArgumentException {
if (pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingClick.class);
}
public ContactTrackingSummaryReport getContactTrackingSummary(String contactId, String createdSinceTimestamp) throws IllegalArgumentException, ConstantContactServiceException {
if (contactId == null || !(contactId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return contactTrackingService.getSummary(this.getAccessToken(), contactId, createdSinceTimestamp);
}
public List<ContactTrackingSummaryByCampaignReport> getContactTrackingSummaryByCampaign(String contactId) throws IllegalArgumentException, ConstantContactServiceException {
if (contactId == null || !(contactId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return contactTrackingService.getSummaryByCampaign(this.getAccessToken(), contactId);
}
public ResultSet<? extends TrackingContactsBase> getContactTrackingActivities(String contactId, Integer limit, String createdSinceTimestamp) throws IllegalArgumentException, ConstantContactServiceException {
if (contactId == null || !(contactId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return contactTrackingService.getActivities(this.getAccessToken(), contactId, limit, createdSinceTimestamp);
}
public ResultSet<TrackingContactsBase> getContactTrackingActivities(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException {
if(pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, TrackingContactsBase.class);
}
public ResultSet<ContactTrackingBounce> getContactTrackingBounces(String contactId, Integer limit) throws IllegalArgumentException,
ConstantContactServiceException {
if (contactId == null || !(contactId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return contactTrackingService.getBounces(this.getAccessToken(), contactId, limit);
}
public ResultSet<ContactTrackingBounce> getContactTrackingBounces(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException {
if(pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, ContactTrackingBounce.class);
}
public ResultSet<ContactTrackingClick> getContactTrackingClicks(String contactId, Integer limit, String createdSinceTimestamp) throws IllegalArgumentException,
ConstantContactServiceException {
if (contactId == null || !(contactId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return contactTrackingService.getClicks(this.getAccessToken(), contactId, limit, createdSinceTimestamp);
}
public ResultSet<ContactTrackingClick> getContactTrackingClicks(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException {
if(pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, ContactTrackingClick.class);
}
public ResultSet<ContactTrackingForward> getContactTrackingForwards(String contactId, Integer limit, String createdSinceTimestamp) throws IllegalArgumentException,
ConstantContactServiceException {
if (contactId == null || !(contactId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return contactTrackingService.getForwards(this.getAccessToken(), contactId, limit, createdSinceTimestamp);
}
public ResultSet<ContactTrackingForward> getContactTrackingForwards(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException {
if (pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, ContactTrackingForward.class);
}
public ResultSet<ContactTrackingOpen> getContactTrackingOpens(String contactId, Integer limit, String createdSinceTimestamp) throws IllegalArgumentException,
ConstantContactServiceException {
if (contactId == null || !(contactId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return contactTrackingService.getOpens(this.getAccessToken(), contactId, limit, createdSinceTimestamp);
}
public ResultSet<ContactTrackingOpen> getContactTrackingOpens(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException {
if(pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, ContactTrackingOpen.class);
}
public ResultSet<ContactTrackingSend> getContactTrackingSends(String contactId, Integer limit, String createdSinceTimestamp) throws IllegalArgumentException,
ConstantContactServiceException {
if (contactId == null || !(contactId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return contactTrackingService.getSends(this.getAccessToken(), contactId, limit, createdSinceTimestamp);
}
public ResultSet<ContactTrackingSend> getContactTrackingSends(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException {
if(pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, ContactTrackingSend.class);
}
public ResultSet<ContactTrackingUnsubscribe> getContactTrackingUnsubscribes(String contactId, Integer limit, String createdSinceTimestamp) throws IllegalArgumentException,
ConstantContactServiceException {
if (contactId == null || !(contactId.length() > 0)) {
throw new IllegalArgumentException(Config.Errors.ID);
}
return contactTrackingService.getUnsubscribes(this.getAccessToken(), contactId, limit, createdSinceTimestamp);
}
public ResultSet<ContactTrackingUnsubscribe> getContactTrackingUnsubscribes(Pagination pagination) throws IllegalArgumentException,
ConstantContactServiceException {
if(pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, ContactTrackingUnsubscribe.class);
}
public ContactsResponse addBulkContacts(AddContactsRequest request) throws IllegalArgumentException, ConstantContactServiceException {
if (request == null) {
throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_REQUEST_NULL);
}
return bulkActivitiesService.addContacts(this.getAccessToken(), request);
}
public ContactsResponse addBulkContactsMultipart(String fileName, File file, ArrayList<String> listIds) throws ConstantContactServiceException, IOException{
if (fileName == null || "".equals(fileName)){
throw new IllegalArgumentException(Config.Errors.FILE_NAME_NULL);
} else if (file == null){
throw new IllegalArgumentException(Config.Errors.FILE_NULL);
} else if (listIds == null){
throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_LIST_NULL);
}
Map<String,String> textParts = new HashMap<String,String>();
StringBuilder lists = new StringBuilder();
lists.append(listIds.remove(0));
for (String list : listIds){
lists.append(",");
lists.append(list);
}
textParts.put("lists", lists.toString());
InputStream fileStream = new FileInputStream(file);
MultipartBody request = MultipartBuilder.buildMultipartBody(textParts, fileName, fileStream);
return bulkActivitiesService.addContacts(this.getAccessToken(), request);
}
public ContactsResponse removeBulkContactsFromLists(RemoveContactsRequest request) throws IllegalArgumentException, ConstantContactServiceException {
if (request == null) {
throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_REQUEST_NULL);
}
return bulkActivitiesService.removeContactsFromLists(this.getAccessToken(), request);
}
public ContactsResponse removeBulkContactsFromListsMultipart(String fileName, File file, ArrayList<String> listIds)
throws ConstantContactServiceException, IOException {
if (fileName == null || "".equals(fileName)) {
throw new IllegalArgumentException(Config.Errors.FILE_NAME_NULL);
}
else if (file == null) {
throw new IllegalArgumentException(Config.Errors.FILE_NULL);
}
else if (listIds == null) {
throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_LIST_NULL);
}
Map<String, String> textParts = new HashMap<String, String>();
StringBuilder lists = new StringBuilder();
lists.append(listIds.remove(0));
for (String list : listIds) {
lists.append(",");
lists.append(list);
}
textParts.put("lists", lists.toString());
InputStream fileStream = new FileInputStream(file);
MultipartBody request = MultipartBuilder.buildMultipartBody(textParts, fileName, fileStream);
return bulkActivitiesService.removeContactsFromLists(this.getAccessToken(), request);
}
public ContactsResponse clearBulkContactsLists(ClearListsRequest request) throws IllegalArgumentException, ConstantContactServiceException {
if (request == null) {
throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_REQUEST_NULL);
}
return bulkActivitiesService.clearLists(this.getAccessToken(), request);
}
public ContactsResponse exportBulkContacts(ExportContactsRequest request) throws IllegalArgumentException, ConstantContactServiceException {
if (request == null) {
throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_REQUEST_NULL);
}
return bulkActivitiesService.exportContacts(this.getAccessToken(), request);
}
/**
*
* Get Bulk Summary Report API.<br/>
* Details in : {@link BulkActivitiesService#getSummaryReport(String)}
*
* @return A {@link List} of {@link SummaryReport} in case of success; an exception is thrown otherwise.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public List<SummaryReport> getBulkSummaryReport() throws ConstantContactServiceException {
return bulkActivitiesService.getSummaryReport(this.getAccessToken());
}
public List<DetailedStatusReport> getBulkDetailedStatusReport(String status, String type, String id) throws IllegalArgumentException,
ConstantContactServiceException {
return bulkActivitiesService.getDetailedStatusReport(this.getAccessToken(), status, type, id);
}
/**
* Retrieve My Library product information. <br />
* Details in : {@link MyLibraryService#getLibraryInfo(String)}
*
* @return The {@link MyLibrarySummary} for this account
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public MyLibrarySummary getLibraryInfo() throws ConstantContactServiceException{
return myLibraryService.getLibraryInfo(this.getAccessToken());
}
/**
* Retrieves the list of folders <br />
* Details in : {@link MyLibraryService#getLibraryFolders(String, FolderSortOptions, Integer)}
*
* @param sortBy The method to sort by. See {@link FolderSortOptions}. Leave null to not use
* @param limit The number of results to return. Leave null to use default.
* @throws {@link ConstantContactServiceException} When something went wrong
* in the Constant Contact flow or an error is returned from server.
* @return The {@link ResultSet} of {@link MyLibraryFolder} Data
*/
public ResultSet<MyLibraryFolder> getLibraryFolders(MyLibraryFolder.FolderSortOptions sortBy, Integer limit) throws ConstantContactServiceException{
return myLibraryService.getLibraryFolders(this.getAccessToken(), sortBy, limit);
}
public ResultSet<MyLibraryFolder> getLibraryFolders(Pagination pagination) throws ConstantContactServiceException, IllegalArgumentException{
if (pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, MyLibraryFolder.class);
}
public MyLibraryFolder addLibraryFolder(MyLibraryFolder folder) throws ConstantContactServiceException, IllegalArgumentException{
if (folder == null){
throw new IllegalArgumentException(Config.Errors.FOLDER_NULL);
}
return myLibraryService.addLibraryFolder(this.getAccessToken(),folder);
}
public MyLibraryFolder getLibraryFolder(String folderId) throws ConstantContactServiceException, IllegalArgumentException{
if (folderId == null || folderId.trim().equals("")){
throw new IllegalArgumentException(Config.Errors.FOLDER_ID_NULL);
}
return myLibraryService.getLibraryFolder(this.getAccessToken(), folderId);
}
public MyLibraryFolder updateLibraryFolder(MyLibraryFolder folder, Boolean includePayload) throws ConstantContactServiceException, IllegalArgumentException {
if (folder == null || folder.getId() == null || folder.getId().trim().equals("")){
throw new IllegalArgumentException(Config.Errors.FOLDER_ID_NULL);
}
return myLibraryService.updateLibraryFolder(this.getAccessToken(), folder, includePayload);
}
public void deleteLibraryFolder(String folderId) throws ConstantContactServiceException, IllegalArgumentException {
if (folderId == null || folderId.trim().equals("")){
throw new IllegalArgumentException(Config.Errors.FOLDER_ID_NULL);
}
myLibraryService.deleteLibraryFolder(this.getAccessToken(), folderId);
}
/**
* Retrieve Library Trash API.<br/>
* Details in : {@link MyLibraryService#getLibraryTrash(String, MyLibraryFile.Type, MyLibraryFile.SortBy, Integer)}
*
* @param type - The type of files to return. Null for default.
* @param sortBy - The way to sort results. Null for default
* @param limit - The number of results to return per page.
* @return A {@link ResultSet} of {@link MyLibraryFile} in case of success; an exception is thrown otherwise.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public ResultSet<MyLibraryFile> getLibraryTrash(MyLibraryFile.Type type, MyLibraryFile.SortBy sortBy, Integer limit) throws ConstantContactServiceException {
return myLibraryService.getLibraryTrash(this.getAccessToken(), type, sortBy, limit);
}
public ResultSet<MyLibraryFile> getLibraryTrash(Pagination pagination) throws ConstantContactServiceException, IllegalArgumentException {
if(pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, MyLibraryFile.class);
}
/**
* Delete Library Trash API.<br/>
*
* @return Void
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public void deleteLibraryTrash() throws ConstantContactServiceException {
myLibraryService.deleteLibraryTrash(this.getAccessToken());
return;
}
/**
* Retrieve Library Files API.<br/>
* Details in : {@link MyLibraryService#getLibraryFiles(String, MyLibraryFile.Type, MyLibrary.Source, MyLibraryFile.SortBy, Integer)}
*
* @param type - The type of files to return. Null for default.
* @param source - The source of the files. Null for default.
* @param sortBy - The way to sort results. Null for default
* @param limit - The number of results to return per page.
* @return A {@link ResultSet} of {@link MyLibraryFile} in case of success; an exception is thrown otherwise.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public ResultSet<MyLibraryFile> getLibraryFiles(MyLibraryFile.Type type, ImageSource source, MyLibraryFile.SortBy sortBy, Integer limit) throws ConstantContactServiceException{
return myLibraryService.getLibraryFiles(this.getAccessToken(), type, source, sortBy, limit);
}
public ResultSet<MyLibraryFile> getLibraryFiles(Pagination pagination) throws ConstantContactServiceException, IllegalArgumentException {
if(pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, MyLibraryFile.class);
}
/**
* Retrieve Library Files API.<br/>
* Details in : {@link MyLibraryService#getLibraryFilesByFolder(String, MyLibraryFile.Type, MyLibrary.Source, MyLibraryFile.SortBy, Integer)}
*
* @param folderId - The library Folder Id
* @param limit - The number of results to return per page.
* @return A {@link ResultSet} of {@link MyLibraryFile} in case of success; an exception is thrown otherwise.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public ResultSet<MyLibraryFile> getLibraryFilesByFolder(String folderId, Integer limit) throws ConstantContactServiceException{
return myLibraryService.getLibraryFilesByFolder(this.getAccessToken(), folderId, limit);
}
public ResultSet<MyLibraryFile> getLibraryFilesByFolder(Pagination pagination) throws ConstantContactServiceException, IllegalArgumentException {
if(pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, MyLibraryFile.class);
}
public MyLibraryFile getLibraryFile(String fileId) throws ConstantContactServiceException, IllegalArgumentException{
if (fileId == null || fileId.trim().equals("")){
throw new IllegalArgumentException(Config.Errors.FILE_ID_NULL);
}
return myLibraryService.getLibraryFile(this.getAccessToken(), fileId);
}
public MyLibraryFile updateLibraryFile(MyLibraryFile file, Boolean includePayload) throws ConstantContactServiceException, IllegalArgumentException {
if (file == null || file.getId() == null || file.getId().trim().equals("")){
throw new IllegalArgumentException(Config.Errors.FILE_ID_NULL);
}
return myLibraryService.updateLibraryFile(this.getAccessToken(), file, includePayload);
}
public void deleteLibraryFile(String fileId) throws ConstantContactServiceException, IllegalArgumentException {
if (fileId == null || fileId.trim().equals("")){
throw new IllegalArgumentException(Config.Errors.FILE_ID_NULL);
}
myLibraryService.deleteLibraryFile(this.getAccessToken(), fileId);
}
public List<UploadStatus> getLibraryFilesUploadStatus(String ... fileId) throws ConstantContactServiceException, IllegalArgumentException {
if (fileId == null || fileId.length < 1){
throw new IllegalArgumentException(Config.Errors.FILE_ID_NULL);
}
return myLibraryService.getLibraryFilesUploadStatus(this.getAccessToken(), fileId);
}
public List<MoveResults> moveLibraryFiles(String folderId, List<String> fileIds) throws ConstantContactServiceException, IllegalArgumentException {
if (fileIds == null || fileIds.size() < 1){
throw new IllegalArgumentException(Config.Errors.FILE_ID_NULL);
}
StringBuilder body = new StringBuilder("[");
body.append("\"").append(fileIds.get(0)).append("\"");
for (int i=1;i<fileIds.size();i++){
body.append(",").append("\"").append(fileIds.get(i)).append("\"");
}
body.append("]");
return myLibraryService.moveLibraryFiles(this.getAccessToken(), folderId, body.toString());
}
public String addLibraryFile(File file, String fileName, String description, FileType fileType,
String folderId, ImageSource imageSource) throws ConstantContactServiceException, IOException, IllegalArgumentException {
if (fileName == null || "".equals(fileName)){
throw new IllegalArgumentException(Config.Errors.FILE_NAME_NULL);
} else if (file == null){
throw new IllegalArgumentException(Config.Errors.FILE_NULL);
} else if (folderId == null){
throw new IllegalArgumentException(Config.Errors.FOLDER_ID_NULL);
} else if (imageSource == null){
throw new IllegalArgumentException(Config.Errors.MY_LIBRARY_IMAGE_SOURCE_NULL);
} else if (description == null){
throw new IllegalArgumentException(Config.Errors.MY_LIBRARY_DESCRIPTION_NULL);
} else if (fileType == null){
throw new IllegalArgumentException(Config.Errors.MY_LIBRARY_FILE_TYPE_NULL);
}
Map<String,String> textParts = new HashMap<String,String>();
textParts.put("description", description);
textParts.put("file_type", fileType.toString());
textParts.put("folder_id", folderId);
textParts.put("source", imageSource.toString());
InputStream fileStream = new FileInputStream(file);
MultipartBody request = MultipartBuilder.buildMultipartBody(textParts, fileName, fileStream);
return myLibraryService.addLibraryFile(this.getAccessToken(), request);
}
/**
* Get event API.<br/>
* Details in : {@link EventSpotService#getEvent(String, String)}
*
* @param eventId The the event id.
* @return The event.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public Event getEvent(String eventId) throws ConstantContactServiceException,
IllegalArgumentException {
return getEventSpotService().getEvent(getAccessToken(), eventId);
}
/**
* Get events API. <br/>
* Details in : {@link EventSpotService#getEvents(String, Integer)}
*
* @param limit The maximum number of results to return - can be null.
* @return The result set of events.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public ResultSet<Event> getEvents(Integer limit) throws ConstantContactServiceException,
IllegalArgumentException {
return getEventSpotService().getEvents(getAccessToken(), limit);
}
public ResultSet<Event> getEvents(Pagination pagination) throws ConstantContactServiceException,
IllegalArgumentException {
if (pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, Event.class);
}
/**
* Add events API.<br/>
* Details in : {@link EventSpotService#addEvent(String, Event)}
*
* @param event The {@link Event} to add.
* @return The added event.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public Event addEvent(Event event) throws IllegalArgumentException, ConstantContactServiceException {
if (event == null) {
throw new IllegalArgumentException(Config.Errors.EVENT);
}
return getEventSpotService().addEvent(getAccessToken(), event);
}
public Event updateEvent(Event event) throws IllegalArgumentException, ConstantContactServiceException {
if(event == null) {
throw new IllegalArgumentException(Config.Errors.EVENT);
}
return getEventSpotService().updateEvent(getAccessToken(), event);
}
public boolean updateEventStatus(String eventId, String status) throws IllegalArgumentException, ConstantContactServiceException {
if(eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
return getEventSpotService().updateEventStatus(getAccessToken(), eventId, status);
}
/**
* Get event fees API. <br/>
* Details in : {@link EventSpotService#getEventFees(String, String)}
*
* @param eventId The event id.
* @return The list of event fees.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public List<EventFee> getEventFees(String eventId) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
return getEventSpotService().getEventFees(getAccessToken(), eventId);
}
/**
* Add Event fee API.<br/>
* Details in : {@link EventSpotService#addEventFee(String, String, EventFee)}
*
* @param eventId The event id.
* @param eventFee The {@link EventFee} to add.
* @return The added event fee.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public EventFee addEventFee(String eventId, EventFee eventFee) throws ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (eventFee == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_FEE);
}
return getEventSpotService().addEventFee(getAccessToken(), eventId, eventFee);
}
/**
* Get event fee API.<br/>
* Details in : {@link EventSpotService#getEventFee(String, String, String)}
*
* @param eventId The event id.
* @param feeId The fee id.
* @return The event fee.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public EventFee getEventFee(String eventId, String feeId) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (feeId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_FEE_ID);
}
return getEventSpotService().getEventFee(getAccessToken(), eventId, feeId);
}
public EventFee updateEventFee(String eventId, EventFee eventFee) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (eventFee == null || eventFee.getId() == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_FEE_ID);
}
return getEventSpotService().updateEventFee(getAccessToken(), eventId, eventFee);
}
public boolean deleteEventFee(String eventId, EventFee eventFee) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (eventFee == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_FEE);
}
if (eventFee.getId() == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_FEE_ID);
}
return getEventSpotService().deleteEventFee(getAccessToken(), eventId, eventFee.getId());
}
public boolean deleteEventFee(String eventId, String eventFeeId) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (eventFeeId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_FEE_ID);
}
return getEventSpotService().deleteEventFee(getAccessToken(), eventId, eventFeeId);
}
/**
* Get event promocodes API. <br/>
* Details in : {@link EventSpotService#getEventPromocodes(String, String)}
*
* @eventId The event id.
* @return The list of event promocodes.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public List<Promocode> getEventPromocodes(String eventId) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
return getEventSpotService().getEventPromocodes(getAccessToken(), eventId);
}
/**
* Add event promocode API.<br/>
* Details in : {@link EventSpotService#addEventPromocode(String, String, Promocode)}
*
* @param eventId The event id.
* @param promocode The {@link Promocode} to add.
* @return The added event promocode.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public Promocode addEventPromocode(String eventId, Promocode promocode) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (promocode == null) {
throw new IllegalArgumentException(Config.Errors.PROMOCODE);
}
return getEventSpotService().addEventPromocode(getAccessToken(), eventId, promocode);
}
/**
* Get event promocode API.<br/>
* Details in : {@link EventSpotService#getEventPromocode(String, String, String)}
*
* @param eventId The event id.
* @param promocodeId The promocode id.
* @return The event promocode.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public Promocode getEventPromocode(String eventId, String promocodeId) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (promocodeId == null) {
throw new IllegalArgumentException(Config.Errors.PROMOCODE_ID);
}
return getEventSpotService().getEventPromocode(getAccessToken(), eventId, promocodeId);
}
public Promocode updateEventPromocode(String eventId, Promocode promocode) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (promocode == null || promocode.getId() == null) {
throw new IllegalArgumentException(Config.Errors.PROMOCODE);
}
return getEventSpotService().updateEventPromocode(getAccessToken(), eventId, promocode);
}
public boolean deleteEventPromocode(String eventId, String promocodeId) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (promocodeId == null) {
throw new IllegalArgumentException(Config.Errors.PROMOCODE_ID);
}
return getEventSpotService().deleteEventPromocode(getAccessToken(), eventId, promocodeId);
}
public boolean deleteEventPromocode(String eventId, Promocode promocode) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (promocode == null) {
throw new IllegalArgumentException(Config.Errors.PROMOCODE);
}
if (promocode.getId() == null) {
throw new IllegalArgumentException(Config.Errors.PROMOCODE_ID);
}
return getEventSpotService().deleteEventPromocode(getAccessToken(), eventId, promocode.getId());
}
/**
* Get event registrants API. <br/>
* Details in : {@link EventSpotService#getEventRegistrants(String, String, Integer)}
*
* @eventId The event id.
* @return The result set of event registrants.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public ResultSet<Registrant> getEventRegistrants(String eventId, Integer limit) throws IllegalArgumentException,
ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
return getEventSpotService().getEventRegistrants(getAccessToken(), eventId, limit);
}
public ResultSet<Registrant> getEventRegistrants(String eventId, Pagination pagination) throws IllegalArgumentException,
ConstantContactServiceException {
if (pagination == null) {
throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL);
}
return getPaginationHelperService().getPage(this.getAccessToken(), pagination, Registrant.class);
}
/**
* Get event registrant API.<br/>
* Details in : {@link EventSpotService#getEventRegistrant(String, String, String)}
*
* @param eventId The event id.
* @param registrantId The event registrant id.
* @return The event registrant {@link Registrant}.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public RegistrantDetails getEventRegistrant(String eventId, String registrantId) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (registrantId == null) {
throw new IllegalArgumentException(Config.Errors.REGISTRANT_ID);
}
return getEventSpotService().getEventRegistrant(getAccessToken(), eventId, registrantId);
}
/**
* Get event items API. <br/>
* Details in : {@link EventSpotService#getEventItems(String, String)}
*
* @param eventId The event id.
* @return The list of event items.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public List<EventItem> getEventItems(String eventId) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
return getEventSpotService().getEventItems(getAccessToken(), eventId);
}
/**
* Get event item API.<br/>
* Details in : {@link EventSpotService#getEventItem(String, String, String)}
*
* @param eventId The event id.
* @param itemId The event item id.
* @return The event item {@link EventItem}.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public EventItem getEventItem(String eventId, String itemId) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (itemId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM_ID);
}
return getEventSpotService().getEventItem(getAccessToken(), eventId, itemId);
}
/**
* Add event item API.<br/>
* Details in : {@link EventSpotService#addEventItem(String, String, EventItem)}
*
* @param eventId The event id.
* @param item The {@link EventItem} to add.
* @return The added event item.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public EventItem addEventItem(String eventId, EventItem item) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (item == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM);
}
return getEventSpotService().addEventItem(getAccessToken(), eventId, item);
}
public EventItem updateEventItem(String eventId, EventItem item) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (item == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM);
}
if (item.getId() == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM_ID);
}
return getEventSpotService().updateEventItem(getAccessToken(), eventId, item);
}
public boolean deleteEventItem(String eventId, String itemId) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (itemId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM_ID);
}
return getEventSpotService().deleteEventItem(getAccessToken(), eventId, itemId);
}
public boolean deleteEventItem(String eventId, EventItem item) throws IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (item == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM);
}
if (item.getId() == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM_ID);
}
return getEventSpotService().deleteEventItem(getAccessToken(), eventId, item.getId());
}
/**
* Get event item attributes API.<br/>
* Details in : {@link EventSpotService#getEventItemAttributes(String, String, String)}
*
* @param eventId The event id.
* @param itemId The event item id.
* @return The list of event item attributes {@link EventItemAttribute}.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public List<EventItemAttribute> getEventItemAttributes(String eventId, String itemId) throws IllegalArgumentException,
ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (itemId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM_ID);
}
return getEventSpotService().getEventItemAttributes(getAccessToken(), eventId, itemId);
}
/**
* Get event item attribute API.<br/>
* Details in : {@link EventSpotService#getEventItemAttribute(String, String, String, String)}
*
* @param eventId The event id.
* @param itemId The event item id.
* @param attributeId The event item attribute id.
* @return The event item attribute {@link EventItemAttribute}.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public EventItemAttribute getEventItemAttribute(String eventId, String itemId, String attributeId) throws IllegalArgumentException,
ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (itemId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM_ID);
}
if (attributeId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM_ATTRIBUTE_ID);
}
return getEventSpotService().getEventItemAttribute(getAccessToken(), eventId, itemId, attributeId);
}
/**
* Add event item attribute API.<br/>
* Details in : {@link EventSpotService#addEventItemAttribute(String, String, String, EventItemAttribute)}
*
* @param eventId The event id.
* @param itemId The event item id.
* @param itemAttribute The {@link EventItemAttribute} to add.
* @return The added event item attribute.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public EventItemAttribute addEventItemAttribute(String eventId, String itemId, EventItemAttribute itemAttribute) throws
IllegalArgumentException, ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (itemId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM_ID);
}
if (itemAttribute == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM_ATTRIBUTE);
}
return getEventSpotService().addEventItemAttribute(getAccessToken(), eventId, itemId, itemAttribute);
}
public EventItemAttribute updateEventItemAttribute(String eventId, String itemId, EventItemAttribute itemAttribute) throws
IllegalArgumentException,
ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (itemId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM_ID);
}
if (itemAttribute == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM_ATTRIBUTE);
}
return getEventSpotService().updateEventItemAttribute(getAccessToken(), eventId, itemId, itemAttribute);
}
public boolean deleteEventItemAttribute(String eventId, String itemId, String itemAttributeId) throws IllegalArgumentException,
ConstantContactServiceException {
if (eventId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ID);
}
if (itemId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM_ID);
}
if (itemAttributeId == null) {
throw new IllegalArgumentException(Config.Errors.EVENT_ITEM_ATTRIBUTE_ID);
}
return getEventSpotService().deleteEventItemAttribute(getAccessToken(), eventId, itemId, itemAttributeId);
}
/**
* Get account info API.<br/>
* Details in : {@link AccountService#getAccountInfo(String)}
*
* @return The account info.
* @throws ConstantContactServiceException Thrown when :
* <ul>
* <li>something went wrong either on the client side;</li>
* <li>or an error message was received from the server side.</li>
* </ul>
* <br/>
* To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/>
* Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()}
*/
public AccountInfo getAccountInfo() throws ConstantContactServiceException {
return getAccountService().getAccountInfo(getAccessToken());
}
public AccountInfo updateAccountInfo(AccountInfo accountInfo) throws IllegalArgumentException, ConstantContactServiceException {
if(accountInfo == null) {
throw new IllegalArgumentException(Config.Errors.ACCOUNT_INFO);
}
return getAccountService().updateAccountInfo(getAccessToken(), accountInfo);
}
} |
package com.illposed.osc.argument;
import java.io.Serializable;
/**
* This class represents an OSC 32bit unsigned integer.
* We use this class, because Java has no matching primitive data-type,
* and <tt>long</tt> is already used for signed 64bit integers.
*/
public final class OSCUnsigned implements Cloneable, Serializable, Comparable<OSCUnsigned> {
/**
* The number of bytes used to represent an unsigned integer value in binary form.
*/
public static final int BYTES = 4;
/**
* A constant holding the minimum value a 32bit unsigned integer can have, 0.
*/
public static final OSCUnsigned MIN_VALUE = new OSCUnsigned(0x0L);
/**
* A constant holding the maximum value a 32bit unsigned integer can have, 2^{32}.
*/
public static final OSCUnsigned MAX_VALUE = new OSCUnsigned(0xFFFFFFFFL);
private static final long serialVersionUID = 1L;
private final long value;
private OSCUnsigned(final long value) {
this.value = value;
}
@Override
public boolean equals(final Object other) {
final boolean equal;
if (other instanceof OSCUnsigned) {
equal = (toLong() == ((OSCUnsigned) other).toLong());
} else {
equal = false;
}
return equal;
}
@Override
public int hashCode() {
int hash = 5;
hash = 89 * hash + (int) (this.value ^ (this.value >>> 32));
return hash;
}
@Override
public int compareTo(final OSCUnsigned other) {
return (int) (toLong() - other.toLong());
}
@Override
public OSCUnsigned clone() throws CloneNotSupportedException {
return (OSCUnsigned) super.clone();
}
/**
* Returns the 32bit unsigned value in form of a long.
* @return contains the value in the lower/least significant 32 bits; always positive
*/
public long toLong() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static OSCUnsigned valueOf(final byte[] bytes) {
if (bytes.length != BYTES) {
throw new IllegalArgumentException("We need exactly 4 bytes");
}
final long value
= ((long) bytes[0] & 0xFF) << (3 * Byte.SIZE)
| ((long) bytes[1] & 0xFF) << (2 * Byte.SIZE)
| ((long) bytes[2] & 0xFF) << (1 * Byte.SIZE)
| ((long) bytes[3] & 0xFF);
return valueOf(value);
}
public static OSCUnsigned valueOf(final long value) {
if (value < MIN_VALUE.value || value > MAX_VALUE.value) {
throw new IllegalArgumentException(
"Value " + value + " lies not within 32bit unsigned integer range ("
+ MIN_VALUE.value + " - " + MAX_VALUE.value + ").");
}
return new OSCUnsigned(value);
}
} |
package com.docusign.esign.client;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.joda.*;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.FileDataBodyPart;
import javax.ws.rs.core.Response.Status.Family;
import javax.ws.rs.core.MediaType;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;
import java.net.URLEncoder;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import com.docusign.esign.client.auth.Authentication;
import com.docusign.esign.client.auth.HttpBasicAuth;
import com.docusign.esign.client.auth.ApiKeyAuth;
import com.docusign.esign.client.auth.OAuth;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T11:06:30.816-07:00")
public class ApiClient {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private String basePath = "https:
private boolean debugging = false;
private int connectionTimeout = 0;
private Client httpClient;
private ObjectMapper objectMapper;
private Map<String, Authentication> authentications;
private int statusCode;
private Map<String, List<String>> responseHeaders;
private DateFormat dateFormat;
public ApiClient() {
objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
objectMapper.registerModule(new JodaModule());
objectMapper.setDateFormat(ApiClient.buildDefaultDateFormat());
dateFormat = ApiClient.buildDefaultDateFormat();
// Set default User-Agent.
setUserAgent("Swagger-Codegen/2.0.1/java");
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
rebuildHttpClient();
}
public static DateFormat buildDefaultDateFormat() {
// Use RFC3339 format for date and datetime.
// See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
// Use UTC as the default time zone.
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat;
}
/**
* Build the Client used to make HTTP requests with the latest settings,
* i.e. objectMapper and debugging.
* TODO: better to use the Builder Pattern?
*/
public ApiClient rebuildHttpClient() {
// Add the JSON serialization support to Jersey
JacksonJsonProvider jsonProvider = new JacksonJsonProvider(objectMapper);
DefaultClientConfig conf = new DefaultClientConfig();
conf.getSingletons().add(jsonProvider);
Client client = Client.create(conf);
if (debugging) {
client.addFilter(new LoggingFilter());
}
this.httpClient = client;
return this;
}
/**
* Returns the current object mapper used for JSON serialization/deserialization.
* <p>
* Note: If you make changes to the object mapper, remember to set it back via
* <code>setObjectMapper</code> in order to trigger HTTP client rebuilding.
* </p>
*/
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public ApiClient setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
// Need to rebuild the Client as it depends on object mapper.
rebuildHttpClient();
return this;
}
public Client getHttpClient() {
return httpClient;
}
public ApiClient setHttpClient(Client httpClient) {
this.httpClient = httpClient;
return this;
}
public String getBasePath() {
return basePath;
}
public ApiClient setBasePath(String basePath) {
this.basePath = basePath;
return this;
}
/**
* Gets the status code of the previous request
*/
public int getStatusCode() {
return statusCode;
}
/**
* Gets the response headers of the previous request
*/
public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* Get authentications (key: authentication name, value: authentication).
*/
public Map<String, Authentication> getAuthentications() {
return authentications;
}
/**
* Get authentication for the given name.
*
* @param authName The authentication name
* @return The authentication, null if not found
*/
public Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
/**
* Helper method to set username for the first HTTP basic authentication.
*/
public void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set password for the first HTTP basic authentication.
*/
public void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set API key value for the first API key authentication.
*/
public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication.
*/
public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set access token for the first OAuth2 authentication.
*/
public void setAccessToken(String accessToken) {
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
((OAuth) auth).setAccessToken(accessToken);
return;
}
}
throw new RuntimeException("No OAuth2 authentication configured!");
}
/**
* Set the User-Agent header's value (by adding to the default header map).
*/
public ApiClient setUserAgent(String userAgent) {
addDefaultHeader("User-Agent", userAgent);
return this;
}
/**
* Add a default header.
*
* @param key The header's key
* @param value The header's value
*/
public ApiClient addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value);
return this;
}
/**
* Check that whether debugging is enabled for this API client.
*/
public boolean isDebugging() {
return debugging;
}
/**
* Enable/disable debugging for this API client.
*
* @param debugging To enable (true) or disable (false) debugging
*/
public ApiClient setDebugging(boolean debugging) {
this.debugging = debugging;
// Need to rebuild the Client as it depends on the value of debugging.
rebuildHttpClient();
return this;
}
/**
* Connect timeout (in milliseconds).
*/
public int getConnectTimeout() {
return connectionTimeout;
}
/**
* Set the connect timeout (in milliseconds).
* A value of 0 means no timeout, otherwise values must be between 1 and
* {@link Integer#MAX_VALUE}.
*/
public ApiClient setConnectTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
httpClient.setConnectTimeout(connectionTimeout);
return this;
}
/**
* Get the date format used to parse/format date parameters.
*/
public DateFormat getDateFormat() {
return dateFormat;
}
/**
* Set the date format used to parse/format date parameters.
*/
public ApiClient setDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
// Also set the date format for model (de)serialization with Date properties.
this.objectMapper.setDateFormat((DateFormat) dateFormat.clone());
// Need to rebuild the Client as objectMapper changes.
rebuildHttpClient();
return this;
}
/**
* Parse the given string into Date object.
*/
public Date parseDate(String str) {
try {
return dateFormat.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
/**
* Format the given Date object into string.
*/
public String formatDate(Date date) {
return dateFormat.format(date);
}
/**
* Format the given parameter object into string.
*/
public String parameterToString(Object param) {
if (param == null) {
return "";
} else if (param instanceof Date) {
return formatDate((Date) param);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for(Object o : (Collection<?>)param) {
if(b.length() > 0) {
b.append(",");
}
b.append(String.valueOf(o));
}
return b.toString();
} else {
return String.valueOf(param);
}
}
/*
Format to {@code Pair} objects.
*/
public List<Pair> parameterToPairs(String collectionFormat, String name, Object value){
List<Pair> params = new ArrayList<Pair>();
// preconditions
if (name == null || name.isEmpty() || value == null) return params;
Collection<?> valueCollection = null;
if (value instanceof Collection<?>) {
valueCollection = (Collection<?>) value;
} else {
params.add(new Pair(name, parameterToString(value)));
return params;
}
if (valueCollection.isEmpty()){
return params;
}
// get the collection format
collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
// create the params based on the collection format
if (collectionFormat.equals("multi")) {
for (Object item : valueCollection) {
params.add(new Pair(name, parameterToString(item)));
}
return params;
}
String delimiter = ",";
if (collectionFormat.equals("csv")) {
delimiter = ",";
} else if (collectionFormat.equals("ssv")) {
delimiter = " ";
} else if (collectionFormat.equals("tsv")) {
delimiter = "\t";
} else if (collectionFormat.equals("pipes")) {
delimiter = "|";
}
StringBuilder sb = new StringBuilder() ;
for (Object item : valueCollection) {
sb.append(delimiter);
sb.append(parameterToString(item));
}
params.add(new Pair(name, sb.substring(1)));
return params;
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
*/
public boolean isJsonMime(String mime) {
return mime != null && mime.matches("(?i)application\\/json(;.*)?");
}
/**
* Select the Accept header's value from the given accepts array:
* if JSON exists in the given array, use it;
* otherwise use all of them (joining into a string)
*
* @param accepts The accepts array to select from
* @return The Accept header to use. If the given array is empty,
* null will be returned (not to set the Accept header explicitly).
*/
public String selectHeaderAccept(String[] accepts) {
if (accepts.length == 0) {
return null;
}
for (String accept : accepts) {
if (isJsonMime(accept)) {
return accept;
}
}
return StringUtil.join(accepts, ",");
}
/**
* Select the Content-Type header's value from the given array:
* if JSON exists in the given array, use it;
* otherwise use the first one of the array.
*
* @param contentTypes The Content-Type array to select from
* @return The Content-Type header to use. If the given array is empty,
* JSON will be used.
*/
public String selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0) {
return "application/json";
}
for (String contentType : contentTypes) {
if (isJsonMime(contentType)) {
return contentType;
}
}
return contentTypes[0];
}
/**
* Escape the given string to be used as URL query value.
*/
public String escapeString(String str) {
try {
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) {
return str;
}
}
/**
* Serialize the given Java object into string according the given
* Content-Type (only JSON is supported for now).
*/
public Object serialize(Object obj, String contentType, Map<String, Object> formParams) throws ApiException {
if (contentType.startsWith("multipart/form-data")) {
FormDataMultiPart mp = new FormDataMultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE));
} else {
mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
}
}
return mp;
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
return this.getXWWWFormUrlencodedParams(formParams);
} else {
// We let Jersey attempt to serialize the body
return obj;
}
}
/**
* Build full URL by concatenating base path, the given sub path and query parameters.
*
* @param path The sub path
* @param queryParams The query parameters
* @return The full URL
*/
private String buildUrl(String path, List<Pair> queryParams) {
final StringBuilder url = new StringBuilder();
url.append(basePath).append(path);
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) {
if (param.getValue() != null) {
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
}
}
}
return url.toString();
}
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
if (body != null && !formParams.isEmpty()) {
throw new ApiException(500, "Cannot have body and form params");
}
updateParamsForAuth(authNames, queryParams, headerParams);
final String url = buildUrl(path, queryParams);
Builder builder;
if (accept == null) {
builder = httpClient.resource(url).getRequestBuilder();
} else {
builder = httpClient.resource(url).accept(accept);
}
for (String key : headerParams.keySet()) {
builder = builder.header(key, headerParams.get(key));
}
for (String key : defaultHeaderMap.keySet()) {
if (!headerParams.containsKey(key)) {
builder = builder.header(key, defaultHeaderMap.get(key));
}
}
// Add DocuSign Tracking Header
builder = builder.header("X-DocuSign-SDK", "Java");
ClientResponse response = null;
if ("GET".equals(method)) {
response = (ClientResponse) builder.get(ClientResponse.class);
} else if ("POST".equals(method)) {
response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("PUT".equals(method)) {
response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("DELETE".equals(method)) {
response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("PATCH".equals(method)) {
response = builder.type(contentType).header("X-HTTP-Method-Override", "PATCH").post(ClientResponse.class, serialize(body, contentType, formParams));
}
else {
throw new ApiException(500, "unknown method type " + method);
}
return response;
}
/**
* Invoke API by sending HTTP request with the given options.
*
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
* @param queryParams The query parameters
* @param body The request body object - if it is not binary, otherwise null
* @param headerParams The header parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames);
statusCode = response.getStatusInfo().getStatusCode();
responseHeaders = response.getHeaders();
if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) {
return null;
} else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
if (returnType == null)
return null;
else
return response.getEntity(returnType);
} else {
String message = "error";
String respBody = null;
if (response.hasEntity()) {
try {
respBody = response.getEntity(String.class);
message = respBody;
} catch (RuntimeException e) {
// e.printStackTrace();
}
}
throw new ApiException(
response.getStatusInfo().getStatusCode(),
message,
response.getHeaders(),
respBody);
}
}
/**
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
*/
private void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
auth.applyToParams(queryParams, headerParams);
}
}
/**
* Encode the given form parameters as request body.
*/
private String getXWWWFormUrlencodedParams(Map<String, Object> formParams) {
StringBuilder formParamBuilder = new StringBuilder();
for (Entry<String, Object> param : formParams.entrySet()) {
String valueStr = parameterToString(param.getValue());
try {
formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8"))
.append("=")
.append(URLEncoder.encode(valueStr, "utf8"));
formParamBuilder.append("&");
} catch (UnsupportedEncodingException e) {
// move on to next
}
}
String encodedFormParams = formParamBuilder.toString();
if (encodedFormParams.endsWith("&")) {
encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1);
}
return encodedFormParams;
}
} |
package com.dteknoloji.domain.beacon;
import java.io.Serializable;
import javax.persistence.*;
import javax.validation.constraints.Size;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dteknoloji.domain.beaconGroup.BeaconGroup;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@Table(name = "beacons")
@ResponseBody
@JsonIgnoreProperties(value = {"links"})
public class Beacon extends ResourceSupport implements Serializable {
// UUID hex string (including dashes) is 36 characters long
public static final int UUID_MAX_LENGTH = 36;
// Major hex string is 4 characters long
public static final int MAJOR_MIN_LENGTH = 1;
public static final int MAJOR_MAX_LENGTH = 4;
// Minor hex string is 4 characters long
public static final int MINOR_MIN_LENGTH = 1;
public static final int MINOR_MAX_LENGTH = 4;
public static final int DESCRIPTION_MAX_LENGTH = 200;
@Id
@Column(name = "beacon_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long beaconId;
@Column(name = "uuid", nullable = false, length = UUID_MAX_LENGTH)
@Size(min = UUID_MAX_LENGTH, max = UUID_MAX_LENGTH)
private String uuid = "";
@Column(name = "major", nullable = false, length = MAJOR_MAX_LENGTH)
@Size(min = MAJOR_MIN_LENGTH, max = MAJOR_MAX_LENGTH)
private String major = "";
@Column(name = "minor", nullable = false, length = MINOR_MAX_LENGTH)
@Size(min = MINOR_MIN_LENGTH, max = MINOR_MAX_LENGTH)
private String minor = "";
@Column(name = "description", nullable = false, length = DESCRIPTION_MAX_LENGTH)
@Size(max = DESCRIPTION_MAX_LENGTH)
private String description = "";
@ManyToOne(targetEntity = BeaconGroup.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL, optional = true)
@JsonIgnoreProperties(value = {"name", "description", "beacons"})
private BeaconGroup group;
public Long getBeaconId() {
return beaconId;
}
public void setBeaconId(Long beaconId) {
this.beaconId = beaconId;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public String getMinor() {
return minor;
}
public void setMinor(String minor) {
this.minor = minor;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BeaconGroup getGroup() {
return group;
}
public void setGroup(BeaconGroup group) {
this.group = group;
}
} |
package org.italiangrid.srm.client;
import gov.lbl.srm.StorageResourceManager.ArrayOfAnyURI;
import gov.lbl.srm.StorageResourceManager.ArrayOfTGetFileRequest;
import gov.lbl.srm.StorageResourceManager.ISRM;
import gov.lbl.srm.StorageResourceManager.SRMServiceLocator;
import gov.lbl.srm.StorageResourceManager.SrmLsRequest;
import gov.lbl.srm.StorageResourceManager.SrmLsResponse;
import gov.lbl.srm.StorageResourceManager.SrmPingRequest;
import gov.lbl.srm.StorageResourceManager.SrmPingResponse;
import gov.lbl.srm.StorageResourceManager.SrmPrepareToGetRequest;
import gov.lbl.srm.StorageResourceManager.SrmPrepareToGetResponse;
import gov.lbl.srm.StorageResourceManager.SrmStatusOfGetRequestRequest;
import gov.lbl.srm.StorageResourceManager.SrmStatusOfGetRequestResponse;
import gov.lbl.srm.StorageResourceManager.TDirOption;
import gov.lbl.srm.StorageResourceManager.TGetFileRequest;
import gov.lbl.srm.StorageResourceManager.TStatusCode;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.rpc.ServiceException;
import org.apache.axis.AxisProperties;
import org.apache.axis.types.URI;
import org.apache.axis.types.URI.MalformedURIException;
import org.italiangrid.axis.CANLAxis1SocketFactory;
import org.italiangrid.axis.DefaultConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple SRM client.
*
* @author andreaceccanti
*
*/
public class SRMClient implements SRMHelper {
Logger logger = LoggerFactory.getLogger(SRMClient.class);
public static class Builder {
private String serviceURL = "https://localhost:8444";
private String proxyFilePath;
private String trustAnchorDir = "/etc/grid-security/certificates";
public Builder() {
}
public Builder serviceURL(String url) {
serviceURL = url;
return this;
}
public Builder proxyFilePath(String pfp) {
proxyFilePath = pfp;
return this;
}
public Builder trustAnchorDIr(String tad) {
trustAnchorDir = tad;
return this;
}
public SRMClient build() throws MalformedURLException, ServiceException {
return new SRMClient(this);
}
}
private static final String AXIS_SOCKET_FACTORY_PROPERTY = "axis.socketSecureFactory";
private ISRM serviceEndpoint;
private SRMClient(Builder builder) throws MalformedURLException,
ServiceException {
DefaultConfigurator configurator = new DefaultConfigurator();
configurator.setEnableGSIHandshake(true);
configurator.setProxyFile(builder.proxyFilePath);
configurator.setTrustAnchorsDir(builder.trustAnchorDir);
CANLAxis1SocketFactory.setConfigurator(configurator);
AxisProperties.setProperty(AXIS_SOCKET_FACTORY_PROPERTY,
CANLAxis1SocketFactory.class.getName());
SRMServiceLocator locator = new SRMServiceLocator();
serviceEndpoint = locator.getsrm(new URL(builder.serviceURL));
}
public SrmPingResponse srmPing() throws RemoteException {
return serviceEndpoint.srmPing(new SrmPingRequest());
}
public SrmStatusOfGetRequestResponse srmPTG(List<String> surls,
long maxWaitingTimeInMsec) throws MalformedURIException, RemoteException {
checkMaxWaitingTimeInSecArgument(maxWaitingTimeInMsec);
checkSulrsArgument(surls);
List<TGetFileRequest> requests = new ArrayList<TGetFileRequest>();
for (String s : surls)
requests.add(new TGetFileRequest(new URI(s), new TDirOption(false, false,
0)));
SrmPrepareToGetRequest ptg = new SrmPrepareToGetRequest();
ptg.setArrayOfFileRequests(new ArrayOfTGetFileRequest(requests
.toArray(new TGetFileRequest[requests.size()])));
SrmPrepareToGetResponse resp = serviceEndpoint.srmPrepareToGet(ptg);
if (!resp.getReturnStatus().getStatusCode()
.equals(TStatusCode.SRM_REQUEST_QUEUED)) {
throw new SRMError(resp.getReturnStatus().getStatusCode(), resp
.getReturnStatus().getExplanation());
}
String token = resp.getRequestToken();
SrmStatusOfGetRequestRequest sptg = new SrmStatusOfGetRequestRequest();
sptg.setRequestToken(token);
long cumulativeSleepTime = 0;
long sleepInterval = 50;
int requestCounter = 0;
TStatusCode lastStatus;
SrmStatusOfGetRequestResponse sptgResp = null;
do {
requestCounter++;
sptgResp = serviceEndpoint.srmStatusOfGetRequest(sptg);
lastStatus = sptgResp.getReturnStatus().getStatusCode();
if (lastStatus.equals(TStatusCode.SRM_REQUEST_QUEUED)
|| (lastStatus.equals(TStatusCode.SRM_REQUEST_INPROGRESS))) {
try {
Thread.sleep(sleepInterval);
cumulativeSleepTime += sleepInterval;
sleepInterval *= 2;
} catch (InterruptedException e) {
}
} else
return sptgResp;
} while (cumulativeSleepTime < maxWaitingTimeInMsec);
logger.warn(
"PtG still in progress after {} status requests and {} waiting time.",
requestCounter, maxWaitingTimeInMsec);
return sptgResp;
}
public SrmLsResponse srmLs(List<String> surls,
long maxWaitingTimeInMsec) throws MalformedURIException, RemoteException {
checkMaxWaitingTimeInSecArgument(maxWaitingTimeInMsec);
checkSulrsArgument(surls);
SrmLsRequest request = new SrmLsRequest();
// have strings, but need uris
List<URI> uris = new ArrayList<URI>();
for(String surl : surls) {
uris.add(new URI(surl));
}
request.setArrayOfSURLs(new ArrayOfAnyURI(uris.toArray(new URI[uris.size()])));
return serviceEndpoint.srmLs(request);
}
private void checkMaxWaitingTimeInSecArgument(long maxWaitingTimeInMsec) {
if (maxWaitingTimeInMsec < 0)
throw new IllegalArgumentException("Please specify a positive integer"
+ " for the max waiting time");
}
private void checkSulrsArgument(List<String> surls) {
if (surls == null || surls.isEmpty())
throw new IllegalArgumentException(
"Please provide a non-null or not-empty" + " list of surls.");
}
} |
// This file is part of the Salesforce Marketing Cloud Java client library.
// modification, are permitted provided that the following conditions
// are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of ExactTarget, Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.exacttarget.fuelsdk;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import static org.junit.Assert.*;
import static com.exacttarget.fuelsdk.ETResult.Status.*;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ETDataExtensionTest {
private static final String CLIENT_ID = "m2x67xmfr4vassc6hskv359r";
private static final Integer DATA_EXTENSION_FOLDER_ID = 94511;
private static ETClient client = null;
@BeforeClass
public static void setUpBeforeClass()
throws ETSdkException
{
client = new ETClient();
}
private static String id = null;
@Test
public void _01_TestCreateSingle()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETDataExtension dataExtension = new ETDataExtension();
dataExtension.setKey("test1");
dataExtension.setName("test1");
dataExtension.addColumn("CustomerID", true);
dataExtension.addColumn("FullName");
dataExtension.addColumn("FirstName");
dataExtension.addColumn("LastName");
dataExtension.addColumn("Age", ETDataExtensionColumn.Type.NUMBER);
dataExtension.addColumn("EmailAddress", ETDataExtensionColumn.Type.EMAIL_ADDRESS);
ETResponse<ETDataExtension> response = client.create(dataExtension);
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(1, response.getResults().size());
ETResult<ETDataExtension> result = response.getResult();
assertNull(result.getRequestId());
assertEquals(OK, result.getStatus());
assertEquals("OK", result.getResponseCode());
assertEquals("Data Extension created.", result.getResponseMessage());
assertNull(result.getErrorCode());
assertNotNull(result.getObjectId());
ETDataExtension de = result.getObject();
assertNotNull(de.getId());
assertEquals("test1", de.getKey());
assertEquals("test1", de.getName());
assertNull(de.getDescription());
assertNull(de.getFolderId());
assertNull(de.getIsSendable());
assertNull(de.getIsTestable());
// save the ID for use in subsequent tests
id = result.getObjectId();
}
private static ETDataExtension dataExtension = null;
@Test
public void _02_TestRetrieveSingle()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtension> response = client.retrieve(ETDataExtension.class, "id=" + id);
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(1, response.getResults().size());
ETResult<ETDataExtension> result = response.getResult();
assertNull(result.getRequestId());
assertNull(result.getStatus());
assertNull(result.getResponseCode());
assertNull(result.getResponseMessage());
assertNull(result.getErrorCode());
assertEquals(id, result.getObjectId());
ETDataExtension de = result.getObject();
assertEquals(id, de.getId());
assertEquals("test1", de.getKey());
assertEquals("test1", de.getName());
assertEquals("", de.getDescription());
assertEquals(DATA_EXTENSION_FOLDER_ID, de.getFolderId());
assertEquals(false, de.getIsSendable());
assertEquals(false, de.getIsTestable());
// save the object for use in subsequent tests
dataExtension = de;
}
@Test
public void _03_TestInsertSingleRow()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETDataExtensionRow row = new ETDataExtensionRow();
row.setColumn("CustomerID", "1");
row.setColumn("FullName", "Ian Murdock");
row.setColumn("FirstName", "Ian");
row.setColumn("LastName", "Murdock");
row.setColumn("Age", "41");
row.setColumn("EmailAddress", "imurdock@example.com");
ETResponse<ETDataExtensionRow> response = dataExtension.insert(row);
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(1, response.getResults().size());
ETResult<ETDataExtensionRow> result = response.getResult();
assertNull(result.getRequestId());
assertEquals(OK, result.getStatus());
assertEquals("OK", result.getResponseCode());
assertEquals("Created DataExtensionObject", result.getResponseMessage());
assertNull(result.getErrorCode());
assertNull(result.getObjectId());
ETDataExtensionRow r = result.getObject();
assertEquals("1", r.getColumn("CustomerID"));
assertEquals("Ian Murdock", r.getColumn("FullName"));
assertEquals("Ian", r.getColumn("FirstName"));
assertEquals("Murdock", r.getColumn("LastName"));
assertEquals("41", r.getColumn("Age"));
assertEquals("imurdock@example.com", r.getColumn("EmailAddress"));
}
@Test
public void _04_TestInsertMultipleRows()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETDataExtensionRow row1 = new ETDataExtensionRow();
row1.setColumn("CustomerID", "2");
row1.setColumn("FullName", "Fred Flintstone");
row1.setColumn("FirstName", "Fred");
row1.setColumn("LastName", "Flintstone");
row1.setColumn("Age", "36");
row1.setColumn("EmailAddress", "fred@flintstone.com");
ETDataExtensionRow row2 = new ETDataExtensionRow();
row2.setColumn("CustomerID", "3");
row2.setColumn("FullName", "Wilma Flintstone");
row2.setColumn("FirstName", "Wilma");
row2.setColumn("LastName", "Flintstone");
row2.setColumn("Age", "34");
row2.setColumn("EmailAddress", "wilma@flintstone.com");
ETResponse<ETDataExtensionRow> response = dataExtension.insert(row1, row2);
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(2, response.getResults().size());
ETResult<ETDataExtensionRow> result1 = response.getResults().get(0);
assertNull(result1.getRequestId());
assertEquals(OK, result1.getStatus());
assertEquals("OK", result1.getResponseCode());
assertEquals("Created DataExtensionObject", result1.getResponseMessage());
assertNull(result1.getErrorCode());
assertNull(result1.getObjectId());
ETDataExtensionRow r1 = result1.getObject();
assertEquals("2", r1.getColumn("CustomerID"));
assertEquals("Fred Flintstone", r1.getColumn("FullName"));
assertEquals("Fred", r1.getColumn("FirstName"));
assertEquals("Flintstone", r1.getColumn("LastName"));
assertEquals("36", r1.getColumn("Age"));
assertEquals("fred@flintstone.com", r1.getColumn("EmailAddress"));
ETResult<ETDataExtensionRow> result2 = response.getResults().get(1);
assertNull(result2.getRequestId());
assertEquals(OK, result2.getStatus());
assertEquals("OK", result2.getResponseCode());
assertEquals("Created DataExtensionObject", result2.getResponseMessage());
assertNull(result2.getErrorCode());
assertNull(result2.getObjectId());
ETDataExtensionRow r2 = result2.getObject();
assertEquals("3", r2.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", r2.getColumn("FullName"));
assertEquals("Wilma", r2.getColumn("FirstName"));
assertEquals("Flintstone", r2.getColumn("LastName"));
assertEquals("34", r2.getColumn("Age"));
assertEquals("wilma@flintstone.com", r2.getColumn("EmailAddress"));
}
@Test
public void _05_TestSelectAll()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select();
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 3, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(3, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("1", row1.getColumn("CustomerID"));
assertEquals("Ian Murdock", row1.getColumn("FullName"));
assertEquals("Ian", row1.getColumn("FirstName"));
assertEquals("Murdock", row1.getColumn("LastName"));
assertEquals("41", row1.getColumn("Age"));
assertEquals("imurdock@example.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertEquals("2", row2.getColumn("CustomerID"));
assertEquals("Fred Flintstone", row2.getColumn("FullName"));
assertEquals("Fred", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertEquals("36", row2.getColumn("Age"));
assertEquals("fred@flintstone.com", row2.getColumn("EmailAddress"));
ETDataExtensionRow row3 = rows.get(2);
assertEquals("3", row3.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", row3.getColumn("FullName"));
assertEquals("Wilma", row3.getColumn("FirstName"));
assertEquals("Flintstone", row3.getColumn("LastName"));
assertEquals("34", row3.getColumn("Age"));
assertEquals("wilma@flintstone.com", row3.getColumn("EmailAddress"));
}
@Test
public void _06_TestSelectAllSingleColumnSpecified()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("LastName");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 3, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(3, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertNull(row1.getColumn("CustomerID"));
assertNull(row1.getColumn("FullName"));
assertNull(row1.getColumn("FirstName"));
assertEquals("Murdock", row1.getColumn("LastName"));
assertNull(row1.getColumn("Age"));
assertNull(row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertNull(row2.getColumn("CustomerID"));
assertNull(row2.getColumn("FullName"));
assertNull(row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertNull(row2.getColumn("Age"));
assertNull(row2.getColumn("EmailAddress"));
ETDataExtensionRow row3 = rows.get(2);
assertNull(row3.getColumn("CustomerID"));
assertNull(row3.getColumn("FullName"));
assertNull(row3.getColumn("FirstName"));
assertEquals("Flintstone", row3.getColumn("LastName"));
assertNull(row3.getColumn("Age"));
assertNull(row3.getColumn("EmailAddress"));
}
@Test
public void _07_TestSelectAllMultipleColumnsSpecified()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("LastName",
"FirstName",
"EmailAddress");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 3, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(3, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertNull(row1.getColumn("CustomerID"));
assertNull(row1.getColumn("FullName"));
assertEquals("Ian", row1.getColumn("FirstName"));
assertEquals("Murdock", row1.getColumn("LastName"));
assertNull(row1.getColumn("Age"));
assertEquals("imurdock@example.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertNull(row2.getColumn("CustomerID"));
assertNull(row2.getColumn("FullName"));
assertEquals("Fred", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertNull(row2.getColumn("Age"));
assertEquals("fred@flintstone.com", row2.getColumn("EmailAddress"));
ETDataExtensionRow row3 = rows.get(2);
assertNull(row3.getColumn("CustomerID"));
assertNull(row3.getColumn("FullName"));
assertEquals("Wilma", row3.getColumn("FirstName"));
assertEquals("Flintstone", row3.getColumn("LastName"));
assertNull(row3.getColumn("Age"));
assertEquals("wilma@flintstone.com", row3.getColumn("EmailAddress"));
}
@Test
public void _08_TestSelectAllSorted()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("ORDER BY FirstName");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 3, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(3, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("2", row1.getColumn("CustomerID"));
assertEquals("Fred Flintstone", row1.getColumn("FullName"));
assertEquals("Fred", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertEquals("36", row1.getColumn("Age"));
assertEquals("fred@flintstone.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertEquals("1", row2.getColumn("CustomerID"));
assertEquals("Ian Murdock", row2.getColumn("FullName"));
assertEquals("Ian", row2.getColumn("FirstName"));
assertEquals("Murdock", row2.getColumn("LastName"));
assertEquals("41", row2.getColumn("Age"));
assertEquals("imurdock@example.com", row2.getColumn("EmailAddress"));
ETDataExtensionRow row3 = rows.get(2);
assertEquals("3", row3.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", row3.getColumn("FullName"));
assertEquals("Wilma", row3.getColumn("FirstName"));
assertEquals("Flintstone", row3.getColumn("LastName"));
assertEquals("34", row3.getColumn("Age"));
assertEquals("wilma@flintstone.com", row3.getColumn("EmailAddress"));
}
@Test
public void _09_TestSelectAllSortedSingleColumnSpecified()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("LastName",
"ORDER BY FirstName");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 3, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(3, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertNull(row1.getColumn("CustomerID"));
assertNull(row1.getColumn("FullName"));
assertNull(row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertNull(row1.getColumn("Age"));
assertNull(row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertNull(row2.getColumn("CustomerID"));
assertNull(row2.getColumn("FullName"));
assertNull(row2.getColumn("FirstName"));
assertEquals("Murdock", row2.getColumn("LastName"));
assertNull(row2.getColumn("Age"));
assertNull(row2.getColumn("EmailAddress"));
ETDataExtensionRow row3 = rows.get(2);
assertNull(row3.getColumn("CustomerID"));
assertNull(row3.getColumn("FullName"));
assertNull(row3.getColumn("FirstName"));
assertEquals("Flintstone", row3.getColumn("LastName"));
assertNull(row3.getColumn("Age"));
assertNull(row3.getColumn("EmailAddress"));
}
@Test
public void _10_TestSelectAllSortedMultipleColumnsSpecified()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("LastName",
"FirstName",
"EmailAddress",
"ORDER BY FirstName");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 3, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(3, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertNull(row1.getColumn("CustomerID"));
assertNull(row1.getColumn("FullName"));
assertEquals("Fred", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertNull(row1.getColumn("Age"));
assertEquals("fred@flintstone.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertNull(row2.getColumn("CustomerID"));
assertNull(row2.getColumn("FullName"));
assertEquals("Ian", row2.getColumn("FirstName"));
assertEquals("Murdock", row2.getColumn("LastName"));
assertNull(row2.getColumn("Age"));
assertEquals("imurdock@example.com", row2.getColumn("EmailAddress"));
ETDataExtensionRow row3 = rows.get(2);
assertNull(row3.getColumn("CustomerID"));
assertNull(row3.getColumn("FullName"));
assertEquals("Wilma", row3.getColumn("FirstName"));
assertEquals("Flintstone", row3.getColumn("LastName"));
assertNull(row3.getColumn("Age"));
assertEquals("wilma@flintstone.com", row3.getColumn("EmailAddress"));
}
@Test
public void _11_TestSelectAllPaginated()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response1 = dataExtension.select(1, 2);
assertNotNull(response1.getRequestId());
assertEquals(OK, response1.getStatus());
assertEquals("200", response1.getResponseCode());
assertEquals("OK", response1.getResponseMessage());
assertEquals((Integer) 1, response1.getPage());
assertEquals((Integer) 2, response1.getPageSize());
assertEquals((Integer) 3, response1.getTotalCount());
assertTrue(response1.hasMoreResults());
List<ETDataExtensionRow> rows1 = response1.getObjects();
assertEquals(2, rows1.size());
ETDataExtensionRow row1 = rows1.get(0);
assertEquals("1", row1.getColumn("CustomerID"));
assertEquals("Ian Murdock", row1.getColumn("FullName"));
assertEquals("Ian", row1.getColumn("FirstName"));
assertEquals("Murdock", row1.getColumn("LastName"));
assertEquals("41", row1.getColumn("Age"));
assertEquals("imurdock@example.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows1.get(1);
assertEquals("2", row2.getColumn("CustomerID"));
assertEquals("Fred Flintstone", row2.getColumn("FullName"));
assertEquals("Fred", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertEquals("36", row2.getColumn("Age"));
assertEquals("fred@flintstone.com", row2.getColumn("EmailAddress"));
ETResponse<ETDataExtensionRow> response2 = dataExtension.select(2, 2);
assertNotNull(response2.getRequestId());
assertEquals(OK, response2.getStatus());
assertEquals("200", response2.getResponseCode());
assertEquals("OK", response2.getResponseMessage());
assertEquals((Integer) 2, response2.getPage());
assertEquals((Integer) 2, response2.getPageSize());
assertEquals((Integer) 3, response2.getTotalCount());
assertFalse(response2.hasMoreResults());
List<ETDataExtensionRow> rows2 = response2.getObjects();
assertEquals(1, rows2.size());
ETDataExtensionRow row3 = rows2.get(0);
assertEquals("3", row3.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", row3.getColumn("FullName"));
assertEquals("Wilma", row3.getColumn("FirstName"));
assertEquals("Flintstone", row3.getColumn("LastName"));
assertEquals("34", row3.getColumn("Age"));
assertEquals("wilma@flintstone.com", row3.getColumn("EmailAddress"));
}
@Test
public void _12_TestSelectAllPaginatedSingleColumnSpecified()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response1 = dataExtension.select(1, 2,
"LastName");
assertNotNull(response1.getRequestId());
assertEquals(OK, response1.getStatus());
assertEquals("200", response1.getResponseCode());
assertEquals("OK", response1.getResponseMessage());
assertEquals((Integer) 1, response1.getPage());
assertEquals((Integer) 2, response1.getPageSize());
assertEquals((Integer) 3, response1.getTotalCount());
assertTrue(response1.hasMoreResults());
List<ETDataExtensionRow> rows1 = response1.getObjects();
assertEquals(2, rows1.size());
ETDataExtensionRow row1 = rows1.get(0);
assertNull(row1.getColumn("CustomerID"));
assertNull(row1.getColumn("FullName"));
assertNull(row1.getColumn("FirstName"));
assertEquals("Murdock", row1.getColumn("LastName"));
assertNull(row1.getColumn("Age"));
assertNull(row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows1.get(1);
assertNull(row2.getColumn("CustomerID"));
assertNull(row2.getColumn("FullName"));
assertNull(row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertNull(row2.getColumn("Age"));
assertNull(row2.getColumn("EmailAddress"));
ETResponse<ETDataExtensionRow> response2 = dataExtension.select(2, 2,
"LastName");
assertNotNull(response2.getRequestId());
assertEquals(OK, response2.getStatus());
assertEquals("200", response2.getResponseCode());
assertEquals("OK", response2.getResponseMessage());
assertEquals((Integer) 2, response2.getPage());
assertEquals((Integer) 2, response2.getPageSize());
assertEquals((Integer) 3, response2.getTotalCount());
assertFalse(response2.hasMoreResults());
List<ETDataExtensionRow> rows2 = response2.getObjects();
assertEquals(1, rows2.size());
ETDataExtensionRow row3 = rows2.get(0);
assertNull(row3.getColumn("CustomerID"));
assertNull(row3.getColumn("FullName"));
assertNull(row3.getColumn("FirstName"));
assertEquals("Flintstone", row3.getColumn("LastName"));
assertNull(row3.getColumn("Age"));
assertNull(row3.getColumn("EmailAddress"));
}
@Test
public void _13_TestSelectAllPaginatedMultipleColumnsSpecified()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response1 = dataExtension.select(1, 2,
"LastName",
"FirstName",
"EmailAddress");
assertNotNull(response1.getRequestId());
assertEquals(OK, response1.getStatus());
assertEquals("200", response1.getResponseCode());
assertEquals("OK", response1.getResponseMessage());
assertEquals((Integer) 1, response1.getPage());
assertEquals((Integer) 2, response1.getPageSize());
assertEquals((Integer) 3, response1.getTotalCount());
assertTrue(response1.hasMoreResults());
List<ETDataExtensionRow> rows1 = response1.getObjects();
assertEquals(2, rows1.size());
ETDataExtensionRow row1 = rows1.get(0);
assertNull(row1.getColumn("CustomerID"));
assertNull(row1.getColumn("FullName"));
assertEquals("Ian", row1.getColumn("FirstName"));
assertEquals("Murdock", row1.getColumn("LastName"));
assertNull(row1.getColumn("Age"));
assertEquals("imurdock@example.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows1.get(1);
assertNull(row2.getColumn("CustomerID"));
assertNull(row2.getColumn("FullName"));
assertEquals("Fred", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertNull(row2.getColumn("Age"));
assertEquals("fred@flintstone.com", row2.getColumn("EmailAddress"));
ETResponse<ETDataExtensionRow> response2 = dataExtension.select(2, 2,
"LastName",
"FirstName",
"EmailAddress");
assertNotNull(response2.getRequestId());
assertEquals(OK, response2.getStatus());
assertEquals("200", response2.getResponseCode());
assertEquals("OK", response2.getResponseMessage());
assertEquals((Integer) 2, response2.getPage());
assertEquals((Integer) 2, response2.getPageSize());
assertEquals((Integer) 3, response2.getTotalCount());
assertFalse(response2.hasMoreResults());
List<ETDataExtensionRow> rows2 = response2.getObjects();
assertEquals(1, rows2.size());
ETDataExtensionRow row3 = rows2.get(0);
assertNull(row3.getColumn("CustomerID"));
assertNull(row3.getColumn("FullName"));
assertEquals("Wilma", row3.getColumn("FirstName"));
assertEquals("Flintstone", row3.getColumn("LastName"));
assertNull(row3.getColumn("Age"));
assertEquals("wilma@flintstone.com", row3.getColumn("EmailAddress"));
}
@Test
public void _14_TestSelectFiltered()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("LastName=Flintstone");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 2, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(2, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("2", row1.getColumn("CustomerID"));
assertEquals("Fred Flintstone", row1.getColumn("FullName"));
assertEquals("Fred", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertEquals("36", row1.getColumn("Age"));
assertEquals("fred@flintstone.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertEquals("3", row2.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", row2.getColumn("FullName"));
assertEquals("Wilma", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertEquals("34", row2.getColumn("Age"));
assertEquals("wilma@flintstone.com", row2.getColumn("EmailAddress"));
}
@Test
public void _15_TestSelectFilteredSingleColumnSpecified()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("LastName=Flintstone",
"LastName");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 2, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(2, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertNull(row1.getColumn("CustomerID"));
assertNull(row1.getColumn("FullName"));
assertNull(row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertNull(row1.getColumn("Age"));
assertNull(row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertNull(row2.getColumn("CustomerID"));
assertNull(row2.getColumn("FullName"));
assertNull(row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertNull(row2.getColumn("Age"));
assertNull(row2.getColumn("EmailAddress"));
}
@Test
public void _16_TestSelectFilteredMultipleColumnsSpecified()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("LastName=Flintstone",
"LastName",
"FirstName",
"EmailAddress");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 2, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(2, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertNull(row1.getColumn("CustomerID"));
assertNull(row1.getColumn("FullName"));
assertEquals("Fred", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertNull(row1.getColumn("Age"));
assertEquals("fred@flintstone.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertNull(row2.getColumn("CustomerID"));
assertNull(row2.getColumn("FullName"));
assertEquals("Wilma", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertNull(row2.getColumn("Age"));
assertEquals("wilma@flintstone.com", row2.getColumn("EmailAddress"));
}
@Test
public void _17_TestSelectFilteredNotEquals()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("LastName != Flintstone");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 1, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(1, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("1", row1.getColumn("CustomerID"));
assertEquals("Ian Murdock", row1.getColumn("FullName"));
assertEquals("Ian", row1.getColumn("FirstName"));
assertEquals("Murdock", row1.getColumn("LastName"));
assertEquals("41", row1.getColumn("Age"));
assertEquals("imurdock@example.com", row1.getColumn("EmailAddress"));
}
@Test
public void _18_TestSelectFilteredLessThan()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("Age < 36");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 1, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(1, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("3", row1.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", row1.getColumn("FullName"));
assertEquals("Wilma", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertEquals("34", row1.getColumn("Age"));
assertEquals("wilma@flintstone.com", row1.getColumn("EmailAddress"));
}
@Test
public void _19_TestSelectFilteredLessThanOrEquals()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("Age <= 36");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 2, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(2, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("2", row1.getColumn("CustomerID"));
assertEquals("Fred Flintstone", row1.getColumn("FullName"));
assertEquals("Fred", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertEquals("36", row1.getColumn("Age"));
assertEquals("fred@flintstone.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertEquals("3", row2.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", row2.getColumn("FullName"));
assertEquals("Wilma", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertEquals("34", row2.getColumn("Age"));
assertEquals("wilma@flintstone.com", row2.getColumn("EmailAddress"));
}
@Test
public void _20_TestSelectFilteredGreaterThan()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("Age > 36");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 1, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(1, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("1", row1.getColumn("CustomerID"));
assertEquals("Ian Murdock", row1.getColumn("FullName"));
assertEquals("Ian", row1.getColumn("FirstName"));
assertEquals("Murdock", row1.getColumn("LastName"));
assertEquals("41", row1.getColumn("Age"));
assertEquals("imurdock@example.com", row1.getColumn("EmailAddress"));
}
@Test
public void _21_TestSelectFilteredGreaterThanOrEquals()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("Age >= 36");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 2, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(2, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("1", row1.getColumn("CustomerID"));
assertEquals("Ian Murdock", row1.getColumn("FullName"));
assertEquals("Ian", row1.getColumn("FirstName"));
assertEquals("Murdock", row1.getColumn("LastName"));
assertEquals("41", row1.getColumn("Age"));
assertEquals("imurdock@example.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertEquals("2", row2.getColumn("CustomerID"));
assertEquals("Fred Flintstone", row2.getColumn("FullName"));
assertEquals("Fred", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertEquals("36", row2.getColumn("Age"));
assertEquals("fred@flintstone.com", row2.getColumn("EmailAddress"));
}
@Test
public void _22_TestSelectFilteredIn1()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("Age in (34, 35)");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 1, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(1, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("3", row1.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", row1.getColumn("FullName"));
assertEquals("Wilma", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertEquals("34", row1.getColumn("Age"));
assertEquals("wilma@flintstone.com", row1.getColumn("EmailAddress"));
}
@Test
public void _23_TestSelectFilteredIn2()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("Age in (34, 35, 36)");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 2, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(2, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("2", row1.getColumn("CustomerID"));
assertEquals("Fred Flintstone", row1.getColumn("FullName"));
assertEquals("Fred", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertEquals("36", row1.getColumn("Age"));
assertEquals("fred@flintstone.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertEquals("3", row2.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", row2.getColumn("FullName"));
assertEquals("Wilma", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertEquals("34", row2.getColumn("Age"));
assertEquals("wilma@flintstone.com", row2.getColumn("EmailAddress"));
}
@Test
public void _24_TestSelectFilteredIn3()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("Age in (34, 35, 36, 37)");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 2, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(2, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("2", row1.getColumn("CustomerID"));
assertEquals("Fred Flintstone", row1.getColumn("FullName"));
assertEquals("Fred", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertEquals("36", row1.getColumn("Age"));
assertEquals("fred@flintstone.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertEquals("3", row2.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", row2.getColumn("FullName"));
assertEquals("Wilma", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertEquals("34", row2.getColumn("Age"));
assertEquals("wilma@flintstone.com", row2.getColumn("EmailAddress"));
}
@Test
public void _25_TestSelectFilteredBetween()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("Age between 30 and 40");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 2, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(2, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("2", row1.getColumn("CustomerID"));
assertEquals("Fred Flintstone", row1.getColumn("FullName"));
assertEquals("Fred", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertEquals("36", row1.getColumn("Age"));
assertEquals("fred@flintstone.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertEquals("3", row2.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", row2.getColumn("FullName"));
assertEquals("Wilma", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertEquals("34", row2.getColumn("Age"));
assertEquals("wilma@flintstone.com", row2.getColumn("EmailAddress"));
}
@Test
public void _26_TestSelectFilteredLike()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("LastName like 'Flint%'");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 2, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(2, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("2", row1.getColumn("CustomerID"));
assertEquals("Fred Flintstone", row1.getColumn("FullName"));
assertEquals("Fred", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertEquals("36", row1.getColumn("Age"));
assertEquals("fred@flintstone.com", row1.getColumn("EmailAddress"));
ETDataExtensionRow row2 = rows.get(1);
assertEquals("3", row2.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", row2.getColumn("FullName"));
assertEquals("Wilma", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertEquals("34", row2.getColumn("Age"));
assertEquals("wilma@flintstone.com", row2.getColumn("EmailAddress"));
}
@Test
public void _27_TestSelectFilteredAnd()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("LastName=Flintstone and FirstName = 'Wilma'");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 1, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(1, rows.size());
ETDataExtensionRow row1 = rows.get(0);
assertEquals("3", row1.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", row1.getColumn("FullName"));
assertEquals("Wilma", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertEquals("34", row1.getColumn("Age"));
assertEquals("wilma@flintstone.com", row1.getColumn("EmailAddress"));
}
@Test
public void _28_TestSelectFilteredPaginated()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response1 = dataExtension.select("LastName=Flintstone",
1, 1);
assertNotNull(response1.getRequestId());
assertEquals(OK, response1.getStatus());
assertEquals("200", response1.getResponseCode());
assertEquals("OK", response1.getResponseMessage());
assertEquals((Integer) 1, response1.getPage());
assertEquals((Integer) 1, response1.getPageSize());
assertEquals((Integer) 2, response1.getTotalCount());
assertTrue(response1.hasMoreResults());
List<ETDataExtensionRow> rows1 = response1.getObjects();
assertEquals(1, rows1.size());
ETDataExtensionRow row1 = rows1.get(0);
assertEquals("2", row1.getColumn("CustomerID"));
assertEquals("Fred Flintstone", row1.getColumn("FullName"));
assertEquals("Fred", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertEquals("36", row1.getColumn("Age"));
assertEquals("fred@flintstone.com", row1.getColumn("EmailAddress"));
ETResponse<ETDataExtensionRow> response2 = dataExtension.select("LastName=Flintstone",
2, 1);
assertNotNull(response2.getRequestId());
assertEquals(OK, response2.getStatus());
assertEquals("200", response2.getResponseCode());
assertEquals("OK", response2.getResponseMessage());
assertEquals((Integer) 2, response2.getPage());
assertEquals((Integer) 1, response2.getPageSize());
assertEquals((Integer) 2, response2.getTotalCount());
assertFalse(response2.hasMoreResults());
List<ETDataExtensionRow> rows2 = response2.getObjects();
assertEquals(1, rows2.size());
ETDataExtensionRow row2 = rows2.get(0);
assertEquals("3", row2.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", row2.getColumn("FullName"));
assertEquals("Wilma", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertEquals("34", row2.getColumn("Age"));
assertEquals("wilma@flintstone.com", row2.getColumn("EmailAddress"));
}
@Test
public void _29_TestSelectFilteredPaginatedSingleColumnSpecified()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response1 = dataExtension.select("LastName=Flintstone",
1, 1,
"LastName");
assertNotNull(response1.getRequestId());
assertEquals(OK, response1.getStatus());
assertEquals("200", response1.getResponseCode());
assertEquals("OK", response1.getResponseMessage());
assertEquals((Integer) 1, response1.getPage());
assertEquals((Integer) 1, response1.getPageSize());
assertEquals((Integer) 2, response1.getTotalCount());
assertTrue(response1.hasMoreResults());
List<ETDataExtensionRow> rows1 = response1.getObjects();
assertEquals(1, rows1.size());
ETDataExtensionRow row1 = rows1.get(0);
assertNull(row1.getColumn("CustomerID"));
assertNull(row1.getColumn("FullName"));
assertNull(row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertNull(row1.getColumn("Age"));
assertNull(row1.getColumn("EmailAddress"));
ETResponse<ETDataExtensionRow> response2 = dataExtension.select("LastName=Flintstone",
2, 1,
"LastName");
assertNotNull(response2.getRequestId());
assertEquals(OK, response2.getStatus());
assertEquals("200", response2.getResponseCode());
assertEquals("OK", response2.getResponseMessage());
assertEquals((Integer) 2, response2.getPage());
assertEquals((Integer) 1, response2.getPageSize());
assertEquals((Integer) 2, response2.getTotalCount());
assertFalse(response2.hasMoreResults());
List<ETDataExtensionRow> rows2 = response2.getObjects();
assertEquals(1, rows2.size());
ETDataExtensionRow row2 = rows2.get(0);
assertNull(row2.getColumn("CustomerID"));
assertNull(row2.getColumn("FullName"));
assertNull(row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertNull(row2.getColumn("Age"));
assertNull(row2.getColumn("EmailAddress"));
}
@Test
public void _30_TestSelectFilteredPaginatedMultipleColumnsSpecified()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response1 = dataExtension.select("LastName=Flintstone",
1, 1,
"LastName",
"FirstName",
"EmailAddress");
assertNotNull(response1.getRequestId());
assertEquals(OK, response1.getStatus());
assertEquals("200", response1.getResponseCode());
assertEquals("OK", response1.getResponseMessage());
assertEquals((Integer) 1, response1.getPage());
assertEquals((Integer) 1, response1.getPageSize());
assertEquals((Integer) 2, response1.getTotalCount());
assertTrue(response1.hasMoreResults());
List<ETDataExtensionRow> rows1 = response1.getObjects();
assertEquals(1, rows1.size());
ETDataExtensionRow row1 = rows1.get(0);
assertNull(row1.getColumn("CustomerID"));
assertNull(row1.getColumn("FullName"));
assertEquals("Fred", row1.getColumn("FirstName"));
assertEquals("Flintstone", row1.getColumn("LastName"));
assertNull(row1.getColumn("Age"));
assertEquals("fred@flintstone.com", row1.getColumn("EmailAddress"));
ETResponse<ETDataExtensionRow> response2 = dataExtension.select("LastName=Flintstone",
2, 1,
"LastName",
"FirstName",
"EmailAddress");
assertNotNull(response2.getRequestId());
assertEquals(OK, response2.getStatus());
assertEquals("200", response2.getResponseCode());
assertEquals("OK", response2.getResponseMessage());
assertEquals((Integer) 2, response2.getPage());
assertEquals((Integer) 1, response2.getPageSize());
assertEquals((Integer) 2, response2.getTotalCount());
assertFalse(response2.hasMoreResults());
List<ETDataExtensionRow> rows2 = response2.getObjects();
assertEquals(1, rows2.size());
ETDataExtensionRow row2 = rows2.get(0);
assertNull(row2.getColumn("CustomerID"));
assertNull(row2.getColumn("FullName"));
assertEquals("Wilma", row2.getColumn("FirstName"));
assertEquals("Flintstone", row2.getColumn("LastName"));
assertNull(row2.getColumn("Age"));
assertEquals("wilma@flintstone.com", row2.getColumn("EmailAddress"));
}
@Test
public void _31_TestSelectZeroRowsReturned()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.select("LastName=fnord");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("200", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertEquals((Integer) 1, response.getPage());
assertEquals((Integer) 2500, response.getPageSize());
assertEquals((Integer) 0, response.getTotalCount());
assertFalse(response.hasMoreResults());
List<ETDataExtensionRow> rows = response.getObjects();
assertEquals(0, rows.size());
}
@Test
public void _32_TestUpdateSingleRow()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETDataExtensionRow row = new ETDataExtensionRow();
row.setColumn("CustomerID", "1");
row.setColumn("FirstName", "IAN");
ETResponse<ETDataExtensionRow> response = dataExtension.update(row);
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(1, response.getResults().size());
ETResult<ETDataExtensionRow> result = response.getResult();
assertNull(result.getRequestId());
assertEquals(OK, result.getStatus());
assertEquals("OK", result.getResponseCode());
assertEquals("Updated DataExtensionObject", result.getResponseMessage());
assertNull(result.getErrorCode());
assertNull(result.getObjectId());
ETDataExtensionRow r = result.getObject();
assertEquals("1", r.getColumn("CustomerID"));
assertNull(r.getColumn("FullName"));
assertEquals("IAN", r.getColumn("FirstName"));
assertNull(r.getColumn("LastName"));
assertNull(r.getColumn("Age"));
assertNull(r.getColumn("EmailAddress"));
}
@Test
public void _33_TestUpdateMultipleRows()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETDataExtensionRow row1 = new ETDataExtensionRow();
row1.setColumn("CustomerID", "2");
row1.setColumn("FirstName", "FRED");
ETDataExtensionRow row2 = new ETDataExtensionRow();
row2.setColumn("CustomerID", "3");
row2.setColumn("FirstName", "WILMA");
ETResponse<ETDataExtensionRow> response = dataExtension.update(row1, row2);
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(2, response.getResults().size());
ETResult<ETDataExtensionRow> result1 = response.getResults().get(0);
assertNull(result1.getRequestId());
assertEquals(OK, result1.getStatus());
assertEquals("OK", result1.getResponseCode());
assertEquals("Updated DataExtensionObject", result1.getResponseMessage());
assertNull(result1.getErrorCode());
assertNull(result1.getObjectId());
ETDataExtensionRow r1 = result1.getObject();
assertEquals("2", r1.getColumn("CustomerID"));
assertNull(r1.getColumn("FullName"));
assertEquals("FRED", r1.getColumn("FirstName"));
assertNull(r1.getColumn("LastName"));
assertNull(r1.getColumn("Age"));
assertNull(r1.getColumn("EmailAddress"));
ETResult<ETDataExtensionRow> result2 = response.getResults().get(1);
assertNull(result2.getRequestId());
assertEquals(OK, result2.getStatus());
assertEquals("OK", result2.getResponseCode());
assertEquals("Updated DataExtensionObject", result2.getResponseMessage());
assertNull(result2.getErrorCode());
assertNull(result2.getObjectId());
ETDataExtensionRow r2 = result2.getObject();
assertEquals("3", r2.getColumn("CustomerID"));
assertNull(r2.getColumn("FullName"));
assertEquals("WILMA", r2.getColumn("FirstName"));
assertNull(r2.getColumn("LastName"));
assertNull(r2.getColumn("Age"));
assertNull(r2.getColumn("EmailAddress"));
}
@Test
public void _34_TestUpdateRowsByFilter()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETResponse<ETDataExtensionRow> response = dataExtension.update("LastName=Flintstone",
"FirstName='Fred and Wilma'");
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(2, response.getResults().size());
ETResult<ETDataExtensionRow> result1 = response.getResults().get(0);
assertNull(result1.getRequestId());
assertEquals(OK, result1.getStatus());
assertEquals("OK", result1.getResponseCode());
assertEquals("Updated DataExtensionObject", result1.getResponseMessage());
assertNull(result1.getErrorCode());
assertNull(result1.getObjectId());
ETDataExtensionRow r1 = result1.getObject();
assertEquals("2", r1.getColumn("CustomerID"));
assertEquals("Fred Flintstone", r1.getColumn("FullName"));
assertEquals("Fred and Wilma", r1.getColumn("FirstName"));
assertEquals("Flintstone", r1.getColumn("LastName"));
assertEquals("36", r1.getColumn("Age"));
assertEquals("fred@flintstone.com", r1.getColumn("EmailAddress"));
ETResult<ETDataExtensionRow> result2 = response.getResults().get(1);
assertNull(result2.getRequestId());
assertEquals(OK, result2.getStatus());
assertEquals("OK", result2.getResponseCode());
assertEquals("Updated DataExtensionObject", result2.getResponseMessage());
assertNull(result2.getErrorCode());
assertNull(result2.getObjectId());
ETDataExtensionRow r2 = result2.getObject();
assertEquals("3", r2.getColumn("CustomerID"));
assertEquals("Wilma Flintstone", r2.getColumn("FullName"));
assertEquals("Fred and Wilma", r2.getColumn("FirstName"));
assertEquals("Flintstone", r2.getColumn("LastName"));
assertEquals("34", r2.getColumn("Age"));
assertEquals("wilma@flintstone.com", r2.getColumn("EmailAddress"));
}
@Test(expected = ETSdkException.class)
public void _35_TestUpdateRowsByFilterInvalidOperator()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
@SuppressWarnings("unused")
ETResponse<ETDataExtensionRow> response = dataExtension.update("LastName=Flintstone",
"FirstName != 'Fred and Wilma'");
}
@Test
public void _36_TestDeleteSingleRow()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETDataExtensionRow row = new ETDataExtensionRow();
row.setColumn("CustomerID", "1");
ETResponse<ETDataExtensionRow> response = dataExtension.delete(row);
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(1, response.getResults().size());
ETResult<ETDataExtensionRow> result = response.getResult();
assertNull(result.getRequestId());
assertEquals(OK, result.getStatus());
assertEquals("OK", result.getResponseCode());
assertEquals("Deleted DataExtensionObject", result.getResponseMessage());
assertNull(result.getErrorCode());
assertNull(result.getObject());
assertNull(result.getObjectId());
}
@Test
public void _37_TestDeleteMultipleRows()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETDataExtensionRow row1 = new ETDataExtensionRow();
row1.setColumn("CustomerID", "2");
ETDataExtensionRow row2 = new ETDataExtensionRow();
row2.setColumn("CustomerID", "3");
ETResponse<ETDataExtensionRow> response = dataExtension.delete(row1, row2);
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(2, response.getResults().size());
ETResult<ETDataExtensionRow> result1 = response.getResults().get(0);
assertNull(result1.getRequestId());
assertEquals(OK, result1.getStatus());
assertEquals("OK", result1.getResponseCode());
assertEquals("Deleted DataExtensionObject", result1.getResponseMessage());
assertNull(result1.getErrorCode());
assertNull(result1.getObject());
assertNull(result1.getObjectId());
ETResult<ETDataExtensionRow> result2 = response.getResults().get(1);
assertNull(result2.getRequestId());
assertEquals(OK, result2.getStatus());
assertEquals("OK", result2.getResponseCode());
assertEquals("Deleted DataExtensionObject", result2.getResponseMessage());
assertNull(result2.getErrorCode());
assertNull(result2.getObject());
assertNull(result2.getObjectId());
}
//@Test
public void _38_TestDeleteRowsByFilter()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
}
//@Test
public void _39_TestDeleteRowsByFilterInvalidOperator()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
}
@Test
public void _40_TestDeleteSingle()
throws ETSdkException
{
assertEquals(CLIENT_ID, client.getClientId());
ETDataExtension dataExtension = new ETDataExtension();
dataExtension.setKey("test1");
ETResponse<ETDataExtension> response = client.delete(dataExtension);
assertNotNull(response.getRequestId());
assertEquals(OK, response.getStatus());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(1, response.getResults().size());
ETResult<ETDataExtension> result = response.getResult();
assertNull(result.getRequestId());
assertEquals(OK, result.getStatus());
assertEquals("OK", result.getResponseCode());
assertEquals("Data Extension deleted.", result.getResponseMessage());
assertNull(result.getErrorCode());
}
} |
/* @java.file.header */
package org.gridgain.grid.cache;
import org.gridgain.grid.lang.*;
import org.jetbrains.annotations.*;
/**
* Cache projection flags that specify projection behaviour. This flags can be explicitly passed into
* the following methods on {@link GridCacheProjection}:
* <ul>
* <li>{@link GridCacheProjection#flagsOn(GridCacheFlag...)}</li>
* <li>{@link GridCacheProjection#flagsOff(GridCacheFlag...)}</li>
* </ul>
* Also, some flags, like {@link #LOCAL}, or {@link #READ} may be implicitly set whenever
* creating new projections and passing entries to predicate filters.
*/
public enum GridCacheFlag {
/**
* Only operations that don't require any communication with
* other cache nodes are allowed. This flag is automatically set
* on underlying projection for all the entries that are given to
* predicate filters to make sure that no distribution happens
* from inside of predicate evaluation.
*/
LOCAL,
/**
* Only operations that don't change cached data are allowed.
* This flag is automatically set on underlying projection for
* all the entries that are given to predicate filters to make
* sure that data cannot be updated during predicate evaluation.
*/
READ,
/**
* Clone values prior to returning them to user.
* <p>
* Whenever values are returned from cache, they cannot be directly updated
* as cache holds the same references internally. If it is needed to
* update values that are returned from cache, this flag will provide
* automatic cloning of values prior to returning so they can be directly
* updated.
*
* @see GridCacheConfiguration#getCloner()
*/
CLONE,
/** Skips store, i.e. no read-through and no write-through behavior. */
SKIP_STORE,
/** Skip swap space for reads and writes. */
SKIP_SWAP,
/** Synchronous commit. */
SYNC_COMMIT,
/**
* Switches a cache projection to work in {@code 'invalidation'} mode.
* Instead of updating remote entries with new values, small invalidation
* messages will be sent to set the values to {@code null}.
*
* @see GridCacheTx#isInvalidate()
* @see GridCacheConfiguration#isInvalidate()
*/
INVALIDATE,
/**
* Skips version check during {@link GridCacheProjection#transform(Object, GridClosure)} writes in
* {@link GridCacheAtomicityMode#ATOMIC} mode. By default, in {@code ATOMIC} mode, whenever
* {@code transform(...)} is called, cache values (and not the {@code transform} closure) are sent from primary
* node to backup nodes to ensure proper update ordering.
* <p>
* By setting this flag, version check is skipped, and {@code transform} closure is applied on both, primary
* and backup nodes. Use this flag for better performance if you are sure that there are no
* concurrent updates happening for the same key.
*/
FORCE_TRANSFORM_BACKUP;
private static final GridCacheFlag[] VALS = values();
/**
* Efficiently gets enumerated value from its ordinal.
*
* @param ord Ordinal value.
* @return Enumerated value or {@code null} if ordinal out of range.
*/
@Nullable public static GridCacheFlag fromOrdinal(int ord) {
return ord >= 0 && ord < VALS.length ? VALS[ord] : null;
}
} |
package com.forgeessentials.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import com.forgeessentials.api.APIRegistry;
import com.forgeessentials.api.UserIdent;
import com.forgeessentials.commons.selections.Point;
import com.forgeessentials.commons.selections.WarpPoint;
import com.forgeessentials.data.v2.DataManager;
import com.forgeessentials.data.v2.Loadable;
import com.forgeessentials.util.events.FEPlayerEvent.ClientHandshakeEstablished;
import com.forgeessentials.util.events.FEPlayerEvent.NoPlayerInfoEvent;
import com.forgeessentials.util.selections.SelectionHandler;
import com.google.gson.annotations.Expose;
public class PlayerInfo implements Loadable
{
private static HashMap<UUID, PlayerInfo> playerInfoMap = new HashMap<UUID, PlayerInfo>();
/* General */
public final UserIdent ident;
@Expose(serialize = false)
private boolean hasFEClient = false;
/* Teleport */
private WarpPoint home;
private WarpPoint lastTeleportOrigin;
private WarpPoint lastDeathLocation;
private long lastTeleportTime = 0;
/* Selection */
private Point sel1;
private Point sel2;
private int selDim;
/* Selection wand */
@Expose(serialize = false)
private boolean wandEnabled = false;
@Expose(serialize = false)
private String wandID;
@Expose(serialize = false)
private int wandDmg;
/* Inventory groups */
private Map<String, List<ItemStack>> inventoryGroups = new HashMap<>();
private String activeInventoryGroup = "default";
/* Stats / time */
private long timePlayed = 0;
@Expose(serialize = false)
private long timePlayedRef = 0;
private Date firstLogin = new Date();
private Date lastLogin = new Date();
private Date lastLogout;
@Expose(serialize = false)
private long lastActivity = System.currentTimeMillis();
private HashMap<String, Date> namedTimeout = new HashMap<String, Date>();
private PlayerInfo(UUID uuid)
{
this.ident = UserIdent.get(uuid);
}
@Override
public void afterLoad()
{
if (namedTimeout == null)
namedTimeout = new HashMap<String, Date>();
lastActivity = System.currentTimeMillis();
if (activeInventoryGroup == null || activeInventoryGroup.isEmpty())
activeInventoryGroup = "default";
}
/**
* Notifies the PlayerInfo to save itself to the Data store.
*/
public void save()
{
DataManager.getInstance().save(this, ident.getUuid().toString());
}
public boolean isLoggedIn()
{
return ident.hasPlayer();
}
public static PlayerInfo get(UUID uuid)
{
PlayerInfo info = playerInfoMap.get(uuid);
if (info != null)
return info;
// Attempt to populate this info with some data from our storage
info = DataManager.getInstance().load(PlayerInfo.class, uuid.toString());
if (info != null)
{
playerInfoMap.put(uuid, info);
return info;
}
// Create new player info data
EntityPlayerMP player = UserIdent.getPlayerByUuid(uuid);
info = new PlayerInfo(uuid);
playerInfoMap.put(uuid, info);
if (player != null)
APIRegistry.getFEEventBus().post(new NoPlayerInfoEvent(player));
return info;
}
public static PlayerInfo get(EntityPlayer player)
{
return get(player.getPersistentID());
}
public static PlayerInfo get(UserIdent ident)
{
if (!ident.hasUuid())
return null;
return get(ident.getUuid());
}
public static Collection<PlayerInfo> getAll()
{
return playerInfoMap.values();
}
public static void login(UUID uuid)
{
PlayerInfo pi = get(uuid);
pi.lastActivity = System.currentTimeMillis();
pi.timePlayedRef = System.currentTimeMillis();
pi.lastLogin = new Date();
}
public static void logout(UUID uuid)
{
if (!playerInfoMap.containsKey(uuid))
return;
PlayerInfo pi = playerInfoMap.remove(uuid);
pi.getTimePlayed();
pi.lastLogout = new Date();
pi.timePlayedRef = 0;
pi.save();
}
public static boolean exists(UUID uuid)
{
if (playerInfoMap.containsKey(uuid))
return true;
if (DataManager.getInstance().exists(PlayerInfo.class, uuid.toString()))
return true;
return false;
}
/**
* Unload PlayerInfo and save to disk
*/
public static void discard(UUID uuid)
{
PlayerInfo info = playerInfoMap.remove(uuid);
if (info != null)
info.save();
}
/**
* Discard all PlayerInfo
*/
public static void discardAll()
{
for (PlayerInfo info : playerInfoMap.values())
info.save();
playerInfoMap.clear();
}
public Date getFirstLogin()
{
return firstLogin;
}
public Date getLastLogin()
{
return lastLogin;
}
public Date getLastLogout()
{
return lastLogout;
}
public long getTimePlayed()
{
if (isLoggedIn() && timePlayedRef != 0)
{
timePlayed += System.currentTimeMillis() - timePlayedRef;
timePlayedRef = System.currentTimeMillis();
}
return timePlayed;
}
public void setActive()
{
lastActivity = System.currentTimeMillis();
}
public void setActive(long delta)
{
lastActivity = System.currentTimeMillis() - delta;
}
public long getInactiveTime()
{
return System.currentTimeMillis() - lastActivity;
}
/* Timeouts */
/**
* Check, if a timeout passed
*
* @param name
* @return true, if the timeout passed
*/
public boolean checkTimeout(String name)
{
Date timeout = namedTimeout.get(name);
if (timeout == null)
return true;
if (timeout.after(new Date()))
return false;
namedTimeout.remove(name);
return true;
}
/**
* Get the remaining timeout in milliseconds
*/
public long getRemainingTimeout(String name)
{
Date timeout = namedTimeout.get(name);
if (timeout == null)
return 0;
return timeout.getTime() - new Date().getTime();
}
/**
* Start a named timeout. Use {@link #checkTimeout(String)} to check if the timeout has passed.
*
* @param name
* Unique name of the timeout
* @param milliseconds
* Timeout in milliseconds
*/
public void startTimeout(String name, long milliseconds)
{
Date date = new Date();
date.setTime(date.getTime() + milliseconds);
namedTimeout.put(name, date);
}
/* Wand */
public boolean isWandEnabled()
{
return wandEnabled;
}
public void setWandEnabled(boolean wandEnabled)
{
this.wandEnabled = wandEnabled;
}
public String getWandID()
{
return wandID;
}
public void setWandID(String wandID)
{
this.wandID = wandID;
}
public int getWandDmg()
{
return wandDmg;
}
public void setWandDmg(int wandDmg)
{
this.wandDmg = wandDmg;
}
/* Selection */
public Point getSel1()
{
return sel1;
}
public Point getSel2()
{
return sel2;
}
public int getSelDim()
{
return selDim;
}
public void setSel1(Point point)
{
sel1 = point;
}
public void setSel2(Point point)
{
sel2 = point;
}
public void setSelDim(int dimension)
{
selDim = dimension;
}
/* Inventory groups */
public Map<String, List<ItemStack>> getInventoryGroups()
{
return inventoryGroups;
}
public List<ItemStack> getInventoryGroupItems(String name)
{
return inventoryGroups.get(name);
}
public String getInventoryGroup()
{
return activeInventoryGroup;
}
public void setInventoryGroup(String name)
{
if (!activeInventoryGroup.equals(name))
{
// Get the new inventory
List<ItemStack> newInventory = inventoryGroups.get(name);
// Create empty inventory if it did not exist yet
if (newInventory == null)
newInventory = new ArrayList<>();
// ChatOutputHandler.felog.info(String.format("Changing inventory group for %s from %s to %s",
// ident.getUsernameOrUUID(), activeInventoryGroup, name));
/*
* ChatOutputHandler.felog.info("Items in old inventory:"); for (int i = 0; i <
* ident.getPlayer().inventory.getSizeInventory(); i++) { ItemStack itemStack =
* ident.getPlayer().inventory.getStackInSlot(i); if (itemStack != null) ChatOutputHandler.felog.info(" " +
* itemStack.getDisplayName()); } ChatOutputHandler.felog.info("Items in new inventory:"); for (ItemStack
* itemStack : newInventory) if (itemStack != null) ChatOutputHandler.felog.info(" " +
* itemStack.getDisplayName());
*/
// Swap player inventory and store the old one
inventoryGroups.put(activeInventoryGroup, PlayerUtil.swapInventory(this.ident.getPlayerMP(), newInventory));
// Clear the inventory-group that was assigned to the player (optional)
inventoryGroups.put(name, null);
// Save the new active inventory-group
activeInventoryGroup = name;
this.save();
}
}
/* Teleportation */
public WarpPoint getLastTeleportOrigin()
{
return lastTeleportOrigin;
}
public void setLastTeleportOrigin(WarpPoint lastTeleportStart)
{
this.lastTeleportOrigin = lastTeleportStart;
}
public WarpPoint getLastDeathLocation()
{
return lastDeathLocation;
}
public void setLastDeathLocation(WarpPoint lastDeathLocation)
{
this.lastDeathLocation = lastDeathLocation;
}
public long getLastTeleportTime()
{
return lastTeleportTime;
}
public void setLastTeleportTime(long currentTimeMillis)
{
this.lastTeleportTime = currentTimeMillis;
}
public WarpPoint getHome()
{
return home;
}
public void setHome(WarpPoint home)
{
this.home = home;
}
/* Other */
public boolean getHasFEClient()
{
return hasFEClient;
}
public void setHasFEClient(boolean status)
{
this.hasFEClient = status;
APIRegistry.getFEEventBus().post(new ClientHandshakeEstablished(this.ident.getPlayer()));
}
} |
package com.github.davidmoten.rx;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.observables.AbstractOnSubscribe;
/**
* Utility class for writing Observable streams to ObjectOutputStreams and
* reading Observable streams of indeterminate size from ObjectInputStreams.
*/
public final class Serialized {
private static final int DEFAULT_BUFFER_SIZE = 8192;
/**
* Returns the deserialized objects from the given {@link InputStream} as an
* {@link Observable} stream.
*
* @param is
* the input stream
* @param <T>
* the generic type of the returned stream
* @return the stream of deserialized objects from the {@link InputStream}
* as an {@link Observable}.
*/
public static <T extends Serializable> Observable<T> read(final ObjectInputStream ois) {
return Observable.create(new AbstractOnSubscribe<T, ObjectInputStream>() {
@Override
protected ObjectInputStream onSubscribe(Subscriber<? super T> subscriber) {
return ois;
}
@Override
protected void next(SubscriptionState<T, ObjectInputStream> state) {
ObjectInputStream ois = state.state();
try {
@SuppressWarnings("unchecked")
T t = (T) ois.readObject();
state.onNext(t);
} catch (EOFException e) {
state.onCompleted();
} catch (ClassNotFoundException e) {
state.onError(e);
return;
} catch (IOException e) {
state.onError(e);
return;
}
}
});
}
/**
* Returns the deserialized objects from the given {@link File} as an
* {@link Observable} stream. Uses buffer of size <code>bufferSize</code>
* buffer reads from the File.
*
* @param file
* the input file
* @param bufferSize
* the buffer size for reading bytes from the file.
* @param <T>
* the generic type of the deserialized objects returned in the
* stream
* @return the stream of deserialized objects from the {@link InputStream}
* as an {@link Observable}.
*/
public static <T extends Serializable> Observable<T> read(final File file, final int bufferSize) {
Func0<ObjectInputStream> resourceFactory = new Func0<ObjectInputStream>() {
@Override
public ObjectInputStream call() {
try {
return new ObjectInputStream(new BufferedInputStream(new FileInputStream(file),
bufferSize));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
Func1<ObjectInputStream, Observable<? extends T>> observableFactory = new Func1<ObjectInputStream, Observable<? extends T>>() {
@Override
public Observable<? extends T> call(ObjectInputStream is) {
return read(is);
}
};
Action1<ObjectInputStream> disposeAction = new Action1<ObjectInputStream>() {
@Override
public void call(ObjectInputStream ois) {
try {
ois.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
return Observable.using(resourceFactory, observableFactory, disposeAction, true);
}
/**
* Returns the deserialized objects from the given {@link File} as an
* {@link Observable} stream. A buffer size of 8192 bytes is used by default.
*
* @param file
* the input file containing serialized java objects
* @param <T>
* the generic type of the deserialized objects returned in the
* stream
* @return the stream of deserialized objects from the {@link InputStream}
* as an {@link Observable}.
*/
public static <T extends Serializable> Observable<T> read(final File file) {
return read(file, DEFAULT_BUFFER_SIZE);
}
/**
* Returns a duplicate of the input stream but with the side effect that
* emissions from the source are written to the input stream wrapped as an
* ObjectOutputStream.
*
* @param source
* the source of objects to write
* @param oos
* the output stream to write to
* @param <T>
* the generic type of the objects being serialized
* @return
*/
public static <T extends Serializable> Observable<T> write(Observable<T> source,
final ObjectOutputStream oos) {
return source.doOnNext(new Action1<T>() {
@Override
public void call(T t) {
try {
ois.writeObject(t);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
/**
* Writes the source stream to the given file in given append mode and using
* the given buffer size.
*
* @param source
* observable stream to write
* @param file
* file to write to
* @param append
* if true writes are appended to file otherwise overwrite the
* file
* @param bufferSize
* the buffer size in bytes to use.
* @param <T>
* the generic type of the input stream
* @return
*/
public static <T extends Serializable> Observable<T> write(final Observable<T> source,
final File file, final boolean append, final int bufferSize) {
Func0<ObjectOutputStream> resourceFactory = new Func0<ObjectOutputStream>() {
@Override
public ObjectOutputStream call() {
try {
return new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(
file, append), bufferSize));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
Func1<ObjectOutputStream, Observable<? extends T>> observableFactory = new Func1<ObjectOutputStream, Observable<? extends T>>() {
@Override
public Observable<? extends T> call(ObjectOutputStream oos) {
return write(source, oos);
}
};
Action1<ObjectOutputStream> disposeAction = new Action1<ObjectOutputStream>() {
@Override
public void call(ObjectOutputStream oos) {
try {
oos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
return Observable.using(resourceFactory, observableFactory, disposeAction, true);
}
/**
* Writes the source stream to the given file in given append mode and using
* the a buffer size of 8192 bytes.
*
* @param source
* observable stream to write
* @param file
* file to write to
* @param append
* if true writes are appended to file otherwise overwrite the
* file
* @param <T>
* the generic type of the input stream
* @return
*/
public static <T extends Serializable> Observable<T> write(final Observable<T> source,
final File file, final boolean append) {
return write(source, file, append, DEFAULT_BUFFER_SIZE);
}
} |
package org.jlib.core.collections.list;
import java.util.ArrayList;
import org.jlib.core.collections.Collection;
/**
* <p>
* Fixed sized array. Replacement for the standard Java arrays with special features.
* </p>
* <p>
* The only syntactical difference to Java arrays lies in the syntax of setting and
* getting objects and getting the array size:
* </p>
*
* <pre>
* {@literal
* // good(?) old Java array // cool(!) new jlib Array class
* String[] stringArray = new String[10]; Array<String> stringArray = new Array<String>(10);
* stringArray[4] = "good(?) old Java array"; stringArray.set(4, "cool(!) new jlib Array class");
* String s = stringArray[4]; String s = stringArray.get(4);
* int size = stringArray.length; int size = stringArray.size(); }
* </pre>
*
* <p>
* Special features:
* </p>
* <ul>
* <li> Minimum and maximum index: <br/> On instantiation, you can specify the minimum and
* the maximum index of the Array. Thus, no offset is necessary for Arrays starting at
* other indices than 0. The following example illustrates how an Array is filled with
* numbers from 1 to 10:
*
* <pre>
* // good(?) old Java array // cool(!) new jlib Array class
* Integer[] integerArray = new Integer[10]; Array<Integer> integerArray = new Array<Integer>(1, 10);
* for (int i = 1; i <= 10; i ++) for (int i = 1; i <= 10; i ++)
* integerArray[i - 1] = i; integerArray.set(i, i);
* </pre>
*
* </li>
* <li> Conformance to the Java Collections framework <br/> The class implements the
* {@code java.util.Collection} interface and thus behaves like all Java Collections.
* </li>
* <br />
* <li> Full support for generics:<br/> The Java arrays do not support generic classes.
* For example, you cannot create an array of String lists:
*
* <pre>
* {@literal
* // FORBIDDEN!
* List<String>[] stringListArray = new List<String>[10];
*
* // PERMITTED!
* Array<List<String>> stringListArray = new Array<List<String>>(10);}
* </pre>
*
* </li>
* <li> Easy to create:<br />
*
* <pre>
* {@literal
* // creating an Array with three Strings
* Array<String> stringArray = new Array<String>("cool", "Array", "class!");
*
* // creating an Array with three Strings starting at index 1
* Array<String> stringArray = new Array<String>(1, "jlib", "is", "cool!");}
* </pre>
*
* A small problem arises if you want to create Arrays of Integers. The Java autoboxing
* feature forbids the following Array creation:
*
* <pre>
* {@literal
* // FORBIDDEN!
* Array<Integer> integerArray = new Array<Integer>(1, 2, 3, 4, 5, 6);}
* </pre>
*
* The compiler claims:
*
* <pre>
* {@literal The constructor Array<Integer>(Integer[]) is ambiguous}
* </pre>
*
* It doesn't know whether the first parameter is meant as the minimum index of the Array
* or the first Element of the list. You could pass a Java array of Integers instead which
* is the equivalent to the list form for the argument {@code Integer... elements} but
* this class provides an easier way: the factory methods
* {@link #newIntegerArray(Integer[])} or {@link #newIntegerArrayFrom(int, Integer[])}.
* The latter form takes the minimum index as first argument.
*
* <pre>
* // possible but not handy
* Array<Integer> integerArray = new Array<Integer>(new Integer[] {1, 2, 3, 4, 5, 6});
* Array<Integer> integerArray = new Array<Integer>(1, new Integer[] {1, 2, 3, 4, 5, 6});
*
* // easier to use (needs the static import of the factory method(s))
* Array<Integer> integerArray = newIntegerArray(1, 2, 3, 4, 5);
* Array<Integer> integerArray = newIntegerArrayFrom(1, 1, 2, 3, 4, 5);
* </pre>
*
* </li>
* </ul>
*
* @param <Element>
* type of elements held in the List
* @author Igor Akkerman
*/
public class Array<Element>
extends AbstractEditableIndexList<Element>
implements Cloneable {
/** ArrayList containing the Elements of this Array */
private ArrayList<Element> backedList;
/**
* Creates a new empty Array.
*/
public Array() {
super();
construct();
}
public Array(int size)
throws IllegalArgumentException {
super();
if (size != 0)
construct(0, size - 1);
else
construct();
}
public Array(int minimumIndex, int maximumIndex)
throws IllegalArgumentException {
super();
construct(minimumIndex, maximumIndex);
}
/**
* Creates a new Array containing the specified Elements. That is, the index
* of the first Element of the specified list in this Array is 0. The fixed
* size of this Array is the size of the specified list.
*
* @param elements
* comma separated list of Elements to store or Java array containing
* those Elements
*/
public Array(Element... elements) {
this(0, elements);
}
/**
* Creates a new Array containing the specified Integer Elements. That is,
* the index of the first Element of the specified list in this Array is 0.
* The fixed size of this Array is the size of the specified list.
*
* @param elements
* comma separated list of Integer Elements to store or Java array
* containing those Elements
* @return the new Array of Integers
*/
public static Array<Integer> newIntegerArray(Integer... elements) {
return new Array<Integer>(0, elements);
}
/**
* Creates a new Array containing the specified Elements having a specified
* minimum index. That is, the index of the first Element of the specified
* list in this Array can be specified. The fixed size of this Array is the
* size of the specified list.
*
* @param minimumIndex
* integer specifying the minimum index of this Array
* @param elements
* comma separated list of Elements to store or Java array containing
* those Elements
*/
public Array(int minimumIndex, Element... elements) {
super();
if (elements.length != 0)
construct(minimumIndex, minimumIndex + elements.length - 1);
else
construct();
for (int index = 0; index < elements.length; index ++)
backedList.set(index, elements[index]);
}
/**
* Creates a new Array containing the specified Integer Elements having a
* specified minimum index. That is, the index of the first Element of the
* specified list in this Array can be specified. The fixed size of this
* Array is the size of the specified list.
*
* @param minimumIndex
* integer specifying the minimum index of this Array
* @param elements
* comma separated list of Integer elements to store or Java array
* containing those Elements
* @return the new Array of Integers
*/
public static Array<Integer> newIntegerArrayFrom(int minimumIndex, Integer... elements) {
return new Array<Integer>(minimumIndex, elements);
}
public Array(Collection<Element> collection){
this(0, collection);
}
/**
* Creates a new Array containing the Elements of the specified Java
* Collection. The index of the first Element of the specified Collection in
* this Array is 0. The fixed size of this Array is the size of the
* specified Collection.
*
* @param collection
* Java Collection of which the Elements are copied to this Array
* @throws NullPointerException
* if {@code collection} is {@code null}
*/
public Array(java.util.Collection<Element> collection)
throws NullPointerException {
this(0, collection);
}
public Array(int minIndex, Collection<Element> collection)
throws NullPointerException, IllegalArgumentException {
super();
if (minIndex < 0)
throw new IllegalArgumentException();
int collectionSize = collection.size();
backedList = new ArrayList<Element>(collectionSize);
for (Element collectionElement : collection)
backedList.add(collectionElement);
this.minIndex = minIndex;
this.maxIndex = minIndex + collectionSize - 1;
}
public Array(int minIndex, java.util.Collection<Element> collection)
throws NullPointerException, IllegalArgumentException {
super();
if (minIndex < 0)
throw new IllegalArgumentException();
backedList = new ArrayList<Element>(collection);
this.minIndex = minIndex;
this.maxIndex = minIndex + backedList.size() - 1;
}
/**
* Constructs this Array as empty.
*/
private void construct() {
backedList = new ArrayList<Element>(0);
minIndex = -1;
maxIndex = -2;
}
private void construct(int minIndex, int maxIndex)
throws IllegalArgumentException {
if (minIndex < 0 || minIndex > maxIndex)
throw new IllegalArgumentException();
int size = maxIndex - minIndex + 1;
backedList = new ArrayList<Element>(size);
for (int index = 0; index < size; index ++)
backedList.add(null);
this.minIndex = minIndex;
this.maxIndex = maxIndex;
}
// @see org.jlib.core.collections.list.IndexList#get(int)
@Override
public Element get(int index)
throws ListIndexOutOfBoundsException {
try {
return backedList.get(index - minIndex);
}
catch (IndexOutOfBoundsException exception) {
throw new ListIndexOutOfBoundsException(index);
}
}
// @see org.jlib.core.collections.list.EditableIndexList#set(int, java.lang.Object)
@Override
public Element set(int index, Element element)
throws ListIndexOutOfBoundsException {
try {
Element oldElement = get(index);
backedList.set(index - minIndex, element);
return oldElement;
}
catch (IndexOutOfBoundsException exception) {
throw new ListIndexOutOfBoundsException(index);
}
}
// @see org.jlib.core.collections.AbstractCollection#contains(java.lang.Object)
@Override
// overridden for efficiency
public boolean contains(Object object) {
return backedList.contains(object);
}
// @see org.jlib.core.collections.AbstractCollection#containsAll(org.jlib.core.collections.Collection)
// overridden for efficiency
@Override
public boolean containsAll(java.util.Collection<?> javaCollection) {
return backedList.containsAll(javaCollection);
}
// @see java.lang.Object#clone()
@Override
@SuppressWarnings("unchecked")
public Object clone()
throws CloneNotSupportedException {
Array<Element> clonedArray = (Array<Element>) super.clone();
clonedArray.backedList = (ArrayList<Element>) backedList.clone();
return clonedArray;
}
// @see org.jlib.core.collections.list.IndexList#equals(java.lang.Object)
@Override
public boolean equals(Object otherObject) {
if (!(otherObject instanceof Array<?>))
return false;
Array<?> otherArray = (Array<?>) otherObject;
return minIndex == otherArray.minIndex && maxIndex == otherArray.maxIndex &&
backedList.equals(otherArray.backedList);
}
// @see org.jlib.core.collections.AbstractCollection#hashCode()
@Override
public int hashCode() {
return minIndex + maxIndex + backedList.hashCode();
}
} |
package com.flexibledeveloper.observer;
import org.junit.Test;
public class ObserverTest {
@Test
public void nominalBehavior() {
System.out.println("Creating Subject");
ConcreteSubject subject = new ConcreteSubject();
Data originalData = new Data("Original Value 1","Original Value 2","Original Value 3");
subject.setData(originalData);
System.out.println("Creating Observers");
Observer observer1 = new ConcreteObserver1();
Observer observer2 = new ConcreteObserver2();
Observer observer3 = new ConcreteObserver3();
System.out.println("Registering Observers");
subject.registerObserver(observer1);
subject.registerObserver(observer2);
subject.registerObserver(observer3);
System.out.println("\nNotifying observers");
subject.notifyObservers();
Data newData = new Data("New Value 1","New Value 2","New Value 3");
System.out.println("\nNotifying observers with new data");
subject.notifyObservers(newData);
System.out.println("\nRemoving observer2");
subject.removeObserver(observer2);
System.out.println("\nNotifying remaining observers");
subject.notifyObservers(newData);
}
} |
package com.github.jerdeb.daqvalidator;
import java.io.IOException;
import java.net.URI;
import javax.json.stream.JsonGenerator;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
public class Main {
// Base URI the Grizzly HTTP server will listen on
private static final String SCHEME = "http";
private static final String DOMAIN = (System.getenv("OPENSHIFT_DIY_IP") != null) ? System.getenv("OPENSHIFT_DIY_IP") : "localhost";
private static final String PORT_NUMBER = "8080" ;
private static final String APPLICATION = "daqvalidator";
public static final String BASE_URI = SCHEME+"://"+DOMAIN+":"+PORT_NUMBER+"/"+ APPLICATION + "/";
/**
* Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
* @return Grizzly HTTP server.
*/
public static HttpServer startServer() {
final ResourceConfig rc = new ResourceConfig().packages("com.github.jerdeb.daqvalidator").property(JsonGenerator.PRETTY_PRINTING, true);
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
}
/**
* Main method.
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// Start server and wait for user input to stop
final HttpServer server = startServer();
try {
server.start();
System.out.println(String.format("Jersey app started with WADL available at " + "%sapplication.wadl\n", BASE_URI));
// Wait forever (i.e. until the JVM instance is terminated externally)
Thread.currentThread().join();
} catch (Exception ioe) {
System.out.println("Error running service: " + ioe.toString());
} finally {
if(server != null && server.isStarted()) {
server.shutdownNow();
}
}
}
} |
package com.github.mongobee.utils;
import com.github.mongobee.changeset.ChangeEntry;
import com.github.mongobee.exception.MongobeeChangeSetException;
import com.github.mongobee.test.changelogs.*;
import junit.framework.Assert;
import org.junit.Test;
import java.lang.reflect.Method;
import java.util.List;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
/**
* @author lstolowski
* @since 27/07/2014
*/
public class ChangeServiceTest {
@Test
public void shouldFindChangeLogClasses(){
// given
String scanPackage = MongobeeTestResource.class.getPackage().getName();
ChangeService service = new ChangeService(scanPackage);
// when
List<Class<?>> foundClasses = service.fetchChangeLogs();
// then
assertTrue(foundClasses != null && foundClasses.size() > 0);
}
@Test
public void shouldFindChangeSetMethods() throws MongobeeChangeSetException {
// given
String scanPackage = MongobeeTestResource.class.getPackage().getName();
ChangeService service = new ChangeService(scanPackage);
// when
List<Method> foundMethods = service.fetchChangeSets(MongobeeTestResource.class);
// then
assertTrue(foundMethods != null && foundMethods.size() == 5);
}
@Test
public void shouldFindAnotherChangeSetMethods() throws MongobeeChangeSetException {
// given
String scanPackage = MongobeeTestResource.class.getPackage().getName();
ChangeService service = new ChangeService(scanPackage);
// when
List<Method> foundMethods = service.fetchChangeSets(AnotherMongobeeTestResource.class);
// then
assertTrue(foundMethods != null && foundMethods.size() == 6);
}
@Test
public void shouldFindIsRunAlwaysMethod() throws MongobeeChangeSetException {
// given
String scanPackage = MongobeeTestResource.class.getPackage().getName();
ChangeService service = new ChangeService(scanPackage);
// when
List<Method> foundMethods = service.fetchChangeSets(AnotherMongobeeTestResource.class);
// then
for (Method foundMethod : foundMethods) {
if (foundMethod.getName().equals("testChangeSetWithAlways")){
assertTrue(service.isRunAlwaysChangeSet(foundMethod));
} else {
assertFalse(service.isRunAlwaysChangeSet(foundMethod));
}
}
}
@Test
public void shouldCreateEntry() throws MongobeeChangeSetException {
// given
String scanPackage = MongobeeTestResource.class.getPackage().getName();
ChangeService service = new ChangeService(scanPackage);
List<Method> foundMethods = service.fetchChangeSets(MongobeeTestResource.class);
for (Method foundMethod : foundMethods) {
// when
ChangeEntry entry = service.createChangeEntry(foundMethod);
// then
Assert.assertEquals("testuser", entry.getAuthor());
Assert.assertEquals(MongobeeTestResource.class.getName(), entry.getChangeLogClass());
Assert.assertNotNull(entry.getTimestamp());
Assert.assertNotNull(entry.getChangeId());
Assert.assertNotNull(entry.getChangeSetMethodName());
}
}
@Test(expected = MongobeeChangeSetException.class)
public void shouldFailOnDuplicatedChangeSets() throws MongobeeChangeSetException {
String scanPackage = ChangeLogWithDuplicate.class.getPackage().getName();
ChangeService service = new ChangeService(scanPackage);
service.fetchChangeSets(ChangeLogWithDuplicate.class);
}
} |
package com.github.kratorius.jefs;
import com.github.kratorius.jefs.internal.BitUtils;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nonnull;
public class SPSCQueue<T> implements Queue<T> {
private final T[] buffer;
private final int mask;
private final AtomicLong head = new PaddedAtomicLong(0);
private final AtomicLong tail = new PaddedAtomicLong(0);
static class PaddedAtomicLong extends AtomicLong {
public volatile long p0 = 0L, p1 = 1L, p2 = 2L, p3 = 3L;
public volatile long p4 = 4L, p5 = 5L, p6 = 6L, p7 = 7L;
PaddedAtomicLong(long initialValue) {
super(initialValue);
}
}
/**
* Creates a new single-producer/single-consumer queue.
*
* @param capacity the suggested capacity of the queue; the actual queue size will
* be the next (positive) power of two. To get the actual capacity
* of the queue, use {@link #actualCapacity()}
*/
@SuppressWarnings("unchecked")
public SPSCQueue(final int capacity) {
int actualSize = BitUtils.roundToNextPowerOfTwo(capacity);
buffer = (T[]) new Object[actualSize];
// use a mask to access actual buffer items, this works because
// the buffer is always a power of 2 and using idx & mask is equivalent
// of length % idx but way more efficient, i.e: i % 2^k == i & (2^k - 1)
mask = actualSize - 1;
}
/**
* Returns the actual capacity of the queue.
*
* Because we round up the queue bound size to the next power of two,
* the actual capacity of the queue might be larger than what exactly
* specified.
*
* @return the effective capacity of the queue
*/
public int actualCapacity() {
return buffer.length;
}
@Override
public int size() {
return (int) (tail.get() - head.get());
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean contains(Object o) {
if (o == null) {
return false;
}
final long end = tail.get();
for (long i = head.get(); i < end; i++) {
if (o.equals(buffer[(int)i & mask])) {
return true;
}
}
return false;
}
@Override
public boolean add(T t) {
if (!offer(t)) {
throw new IllegalStateException("full queue");
}
return true;
}
@Override
public boolean containsAll(@Nonnull Collection<?> objects) {
for (Object o : objects) {
if (!contains(o)) {
return false;
}
}
return true;
}
@Override
public boolean addAll(@Nonnull Collection<? extends T> items) {
for (T item : items) {
add(item);
}
return true;
}
public void clear() {
final long head = this.head.getAndSet(0);
final long tail = this.tail.getAndSet(0);
// remove any reference to old objects so they can be garbage collected
for (long i = head; i <= tail; i++) {
buffer[(int)i & mask] = null;
}
}
@Override
public boolean offer(final T t) {
if (t == null) {
throw new IllegalStateException("queue doesn't support null items");
}
final long currentTail = tail.get();
final long wrapPoint = currentTail - buffer.length;
if (head.get() <= wrapPoint) {
return false;
}
// we can use lazySet because there's only a single producer
buffer[(int)currentTail & mask] = t;
tail.lazySet(currentTail + 1);
return true;
}
@Override
public T remove() {
final T t = poll();
if (t == null) {
throw new NoSuchElementException("empty queue");
}
return t;
}
@Override
public T poll() throws NoSuchElementException {
final long currentHead = head.get();
if (currentHead >= tail.get()) {
// empty queue
return null;
}
final int index = (int)currentHead & mask;
final T t = buffer[index];
buffer[index] = null;
head.lazySet(currentHead + 1);
return t;
}
@Override
public T element() {
final T t = peek();
if (t == null) {
throw new NoSuchElementException("empty queue");
}
return t;
}
@Override
public T peek() {
return buffer[(int)head.get() & mask];
}
@Override @Nonnull
public Iterator<T> iterator() {
throw new UnsupportedOperationException();
}
@Override @Nonnull
public Object[] toArray() {
throw new UnsupportedOperationException();
}
@Override @Nonnull
public <A> A[] toArray(@Nonnull A[] ts) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(@Nonnull Collection<?> objects) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(@Nonnull Collection<?> objects) {
throw new UnsupportedOperationException();
}
} |
package org.jtrfp.trcl.obj;
import java.awt.Dimension;
import java.util.List;
import javax.media.opengl.GL3;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.AnimatedTexture;
import org.jtrfp.trcl.RenderMode;
import org.jtrfp.trcl.Sequencer;
import org.jtrfp.trcl.Triangle;
import org.jtrfp.trcl.beh.BehaviorNotFoundException;
import org.jtrfp.trcl.beh.DestroysEverythingBehavior;
import org.jtrfp.trcl.core.ResourceManager;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.core.Texture;
import org.jtrfp.trcl.core.TextureDescription;
import org.jtrfp.trcl.file.ModelingType;
import org.jtrfp.trcl.file.Weapon;
import org.jtrfp.trcl.flow.GameVersion;
import org.jtrfp.trcl.gpu.Model;
import org.jtrfp.trcl.img.vq.ColorPaletteVectorList;
import org.jtrfp.trcl.math.Vect3D;
import org.jtrfp.trcl.obj.Explosion.ExplosionType;
import org.jtrfp.trcl.snd.SoundSystem;
import org.jtrfp.trcl.snd.SoundTexture;
public class ProjectileFactory {
private int projectileIndex=0;
private final TR tr;
private final Projectile [] projectiles = new Projectile[20];
private final double projectileSpeed;
private final Weapon weapon;
private final SoundTexture soundTexture;
public ProjectileFactory(TR tr, Weapon weapon, ExplosionType explosionType){
this.tr=tr;
this.weapon=weapon;
this.projectileSpeed=weapon.getSpeed()/TR.crossPlatformScalar;
Model modelToUse;
TextureDescription t;
Triangle [] tris;
final int damageOnImpact=weapon.getDamage();
try{
modelToUse = new Model(false,tr);
final ModelingType modelingType = weapon.getModelingType();
if(modelingType instanceof ModelingType.FlatModelingType){
ModelingType.FlatModelingType mt = (ModelingType.FlatModelingType)modelingType;
Dimension dims = mt.getSegmentSize();
final int laserplaneLength = (int)(dims.getWidth()/TR.crossPlatformScalar);
final int laserplaneWidth = (int)(dims.getHeight()/TR.crossPlatformScalar);
t = tr.getResourceManager().getRAWAsTexture(
tr.config.getGameVersion()!=GameVersion.TV?mt.getF3RawFileName():mt.getTvRawFileName(),
tr.getDarkIsClearPaletteVL(), null,
false);
final double Y_SLANT=1024;
tris =(Triangle.quad2Triangles(new double[]{-laserplaneLength/2.,laserplaneLength/2.,laserplaneLength/2.,-laserplaneLength/2.},
new double[]{0,0,Y_SLANT,Y_SLANT}, new double[]{-laserplaneWidth/2.,-laserplaneWidth/2.,laserplaneWidth/2.,laserplaneWidth/2.},
new double[]{1,0,0,1}, new double[]{0,0,1,1}, t, RenderMode.STATIC,Vector3D.ZERO,"ProjectileFactory:"+weapon.toString()));//UVtr
tris[0].setAlphaBlended(true);
tris[1].setAlphaBlended(true);
modelToUse.addTriangles(tris);
//modelToUse.finalizeModel();
//modelToUse = tr.getResourceManager().getBINModel("LASER3.BIN", tr.getGlobalPaletteVL(), null, null);
for(int i=0; i<projectiles.length; i++){
projectiles[i]=new ProjectileObject3D(tr,modelToUse, weapon, explosionType);}
}//end if(isLaser)
else if(modelingType instanceof ModelingType.BillboardModelingType){
final ModelingType.BillboardModelingType mt = (ModelingType.BillboardModelingType)modelingType;
final Texture [] frames = new Texture[mt.getRawFileNames().length];
final String [] fileNames = mt.getRawFileNames();
final ResourceManager mgr = tr.getResourceManager();
final ColorPaletteVectorList pal = tr.getGlobalPaletteVL();
GL3 gl = tr.gpu.get().getGl();
for(int i=0; i<frames.length;i++){
frames[i]=(Texture)mgr.getRAWAsTexture(fileNames[i], pal, null, false);
}//end for(frames)
TextureDescription tex = new AnimatedTexture(new Sequencer(mt.getTimeInMillisPerFrame(),frames.length,false), frames);
for(int i=0; i<projectiles.length; i++){
projectiles[i]=new ProjectileBillboard(tr,weapon,tex,ExplosionType.Billow);}
}//end (billboard)
else if(modelingType instanceof ModelingType.BINModelingType){
final ModelingType.BINModelingType mt = (ModelingType.BINModelingType)modelingType;
modelToUse = tr.getResourceManager().getBINModel(mt.getBinFileName(), tr.getGlobalPaletteVL(),null, tr.gpu.get().getGl());
for(int i=0; i<projectiles.length; i++){
projectiles[i]=new ProjectileObject3D(tr,modelToUse, weapon, explosionType);
}
}//end BIN Modeling Type
else{throw new RuntimeException("Unhandled ModelingType: "+modelingType.getClass().getName());}
}//end try
catch(Exception e){e.printStackTrace();}
//CLAUSE: FFF needs destroysEvertyhing behavior
if(weapon==Weapon.DAM){
for(int i=0; i<projectiles.length; i++){
((WorldObject)projectiles[i]).addBehavior(new DestroysEverythingBehavior());
}
}//end if(DAM)
//Sound
String soundFile=null;
switch(weapon){
//PEW!!!
case PAC:
{
soundFile="LASER2.WAV";
break;
}
case ION:
{
soundFile="LASER3.WAV";
break;
}
case RTL:
{
soundFile="LASER4.WAV";
break;
}
case DAM:
case redLaser:
case blueLaser:
case greenLaser:
case purpleLaser:
case purpleRing:
{
soundFile="LASER5.WAV";
break;
}
//Missile
case enemyMissile:
case SWT:
case MAM:
case SAD:
{
soundFile="MISSILE.WAV";
break;
}
//SILENT
case purpleBall:
case goldBall:
case fireBall:
case blueFireBall:
case bullet:
case bossW8:
case bossW7:
case bossW6:
case atomWeapon:
default:
break;
}//end case()
soundTexture = soundFile!=null?tr.getResourceManager().soundTextures.get(soundFile):null;
}//end constructor(...)
public Projectile fire(double[] newPosition, Vector3D heading, WorldObject objectOfOrigin) {
assert !Vect3D.isAnyNaN(newPosition);
assert heading.getNorm()!=0 && heading.getNorm()!=Double.NaN;
final Projectile result = projectiles[projectileIndex];
result.destroy();
final Vector3D newVelocity;
if(weapon.isSumWithProjectorVel()){
Vector3D originVelocity = Vector3D.ZERO;
try{final Velocible vel = objectOfOrigin.probeForBehavior(Velocible.class);
originVelocity = vel.getVelocity();
}catch(BehaviorNotFoundException e){}
newVelocity = heading.scalarMultiply(projectileSpeed).add(originVelocity);
}else// !sumWithProjector
newVelocity = heading.scalarMultiply(projectileSpeed);
result.reset(newPosition, newVelocity, objectOfOrigin);
((WorldObject)result).setTop(objectOfOrigin.getTop());
tr.getDefaultGrid().add((WorldObject)result);
if(soundTexture!=null)
tr.soundSystem.get().enqueuePlaybackEvent(
tr.soundSystem
.get()
.getPlaybackFactory()
.create(soundTexture,
(WorldObject)result,
tr.mainRenderer.get().getCamera(),
(objectOfOrigin instanceof Player?.6:1)*SoundSystem.DEFAULT_SFX_VOLUME));//TODO: Use configuration volume instead
projectileIndex++;
projectileIndex%=projectiles.length;
return result;
}//end fire(...)
public Projectile[] getProjectiles() {
return projectiles;
}
public Weapon getWeapon() {
return weapon;
}
}//end ProjectileFactory |
package com.salesforce.phoenix.schema;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import com.salesforce.phoenix.util.TestUtil;
public class PDataTypeTest {
@Test
public void testFloatToLongComparison() {
// Basic tests
assertTrue(PDataType.FLOAT.compareTo(PDataType.FLOAT.toBytes(1e100), 0, PDataType.FLOAT.getByteSize(), null,
PDataType.LONG.toBytes(1), 0, PDataType.LONG.getByteSize(), null, PDataType.LONG) > 0);
assertTrue(PDataType.FLOAT.compareTo(PDataType.FLOAT.toBytes(0.001), 0, PDataType.FLOAT.getByteSize(), null,
PDataType.LONG.toBytes(1), 0, PDataType.LONG.getByteSize(), null, PDataType.LONG) < 0);
// Edge tests
assertTrue(PDataType.FLOAT.compareTo(PDataType.FLOAT.toBytes(Integer.MAX_VALUE), 0,
PDataType.FLOAT.getByteSize(), null, PDataType.LONG.toBytes(Integer.MAX_VALUE - 1), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) > 0);
assertTrue(PDataType.FLOAT.compareTo(PDataType.FLOAT.toBytes(Integer.MIN_VALUE), 0,
PDataType.FLOAT.getByteSize(), null, PDataType.LONG.toBytes(Integer.MIN_VALUE + 1), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) < 0);
assertTrue(PDataType.FLOAT.compareTo(PDataType.FLOAT.toBytes(Integer.MIN_VALUE), 0,
PDataType.FLOAT.getByteSize(), null, PDataType.LONG.toBytes(Integer.MIN_VALUE), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) == 0);
assertTrue(PDataType.FLOAT.compareTo(PDataType.FLOAT.toBytes(Integer.MAX_VALUE + 1.0F), 0,
PDataType.FLOAT.getByteSize(), null, PDataType.LONG.toBytes(Integer.MAX_VALUE), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) > 0); // Passes due to rounding
assertTrue(PDataType.FLOAT.compareTo(PDataType.FLOAT.toBytes(Integer.MAX_VALUE + 129.0F), 0,
PDataType.FLOAT.getByteSize(), null, PDataType.LONG.toBytes(Integer.MAX_VALUE), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) > 0);
assertTrue(PDataType.FLOAT.compareTo(PDataType.FLOAT.toBytes(Integer.MIN_VALUE - 128.0F), 0,
PDataType.FLOAT.getByteSize(), null, PDataType.LONG.toBytes(Integer.MIN_VALUE), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) == 0);
assertTrue(PDataType.FLOAT.compareTo(PDataType.FLOAT.toBytes(Integer.MIN_VALUE - 129.0F), 0,
PDataType.FLOAT.getByteSize(), null, PDataType.LONG.toBytes(Integer.MIN_VALUE), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) < 0);
float f1 = 9111111111111111.0F;
float f2 = 9111111111111112.0F;
assertTrue(f1 == f2);
long la = 9111111111111111L;
assertTrue(f1 > Integer.MAX_VALUE);
assertTrue(la == f1);
assertTrue(la == f2);
assertTrue(PDataType.FLOAT.compareTo(PDataType.FLOAT.toBytes(f1), 0, PDataType.FLOAT.getByteSize(), null,
PDataType.LONG.toBytes(la), 0, PDataType.LONG.getByteSize(), null, PDataType.LONG) == 0);
assertTrue(PDataType.FLOAT.compareTo(PDataType.FLOAT.toBytes(f2), 0, PDataType.FLOAT.getByteSize(), null,
PDataType.LONG.toBytes(la), 0, PDataType.LONG.getByteSize(), null, PDataType.LONG) == 0);
// Same as above, but reversing LHS and RHS
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(1), 0, PDataType.LONG.getByteSize(), null,
PDataType.FLOAT.toBytes(1e100), 0, PDataType.FLOAT.getByteSize(), null, PDataType.FLOAT) < 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(1), 0, PDataType.LONG.getByteSize(), null,
PDataType.FLOAT.toBytes(0.001), 0, PDataType.FLOAT.getByteSize(), null, PDataType.FLOAT) > 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Integer.MAX_VALUE - 1), 0,
PDataType.LONG.getByteSize(), null, PDataType.FLOAT.toBytes(Integer.MAX_VALUE), 0,
PDataType.FLOAT.getByteSize(), null, PDataType.FLOAT) < 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Integer.MIN_VALUE + 1), 0,
PDataType.LONG.getByteSize(), null, PDataType.FLOAT.toBytes(Integer.MIN_VALUE), 0,
PDataType.FLOAT.getByteSize(), null, PDataType.FLOAT) > 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Integer.MIN_VALUE), 0, PDataType.LONG.getByteSize(),
null, PDataType.FLOAT.toBytes(Integer.MIN_VALUE), 0, PDataType.FLOAT.getByteSize(), null,
PDataType.FLOAT) == 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Integer.MAX_VALUE), 0, PDataType.LONG.getByteSize(),
null, PDataType.FLOAT.toBytes(Integer.MAX_VALUE + 1.0F), 0, PDataType.FLOAT.getByteSize(), null,
PDataType.FLOAT) < 0); // Passes due to rounding
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Integer.MAX_VALUE), 0, PDataType.LONG.getByteSize(),
null, PDataType.FLOAT.toBytes(Integer.MAX_VALUE + 129.0F), 0, PDataType.FLOAT.getByteSize(), null,
PDataType.FLOAT) < 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Integer.MIN_VALUE), 0, PDataType.LONG.getByteSize(),
null, PDataType.FLOAT.toBytes(Integer.MIN_VALUE - 128.0F), 0, PDataType.FLOAT.getByteSize(), null,
PDataType.FLOAT) == 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Integer.MIN_VALUE), 0, PDataType.LONG.getByteSize(),
null, PDataType.FLOAT.toBytes(Integer.MIN_VALUE - 129.0F), 0, PDataType.FLOAT.getByteSize(), null,
PDataType.FLOAT) > 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(la), 0, PDataType.LONG.getByteSize(), null,
PDataType.FLOAT.toBytes(f1), 0, PDataType.FLOAT.getByteSize(), null, PDataType.FLOAT) == 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(la), 0, PDataType.LONG.getByteSize(), null,
PDataType.FLOAT.toBytes(f2), 0, PDataType.FLOAT.getByteSize(), null, PDataType.FLOAT) == 0);
}
@Test
public void testDoubleToDecimalComparison() {
// Basic tests
assertTrue(PDataType.DOUBLE.compareTo(PDataType.DOUBLE.toBytes(1.23), 0, PDataType.DOUBLE.getByteSize(), null,
PDataType.DECIMAL.toBytes(BigDecimal.valueOf(1.24)), 0, PDataType.DECIMAL.getByteSize(), null, PDataType.DECIMAL) < 0);
}
@Test
public void testDoubleToLongComparison() {
// Basic tests
assertTrue(PDataType.DOUBLE.compareTo(PDataType.DOUBLE.toBytes(-1e100), 0, PDataType.DOUBLE.getByteSize(), null,
PDataType.LONG.toBytes(1), 0, PDataType.LONG.getByteSize(), null, PDataType.LONG) < 0);
assertTrue(PDataType.DOUBLE.compareTo(PDataType.DOUBLE.toBytes(0.001), 0, PDataType.DOUBLE.getByteSize(), null,
PDataType.LONG.toBytes(1), 0, PDataType.LONG.getByteSize(), null, PDataType.LONG) < 0);
assertTrue(PDataType.DOUBLE.compareTo(PDataType.DOUBLE.toBytes(Long.MAX_VALUE), 0,
PDataType.DOUBLE.getByteSize(), null, PDataType.LONG.toBytes(Long.MAX_VALUE - 1), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) > 0);
assertTrue(PDataType.DOUBLE.compareTo(PDataType.DOUBLE.toBytes(Long.MIN_VALUE), 0,
PDataType.DOUBLE.getByteSize(), null, PDataType.LONG.toBytes(Long.MIN_VALUE + 1), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) < 0);
assertTrue(PDataType.DOUBLE.compareTo(PDataType.DOUBLE.toBytes(Long.MIN_VALUE), 0,
PDataType.DOUBLE.getByteSize(), null, PDataType.LONG.toBytes(Long.MIN_VALUE), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) == 0);
assertTrue(PDataType.DOUBLE.compareTo(PDataType.DOUBLE.toBytes(Long.MAX_VALUE + 1024.0), 0,
PDataType.DOUBLE.getByteSize(), null, PDataType.LONG.toBytes(Long.MAX_VALUE), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) == 0);
assertTrue(PDataType.DOUBLE.compareTo(PDataType.DOUBLE.toBytes(Long.MAX_VALUE + 1025.0), 0,
PDataType.DOUBLE.getByteSize(), null, PDataType.LONG.toBytes(Long.MAX_VALUE), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) > 0);
assertTrue(PDataType.DOUBLE.compareTo(PDataType.DOUBLE.toBytes(Long.MIN_VALUE - 1024.0), 0,
PDataType.DOUBLE.getByteSize(), null, PDataType.LONG.toBytes(Long.MIN_VALUE), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) == 0);
assertTrue(PDataType.DOUBLE.compareTo(PDataType.DOUBLE.toBytes(Long.MIN_VALUE - 1025.0), 0,
PDataType.DOUBLE.getByteSize(), null, PDataType.LONG.toBytes(Long.MIN_VALUE), 0,
PDataType.LONG.getByteSize(), null, PDataType.LONG) < 0);
// Same as above, but reversing LHS and RHS
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(1), 0, PDataType.LONG.getByteSize(), null,
PDataType.DOUBLE.toBytes(-1e100), 0, PDataType.DOUBLE.getByteSize(), null, PDataType.DOUBLE) > 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(1), 0, PDataType.LONG.getByteSize(), null,
PDataType.DOUBLE.toBytes(0.001), 0, PDataType.DOUBLE.getByteSize(), null, PDataType.DOUBLE) > 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Long.MAX_VALUE - 1), 0,
PDataType.LONG.getByteSize(), null, PDataType.DOUBLE.toBytes(Long.MAX_VALUE), 0,
PDataType.DOUBLE.getByteSize(), null, PDataType.DOUBLE) < 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Long.MIN_VALUE + 1), 0,
PDataType.LONG.getByteSize(), null, PDataType.DOUBLE.toBytes(Long.MIN_VALUE), 0,
PDataType.DOUBLE.getByteSize(), null, PDataType.DOUBLE) > 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Long.MIN_VALUE), 0, PDataType.LONG.getByteSize(),
null, PDataType.DOUBLE.toBytes(Long.MIN_VALUE), 0, PDataType.DOUBLE.getByteSize(), null,
PDataType.DOUBLE) == 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Long.MAX_VALUE), 0, PDataType.LONG.getByteSize(),
null, PDataType.DOUBLE.toBytes(Long.MAX_VALUE + 1024.0), 0, PDataType.DOUBLE.getByteSize(), null,
PDataType.DOUBLE) == 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Long.MAX_VALUE), 0, PDataType.LONG.getByteSize(),
null, PDataType.DOUBLE.toBytes(Long.MAX_VALUE + 1025.0), 0, PDataType.DOUBLE.getByteSize(), null,
PDataType.DOUBLE) < 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Long.MIN_VALUE), 0, PDataType.LONG.getByteSize(),
null, PDataType.DOUBLE.toBytes(Long.MIN_VALUE - 1024.0), 0, PDataType.DOUBLE.getByteSize(), null,
PDataType.DOUBLE) == 0);
assertTrue(PDataType.LONG.compareTo(PDataType.LONG.toBytes(Long.MIN_VALUE), 0, PDataType.LONG.getByteSize(),
null, PDataType.DOUBLE.toBytes(Long.MIN_VALUE - 1025.0), 0, PDataType.DOUBLE.getByteSize(), null,
PDataType.DOUBLE) > 0);
long i = 10;
long maxl = (1L << 62);
try {
for (; i < 100; i++) {
double d = Math.pow(2, i);
if ((long)d > maxl) {
assertTrue(i > 62);
continue;
}
long l = (1L << i) - 1;
assertTrue(l + 1L == (long)d);
assertTrue(l < (long)d);
}
} catch (AssertionError t) {
throw t;
}
double d = 0.0;
try {
while (d <= 1024) {
double d1 = Long.MAX_VALUE;
double d2 = Long.MAX_VALUE + d;
assertTrue(d2 == d1);
d++;
}
} catch (AssertionError t) {
throw t;
}
d = 0.0;
try {
while (d >= -1024) {
double d1 = Long.MIN_VALUE;
double d2 = Long.MIN_VALUE + d;
assertTrue(d2 == d1);
d
}
} catch (AssertionError t) {
throw t;
}
double d1 = Long.MAX_VALUE;
double d2 = Long.MAX_VALUE + 1024.0;
double d3 = Long.MAX_VALUE + 1025.0;
assertTrue(d1 == d2);
assertTrue(d3 > d1);
long l1 = Long.MAX_VALUE - 1;
assertTrue((long)d1 > l1);
}
@Test
public void testLong() {
Long la = 4L;
byte[] b = PDataType.LONG.toBytes(la);
Long lb = (Long)PDataType.LONG.toObject(b);
assertEquals(la,lb);
Long na = 1L;
Long nb = -1L;
byte[] ba = PDataType.LONG.toBytes(na);
byte[] bb = PDataType.LONG.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
Integer value = 100;
Object obj = PDataType.LONG.toObject(value, PDataType.INTEGER);
assertTrue(obj instanceof Long);
assertEquals(100, ((Long)obj).longValue());
Long longValue = 100l;
Object longObj = PDataType.LONG.toObject(longValue, PDataType.LONG);
assertTrue(longObj instanceof Long);
assertEquals(100, ((Long)longObj).longValue());
assertEquals(0, PDataType.LONG.compareTo(Long.MAX_VALUE, Float.valueOf(Long.MAX_VALUE), PDataType.FLOAT));
assertEquals(0, PDataType.LONG.compareTo(Long.MAX_VALUE, Double.valueOf(Long.MAX_VALUE), PDataType.DOUBLE));
assertEquals(-1, PDataType.LONG.compareTo(99, Float.valueOf(100), PDataType.FLOAT));
assertEquals(1, PDataType.LONG.compareTo(101, Float.valueOf(100), PDataType.FLOAT));
Double d = -2.0;
Object lo = PDataType.LONG.toObject(d, PDataType.DOUBLE);
assertEquals(-2L, ((Long)lo).longValue());
byte[] bytes = PDataType.DOUBLE.toBytes(d);
lo = PDataType.LONG.toObject(bytes,0, bytes.length, PDataType.DOUBLE);
assertEquals(-2L, ((Long)lo).longValue());
Float f = -2.0f;
lo = PDataType.LONG.toObject(f, PDataType.FLOAT);
assertEquals(-2L, ((Long)lo).longValue());
bytes = PDataType.FLOAT.toBytes(f);
lo = PDataType.LONG.toObject(bytes,0, bytes.length, PDataType.FLOAT);
assertEquals(-2L, ((Long)lo).longValue());
// Checks for unsignedlong
d = 2.0;
lo = PDataType.UNSIGNED_LONG.toObject(d, PDataType.DOUBLE);
assertEquals(2L, ((Long)lo).longValue());
bytes = PDataType.DOUBLE.toBytes(d);
lo = PDataType.UNSIGNED_LONG.toObject(bytes,0, bytes.length, PDataType.DOUBLE);
assertEquals(2L, ((Long)lo).longValue());
f = 2.0f;
lo = PDataType.UNSIGNED_LONG.toObject(f, PDataType.FLOAT);
assertEquals(2L, ((Long)lo).longValue());
bytes = PDataType.FLOAT.toBytes(f);
lo = PDataType.UNSIGNED_LONG.toObject(bytes,0, bytes.length, PDataType.FLOAT);
assertEquals(2L, ((Long)lo).longValue());
}
@Test
public void testInt() {
Integer na = 4;
byte[] b = PDataType.INTEGER.toBytes(na);
Integer nb = (Integer)PDataType.INTEGER.toObject(b);
assertEquals(na,nb);
na = 1;
nb = -1;
byte[] ba = PDataType.INTEGER.toBytes(na);
byte[] bb = PDataType.INTEGER.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = -1;
nb = -3;
ba = PDataType.INTEGER.toBytes(na);
bb = PDataType.INTEGER.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = -3;
nb = -100000000;
ba = PDataType.INTEGER.toBytes(na);
bb = PDataType.INTEGER.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
Long value = 100l;
Object obj = PDataType.INTEGER.toObject(value, PDataType.LONG);
assertTrue(obj instanceof Integer);
assertEquals(100, ((Integer)obj).intValue());
Float unsignedFloatValue = 100f;
Object unsignedFloatObj = PDataType.INTEGER.toObject(unsignedFloatValue, PDataType.UNSIGNED_FLOAT);
assertTrue(unsignedFloatObj instanceof Integer);
assertEquals(100, ((Integer)unsignedFloatObj).intValue());
Double unsignedDoubleValue = 100d;
Object unsignedDoubleObj = PDataType.INTEGER.toObject(unsignedDoubleValue, PDataType.UNSIGNED_DOUBLE);
assertTrue(unsignedDoubleObj instanceof Integer);
assertEquals(100, ((Integer)unsignedDoubleObj).intValue());
Float floatValue = 100f;
Object floatObj = PDataType.INTEGER.toObject(floatValue, PDataType.FLOAT);
assertTrue(floatObj instanceof Integer);
assertEquals(100, ((Integer)floatObj).intValue());
Double doubleValue = 100d;
Object doubleObj = PDataType.INTEGER.toObject(doubleValue, PDataType.DOUBLE);
assertTrue(doubleObj instanceof Integer);
assertEquals(100, ((Integer)doubleObj).intValue());
Short shortValue = 100;
Object shortObj = PDataType.INTEGER.toObject(shortValue, PDataType.SMALLINT);
assertTrue(shortObj instanceof Integer);
assertEquals(100, ((Integer)shortObj).intValue());
}
@Test
public void testSmallInt() {
Short na = 4;
byte[] b = PDataType.SMALLINT.toBytes(na);
Short nb = (Short)PDataType.SMALLINT.toObject(b);
assertEquals(na,nb);
na = 4;
b = PDataType.SMALLINT.toBytes(na, ColumnModifier.SORT_DESC);
ImmutableBytesWritable ptr = new ImmutableBytesWritable();
ptr.set(b);
nb = PDataType.SMALLINT.getCodec().decodeShort(ptr, ColumnModifier.SORT_DESC);
assertEquals(na,nb);
na = 1;
nb = -1;
byte[] ba = PDataType.SMALLINT.toBytes(na);
byte[] bb = PDataType.SMALLINT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = -1;
nb = -3;
ba = PDataType.SMALLINT.toBytes(na);
bb = PDataType.SMALLINT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = -3;
nb = -10000;
ba = PDataType.SMALLINT.toBytes(na);
bb = PDataType.SMALLINT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
Integer value = 100;
Object obj = PDataType.SMALLINT.toObject(value, PDataType.INTEGER);
assertTrue(obj instanceof Short);
assertEquals(100, ((Short)obj).shortValue());
Float unsignedFloatValue = 100f;
Object unsignedFloatObj = PDataType.SMALLINT.toObject(unsignedFloatValue, PDataType.UNSIGNED_FLOAT);
assertTrue(unsignedFloatObj instanceof Short);
assertEquals(100, ((Short)unsignedFloatObj).shortValue());
Double unsignedDoubleValue = 100d;
Object unsignedDoubleObj = PDataType.SMALLINT.toObject(unsignedDoubleValue, PDataType.UNSIGNED_DOUBLE);
assertTrue(unsignedDoubleObj instanceof Short);
assertEquals(100, ((Short)unsignedDoubleObj).shortValue());
Float floatValue = 100f;
Object floatObj = PDataType.SMALLINT.toObject(floatValue, PDataType.FLOAT);
assertTrue(floatObj instanceof Short);
assertEquals(100, ((Short)floatObj).shortValue());
Double doubleValue = 100d;
Object doubleObj = PDataType.SMALLINT.toObject(doubleValue, PDataType.DOUBLE);
assertTrue(doubleObj instanceof Short);
assertEquals(100, ((Short)doubleObj).shortValue());
}
@Test
public void testTinyInt() {
Byte na = 4;
byte[] b = PDataType.TINYINT.toBytes(na);
Byte nb = (Byte)PDataType.TINYINT.toObject(b);
assertEquals(na,nb);
na = 1;
nb = -1;
byte[] ba = PDataType.TINYINT.toBytes(na);
byte[] bb = PDataType.TINYINT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = -1;
nb = -3;
ba = PDataType.TINYINT.toBytes(na);
bb = PDataType.TINYINT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = -3;
nb = -100;
ba = PDataType.TINYINT.toBytes(na);
bb = PDataType.TINYINT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
Integer value = 100;
Object obj = PDataType.TINYINT.toObject(value, PDataType.INTEGER);
assertTrue(obj instanceof Byte);
assertEquals(100, ((Byte)obj).byteValue());
Float floatValue = 100f;
Object floatObj = PDataType.TINYINT.toObject(floatValue, PDataType.FLOAT);
assertTrue(floatObj instanceof Byte);
assertEquals(100, ((Byte)floatObj).byteValue());
Float unsignedFloatValue = 100f;
Object unsignedFloatObj = PDataType.TINYINT.toObject(unsignedFloatValue, PDataType.UNSIGNED_FLOAT);
assertTrue(unsignedFloatObj instanceof Byte);
assertEquals(100, ((Byte)unsignedFloatObj).byteValue());
Double unsignedDoubleValue = 100d;
Object unsignedDoubleObj = PDataType.TINYINT.toObject(unsignedDoubleValue, PDataType.UNSIGNED_DOUBLE);
assertTrue(unsignedDoubleObj instanceof Byte);
assertEquals(100, ((Byte)unsignedDoubleObj).byteValue());
Double doubleValue = 100d;
Object doubleObj = PDataType.TINYINT.toObject(doubleValue, PDataType.DOUBLE);
assertTrue(doubleObj instanceof Byte);
assertEquals(100, ((Byte)doubleObj).byteValue());
}
@Test
public void testUnsignedSmallInt() {
Short na = 4;
byte[] b = PDataType.UNSIGNED_SMALLINT.toBytes(na);
Short nb = (Short)PDataType.UNSIGNED_SMALLINT.toObject(b);
assertEquals(na,nb);
na = 10;
nb = 8;
byte[] ba = PDataType.UNSIGNED_SMALLINT.toBytes(na);
byte[] bb = PDataType.UNSIGNED_SMALLINT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
Integer value = 100;
Object obj = PDataType.UNSIGNED_SMALLINT.toObject(value, PDataType.INTEGER);
assertTrue(obj instanceof Short);
assertEquals(100, ((Short)obj).shortValue());
Float floatValue = 100f;
Object floatObj = PDataType.UNSIGNED_SMALLINT.toObject(floatValue, PDataType.FLOAT);
assertTrue(floatObj instanceof Short);
assertEquals(100, ((Short)floatObj).shortValue());
Float unsignedFloatValue = 100f;
Object unsignedFloatObj = PDataType.UNSIGNED_SMALLINT.toObject(unsignedFloatValue, PDataType.UNSIGNED_FLOAT);
assertTrue(unsignedFloatObj instanceof Short);
assertEquals(100, ((Short)unsignedFloatObj).shortValue());
Double unsignedDoubleValue = 100d;
Object unsignedDoubleObj = PDataType.UNSIGNED_SMALLINT.toObject(unsignedDoubleValue, PDataType.UNSIGNED_DOUBLE);
assertTrue(unsignedDoubleObj instanceof Short);
assertEquals(100, ((Short)unsignedDoubleObj).shortValue());
Double doubleValue = 100d;
Object doubleObj = PDataType.UNSIGNED_SMALLINT.toObject(doubleValue, PDataType.DOUBLE);
assertTrue(doubleObj instanceof Short);
assertEquals(100, ((Short)doubleObj).shortValue());
}
@Test
public void testUnsignedTinyInt() {
Byte na = 4;
byte[] b = PDataType.UNSIGNED_TINYINT.toBytes(na);
Byte nb = (Byte)PDataType.UNSIGNED_TINYINT.toObject(b);
assertEquals(na,nb);
na = 10;
nb = 8;
byte[] ba = PDataType.UNSIGNED_TINYINT.toBytes(na);
byte[] bb = PDataType.UNSIGNED_TINYINT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
Integer value = 100;
Object obj = PDataType.UNSIGNED_TINYINT.toObject(value, PDataType.INTEGER);
assertTrue(obj instanceof Byte);
assertEquals(100, ((Byte)obj).byteValue());
Float floatValue = 100f;
Object floatObj = PDataType.UNSIGNED_TINYINT.toObject(floatValue, PDataType.FLOAT);
assertTrue(floatObj instanceof Byte);
assertEquals(100, ((Byte)floatObj).byteValue());
Float unsignedFloatValue = 100f;
Object unsignedFloatObj = PDataType.UNSIGNED_TINYINT.toObject(unsignedFloatValue, PDataType.UNSIGNED_FLOAT);
assertTrue(unsignedFloatObj instanceof Byte);
assertEquals(100, ((Byte)unsignedFloatObj).byteValue());
Double unsignedDoubleValue = 100d;
Object unsignedDoubleObj = PDataType.UNSIGNED_TINYINT.toObject(unsignedDoubleValue, PDataType.UNSIGNED_DOUBLE);
assertTrue(unsignedDoubleObj instanceof Byte);
assertEquals(100, ((Byte)unsignedDoubleObj).byteValue());
Double doubleValue = 100d;
Object doubleObj = PDataType.UNSIGNED_TINYINT.toObject(doubleValue, PDataType.DOUBLE);
assertTrue(doubleObj instanceof Byte);
assertEquals(100, ((Byte)doubleObj).byteValue());
}
@Test
public void testUnsignedFloat() {
Float na = 0.005f;
byte[] b = PDataType.UNSIGNED_FLOAT.toBytes(na);
Float nb = (Float)PDataType.UNSIGNED_FLOAT.toObject(b);
assertEquals(na,nb);
na = 10.0f;
b = PDataType.UNSIGNED_FLOAT.toBytes(na, ColumnModifier.SORT_DESC);
ImmutableBytesWritable ptr = new ImmutableBytesWritable();
ptr.set(b);
nb = PDataType.UNSIGNED_FLOAT.getCodec().decodeFloat(ptr, ColumnModifier.SORT_DESC);
assertEquals(na,nb);
na = 2.0f;
nb = 1.0f;
byte[] ba = PDataType.UNSIGNED_FLOAT.toBytes(na);
byte[] bb = PDataType.UNSIGNED_FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = 0.0f;
nb = Float.MIN_VALUE;
ba = PDataType.UNSIGNED_FLOAT.toBytes(na);
bb = PDataType.UNSIGNED_FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = Float.MIN_VALUE;
nb = Float.MAX_VALUE;
ba = PDataType.UNSIGNED_FLOAT.toBytes(na);
bb = PDataType.UNSIGNED_FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = Float.MAX_VALUE;
nb = Float.POSITIVE_INFINITY;
ba = PDataType.UNSIGNED_FLOAT.toBytes(na);
bb = PDataType.UNSIGNED_FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = Float.POSITIVE_INFINITY;
nb = Float.NaN;
ba = PDataType.UNSIGNED_FLOAT.toBytes(na);
bb = PDataType.UNSIGNED_FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
Integer value = 100;
Object obj = PDataType.UNSIGNED_FLOAT.toObject(value, PDataType.INTEGER);
assertTrue(obj instanceof Float);
}
@Test
public void testUnsignedDouble() {
Double na = 0.005;
byte[] b = PDataType.UNSIGNED_DOUBLE.toBytes(na);
Double nb = (Double)PDataType.UNSIGNED_DOUBLE.toObject(b);
assertEquals(na,nb);
na = 10.0;
b = PDataType.UNSIGNED_DOUBLE.toBytes(na, ColumnModifier.SORT_DESC);
ImmutableBytesWritable ptr = new ImmutableBytesWritable();
ptr.set(b);
nb = PDataType.UNSIGNED_DOUBLE.getCodec().decodeDouble(ptr, ColumnModifier.SORT_DESC);
assertEquals(na,nb);
na = 2.0;
nb = 1.0;
byte[] ba = PDataType.UNSIGNED_DOUBLE.toBytes(na);
byte[] bb = PDataType.UNSIGNED_DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = 0.0;
nb = Double.MIN_VALUE;
ba = PDataType.UNSIGNED_DOUBLE.toBytes(na);
bb = PDataType.UNSIGNED_DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = Double.MIN_VALUE;
nb = Double.MAX_VALUE;
ba = PDataType.UNSIGNED_DOUBLE.toBytes(na);
bb = PDataType.UNSIGNED_DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = Double.MAX_VALUE;
nb = Double.POSITIVE_INFINITY;
ba = PDataType.UNSIGNED_DOUBLE.toBytes(na);
bb = PDataType.UNSIGNED_DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = Double.POSITIVE_INFINITY;
nb = Double.NaN;
ba = PDataType.UNSIGNED_DOUBLE.toBytes(na);
bb = PDataType.UNSIGNED_DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
Integer value = 100;
Object obj = PDataType.UNSIGNED_DOUBLE.toObject(value, PDataType.INTEGER);
assertTrue(obj instanceof Double);
assertEquals(1, PDataType.UNSIGNED_DOUBLE.compareTo(Double.valueOf(101), Long.valueOf(100), PDataType.LONG));
assertEquals(0, PDataType.UNSIGNED_DOUBLE.compareTo(Double.valueOf(Long.MAX_VALUE), Long.MAX_VALUE, PDataType.LONG));
assertEquals(-1, PDataType.UNSIGNED_DOUBLE.compareTo(Double.valueOf(1), Long.valueOf(100), PDataType.LONG));
assertEquals(0, PDataType.UNSIGNED_DOUBLE.compareTo(Double.valueOf(101), BigDecimal.valueOf(101.0), PDataType.DECIMAL));
}
@Test
public void testFloat() {
Float na = 0.005f;
byte[] b = PDataType.FLOAT.toBytes(na);
Float nb = (Float)PDataType.FLOAT.toObject(b);
assertEquals(na,nb);
na = 10.0f;
b = PDataType.FLOAT.toBytes(na, ColumnModifier.SORT_DESC);
ImmutableBytesWritable ptr = new ImmutableBytesWritable();
ptr.set(b);
nb = PDataType.FLOAT.getCodec().decodeFloat(ptr, ColumnModifier.SORT_DESC);
assertEquals(na,nb);
na = 1.0f;
nb = -1.0f;
byte[] ba = PDataType.FLOAT.toBytes(na);
byte[] bb = PDataType.FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = -1f;
nb = -3f;
ba = PDataType.FLOAT.toBytes(na);
bb = PDataType.FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = Float.NEGATIVE_INFINITY;
nb = -Float.MAX_VALUE;
ba = PDataType.FLOAT.toBytes(na);
bb = PDataType.FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = -Float.MAX_VALUE;
nb = -Float.MIN_VALUE;
ba = PDataType.FLOAT.toBytes(na);
bb = PDataType.FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = -Float.MIN_VALUE;
nb = -0.0f;
ba = PDataType.FLOAT.toBytes(na);
bb = PDataType.FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = -0.0f;
nb = 0.0f;
ba = PDataType.FLOAT.toBytes(na);
bb = PDataType.FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = 0.0f;
nb = Float.MIN_VALUE;
ba = PDataType.FLOAT.toBytes(na);
bb = PDataType.FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = Float.MIN_VALUE;
nb = Float.MAX_VALUE;
ba = PDataType.FLOAT.toBytes(na);
bb = PDataType.FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = Float.MAX_VALUE;
nb = Float.POSITIVE_INFINITY;
ba = PDataType.FLOAT.toBytes(na);
bb = PDataType.FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = Float.POSITIVE_INFINITY;
nb = Float.NaN;
ba = PDataType.FLOAT.toBytes(na);
bb = PDataType.FLOAT.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
Integer value = 100;
Object obj = PDataType.FLOAT.toObject(value, PDataType.INTEGER);
assertTrue(obj instanceof Float);
Double dvalue = Double.NEGATIVE_INFINITY;
obj = PDataType.FLOAT.toObject(dvalue, PDataType.DOUBLE);
assertTrue(obj instanceof Float);
assertEquals(Float.NEGATIVE_INFINITY, obj);
na = 1.0f;
nb = -1.0f;
ba = PDataType.FLOAT.toBytes(na);
bb = PDataType.FLOAT.toBytes(nb);
float nna = PDataType.FLOAT.getCodec().decodeFloat(ba, 0, ColumnModifier.SORT_DESC);
float nnb = PDataType.FLOAT.getCodec().decodeFloat(bb, 0, ColumnModifier.SORT_DESC);
assertTrue(Float.compare(nna, nnb) < 0);
}
@Test
public void testDouble() {
Double na = 0.005;
byte[] b = PDataType.DOUBLE.toBytes(na);
Double nb = (Double)PDataType.DOUBLE.toObject(b);
assertEquals(na,nb);
na = 10.0;
b = PDataType.DOUBLE.toBytes(na, ColumnModifier.SORT_DESC);
ImmutableBytesWritable ptr = new ImmutableBytesWritable();
ptr.set(b);
nb = PDataType.DOUBLE.getCodec().decodeDouble(ptr, ColumnModifier.SORT_DESC);
assertEquals(na,nb);
na = 1.0;
nb = -1.0;
byte[] ba = PDataType.DOUBLE.toBytes(na);
byte[] bb = PDataType.DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = -1.0;
nb = -3.0;
ba = PDataType.DOUBLE.toBytes(na);
bb = PDataType.DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = Double.NEGATIVE_INFINITY;
nb = -Double.MAX_VALUE;
ba = PDataType.DOUBLE.toBytes(na);
bb = PDataType.DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = -Double.MAX_VALUE;
nb = -Double.MIN_VALUE;
ba = PDataType.DOUBLE.toBytes(na);
bb = PDataType.DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = -Double.MIN_VALUE;
nb = -0.0;
ba = PDataType.DOUBLE.toBytes(na);
bb = PDataType.DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = -0.0;
nb = 0.0;
ba = PDataType.DOUBLE.toBytes(na);
bb = PDataType.DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = 0.0;
nb = Double.MIN_VALUE;
ba = PDataType.DOUBLE.toBytes(na);
bb = PDataType.DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = Double.MIN_VALUE;
nb = Double.MAX_VALUE;
ba = PDataType.DOUBLE.toBytes(na);
bb = PDataType.DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = Double.MAX_VALUE;
nb = Double.POSITIVE_INFINITY;
ba = PDataType.DOUBLE.toBytes(na);
bb = PDataType.DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
na = Double.POSITIVE_INFINITY;
nb = Double.NaN;
ba = PDataType.DOUBLE.toBytes(na);
bb = PDataType.DOUBLE.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) < 0);
Integer value = 100;
Object obj = PDataType.DOUBLE.toObject(value, PDataType.INTEGER);
assertTrue(obj instanceof Double);
na = 1.0;
nb = -1.0;
ba = PDataType.DOUBLE.toBytes(na);
bb = PDataType.DOUBLE.toBytes(nb);
double nna = PDataType.DOUBLE.getCodec().decodeDouble(ba, 0, ColumnModifier.SORT_DESC);
double nnb = PDataType.DOUBLE.getCodec().decodeDouble(bb, 0, ColumnModifier.SORT_DESC);
assertTrue(Double.compare(nna, nnb) < 0);
assertEquals(1, PDataType.DOUBLE.compareTo(Double.valueOf(101), Long.valueOf(100), PDataType.LONG));
assertEquals(0, PDataType.DOUBLE.compareTo(Double.valueOf(Long.MAX_VALUE), Long.MAX_VALUE, PDataType.LONG));
assertEquals(-1, PDataType.DOUBLE.compareTo(Double.valueOf(1), Long.valueOf(100), PDataType.LONG));
assertEquals(0, PDataType.DOUBLE.compareTo(Double.valueOf(101), BigDecimal.valueOf(101.0), PDataType.DECIMAL));
}
@Test
public void testBigDecimal() {
byte[] b;
BigDecimal na, nb;
b = new byte[] {
(byte)0xc2,0x02,0x10,0x36,0x22,0x22,0x22,0x22,0x22,0x22,0x0f,0x27,0x38,0x1c,0x05,0x40,0x62,0x21,0x54,0x4d,0x4e,0x01,0x14,0x36,0x0d,0x33
};
BigDecimal decodedBytes = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(decodedBytes.compareTo(BigDecimal.ZERO) > 0);
na = new BigDecimal(new BigInteger("12345678901239998123456789"), 2);
//[-52, 13, 35, 57, 79, 91, 13, 40, 100, 82, 24, 46, 68, 90]
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
TestUtil.assertRoundEquals(na,nb);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal("115.533333333333331438552704639732837677001953125");
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
TestUtil.assertRoundEquals(na,nb);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal(2.5);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
// If we don't remove trailing zeros, this fails
na = new BigDecimal(Double.parseDouble("96.45238095238095"));
String naStr = na.toString();
assertTrue(naStr != null);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
TestUtil.assertRoundEquals(na,nb);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
// If we don't remove trailing zeros, this fails
na = new BigDecimal(-1000);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal("1000.5829999999999913");
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = TestUtil.computeAverage(11000, 3);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal(new BigInteger("12345678901239999"), 2);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal(1);
nb = new BigDecimal(-1);
byte[] ba = PDataType.DECIMAL.toBytes(na);
byte[] bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
na = new BigDecimal(-1);
nb = new BigDecimal(-2);
ba = PDataType.DECIMAL.toBytes(na);
bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
na = new BigDecimal(-3);
nb = new BigDecimal(-1000);
assertTrue(na.compareTo(nb) > 0);
ba = PDataType.DECIMAL.toBytes(na);
bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
na = new BigDecimal(BigInteger.valueOf(12345678901239998L), 2);
nb = new BigDecimal(97);
assertTrue(na.compareTo(nb) > 0);
ba = PDataType.DECIMAL.toBytes(na);
bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
List<BigDecimal> values = Arrays.asList(new BigDecimal[] {
new BigDecimal(-1000),
new BigDecimal(-100000000),
new BigDecimal(1000),
new BigDecimal("-0.001"),
new BigDecimal("0.001"),
new BigDecimal(new BigInteger("12345678901239999"), 2),
new BigDecimal(new BigInteger("12345678901239998"), 2),
new BigDecimal(new BigInteger("12345678901239998123456789"), 2), // bigger than long
new BigDecimal(new BigInteger("-1000"),3),
new BigDecimal(new BigInteger("-1000"),10),
new BigDecimal(99),
new BigDecimal(97),
new BigDecimal(-3)
});
List<byte[]> byteValues = new ArrayList<byte[]>();
for (int i = 0; i < values.size(); i++) {
byteValues.add(PDataType.DECIMAL.toBytes(values.get(i)));
}
for (int i = 0; i < values.size(); i++) {
BigDecimal expected = values.get(i);
BigDecimal actual = (BigDecimal)PDataType.DECIMAL.toObject(byteValues.get(i));
assertTrue("For " + i + " expected " + expected + " but got " + actual,expected.round(PDataType.DEFAULT_MATH_CONTEXT).compareTo(actual.round(PDataType.DEFAULT_MATH_CONTEXT)) == 0);
assertTrue(byteValues.get(i).length <= PDataType.DECIMAL.estimateByteSize(expected));
}
Collections.sort(values);
Collections.sort(byteValues, Bytes.BYTES_COMPARATOR);
for (int i = 0; i < values.size(); i++) {
BigDecimal expected = values.get(i);
byte[] bytes = PDataType.DECIMAL.toBytes(values.get(i));
assertNotNull("bytes converted from values should not be null!", bytes);
BigDecimal actual = (BigDecimal)PDataType.DECIMAL.toObject(byteValues.get(i));
assertTrue("For " + i + " expected " + expected + " but got " + actual,expected.round(PDataType.DEFAULT_MATH_CONTEXT).compareTo(actual.round(PDataType.DEFAULT_MATH_CONTEXT))==0);
}
{
String[] strs ={
"\\xC2\\x03\\x0C\\x10\\x01\\x01\\x01\\x01\\x01\\x019U#\\x13W\\x09\\x09"
,"\\xC2\\x03<,ddddddN\\x1B\\x1B!.9N"
,"\\xC2\\x039"
,"\\xC2\\x03\\x16,\\x01\\x01\\x01\\x01\\x01\\x01E\\x16\\x16\\x03@\\x1EG"
,"\\xC2\\x02d6dddddd\\x15*]\\x0E<1F"
,"\\xC2\\x04 3"
,"\\xC2\\x03$Ldddddd\\x0A\\x06\\x06\\x1ES\\x1C\\x08"
,"\\xC2\\x03\\x1E\\x0A\\x01\\x01\\x01\\x01\\x01\\x01#\\x0B=4 AV"
,"\\xC2\\x02\\\\x04dddddd\\x15*]\\x0E<1F"
,"\\xC2\\x02V\"\\x01\\x01\\x01\\x01\\x01\\x02\\x1A\\x068\\x162&O"
};
for (String str : strs) {
byte[] bytes = Bytes.toBytesBinary(str);
Object o = PDataType.DECIMAL.toObject(bytes);
assertNotNull(o);
//System.out.println(o.getClass() +" " + bytesToHex(bytes)+" " + o+" ");
}
}
}
public static String bytesToHex(byte[] bytes) {
final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] hexChars = new char[bytes.length * 2];
int v;
for ( int j = 0; j < bytes.length; j++ ) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
@Test
public void testEmptyString() throws Throwable {
byte[] b1 = PDataType.VARCHAR.toBytes("");
byte[] b2 = PDataType.VARCHAR.toBytes(null);
assert (b1.length == 0 && Bytes.compareTo(b1, b2) == 0);
}
@Test
public void testNull() throws Throwable {
byte[] b = new byte[8];
for (PDataType type : PDataType.values()) {
try {
type.toBytes(null);
type.toBytes(null, b, 0);
type.toObject(new byte[0],0,0);
type.toObject(new byte[0],0,0, type);
} catch (ConstraintViolationException e) {
// Fixed width types do not support the concept of a "null" value.
if (! (type.isFixedWidth() && e.getMessage().contains("may not be null"))) {
fail(type + ":" + e);
}
}
}
}
@Test
public void testValueCoersion() throws Exception {
// Testing coercing integer to other values.
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.FLOAT));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.FLOAT, 10.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.FLOAT, 0.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.FLOAT, -10.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.FLOAT, Double.valueOf(Float.MAX_VALUE) + Double.valueOf(Float.MAX_VALUE)));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.LONG));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.LONG, 10.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.LONG, 0.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.LONG, -10.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.LONG, Double.valueOf(Long.MAX_VALUE) + Double.valueOf(Long.MAX_VALUE)));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_INT));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_INT, 10.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_INT, 0.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_INT, -10.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_LONG));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_LONG, 10.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_LONG, 0.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_LONG, -10.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.SMALLINT));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.SMALLINT, 10.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.SMALLINT, 0.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.SMALLINT, -10.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.SMALLINT, -100000.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.TINYINT));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.TINYINT, 10.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.TINYINT, 0.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.TINYINT, -10.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.TINYINT, -1000.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_SMALLINT));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 10.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 0.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, -10.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, -100000.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_TINYINT));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 10.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 0.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_TINYINT, -10.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_TINYINT, -1000.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_DOUBLE));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, 10.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, 0.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, -10.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_FLOAT));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_FLOAT, 10.0));
assertTrue(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_FLOAT, 0.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_FLOAT, -10.0));
assertFalse(PDataType.DOUBLE.isCoercibleTo(PDataType.UNSIGNED_FLOAT, Double.MAX_VALUE));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.DOUBLE));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.LONG));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.LONG, 10.0f));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.LONG, 0.0f));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.LONG, -10.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.LONG, Float.valueOf(Long.MAX_VALUE) + Float.valueOf(Long.MAX_VALUE)));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_INT));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_INT, 10.0f));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_INT, 0.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_INT, -10.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_LONG));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_LONG, 10.0f));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_LONG, 0.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_LONG, -10.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.SMALLINT));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.SMALLINT, 10.0f));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.SMALLINT, 0.0f));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.SMALLINT, -10.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.SMALLINT, -100000.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.TINYINT));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.TINYINT, 10.0f));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.TINYINT, 0.0f));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.TINYINT, -10.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.TINYINT, -1000.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 10.0f));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 0.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, -10.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, -100000.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_TINYINT));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 10.0f));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 0.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, -10.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, -1000.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_DOUBLE));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_FLOAT));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_FLOAT, 10.0f));
assertTrue(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_FLOAT, 0.0f));
assertFalse(PDataType.FLOAT.isCoercibleTo(PDataType.UNSIGNED_FLOAT, -10.0f));
assertFalse(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.FLOAT));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.DOUBLE));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.FLOAT, 10.0));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.FLOAT, 0.0));
assertFalse(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.FLOAT, Double.MAX_VALUE));
assertFalse(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.LONG));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.LONG, 10.0));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.LONG, 0.0));
assertFalse(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.LONG, Double.MAX_VALUE));
assertFalse(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_INT));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_INT, 10.0));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_INT, 0.0));
assertFalse(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_LONG));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_LONG, 10.0));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_LONG, 0.0));
assertFalse(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.SMALLINT));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.SMALLINT, 10.0));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.SMALLINT, 0.0));
assertFalse(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.TINYINT));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.TINYINT, 10.0));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.TINYINT, 0.0));
assertFalse(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_SMALLINT));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 10.0));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 0.0));
assertFalse(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_TINYINT));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 10.0));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 0.0));
assertFalse(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_FLOAT));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_FLOAT, 10.0));
assertTrue(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_FLOAT, 0.0));
assertFalse(PDataType.UNSIGNED_DOUBLE.isCoercibleTo(PDataType.UNSIGNED_FLOAT, Double.MAX_VALUE));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.FLOAT));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.DOUBLE));
assertFalse(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.LONG));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.LONG, 10.0f));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.LONG, 0.0f));
assertFalse(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.LONG, Float.MAX_VALUE));
assertFalse(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.UNSIGNED_INT));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.UNSIGNED_INT, 10.0f));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.UNSIGNED_INT, 0.0f));
assertFalse(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.UNSIGNED_LONG));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.UNSIGNED_LONG, 10.0f));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.UNSIGNED_LONG, 0.0f));
assertFalse(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.SMALLINT));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.SMALLINT, 10.0f));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.SMALLINT, 0.0f));
assertFalse(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.TINYINT));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.TINYINT, 10.0f));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.TINYINT, 0.0f));
assertFalse(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 10.0f));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 0.0f));
assertFalse(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.UNSIGNED_TINYINT));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 10.0f));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 0.0f));
assertTrue(PDataType.UNSIGNED_FLOAT.isCoercibleTo(PDataType.UNSIGNED_DOUBLE));
// Testing coercing integer to other values.
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.DOUBLE));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.FLOAT));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.LONG));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.LONG, 10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.LONG, 0));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.LONG, -10));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_INT));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_INT, 10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_INT, 0));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_INT, -10));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_LONG));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_LONG, 10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_LONG, 0));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_LONG, -10));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.SMALLINT));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.SMALLINT, 10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.SMALLINT, 0));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.SMALLINT, -10));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.SMALLINT, -100000));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.TINYINT));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.TINYINT, 10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.TINYINT, 0));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.TINYINT, -10));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.TINYINT, -1000));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_SMALLINT));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 0));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, -10));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, -100000));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_TINYINT));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 0));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_TINYINT, -10));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_TINYINT, -1000));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_FLOAT, -10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_FLOAT, 10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_FLOAT, 0));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, -10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, 10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, 0));
// Testing coercing long to other values.
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.DOUBLE));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.FLOAT));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.INTEGER));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, Long.MAX_VALUE));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, Integer.MAX_VALUE + 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, (long)Integer.MAX_VALUE));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, Integer.MAX_VALUE - 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, 0L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, -10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, Integer.MIN_VALUE + 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, (long)Integer.MIN_VALUE));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, Integer.MIN_VALUE - 10L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, Long.MIN_VALUE));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_INT));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_INT, 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_INT, 0L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_INT, -10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_LONG, Long.MAX_VALUE));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_LONG, 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_LONG, 0L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_LONG, -10L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_LONG, Long.MIN_VALUE));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.SMALLINT));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.SMALLINT, 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.SMALLINT, 0L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.SMALLINT, -10L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.SMALLINT, -100000L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.TINYINT));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.TINYINT, 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.TINYINT, 0L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.TINYINT, -10L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.TINYINT, -1000L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_SMALLINT));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 0L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, -10L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, -100000L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_TINYINT));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 0L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_TINYINT, -10L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_TINYINT, -1000L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, 0L));
assertFalse(PDataType.LONG
.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, -1L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_FLOAT, 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_FLOAT, 0L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_FLOAT, -1L));
// Testing coercing smallint to other values.
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.DOUBLE));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.FLOAT));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.LONG));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.LONG, (short)10));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.LONG, (short)0));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.LONG, (short)-10));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.INTEGER));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.INTEGER, (short)10));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.INTEGER, (short)0));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.INTEGER, (short)-10));
assertFalse(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_INT));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_INT, (short)10));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_INT, (short)0));
assertFalse(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_INT, (short)-10));
assertFalse(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_LONG));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_LONG, (short)10));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_LONG, (short)0));
assertFalse(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_LONG, (short)-10));
assertFalse(PDataType.SMALLINT.isCoercibleTo(PDataType.TINYINT));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.TINYINT, (short)10));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.TINYINT, (short)0));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.TINYINT, (short)-10));
assertFalse(PDataType.SMALLINT.isCoercibleTo(PDataType.TINYINT, (short)1000));
assertFalse(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, (short)10));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, (short)0));
assertFalse(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, (short)-10));
assertFalse(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_TINYINT));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, (short)10));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, (short)0));
assertFalse(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, (short)-10));
assertFalse(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, (short)1000));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, (short)10));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, (short)0));
assertFalse(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, (short)-1));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_FLOAT, (short)10));
assertTrue(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_FLOAT, (short)0));
assertFalse(PDataType.SMALLINT.isCoercibleTo(PDataType.UNSIGNED_FLOAT, (short)-1));
// Testing coercing tinyint to other values.
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.DOUBLE));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.FLOAT));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.LONG));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.LONG, (byte)10));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.LONG, (byte)0));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.LONG, (byte)-10));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.INTEGER));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.INTEGER, (byte)10));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.INTEGER, (byte)0));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.INTEGER, (byte)-10));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.SMALLINT));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.SMALLINT, (byte)100));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.SMALLINT, (byte)0));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.SMALLINT, (byte)-10));
assertFalse(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_INT));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_INT, (byte)10));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_INT, (byte)0));
assertFalse(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_INT, (byte)-10));
assertFalse(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_LONG));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_LONG, (byte)10));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_LONG, (byte)0));
assertFalse(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_LONG, (byte)-10));
assertFalse(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, (byte)10));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, (byte)0));
assertFalse(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, (byte)-10));
assertFalse(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_TINYINT));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, (byte)10));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, (byte)0));
assertFalse(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, (byte)-10));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, (byte)10));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, (byte)0));
assertFalse(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_DOUBLE, (byte)-1));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_FLOAT, (byte)10));
assertTrue(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_FLOAT, (byte)0));
assertFalse(PDataType.TINYINT.isCoercibleTo(PDataType.UNSIGNED_FLOAT, (byte)-1));
// Testing coercing unsigned_int to other values.
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.DOUBLE));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.FLOAT));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.INTEGER));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.INTEGER, 10));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.INTEGER, 0));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.LONG));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.LONG, 10));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.LONG, 0));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_LONG));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_LONG, 10));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_LONG, 0));
assertFalse(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.SMALLINT));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.SMALLINT, 10));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.SMALLINT, 0));
assertFalse(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.TINYINT));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.TINYINT, 10));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.TINYINT, 0));
assertFalse(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 10));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 0));
assertFalse(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 100000));
assertFalse(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_TINYINT));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 10));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 0));
assertFalse(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 1000));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_DOUBLE));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_FLOAT));
// Testing coercing unsigned_long to other values.
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.DOUBLE));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.FLOAT));
assertFalse(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.INTEGER));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.INTEGER, 10L));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.INTEGER, 0L));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.LONG));
assertFalse(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.UNSIGNED_INT));
assertFalse(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.SMALLINT));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.SMALLINT, 10L));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.SMALLINT, 0L));
assertFalse(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.TINYINT));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.TINYINT, 10L));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.TINYINT, 0L));
assertFalse(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.UNSIGNED_SMALLINT));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 10L));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 0L));
assertFalse(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, 100000L));
assertFalse(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_TINYINT));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 10L));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 0L));
assertFalse(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.UNSIGNED_TINYINT, 1000L));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.UNSIGNED_DOUBLE));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.UNSIGNED_FLOAT));
// Testing coercing unsigned_smallint to other values.
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.DOUBLE));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.FLOAT));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.INTEGER));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.INTEGER, (short)10));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.INTEGER, (short)0));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.LONG));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.LONG, (short)10));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.LONG, (short)0));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.UNSIGNED_LONG));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.UNSIGNED_LONG, (short)10));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.UNSIGNED_LONG, (short)0));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.UNSIGNED_INT));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.UNSIGNED_INT, (short)10));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.UNSIGNED_INT, (short)0));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.SMALLINT));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.SMALLINT, (short)10));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.SMALLINT, (short)0));
assertFalse(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.TINYINT));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.TINYINT, (short)10));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.TINYINT, (short)0));
assertFalse(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.TINYINT, (short)1000));
assertFalse(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.UNSIGNED_TINYINT));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, (short)10));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, (short)0));
assertFalse(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.UNSIGNED_TINYINT, (short)1000));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.UNSIGNED_DOUBLE));
assertTrue(PDataType.UNSIGNED_SMALLINT.isCoercibleTo(PDataType.UNSIGNED_FLOAT));
// Testing coercing unsigned_tinyint to other values.
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.DOUBLE));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.FLOAT));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.INTEGER));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.INTEGER, (byte)10));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.INTEGER, (byte)0));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.LONG));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.LONG, (byte)10));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.LONG, (byte)0));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.UNSIGNED_LONG));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.UNSIGNED_LONG, (byte)10));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.UNSIGNED_LONG, (byte)0));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.UNSIGNED_INT));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.UNSIGNED_INT, (byte)10));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.UNSIGNED_INT, (byte)0));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.SMALLINT));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.SMALLINT, (byte)10));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.SMALLINT, (byte)0));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.TINYINT));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.TINYINT, (byte)10));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.TINYINT, (byte)0));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, (byte)10));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.UNSIGNED_SMALLINT, (byte)0));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.UNSIGNED_DOUBLE));
assertTrue(PDataType.UNSIGNED_TINYINT.isCoercibleTo(PDataType.UNSIGNED_FLOAT));
// Testing coercing Date types
assertTrue(PDataType.DATE.isCoercibleTo(PDataType.TIMESTAMP));
assertTrue(PDataType.DATE.isCoercibleTo(PDataType.TIME));
assertTrue(PDataType.TIMESTAMP.isCoercibleTo(PDataType.DATE));
assertTrue(PDataType.TIMESTAMP.isCoercibleTo(PDataType.TIME));
assertTrue(PDataType.TIME.isCoercibleTo(PDataType.TIMESTAMP));
assertTrue(PDataType.TIME.isCoercibleTo(PDataType.DATE));
}
@Test
public void testGetDeicmalPrecisionAndScaleFromRawBytes() throws Exception {
// Special case for 0.
BigDecimal bd = new BigDecimal("0");
byte[] b = PDataType.DECIMAL.toBytes(bd);
int[] v = PDataType.getDecimalPrecisionAndScale(b, 0, b.length);
assertEquals(0, v[0]);
assertEquals(0, v[1]);
BigDecimal[] bds = new BigDecimal[] {
new BigDecimal("1"),
new BigDecimal("0.11"),
new BigDecimal("1.1"),
new BigDecimal("11"),
new BigDecimal("101"),
new BigDecimal("10.1"),
new BigDecimal("1.01"),
new BigDecimal("0.101"),
new BigDecimal("1001"),
new BigDecimal("100.1"),
new BigDecimal("10.01"),
new BigDecimal("1.001"),
new BigDecimal("0.1001"),
new BigDecimal("10001"),
new BigDecimal("1000.1"),
new BigDecimal("100.01"),
new BigDecimal("10.001"),
new BigDecimal("1.0001"),
new BigDecimal("0.10001"),
new BigDecimal("100000000000000000000000000000"),
new BigDecimal("1000000000000000000000000000000"),
new BigDecimal("0.000000000000000000000000000001"),
new BigDecimal("0.0000000000000000000000000000001"),
new BigDecimal("111111111111111111111111111111"),
new BigDecimal("1111111111111111111111111111111"),
new BigDecimal("0.111111111111111111111111111111"),
new BigDecimal("0.1111111111111111111111111111111"),
};
for (int i=0; i<bds.length; i++) {
testReadDecimalPrecisionAndScaleFromRawBytes(bds[i]);
testReadDecimalPrecisionAndScaleFromRawBytes(bds[i].negate());
}
}
@Test
public void testDateConversions() {
long now = System.currentTimeMillis();
Date date = new Date(now);
Time t = new Time(now);
Timestamp ts = new Timestamp(now);
Object o = PDataType.DATE.toObject(ts, PDataType.TIMESTAMP);
assertEquals(o.getClass(), java.sql.Date.class);
o = PDataType.DATE.toObject(t, PDataType.TIME);
assertEquals(o.getClass(), java.sql.Date.class);
o = PDataType.TIME.toObject(date, PDataType.DATE);
assertEquals(o.getClass(), java.sql.Time.class);
o = PDataType.TIME.toObject(ts, PDataType.TIMESTAMP);
assertEquals(o.getClass(), java.sql.Time.class);
o = PDataType.TIMESTAMP.toObject(date, PDataType.DATE);
assertEquals(o.getClass(), java.sql.Timestamp.class);
o = PDataType.TIMESTAMP.toObject(t, PDataType.TIME);
assertEquals(o.getClass(), java.sql.Timestamp.class);
}
private void testReadDecimalPrecisionAndScaleFromRawBytes(BigDecimal bd) {
byte[] b = PDataType.DECIMAL.toBytes(bd);
int[] v = PDataType.getDecimalPrecisionAndScale(b, 0, b.length);
assertEquals(bd.toString(), bd.precision(), v[0]);
assertEquals(bd.toString(), bd.scale(), v[1]);
}
} |
package com.github.tminglei.bind;
import java.util.*;
/**
* object used to hold bind result or errors
*/
public class BindObject implements Iterable<Map.Entry<String, Object>> {
static final String DEFAULT_KEY = "_default$";
private final Object errors;
private final Map<String, Object> data;
BindObject(Object errors) {
this.errors = errors;
this.data = new HashMap<>();
}
BindObject(Map<String, Object> data) {
this.errors = null;
this.data = data;
}
/**
* @param <T> expected type
* @return the errors optional
*/
public <T> Optional<T> errors() {
return Optional.ofNullable((T) errors);
}
/**
* implementation for interface Iterable
* @return the field iterator
*/
@Override
public Iterator<Map.Entry<String, Object>> iterator() {
return data.entrySet().iterator();
}
/**
* @return field names
*/
public Set<String> names() {
return data.keySet();
}
/**
* @param name field name
* @return field bind object
*/
public BindObject node(String name) {
return (BindObject) data.get(name);
}
/**
* @param <T> expected type
* @return the final result value
*/
public <T> T get() {
return (T) data.get(DEFAULT_KEY);
}
/**
* @param name field name
* @param <T> expected type
* @return field value
*/
public <T> T get(String name) {
return (T) data.get(name);
}
/**
* @param name field name
* @return true if exists; false if not
*/
public boolean has(String name) {
return data.get(name) != null;
}
/**
* convert to specified type (NOTE: only Map is supported currently)
* @param target target type class
* @param <T> target type
* @return converted object
*/
public <T> T to(Class<T> target) {
if (target == Map.class) {
return (T) FrameworkUtils.bind2map(this);
} else throw new IllegalArgumentException("Unsupported type: " + target);
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
if (errors != null) {
buf.append("errors: ");
buf.append(errors);
} else {
buf.append("{ ");
data.entrySet().stream().forEach(e -> {
buf.append(e.getKey()).append(": ").append(e.getValue()).append(", ");
});
buf.append(" }");
}
return buf.toString();
}
} |
package org.lightmare.utils.earfile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collections;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.lightmare.jpa.ConfigLoader;
import org.lightmare.utils.AbstractIOUtils;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
import org.lightmare.utils.fs.FileType;
/**
* Implementation of {@link AbstractIOUtils} for jar files
*
* @author levan
*
*/
public class JarUtils extends AbstractIOUtils {
public static final FileType type = FileType.JAR;
public JarUtils(String path) {
super(path);
}
public JarUtils(File file) {
super(file);
}
public JarUtils(URL url) throws IOException {
super(url);
}
@Override
public FileType getType() {
return type;
}
@Override
public InputStream earReader() throws IOException {
return null;
}
@Override
public void getEjbLibs() throws IOException {
}
@Override
public void extractEjbJars(Set<String> jarNames) throws IOException {
URL currentURL = realFile.toURI().toURL();
getEjbURLs().add(currentURL);
boolean checkOnOrm = checkOnOrm(path);
if (xmlFromJar && checkOnOrm) {
String xmlPath = StringUtils.concat(currentURL.toString(),
ARCHIVE_URL_DELIM, ConfigLoader.XML_PATH);
URL xmlURL = new URL(JAR, StringUtils.EMPTY_STRING, xmlPath);
getXmlFiles().put(realFile.getName(), xmlURL);
getXmlURLs().put(currentURL, xmlURL);
}
}
@Override
public boolean checkOnOrm(String jarName) throws IOException {
ZipFile zipFile = getEarFile();
ZipEntry xmlEntry = zipFile.getEntry(ConfigLoader.XML_PATH);
return ObjectUtils.notNull(xmlEntry);
}
@Override
protected void scanArchive(Object... args) throws IOException {
if (CollectionUtils.available(args)) {
xmlFromJar = (Boolean) CollectionUtils.getFirst(args);
}
extractEjbJars(Collections.<String> emptySet());
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.