answer stringlengths 17 10.2M |
|---|
package bio.terra.cli.context;
import static bio.terra.cli.context.GlobalContext.CommandRunners.DOCKER_CONTAINER;
import static bio.terra.cli.context.GlobalContext.CommandRunners.LOCAL_PROCESS;
import static bio.terra.cli.context.utils.Logger.LogLevel;
import bio.terra.cli.apps.CommandRunner;
import bio.terra.cli.apps.DockerCommandRunner;
import bio.terra.cli.apps.LocalProcessCommandRunner;
import bio.terra.cli.auth.AuthenticationManager.BrowserLaunchOption;
import bio.terra.cli.command.exception.SystemException;
import bio.terra.cli.command.exception.UserActionableException;
import bio.terra.cli.context.utils.JacksonMapper;
import bio.terra.cli.service.ServerManager;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This POJO class represents an instance of the Terra CLI global context. This is intended
* primarily for authentication and connection-related context values that will span multiple
* workspaces.
*/
public class GlobalContext {
private static final Logger logger = LoggerFactory.getLogger(GlobalContext.class);
// global auth context = list of Terra users, CLI-generated key of current Terra user,
// flag indicating whether to launch a browser automatically or not
public Map<String, TerraUser> terraUsers;
public String currentTerraUserKey;
public BrowserLaunchOption browserLaunchOption = BrowserLaunchOption.auto;
// global server context = service uris, environment name
public ServerSpecification server;
// global apps context = flag for how to launch tools, docker image id or tag
public CommandRunners commandRunnerOption = DOCKER_CONTAINER;
public String dockerImageId;
// maximum number of resources to cache on disk for a single workspace before throwing an error
// (corresponds to ~1MB cache size on disk)
public int resourcesCacheSize = DEFAULT_RESOURCES_CACHE_SIZE;
public static final int DEFAULT_RESOURCES_CACHE_SIZE = 1000;
// global logging context = log levels for file and stdout
public LogLevel fileLoggingLevel = LogLevel.INFO;
public LogLevel consoleLoggingLevel = LogLevel.OFF;
// file paths related to persisting the global context on disk
private static final String GLOBAL_CONTEXT_DIRNAME = ".terra";
private static final String GLOBAL_CONTEXT_FILENAME = "global-context.json";
private static final String PET_KEYS_DIRNAME = "pet-keys";
private static final String LOGS_DIRNAME = "logs";
private static final String LOG_FILENAME = "terra.log";
// defaut constructor needed for Jackson de/serialization
private GlobalContext() {}
private GlobalContext(ServerSpecification server, String dockerImageId) {
this.terraUsers = new HashMap<>();
this.server = server;
this.dockerImageId = dockerImageId;
}
// Persisting on disk
/**
* Read in an instance of this class from a JSON-formatted file in the global context directory.
* If there is no existing file, this method returns an object populated with default values.
*
* <p>Note: DO NOT put any logger statements in this function. Because we setup the loggers using
* the logging levels specified in the global context, the loggers have not been setup when we
* first call this function.
*
* @return an instance of this class
*/
public static GlobalContext readFromFile() {
// try to read in an instance of the global context file
try {
return JacksonMapper.readFileIntoJavaObject(
getGlobalContextFile().toFile(), GlobalContext.class);
} catch (IOException ioEx) {
// file not found is a common error here (e.g. first time running the CLI, there will be no
// pre-existing global context file). we handle this by returning an object populated with
// default values below. so, no need to log or throw the exception returned here.
}
// if the global context file does not exist or there is an error reading it, return an object
// populated with default values
return new GlobalContext(ServerManager.defaultServer(), DockerCommandRunner.defaultImageId());
}
/** Write an instance of this class to a JSON-formatted file in the global context directory. */
private void writeToFile() {
try {
JacksonMapper.writeJavaObjectToFile(getGlobalContextFile().toFile(), this);
} catch (IOException ioEx) {
logger.error("Error persisting global context.", ioEx);
}
}
// Auth
/** Getter for the current Terra user. Returns null if no current user is defined. */
@JsonIgnore
public Optional<TerraUser> getCurrentTerraUser() {
if (currentTerraUserKey == null) {
return Optional.empty();
}
return Optional.of(terraUsers.get(currentTerraUserKey));
}
/** Utility method that throws an exception if the current Terra user is not defined. */
public TerraUser requireCurrentTerraUser() {
Optional<TerraUser> terraUserOpt = getCurrentTerraUser();
if (!terraUserOpt.isPresent()) {
throw new UserActionableException("The current Terra user is not defined. Login required.");
}
return terraUserOpt.get();
}
/**
* Add a new Terra user to the list of identity contexts, or update an existing one. Optionally
* update the current user. Persists on disk.
*/
public void addOrUpdateTerraUser(TerraUser terraUser, boolean setAsCurrentUser) {
if (terraUsers.get(terraUser.cliGeneratedUserKey) != null) {
logger.info("Terra user {} already exists, updating.", terraUser.terraUserEmail);
}
terraUsers.put(terraUser.cliGeneratedUserKey, terraUser);
if (setAsCurrentUser) {
currentTerraUserKey = terraUser.cliGeneratedUserKey;
}
writeToFile();
}
/**
* Add a new Terra user to the list of identity contexts, or update an existing one. Persists on
* disk.
*/
public void addOrUpdateTerraUser(TerraUser terraUser) {
addOrUpdateTerraUser(terraUser, false);
}
/**
* Setter for the browser launch option. Persists on disk.
*
* @param browserLaunchOption new value for the browser launch option
*/
public void updateBrowserLaunchFlag(BrowserLaunchOption browserLaunchOption) {
logger.info(
"Updating browser launch flag from {} to {}.",
this.browserLaunchOption,
browserLaunchOption);
this.browserLaunchOption = browserLaunchOption;
writeToFile();
}
/**
* Setter for the command runner option. Persists on disk.
*
* @param commandRunnerOption new value for the command runner option
*/
public void updateCommandRunnerOption(CommandRunners commandRunnerOption) {
logger.info(
"Updating command runner flag from {} to {}.",
this.commandRunnerOption,
commandRunnerOption);
this.commandRunnerOption = commandRunnerOption;
writeToFile();
}
/**
* Setter for the resources cache size. Persists on disk.
*
* @param resourcesCacheSize new value for the resources cache size
*/
public void updateResourcesCacheSize(int resourcesCacheSize) {
logger.info(
"Updating resources cache size from {} to {}.",
this.resourcesCacheSize,
resourcesCacheSize);
this.resourcesCacheSize = resourcesCacheSize;
writeToFile();
}
/**
* Setter for the console logging level. Persists on disk.
*
* @param consoleLoggingLevel new value for the console logging level
*/
public void updateConsoleLoggingLevel(LogLevel consoleLoggingLevel) {
logger.info(
"Updating console logging level from {} to {}.",
this.consoleLoggingLevel,
consoleLoggingLevel);
this.consoleLoggingLevel = consoleLoggingLevel;
writeToFile();
}
/**
* Setter for the file logging level. Persists on disk.
*
* @param fileLoggingLevel new value for the file logging level
*/
public void updateFileLoggingLevel(LogLevel fileLoggingLevel) {
logger.info(
"Updating file logging level from {} to {}.", this.fileLoggingLevel, fileLoggingLevel);
this.fileLoggingLevel = fileLoggingLevel;
writeToFile();
}
// Server
/** Setter for the current Terra server. Persists on disk. */
public void updateServer(ServerSpecification server) {
logger.info("Updating server from {} to {}.", this.server.name, server.name);
this.server = server;
writeToFile();
}
// Apps
/** Setter for the Docker image id. Persists on disk. */
public void updateDockerImageId(String dockerImageId) {
logger.info("Updating Docker image id from {} to {}.", this.dockerImageId, dockerImageId);
this.dockerImageId = dockerImageId;
writeToFile();
}
/** This enum defines the different ways of running tool/app commands. */
public enum CommandRunners {
DOCKER_CONTAINER,
LOCAL_PROCESS;
}
/** Helper method to get the {@link CommandRunner} sub-class that maps to each enum value. */
public CommandRunner getRunner(WorkspaceContext workspaceContext) {
switch (commandRunnerOption) {
case DOCKER_CONTAINER:
return new DockerCommandRunner(this, workspaceContext);
case LOCAL_PROCESS:
return new LocalProcessCommandRunner(this, workspaceContext);
default:
throw new SystemException("Unsupported command runner type: " + this);
}
}
// Directory and file names
// - global context directory parent: $HOME/
// - global context directory: .terra/
// - persisted global context file: global-context.json
// - sub-directory for persisting pet SA keys: pet-keys/[terra user id]/
// - pet SA key filename: [workspace id]
// - sub-directory for log files: logs/
// -*.terra.log
/**
* Get the global context directory.
*
* @return absolute path to global context directory
*/
@JsonIgnore
public static Path getGlobalContextDir() {
// TODO: allow overriding this (e.g. env var != user home directory)
Path parentDir = Paths.get(System.getProperty("user.home"));
return parentDir.resolve(GLOBAL_CONTEXT_DIRNAME).toAbsolutePath();
}
/**
* Get the global context file.
*
* @return absolute path to the global context file
*/
@JsonIgnore
private static Path getGlobalContextFile() {
return getGlobalContextDir().resolve(GLOBAL_CONTEXT_FILENAME);
}
/**
* Get the directory that contains the pet SA key files for the given user. This is a
* sub-directory of the global context directory.
*
* @param terraUser user whose key files we want
* @return absolute path to the key file directory for the given user
*/
@JsonIgnore
public static Path getPetSaKeyDir(TerraUser terraUser) {
return getGlobalContextDir().resolve(PET_KEYS_DIRNAME).resolve(terraUser.terraUserId);
}
/**
* Get the pet SA key file for the given user and workspace. This is stored in a sub-directory of
* the global context directory.
*
* @param terraUser user whose key file we want
* @param workspaceContext workspace the key file was created for
* @return absolute path to the pet SA key file for the given user and workspace
*/
@JsonIgnore
public static Path getPetSaKeyFile(TerraUser terraUser, WorkspaceContext workspaceContext) {
return getPetSaKeyDir(terraUser).resolve(workspaceContext.getWorkspaceId().toString());
}
/**
* Get the global log file name.
*
* @return absolute path to the log file
*/
@JsonIgnore
public static Path getLogFile() {
return getGlobalContextDir().resolve(LOGS_DIRNAME).resolve(LOG_FILENAME);
}
} |
package biweekly.io;
import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;
import biweekly.ICalendar;
import biweekly.component.ICalComponent;
import biweekly.component.RawComponent;
import biweekly.component.marshaller.DaylightSavingsTimeMarshaller;
import biweekly.component.marshaller.ICalComponentMarshaller;
import biweekly.component.marshaller.ICalendarMarshaller;
import biweekly.component.marshaller.RawComponentMarshaller;
import biweekly.component.marshaller.StandardTimeMarshaller;
import biweekly.component.marshaller.VAlarmMarshaller;
import biweekly.component.marshaller.VEventMarshaller;
import biweekly.component.marshaller.VFreeBusyMarshaller;
import biweekly.component.marshaller.VJournalMarshaller;
import biweekly.component.marshaller.VTimezoneMarshaller;
import biweekly.component.marshaller.VTodoMarshaller;
import biweekly.io.xml.XCalNamespaceContext;
import biweekly.property.ICalProperty;
import biweekly.property.RawProperty;
import biweekly.property.Xml;
import biweekly.property.marshaller.ActionMarshaller;
import biweekly.property.marshaller.AttachmentMarshaller;
import biweekly.property.marshaller.AttendeeMarshaller;
import biweekly.property.marshaller.CalendarScaleMarshaller;
import biweekly.property.marshaller.CategoriesMarshaller;
import biweekly.property.marshaller.ClassificationMarshaller;
import biweekly.property.marshaller.CommentMarshaller;
import biweekly.property.marshaller.CompletedMarshaller;
import biweekly.property.marshaller.ContactMarshaller;
import biweekly.property.marshaller.CreatedMarshaller;
import biweekly.property.marshaller.DateDueMarshaller;
import biweekly.property.marshaller.DateEndMarshaller;
import biweekly.property.marshaller.DateStartMarshaller;
import biweekly.property.marshaller.DateTimeStampMarshaller;
import biweekly.property.marshaller.DescriptionMarshaller;
import biweekly.property.marshaller.DurationPropertyMarshaller;
import biweekly.property.marshaller.ExceptionDatesMarshaller;
import biweekly.property.marshaller.ExceptionRuleMarshaller;
import biweekly.property.marshaller.FreeBusyMarshaller;
import biweekly.property.marshaller.GeoMarshaller;
import biweekly.property.marshaller.ICalPropertyMarshaller;
import biweekly.property.marshaller.LastModifiedMarshaller;
import biweekly.property.marshaller.LocationMarshaller;
import biweekly.property.marshaller.MethodMarshaller;
import biweekly.property.marshaller.OrganizerMarshaller;
import biweekly.property.marshaller.PercentCompleteMarshaller;
import biweekly.property.marshaller.PriorityMarshaller;
import biweekly.property.marshaller.ProductIdMarshaller;
import biweekly.property.marshaller.RawPropertyMarshaller;
import biweekly.property.marshaller.RecurrenceDatesMarshaller;
import biweekly.property.marshaller.RecurrenceIdMarshaller;
import biweekly.property.marshaller.RecurrenceRuleMarshaller;
import biweekly.property.marshaller.RelatedToMarshaller;
import biweekly.property.marshaller.RepeatMarshaller;
import biweekly.property.marshaller.RequestStatusMarshaller;
import biweekly.property.marshaller.ResourcesMarshaller;
import biweekly.property.marshaller.SequenceMarshaller;
import biweekly.property.marshaller.StatusMarshaller;
import biweekly.property.marshaller.SummaryMarshaller;
import biweekly.property.marshaller.TimezoneIdMarshaller;
import biweekly.property.marshaller.TimezoneNameMarshaller;
import biweekly.property.marshaller.TimezoneOffsetFromMarshaller;
import biweekly.property.marshaller.TimezoneOffsetToMarshaller;
import biweekly.property.marshaller.TimezoneUrlMarshaller;
import biweekly.property.marshaller.TransparencyMarshaller;
import biweekly.property.marshaller.TriggerMarshaller;
import biweekly.property.marshaller.UidMarshaller;
import biweekly.property.marshaller.UrlMarshaller;
import biweekly.property.marshaller.VersionMarshaller;
import biweekly.property.marshaller.XmlMarshaller;
/**
* <p>
* Manages a listing of component and property marshallers. This is useful for
* injecting the marshallers of any experimental components or properties you
* have defined into a reader or writer object. The same object instance can be
* reused and injected into multiple reader/writer classes.
* </p>
* <p>
* <b>Example:</b>
*
* <pre class="brush:java">
* //init the registrar
* ICalMarshallerRegistrar registrar = new ICalMarshallerRegistrar();
* registrar.register(new CustomPropertyMarshaller());
* registrar.register(new AnotherCustomPropertyMarshaller());
* registrar.register(new CustomComponentMarshaller());
*
* //inject into a reader class
* ICalReader textReader = new ICalReader(...);
* textReader.setRegistrar(registrar);
* List<ICalendar> icals = new ArrayList<ICalendar>();
* ICalendar ical;
* while ((ical = textReader.readNext()) != null){
* icals.add(ical);
* }
*
* //inject the same instance in another reader/writer class
* JCalWriter writer = new JCalWriter(...);
* writer.setRegistrar(registrar);
* for (ICalendar ical : icals){
* writer.write(ical);
* }
* </pre>
*
* </p>
* @author Michael Angstadt
*/
public class ICalMarshallerRegistrar {
//define standard component marshallers
private static final Map<String, ICalComponentMarshaller<? extends ICalComponent>> standardCompByName = new HashMap<String, ICalComponentMarshaller<? extends ICalComponent>>();
private static final Map<Class<? extends ICalComponent>, ICalComponentMarshaller<? extends ICalComponent>> standardCompByClass = new HashMap<Class<? extends ICalComponent>, ICalComponentMarshaller<? extends ICalComponent>>();
static {
registerStandard(new ICalendarMarshaller());
registerStandard(new VAlarmMarshaller());
registerStandard(new VEventMarshaller());
registerStandard(new VFreeBusyMarshaller());
registerStandard(new VJournalMarshaller());
registerStandard(new VTodoMarshaller());
registerStandard(new VTimezoneMarshaller());
registerStandard(new StandardTimeMarshaller());
registerStandard(new DaylightSavingsTimeMarshaller());
}
//define standard property marshallers
private static final Map<String, ICalPropertyMarshaller<? extends ICalProperty>> standardPropByName = new HashMap<String, ICalPropertyMarshaller<? extends ICalProperty>>();
private static final Map<Class<? extends ICalProperty>, ICalPropertyMarshaller<? extends ICalProperty>> standardPropByClass = new HashMap<Class<? extends ICalProperty>, ICalPropertyMarshaller<? extends ICalProperty>>();
private static final Map<QName, ICalPropertyMarshaller<? extends ICalProperty>> standardPropByQName = new HashMap<QName, ICalPropertyMarshaller<? extends ICalProperty>>();
static {
//RFC 5545
registerStandard(new ActionMarshaller());
registerStandard(new AttachmentMarshaller());
registerStandard(new AttendeeMarshaller());
registerStandard(new CalendarScaleMarshaller());
registerStandard(new CategoriesMarshaller());
registerStandard(new ClassificationMarshaller());
registerStandard(new CommentMarshaller());
registerStandard(new CompletedMarshaller());
registerStandard(new ContactMarshaller());
registerStandard(new CreatedMarshaller());
registerStandard(new DateDueMarshaller());
registerStandard(new DateEndMarshaller());
registerStandard(new DateStartMarshaller());
registerStandard(new DateTimeStampMarshaller());
registerStandard(new DescriptionMarshaller());
registerStandard(new DurationPropertyMarshaller());
registerStandard(new ExceptionDatesMarshaller());
registerStandard(new FreeBusyMarshaller());
registerStandard(new GeoMarshaller());
registerStandard(new LastModifiedMarshaller());
registerStandard(new LocationMarshaller());
registerStandard(new MethodMarshaller());
registerStandard(new OrganizerMarshaller());
registerStandard(new PercentCompleteMarshaller());
registerStandard(new PriorityMarshaller());
registerStandard(new ProductIdMarshaller());
registerStandard(new RecurrenceDatesMarshaller());
registerStandard(new RecurrenceIdMarshaller());
registerStandard(new RecurrenceRuleMarshaller());
registerStandard(new RelatedToMarshaller());
registerStandard(new RepeatMarshaller());
registerStandard(new RequestStatusMarshaller());
registerStandard(new ResourcesMarshaller());
registerStandard(new SequenceMarshaller());
registerStandard(new StatusMarshaller());
registerStandard(new SummaryMarshaller());
registerStandard(new TimezoneIdMarshaller());
registerStandard(new TimezoneNameMarshaller());
registerStandard(new TimezoneOffsetFromMarshaller());
registerStandard(new TimezoneOffsetToMarshaller());
registerStandard(new TimezoneUrlMarshaller());
registerStandard(new TransparencyMarshaller());
registerStandard(new TriggerMarshaller());
registerStandard(new UidMarshaller());
registerStandard(new UrlMarshaller());
registerStandard(new VersionMarshaller());
//RFC 6321
registerStandard(new XmlMarshaller());
//RFC 2445
registerStandard(new ExceptionRuleMarshaller());
}
private final Map<String, ICalComponentMarshaller<? extends ICalComponent>> experimentalCompByName = new HashMap<String, ICalComponentMarshaller<? extends ICalComponent>>(0);
private final Map<Class<? extends ICalComponent>, ICalComponentMarshaller<? extends ICalComponent>> experimentalCompByClass = new HashMap<Class<? extends ICalComponent>, ICalComponentMarshaller<? extends ICalComponent>>(0);
private final Map<String, ICalPropertyMarshaller<? extends ICalProperty>> experimentalPropByName = new HashMap<String, ICalPropertyMarshaller<? extends ICalProperty>>(0);
private final Map<Class<? extends ICalProperty>, ICalPropertyMarshaller<? extends ICalProperty>> experimentalPropByClass = new HashMap<Class<? extends ICalProperty>, ICalPropertyMarshaller<? extends ICalProperty>>(0);
private final Map<QName, ICalPropertyMarshaller<? extends ICalProperty>> experimentalPropByQName = new HashMap<QName, ICalPropertyMarshaller<? extends ICalProperty>>(0);
/**
* Gets a component marshaller by name.
* @param componentName the component name (e.g. "VEVENT")
* @return the component marshaller or a {@link RawComponentMarshaller} if
* not found
*/
public ICalComponentMarshaller<? extends ICalComponent> getComponentMarshaller(String componentName) {
componentName = componentName.toUpperCase();
ICalComponentMarshaller<? extends ICalComponent> marshaller = experimentalCompByName.get(componentName);
if (marshaller != null) {
return marshaller;
}
marshaller = standardCompByName.get(componentName);
if (marshaller != null) {
return marshaller;
}
return new RawComponentMarshaller(componentName);
}
/**
* Gets a property marshaller by name.
* @param propertyName the property name (e.g. "VERSION")
* @return the property marshaller or a {@link RawPropertyMarshaller} if not
* found
*/
public ICalPropertyMarshaller<? extends ICalProperty> getPropertyMarshaller(String propertyName) {
propertyName = propertyName.toUpperCase();
ICalPropertyMarshaller<? extends ICalProperty> marshaller = experimentalPropByName.get(propertyName);
if (marshaller != null) {
return marshaller;
}
marshaller = standardPropByName.get(propertyName);
if (marshaller != null) {
return marshaller;
}
return new RawPropertyMarshaller(propertyName);
}
/**
* Gets a component marshaller by class.
* @param clazz the component class
* @return the component marshaller or null if not found
*/
public ICalComponentMarshaller<? extends ICalComponent> getComponentMarshaller(Class<? extends ICalComponent> clazz) {
ICalComponentMarshaller<? extends ICalComponent> marshaller = experimentalCompByClass.get(clazz);
if (marshaller != null) {
return marshaller;
}
return standardCompByClass.get(clazz);
}
/**
* Gets a property marshaller by class.
* @param clazz the property class
* @return the property marshaller or null if not found
*/
public ICalPropertyMarshaller<? extends ICalProperty> getPropertyMarshaller(Class<? extends ICalProperty> clazz) {
ICalPropertyMarshaller<? extends ICalProperty> marshaller = experimentalPropByClass.get(clazz);
if (marshaller != null) {
return marshaller;
}
return standardPropByClass.get(clazz);
}
/**
* Gets the appropriate component marshaller for a given component instance.
* @param component the component instance
* @return the component marshaller or null if not found
*/
public ICalComponentMarshaller<? extends ICalComponent> getComponentMarshaller(ICalComponent component) {
if (component instanceof RawComponent) {
RawComponent raw = (RawComponent) component;
return new RawComponentMarshaller(raw.getName());
}
return getComponentMarshaller(component.getClass());
}
/**
* Gets the appropriate property marshaller for a given property instance.
* @param property the property instance
* @return the property marshaller or null if not found
*/
public ICalPropertyMarshaller<? extends ICalProperty> getPropertyMarshaller(ICalProperty property) {
if (property instanceof RawProperty) {
RawProperty raw = (RawProperty) property;
return new RawPropertyMarshaller(raw.getName());
}
return getPropertyMarshaller(property.getClass());
}
/**
* Gets a property marshaller by XML local name and namespace.
* @param qname the XML local name and namespace
* @return the property marshaller or a {@link XmlMarshaller} if not found
*/
public ICalPropertyMarshaller<? extends ICalProperty> getPropertyMarshaller(QName qname) {
ICalPropertyMarshaller<? extends ICalProperty> marshaller = experimentalPropByQName.get(qname);
if (marshaller != null) {
return marshaller;
}
marshaller = standardPropByQName.get(qname);
if (marshaller != null) {
return marshaller;
}
if (XCalNamespaceContext.XCAL_NS.equals(qname.getNamespaceURI())) {
return new RawPropertyMarshaller(qname.getLocalPart().toUpperCase());
}
return getPropertyMarshaller(Xml.class);
}
/**
* Registers a component marshaller.
* @param marshaller the marshaller to register
*/
public void register(ICalComponentMarshaller<? extends ICalComponent> marshaller) {
experimentalCompByName.put(marshaller.getComponentName().toUpperCase(), marshaller);
experimentalCompByClass.put(marshaller.getComponentClass(), marshaller);
}
/**
* Registers a property marshaller.
* @param marshaller the marshaller to register
*/
public void register(ICalPropertyMarshaller<? extends ICalProperty> marshaller) {
experimentalPropByName.put(marshaller.getPropertyName().toUpperCase(), marshaller);
experimentalPropByClass.put(marshaller.getPropertyClass(), marshaller);
experimentalPropByQName.put(marshaller.getQName(), marshaller);
}
/**
* Unregisters a component marshaller.
* @param marshaller the marshaller to unregister
*/
public void unregister(ICalComponentMarshaller<? extends ICalComponent> marshaller) {
experimentalCompByName.remove(marshaller.getComponentName().toUpperCase());
experimentalCompByClass.remove(marshaller.getComponentClass());
}
/**
* Unregisters a property marshaller
* @param marshaller the marshaller to unregister
*/
public void unregister(ICalPropertyMarshaller<? extends ICalProperty> marshaller) {
experimentalPropByName.remove(marshaller.getPropertyName().toUpperCase());
experimentalPropByClass.remove(marshaller.getPropertyClass());
experimentalPropByQName.remove(marshaller.getQName());
}
/**
* Convenience method for getting the marshaller of the root iCalendar
* component ("VCALENDAR").
* @return the marshaller
*/
public static ICalendarMarshaller getICalendarMarshaller() {
return (ICalendarMarshaller) standardCompByClass.get(ICalendar.class);
}
private static void registerStandard(ICalComponentMarshaller<? extends ICalComponent> marshaller) {
standardCompByName.put(marshaller.getComponentName().toUpperCase(), marshaller);
standardCompByClass.put(marshaller.getComponentClass(), marshaller);
}
private static void registerStandard(ICalPropertyMarshaller<? extends ICalProperty> marshaller) {
standardPropByName.put(marshaller.getPropertyName().toUpperCase(), marshaller);
standardPropByClass.put(marshaller.getPropertyClass(), marshaller);
standardPropByQName.put(marshaller.getQName(), marshaller);
}
} |
package bj.pranie.controller;
import bj.pranie.dao.ReservationDao;
import bj.pranie.dao.WashTimeDao;
import bj.pranie.entity.Reservation;
import bj.pranie.entity.User;
import bj.pranie.entity.WashTime;
import bj.pranie.entity.myEnum.UserRole;
import bj.pranie.model.TimeWeekModel;
import bj.pranie.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Controller
@RequestMapping("/week")
public class WeekController {
private static final int RESET_TIME = 10;
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
private static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
@Autowired
private ReservationDao reservationDao;
@Autowired
private WashTimeDao washTimeDao;
@RequestMapping(method = RequestMethod.GET)
public String week(Model model) throws ParseException {
String weekId = getCurrentWeekId();
setModel(weekId, model);
return "wm/week";
}
@RequestMapping(path = "/{weekId}", method = RequestMethod.GET)
public String week(@PathVariable String weekId, Model model) throws ParseException {
setModel(weekId, model);
return "wm/week";
}
// private
private enum WEEK_TYPE {
PREV, NEXT
}
private void setModel(String weekId, Model model) {
model.addAttribute("weekId", weekId);
if (isAuthAdmin() || isBeforeCurrentWeekId(weekId)) {
model.addAttribute("nextWeekId", getSpecificWeekId(weekId, WEEK_TYPE.NEXT));
}
model.addAttribute("prevWeekId", getSpecificWeekId(weekId, WEEK_TYPE.PREV));
model.addAttribute("weekFrame", getWeekFrame(weekId));
model.addAttribute("wmFree", getWmFree(weekId));
model.addAttribute("timesWeek", getWeekReservations(weekId));
model.addAttribute("user", SecurityContextHolder.getContext().getAuthentication().getPrincipal());
}
private boolean isAuthAdmin() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof User) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (user.getRole() == UserRole.ADMIN) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/*
WeekId = year-weekOfYear
*/
private String getCurrentWeekId() {
Calendar calendar = TimeUtil.getCalendar();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setTime(new Date());
int time = calendar.get(Calendar.HOUR_OF_DAY);
int today = calendar.get(Calendar.DAY_OF_WEEK);
if (today == Calendar.SUNDAY && time > RESET_TIME) {
calendar.add(Calendar.DAY_OF_WEEK, 1);
} else {
calendar.add(Calendar.DAY_OF_WEEK, -today + Calendar.MONDAY);
}
return calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.WEEK_OF_YEAR);
}
private boolean isBeforeCurrentWeekId(String weekId) {
try {
int year = Integer.parseInt(weekId.split("-")[0]);
int week = Integer.parseInt(weekId.split("-")[1]);
Calendar calendar = TimeUtil.getCalendar();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.WEEK_OF_YEAR, week);
String currentWeekId = getCurrentWeekId();
int currentYear = Integer.parseInt(currentWeekId.split("-")[0]);
int currentWeek = Integer.parseInt(currentWeekId.split("-")[1]);
Calendar currentCalendar = TimeUtil.getCalendar();
currentCalendar.set(Calendar.YEAR, currentYear);
currentCalendar.set(Calendar.WEEK_OF_YEAR, currentWeek);
return calendar.before(currentCalendar);
} catch (Exception e) {
return false;
}
}
private String getSpecificWeekId(String weekId, WEEK_TYPE week_type) {
Calendar calendar = TimeUtil.getCalendar();
int year = Integer.parseInt(weekId.split("-")[0]);
int week = Integer.parseInt(weekId.split("-")[1]);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.WEEK_OF_YEAR, week);
switch (week_type) {
case NEXT:
calendar.add(Calendar.WEEK_OF_YEAR, 1);
break;
case PREV:
calendar.add(Calendar.WEEK_OF_YEAR, -1);
break;
}
return calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.WEEK_OF_YEAR);
}
private String getWeekFrame(String weekId) {
Calendar calendar = TimeUtil.getCalendar();
int year = Integer.parseInt(weekId.split("-")[0]);
int weekOfTheYear = Integer.parseInt(weekId.split("-")[1]);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.WEEK_OF_YEAR, weekOfTheYear);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
String weekFrame = dateFormat.format(calendar.getTime()) + " - ";
calendar.add(Calendar.DAY_OF_MONTH, 6);
weekFrame += dateFormat.format(calendar.getTime());
return weekFrame;
}
public List<TimeWeekModel> getWeekReservations(String weekId) {
List<TimeWeekModel> timeWeekModels = new ArrayList<>();
List<String> weekDays = getWeekDays(weekId);
List<WashTime> washTimes = getWashTimes();
for (WashTime washTime : washTimes
) {
TimeWeekModel timeWeekModel = new TimeWeekModel();
String fromTime = timeFormat.format(washTime.getFromTime());
String toTime = timeFormat.format(washTime.getToTime());
timeWeekModel.setTime(fromTime + " - " + toTime);
List<TimeWeekModel.WmDate> wmDates = new ArrayList<>();
for (String date : weekDays) {
TimeWeekModel.WmDate wmDate = timeWeekModel.new WmDate();
wmDate.setDate(date);
boolean isPast = TimeUtil.isPast(fromTime, date);
List<Reservation> reservations = getWmFree(washTime.getId(), date);
int wmFree = 3;
if (isPast) {
wmFree = 0;
} else {
wmFree -= reservations.size();
}
wmDate.setWmFree(wmFree);
wmDate.setColor(getCellColor(wmFree, isPast, isMyReservation(reservations)));
wmDates.add(wmDate);
}
timeWeekModel.setDates(wmDates);
timeWeekModels.add(timeWeekModel);
}
return timeWeekModels;
}
private List<WashTime> getWashTimes() {
List<WashTime> washTimes = new ArrayList<>();
Iterator<WashTime> washTimeIterator = washTimeDao.findAll().iterator();
while (washTimeIterator.hasNext())
washTimes.add(washTimeIterator.next());
return washTimes;
}
boolean isMyReservation(List<Reservation> reservations) {
//TODO:
return false;
}
private List<String> getWeekDays(String weekId) {
List<String> daysOfWeek = new ArrayList<>();
int year = Integer.parseInt(weekId.split("-")[0]);
int weekOfYear = Integer.parseInt(weekId.split("-")[1]);
Calendar now = TimeUtil.getCalendar();
now.set(Calendar.WEEK_OF_YEAR, weekOfYear);
now.set(Calendar.YEAR, year);
now.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
for (int i = 0; i < 6; i++) {
daysOfWeek.add(dateFormat.format(now.getTime()));
now.add(Calendar.DAY_OF_MONTH, 1);
}
return daysOfWeek;
}
private List<Reservation> getWmFree(long washTimeId, String date) {
java.sql.Date sqlDate = null;
try {
sqlDate = new java.sql.Date(dateFormat.parse(date).getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return reservationDao.findByWashTimeIdAndDate(washTimeId, sqlDate);
}
private Long getWmFree(String weekId) {
Long wmFree = washTimeDao.count() * 6 * 3;
String weekFrame = getWeekFrame(weekId);
java.sql.Date fromDate = new java.sql.Date(TimeUtil.getCalendar().getTime().getTime());
java.sql.Date toDate = null;
try {
toDate = new java.sql.Date(dateFormat.parse(weekFrame.split("-")[1]).getTime());
} catch (ParseException e) {
e.printStackTrace();
}
wmFree -= reservationDao.countByDatesBetween(fromDate, toDate);
return wmFree;
}
private String getCellColor(int freeSpace, boolean past, boolean myReservation) {
if (past) {
return "#FF0000";
} else if (myReservation) {
return "#FFF200";
}
switch (freeSpace) {
case 3:
return "#1E9600";
case 2:
return "#408000";
case 1:
return "#2C5900";
default:
return "#FF0000";
}
}
} |
package cc.notsoclever.tools;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MyRouteBuilder extends RouteBuilder {
public void configure() {
from("restlet:///tags/{orgName}/{projectName}?restletMethods=get")
.to("log:bar")
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
String on = exchange.getIn().getHeader("orgName", String.class);
String cn = exchange.getIn().getHeader("projectName", String.class);
Versions versions = new Versions(on, cn);
ObjectMapper mapper = new ObjectMapper();
String tags = versions.getTags();
String json = mapper.writeValueAsString(VersionsUtils.extractVersions(tags, cn));
exchange.getOut().setBody(json);
exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/json");
}
});
from("restlet:///compare/{orgName}/{projectName}/{v1}/{v2}?restletMethods=get")
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
String on = exchange.getIn().getHeader("orgName", String.class);
String cn = exchange.getIn().getHeader("projectName", String.class);
String v1 = exchange.getIn().getHeader("v1", String.class);
String v2 = exchange.getIn().getHeader("v2", String.class);
Versions versions = new Versions(on, cn);
versions.compare(v1, v2);
ObjectMapper mapper = new ObjectMapper();
exchange.getOut().setBody(mapper.writeValueAsString(versions));
exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/json");
}
});
from("restlet:///foo/{orgName}/{projectName}?restletMethods=get")
.to("log:foo")
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);
System.out.println(System.getProperty("user.dir"));
File folder = new File(System.getProperty("user.dir" + "/target"));
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
s = s + "File " + listOfFiles[i].getName();
} else if (listOfFiles[i].isDirectory()) {
s = s + "Directory " + listOfFiles[i].getName();
}
}
Message out = exchange.getOut();
out.setBody(s);
/*
InputStream input = getClass().getClassLoader().getResourceAsStream("index.html");
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuffer sb = new StringBuffer();
//String s;
while ((s = reader.readLine()) != null) {
sb.append(s);
}
out.setBody(sb.toString());
*/
}
});
}
} |
package com.akdeniz.googleplaycrawler;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import javax.crypto.Cipher;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import com.akdeniz.googleplaycrawler.GooglePlay.AndroidBuildProto;
import com.akdeniz.googleplaycrawler.GooglePlay.AndroidCheckinProto;
import com.akdeniz.googleplaycrawler.GooglePlay.AndroidCheckinRequest;
import com.akdeniz.googleplaycrawler.GooglePlay.DeviceConfigurationProto;
import com.akdeniz.googleplaycrawler.misc.Base64;
import com.akdeniz.googleplaycrawler.misc.DummyX509TrustManager;
/**
*
* @author akdeniz
*
*/
public class Utils {
private static final String GOOGLE_PUBLIC_KEY = "AAAAgMom/1a/v0lblO2Ubrt60J2gcuXSljGFQXgcyZWveWLEwo6prwgi3"
+ "iJIZdodyhKZQrNWp5nKJ3srRXcUW+F1BD3baEVGcmEgqaLZUNBjm057pKRI16kB0YppeGx5qIQ5QjKzsR8ETQbKLNWgRY0Q"
+ "RNVz34kMJR3P/LgHax/6rmf5AAAAAwEAAQ==";
/**
* Parses key-value response into map.
*/
public static Map<String, String> parseResponse(String response) {
Map<String, String> keyValueMap = new HashMap<String, String>();
StringTokenizer st = new StringTokenizer(response, "\n\r");
while (st.hasMoreTokens()) {
String[] keyValue = st.nextToken().split("=");
// Note to self: the original implementation did not check for array length.
// Nowadays it is possible to get keys with empty values and therefore an
// ArrayIndexOutOfBoundsException. Since we are only interested in "Auth=",
// we can simply ignore everything that's not a k/v pair.
if (keyValue.length==2) {
keyValueMap.put(keyValue[0], keyValue[1]);
}
else {
//System.err.println("Utils.paseResponse: "+response);
}
}
return keyValueMap;
}
private static PublicKey createKey(byte[] keyByteArray) throws Exception {
int modulusLength = readInt(keyByteArray, 0);
byte[] modulusByteArray = new byte[modulusLength];
System.arraycopy(keyByteArray, 4, modulusByteArray, 0, modulusLength);
BigInteger modulus = new BigInteger(1, modulusByteArray);
int exponentLength = readInt(keyByteArray, modulusLength + 4);
byte[] exponentByteArray = new byte[exponentLength];
System.arraycopy(keyByteArray, modulusLength + 8, exponentByteArray, 0, exponentLength);
BigInteger publicExponent = new BigInteger(1, exponentByteArray);
return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
}
/**
* Encrypts given string with Google Public Key.
*
*/
public static String encryptString(String str2Encrypt) throws Exception {
byte[] keyByteArray = Base64.decode(GOOGLE_PUBLIC_KEY, Base64.DEFAULT);
byte[] header = new byte[5];
byte[] digest = MessageDigest.getInstance("SHA-1").digest(keyByteArray);
header[0] = 0;
System.arraycopy(digest, 0, header, 1, 4);
PublicKey publicKey = createKey(keyByteArray);
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA1ANDMGF1PADDING");
byte[] bytes2Encrypt = str2Encrypt.getBytes("UTF-8");
int len = ((bytes2Encrypt.length - 1) / 86) + 1;
byte[] cryptedBytes = new byte[len * 133];
for (int j = 0; j < len; j++) {
cipher.init(1, publicKey);
byte[] arrayOfByte4 = cipher.doFinal(bytes2Encrypt, j * 86, (bytes2Encrypt.length - j * 86));
System.arraycopy(header, 0, cryptedBytes, j * 133, header.length);
System.arraycopy(arrayOfByte4, 0, cryptedBytes, j * 133 + header.length, arrayOfByte4.length);
}
return Base64.encodeToString(cryptedBytes, 10);
}
private static int readInt(byte[] data, int offset) {
return (0xFF & data[offset]) << 24 | (0xFF & data[(offset + 1)]) << 16 | (0xFF & data[(offset + 2)]) << 8
| (0xFF & data[(offset + 3)]);
}
/**
* Reads all contents of the input stream.
*
*/
public static byte[] readAll(InputStream inputStream) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int k = 0;
for (; (k = inputStream.read(buffer)) != -1;) {
outputStream.write(buffer, 0, k);
}
return outputStream.toByteArray();
}
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);
}
public static byte[] hexToBytes(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
}
return data;
}
public static Scheme getMockedScheme() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { new DummyX509TrustManager() }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
Scheme https = new Scheme("https", 443, sf);
return https;
}
public static AndroidCheckinRequest generateAndroidCheckinRequest() {
return AndroidCheckinRequest
.newBuilder()
.setId(0)
.setCheckin(
AndroidCheckinProto
.newBuilder()
.setBuild(
AndroidBuildProto.newBuilder()
.setId("samsung/dream2ltexx/dream2lte:7.0/NRD90M/G955FXXU1AQGB:user/release-keys")
.setProduct("dream2ltexx").setCarrier("Google").setRadio("I9300XXALF2")
.setBootloader("PRIMELA03").setClient("android-google")
.setTimestamp(new Date().getTime() / 1000).setGoogleServices(16).setDevice("dream2lte")
.setSdkVersion(26).setModel("SM-G955F").setManufacturer("Samsung")
.setBuildProduct("dream2ltexx").setOtaInstalled(false)).setLastCheckinMsec(0)
.setCellOperator("310260").setSimOperator("310260").setRoaming("mobile-notroaming")
.setUserNumber(0)).setLocale("en_US").setTimeZone("Europe/Berlin").setVersion(3)
.setDeviceConfiguration(getDeviceConfigurationProto()).setFragment(0).build();
}
public static DeviceConfigurationProto getDeviceConfigurationProto() {
return DeviceConfigurationProto
.newBuilder()
.setTouchScreen(3)
.setKeyboard(1)
.setNavigation(1)
.setScreenLayout(2)
.setHasHardKeyboard(false)
.setHasFiveWayNavigation(false)
.setScreenDensity(320)
.setGlEsVersion(196610)
.addAllSystemSharedLibrary(
Arrays.asList("android.test.runner", "com.android.future.usb.accessory", "com.android.location.provider",
"com.android.nfc_extras", "com.google.android.maps", "com.google.android.media.effects",
"com.google.widevine.software.drm", "javax.obex"))
.addAllSystemAvailableFeature(
Arrays.asList("android.hardware.bluetooth","android.hardware.bluetooth_le", "android.hardware.camera",
"android.hardware.camera.autofocus", "android.hardware.camera.flash",
"android.hardware.camera.front", "android.hardware.faketouch", "android.hardware.location",
"android.hardware.location.gps", "android.hardware.location.network",
"android.hardware.microphone", "android.hardware.nfc", "android.hardware.screen.landscape",
"android.hardware.screen.portrait", "android.hardware.sensor.accelerometer",
"android.hardware.sensor.barometer", "android.hardware.sensor.compass",
"android.hardware.sensor.gyroscope", "android.hardware.sensor.light",
"android.hardware.sensor.proximity", "android.hardware.telephony",
"android.hardware.telephony.gsm", "android.hardware.touchscreen",
"android.hardware.touchscreen.multitouch", "android.hardware.touchscreen.multitouch.distinct",
"android.hardware.touchscreen.multitouch.jazzhand", "android.hardware.usb.accessory",
"android.hardware.usb.host", "android.hardware.wifi", "android.hardware.wifi.direct",
"android.software.live_wallpaper", "android.software.sip", "android.software.sip.voip",
"com.cyanogenmod.android", "com.cyanogenmod.nfc.enhanced", "org.cyanogenmod.theme",
"com.google.android.feature.GOOGLE_BUILD", "com.nxp.mifare", "com.tmobile.software.themes"))
.addAllNativePlatform(Arrays.asList("armeabi-v7a", "armeabi"))
.setScreenWidth(720)
.setScreenHeight(1184)
.addAllSystemSupportedLocale(
Arrays.asList("af", "af_ZA", "am", "am_ET", "ar", "ar_EG", "bg", "bg_BG", "ca", "ca_ES", "cs", "cs_CZ",
"da", "da_DK", "de", "de_AT", "de_CH", "de_DE", "de_LI", "el", "el_GR", "en", "en_AU", "en_CA",
"en_GB", "en_NZ", "en_SG", "en_US", "es", "es_ES", "es_US", "fa", "fa_IR", "fi", "fi_FI", "fr",
"fr_BE", "fr_CA", "fr_CH", "fr_FR", "hi", "hi_IN", "hr", "hr_HR", "hu", "hu_HU", "in", "in_ID",
"it", "it_CH", "it_IT", "iw", "iw_IL", "ja", "ja_JP", "ko", "ko_KR", "lt", "lt_LT", "lv",
"lv_LV", "ms", "ms_MY", "nb", "nb_NO", "nl", "nl_BE", "nl_NL", "pl", "pl_PL", "pt", "pt_BR",
"pt_PT", "rm", "rm_CH", "ro", "ro_RO", "ru", "ru_RU", "sk", "sk_SK", "sl", "sl_SI", "sr",
"sr_RS", "sv", "sv_SE", "sw", "sw_TZ", "th", "th_TH", "tl", "tl_PH", "tr", "tr_TR", "ug",
"ug_CN", "uk", "uk_UA", "vi", "vi_VN", "zh_CN", "zh_TW", "zu", "zu_ZA"))
.addAllGlExtension(
Arrays.asList("GL_EXT_debug_marker", "GL_EXT_discard_framebuffer", "GL_EXT_multi_draw_arrays",
"GL_EXT_shader_texture_lod", "GL_EXT_texture_format_BGRA8888",
"GL_IMG_multisampled_render_to_texture", "GL_IMG_program_binary", "GL_IMG_read_format",
"GL_IMG_shader_binary", "GL_IMG_texture_compression_pvrtc", "GL_IMG_texture_format_BGRA8888",
"GL_IMG_texture_npot", "GL_IMG_vertex_array_object", "GL_OES_EGL_image",
"GL_OES_EGL_image_external", "GL_OES_blend_equation_separate", "GL_OES_blend_func_separate",
"GL_OES_blend_subtract", "GL_OES_byte_coordinates", "GL_OES_compressed_ETC1_RGB8_texture",
"GL_OES_compressed_paletted_texture", "GL_OES_depth24", "GL_OES_depth_texture",
"GL_OES_draw_texture", "GL_OES_egl_sync", "GL_OES_element_index_uint",
"GL_OES_extended_matrix_palette", "GL_OES_fixed_point", "GL_OES_fragment_precision_high",
"GL_OES_framebuffer_object", "GL_OES_get_program_binary", "GL_OES_mapbuffer",
"GL_OES_matrix_get", "GL_OES_matrix_palette", "GL_OES_packed_depth_stencil",
"GL_OES_point_size_array", "GL_OES_point_sprite", "GL_OES_query_matrix", "GL_OES_read_format",
"GL_OES_required_internalformat", "GL_OES_rgb8_rgba8", "GL_OES_single_precision",
"GL_OES_standard_derivatives", "GL_OES_stencil8", "GL_OES_stencil_wrap",
"GL_OES_texture_cube_map", "GL_OES_texture_env_crossbar", "GL_OES_texture_float",
"GL_OES_texture_half_float", "GL_OES_texture_mirrored_repeat", "GL_OES_vertex_array_object",
"GL_OES_vertex_half_float")).build();
}
} |
package com.annelieseschools.minecraft;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
@Mod(modid="AndrewMods", version="1.8")
public class Main extends BaseEventBus {
public static Block enderBlock;
/**
* In order to add a new mod to our list we'll use
* the method addMod
*
* addMod(new BlockBreakMessage());
*
*/
@EventHandler
public void init(FMLInitializationEvent event) {
addMod(new BlockBreakMessage());
addMod(new PigsDroppingDiamonds());
// addMod(new BiggerTNTExplosion());
addMod(new SheepsDontDie());
addMod(new BlockFillerPositionSelector());
addMod(new SuperJump());
enderBlock = new EnderBlock();
// enderBlock = new BlockChanger();
// enderBlock = new TheMajesticEnderiumBlock();
// enderBlock = new EnderIngotFromEnderBlock();
GameRegistry.registerBlock(enderBlock, "enderBlock");
Item enderBlockItem = GameRegistry.findItem("andrewmods", "enderBlock");
ModelResourceLocation enderBlockModel = new ModelResourceLocation(
"andrewmods:enderBlock", "inventory");
Minecraft.getMinecraft().getRenderItem().getItemModelMesher()
.register(enderBlockItem, 0, enderBlockModel);
}
@EventHandler
public void postInit(FMLPostInitializationEvent e) {
FMLCommonHandler.instance().bus().register(new SpeedTicker());
FMLCommonHandler.instance().bus().register(new Trampoline());
MinecraftForge.EVENT_BUS.register(new SpeedTicker());
MinecraftForge.EVENT_BUS.register(new Trampoline());
}
@EventHandler
public void registerCommands(FMLServerStartingEvent event) {
event.registerServerCommand(new SuperJumpCommand());
event.registerServerCommand(new FlamingPigs());
event.registerServerCommand(new BlockFillerCommand());
}
} |
package com.carpentersblocks.util;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import org.apache.logging.log4j.Level;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier;
/**
* Stores attribute and unique identifier for validation purposes.
*/
public class Attribute {
private static final String TAG_UNIQUE_ID = "cbUniqueId";
private ItemStack _itemStack;
private String _uniqueId;
private boolean _error;
public Attribute(ItemStack itemStack) {
if (itemStack != null && itemStack.getItem() != null) {
this._itemStack = itemStack;
_uniqueId = GameRegistry.findUniqueIdentifierFor(itemStack.getItem()).toString();
}
}
public ItemStack getItemStack() {
return _itemStack;
}
public String getUniqueId() {
return _uniqueId;
}
/**
* Write the stack fields to a NBT object. Return the new NBT object.
*/
public NBTTagCompound writeToNBT(NBTTagCompound nbt)
{
_itemStack.writeToNBT(nbt);
nbt.setString(TAG_UNIQUE_ID, _uniqueId);
return nbt;
}
public static Attribute loadAttributeFromNBT(NBTTagCompound nbt)
{
ItemStack itemStack = ItemStack.loadItemStackFromNBT(nbt);
if (itemStack == null) {
String uuid = nbt.getString(TAG_UNIQUE_ID);
if (uuid.contains(":")) {
UniqueIdentifier uniqueId = new UniqueIdentifier(uuid);
itemStack = GameRegistry.findItemStack(uniqueId.modId, uniqueId.name, 1);
if (itemStack != null) {
int dmg = nbt.getShort("Damage");
itemStack.setItemDamage(dmg);
ModLogger.log(Level.WARN, "Invalid Id for attribute '" + uniqueId.toString() + "' corrected.");
} else {
ModLogger.log(Level.WARN, "Block attribute '" + uniqueId.toString() + "' was unable to be recovered. Was a mod removed?");
}
} else {
ModLogger.log(Level.WARN, "Unable to resolve attribute '" + uuid + "'");
}
}
return new Attribute(itemStack);
}
} |
package com.decentralizeddatabase.reno;
import com.decentralizeddatabase.errors.*;
import com.decentralizeddatabase.reno.crypto.Hasher;
import com.decentralizeddatabase.reno.filetable.*;
import com.decentralizeddatabase.reno.jailcellaccess.*;
import com.decentralizeddatabase.utils.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.json.JSONObject;
public class Reno {
private static final Logger LOGGER = LoggerFactory.getLogger(Reno.class);
public static void listAll(final DecentralizedDBRequest request,
final DecentralizedDBResponse response) throws BadRequest {
LOGGER.info("Processing listAll");
final String user = Validations.validateUser(request.getUser());
final Collection<FileData> fileList = FileTable.getFiles(user);
final List<String> filenames = new ArrayList<>();
for (FileData file : fileList) {
filenames.add(file.getFilename());
}
response.setList(filenames);
}
public static void read(final DecentralizedDBRequest request,
final DecentralizedDBResponse response) throws BadRequest,
EncryptionError,
FileNotFoundError,
JailCellServerError {
final String filename = request.getFilename();
final String user = Validations.validateUser(request.getUser());
final String rawSecretKey = Validations.validateRawSecretKey(request.getSecretKey());
final String secretKey = Hasher.createSecretKey(rawSecretKey);
final long numBlocks = FileTable.getFile(user, filename).getFileSize();
final List<String> keys = DataManipulator.createKeys(secretKey, filename, user, numBlocks);
List<FileBlock> blocks = retrieve(keys);
final String file = DataManipulator.makeFile(blocks, secretKey);
response.setData(file);
}
public static void write(final DecentralizedDBRequest request,
final DecentralizedDBResponse response) throws BadRequest,
EncryptionError,
FileNotFoundError,
JailCellServerError {
final String file = request.getFile();
final String filename = request.getFilename();
final String user = Validations.validateUser(request.getUser());
final String rawSecretKey = Validations.validateRawSecretKey(request.getSecretKey());
final String secretKey = Hasher.createSecretKey(rawSecretKey);
LOGGER.info("Processing write request for {}", filename);
final List<FileBlock> blocks = DataManipulator.createBlocks(secretKey, file);
final List<String> keys = DataManipulator.createKeys(secretKey, filename, user, blocks.size());
if (FileTable.containsFile(user, filename)) {
LOGGER.info("{} already exists, overwriting...", filename);
final long fileSize = FileTable.getFile(user, filename).getFileSize();
final List<String> oldKeys = DataManipulator.createKeys(secretKey, filename, user, fileSize);
sendForDelete(oldKeys);
}
sendForWrite(blocks, keys);
FileTable.addFile(user, filename, blocks.size());
}
public static void delete(final DecentralizedDBRequest request,
final DecentralizedDBResponse response) throws BadRequest,
FileNotFoundError,
JailCellServerError {
final String filename = request.getFilename();
final String user = Validations.validateUser(request.getUser());
final String rawSecretKey = Validations.validateRawSecretKey(request.getSecretKey());
final String secretKey = Hasher.createSecretKey(rawSecretKey);
final long numBlocks = FileTable.getFile(user, filename).getFileSize();
final List<String> blockKeys = DataManipulator.createKeys(secretKey, filename, user, numBlocks);
sendForDelete(blockKeys);
FileTable.removeFile(user, filename);
}
//Refactor and break up after confirmed working
//TODO: Magic numbers (strings??)
private static void sendForWrite(final List<FileBlock> blocks, final List<String> keys) throws JailCellServerError {
final List<JailCellInfo> jailCells = JailCellAccess.getJailCells();
final int numCells = jailCells.size();
final List<List<String>> brokenUpBlocks = new ArrayList<>(Collections.nCopies(numCells, new ArrayList<>()));
int keyIdx = 0;
final List<List<String>> brokenUpKeys = new ArrayList<>(Collections.nCopies(numCells, new ArrayList<>()));
final Random rnd = new Random();//todo set seed?
for (FileBlock block : blocks) {
final String encoded = block.encodeOrderIntoBlock();
final String currKey = keys.get(keyIdx++);
final int idx = rnd.nextInt(numCells);
brokenUpBlocks.get(idx).add(encoded);
brokenUpKeys.get(idx).add(currKey);
}
//TODO: Thread this
for (int i = 0; i < numCells; i++) {
final String jailCellUrl = jailCells.get(i).url;
final List<String> currKeys = brokenUpKeys.get(i);
final List<String> currBlocks = brokenUpBlocks.get(i);
final JSONObject toPost = new JSONObject();
toPost.put("method", "write");
toPost.put("keys", currKeys);
toPost.put("blocks", currBlocks);
HttpUtility.postToJailCell(toPost, jailCellUrl);
}
}
private static void sendForDelete(final List<String> keys) throws JailCellServerError {
final List<JailCellInfo> jailCells = JailCellAccess.getJailCells();
//Thread this
for (JailCellInfo jailCell : jailCells) {
final String jailCellUrl = jailCell.url;
final JSONObject toPost = new JSONObject();
toPost.put("method", "delete");
toPost.put("keys", keys);
HttpUtility.postToJailCell(toPost, jailCellUrl);
}
}
private static List<FileBlock> retrieve(final List<String> keys) throws JailCellServerError {
final List<JailCellInfo> jailCells = JailCellAccess.getJailCells();
final List<String> encodedFileStrings = new ArrayList<>();//Needs to be threadsafe
//Thread this
for (JailCellInfo jailCell : jailCells) {
final String jailCellUrl = jailCell.url;
JSONObject toPost = new JSONObject();
toPost.put("method", "read");
toPost.put("keys", keys);
JSONObject jsonObj = HttpUtility.postToJailCellWithResponse(toPost, jailCellUrl);
List<String> blocks = (List<String>)(jsonObj.get("blocks"));
encodedFileStrings.addAll(blocks);
}
//TODO: Streams?
final List<FileBlock> fileBlocks = new ArrayList<>();
for (String encodedString : encodedFileStrings) {
fileBlocks.add(new FileBlock(encodedString));
}
return fileBlocks;
}
} |
package com.demigodsrpg.demigames.game;
import com.demigodsrpg.demigames.impl.Demigames;
import com.demigodsrpg.demigames.session.Session;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import java.util.Optional;
public interface Game extends Listener {
String getName();
String getDirectory();
boolean canPlace();
boolean canBreak();
boolean canDrop();
boolean canLateJoin();
default boolean hasSpectateChat() {
return false;
}
int getMinimumPlayers();
default int getNumberOfTeams() {
return 0;
}
default int getTotalRounds() {
return 1;
}
void onWin(Session session, Player player);
void onLose(Session session, Player player);
void onTie(Session session, Player player);
void onPlayerJoin(Player player);
void onPlayerQuit(Player player);
void setupLocations(Session session);
default void onServerStart() {
}
default void onServerStop() {
}
default ConfigurationSection getConfig() {
ConfigurationSection parent = Demigames.getInstance().getConfig();
if (parent.getKeys(false).contains(getName())) {
return parent.getConfigurationSection(getName());
}
return parent.createSection(getName());
}
default Optional<Session> checkPlayer(Player player) {
Optional<Session> opSession = Demigames.getSessionRegistry().getSession(player);
if (opSession.isPresent() && opSession.get().getGame().isPresent()) {
if (opSession.get().getGame().get().equals(this)) {
return opSession;
}
}
return Optional.empty();
}
} |
package com.easternedgerobotics.rov;
import com.easternedgerobotics.rov.control.ExponentialMotionScale;
import com.easternedgerobotics.rov.event.BroadcastEventPublisher;
import com.easternedgerobotics.rov.event.EventPublisher;
import com.easternedgerobotics.rov.fx.MainView;
import com.easternedgerobotics.rov.fx.SensorView;
import com.easternedgerobotics.rov.fx.ThrusterPowerSlidersView;
import com.easternedgerobotics.rov.fx.ViewLoader;
import com.easternedgerobotics.rov.io.Joystick;
import com.easternedgerobotics.rov.io.Joysticks;
import com.easternedgerobotics.rov.value.AftCameraSpeedValue;
import javafx.application.Application;
import javafx.stage.Stage;
import org.pmw.tinylog.Logger;
import rx.Observable;
import rx.broadcast.SingleSourceFifoOrder;
import rx.broadcast.UdpBroadcast;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;
public final class Topside extends Application {
private static final int AFT_CAMERA_MOTOR_FORWARD_JOYSTICK_BUTTON = 6;
private static final int AFT_CAMERA_MOTOR_REVERSE_JOYSTICK_BUTTON = 4;
private static final float AFT_CAMERA_MOTOR_ROTATION_SPEED = 0.3f;
private EventPublisher eventPublisher;
private ViewLoader viewLoader;
@Override
public void init() throws SocketException, UnknownHostException {
final InetAddress broadcastAddress = InetAddress.getByName("192.168.88.255");
final int broadcastPort = BroadcastEventPublisher.DEFAULT_BROADCAST_PORT;
final DatagramSocket socket = new DatagramSocket(broadcastPort);
eventPublisher = new BroadcastEventPublisher(new UdpBroadcast<>(
socket, broadcastAddress, broadcastPort, new SingleSourceFifoOrder<>(SingleSourceFifoOrder.DROP_LATE)));
viewLoader = new ViewLoader(new HashMap<Class<?>, Object>() {
{
put(EventPublisher.class, eventPublisher);
}
});
Joysticks.logitechExtreme3dPro().subscribe(this::joystickInitialization);
Logger.info("Initialised");
}
@Override
public void start(final Stage stage) {
Logger.info("Starting");
viewLoader.loadIntoStage(MainView.class, stage);
stage.setTitle("Control Software");
stage.show();
final Stage thrusterStage = viewLoader.load(ThrusterPowerSlidersView.class);
thrusterStage.setTitle("Thruster Power");
thrusterStage.initOwner(stage);
thrusterStage.show();
final Stage sensorStage = viewLoader.load(SensorView.class);
sensorStage.setTitle("Sensors 'n' stuff");
sensorStage.initOwner(stage);
sensorStage.show();
Logger.info("Started");
}
@Override
public void stop() {
Logger.info("Stopping");
eventPublisher.stop();
Logger.info("Stopped");
}
/**
* Initializes the given joystick.
* @param joystick the joystick
*/
@SuppressWarnings("checkstyle:avoidinlineconditionals")
private void joystickInitialization(final Joystick joystick) {
final ExponentialMotionScale scale = new ExponentialMotionScale();
final Observable<AftCameraSpeedValue> aftCameraForward = joystick
.button(AFT_CAMERA_MOTOR_FORWARD_JOYSTICK_BUTTON)
.map(value -> new AftCameraSpeedValue(value ? AFT_CAMERA_MOTOR_ROTATION_SPEED : 0));
final Observable<AftCameraSpeedValue> aftCameraReverse = joystick
.button(AFT_CAMERA_MOTOR_REVERSE_JOYSTICK_BUTTON)
.map(value -> new AftCameraSpeedValue(value ? -AFT_CAMERA_MOTOR_ROTATION_SPEED : 0));
joystick.axes().map(scale::apply).subscribe(eventPublisher::emit, Logger::error);
aftCameraForward.mergeWith(aftCameraReverse)
.subscribe(eventPublisher::emit, Logger::error);
}
public static void main(final String[] args) {
launch(args);
}
} |
package com.forgeessentials.chat;
import java.util.HashSet;
import java.util.IllegalFormatException;
import java.util.Set;
import net.minecraftforge.common.config.Configuration;
import com.forgeessentials.core.moduleLauncher.config.ConfigLoader.ConfigLoaderBase;
import com.forgeessentials.util.OutputHandler;
public class ChatConfig extends ConfigLoaderBase
{
private static final String CATEGORY = ModuleChat.CONFIG_CATEGORY;
private static final String CAT_GM = CATEGORY + ".Gamemodes";
public static final String CHAT_FORMAT_HELP = "Format for chat. Always needs to contain all 5 \"%s\" placeholders like the default!";
private static final String MUTEDCMD_HELP = "All commands in here will be blocked if the player is muted.";
private static final String WELCOME_MESSAGE = "Welcome messages for new players. Can be colour formatted (supports script arguments)";
private static final String LOGIN_MESSAGE = "Login message shown each time the player logs in (supports script arguments)";
private static final String DEFAULT_WELCOME_MESSAGE = "New player @player joined the server!";
private static final String[] DEFAULT_LOGIN_MESSAGE = new String[] { "Welcome @player.", "This server is running ForgeEssentials" };
public static String gamemodeCreative;
public static String gamemodeAdventure;
public static String gamemodeSurvival;
public static String chatFormat = "%s%s<%s>%s%s ";
public static String welcomeMessage;
public static String[] loginMessage;
public static Set<String> mutedCommands = new HashSet<>();
@Override
public void load(Configuration config, boolean isReload)
{
config.addCustomCategoryComment("Chat", "Chat configuration");
try
{
chatFormat = config.get("Chat", "ChatFormat", "%s%s<%s>%s%s ", CHAT_FORMAT_HELP).getString();
String.format(chatFormat, "", "", "", "", "");
}
catch (IllegalFormatException e)
{
OutputHandler.felog.severe("Invalid chat format specified in chat config!");
chatFormat = "%s%s<%s>%s%s ";
}
welcomeMessage = config.get("Chat", "WelcomeMessage", DEFAULT_WELCOME_MESSAGE, WELCOME_MESSAGE).getString();
loginMessage = config.get("Chat", "LoginMessage", DEFAULT_LOGIN_MESSAGE, LOGIN_MESSAGE).getStringList();
config.addCustomCategoryComment(CAT_GM, "Gamemode names");
gamemodeSurvival = config.get(CAT_GM, "Survival", "survival").getString();
gamemodeCreative = config.get(CAT_GM, "Creative", "creative").getString();
gamemodeAdventure = config.get(CAT_GM, "Adventure", "adventure").getString();
mutedCommands.clear();
for (String cmd : config.get("Chat.mute", "mutedCommands", new String[] { "me" }, MUTEDCMD_HELP).getStringList())
mutedCommands.add(cmd);
ModuleChat.instance.setChatLogging(config.get(CATEGORY, "LogChat", true, "Log all chat messages").getBoolean(true));
}
@Override
public void save(Configuration config)
{
}
} |
package com.github.jhpoelen.fbob;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.tuple.Pair;
import ucar.ma2.InvalidRangeException;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class ConfigUtil {
private static final Logger LOG = Logger.getLogger(ConfigUtil.class.getName());
public static final String OUTPUT_DEFAULTS = "output.start.year;0;;\n" +
"output.file.prefix;osm;;\n" +
"output.dir.path;output;;\n" +
"output.recordfrequency.ndt;12;;\n" +
";;;\n" +
"# CSV separator (COMA, SEMICOLON, EQUALS, COLON, TAB);;;\n" +
"output.csv.separator;COMA;;\n" +
";;;\n" +
"# Save restart file;;;\n" +
"output.restart.enabled;false;;\n" +
"output.restart.recordfrequency.ndt;60;;\n" +
"output.restart.spinup;114;;\n" +
";;;\n" +
"# Biomass;;;\n" +
"output.biomass.enabled;true;;\n" +
"output.biomass.bysize.enabled;false;;\n" +
"output.biomass.byage.enabled;false;;\n" +
"# Abundance;;;\n" +
"output.abundance.enabled;false;;\n" +
"output.abundance.bysize.enabled;false;;\n" +
"output.abundance.byage.enabled;true;;\n" +
"# Mortality;;;\n" +
"output.mortality.enabled;true;;\n" +
"output.mortality.perSpecies.byAge.enabled;true;;\n" +
"output.mortality.perSpecies.bySize.enabled;false;;\n" +
"# Yield;;;\n" +
"output.yield.biomass.enabled;true;;\n" +
"output.yield.abundance.enabled;false;;\n" +
"output.yieldN.bySize.enabled;false;;\n" +
"output.yield.bySize.enabled;false;;\n" +
"output.yieldN.byAge.enabled;false;;\n" +
"output.yield.byAge.enabled;false;;\n" +
"# Size;;;\n" +
"output.size.enabled;true ;;\n" +
"output.size.catch.enabled;true ;;\n" +
"output.meanSize.byAge.enabled;false;;\n" +
"# TL;;;\n" +
"output.TL.enabled;true;;\n" +
"output.TL.catch.enabled;true;;\n" +
"output.biomass.byTL.enabled;true;;\n" +
"output.meanTL.bySize.enabled;false;;\n" +
"output.meanTL.byAge.enabled;false;;\n" +
"# Predation;;;\n" +
"output.diet.composition.enabled;true;;\n" +
"output.diet.composition.byAge.enabled;false;;\n" +
"output.diet.composition.bySize.enabled;false;;\n" +
"output.diet.pressure.enabled;true;;\n" +
"output.diet.pressure.byAge.enabled;false;;\n" +
"output.diet.pressure.bySize.enabled;false;;\n" +
"# Spatial;;;\n" +
"output.spatial.enabled;false;;\n" +
"output.spatial.ltl.enabled;false;;\n" +
";;;\n" +
"# Advanced parameters;;;\n" +
"# Whether to include step 0 of the simulation in the outputs;;;\n" +
"output.step0.include;false;;\n" +
"# Cutoff for biomass, abundance, mean size and mean trophic level outputs;;;";
public static void writeLine(OutputStream os, List<String> values, boolean leadingNewline) throws IOException {
List<String> escapedValues = new ArrayList<String>();
for (String value : values) {
escapedValues.add(StringEscapeUtils.escapeCsv(value));
}
String row = StringUtils.join(escapedValues, ";");
String line = leadingNewline ? ("\n" + row) : row;
IOUtils.copy(IOUtils.toInputStream(line, "UTF-8"), os);
}
public static void writeLine(OutputStream os, List<String> values) throws IOException {
writeLine(os, values, true);
}
public static void generateSeasonalReproductionFor(List<Group> groups, StreamFactory factory, ValueFactory valueFactory, Integer numberOfTimestepsPerYear) throws IOException {
OutputStream os = factory.outputStreamFor("osm_param-reproduction.csv");
for (int i = 0; i < groups.size(); i++) {
String reproductionFilename = reproductionFilename(i);
String paramName = "reproduction.season.file.sp" + i;
writeLine(os, Arrays.asList(paramName, reproductionFilename), i > 0);
}
List<Pair<Double, String>> months = Arrays.asList(
Pair.of(1.0 / 12.0, "Jan"),
Pair.of(2.0 / 12.0, "Feb"),
Pair.of(3.0 / 12.0, "Mar"),
Pair.of(4.0 / 12.0, "Apr"),
Pair.of(5.0 / 12.0, "May"),
Pair.of(6.0 / 12.0, "Jun"),
Pair.of(7.0 / 12.0, "Jul"),
Pair.of(8.0 / 12.0, "Aug"),
Pair.of(9.0 / 12.0, "Sep"),
Pair.of(10.0 / 12.0, "Oct"),
Pair.of(11.0 / 12.0, "Nov"),
Pair.of(12.0 / 12.0, "Dec"));
for (int i = 0; i < groups.size(); i++) {
double values[] = new double[numberOfTimestepsPerYear];
Arrays.fill(values, 0);
double valuesSum = 0.0;
OutputStream reprodOs = factory.outputStreamFor(reproductionFilename(i));
final Group group = groups.get(i);
writeLine(reprodOs, Arrays.asList("Time (year)", group.getName()), false);
for (int timeStep = 0; timeStep < numberOfTimestepsPerYear; timeStep++) {
for (Pair<Double, String> month : months) {
double upper = (double) (timeStep + 1) / numberOfTimestepsPerYear;
if (upper <= month.getLeft()) {
String reproductionForSpawningMonth = valueFactory.groupValueFor("spawning." + month.getRight(), group);
if (NumberUtils.isParsable(reproductionForSpawningMonth)) {
double value = Double.parseDouble(reproductionForSpawningMonth);
valuesSum += value;
values[timeStep]= value;
}
break;
}
}
}
if (values.length > 0) {
for (int timeStep = 0; timeStep < numberOfTimestepsPerYear; timeStep++) {
double valueNormalized = valuesSum == 0
? (1.0 / numberOfTimestepsPerYear)
: (values[timeStep] / valuesSum);
writeLine(reprodOs,
Arrays.asList(formatTimeStep(numberOfTimestepsPerYear, timeStep),
String.format("%.3f", valueNormalized)));
}
}
}
}
private static String formatTimeStep(Integer numberOfTimestepsPerYear, int stepNumber) {
return String.format("%.3f", (double) stepNumber / numberOfTimestepsPerYear);
}
public static String reproductionFilename(int i) {
return "reproduction-seasonality-sp" + i + ".csv";
}
public static void generateFishingParametersFor(List<Group> groupNames, StreamFactory factory, Integer timeStepsPerYear) throws IOException {
generateFishingSeasonalityConfig(groupNames, factory);
generateFishingSeasonalityTables(groupNames, factory, timeStepsPerYear);
}
public static void generateFishingSeasonalityTables(List<Group> groups, StreamFactory factory, Integer timeStepsPerYear) throws IOException {
for (Group group : groups) {
OutputStream seasonalityOs = factory.outputStreamFor(finishingSeasonalityFilename(group));
writeLine(seasonalityOs, Arrays.asList("Time", "Season"), false);
for (int i = 0; i < timeStepsPerYear; i++) {
writeLine(seasonalityOs, Arrays.asList(formatTimeStep(timeStepsPerYear, i), ""));
}
}
}
public static void generateFishingSeasonalityConfig(List<Group> groups, StreamFactory factory) throws IOException {
OutputStream os = factory.outputStreamFor("osm_param-fishing.csv");
writeZerosFor(groups, "mortality.fishing.rate.sp", os);
writeZerosFor(groups, "mortality.fishing.recruitment.age.sp", os);
writeZerosFor(groups, "mortality.fishing.recruitment.size.sp", os);
for (Group group : groups) {
String paramName = "mortality.fishing.season.distrib.file.sp" + groups.indexOf(group);
String fishingSeasonality = finishingSeasonalityFilename(group);
writeLine(os, Arrays.asList(paramName, fishingSeasonality));
}
}
public static String finishingSeasonalityFilename(Group groupName) {
return "fishing/fishing-seasonality-" + groupName.getName() + ".csv";
}
public static void writeZerosFor(List<Group> groupNames, String paramName, OutputStream os) throws IOException {
for (Group groupName : groupNames) {
writeLine(os, Arrays.asList(paramName + groupNames.indexOf(groupName), "0.0"));
}
}
public static void generateStarvationFor(List<Group> groupNames, StreamFactory factory) throws IOException {
OutputStream os = factory.outputStreamFor("osm_param-starvation.csv");
for (int i = 0; i < groupNames.size(); i++) {
String paramName = "mortality.starvation.rate.max.sp" + i;
writeLine(os, Arrays.asList(paramName, "0.3"), i > 0);
}
}
public static void generateSpecies(List<Group> groups, StreamFactory factory, ValueFactory valueFactory) throws IOException {
OutputStream os = factory.outputStreamFor("osm_param-species.csv");
for (Group groupName : groups) {
int i = groups.indexOf(groupName);
writeLine(os, Arrays.asList("species.name.sp" + i, groupName.getName()), i > 0);
}
writeParamLines(groups, "species.egg.size.sp", valueFactory, os);
writeParamLines(groups, "species.egg.weight.sp", valueFactory, os);
writeParamLines(groups, "species.K.sp", valueFactory, os);
writeParamLines(groups, "species.length2weight.allometric.power.sp", valueFactory, os);
writeParamLines(groups, "species.length2weight.condition.factor.sp", valueFactory, os);
writeParamLines(groups, "species.lifespan.sp", valueFactory, os);
writeParamLines(groups, "species.lInf.sp", valueFactory, os);
writeParamLines(groups, "species.maturity.size.sp", valueFactory, os);
writeParamLines(groups, "species.maturity.age.sp", valueFactory, os);
writeParamLines(groups, "species.relativefecundity.sp", valueFactory, os);
writeParamLines(groups, "species.sexratio.sp", valueFactory, os);
writeParamLines(groups, "species.t0.sp", valueFactory, os);
writeParamLines(groups, "species.vonbertalanffy.threshold.age.sp", valueFactory, os);
}
public static void generateLtlForGroups(List<Group> groupsBackground, StreamFactory factory, ValueFactory valueFactory) throws IOException {
OutputStream os = factory.outputStreamFor("osm_param-ltl.csv");
for (Group groupName : groupsBackground) {
int i = groupsBackground.indexOf(groupName);
writeLine(os, Arrays.asList("plankton.name.plk" + i, groupName.getName()), i > 0);
}
writeParamLines(groupsBackground, "plankton.accessibility2fish.plk", valueFactory, os);
writeParamLines(groupsBackground, "plankton.conversion2tons.plk", valueFactory, os);
writeParamLines(groupsBackground, "plankton.size.max.plk", valueFactory, os);
writeParamLines(groupsBackground, "plankton.size.min.plk", valueFactory, os);
writeParamLines(groupsBackground, "plankton.TL.plk", valueFactory, os);
}
public static void writeParamLines(List<Group> groups, String paramPrefix, ValueFactory valueFactory, OutputStream os) throws IOException {
for (Group group : groups) {
final String paramName = paramPrefix + groups.indexOf(group);
writeLine(os, Arrays.asList(paramName, valueFactory.groupValueFor(paramPrefix, group)));
}
}
public static void writeParamLines(List<Group> groupNames, String paramPrefix, List<String> paramValues, OutputStream os) throws IOException {
for (Group group : groupNames) {
List<String> values = new ArrayList<String>() {{
add(paramPrefix + groupNames.indexOf(group));
addAll(paramValues);
}};
writeLine(os, values);
}
}
public static void generatePredationFor(List<Group> groupNames, StreamFactory factory, ValueFactory valueFactory) throws IOException {
OutputStream os = factory.outputStreamFor("osm_param-predation.csv");
writeLine(os, Arrays.asList("predation.accessibility.file", "predation-accessibility.csv"), false);
writeLine(os, Arrays.asList("predation.accessibility.stage.structure", "age"));
writeParamLines(groupNames, "predation.accessibility.stage.threshold.sp", valueFactory, os);
writeParamLines(groupNames, "predation.efficiency.critical.sp", valueFactory, os);
writeParamLines(groupNames, "predation.ingestion.rate.max.sp", valueFactory, os);
writeParamLines(groupNames, "predation.predPrey.sizeRatio.max.sp", Arrays.asList("0.0", "0.0"), os);
writeParamLines(groupNames, "predation.predPrey.sizeRatio.min.sp", Arrays.asList("0.0", "0.0"), os);
writeLine(os, Arrays.asList("predation.predPrey.stage.structure", "size"));
writeParamLines(groupNames, "predation.predPrey.stage.threshold.sp", valueFactory, os);
}
public static void generateAllParametersFor(Integer timeStepsPerYear, List<Group> groupFocal, List<Group> groupsBackground, StreamFactory factory) throws IOException {
OutputStream os = factory.outputStreamFor("osm_all-parameters.csv");
writeLine(os, Arrays.asList("simulation.time.ndtPerYear", timeStepsPerYear.toString()));
writeLine(os, Arrays.asList("simulation.time.nyear", "134"));
writeLine(os, Arrays.asList("simulation.restart.file", "null"));
writeLine(os, Arrays.asList("output.restart.recordfrequency.ndt", "60"));
writeLine(os, Arrays.asList("output.restart.spinup", "114"));
writeLine(os, Arrays.asList("simulation.nschool", "20"));
writeLine(os, Arrays.asList("simulation.ncpu", "8"));
writeLine(os, Arrays.asList("simulation.nplankton", Integer.toString(groupsBackground.size())));
writeLine(os, Arrays.asList("simulation.nsimulation", "10"));
writeLine(os, Arrays.asList("simulation.nspecies", Integer.toString(groupFocal.size())));
writeLine(os, Arrays.asList("mortality.algorithm", "stochastic"));
writeLine(os, Arrays.asList("mortality.subdt", "10"));
writeLine(os, Arrays.asList("osmose.configuration.output", "osm_param-output.csv"));
writeLine(os, Arrays.asList("osmose.configuration.movement", "osm_param-movement.csv"));
writeLine(os, Arrays.asList("osmose.configuration.mortality.fishing", "osm_param-fishing.csv"));
writeLine(os, Arrays.asList("osmose.configuration.mortality.natural", "osm_param-natural-mortality.csv"));
writeLine(os, Arrays.asList("osmose.configuration.mortality.predation", "osm_param-predation.csv"));
writeLine(os, Arrays.asList("osmose.configuration.mortality.starvation", "osm_param-starvation.csv"));
writeLine(os, Arrays.asList("osmose.configuration.reproduction", "osm_param-reproduction.csv"));
writeLine(os, Arrays.asList("osmose.configuration.species", "osm_param-species.csv"));
writeLine(os, Arrays.asList("osmose.configuration.plankton", "osm_param-ltl.csv"));
writeLine(os, Arrays.asList("osmose.configuration.grid", "osm_param-grid.csv"));
writeLine(os, Arrays.asList("osmose.configuration.initialization", "osm_param-init-pop.csv"));
}
public static void generateOutputParamsFor(List<Group> groupNames, StreamFactory factory, ValueFactory valueFactory) throws IOException {
OutputStream os = factory.outputStreamFor("osm_param-output.csv");
IOUtils.copy(IOUtils.toInputStream(OUTPUT_DEFAULTS, "UTF-8"), os);
writeLine(os, Arrays.asList("output.cutoff.enabled", "true"));
writeParamLines(groupNames, "output.cutoff.age.sp", valueFactory, os);
writeLine(os, Arrays.asList("output.distrib.bySize.min", "0"));
writeLine(os, Arrays.asList("output.distrib.bySize.max", "205"));
writeLine(os, Arrays.asList("output.distrib.bySize.incr", "10"));
writeLine(os, Arrays.asList("output.distrib.byAge.min", "0"));
writeLine(os, Arrays.asList("output.distrib.byAge.max", "10"));
writeLine(os, Arrays.asList("output.distrib.byAge.incr", "1"));
writeLine(os, Arrays.asList("output.diet.stage.structure", "age"));
writeParamLines(groupNames, "output.diet.stage.threshold.sp", Arrays.asList("0", "1", "2"), os);
}
public static void generateNaturalMortalityFor(List<Group> groupNames, StreamFactory factory, ValueFactory valueFactory) throws IOException {
OutputStream os = factory.outputStreamFor("osm_param-natural-mortality.csv");
writeLine(os, Arrays.asList("mortality.natural.larva.rate.file", "null"), false);
writeParamLines(groupNames, "mortality.natural.larva.rate.sp", valueFactory, os);
writeLine(os, Arrays.asList("mortality.natural.rate.file", "null"));
writeParamLines(groupNames, "mortality.natural.rate.sp", valueFactory, os);
}
public static void generateInitBiomassFor(List<Group> groupNames, StreamFactory factory, ValueFactory valueFactory) throws IOException {
OutputStream os = factory.outputStreamFor("osm_param-init-pop.csv");
writeParamLines(groupNames, "population.seeding.biomass.sp", valueFactory, os);
}
public static void generateStatic(StreamFactory factory) throws IOException {
generateFromTemplate(factory, "osm_param-grid.csv");
generateFromTemplate(factory, "README.xlsx");
}
public static void generateFromTemplate(StreamFactory factory, String staticTemplate) throws IOException {
OutputStream os = factory.outputStreamFor(staticTemplate);
IOUtils.copy(ConfigUtil.class.getResourceAsStream("osmose_config/" + staticTemplate), os);
}
public static void generateMaps(List<Group> groupNames, StreamFactory factory, ValueFactory valueFactory) throws IOException {
OutputStream maskOs = factory.outputStreamFor("grid-mask.csv");
IOUtils.copy(ConfigUtil.class.getResourceAsStream("osmose_config/grid-mask.csv"), maskOs);
generateMovementConfig(groupNames, factory, valueFactory);
generateMovementMapTemplates(groupNames, factory);
}
public static void generateMovementMapTemplates(List<Group> groups, StreamFactory factory) throws IOException {
int nMaps = 1;
for (Group group : groups) {
OutputStream mapOutputStream = factory.outputStreamFor(getMapName(group));
IOUtils.copy(ConfigUtil.class.getResourceAsStream("osmose_config/maps/Amberjacks_1.csv"), mapOutputStream);
nMaps++;
}
}
public static void generateMovementConfig(List<Group> groups, StreamFactory factory, ValueFactory valueFactory) throws IOException {
OutputStream os = factory.outputStreamFor("osm_param-movement.csv");
writeParamLines(groups, "movement.distribution.method.sp", valueFactory, os);
writeParamLines(groups, "movement.randomwalk.range.sp", valueFactory, os);
int nMaps = 1;
for (Group group : groups) {
addMapForGroup(os, nMaps, group, getMapName(group));
nMaps++;
}
}
public static String getMapName(Group group) {
return "maps/" + group.getName() + "_1.csv";
}
public static void addMapForGroup(OutputStream os, int nMaps, Group group, String mapName) throws IOException {
String prefix = "movement.map" + nMaps;
writeLine(os, Arrays.asList(prefix + ".age.max", "2"));
writeLine(os, Arrays.asList(prefix + ".age.min", "0"));
writeLine(os, Arrays.asList(prefix + ".file", mapName));
writeLine(os, Arrays.asList(prefix + ".season", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"));
writeLine(os, Arrays.asList(prefix + ".species", group.getName()));
}
public static void generateConfigFor(Config config, StreamFactory factory, ValueFactory valueFactory) throws IOException {
generateConfigFor(config.getTimeStepsPerYear(),
config.getGroups()
.stream()
.filter(group -> group.getType() == GroupType.FOCAL)
.collect(Collectors.toList()),
config.getGroups()
.stream()
.filter(group -> group.getType() == GroupType.BACKGROUND)
.collect(Collectors.toList()),
factory, valueFactory);
}
public static void generateConfigFor(Integer timeStepsPerYear, List<Group> groupsFocal, List<Group> groupsBackground, StreamFactory factory, ValueFactory valueFactory) throws IOException {
generateAllParametersFor(timeStepsPerYear, groupsFocal, groupsBackground, factory);
generateFishingParametersFor(groupsFocal, factory, timeStepsPerYear);
generateInitBiomassFor(groupsFocal, factory, valueFactory);
generateMaps(groupsFocal, factory, valueFactory);
generateNaturalMortalityFor(groupsFocal, factory, valueFactory);
generateOutputParamsFor(groupsFocal, factory, valueFactory);
generatePredationFor(groupsFocal, factory, valueFactory);
generatePredationAccessibilityFor(groupsFocal, groupsBackground, factory, valueFactory);
generateSeasonalReproductionFor(groupsFocal, factory, valueFactory, timeStepsPerYear);
generateSpecies(groupsFocal, factory, valueFactory);
generateStarvationFor(groupsFocal, factory);
generateLtlForGroups(groupsBackground, factory, valueFactory);
generateLtlBiomassForGroups(groupsBackground, factory, valueFactory);
generateStatic(factory);
generateFunctionGroupList(new ArrayList<Group>() {{
addAll(groupsFocal);
addAll(groupsBackground);
}}, factory);
}
protected static void generateFunctionGroupList(List<Group> groups, StreamFactory factory) throws IOException {
OutputStream outputStream = factory.outputStreamFor("functional_groups.csv");
IOUtils.write("functional group name,functional group type,species name,species url", outputStream);
for (Group group : groups) {
for (Taxon taxon : group.getTaxa()) {
List<String> row = Arrays.asList(group.getName(), group.getType().name().toLowerCase(), taxon.getName(), taxon.getUrl());
IOUtils.write("\n", outputStream);
IOUtils.write(StringUtils.join(row, ","), outputStream);
}
}
}
private static void writeGroup(OutputStream outputStream, List<Group> groups) throws IOException {
for (Group group : groups) {
for (Taxon taxon : group.getTaxa()) {
List<String> row = Arrays.asList(group.getName(), group.getType().name(), taxon.getName(), taxon.getUrl());
IOUtils.write("\n", outputStream);
IOUtils.write(StringUtils.join(row, ","), outputStream);
}
}
}
private static void generateLtlBiomassForGroups(List<Group> groupsBackground, StreamFactory factory, ValueFactory valueFactory) throws IOException {
final String resourceName = "osm_ltlbiomass.nc";
OutputStream os = factory.outputStreamFor(resourceName);
try {
final File ltlbiomass = File.createTempFile("ltlbiomass", ".nc");
ltlbiomass.deleteOnExit();
LtlBiomassUtil.generateLtlBiomassNC(ltlbiomass, groupsBackground.size());
IOUtils.copy(FileUtils.openInputStream(ltlbiomass), os);
} catch (InvalidRangeException e) {
throw new IOException("failed to generate [" + resourceName + "]", e);
}
}
public static ValueFactory getProxyValueFactory(List<ValueFactory> valueFactories) {
return new ValueFactoryProxy(valueFactories);
}
enum Overlap {
small(0.1), moderate(0.5), strong(1.0);
private final double value;
Overlap(double value) {
this.value = value;
}
}
enum EcologicalRegion {
benthic, demersal, pelagic
}
public static void generatePredationAccessibilityFor(List<Group> focalGroups, List<Group> backgroundGroups, StreamFactory factory, ValueFactory valueFactory) throws IOException {
List<Group> groupList = new ArrayList<Group>() {{
addAll(focalGroups);
addAll(backgroundGroups);
}};
List<String> groupNames = groupList.stream().map(Group::getName).collect(Collectors.toList());
OutputStream outputStream = factory.outputStreamFor("predation-accessibility.csv");
writeLine(outputStream, new ArrayList<String>() {{
add("v Prey / Predator >");
addAll(groupNames);
}}, false);
for (int j = 0; j < groupNames.size(); j++) {
List<String> row = new ArrayList<String>();
row.add(groupNames.get(j));
for (int i = 0; i < groupNames.size(); i++) {
Overlap overlap = i == j
? Overlap.strong
: calculateOverlap(groupList, valueFactory, j, i);
row.add(String.format("%.2f", 0.8 * overlap.value));
}
writeLine(outputStream, row);
}
}
private static Overlap calculateOverlap(List<Group> groupList, ValueFactory valueFactory, int j, int i) {
Group groupA = groupList.get(i);
EcologicalRegion regionA = ecologicalRegionFor(valueFactory, groupA);
Pair<Double, Double> depthRangeA = depthRangeFor(valueFactory, groupA);
Group groupB = groupList.get(j);
EcologicalRegion regionB = ecologicalRegionFor(valueFactory, groupB);
Pair<Double, Double> depthRangeB = depthRangeFor(valueFactory, groupB);
return determineOverlap(Pair.of(regionA, regionB), Pair.of(depthRangeA, depthRangeB));
}
private static EcologicalRegion ecologicalRegionFor(ValueFactory valueFactory, Group group) {
EcologicalRegion region = null;
if (ecoRegionMatches(valueFactory, "Benthic", group)) {
region = EcologicalRegion.benthic;
} else if (ecoRegionMatches(valueFactory, "Demersal", group)) {
region = EcologicalRegion.demersal;
} else if (ecoRegionMatches(valueFactory, "Pelagic", group)) {
region = EcologicalRegion.pelagic;
}
return region;
}
private static Pair<Double, Double> depthRangeFor(ValueFactory valueFactory, Group group) {
String depthMin = valueFactory.groupValueFor("estimate.DepthMin", group);
String depthMax = valueFactory.groupValueFor("estimate.DepthMax", group);
Pair<Double, Double> depthRangeMinMax = null;
if (StringUtils.isNotBlank(depthMin) && StringUtils.isNotBlank(depthMax)) {
try {
depthRangeMinMax = Pair.of(Double.parseDouble(depthMin), Double.parseDouble(depthMax));
} catch (NumberFormatException ex) {
LOG.log(Level.WARNING, "illegal depth format depthMin: [" + depthMin + "], depthMax: [" + depthMax + "]", ex);
}
}
return depthRangeMinMax;
}
private static Overlap determineOverlap(Pair<EcologicalRegion, EcologicalRegion> region,
Pair<Pair<Double, Double>, Pair<Double, Double>> depthRangeMinMax) {
Overlap overlap;
if (matchingEcoRegions(region)
&& overlappingDepthRange(depthRangeMinMax)) {
overlap = Overlap.strong;
} else if (!matchingEcoRegions(region)
&& overlappingDepthRange(depthRangeMinMax)) {
overlap = Overlap.moderate;
} else if (matchingEcoRegions(region)
&& !overlappingDepthRange(depthRangeMinMax)) {
overlap = Overlap.moderate;
} else {
overlap = Overlap.small;
}
return overlap;
}
private static boolean matchingEcoRegions(Pair<EcologicalRegion, EcologicalRegion> regionPair) {
return regionPair.getLeft() != null
&& regionPair.getLeft() == regionPair.getRight();
}
private static boolean overlappingDepthRange(Pair<Pair<Double, Double>, Pair<Double, Double>> depthRangeMinMax) {
Pair<Double, Double> left = depthRangeMinMax.getLeft();
Pair<Double, Double> right = depthRangeMinMax.getRight();
return left != null
&& right != null
&& (left.getLeft() < right.getRight() || right.getLeft() < left.getRight());
}
private static boolean ecoRegionMatches(ValueFactory valueFactory, String ecologyFieldName, Group group) {
return StringUtils.equals("-1", valueFactory.groupValueFor("ecology." + ecologyFieldName, group));
}
} |
package com.imcode.imcms.domain.dto;
import com.imcode.imcms.sorted.TypeSort;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List;
@Data
@NoArgsConstructor
public class MenuDTO implements Documentable, Serializable {
private static final long serialVersionUID = 2486639868480793796L;
private Integer menuIndex;
private Integer docId;
private List<MenuItemDTO> menuItems;
private boolean nested;
private TypeSort typeSorts;
} |
package com.impossibl.postgres.jdbc;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.impossibl.postgres.jdbc.SQLTextTree.CommentPiece;
import com.impossibl.postgres.jdbc.SQLTextTree.CompositeNode;
import com.impossibl.postgres.jdbc.SQLTextTree.EscapeNode;
import com.impossibl.postgres.jdbc.SQLTextTree.GrammarPiece;
import com.impossibl.postgres.jdbc.SQLTextTree.MultiStatementNode;
import com.impossibl.postgres.jdbc.SQLTextTree.NumericLiteralPiece;
import com.impossibl.postgres.jdbc.SQLTextTree.ParameterPiece;
import com.impossibl.postgres.jdbc.SQLTextTree.ParenGroupNode;
import com.impossibl.postgres.jdbc.SQLTextTree.Processor;
import com.impossibl.postgres.jdbc.SQLTextTree.QuotedIdentifierPiece;
import com.impossibl.postgres.jdbc.SQLTextTree.StatementNode;
import com.impossibl.postgres.jdbc.SQLTextTree.StringLiteralPiece;
import com.impossibl.postgres.jdbc.SQLTextTree.UnquotedIdentifierPiece;
import com.impossibl.postgres.jdbc.SQLTextTree.WhitespacePiece;
public class SQLText {
private MultiStatementNode root;
public SQLText(String sqlText) throws ParseException {
root = parse(sqlText);
}
public int getStatementCount() {
return root.getNodeCount();
}
public StatementNode getLastStatement() {
return (StatementNode) root.get(root.getNodeCount()-1);
}
public void process(Processor processor) throws SQLException {
root.process(processor);
}
@Override
public String toString() {
return root.toString();
}
/*
* Lexical pattern for the parser that finds these things:
* > SQL identifier
* > SQL quoted identifier (ignoring escaped double quotes)
* > Single quoted strings (ignoring escaped single quotes)
* > SQL comments... from "--" to end of line
* > C-Style comments (including nested sections)
* > ? Parameter placeholders
* > ; Statement breaks
*/
private static final Pattern LEXER = Pattern
.compile(
"(?:\"((?:[^\"\"]|\\\\.)*)\")|" + /* Quoted identifier */
"(?:'((?:[^\'\']|\\\\.)*)')|" + /* String literal */
"((?:\\-\\-.*$)|(?:/\\*(?:(?:.|\\n)*)\\*/))|" + /* Comments */
"(\\?)|" + /* Parameter marker */
"(;)|" + /* Statement break */
"(\\{|\\})|" + /* Escape open/close */
"([a-zA-Z_][\\w_]*)|" + /* Unquoted identifier */
"((?:[+-]?(?:\\d+)?(?:\\.\\d+(?:[eE][+-]?\\d+)?))|(?:[+-]?\\d+))|" + /* Numeric literal */
"(\\(|\\))|" + /* Parens (grouping) */
"(,)|" + /* Comma (breaking) */
"(\\s+)", /* Whitespace */
Pattern.MULTILINE);
public static MultiStatementNode parse(String sql) throws ParseException {
Stack<CompositeNode> parents = new Stack<CompositeNode>();
parents.push(new MultiStatementNode(0));
parents.push(new StatementNode(0));
Matcher matcher = LEXER.matcher(sql);
int paramId = 1;
int startIdx = 0;
try {
while(matcher.find()) {
//Add the unmatched region as grammar...
if(startIdx != matcher.start()) {
String txt = sql.substring(startIdx, matcher.start()).trim();
parents.peek().add(new GrammarPiece(txt, matcher.start()));
}
//Add whatever we matched...
String val;
if((val = matcher.group(1)) != null) {
parents.peek().add(new QuotedIdentifierPiece(val, matcher.start()));
}
else if((val = matcher.group(2)) != null) {
parents.peek().add(new StringLiteralPiece(val, matcher.start()));
}
else if((val = matcher.group(3)) != null) {
parents.peek().add(new CommentPiece(val, matcher.start()));
}
else if((val = matcher.group(4)) != null) {
parents.peek().add(new ParameterPiece(paramId++, matcher.start()));
}
else if((val = matcher.group(5)) != null) {
//Pop & add everything until the top node
while(parents.size() > 1) {
CompositeNode comp = parents.pop();
comp.setEndPos(matcher.end());
parents.peek().add(comp);
}
parents.push(new StatementNode(matcher.start()));
}
else if((val = matcher.group(6)) != null) {
if(val.equals("{")) {
parents.push(new EscapeNode(matcher.start()));
}
else {
if(parents.peek() instanceof EscapeNode) {
EscapeNode tmp = (EscapeNode) parents.pop();
tmp.setEndPos(matcher.end());
parents.peek().add(tmp);
}
else {
throw new ParseException("Mismatched curly brace", matcher.start());
}
}
}
else if((val = matcher.group(7)) != null) {
parents.peek().add(new UnquotedIdentifierPiece(val, matcher.start()));
}
else if((val = matcher.group(8)) != null) {
parents.peek().add(new NumericLiteralPiece(val, matcher.start()));
}
else if((val = matcher.group(9)) != null) {
if(val.equals("(")) {
parents.push(new ParenGroupNode(matcher.start()));
}
else {
if(parents.peek() instanceof ParenGroupNode) {
ParenGroupNode tmp = (ParenGroupNode) parents.pop();
tmp.setEndPos(matcher.end());
parents.peek().add(tmp);
}
else {
throw new ParseException("Mismmatched parenthesis", matcher.start());
}
}
}
else if((val = matcher.group(10)) != null) {
parents.peek().add(new GrammarPiece(",", matcher.start()));
}
else if((val = matcher.group(11)) != null) {
parents.peek().add(new WhitespacePiece(val, matcher.start()));
}
startIdx = matcher.end();
}
//Add last grammar node
if(startIdx != sql.length()) {
parents.peek().add(new GrammarPiece(sql.substring(startIdx), startIdx));
}
//Auto close last statement
if(parents.peek() instanceof StatementNode) {
CompositeNode tmp = parents.pop();
tmp.setEndPos(startIdx);
parents.peek().add(tmp);
}
return (MultiStatementNode)parents.get(0);
}
catch(ParseException e) {
throw e;
}
catch(Exception e) {
//Grab about 10 characters to report context of error
String errorTxt = sql.substring(startIdx, Math.min(sql.length(), startIdx+10));
throw new ParseException("Error near: " + errorTxt, startIdx);
}
}
} |
package com.minervabay.entity;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.json.Json;
import javax.json.JsonObject;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author thiago
*/
@Entity
@Table(name = "dadoscatalogo")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Dadoscatalogo.findAll", query = "SELECT d FROM Dadoscatalogo d"),
@NamedQuery(name = "Dadoscatalogo.findByPatrimonio", query = "SELECT d FROM Dadoscatalogo d WHERE d.patrimonio = :patrimonio"),
@NamedQuery(name = "Dadoscatalogo.findByTitulo", query = "SELECT d FROM Dadoscatalogo d WHERE d.titulo = :titulo"),
@NamedQuery(name = "Dadoscatalogo.findByAutoria", query = "SELECT d FROM Dadoscatalogo d WHERE d.autoria = :autoria"),
@NamedQuery(name = "Dadoscatalogo.findByVeiculo", query = "SELECT d FROM Dadoscatalogo d WHERE d.veiculo = :veiculo"),
@NamedQuery(name = "Dadoscatalogo.findByDataPublicacao", query = "SELECT d FROM Dadoscatalogo d WHERE d.dataPublicacao = :dataPublicacao"),
@NamedQuery(name = "Dadoscatalogo.findByArquivo", query = "SELECT d FROM Dadoscatalogo d WHERE d.arquivo = :arquivo")})
public class Dadoscatalogo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "patrimonio")
private Integer patrimonio;
@Size(max = 2147483647)
@Column(name = "titulo")
private String titulo;
@Size(max = 2147483647)
@Column(name = "autoria")
private String autoria;
@Size(max = 2147483647)
@Column(name = "veiculo")
private String veiculo;
@Column(name = "data_publicacao")
@Temporal(TemporalType.DATE)
private Date dataPublicacao;
@Size(max = 2147483647)
@Column(name = "arquivo")
private String arquivo;
@OneToMany(mappedBy = "patrimonio", cascade = CascadeType.REMOVE)
private Collection<PalavrasChave> palavrasChaveCollection;
@OneToMany(mappedBy = "patrimonio", cascade = CascadeType.REMOVE)
private Collection<Comentarios> comentariosCollection;
public Dadoscatalogo() {
}
public Dadoscatalogo(Integer patrimonio) {
this.patrimonio = patrimonio;
}
public Integer getPatrimonio() {
return patrimonio;
}
public void setPatrimonio(Integer patrimonio) {
this.patrimonio = patrimonio;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getAutoria() {
return autoria;
}
public void setAutoria(String autoria) {
this.autoria = autoria;
}
public String getVeiculo() {
return veiculo;
}
public void setVeiculo(String veiculo) {
this.veiculo = veiculo;
}
public Date getDataPublicacao() {
return dataPublicacao;
}
public void setDataPublicacao(Date dataPublicacao) {
this.dataPublicacao = dataPublicacao;
}
public String getArquivo() {
return arquivo;
}
public void setArquivo(String arquivo) {
this.arquivo = arquivo;
}
@XmlTransient
public Collection<PalavrasChave> getPalavrasChaveCollection() {
return palavrasChaveCollection;
}
public void setPalavrasChaveCollection(Collection<PalavrasChave> palavrasChaveCollection) {
this.palavrasChaveCollection = palavrasChaveCollection;
}
@XmlTransient
public Collection<Comentarios> getComentariosCollection() {
return comentariosCollection;
}
public void setComentariosCollection(Collection<Comentarios> comentariosCollection) {
this.comentariosCollection = comentariosCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (patrimonio != null ? patrimonio.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Dadoscatalogo)) {
return false;
}
Dadoscatalogo other = (Dadoscatalogo) object;
if ((this.patrimonio == null && other.patrimonio != null) || (this.patrimonio != null && !this.patrimonio.equals(other.patrimonio))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.minervabay.entity.Dadoscatalogo[ patrimonio=" + patrimonio + " ]";
}
public JsonObject toJson() {
return Json.createObjectBuilder()
.add("patrimonio", patrimonio)
.add("titulo", titulo)
.add("autoria", autoria)
.add("veiculo", veiculo)
.add("datapublicacao", dataPublicacao.toString())
.add("arquivo", arquivo)
.build();
}
} |
package com.monitorjbl.xlsx;
import com.monitorjbl.xlsx.exceptions.CloseException;
import com.monitorjbl.xlsx.exceptions.MissingSheetException;
import com.monitorjbl.xlsx.exceptions.OpenException;
import com.monitorjbl.xlsx.exceptions.ReadException;
import com.monitorjbl.xlsx.impl.StreamingCell;
import com.monitorjbl.xlsx.impl.StreamingRow;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import static com.monitorjbl.xlsx.XmlUtils.document;
import static com.monitorjbl.xlsx.XmlUtils.searchForNodeList;
/**
* Streaming Excel workbook implementation. Most advanced features of POI are not supported.
* Use this only if your application can handle iterating through an entire workbook, row by
* row.
*/
public class StreamingReader implements Iterable<Row>, AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(StreamingReader.class);
private final SharedStringsTable sst;
private final StylesTable stylesTable;
private final XMLEventReader parser;
private final DataFormatter dataFormatter = new DataFormatter();
private int rowCacheSize;
private List<Row> rowCache = new ArrayList<>();
private Iterator<Row> rowCacheIterator;
private String lastContents;
private StreamingRow currentRow;
private StreamingCell currentCell;
private File tmp;
private StreamingReader(SharedStringsTable sst, StylesTable stylesTable, XMLEventReader parser, int rowCacheSize) {
this.sst = sst;
this.stylesTable = stylesTable;
this.parser = parser;
this.rowCacheSize = rowCacheSize;
}
/**
* Read through a number of rows equal to the rowCacheSize field or until there is no more data to read
*
* @return true if data was read
*/
private boolean getRow() {
try {
rowCache.clear();
while(rowCache.size() < rowCacheSize && parser.hasNext()) {
handleEvent(parser.nextEvent());
}
rowCacheIterator = rowCache.iterator();
return rowCacheIterator.hasNext();
} catch(XMLStreamException | SAXException e) {
log.debug("End of stream");
}
return false;
}
/**
* Handles a SAX event.
*
* @param event
* @throws SAXException
*/
private void handleEvent(XMLEvent event) throws SAXException {
if(event.getEventType() == XMLStreamConstants.CHARACTERS) {
Characters c = event.asCharacters();
lastContents += c.getData();
} else if(event.getEventType() == XMLStreamConstants.START_ELEMENT) {
StartElement startElement = event.asStartElement();
String tagLocalName = startElement.getName().getLocalPart();
if("row".equals(tagLocalName)) {
Attribute rowIndex = startElement.getAttributeByName(new QName("r"));
currentRow = new StreamingRow(Integer.parseInt(rowIndex.getValue()));
} else if("c".equals(tagLocalName)) {
Attribute ref = startElement.getAttributeByName(new QName("r"));
String[] coord = ref.getValue().split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
currentCell = new StreamingCell(CellReference.convertColStringToIndex(coord[0]), Integer.parseInt(coord[1]) - 1);
setFormatString(startElement, currentCell);
Attribute type = startElement.getAttributeByName(new QName("t"));
if(type != null) {
currentCell.setType(type.getValue());
}
}
// Clear contents cache
lastContents = "";
} else if(event.getEventType() == XMLStreamConstants.END_ELEMENT) {
EndElement endElement = event.asEndElement();
String tagLocalName = endElement.getName().getLocalPart();
if("v".equals(tagLocalName)) {
currentCell.setRawContents(unformattedContents());
currentCell.setContents(formattedContents());
} else if("row".equals(tagLocalName) && currentRow != null) {
rowCache.add(currentRow);
} else if("c".equals(tagLocalName)) {
currentRow.getCellMap().put(currentCell.getColumnIndex(), currentCell);
}
}
}
/**
* Read the numeric format string out of the styles table for this cell. Stores
* the result in the Cell.
*
* @param startElement
* @param cell
*/
void setFormatString(StartElement startElement, StreamingCell cell) {
Attribute cellStyle = startElement.getAttributeByName(new QName("s"));
String cellStyleString = (cellStyle != null) ? cellStyle.getValue() : null;
XSSFCellStyle style = null;
if(cellStyleString != null) {
style = stylesTable.getStyleAt(Integer.parseInt(cellStyleString));
} else if(stylesTable.getNumCellStyles() > 0) {
style = stylesTable.getStyleAt(0);
}
if(style != null) {
cell.setNumericFormatIndex(style.getDataFormat());
String formatString = style.getDataFormatString();
if(formatString != null) {
cell.setNumericFormat(formatString);
} else {
cell.setNumericFormat(BuiltinFormats.getBuiltinFormat(cell.getNumericFormatIndex()));
}
} else {
cell.setNumericFormatIndex(null);
cell.setNumericFormat(null);
}
}
/**
* Tries to format the contents of the last contents appropriately based on
* the type of cell and the discovered numeric format.
*
* @return
*/
String formattedContents() {
switch(currentCell.getType()) {
case "s": //string stored in shared table
int idx = Integer.parseInt(lastContents);
return new XSSFRichTextString(sst.getEntryAt(idx)).toString();
case "inlineStr": //inline string (not in sst)
return new XSSFRichTextString(lastContents).toString();
case "str": //forumla type
return '"' + lastContents + '"';
case "e": //error type
return "ERROR: " + lastContents;
case "n": //numeric type
if(currentCell.getNumericFormat() != null && lastContents.length() > 0) {
return dataFormatter.formatRawCellContents(
Double.parseDouble(lastContents),
currentCell.getNumericFormatIndex(),
currentCell.getNumericFormat());
} else {
return lastContents;
}
default:
return lastContents;
}
}
/**
* Returns the contents of the cell, with no formatting applied
* @return
*/
String unformattedContents(){
switch(currentCell.getType()) {
case "s": //string stored in shared table
int idx = Integer.parseInt(lastContents);
return new XSSFRichTextString(sst.getEntryAt(idx)).toString();
case "inlineStr": //inline string (not in sst)
return new XSSFRichTextString(lastContents).toString();
default:
return lastContents;
}
}
/**
* Returns a new streaming iterator to loop through rows. This iterator is not
* guaranteed to have all rows in memory, and any particular iteration may
* trigger a load from disk to read in new data.
*
* @return the streaming iterator
*/
@Override
public Iterator<Row> iterator() {
return new StreamingIterator();
}
/**
* Closes the streaming resource, attempting to clean up any temporary files created.
*
* @throws com.monitorjbl.xlsx.exceptions.CloseException if there is an issue closing the stream
*/
@Override
public void close() {
try {
parser.close();
} catch(XMLStreamException e) {
throw new CloseException(e);
}
if(tmp != null) {
log.debug("Deleting tmp file [" + tmp.getAbsolutePath() + "]");
tmp.delete();
}
}
static File writeInputStreamToFile(InputStream is, int bufferSize) throws IOException {
File f = Files.createTempFile("tmp-", ".xlsx").toFile();
try(FileOutputStream fos = new FileOutputStream(f)) {
int read;
byte[] bytes = new byte[bufferSize];
while((read = is.read(bytes)) != -1) {
fos.write(bytes, 0, read);
}
is.close();
fos.close();
return f;
}
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
int rowCacheSize = 10;
int bufferSize = 1024;
int sheetIndex = 0;
String sheetName;
/**
* The number of rows to keep in memory at any given point.
* <p>
* Defaults to 10
* </p>
*
* @param rowCacheSize number of rows
* @return reference to current {@code Builder}
*/
public Builder rowCacheSize(int rowCacheSize) {
this.rowCacheSize = rowCacheSize;
return this;
}
/**
* The number of bytes to read into memory from the input
* resource.
* <p>
* Defaults to 1024
* </p>
*
* @param bufferSize buffer size in bytes
* @return reference to current {@code Builder}
*/
public Builder bufferSize(int bufferSize) {
this.bufferSize = bufferSize;
return this;
}
/**
* Which sheet to open. There can only be one sheet open
* for a single instance of {@code StreamingReader}. If
* more sheets need to be read, a new instance must be
* created.
* <p>
* Defaults to 0
* </p>
*
* @param sheetIndex index of sheet
* @return reference to current {@code Builder}
*/
public Builder sheetIndex(int sheetIndex) {
this.sheetIndex = sheetIndex;
return this;
}
/**
* Which sheet to open. There can only be one sheet open
* for a single instance of {@code StreamingReader}. If
* more sheets need to be read, a new instance must be
* created.
*
* @param sheetName name of sheet
* @return reference to current {@code Builder}
*/
public Builder sheetName(String sheetName) {
this.sheetName = sheetName;
return this;
}
/**
* Reads a given {@code InputStream} and returns a new
* instance of {@code StreamingReader}. Due to Apache POI
* limitations, a temporary file must be written in order
* to create a streaming iterator. This process will use
* the same buffer size as specified in {@link #bufferSize(int)}.
*
* @param is input stream to read in
* @return built streaming reader instance
* @throws com.monitorjbl.xlsx.exceptions.ReadException if there is an issue reading the stream
*/
public StreamingReader read(InputStream is) {
File f = null;
try {
f = writeInputStreamToFile(is, bufferSize);
log.debug("Created temp file [" + f.getAbsolutePath() + "]");
StreamingReader r = read(f);
r.tmp = f;
return r;
} catch(IOException e) {
throw new ReadException("Unable to read input stream", e);
} catch(RuntimeException e) {
f.delete();
throw e;
}
}
/**
* Reads a given {@code File} and returns a new instance
* of {@code StreamingReader}.
*
* @param f file to read in
* @return built streaming reader instance
* @throws com.monitorjbl.xlsx.exceptions.OpenException if there is an issue opening the file
* @throws com.monitorjbl.xlsx.exceptions.ReadException if there is an issue reading the file
*/
public StreamingReader read(File f) {
try {
OPCPackage pkg = OPCPackage.open(f);
XSSFReader reader = new XSSFReader(pkg);
SharedStringsTable sst = reader.getSharedStringsTable();
StylesTable styles = reader.getStylesTable();
InputStream sheet = findSheet(reader);
if(sheet == null) {
throw new MissingSheetException("Unable to find sheet at index [" + sheetIndex + "]");
}
XMLEventReader parser = XMLInputFactory.newInstance().createXMLEventReader(sheet);
return new StreamingReader(sst, styles, parser, rowCacheSize);
} catch(IOException e) {
throw new OpenException("Failed to open file", e);
} catch(OpenXML4JException | XMLStreamException e) {
throw new ReadException("Unable to read workbook", e);
}
}
InputStream findSheet(XSSFReader reader) throws IOException, InvalidFormatException {
int index = sheetIndex;
if(sheetName != null) {
index = -1;
//This file is separate from the worksheet data, and should be fairly small
NodeList nl = searchForNodeList(document(reader.getWorkbookData()), "/workbook/sheets/sheet");
for(int i = 0; i < nl.getLength(); i++) {
if(Objects.equals(nl.item(i).getAttributes().getNamedItem("name").getTextContent(), sheetName)) {
index = i;
}
}
if(index < 0) {
return null;
}
}
Iterator<InputStream> iter = reader.getSheetsData();
InputStream sheet = null;
int i = 0;
while(iter.hasNext()) {
InputStream is = iter.next();
if(i++ == index) {
sheet = is;
log.debug("Found sheet at index [" + sheetIndex + "]");
break;
}
}
return sheet;
}
}
class StreamingIterator implements Iterator<Row> {
@Override
public boolean hasNext() {
return (rowCacheIterator != null && rowCacheIterator.hasNext()) || getRow();
}
@Override
public Row next() {
return rowCacheIterator.next();
}
@Override
public void remove() {
throw new RuntimeException("NotSupported");
}
}
} |
package com.nickdsantos.onedrive4j;
import com.google.gson.Gson;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* @author Nick DS (me@nickdsantos.com)
*
*/
public class OneDrive {
static Logger logger = Logger.getLogger(OneDrive.class.getName());
private static class AlbumServiceHolder {
public static AlbumService _albumServiceInstance = new AlbumService();
}
private static class PhotoServiceHolder {
public static PhotoService _photoServiceInstance = new PhotoService();
}
private static class DriveServiceHolder {
public static DriveService _driveServiceInstance = new DriveService();
}
public static final String LOGIN_API_HOST = "login.live.com";
public static final String DEFAULT_SCHEME = "https";
public static final String AUTHORIZE_URL_PATH = "/oauth20_authorize.srf";
public static final String ACCESS_TOKEN_URL_PATH = "/oauth20_token.srf";
private String _clientId;
private String _clientSecret;
private String _callback;
public OneDrive(String clientId, String clientSecret, String callback) {
_clientId = clientId;
_clientSecret = clientSecret;
_callback = callback;
}
public AlbumService getAlbumService() {
return AlbumServiceHolder._albumServiceInstance;
}
public PhotoService getPhotoService() {
return PhotoServiceHolder._photoServiceInstance;
}
public DriveService getDriveService() {
return DriveServiceHolder._driveServiceInstance;
}
public String authorize(Scope[] scopes) {
StringBuilder sbScopes = new StringBuilder();
for (Scope s : scopes) {
sbScopes.append(s).append(" ");
}
String authzUrl;
try {
URI uri = new URIBuilder()
.setScheme(DEFAULT_SCHEME)
.setHost(LOGIN_API_HOST)
.setPath(AUTHORIZE_URL_PATH)
.setParameter("client_id", _clientId)
.setParameter("scope",sbScopes.toString())
.setParameter("response_type", "code")
.setParameter("redirect_uri", _callback)
.build();
authzUrl = uri.toString();
} catch (URISyntaxException e) {
throw new IllegalStateException("Invalid authorization url", e);
}
return authzUrl;
}
public AccessToken getAccessToken(String authorizationCode) throws IOException {
AccessToken accessToken = null;
URI uri;
try {
uri = new URIBuilder()
.setScheme(DEFAULT_SCHEME)
.setHost(LOGIN_API_HOST)
.setPath(ACCESS_TOKEN_URL_PATH)
.build();
} catch (URISyntaxException e) {
throw new IllegalStateException("Invalid access token path", e);
}
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("client_id", _clientId));
params.add(new BasicNameValuePair("redirect_uri", _callback));
params.add(new BasicNameValuePair("client_secret", _clientSecret));
params.add(new BasicNameValuePair("code", authorizationCode));
params.add(new BasicNameValuePair("grant_type", "authorization_code"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, Consts.UTF_8);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(formEntity);
Map<Object, Object> rawToken = httpClient.execute(httpPost, new OneDriveJsonToMapResponseHandler());
if (rawToken != null) {
accessToken = new AccessToken(
rawToken.get("token_type").toString(),
(int) Double.parseDouble(rawToken.get("expires_in").toString()),
rawToken.get("scope").toString(),
rawToken.get("access_token").toString(),
Objects.toString(rawToken.get("refresh_token"), null),
rawToken.get("user_id").toString());
}
}
return accessToken;
}
/**
* Gets a new access token from a previously acquired refresh token.
*
* @param refreshToken the refresh token.
* @return the access token.
* @throws IOException if an error occurs.
*/
public AccessToken getAccessTokenFromRefreshToken(String refreshToken) throws IOException {
AccessToken accessToken = null;
URI uri;
try {
uri = new URIBuilder()
.setScheme(DEFAULT_SCHEME)
.setHost(LOGIN_API_HOST)
.setPath(ACCESS_TOKEN_URL_PATH)
.build();
} catch (URISyntaxException e) {
throw new IllegalStateException("Invalid access token path", e);
}
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("client_id", _clientId));
params.add(new BasicNameValuePair("redirect_uri", _callback));
params.add(new BasicNameValuePair("client_secret", _clientSecret));
params.add(new BasicNameValuePair("refresh_token", refreshToken));
params.add(new BasicNameValuePair("grant_type", "refresh_token"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, Consts.UTF_8);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(formEntity);
Map<Object, Object> rawResponse = httpClient.execute(httpPost, new OneDriveJsonToMapResponseHandler());
if (rawResponse != null) {
if (rawResponse.containsKey("error")) {
throw new IOException(rawResponse.get("error") + " : " +
rawResponse.get("error_description"));
}
accessToken = new AccessToken(
rawResponse.get("token_type").toString(),
(int) Double.parseDouble(rawResponse.get("expires_in").toString()),
rawResponse.get("scope").toString(),
rawResponse.get("access_token").toString(),
Objects.toString(rawResponse.get("refresh_token"), null),
Objects.toString(rawResponse.get("user_id"), null));
}
}
return accessToken;
}
/**
* Gets the details about the current user.
*
* @param accessToken the access token.
* @return the user's details.
* @throws IOException if an error occurs.
*/
public Me getMe(String accessToken) throws IOException {
URI uri;
try {
uri = new URIBuilder()
.setScheme(DEFAULT_SCHEME)
.setHost("apis.live.net/v5.0")
.setPath("/me")
.addParameter("access_token", accessToken)
.build();
} catch (URISyntaxException e) {
throw new IllegalStateException("Invalid drives path", e);
}
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(uri);
String rawResponse = httpClient.execute(httpGet, new OneDriveStringResponseHandler());
return new Gson().fromJson(rawResponse, Me.class);
} catch (Exception e) {
throw new IOException("Error getting drives", e);
}
}
} |
package com.riptano.cassandra.stress;
import jline.ConsoleReader;
import me.prettyprint.cassandra.service.CassandraHostConfigurator;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.factory.HFactory;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Initiate a stress run against an Apache Cassandra cluster
*
* @author zznate <nate@riptano.com>
*/
public class Stress {
private static Logger log = LoggerFactory.getLogger(Stress.class);
private CommandArgs commandArgs;
private CommandRunner commandRunner;
private static String seedHost;
public static void main( String[] args ) throws Exception {
Stress stress = new Stress();
CommandLine cmd = stress.processArgs(args);
// If we got an initial help, leave
if ( cmd.hasOption("help") ) {
System.exit(0);
}
seedHost = cmd.getArgList().size() > 0 ? cmd.getArgs()[0] : "localhost:9160";
log.info("Starting stress run using seed {} for {} clients...", seedHost, stress.commandArgs.clients);
stress.initializeCommandRunner(cmd);
ConsoleReader reader = new ConsoleReader();
String line;
while ((line = reader.readLine("[cassandra-stress] ")) != null) {
if ( line.equalsIgnoreCase("exit")) {
System.exit(0);
}
stress.processCommand(reader, line);
}
}
private void processCommand(ConsoleReader reader, String line) throws Exception {
// TODO catch command error(s) here, simply errmsg handoff to stdin loop above
CommandLine cmd = processArgs(line.split(" "));
if (cmd.hasOption("help"))
return;
if ( commandArgs.validateCommand() ) {
commandRunner.processCommand(commandArgs);
} else {
reader.printString("Invalid command. Must be one of: read, rangeslice, multiget\n");
}
}
private CommandLine processArgs(String[] args) throws Exception {
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse( buildOptions(), args);
if ( cmd.hasOption("help")) {
printHelp();
return cmd;
}
if ( commandArgs == null ) {
commandArgs = new CommandArgs();
}
if (cmd.hasOption("threads")) {
commandArgs.clients = getIntValueOrExit(cmd, "threads");
}
if ( cmd.hasOption("num-keys") ) {
commandArgs.rowCount = getIntValueOrExit(cmd, "num-keys");
}
log.error("comArgs: " + commandArgs.rowCount);
if ( cmd.hasOption("batch-size")) {
commandArgs.batchSize = getIntValueOrExit(cmd, "batch-size");
}
if ( cmd.hasOption("columns")) {
commandArgs.columnCount = getIntValueOrExit(cmd, "columns");
}
if (cmd.hasOption("operation")) {
commandArgs.operation = cmd.getOptionValue("operation");
}
log.info("{} {} columns into {} keys in batches of {} from {} threads",
new Object[]{commandArgs.operation, commandArgs.columnCount, commandArgs.rowCount,
commandArgs.batchSize, commandArgs.clients});
return cmd;
}
private void initializeCommandRunner(CommandLine cmd) throws Exception {
CassandraHostConfigurator cassandraHostConfigurator = new CassandraHostConfigurator(seedHost);
if ( cmd.hasOption("unframed")) {
cassandraHostConfigurator.setUseThriftFramedTransport(false);
}
Cluster cluster = HFactory.createCluster("StressCluster", cassandraHostConfigurator);
commandArgs.keyspace = HFactory.createKeyspace("Keyspace1", cluster);
commandRunner = new CommandRunner(cluster.getKnownPoolHosts(true));
commandRunner.processCommand(commandArgs);
}
// TODO if --use-all-hosts, then buildHostsFromRing()
// treat the host as a single arg, init cluster and call addHosts for the ring
private static Options buildOptions() {
Options options = new Options();
options.addOption("h", "help", false, "Print this help message and exit");
options.addOption("t","threads", true, "The number of client threads we will create");
options.addOption("n","num-keys",true,"The number of keys to create");
options.addOption("c","columns",true,"The number of columsn to create per key");
options.addOption("b","batch-size",true,"The number of rows in the batch_mutate call");
options.addOption("o","operation",true,"One of insert, read, rangeslice, multiget");
options.addOption("m","unframed",false,"Disable use of TFramedTransport");
return options;
}
private static void printHelp() {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "stress [options]... url1,[[url2],[url3],...]", buildOptions() );
}
private static int getIntValueOrExit(CommandLine cmd, String optionVal) {
try {
return Integer.valueOf(cmd.getOptionValue(optionVal));
} catch (NumberFormatException ne) {
log.error("Invalid number of {} provided - must be a reasonably sized positive integer", optionVal);
System.exit(0);
}
return 0;
}
} |
package test;
import java.io.*;
import junit.framework.*;
import aQute.bnd.build.*;
public class TestSelfBuild extends TestCase {
public static void testSelfBuild() throws Throwable {
Project project = Workspace.getWorkspace(new File("").getAbsoluteFile().getParentFile()).getProject(
"biz.aQute.bndlib");
project.setPedantic(true);
project.action("build");
File files[] = project.build();
assertTrue(project.check("Imports that lack version ranges", "for exported package aQute.bnd.service.resolve.hook"));
assertNotNull(files);
assertEquals(1, files.length);
}
} |
package com.sheepdog.mashmesh;
import com.google.api.client.http.AbstractInputStreamContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.google.api.services.drive.model.ParentReference;
import com.google.api.services.drive.model.Permission;
import com.google.api.services.fusiontables.Fusiontables;
import com.google.api.services.fusiontables.model.Column;
import com.google.api.services.fusiontables.model.Table;
import com.sheepdog.mashmesh.models.OfyService;
import com.sheepdog.mashmesh.models.RideRecord;
import com.sheepdog.mashmesh.models.UserProfile;
import com.sheepdog.mashmesh.util.FusionTableContentWriter;
import com.sheepdog.mashmesh.util.GoogleApiUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
public class DriveExporter {
private static final String DRIVE_FOLDER_MIME_TYPE = "application/vnd.google-apps.folder";
private static final String DRIVE_FOLDER_TITLE = "OpenMash Rides Data";
private static final String DRIVE_FOLDER_DESCRIPTION =
"Fusion Tables for demographic data captured by OpenMash Rides";
private static final String RIDE_TABLE_TITLE = "Historical Rides";
private static final String RIDE_TABLE_DESCRIPTION = "Ride details for all rides";
private final Drive drive;
private final Fusiontables fusiontables;
private ParentReference folder;
public DriveExporter() throws IOException {
try {
drive = GoogleApiUtils.getDrive();
fusiontables = GoogleApiUtils.getFusiontables();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
File folderFile = getFolder();
folder = new ParentReference().setId(folderFile.getId());
}
private File findFileByTitle(String title) throws IOException {
// TODO: Can this be made deterministic in the presence of duplicates?
String query = String.format("title = '%s'", title);
FileList matchingFiles = drive.files().list()
.setQ(query)
.execute();
if (!matchingFiles.getItems().isEmpty()) {
return matchingFiles.getItems().get(0);
} else {
return null;
}
}
private void setPermissions(File file) throws IOException {
// Readable by anyone who has the URL
Permission readPermission = new Permission();
readPermission.setRole("reader");
readPermission.setType("anyone");
readPermission.setValue("ignored");
readPermission.setWithLink(true);
drive.permissions().insert(file.getId(), readPermission).execute();
}
public File getFolder() throws IOException {
File folder = findFileByTitle(DRIVE_FOLDER_TITLE);
if (folder == null) {
folder = new File()
.setTitle(DRIVE_FOLDER_TITLE)
.setDescription(DRIVE_FOLDER_DESCRIPTION)
.setMimeType(DRIVE_FOLDER_MIME_TYPE)
.setShared(true);
folder = drive.files().insert(folder).execute();
setPermissions(folder);
}
return folder;
}
// TODO: Testing
public void deleteAllFiles() throws IOException {
for (File file : drive.files().list().execute().getItems()) {
drive.files().delete(file.getId()).execute();
}
folder = new ParentReference().setId(getFolder().getId());
}
public void addToFolder(File file) throws IOException {
drive.parents().insert(file.getId(), folder).execute();
}
public void snapshotUserTable() throws IOException {
DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
String timestamp = formatter.print(DateTime.now());
Table patientTable = new Table()
.setName("User Profile Data " + timestamp)
.setDescription("Locations of patients and volunteers as of " + timestamp)
.setIsExportable(true)
.setColumns(Arrays.asList(
new Column().setName("User Type").setType("STRING"),
new Column().setName("Location").setType("LOCATION")
));
patientTable = fusiontables.table().insert(patientTable).execute();
FusionTableContentWriter fusionTableWriter = new FusionTableContentWriter(patientTable);
for (UserProfile userProfile : UserProfile.listAll()) {
fusionTableWriter.writeRecord(userProfile.getType().name(), userProfile.getLocation());
}
AbstractInputStreamContent streamContent = fusionTableWriter.getInputStreamContent();
fusiontables.table().importRows(patientTable.getTableId(), streamContent).execute();
File patientFile = findFileByTitle(patientTable.getName());
setPermissions(patientFile);
addToFolder(patientFile);
}
private Table getRideTable() throws IOException {
File rideFile = findFileByTitle(RIDE_TABLE_TITLE);
Table rideTable;
if (rideFile != null) {
rideTable = fusiontables.table().get(rideFile.getId()).execute();
} else {
rideTable = new Table()
.setName(RIDE_TABLE_TITLE)
.setDescription(RIDE_TABLE_DESCRIPTION)
.setIsExportable(true)
.setColumns(Arrays.asList(
new Column().setName("Volunteer Location").setType("LOCATION"),
new Column().setName("Departure Time").setType("DATETIME"),
new Column().setName("Patient Location").setType("LOCATION"),
new Column().setName("Pickup Time").setType("DATETIME"),
new Column().setName("Appointment Address").setType("STRING"),
new Column().setName("Appointment Location").setType("LOCATION"),
new Column().setName("Appointment Time").setType("DATETIME"),
new Column().setName("Distance (miles)").setType("NUMBER"),
new Column().setName("Travel Time (minutes)").setType("NUMBER")
));
rideTable = fusiontables.table().insert(rideTable).execute();
rideFile = findFileByTitle(RIDE_TABLE_TITLE);
setPermissions(rideFile);
addToFolder(rideFile);
}
return rideTable;
}
private Collection<RideRecord> getExportableRideRecords() {
Collection<RideRecord> rideRecords = new ArrayList<RideRecord>();
for (RideRecord rideRecord : RideRecord.getExportableRecords()) {
rideRecords.add(rideRecord);
}
return rideRecords;
}
private void exportRideRecords(Table rideTable, Collection<RideRecord> rideRecords) throws IOException {
FusionTableContentWriter fusionTableWriter = new FusionTableContentWriter(rideTable);
for (RideRecord rideRecord : rideRecords) {
fusionTableWriter.writeRecord(
rideRecord.getVolunteerLocation(),
rideRecord.getDepartureTime(),
rideRecord.getPatientLocation(),
rideRecord.getPickupTime(),
rideRecord.getAppointmentAddress(),
rideRecord.getAppointmentLocation(),
rideRecord.getAppointmentTime(),
rideRecord.getDistanceMiles(),
rideRecord.getTripMinutes()
);
}
AbstractInputStreamContent streamContent = fusionTableWriter.getInputStreamContent();
fusiontables.table().importRows(rideTable.getTableId(), streamContent).execute();
}
private void markRideRecordsUnexportable(Collection<RideRecord> rideRecords) {
for (RideRecord rideRecord : rideRecords) {
rideRecord.setIsExported(true);
}
OfyService.ofy().put(rideRecords);
}
public void updateRideTable() throws IOException {
Table rideTable = getRideTable();
Collection<RideRecord> rideRecords = getExportableRideRecords();
exportRideRecords(rideTable, rideRecords);
markRideRecordsUnexportable(rideRecords);
}
} |
package aQute.bnd.osgi;
import static aQute.libg.slf4j.GradleLogging.LIFECYCLE;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aQute.bnd.header.Attrs;
import aQute.bnd.header.OSGiHeader;
import aQute.bnd.header.Parameters;
import aQute.bnd.service.Plugin;
import aQute.bnd.service.Registry;
import aQute.bnd.service.RegistryDonePlugin;
import aQute.bnd.service.RegistryPlugin;
import aQute.bnd.service.url.URLConnectionHandler;
import aQute.bnd.version.Version;
import aQute.bnd.version.VersionRange;
import aQute.lib.collections.ExtList;
import aQute.lib.collections.SortedList;
import aQute.lib.exceptions.Exceptions;
import aQute.lib.hex.Hex;
import aQute.lib.io.IO;
import aQute.lib.io.IOConstants;
import aQute.lib.strings.Strings;
import aQute.lib.utf8properties.UTF8Properties;
import aQute.libg.cryptography.SHA1;
import aQute.libg.generics.Create;
import aQute.libg.reporter.ReporterAdapter;
import aQute.service.reporter.Reporter;
public class Processor extends Domain implements Reporter, Registry, Constants, Closeable {
private static final Logger logger = LoggerFactory.getLogger(Processor.class);
public static Reporter log;;
static {
ReporterAdapter reporterAdapter = new ReporterAdapter(System.out);
reporterAdapter.setTrace(true);
reporterAdapter.setExceptions(true);
reporterAdapter.setPedantic(true);
log = reporterAdapter;
}
static final int BUFFER_SIZE = IOConstants.PAGE_SIZE * 1;
static Pattern PACKAGES_IGNORED = Pattern
.compile("(java\\.lang\\.reflect|sun\\.reflect).*");
static ThreadLocal<Processor> current = new ThreadLocal<Processor>();
private final static ScheduledExecutorService sheduledExecutor;
private final static ExecutorService executor;
static {
ThreadFactory threadFactory = Executors.defaultThreadFactory();
executor = new ThreadPoolExecutor(0, 64, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory,
new RejectedExecutionHandler() {
/*
* We are stealing another's thread because we have hit max
* pool size, so we cannot let the runnable's exception
* propagate back up this thread.
*/
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
return;
}
try {
r.run();
} catch (Throwable t) {
try {
Thread thread = Thread.currentThread();
thread.getUncaughtExceptionHandler().uncaughtException(thread, t);
} catch (Throwable for_real) {
// we will ignore this
}
}
}
});
sheduledExecutor = new ScheduledThreadPoolExecutor(4, threadFactory);
}
static Random random = new Random();
// TODO handle include files out of date
// TODO make splitter skip eagerly whitespace so trim is not necessary
public final static String LIST_SPLITTER = "\\s*,\\s*";
final List<String> errors = new ArrayList<String>();
final List<String> warnings = new ArrayList<String>();
final Set<Object> basicPlugins = new HashSet<Object>();
private final Set<Closeable> toBeClosed = new HashSet<Closeable>();
private Set<Object> plugins;
boolean pedantic;
boolean trace;
boolean exceptions;
boolean fileMustExist = true;
private File base = new File("").getAbsoluteFile();
private URI baseURI = base.toURI();
Properties properties;
String profile;
private Macro replacer;
private long lastModified;
private File propertiesFile;
private boolean fixup = true;
long modified;
Processor parent;
List<File> included;
CL pluginLoader;
Collection<String> filter;
HashSet<String> missingCommand;
Boolean strict;
boolean fixupMessages;
public static class FileLine {
public static final FileLine DUMMY = new FileLine(null, 0, 0);
public File file;
public int line;
public int length;
public int start;
public int end;
public FileLine() {
}
public FileLine(File file, int line, int length) {
this.file = file;
this.line = line;
this.length = length;
}
public void set(SetLocation sl) {
sl.file(file.getAbsolutePath());
sl.line(line);
sl.length(length);
}
}
public Processor() {
properties = new UTF8Properties();
}
public Processor(Properties parent) {
properties = new UTF8Properties(parent);
}
public Processor(Processor processor) {
this(processor.getProperties0());
this.parent = processor;
}
public Processor(Properties props, boolean copy) {
if (copy)
properties = new UTF8Properties(props);
else
properties = props;
}
public void setParent(Processor processor) {
this.parent = processor;
Properties updated = new UTF8Properties(processor.getProperties0());
updated.putAll(getProperties0());
properties = updated;
}
public Processor getParent() {
return parent;
}
public Processor getTop() {
if (parent == null)
return this;
return parent.getTop();
}
public void getInfo(Reporter processor, String prefix) {
if (prefix == null)
prefix = getBase() + " :";
if (isFailOk())
addAll(warnings, processor.getErrors(), prefix, processor);
else
addAll(errors, processor.getErrors(), prefix, processor);
addAll(warnings, processor.getWarnings(), prefix, processor);
processor.getErrors().clear();
processor.getWarnings().clear();
}
public void getInfo(Reporter processor) {
getInfo(processor, "");
}
private void addAll(List<String> to, List<String> from, String prefix, Reporter reporter) {
try {
for (String message : from) {
String newMessage = prefix + message;
to.add(newMessage);
Location location = reporter.getLocation(message);
if (location != null) {
SetLocation newer = location(newMessage);
for (Field f : newer.getClass().getFields()) {
if (!"message".equals(f.getName())) {
f.set(newer, f.get(location));
}
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* A processor can mark itself current for a thread.
*/
private Processor current() {
Processor p = current.get();
if (p == null)
return this;
return p;
}
public SetLocation warning(String string, Object... args) {
fixupMessages = false;
Processor p = current();
String s = formatArrays(string, args);
if (!p.warnings.contains(s))
p.warnings.add(s);
p.signal();
return location(s);
}
public SetLocation error(String string, Object... args) {
fixupMessages = false;
Processor p = current();
try {
if (p.isFailOk())
return p.warning(string, args);
String s = formatArrays(string, args);
if (!p.errors.contains(s))
p.errors.add(s);
return location(s);
} finally {
p.signal();
}
}
/**
* @deprecated Use SLF4J
* Logger.info(aQute.libg.slf4j.GradleLogging.LIFECYCLE)
* instead.
*/
@Deprecated
public void progress(float progress, String format, Object... args) {
Logger l = getLogger();
if (l.isInfoEnabled(LIFECYCLE)) {
String message = formatArrays(format, args);
if (progress > 0)
l.info(LIFECYCLE, "[{}] {}", (int) progress, message);
else
l.info(LIFECYCLE, "{}", message);
}
}
public void progress(String format, Object... args) {
progress(-1f, format, args);
}
public SetLocation error(String format, Throwable t, Object... args) {
return exception(t, format, args);
}
@Override
public SetLocation exception(Throwable t, String format, Object... args) {
Processor p = current();
if (p.trace) {
p.getLogger().info("Reported exception", t);
} else {
p.getLogger().debug("Reported exception", t);
}
if (p.exceptions) {
printExceptionSummary(t, System.err);
}
// unwrap InvocationTargetException
while ((t instanceof InvocationTargetException) && (t.getCause() != null)) {
t = t.getCause();
}
String s = formatArrays("Exception: %s", Exceptions.toString(t));
if (p.isFailOk()) {
p.warnings.add(s);
} else {
p.errors.add(s);
}
return error(format, args);
}
public int printExceptionSummary(Throwable e, PrintStream out) {
if (e == null) {
return 0;
}
int count = 10;
int n = printExceptionSummary(e.getCause(), out);
if (n == 0) {
out.println("Root cause: " + e.getMessage() + " :" + e.getClass().getName());
count = Integer.MAX_VALUE;
} else {
out.println("Rethrown from: " + e.toString());
}
out.println();
printStackTrace(e, count, out);
System.err.println();
return n + 1;
}
public void printStackTrace(Throwable e, int count, PrintStream out) {
StackTraceElement st[] = e.getStackTrace();
String previousPkg = null;
boolean shorted = false;
if (count < st.length) {
shorted = true;
count
}
for (int i = 0; i < count && i < st.length; i++) {
String cname = st[i].getClassName();
String file = st[i].getFileName();
String method = st[i].getMethodName();
int line = st[i].getLineNumber();
String pkg = Descriptors.getPackage(cname);
if (PACKAGES_IGNORED.matcher(pkg).matches())
continue;
String shortName = Descriptors.getShortName(cname);
if (pkg.equals(previousPkg))
pkg = "''";
else
pkg += "";
if (file.equals(shortName + ".java"))
file = "";
else
file = " (" + file + ")";
String l;
if (st[i].isNativeMethod())
l = "native";
else if (line > 0)
l = "" + line;
else
l = "";
out.printf(" %10s %-40s %s %s%n", l, shortName + "." + method, pkg, file);
previousPkg = pkg;
}
if (shorted)
out.println("...");
}
public void signal() {}
public List<String> getWarnings() {
fixupMessages();
return warnings;
}
public List<String> getErrors() {
fixupMessages();
return errors;
}
/**
* Standard OSGi header parser.
*
* @param value
*/
static public Parameters parseHeader(String value, Processor logger) {
return new Parameters(value, logger);
}
public Parameters parseHeader(String value) {
return new Parameters(value, this);
}
public void addClose(Closeable jar) {
assert jar != null;
toBeClosed.add(jar);
}
public void removeClose(Closeable jar) {
assert jar != null;
toBeClosed.remove(jar);
}
public boolean isPedantic() {
return current().pedantic;
}
public void setPedantic(boolean pedantic) {
this.pedantic = pedantic;
}
public void use(Processor reporter) {
setPedantic(reporter.isPedantic());
setTrace(reporter.isTrace());
setExceptions(reporter.isExceptions());
setFailOk(reporter.isFailOk());
}
public static File getFile(File base, String file) {
return IO.getFile(base, file);
}
public File getFile(String file) {
return getFile(base, file);
}
/**
* Return a list of plugins that implement the given class.
*
* @param clazz Each returned plugin implements this class/interface
* @return A list of plugins
*/
public <T> List<T> getPlugins(Class<T> clazz) {
List<T> l = new ArrayList<T>();
Set<Object> all = getPlugins();
for (Object plugin : all) {
if (clazz.isInstance(plugin))
l.add(clazz.cast(plugin));
}
return l;
}
/**
* Returns the first plugin it can find of the given type.
*
* @param <T>
* @param clazz
*/
public <T> T getPlugin(Class<T> clazz) {
Set<Object> all = getPlugins();
for (Object plugin : all) {
if (clazz.isInstance(plugin))
return clazz.cast(plugin);
}
return null;
}
/**
* Return a list of plugins. Plugins are defined with the -plugin command.
* They are class names, optionally associated with attributes. Plugins can
* implement the Plugin interface to see these attributes. Any object can be
* a plugin.
*/
public Set<Object> getPlugins() {
Set<Object> p;
synchronized (this) {
p = plugins;
if (p != null)
return p;
plugins = p = new CopyOnWriteArraySet<>();
missingCommand = new HashSet<String>();
}
// We only use plugins now when they are defined on our level
// and not if it is in our parent. We inherit from our parent
// through the previous block.
String spe = getProperty(PLUGIN);
if (NONE.equals(spe))
return p;
// The owner of the plugin is always in there.
p.add(this);
setTypeSpecificPlugins(p);
if (parent != null)
p.addAll(parent.getPlugins());
// Look only local
spe = mergeLocalProperties(PLUGIN);
String pluginPath = mergeProperties(PLUGINPATH);
loadPlugins(p, spe, pluginPath);
addExtensions(p);
for (RegistryDonePlugin rdp : getPlugins(RegistryDonePlugin.class)) {
try {
rdp.done();
} catch (Exception e) {
error("Calling done on %s, gives an exception %s", rdp, e);
}
}
return p;
}
/**
* Is called when all plugins are loaded
*
* @param p
*/
protected void addExtensions(Set<Object> p) {
}
/**
* Magic to load the plugins. This is quite tricky actually since we allow
* plugins to be downloaded (this is mainly intended for repositories since
* in general plugins should use extensions, however to bootstrap the
* extensions we need more). Since downloads might need plugins for
* passwords and protocols we need to first load the paths specified on the
* plugin clause, then check if there are any local plugins (starting with
* aQute.bnd and be able to load from our own class loader).
* <p>
* After that, we load the plugin paths, these can use the built in
* connectors.
* <p>
* Last but not least, we load the remaining plugins.
*
* @param instances
* @param pluginString
*/
protected void loadPlugins(Set<Object> instances, String pluginString, String pluginPathString) {
Parameters plugins = new Parameters(pluginString);
CL loader = getLoader();
// First add the plugin-specific paths from their path: directives
for (Entry<String,Attrs> entry : plugins.entrySet()) {
String key = removeDuplicateMarker(entry.getKey());
String path = entry.getValue().get(PATH_DIRECTIVE);
if (path != null) {
String parts[] = path.split("\\s*,\\s*");
try {
for (String p : parts) {
File f = getFile(p).getAbsoluteFile();
loader.add(f.toURI().toURL());
}
} catch (Exception e) {
error("Problem adding path %s to loader for plugin %s. Exception: (%s)", path, key, e);
}
}
}
// Try to load any plugins that are local
// these must start with aQute.bnd.* and
// and be possible to load. The main intention
// of this code is to load the URL connectors so that
// any access to remote plugins can use the connector
// model.
Set<String> loaded = new HashSet<String>();
for (Entry<String,Attrs> entry : plugins.entrySet()) {
String className = removeDuplicateMarker(entry.getKey());
Attrs attrs = entry.getValue();
logger.debug("Trying pre-plugin {}", className);
Object plugin = loadPlugin(getClass().getClassLoader(), attrs, className, true);
if (plugin != null) {
// with the marker!!
loaded.add(entry.getKey());
instances.add(plugin);
}
}
// Make sure we load each plugin only once
// by removing the entries that were successfully loaded
plugins.keySet().removeAll(loaded);
loadPluginPath(instances, pluginPathString, loader);
// Load the remaining plugins
for (Entry<String,Attrs> entry : plugins.entrySet()) {
String className = removeDuplicateMarker(entry.getKey());
Attrs attrs = entry.getValue();
logger.debug("Loading secondary plugin {}", className);
// We can defer the error if the plugin specifies
// a command name. In that case, we'll verify that
// a bnd file does not contain any references to a
// plugin
// command. The reason this feature was added was
// to compile plugin classes with the same build.
String commands = attrs.get(COMMAND_DIRECTIVE);
Object plugin = loadPlugin(loader, attrs, className, commands != null);
if (plugin != null)
instances.add(plugin);
else {
if (commands == null)
error("Cannot load the plugin %s", className);
else {
Collection<String> cs = split(commands);
missingCommand.addAll(cs);
}
}
}
}
/**
* Add the @link {@link Constants#PLUGINPATH} entries (which are file names)
* to the class loader. If this file does not exist, and there is a
* {@link Constants#PLUGINPATH_URL_ATTR} attribute then we download it first
* from that url. You can then also specify a
* {@link Constants#PLUGINPATH_SHA1_ATTR} attribute to verify the file.
*
* @see PLUGINPATH
* @param pluginPath the clauses for the plugin path
* @param loader The class loader to extend
*/
private void loadPluginPath(Set<Object> instances, String pluginPath, CL loader) {
Parameters pluginpath = new Parameters(pluginPath);
nextClause: for (Entry<String,Attrs> entry : pluginpath.entrySet()) {
File f = getFile(entry.getKey()).getAbsoluteFile();
if (!f.isFile()) {
// File does not exist! Check if we need to download
String url = entry.getValue().get(PLUGINPATH_URL_ATTR);
if (url != null) {
try {
logger.debug("downloading {} to {}", url, f.getAbsoluteFile());
URL u = new URL(url);
URLConnection connection = u.openConnection();
// Allow the URLCOnnectionHandlers to interact with the
// connection so they can sign it or decorate it with
// a password etc.
for (Object plugin : instances) {
if (plugin instanceof URLConnectionHandler) {
URLConnectionHandler handler = (URLConnectionHandler) plugin;
if (handler.matches(u))
handler.handle(connection);
}
}
// Copy the url to the file
f.getParentFile().mkdirs();
IO.copy(connection.getInputStream(), f);
// If there is a sha specified, we verify the download
// of the
// the file.
String digest = entry.getValue().get(PLUGINPATH_SHA1_ATTR);
if (digest != null) {
if (Hex.isHex(digest.trim())) {
byte[] sha1 = Hex.toByteArray(digest);
byte[] filesha1 = SHA1.digest(f).digest();
if (!Arrays.equals(sha1, filesha1)) {
error("Plugin path: %s, specified url %s and a sha1 but the file does not match the sha",
entry.getKey(), url);
}
} else {
error("Plugin path: %s, specified url %s and a sha1 '%s' but this is not a hexadecimal",
entry.getKey(), url, digest);
}
}
} catch (Exception e) {
error("Failed to download plugin %s from %s, error %s", entry.getKey(), url, e);
continue nextClause;
}
} else {
error("No such file %s from %s and no 'url' attribute on the path so it can be downloaded",
entry.getKey(), this);
continue nextClause;
}
}
logger.debug("Adding {} to loader for plugins", f);
try {
loader.add(f.toURI().toURL());
} catch (MalformedURLException e) {
// Cannot happen since every file has a correct url
}
}
}
/**
* Load a plugin and customize it. If the plugin cannot be loaded then we
* return null.
*
* @param loader Name of the loader
* @param attrs
* @param className
*/
private Object loadPlugin(ClassLoader loader, Attrs attrs, String className, boolean ignoreError) {
try {
Class< ? > c = loader.loadClass(className);
Object plugin = c.getConstructor().newInstance();
customize(plugin, attrs);
if (plugin instanceof Closeable) {
addClose((Closeable) plugin);
}
return plugin;
} catch (NoClassDefFoundError e) {
if (!ignoreError)
exception(e, "Failed to load plugin %s;%s, error: %s ", className, attrs, e);
} catch (ClassNotFoundException e) {
if (!ignoreError)
exception(e, "Failed to load plugin %s;%s, error: %s ", className, attrs, e);
} catch (Exception e) {
exception(e, "Unexpected error loading plugin %s-%s: %s", className, attrs, e);
}
return null;
}
protected void setTypeSpecificPlugins(Set<Object> list) {
list.add(getExecutor());
list.add(random);
list.addAll(basicPlugins);
}
/**
* Set the initial parameters of a plugin
*
* @param plugin
* @param map
*/
protected <T> T customize(T plugin, Attrs map) {
if (plugin instanceof Plugin) {
((Plugin) plugin).setReporter(this);
try {
if (map == null)
map = Attrs.EMPTY_ATTRS;
((Plugin) plugin).setProperties(map);
} catch (Exception e) {
error("While setting properties %s on plugin %s, %s", map, plugin, e);
}
}
if (plugin instanceof RegistryPlugin) {
((RegistryPlugin) plugin).setRegistry(this);
}
return plugin;
}
/**
* Indicates that this run should ignore errors and succeed anyway
*
* @return true if this processor should return errors
*/
@Override
public boolean isFailOk() {
String v = getProperty(Analyzer.FAIL_OK, null);
return v != null && v.equalsIgnoreCase("true");
}
public File getBase() {
return base;
}
public URI getBaseURI() {
return baseURI;
}
public void setBase(File base) {
this.base = base;
baseURI = (base == null) ? null : base.toURI();
}
public void clear() {
errors.clear();
warnings.clear();
locations.clear();
fixupMessages = false;
}
public Logger getLogger() {
return logger;
}
/**
* @deprecated Use SLF4J Logger.debug instead.
*/
@Deprecated
public void trace(String msg, Object... parms) {
Processor p = current();
Logger l = p.getLogger();
if (p.trace) {
if (l.isInfoEnabled()) {
l.info("{}", formatArrays(msg, parms));
}
} else {
if (l.isDebugEnabled()) {
l.debug("{}", formatArrays(msg, parms));
}
}
}
public <T> List<T> newList() {
return new ArrayList<T>();
}
public <T> Set<T> newSet() {
return new TreeSet<T>();
}
public static <K, V> Map<K,V> newMap() {
return new LinkedHashMap<K,V>();
}
public static <K, V> Map<K,V> newHashMap() {
return new LinkedHashMap<K,V>();
}
public <T> List<T> newList(Collection<T> t) {
return new ArrayList<T>(t);
}
public <T> Set<T> newSet(Collection<T> t) {
return new TreeSet<T>(t);
}
public <K, V> Map<K,V> newMap(Map<K,V> t) {
return new LinkedHashMap<K,V>(t);
}
public void close() throws IOException {
for (Closeable c : toBeClosed) {
try {
c.close();
} catch (IOException e) {
// Who cares?
}
}
if (pluginLoader != null)
pluginLoader.closex();
toBeClosed.clear();
}
public String _basedir(@SuppressWarnings("unused") String args[]) {
if (base == null)
throw new IllegalArgumentException("No base dir set");
return base.getAbsolutePath();
}
public String _propertiesname(String[] args) {
if (args.length > 1) {
error("propertiesname does not take arguments");
return null;
}
File pf = getPropertiesFile();
if (pf == null)
return "";
return pf.getName();
}
public String _propertiesdir(String[] args) {
if (args.length > 1) {
error("propertiesdir does not take arguments");
return null;
}
File pf = getPropertiesFile();
if (pf == null)
return "";
return pf.getParentFile().getAbsolutePath();
}
static String _uri = "${uri;<uri>[;<baseuri>]}, Resolve the uri against the baseuri. baseuri defaults to the processor base.";
public String _uri(String args[]) throws Exception {
Macro.verifyCommand(args, _uri, null, 2, 3);
URI uri = new URI(args[1]);
if (!uri.isAbsolute() || uri.getScheme().equals("file")) {
URI base;
if (args.length > 2) {
base = new URI(args[2]);
} else {
base = getBaseURI();
if (base == null) {
throw new IllegalArgumentException("No base dir set");
}
}
uri = base.resolve(uri.getSchemeSpecificPart());
}
return uri.toString();
}
static String _fileuri = "${fileuri;<path>}, Return a file uri for the specified path. Relative paths are resolved against the processor base.";
public String _fileuri(String args[]) throws Exception {
Macro.verifyCommand(args, _fileuri, null, 2, 2);
File f = IO.getFile(getBase(), args[1]).getCanonicalFile();
return f.toURI().toString();
}
/**
* Property handling ...
*/
public Properties getProperties() {
if (fixup) {
fixup = false;
begin();
}
fixupMessages = false;
return getProperties0();
}
private Properties getProperties0() {
return properties;
}
public String getProperty(String key) {
return getProperty(key, null);
}
public void mergeProperties(File file, boolean override) {
if (file.isFile()) {
try {
Properties properties = loadProperties(file);
mergeProperties(properties, override);
} catch (Exception e) {
error("Error loading properties file: %s", file);
}
} else {
if (!file.exists())
error("Properties file does not exist: %s", file);
else
error("Properties file must a file, not a directory: %s", file);
}
}
public void mergeProperties(Properties properties, boolean override) {
for (Enumeration< ? > e = properties.propertyNames(); e.hasMoreElements();) {
String key = (String) e.nextElement();
String value = properties.getProperty(key);
if (override || !getProperties().containsKey(key))
setProperty(key, value);
}
}
public void setProperties(Properties properties) {
doIncludes(getBase(), properties);
getProperties0().putAll(properties);
mergeProperties(Constants.INIT); // execute macros in -init
getProperties0().remove(Constants.INIT);
}
public void setProperties(File base, Properties properties) {
doIncludes(base, properties);
getProperties0().putAll(properties);
}
public void addProperties(File file) throws Exception {
addIncluded(file);
Properties p = loadProperties(file);
setProperties(p);
}
public void addProperties(Map< ? , ? > properties) {
for (Entry< ? , ? > entry : properties.entrySet()) {
setProperty(entry.getKey().toString(), entry.getValue() + "");
}
}
public synchronized void addIncluded(File file) {
if (included == null)
included = new ArrayList<File>();
included.add(file);
}
/**
* Inspect the properties and if you find -includes parse the line included
* manifest files or properties files. The files are relative from the given
* base, this is normally the base for the analyzer.
*
* @param ubase
* @param p
* @param done
* @throws IOException
* @throws IOException
*/
private void doIncludes(File ubase, Properties p) {
String includes = p.getProperty(INCLUDE);
if (includes != null) {
includes = getReplacer().process(includes);
p.remove(INCLUDE);
Collection<String> clauses = new Parameters(includes).keySet();
for (String value : clauses) {
boolean fileMustExist = true;
boolean overwrite = true;
while (true) {
if (value.startsWith("-")) {
fileMustExist = false;
value = value.substring(1).trim();
} else if (value.startsWith("~")) {
// Overwrite properties!
overwrite = false;
value = value.substring(1).trim();
} else
break;
}
try {
File file = getFile(ubase, value).getAbsoluteFile();
if (!file.isFile()) {
try {
URL url = new URL(value);
int n = value.lastIndexOf('.');
String ext = ".jar";
if (n >= 0)
ext = value.substring(n);
File tmp = File.createTempFile("url", ext);
try {
IO.copy(url.openStream(), tmp);
doIncludeFile(tmp, overwrite, p);
} finally {
tmp.delete();
}
} catch (MalformedURLException mue) {
if (fileMustExist)
error("Included file %s %s", file,
(file.isDirectory() ? "is directory" : "does not exist"));
} catch (Exception e) {
if (fileMustExist)
exception(e, "Error in processing included URL: %s", value);
}
} else
doIncludeFile(file, overwrite, p);
} catch (Exception e) {
if (fileMustExist)
exception(e, "Error in processing included file: %s", value);
}
}
}
}
/**
* @param file
* @param overwrite
* @throws FileNotFoundException
* @throws IOException
*/
public void doIncludeFile(File file, boolean overwrite, Properties target) throws Exception {
doIncludeFile(file, overwrite, target, null);
}
/**
* @param file
* @param overwrite
* @param extensionName
* @throws FileNotFoundException
* @throws IOException
*/
public void doIncludeFile(File file, boolean overwrite, Properties target, String extensionName) throws Exception {
if (included != null && included.contains(file)) {
error("Cyclic or multiple include of %s", file);
} else {
addIncluded(file);
updateModified(file.lastModified(), file.toString());
Properties sub;
if (file.getName().toLowerCase().endsWith(".mf")) {
try (InputStream in = new FileInputStream(file);) {
sub = getManifestAsProperties(in);
}
} else
sub = loadProperties(file);
doIncludes(file.getParentFile(), sub);
// make sure we do not override properties
for (Map.Entry< ? , ? > entry : sub.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (overwrite || !target.containsKey(key)) {
target.setProperty(key, value);
} else if (extensionName != null) {
String extensionKey = extensionName + "." + key;
if (!target.containsKey(extensionKey))
target.setProperty(extensionKey, value);
}
}
}
}
public void unsetProperty(String string) {
getProperties().remove(string);
}
public boolean refresh() {
synchronized (this) {
plugins = null; // We always refresh our plugins
}
if (propertiesFile == null)
return false;
boolean changed = updateModified(propertiesFile.lastModified(), "properties file");
if (included != null) {
for (File file : included) {
if (changed)
break;
changed |= !file.exists() || updateModified(file.lastModified(), "include file: " + file);
}
}
profile = getProperty(PROFILE); // Used in property access
if (changed) {
forceRefresh();
return true;
}
return false;
}
/**
* If strict is true, then extra verification is done.
*/
boolean isStrict() {
if (strict == null)
strict = isTrue(getProperty(STRICT)); // Used in property access
return strict;
}
public void forceRefresh() {
included = null;
Processor p = getParent();
properties = (p != null) ? new UTF8Properties(p.getProperties0()) : new UTF8Properties();
setProperties(propertiesFile, base);
propertiesChanged();
}
public void propertiesChanged() {}
/**
* Set the properties by file. Setting the properties this way will also set
* the base for this analyzer. After reading the properties, this will call
* setProperties(Properties) which will handle the includes.
*
* @param propertiesFile
* @throws FileNotFoundException
* @throws IOException
*/
public void setProperties(File propertiesFile) throws IOException {
propertiesFile = propertiesFile.getAbsoluteFile();
setProperties(propertiesFile, propertiesFile.getParentFile());
}
public void setProperties(File propertiesFile, File base) {
this.propertiesFile = propertiesFile.getAbsoluteFile();
setBase(base);
try {
if (propertiesFile.isFile()) {
// System.err.println("Loading properties " + propertiesFile);
long modified = propertiesFile.lastModified();
if (modified > System.currentTimeMillis() + 100) {
System.err.println("Huh? This is in the future " + propertiesFile);
this.modified = System.currentTimeMillis();
} else
this.modified = modified;
included = null;
Properties p = loadProperties(propertiesFile);
setProperties(p);
} else {
if (fileMustExist) {
error("No such properties file: %s", propertiesFile);
}
}
} catch (IOException e) {
error("Could not load properties %s", propertiesFile);
}
}
protected void begin() {
if (isTrue(getProperty(PEDANTIC)))
setPedantic(true);
}
public static boolean isTrue(String value) {
if (value == null)
return false;
value = value.trim();
if (value.isEmpty())
return false;
if (value.startsWith("!"))
if (value.equals("!"))
return false;
else
return !isTrue(value.substring(1));
if ("false".equalsIgnoreCase(value))
return false;
if ("off".equalsIgnoreCase(value))
return false;
if ("not".equalsIgnoreCase(value))
return false;
return true;
}
/**
* Get a property without preprocessing it with a proper default
*
* @param key
* @param deflt
*/
public String getUnprocessedProperty(String key, String deflt) {
return getProperties().getProperty(key, deflt);
}
/**
* Get a property with preprocessing it with a proper default
*
* @param key
* @param deflt
*/
public String getProperty(String key, String deflt) {
return getProperty(key, deflt, ",");
}
public String getProperty(String key, String deflt, String separator) {
return getProperty(key, deflt, separator, true);
}
@SuppressWarnings("resource")
private String getProperty(String key, String deflt, String separator, boolean inherit) {
Instruction ins = new Instruction(key);
if (!ins.isLiteral()) {
return getWildcardProperty(deflt, separator, inherit, ins);
}
@SuppressWarnings("resource")
Processor source = this;
return getLiteralProperty(key, deflt, source, inherit);
}
private String getWildcardProperty(String deflt, String separator, boolean inherit, Instruction ins) {
// Handle a wildcard key, make sure they're sorted
// for consistency
SortedList<String> sortedList = SortedList.fromIterator(iterator(inherit));
StringBuilder sb = new StringBuilder();
String del = "";
for (String k : sortedList) {
if (ins.matches(k)) {
String v = getLiteralProperty(k, null, this, inherit);
if (v != null) {
sb.append(del);
del = separator;
sb.append(v);
}
}
}
if (sb.length() == 0)
return deflt;
return sb.toString();
}
private String getLiteralProperty(String key, String deflt, Processor source, boolean inherit) {
String value = null;
// Use the key as is first, if found ok
if (filter != null && filter.contains(key)) {
Object raw = getProperties().get(key);
if (raw != null) {
if (raw instanceof String) {
value = (String) raw;
} else {
warning("Key '%s' has a non-String value: %s:%s", key, raw == null ? "" : raw.getClass().getName(),
raw);
}
}
} else {
while (source != null) {
Object raw = source.getProperties().get(key);
if (raw != null) {
if (raw instanceof String) {
value = (String) raw;
} else {
warning("Key '%s' has a non-String value: %s:%s", key,
raw == null ? "" : raw.getClass().getName(), raw);
}
break;
}
if (inherit)
source = source.getParent();
else
break;
}
// Check if we can find a replacement through the
// replacer, which takes profiles into account
if (value == null) {
value = getReplacer().getMacro(key, null);
}
}
if (value != null)
return getReplacer().process(value, source);
else if (deflt != null)
return getReplacer().process(deflt, this);
else
return null;
}
/**
* Helper to load a properties file from disk.
*
* @param file
* @throws IOException
*/
public Properties loadProperties(File file) throws IOException {
updateModified(file.lastModified(), "Properties file: " + file);
InputStream in = new FileInputStream(file);
try {
UTF8Properties p = loadProperties0(in, file);
return p;
} finally {
in.close();
}
}
/**
* Load Properties from disk. The default encoding is ISO-8859-1 but
* nowadays all files are encoded with UTF-8. So we try to load it first as
* UTF-8 and if this fails we fail back to ISO-8859-1
*
* @param in The stream to load from
* @param name The name of the file for doc reasons
* @return a Properties
* @throws IOException
*/
UTF8Properties loadProperties0(InputStream in, File file) throws IOException {
String name = file.getAbsoluteFile().toURI().getPath();
int n = name.lastIndexOf('/');
if (n > 0)
name = name.substring(0, n);
if (name.length() == 0)
name = ".";
try {
UTF8Properties p = new UTF8Properties();
p.load(in, file, this);
return replaceAll0(p, "\\$\\{\\.\\}", name);
} catch (Exception e) {
error("Error during loading properties file: %s, error: %s", name, e);
return new UTF8Properties();
}
}
/**
* Replace a string in all the values of the map. This can be used to
* preassign variables that change. I.e. the base directory ${.} for a
* loaded properties
*/
private static UTF8Properties replaceAll0(Properties p, String pattern, String replacement) {
UTF8Properties result = new UTF8Properties();
for (Iterator<Map.Entry<Object,Object>> i = p.entrySet().iterator(); i.hasNext();) {
Map.Entry<Object,Object> entry = i.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
value = value.replaceAll(pattern, replacement);
result.put(key, value);
}
return result;
}
public static Properties replaceAll(Properties p, String pattern, String replacement) {
return replaceAll0(p, pattern, replacement);
}
/**
* Print a standard Map based OSGi header.
*
* @param exports map { name => Map { attribute|directive => value } }
* @return the clauses
* @throws IOException
*/
public static String printClauses(Map< ? , ? extends Map< ? , ? >> exports) throws IOException {
return printClauses(exports, false);
}
public static String printClauses(Map< ? , ? extends Map< ? , ? >> exports,
@SuppressWarnings("unused") boolean checkMultipleVersions) throws IOException {
StringBuilder sb = new StringBuilder();
String del = "";
for (Entry< ? , ? extends Map< ? , ? >> entry : exports.entrySet()) {
String name = entry.getKey().toString();
Map< ? , ? > clause = entry.getValue();
// We allow names to be duplicated in the input
// by ending them with '~'. This is necessary to use
// the package names as keys. However, we remove these
// suffixes in the output so that you can set multiple
// exports with different attributes.
String outname = removeDuplicateMarker(name);
sb.append(del);
sb.append(outname);
printClause(clause, sb);
del = ",";
}
return sb.toString();
}
public static void printClause(Map< ? , ? > map, StringBuilder sb) throws IOException {
for (Entry< ? , ? > entry : map.entrySet()) {
Object key = entry.getKey();
// Skip directives we do not recognize
if (key.equals(INTERNAL_SOURCE_DIRECTIVE) || key.equals(INTERNAL_EXPORTED_DIRECTIVE)
|| key.equals(NO_IMPORT_DIRECTIVE) || key.equals(PROVIDE_DIRECTIVE)
|| key.equals(SPLIT_PACKAGE_DIRECTIVE) || key.equals(FROM_DIRECTIVE))
continue;
String value = ((String) entry.getValue()).trim();
sb.append(";");
sb.append(key);
sb.append("=");
quote(sb, value);
}
}
/**
* @param sb
* @param value
* @throws IOException
*/
public static boolean quote(Appendable sb, String value) throws IOException {
return OSGiHeader.quote(sb, value);
}
public Macro getReplacer() {
if (replacer == null)
return replacer = new Macro(this, getMacroDomains());
return replacer;
}
/**
* This should be overridden by subclasses to add extra macro command
* domains on the search list.
*/
protected Object[] getMacroDomains() {
return new Object[] {};
}
/**
* Return the properties but expand all macros. This always returns a new
* Properties object that can be used in any way.
*/
public Properties getFlattenedProperties() {
return getReplacer().getFlattenedProperties();
}
/**
* Return the properties but expand all macros. This always returns a new
* Properties object that can be used in any way.
*/
public Properties getFlattenedProperties(boolean ignoreInstructions) {
return getReplacer().getFlattenedProperties(ignoreInstructions);
}
/**
* Return all inherited property keys
*/
public Set<String> getPropertyKeys(boolean inherit) {
Set<String> result;
if (parent == null || !inherit) {
result = Create.set();
} else {
result = parent.getPropertyKeys(inherit);
}
for (Object o : getProperties0().keySet())
result.add(o.toString());
return result;
}
public boolean updateModified(long time, @SuppressWarnings("unused") String reason) {
if (time > lastModified) {
lastModified = time;
return true;
}
return false;
}
public long lastModified() {
return lastModified;
}
/**
* Add or override a new property.
*
* @param key
* @param value
*/
public void setProperty(String key, String value) {
checkheader: for (int i = 0; i < headers.length; i++) {
if (headers[i].equalsIgnoreCase(value)) {
value = headers[i];
break checkheader;
}
}
getProperties().put(key, value);
}
/**
* Read a manifest but return a properties object.
*
* @param in
* @throws IOException
*/
public static Properties getManifestAsProperties(InputStream in) throws IOException {
Properties p = new UTF8Properties();
Manifest manifest = new Manifest(in);
for (Iterator<Object> it = manifest.getMainAttributes().keySet().iterator(); it.hasNext();) {
Attributes.Name key = (Attributes.Name) it.next();
String value = manifest.getMainAttributes().getValue(key);
p.put(key.toString(), value);
}
return p;
}
public File getPropertiesFile() {
return propertiesFile;
}
public void setFileMustExist(boolean mustexist) {
fileMustExist = mustexist;
}
static public String read(InputStream in) throws Exception {
InputStreamReader ir = new InputStreamReader(in, "UTF8");
StringBuilder sb = new StringBuilder();
try {
char chars[] = new char[BUFFER_SIZE];
int size = ir.read(chars);
while (size > 0) {
sb.append(chars, 0, size);
size = ir.read(chars);
}
} finally {
ir.close();
}
return sb.toString();
}
/**
* Join a list.
*/
public static String join(Collection< ? > list, String delimeter) {
return join(delimeter, list);
}
public static String join(String delimeter, Collection< ? >... list) {
StringBuilder sb = new StringBuilder();
String del = "";
if (list != null) {
for (Collection< ? > l : list) {
for (Object item : l) {
sb.append(del);
sb.append(item);
del = delimeter;
}
}
}
return sb.toString();
}
public static String join(Object[] list, String delimeter) {
if (list == null)
return "";
StringBuilder sb = new StringBuilder();
String del = "";
for (Object item : list) {
sb.append(del);
sb.append(item);
del = delimeter;
}
return sb.toString();
}
public static String join(Collection< ? >... list) {
return join(",", list);
}
public static <T> String join(T list[]) {
return join(list, ",");
}
public static void split(String s, Collection<String> set) {
String elements[] = s.trim().split(LIST_SPLITTER);
for (String element : elements) {
if (element.length() > 0)
set.add(element);
}
}
public static Collection<String> split(String s) {
return split(s, LIST_SPLITTER);
}
public static Collection<String> split(String s, String splitter) {
if (s != null)
s = s.trim();
if (s == null || s.trim().length() == 0)
return Collections.emptyList();
return Arrays.asList(s.split(splitter));
}
public static String merge(String... strings) {
ArrayList<String> result = new ArrayList<String>();
for (String s : strings) {
if (s != null)
split(s, result);
}
return join(result);
}
public boolean isExceptions() {
return exceptions;
}
public void setExceptions(boolean exceptions) {
this.exceptions = exceptions;
}
/**
* Make the file short if it is inside our base directory, otherwise long.
*
* @param f
*/
public String normalize(String f) {
if (f.startsWith(base.getAbsolutePath() + "/"))
return f.substring(base.getAbsolutePath().length() + 1);
return f;
}
public String normalize(File f) {
return normalize(f.getAbsolutePath());
}
public static String removeDuplicateMarker(String key) {
int i = key.length() - 1;
while (i >= 0 && key.charAt(i) == DUPLICATE_MARKER)
--i;
return key.substring(0, i + 1);
}
public static boolean isDuplicate(String name) {
return name.length() > 0 && name.charAt(name.length() - 1) == DUPLICATE_MARKER;
}
public void setTrace(boolean x) {
trace = x;
}
public static class CL extends URLClassLoader {
CL(Processor p) {
super(new URL[0], p.getClass().getClassLoader());
}
void closex() {
Class<URLClassLoader> clazz = URLClassLoader.class;
try {
// Java 7 is a good boy, it has a close method
clazz.getMethod("close").invoke(this);
return;
} catch (Exception e) {
// ignore
}
// On Java 6, we're screwed and have to much around
// This is best effort, likely fails on non-SUN vms
try {
Field ucpField = clazz.getDeclaredField("ucp");
ucpField.setAccessible(true);
Object cp = ucpField.get(this);
Field loadersField = cp.getClass().getDeclaredField("loaders");
loadersField.setAccessible(true);
Collection< ? > loaders = (Collection< ? >) loadersField.get(cp);
for (Object loader : loaders) {
try {
Field loaderField = loader.getClass().getDeclaredField("jar");
loaderField.setAccessible(true);
JarFile jarFile = (JarFile) loaderField.get(loader);
jarFile.close();
} catch (Throwable t) {
// if we got this far, this is probably not a JAR loader
// so skip it
}
}
} catch (Throwable t) {
// probably not a SUN VM
}
}
void add(URL url) {
URL urls[] = getURLs();
for (URL u : urls) {
if (u.equals(url))
return;
}
super.addURL(url);
}
@Override
public Class< ? > loadClass(String name) throws ClassNotFoundException {
try {
Class< ? > c = super.loadClass(name);
return c;
} catch (Throwable t) {
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append(" not found, parent: ");
sb.append(getParent());
sb.append(" urls:");
sb.append(Arrays.toString(getURLs()));
sb.append(" exception:");
sb.append(t);
throw new ClassNotFoundException(sb.toString(), t);
}
}
}
protected CL getLoader() {
if (pluginLoader == null) {
pluginLoader = new CL(this);
}
return pluginLoader;
}
/*
* Check if this is a valid project.
*/
public boolean exists() {
return base != null && base.isDirectory() && propertiesFile != null && propertiesFile.isFile();
}
public boolean isOk() {
return isFailOk() || (getErrors().size() == 0);
}
/**
* Move errors and warnings to their proper place by scanning the fixup
* messages property.
*/
private void fixupMessages() {
if (fixupMessages)
return;
fixupMessages = true;
Parameters fixup = getMergedParameters(Constants.FIXUPMESSAGES);
if (fixup.isEmpty())
return;
Instructions instrs = new Instructions(fixup);
doFixup(instrs, errors, warnings, FIXUPMESSAGES_IS_ERROR);
doFixup(instrs, warnings, errors, FIXUPMESSAGES_IS_WARNING);
}
private void doFixup(Instructions instrs, List<String> messages, List<String> other, String type) {
for (int i = 0; i < messages.size(); i++) {
String message = messages.get(i);
Instruction matcher = instrs.finder(message);
if (matcher == null || matcher.isNegated())
continue;
Attrs attrs = instrs.get(matcher);
// Default the pattern applies to the errors and warnings
// but we can restrict it: e.g. restrict:=error
String restrict = attrs.get(FIXUPMESSAGES_RESTRICT_DIRECTIVE);
if (restrict != null && !restrict.equals(type))
continue;
// We can optionally replace the message with another text. E.g.
// replace:"hello world". This can use macro expansion, the ${@}
// macro is set to the old message.
String replace = attrs.get(FIXUPMESSAGES_REPLACE_DIRECTIVE);
if (replace != null) {
logger.debug("replacing {} with {}", message, replace);
setProperty("@", message);
message = getReplacer().process(replace);
messages.set(i, message);
unsetProperty("@");
}
String is = attrs.get(FIXUPMESSAGES_IS_DIRECTIVE);
if (attrs.isEmpty() || FIXUPMESSAGES_IS_IGNORE.equals(is)) {
messages.remove(i
} else {
if (is != null && !type.equals(is)) {
messages.remove(i
other.add(message);
}
}
}
}
public boolean check(String... pattern) throws IOException {
Set<String> missed = Create.set();
if (pattern != null) {
for (String p : pattern) {
boolean match = false;
Pattern pat = Pattern.compile(p);
for (Iterator<String> i = errors.iterator(); i.hasNext();) {
if (pat.matcher(i.next()).find()) {
i.remove();
match = true;
}
}
for (Iterator<String> i = warnings.iterator(); i.hasNext();) {
if (pat.matcher(i.next()).find()) {
i.remove();
match = true;
}
}
if (!match)
missed.add(p);
}
}
if (missed.isEmpty() && isPerfect())
return true;
if (!missed.isEmpty())
System.err.println("Missed the following patterns in the warnings or errors: " + missed);
report(System.err);
return false;
}
protected void report(Appendable out) throws IOException {
if (errors.size() > 0) {
out.append(String.format("
for (int i = 0; i < errors.size(); i++) {
out.append(String.format("%03d: %s%n", i, errors.get(i)));
}
}
if (warnings.size() > 0) {
out.append(String.format("
for (int i = 0; i < warnings.size(); i++) {
out.append(String.format("%03d: %s%n", i, warnings.get(i)));
}
}
}
public boolean isPerfect() {
return getErrors().size() == 0 && getWarnings().size() == 0;
}
public void setForceLocal(Collection<String> local) {
filter = local;
}
/**
* Answer if the name is a missing plugin's command name. If a bnd file
* contains the command name of a plugin, and that plugin is not available,
* then an error is reported during manifest calculation. This allows the
* plugin to fail to load when it is not needed. We first get the plugins to
* ensure it is properly initialized.
*
* @param name
*/
public boolean isMissingPlugin(String name) {
getPlugins();
return missingCommand != null && missingCommand.contains(name);
}
/**
* Append two strings to for a path in a ZIP or JAR file. It is guaranteed
* to return a string that does not start, nor ends with a '/', while it is
* properly separated with slashes. Double slashes are properly removed.
*
* <pre>
* "/" + "abc/def/" becomes "abc/def"
* @param prefix @param suffix @return
*/
public static String appendPath(String... parts) {
StringBuilder sb = new StringBuilder();
boolean lastSlash = true;
for (String part : parts) {
for (int i = 0; i < part.length(); i++) {
char c = part.charAt(i);
if (c == '/') {
if (!lastSlash)
sb.append('/');
lastSlash = true;
} else {
sb.append(c);
lastSlash = false;
}
}
if (!lastSlash && sb.length() > 0) {
sb.append('/');
lastSlash = true;
}
}
if (lastSlash && sb.length() > 0)
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
/**
* Parse the a=b strings and return a map of them.
*
* @param attrs
* @param clazz
*/
public static Attrs doAttrbutes(Object[] attrs, Clazz clazz, Macro macro) {
Attrs map = new Attrs();
if (attrs == null || attrs.length == 0)
return map;
for (Object a : attrs) {
String attr = (String) a;
int n = attr.indexOf('=');
if (n > 0) {
map.put(attr.substring(0, n), macro.process(attr.substring(n + 1)));
} else
throw new IllegalArgumentException(formatArrays(
"Invalid attribute on package-info.java in %s , %s. Must be <key>=<name> ", clazz, attr));
}
return map;
}
/**
* This method is the same as String.format but it makes sure that any
* arrays are transformed to strings.
*
* @param string
* @param parms
*/
public static String formatArrays(String string, Object... parms) {
return Strings.format(string, parms);
}
/**
* Check if the object is an array and turn it into a string if it is,
* otherwise unchanged.
*
* @param object the object to make printable
* @return a string if it was an array or the original object
*/
public static Object makePrintable(Object object) {
if (object == null)
return null;
if (object.getClass().isArray()) {
return Arrays.toString(makePrintableArray(object));
}
return object;
}
private static Object[] makePrintableArray(Object array) {
final int length = Array.getLength(array);
Object[] output = new Object[length];
for (int i = 0; i < length; i++) {
output[i] = makePrintable(Array.get(array, i));
}
return output;
}
public static String append(String... strings) {
List<String> result = Create.list();
for (String s : strings) {
result.addAll(split(s));
}
return join(result);
}
public synchronized Class< ? > getClass(String type, File jar) throws Exception {
CL cl = getLoader();
cl.add(jar.toURI().toURL());
return cl.loadClass(type);
}
public boolean isTrace() {
return current().trace;
}
public static long getDuration(String tm, long dflt) {
if (tm == null)
return dflt;
tm = tm.toUpperCase();
TimeUnit unit = TimeUnit.MILLISECONDS;
Matcher m = Pattern.compile("\\s*(\\d+)\\s*(NANOSECONDS|MICROSECONDS|MILLISECONDS|SECONDS|MINUTES|HOURS|DAYS)?")
.matcher(tm);
if (m.matches()) {
long duration = Long.parseLong(tm);
String u = m.group(2);
if (u != null)
unit = TimeUnit.valueOf(u);
duration = TimeUnit.MILLISECONDS.convert(duration, unit);
return duration;
}
return dflt;
}
/**
* Generate a random string, which is guaranteed to be a valid Java
* identifier (first character is an ASCII letter, subsequent characters are
* ASCII letters or numbers). Takes an optional parameter for the length of
* string to generate; default is 8 characters.
*/
public String _random(String[] args) {
int numchars = 8;
if (args.length > 1) {
try {
numchars = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid character count parameter in ${random} macro.");
}
}
synchronized (Processor.class) {
if (random == null)
random = new Random();
}
char[] letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
char[] alphanums = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
char[] array = new char[numchars];
for (int i = 0; i < numchars; i++) {
char c;
if (i == 0)
c = letters[random.nextInt(letters.length)];
else
c = alphanums[random.nextInt(alphanums.length)];
array[i] = c;
}
return new String(array);
}
public String _native_capability(String... args) throws Exception {
return OSInformation.getNativeCapabilityClause(this, args);
}
/**
* Set the current command thread. This must be balanced with the
* {@link #endHandleErrors(Processor)} method. The method returns the
* previous command owner or null. The command owner will receive all
* warnings and error reports.
*/
protected Processor beginHandleErrors(String message) {
logger.debug("begin {}", message);
Processor previous = current.get();
current.set(this);
return previous;
}
/**
* End a command. Will restore the previous command owner.
*
* @param previous
*/
protected void endHandleErrors(Processor previous) {
logger.debug("end");
current.set(previous);
}
public static Executor getExecutor() {
return executor;
}
public static ScheduledExecutorService getScheduledExecutor() {
return sheduledExecutor;
}
/**
* These plugins are added to the total list of plugins. The separation is
* necessary because the list of plugins is refreshed now and then so we
* need to be able to add them at any moment in time.
*
* @param plugin
*/
public synchronized void addBasicPlugin(Object plugin) {
basicPlugins.add(plugin);
Set<Object> p = plugins;
if (p != null)
p.add(plugin);
}
public synchronized void removeBasicPlugin(Object plugin) {
basicPlugins.remove(plugin);
Set<Object> p = plugins;
if (p != null)
p.remove(plugin);
}
public List<File> getIncluded() {
return included;
}
/**
* Overrides for the Domain class
*/
@Override
public String get(String key) {
return getProperty(key);
}
@Override
public String get(String key, String deflt) {
return getProperty(key, deflt);
}
@Override
public void set(String key, String value) {
getProperties().setProperty(key, value);
}
@Override
public Iterator<String> iterator() {
return iterator(true);
}
private Iterator<String> iterator(boolean inherit) {
Set<String> keys = getPropertyKeys(inherit);
final Iterator<String> it = keys.iterator();
return new Iterator<String>() {
String current;
public boolean hasNext() {
return it.hasNext();
}
public String next() {
return current = it.next();
}
public void remove() {
getProperties().remove(current);
}
};
}
public Set<String> keySet() {
return getPropertyKeys(true);
}
/**
* Printout of the status of this processor for toString()
*/
@Override
public String toString() {
try {
StringBuilder sb = new StringBuilder();
report(sb);
return sb.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Utiltity to replace an extension
*
* @param s
* @param extension
* @param newExtension
*/
public String replaceExtension(String s, String extension, String newExtension) {
if (s.endsWith(extension))
s = s.substring(0, s.length() - extension.length());
return s + newExtension;
}
/**
* Create a location object and add it to the locations
*/
List<Location> locations = new ArrayList<Location>();
static class SetLocationImpl extends Location implements SetLocation {
public SetLocationImpl(String s) {
this.message = s;
}
public SetLocation file(String file) {
this.file = file;
return this;
}
public SetLocation header(String header) {
this.header = header;
return this;
}
public SetLocation context(String context) {
this.context = context;
return this;
}
public SetLocation method(String methodName) {
this.methodName = methodName;
return this;
}
public SetLocation line(int n) {
this.line = n;
return this;
}
public SetLocation reference(String reference) {
this.reference = reference;
return this;
}
public SetLocation details(Object details) {
this.details = details;
return this;
}
public Location location() {
return this;
}
public SetLocation length(int length) {
this.length = length;
return this;
}
}
private SetLocation location(String s) {
SetLocationImpl loc = new SetLocationImpl(s);
locations.add(loc);
return loc;
}
public Location getLocation(String msg) {
for (Location l : locations)
if ((l.message != null) && l.message.equals(msg))
return l;
return null;
}
/**
* Get a header relative to this processor, tking its parents and includes
* into account.
*
* @param header
* @throws IOException
*/
public FileLine getHeader(String header) throws Exception {
return getHeader(
Pattern.compile("^[ \t]*" + Pattern.quote(header), Pattern.MULTILINE + Pattern.CASE_INSENSITIVE));
}
public static Pattern toFullHeaderPattern(String header) {
StringBuilder sb = new StringBuilder();
sb.append("^[ \t]*(").append(header).append(")(\\.[^\\s:=]*)?[ \t]*[ \t:=][ \t]*");
sb.append("[^\\\\\n\r]*(\\\\\n[^\\\\\n\r]*)*");
try {
return Pattern.compile(sb.toString(), Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
} catch (Exception e) {
return Pattern.compile("^[ \t]*" + Pattern.quote(header), Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
}
}
public FileLine getHeader(Pattern header) throws Exception {
return getHeader(header, null);
}
public FileLine getHeader(String header, String clause) throws Exception {
return getHeader(toFullHeaderPattern(header), clause == null ? null : Pattern.compile(Pattern.quote(clause)));
}
public FileLine getHeader(Pattern header, Pattern clause) throws Exception {
FileLine fl = getHeader0(header, clause);
if (fl != null)
return fl;
@SuppressWarnings("resource")
Processor rover = this;
while (rover.getPropertiesFile() == null)
if (rover.parent == null) {
return new FileLine(new File("ANONYMOUS"), 0, 0);
} else
rover = rover.parent;
return new FileLine(rover.getPropertiesFile(), 0, 0);
}
private FileLine getHeader0(Pattern header, Pattern clause) throws Exception {
FileLine fl;
File f = getPropertiesFile();
if (f != null) {
// Find in "our" local file
fl = findHeader(f, header, clause);
if (fl != null)
return fl;
// Get the includes (actually should parse the header
// to see if they override or only provide defaults?
List<File> result = getIncluded();
if (result != null) {
ExtList<File> reversed = new ExtList<File>(result);
Collections.reverse(reversed);
for (File included : reversed) {
fl = findHeader(included, header);
if (fl != null)
return fl;
}
}
}
// Ok, not on this level ...
if (getParent() != null) {
fl = getParent().getHeader(header, clause);
if (fl != null)
return fl;
}
// Ok, report the error on the sub file
// Sometimes we do not have a file ...
if (f == null && parent != null)
f = parent.getPropertiesFile();
if (f == null)
return null;
return new FileLine(f, 0, 0);
}
public static FileLine findHeader(File f, String header) throws IOException {
return findHeader(f,
Pattern.compile("^[ \t]*" + Pattern.quote(header), Pattern.MULTILINE + Pattern.CASE_INSENSITIVE));
}
public static FileLine findHeader(File f, Pattern header) throws IOException {
return findHeader(f, header, null);
}
public static FileLine findHeader(File f, Pattern header, Pattern clause) throws IOException {
if (f.isFile()) {
String s = IO.collect(f);
Matcher matcher = header.matcher(s);
while (matcher.find()) {
FileLine fl = new FileLine();
fl.file = f;
fl.start = matcher.start();
fl.end = matcher.end();
fl.length = fl.end - fl.start;
fl.line = getLine(s, fl.start);
if (clause != null) {
Matcher mclause = clause.matcher(s);
mclause.region(fl.start, fl.end);
if (mclause.find()) {
fl.start = mclause.start();
fl.end = mclause.end();
} else
// If no clause matches, maybe
// we have merged headers
continue;
}
return fl;
}
}
return null;
}
public static int getLine(String s, int index) {
int n = 0;
while (--index > 0) {
char c = s.charAt(index);
if (c == '\n') {
n++;
}
}
return n;
}
/**
* This method is about compatibility. New behavior can be conditionally
* introduced by calling this method and passing what version this behavior
* was introduced. This allows users of bnd to set the -upto instructions to
* the version that they want to be compatible with. If this instruction is
* not set, we assume the latest version.
*/
Version upto = null;
public boolean since(Version introduced) {
if (upto == null) {
String uptov = getProperty(UPTO);
if (uptov == null) {
upto = Version.HIGHEST;
return true;
}
if (!Version.VERSION.matcher(uptov).matches()) {
error("The %s given version is not a version: %s", UPTO, uptov);
upto = Version.HIGHEST;
return true;
}
upto = new Version(uptov);
}
return upto.compareTo(introduced) >= 0;
}
/**
* Report the details of this processor. Should in general be overridden
*
* @param table
* @throws Exception
*/
public void report(Map<String,Object> table) throws Exception {
table.put("Included Files", getIncluded());
table.put("Base", getBase());
table.put("Properties", getProperties0().entrySet());
}
/**
* Simplified way to check booleans
*/
public boolean is(String propertyName) {
return isTrue(getProperty(propertyName));
}
/**
* Return merged properties. The parameters provide a list of property names
* which are concatenated in the output, separated by a comma. Not only are
* those property names looked for, also all property names that have that
* constant as a prefix, a '.', and then whatever (.*). The result is either
* null if nothing was found or a list of properties
*/
public String mergeProperties(String key) {
return mergeProperties(key, ",");
}
public String mergeLocalProperties(String key) {
if (since(About._3_3)) {
return getProperty(makeWildcard(key), null, ",", false);
} else
return mergeProperties(key);
}
public String mergeProperties(String key, String separator) {
if (since(About._2_4))
return getProperty(makeWildcard(key), null, separator, true);
else
return getProperty(key);
}
private String makeWildcard(String key) {
return key + "|" + key + ".*";
}
/**
* Get a Parameters from merged properties
*/
public Parameters getMergedParameters(String key) {
return new Parameters(mergeProperties(key));
}
/**
* Add an element to an array, creating a new one if necessary
*/
public <T> T[] concat(Class<T> type, T[] prefix, T suffix) {
@SuppressWarnings("unchecked")
T[] result = (T[]) Array.newInstance(type, (prefix != null ? prefix.length : 0) + 1);
if (result.length > 1) {
System.arraycopy(prefix, 0, result, 0, result.length - 1);
}
result[result.length - 1] = suffix;
return result;
}
/**
* Try to get a Jar from a file name/path or a url, or in last resort from
* the classpath name part of their files.
*
* @param name URL or filename relative to the base
* @param from Message identifying the caller for errors
* @return null or a Jar with the contents for the name
*/
public Jar getJarFromName(String name, String from) {
File file = new File(name);
if (!file.isAbsolute())
file = new File(getBase(), name);
if (file.exists())
try {
Jar jar = new Jar(file);
addClose(jar);
return jar;
} catch (Exception e) {
error("Exception in parsing jar file for %s: %s %s", from, name, e);
}
// It is not a file ...
try {
// Lets try a URL
URL url = new URL(name);
Jar jar = new Jar(fileName(url.getPath()));
addClose(jar);
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
long lastModified = connection.getLastModified();
if (lastModified == 0)
// We assume the worst :-(
lastModified = System.currentTimeMillis();
EmbeddedResource.build(jar, in, lastModified);
in.close();
return jar;
} catch (IOException ee) {
// ignore
}
return null;
}
private String fileName(String path) {
int n = path.lastIndexOf('/');
if (n > 0)
return path.substring(n + 1);
return path;
}
/**
* Return the name of the properties file
*/
public String _thisfile(String[] args) {
if (propertiesFile == null) {
error("${thisfile} executed on a processor without a properties file");
return null;
}
return propertiesFile.getAbsolutePath().replaceAll("\\\\", "/");
}
/**
* Copy the settings of another processor
*/
public void getSettings(Processor p) {
this.trace = p.isTrace();
this.pedantic = p.isPedantic();
this.exceptions = p.isExceptions();
}
/**
* Return a range expression for a filter from a version. By default this is
* based on consumer compatibility. You can specify a third argument (true)
* to get provider compatibility.
*
* <pre>
* ${frange;1.2.3} ->
* (&(version>=1.2.3)(!(version>=2.0.0)) ${frange;1.2.3, true} ->
* (&(version>=1.2.3)(!(version>=1.3.0)) ${frange;[1.2.3,2.3.4)} ->
* (&(version>=1.2.3)(!(version>=2.3.4))
* </pre>
*/
public String _frange(String[] args) {
if (args.length < 2 || args.length > 3) {
error("Invalid filter range, 2 or 3 args ${frange;<version>[;true|false]}");
return null;
}
String v = args[1];
boolean isProvider = args.length == 3 && isTrue(args[2]);
VersionRange vr;
if (Verifier.isVersion(v)) {
Version l = new Version(v);
Version h = isProvider ? new Version(l.getMajor(), l.getMinor() + 1, 0)
: new Version(l.getMajor() + 1, 0, 0);
vr = new VersionRange(true, l, h, false);
} else if (Verifier.isVersionRange(v)) {
vr = new VersionRange(v);
} else {
error("The _frange parameter %s is neither a version nor a version range", v);
return null;
}
return vr.toFilter();
}
public String _findfile(String args[]) {
File f = getFile(args[1]);
List<String> files = new ArrayList<String>();
tree(files, f, "", new Instruction(args[2]));
return join(files);
}
void tree(List<String> list, File current, String path, Instruction instr) {
if (path.length() > 0)
path = path + "/";
String subs[] = current.list();
if (subs != null) {
for (String sub : subs) {
File f = new File(current, sub);
if (f.isFile()) {
if (instr.matches(sub) && !instr.isNegated())
list.add(path + sub);
} else
tree(list, f, path + sub, instr);
}
}
}
} |
package picoded.conv;
// Java libs
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParser;
// Jackson library
import com.fasterxml.jackson.databind.ObjectMapper;
/// json simplification helpers. When you do not need custom object / array structures
/// Technical notes: Jackson is used internally.
public class ConvertJSON {
private ConvertJSON(){
}
/// cachedMapper builder, used to setup the config
private static ObjectMapper cachedMapperBuilder() {
ObjectMapper cm = new ObjectMapper();
// Allow comments in strings
cm.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
// Allow leading 0's in the int
cm.configure(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS, true);
// Allow single quotes in JSON
cm.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
// Actual map builder
return cm;
}
/// Internal reused object mapper, this is via jackson json conerter
private static ObjectMapper cachedMapper = cachedMapperBuilder();
// From java objects to JSON string conversion
/// Converts input object into a json string
public static String fromMap(Map<String, ?> input) {
return fromObject(input);
}
/// Converts input object into a json string
public static String fromList(List<?> input) {
return fromObject(input);
}
/// Converts input object into a json string
/// Note that this is the core "to JSON string" function that all
/// other type strict varient is built ontop of.
public static String fromObject(Object input) {
try {
return cachedMapper.writeValueAsString(input);
} catch (IOException e) { // IOException shdnt occur, as input is not a file
throw new IllegalArgumentException(e);
}
}
// From JSON string to java object
/// Converts json string into an mapping object
@SuppressWarnings("unchecked")
public static Map<String, Object> toMap(String input) {
return (Map<String, Object>) toCustomClass(input, Map.class);
}
/// Converts json string into an list array
@SuppressWarnings("unchecked")
public static List<Object> toList(String input) {
return (List<Object>) toCustomClass(input, List.class);
}
/// Converts json string into any output object (depends on input)
public static Object toObject(String input) {
return toCustomClass(input, Object.class);
}
/// Converts json string into a custom output object
/// Note that this is the core "to java object" function that all
/// other type strict varient is built ontop of.
public static Object toCustomClass(String input, Class<?> c) {
try {
return cachedMapper.readValue(input, c);
} catch (IOException e) { // IOException shdnt occur, as input is not a file
throw new IllegalArgumentException(e);
}
}
// From string to array conversion
/// Converts a json string into a string[] array
public static String[] toStringArray(String input) {
List<Object> rawList = ConvertJSON.toList(input);
String[] ret = new String[rawList.size()];
if (rawList.isEmpty()) {
return ret;
}
for (int a = 0; a < rawList.size(); ++a) {
ret[a] = (String) rawList.get(a);
}
return ret;
}
/// Converts a json string into a double[] array
public static double[] toDoubleArray(String input) {
List<Object> rawList = ConvertJSON.toList(input);
double[] ret = new double[rawList.size()];
if (rawList.isEmpty()) {
return ret;
}
for (int a = 0; a < rawList.size(); ++a) {
ret[a] = ((Number) rawList.get(a)).doubleValue();
}
return ret;
}
/// Converts a json string into a int[] array
public static int[] toIntArray(String input) {
List<Object> rawList = ConvertJSON.toList(input);
int[] ret = new int[rawList.size()];
if (rawList.isEmpty()) {
return ret;
}
for (int a = 0; a < rawList.size(); ++a) {
ret[a] = ((Number) rawList.get(a)).intValue();
}
return ret;
}
/// Converts a json string into a Object[] array
public static Object[] toObjectArray(String input) {
List<Object> rawList = ConvertJSON.toList(input);
Object[] ret = new Object[rawList.size()];
if (rawList.isEmpty()) {
return ret;
}
for (int a = 0; a < rawList.size(); ++a) {
ret[a] = rawList.get(a);
}
return ret;
}
// From array conversion to string
/// Converts a Object[] to a json string
public static String fromArray(Object[] input) {
throw new IllegalArgumentException("to implement");
}
/// Converts a String[] to a json string
public static String fromArray(String[] input) {
throw new IllegalArgumentException("to implement");
}
/// Converts a double[] to a json string
public static String fromArray(double[] input) {
throw new IllegalArgumentException("to implement");
}
/// Converts a int[] to a json string
public static String fromArray(int[] input) {
throw new IllegalArgumentException("to implement");
}
} |
package com.sleekbyte.tailor.output;
import com.sleekbyte.tailor.common.Location;
import com.sleekbyte.tailor.common.Rules;
import com.sleekbyte.tailor.common.Severity;
import com.sleekbyte.tailor.format.Formatter;
import com.sleekbyte.tailor.utils.Pair;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.AnsiConsole;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Generates and outputs formatted analysis messages for Xcode.
*/
public final class Printer implements Comparable<Printer> {
private File inputFile;
private Severity maxSeverity;
private Formatter formatter;
private Map<String, ViolationMessage> msgBuffer = new HashMap<>();
private Set<Pair<Integer, Integer>> ignoredRegions = new HashSet<>();
private boolean shouldPrintParseErrorMessage = false;
/**
* Constructs a printer for the specified input file, maximum severity, and color setting.
*
* @param inputFile The source file to verify
* @param maxSeverity The maximum severity of any emitted violation messages
* @param formatter Format to print in
*/
public Printer(File inputFile, Severity maxSeverity, Formatter formatter) {
this.inputFile = inputFile;
this.maxSeverity = maxSeverity;
this.formatter = formatter;
}
/**
* Prints warning message.
*
* @param rule Rule associated with warning
* @param warningMsg Warning message to print
* @param location Location object containing line and column number for printing
*/
public void warn(Rules rule, String warningMsg, Location location) {
print(rule, Severity.WARNING, warningMsg, location);
}
public void warn(String warningMsg, Location location) {
print(null, Severity.WARNING, warningMsg, location);
}
/**
* Prints error message.
*
* @param rule Rule associated with error
* @param errorMsg Error message to print
* @param location Location object containing line and column number for printing
*/
public void error(Rules rule, String errorMsg, Location location) {
print(rule, Severity.min(Severity.ERROR, maxSeverity), errorMsg, location);
}
// Visible for testing only
public static String genOutputStringForTest(Rules rule, String filePath, int line, Severity severity, String msg) {
return new ViolationMessage(rule, filePath, line, 0, severity, msg).toString();
}
// Visible for testing only
public static String genOutputStringForTest(String filePath, int line, int column, Severity severity, String msg) {
return new ViolationMessage(filePath, line, column, severity, msg).toString();
}
// Visible for testing only
public static String genOutputStringForTest(Rules rule, String filePath, int line, int column, Severity severity,
String msg) {
return new ViolationMessage(rule, filePath, line, column, severity, msg).toString();
}
public List<ViolationMessage> getViolationMessages() {
return new ArrayList<>(this.msgBuffer.values());
}
/**
* Calls formatter to display all violation or error messages.
*
* @throws IOException if formatter cannot retrieve canonical path from inputFile
*/
public void printAllMessages() throws IOException {
if (shouldPrintParseErrorMessage) {
printParseErrorMessage();
} else {
List<ViolationMessage> outputList = getViolationMessages().stream()
.filter(this::filterIgnoredRegions).collect(Collectors.toList());
Collections.sort(outputList);
formatter.displayViolationMessages(outputList, inputFile);
}
}
public long getNumErrorMessages() {
return getNumMessagesWithSeverity(Severity.ERROR);
}
public long getNumWarningMessages() {
return getNumMessagesWithSeverity(Severity.WARNING);
}
/**
* Suppress analysis output for a given region.
*
* @param start line number where the region begins
* @param end line number where the region ends
*/
public void ignoreRegion(int start, int end) {
this.ignoredRegions.add(new Pair<>(start, end));
}
public void setShouldPrintParseErrorMessage(boolean shouldPrintError) {
shouldPrintParseErrorMessage = shouldPrintError;
}
/**
* Print all rules along with their descriptions to STDOUT.
*/
public static void printRules() {
Rules[] rules = Rules.values();
AnsiConsole.out.println(Ansi.ansi().render(String.format("@|bold %d rules available|@%n", rules.length)));
for (Rules rule : rules) {
AnsiConsole.out.println(Ansi.ansi().render(String.format("@|bold %s|@%n"
+ "@|underline Description:|@ %s%n"
+ "@|underline Style Guide:|@ %s%n", rule.getName(), rule.getDescription(), rule.getLink())));
}
}
@Override
public int compareTo(Printer printer) {
return this.inputFile.compareTo(printer.inputFile);
}
@Override
public boolean equals(Object printerObject) {
if (!(printerObject instanceof Printer)) {
return false;
}
return this.inputFile.equals(((Printer) printerObject).inputFile);
}
@Override
public int hashCode() {
assert false : "hashCode not designed";
return 100;
}
private void print(Rules rule, Severity severity, String msg, Location location) {
ViolationMessage violationMessage;
if (rule != null) {
violationMessage = new ViolationMessage(rule, location.line, location.column, severity, msg);
} else {
violationMessage = new ViolationMessage(location.line, location.column, severity, msg);
}
try {
violationMessage.setFilePath(this.inputFile.getCanonicalPath());
} catch (IOException e) {
System.err.println("Error in getting canonical path of input file: " + e.getMessage());
}
this.msgBuffer.put(violationMessage.toString(), violationMessage);
}
private void printParseErrorMessage() throws IOException {
formatter.displayParseErrorMessage(inputFile);
}
private long getNumMessagesWithSeverity(Severity severity) {
return msgBuffer.values().stream()
.filter(this::filterIgnoredRegions)
.filter(msg -> msg.getSeverity().equals(severity)).count();
}
private boolean filterIgnoredRegions(ViolationMessage msg) {
for (Pair<Integer, Integer> ignoredRegion : ignoredRegions) {
if (ignoredRegion.getFirst() <= msg.getLineNumber()
&& msg.getLineNumber() <= ignoredRegion.getSecond()) {
return false;
}
}
return true;
}
} |
package chess.model;
import chess.model.pieces.ChessPiece;
public class BoardSpace {
private Position position;
private ChessPiece piece;
public BoardSpace(Position position) {
this.position = position;
}
public ChessPiece getPiece() {
return piece;
}
public void setPiece(ChessPiece piece) {
this.piece = piece;
}
public Position getPosition() {
return this.position;
}
/**
* Checks if this space has a piece on it
* @return
*/
public boolean isOccupied() {
return this.piece != null;
}
public boolean isEmpty() {
return !isOccupied();
}
} |
package com.st.controller;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.st.domain.salesforce.Account;
import com.st.repository.AccountRepository;
@RestController
public class AccountController {
private final static Logger logger = LoggerFactory.getLogger(AccountController.class);
@Autowired
private AccountRepository accountRepository;
private final static String HC_LASTOP = "FAILED";
@RequestMapping(value = "/api/accounts", method = RequestMethod.GET)
public List<Account> findAllAccounts(@RequestParam(value = "createddate", required = false) Date createddate) {
List<Account> accounts = null;
if (createddate != null) {
accounts = accountRepository.findByCreateddateAfter(createddate);
} else {
accounts = accountRepository.findAll();
}
return accounts;
}
@RequestMapping(value = "/api/accounts", method = RequestMethod.POST)
public ResponseEntity<Account> addAccount(@RequestBody Account account) {
logger.debug("account: " + account.toString());
if (StringUtils.isEmpty(account.getName())) {
logger.debug("Account must have a name. Returning error: " + HttpStatus.BAD_REQUEST);
return new ResponseEntity<Account>(HttpStatus.BAD_REQUEST);
}
account.setCreateddate(new Date());
Account entity = accountRepository.save(account);
logger.debug("account saved: " + entity.toString());
if (HC_LASTOP.equals(entity.get_hc_lastop())) {
return new ResponseEntity<Account>(entity, HttpStatus.CONFLICT);
}
ResponseEntity<Account> response = new ResponseEntity<>(entity, HttpStatus.OK);
return response;
}
} |
package org.yamcs.client;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.yamcs.protobuf.Yamcs.NamedObjectId;
import org.yamcs.protobuf.Yamcs.Value;
import com.google.protobuf.Timestamp;
public class Helpers {
public static Instant toInstant(Timestamp timestamp) {
return Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos());
}
public static NamedObjectId toNamedObjectId(String name) {
// Some API calls still require NamedObjectId objects, which are bothersome.
// This method automatically generates them from a name which can either be the qualified name (preferred)
// or some alias in the form NAMESPACE/NAME
if (name.startsWith("/")) {
return NamedObjectId.newBuilder().setName(name).build();
} else {
String[] parts = name.split("\\/", 2);
if (parts.length < 2) {
throw new IllegalArgumentException(String.format("'%s' is not a valid name."
+ " Use fully-qualified names or, alternatively,"
+ " an alias in the format NAMESPACE/NAME", name));
}
return NamedObjectId.newBuilder().setNamespace(parts[0]).setName(parts[1]).build();
}
}
public static String toName(NamedObjectId id) {
if (id.hasNamespace()) {
return id.getNamespace() + "/" + id.getName();
} else {
return id.getName();
}
}
/**
* Converts a Protobuf value from the API into a Java equivalent
*/
public static Object parseValue(Value value) {
switch (value.getType()) {
case FLOAT:
return value.getFloatValue();
case DOUBLE:
return value.getDoubleValue();
case SINT32:
return value.getSint32Value();
case UINT32:
return value.getUint32Value() & 0xFFFFFFFFL;
case UINT64:
return value.getUint64Value();
case SINT64:
return value.getSint64Value();
case STRING:
return value.getStringValue();
case BOOLEAN:
return value.getBooleanValue();
case TIMESTAMP:
return Instant.parse(value.getStringValue());
case ENUMERATED:
return value.getStringValue();
case BINARY:
return value.getBinaryValue().toByteArray();
case ARRAY:
List<Object> arr = new ArrayList<>(value.getArrayValueCount());
for (Value item : value.getArrayValueList()) {
arr.add(parseValue(item));
}
return arr;
case AGGREGATE:
Map<String, Object> obj = new LinkedHashMap<>();
for (int i = 0; i < value.getAggregateValue().getNameCount(); i++) {
obj.put(value.getAggregateValue().getName(i), value.getAggregateValue().getValue(i));
}
return obj;
default:
throw new IllegalStateException("Unexpected value type " + value.getType());
}
}
} |
package com.toomasr.sgf4j.board;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Control;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.StrokeType;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class BoardSquare extends StackPane {
private static final int HIGHLIGHT_MULTIPLIER = 3;
private static final double RADIUS_MULTIPLIER = 2.32;
private static final double FONT_MULTIPLIER = 1.8125;
public static int width = 29;
private final int x;
private final int y;
private StoneState squareState = StoneState.EMPTY;
private double strokeWidth = 1.5;
private Circle highLightCircle = new Circle(15, 15, 10);
// main visual stone - a circle shape
private Circle stoneCircle = new Circle(15, 15, 12.5);
private Text text;
private Line lineH;
private Line lineV;
private Circle starPoint;
private Rectangle rect;
public BoardSquare(int x, int y) {
super();
this.x = x;
this.y = y;
setSize(width);
setPadding(Insets.EMPTY);
setAlignment(Pos.CENTER);
// some defaults
highLightCircle.setStrokeType(StrokeType.INSIDE);
highLightCircle.setStrokeWidth(strokeWidth);
highLightCircle.setSmooth(true);
stoneCircle.setStrokeType(StrokeType.INSIDE);
stoneCircle.setStroke(Color.BLACK);
stoneCircle.setStrokeWidth(strokeWidth);
stoneCircle.setSmooth(true);
double[] xy = updateLayoutBounds(stoneCircle);
updateLayoutBounds(highLightCircle, xy[0], xy[1]);
init();
}
private void setSize(int width) {
setMinWidth(width);
setPrefWidth(width);
setMaxWidth(Control.USE_PREF_SIZE);
setMinHeight(width);
setPrefHeight(width);
setMaxHeight(Control.USE_PREF_SIZE);
}
private void init() {
if (rect != null) {
getChildren().remove(rect);
}
rect = new Rectangle(width, width);
rect.setFill(Color.WHITE);
getChildren().add(rect);
// we add the lines that make up the intersection on each rectangle
addTheBgIntersection();
}
private void addTheBgIntersection() {
if (lineH != null) {
getChildren().remove(lineH);
}
lineH = new Line(0, width / 2, width, width / 2);
if (x == 1) {
// the + 1 is to compensate for the stroke width overflow
lineH = new Line(width / 2 + 1, width / 2, width, width / 2);
getChildren().add(lineH);
setAlignment(lineH, Pos.CENTER_RIGHT);
}
else if (x == 19) {
lineH = new Line(width / 2, width / 2, width - 1, width / 2);
getChildren().add(lineH);
setAlignment(lineH, Pos.CENTER_LEFT);
}
else {
getChildren().add(lineH);
setAlignment(lineH, Pos.CENTER);
}
if (lineV != null) {
getChildren().remove(lineV);
}
lineV = new Line(width / 2, 0, width / 2, width);
if (y == 1) {
// the -1 is compensate for the stroke width overflow
lineV = new Line(width / 2, width / 2 - 1, width / 2, 0);
getChildren().add(lineV);
setAlignment(lineV, Pos.BOTTOM_CENTER);
}
else if (y == 19) {
lineV = new Line(width / 2, width / 2, width / 2, width - 1);
getChildren().add(lineV);
setAlignment(lineV, Pos.TOP_CENTER);
}
else {
getChildren().add(lineV);
setAlignment(lineV, Pos.CENTER);
}
if (starPoint != null) {
getChildren().remove(starPoint);
}
if ((x == 4 && y == 4) || (x == 16 && y == 4)
|| (x == 4 && y == 16) || (x == 16 && y == 16)
|| (x == 10 && y == 4) || (x == 10 && y == 16)
|| (x == 4 && y == 10) || (x == 16 && y == 10)
|| (x == 10 && y == 10)) {
starPoint = new Circle(3, 3, 3);
starPoint.setStroke(Color.BLACK);
getChildren().add(starPoint);
}
}
public void removeStone() {
squareState = StoneState.EMPTY;
stoneCircle.setVisible(false);
highLightCircle.setVisible(false);
}
public void addOverlayText(String str) {
// there are SGF files that place multiple labels
// on a single square - right now won't support that
// and always showing the latest one
removeOverlayText();
text = new Text(str);
Font font = Font.font(Font.getDefault().getName(), FontWeight.MEDIUM, width/FONT_MULTIPLIER);
text.setFont(font);
text.setStroke(Color.SADDLEBROWN);
text.setFill(Color.SADDLEBROWN);
setAlignment(text, Pos.CENTER);
getChildren().add(text);
lineH.setVisible(false);
lineV.setVisible(false);
if (starPoint != null) {
starPoint.setVisible(false);
}
}
public void removeOverlayText() {
if (getChildren().contains(text)) {
getChildren().remove(text);
}
lineH.setVisible(true);
lineV.setVisible(true);
if (starPoint != null) {
starPoint.setVisible(true);
}
}
public void placeStone(StoneState stoneState) {
this.squareState = stoneState;
stoneCircle.setRadius( width / RADIUS_MULTIPLIER);
highLightCircle.setRadius(( width / HIGHLIGHT_MULTIPLIER ) - 1.5);
stoneCircle.setVisible(true);
if (stoneState.equals(StoneState.WHITE)) {
stoneCircle.setFill(Color.WHITE);
}
else {
stoneCircle.setFill(Color.BLACK);
}
if (!getChildren().contains(stoneCircle)) {
getChildren().add(stoneCircle);
}
double[] xy = updateLayoutBounds(stoneCircle);
updateLayoutBounds(highLightCircle, xy[0], xy[1]);
}
public void highLightStone() {
if (squareState.equals(StoneState.WHITE)) {
highLightCircle.setStroke(Color.BLACK);
highLightCircle.setFill(Color.WHITE);
}
else {
highLightCircle.setStroke(Color.WHITE);
highLightCircle.setFill(Color.BLACK);
}
highLightCircle.setVisible(true);
if (!getChildren().contains(highLightCircle)) {
getChildren().add(highLightCircle);
}
double[] xy = updateLayoutBounds(stoneCircle);
updateLayoutBounds(highLightCircle, xy[0], xy[1]);
}
public void deHighLightStone() {
if (highLightCircle != null) {
highLightCircle.setVisible(false);
}
}
@Override
public String toString() {
return "BoardStone [x=" + x + ", y=" + y + ", squareState=" + squareState + "]";
}
public int getSize() {
return width;
}
private void updateLayoutBounds(Circle circle, double x, double y) {
circle.setLayoutX(x);
circle.setLayoutY(y);
}
private double[] updateLayoutBounds(Circle circle) {
double layoutX = 0 - circle.getLayoutBounds().getMinX();
double layoutY = 0 - circle.getLayoutBounds().getMinY();
if (layoutX < 0 )
layoutX = 0d;
if (layoutY < 0)
layoutY = 0d;
updateLayoutBounds(circle, layoutX, layoutY);
return new double[] {layoutX, layoutY};
}
public void resizeTo(int newSize) {
BoardSquare.width = newSize;
setPrefSize((double) newSize, (double) newSize);
setMinSize((double) newSize, (double) newSize);
setMaxSize((double) newSize, (double) newSize);
init();
double layoutX = -1;
double layoutY = -1;
if (getChildren().contains(stoneCircle)) {
getChildren().remove(stoneCircle);
stoneCircle.setRadius(width / RADIUS_MULTIPLIER);
updateLayoutBounds(stoneCircle);
getChildren().add(stoneCircle);
}
if (getChildren().contains(highLightCircle)) {
getChildren().remove(highLightCircle);
highLightCircle.setRadius(width / HIGHLIGHT_MULTIPLIER);
if (layoutX >= 0) {
// nice, computed from last round
}
else {
layoutX = 0 - highLightCircle.getLayoutBounds().getMinX();
layoutY = 0 - highLightCircle.getLayoutBounds().getMinY();
if (layoutX < 0 )
layoutX = 0d;
if (layoutY < 0)
layoutY = 0d;
}
updateLayoutBounds(highLightCircle, layoutX, layoutY);
getChildren().add(highLightCircle);
}
if (getChildren().contains(text)) {
String str = text.getText();
removeOverlayText();
addOverlayText(str);
}
}
} |
package org.yamcs;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yamcs.commanding.CommandReleaser;
import org.yamcs.parameter.ParameterProvider;
import org.yamcs.tctm.SimpleTcTmService;
import org.yamcs.tctm.TcTmService;
import org.yamcs.utils.YObjectLoader;
/**
* Used to create processors as defined in yprocessor.yaml
*
* @author mache
*
*/
public class ProcessorFactory {
static Logger log=LoggerFactory.getLogger(YProcessor.class.getName());
/**
* Create a channel with the give name, type, creator and spec
*
* type is used to load the tm, parameter and command classes as defined in yprocessor.yaml
* spec if not null is passed as an extra argument to those classes - it is used for example when creating replay channels to pass on the data that has to be replayed.
* should probably be changed from string to some sort of object.
*
* @param yamcsInstance
* @param name
* @param type
* @param creator
* @param spec
* @return
* @throws YProcessorException
* @throws ConfigurationException
*/
static public YProcessor create(String yamcsInstance, String name, String type, String creator, Object spec) throws YProcessorException, ConfigurationException {
boolean initialized = false;
TcTmService tctms=null;
Map<String,Object> channelConfig = null;
YConfiguration conf=YConfiguration.getConfiguration("yprocessor");
try {
if(conf.containsKey(type,"tmtcpp")) {
Map<String, Object> m = (Map<String, Object>) conf.getMap(type, "tmtcpp");
String clsName = YConfiguration.getString(m, "class");
Object args = m.get("args");
tctms= loadObject(clsName, yamcsInstance, args, spec);
} else {
TmPacketProvider tm=null;
List<ParameterProvider> pps = new ArrayList<ParameterProvider>();
CommandReleaser tc=null;
if(conf.containsKey(type,"telemetryProvider")) {
Map<String, Object> m = (Map<String, Object>) conf.getMap(type, "telemetryProvider");
String tmClass = YConfiguration.getString(m, "class");
Object tmArgs = m.get("args");
tm = loadObject(tmClass, yamcsInstance, tmArgs, spec);
initialized = true;
} else {//TODO: it should work without telemetryProvider (currently causes a NPE in Channel.java)
throw new ConfigurationException("No telemetryProvider specified for channel of type '"+type+"' in yprocessor.yaml");
}
if(conf.containsKey(type,"parameterProviders")) {
List<Map<String, Object>> l = conf.getList(type, "parameterProviders");
for(Map<String, Object> m:l) {
String paramClass = YConfiguration.getString(m, "class");
Object paramArgs = m.get("args");
ParameterProvider pp = loadObject(paramClass, yamcsInstance, paramArgs, spec);
pps.add(pp);
}
initialized = true;
}
if(conf.containsKey(type, "commandReleaser")) {
Map<String, Object> m = (Map<String, Object>) conf.getMap(type, "commandReleaser");
String commandClass = YConfiguration.getString(m, "class");
Object commandArgs = m.get("args");
tc = loadObject(commandClass, yamcsInstance, commandArgs, spec);
initialized = true;
}
if(conf.containsKey(type, "config")) {
channelConfig = (Map<String, Object>) conf.getMap(type, "config");
}
tctms=new SimpleTcTmService(tm, pps, tc);
if(!initialized) {
throw new ConfigurationException("For channel type '"+type+"', none of telemetryProvider, parameterProviders or commandReleaser specified");
}
}
} catch (IOException e) {
throw new ConfigurationException("Cannot load service",e);
}
return create(yamcsInstance, name, type, tctms, creator, channelConfig);
}
/**
* loads objects but passes only non null parameters
*/
static private <T> T loadObject(String className, String yamcsInstance, Object args, Object spec) throws ConfigurationException, IOException {
List<Object> newargs = new ArrayList<Object>();
newargs.add(yamcsInstance);
if(args!=null) {
newargs.add(args);
}
if(spec!=null) {
newargs.add(spec);
}
return new YObjectLoader<T>().loadObject(className, newargs.toArray());
}
static public YProcessor create(String instance, String name, String type, TcTmService tctms, String creator) throws YProcessorException, ConfigurationException {
return create(instance, name, type, tctms, creator, null);
}
/**
* Create a Processor by specifying the service.
* The type is not used in this case, except for showing it in the yamcs monitor.
**/
static public YProcessor create(String instance, String name, String type, TcTmService tctms, String creator, Map<String, Object> config) throws YProcessorException, ConfigurationException {
YProcessor yproc = new YProcessor(instance, name, type, creator);
yproc.init(tctms, config);
return yproc;
}
} |
package com.yiji.falcon.agent.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/*
* :
* guqiu@yiji.com 2016-06-22 17:48
*/
/**
* @author guqiu@yiji.com
*/
public class FileUtil {
private static final Logger log = LoggerFactory.getLogger(FileUtil.class);
/**
*
* @param filePath
* @return
* false
*/
public static boolean isExist(String filePath){
File file = new File(filePath);
return file.exists() && file.isFile();
}
/**
*
*
* @param fileName
* @return
* @throws IOException
*/
public static String getTextFileContent(String fileName){
StringBuilder text = new StringBuilder();
File f = new File(fileName);
if (!f.exists()) {
try {
if(!f.createNewFile()){
log.warn("");
}
} catch (IOException e) {
log.error("");
}
}
try {
FileInputStream fis = new FileInputStream(f);
InputStreamReader read = new InputStreamReader(fis,"UTF-8");
BufferedReader reader = new BufferedReader(read);
String line = "";
while((line = reader.readLine()) != null){
text.append(line).append("\n");
}
reader.close();
} catch (Exception e) {
log.error("",e);
}
return text.toString();
}
/**
*
*
* @param path
* @return
* @throws Exception
*/
public static List<String> getAllFileTextFromDir(String path){
List<String> filesText = new ArrayList<String>();
File f = new File(path);
if (!f.exists()) {
if(!f.mkdirs()){
log.warn("");
}
}
File[] fs = f.listFiles();
if(fs == null){
return new ArrayList<>();
}
try {
for (File file : fs) {
StringBuilder text = new StringBuilder();
FileInputStream fis = new FileInputStream(file);
InputStreamReader read = new InputStreamReader(fis,"UTF-8");
BufferedReader reader = new BufferedReader(read);
String line = "";
while((line = reader.readLine()) != null){
text.append(line).append("\n");
}
filesText.add(text.toString());
reader.close();
}
} catch (Exception e) {
return new ArrayList<>();
}
return filesText;
}
/**
*
*
* @param path
* @param fileName
* @return
* @throws Exception
*/
public static String getFileTextFromDirFile(String path, String fileName){
StringBuilder text = new StringBuilder();
File f = new File(path);
if (!f.exists()) {
if(!f.mkdirs()){
log.warn("");
}
}
f = new File(path + File.separator + fileName);
if(!f.exists()){
try {
if(!f.createNewFile()){
log.warn("");
}
} catch (IOException e) {
log.error("",e);
}
}
try {
FileInputStream fis = new FileInputStream(f);
InputStreamReader read = new InputStreamReader(fis,"UTF-8");
BufferedReader reader = new BufferedReader(read);
String line = "";
while((line = reader.readLine()) != null){
text.append(line).append("\n");
}
reader.close();
} catch (Exception e) {
return "";
}
return text.toString();
}
/**
*
*
* @param text
* @param path
* @param fileName
* @param append : true
* @return
*/
public static boolean writeTextToTextFile(String text,String path, String fileName,boolean append) {
File f = new File(path);
if(!f.exists()){
if(!f.mkdirs()){
log.warn("");
}
}
f = new File(path + File.separator + fileName);
if(!f.exists()){
try {
if(!f.createNewFile()){
log.warn("");
return false;
}
} catch (IOException e) {
log.error("",e);
return false;
}
}
FileOutputStream fos;
try {
fos = new FileOutputStream(f, append);
OutputStreamWriter write = new OutputStreamWriter(fos,"UTF-8");
BufferedWriter writer = new BufferedWriter(write);
writer.write(text);
writer.close();
return true;
} catch (Exception e) {
return false;
}
}
/**
*
* false
* @param text
* @param file
* @param append : true
* @return
*/
public static boolean writeTextToTextFile(String text,File file,boolean append) {
if(!file.exists()){
return false;
}
FileOutputStream fos;
try {
fos = new FileOutputStream(file, append);
OutputStreamWriter write = new OutputStreamWriter(fos,"UTF-8");
BufferedWriter writer = new BufferedWriter(write);
writer.write(text);
writer.close();
return true;
} catch (Exception e) {
return false;
}
}
/**
* InputStreamFile
* @param ins
* @param file
*/
public static boolean inputStreamToFile(InputStream ins,File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
return true;
} catch (Exception e) {
return false;
}
}
/**
*
*
* @param path
* @return
* @throws Exception
*/
public static List<String> getAllFileNamesFromDir(String path){
List<String> fileNames = new ArrayList<>();
File dir = new File(path);
if (!dir.exists()) {
if(!dir.mkdirs()){
log.warn("");
}
}
File[] fs = dir.listFiles();
if(fs == null){
return new ArrayList<>();
}
try {
for (File file : fs) {
appendFileNames(file.getPath(),fileNames);
}
} catch (Exception e) {
log.error("",e);
return new ArrayList<>();
}
return fileNames;
}
private static void appendFileNames(String dir,List<String> fileNames){
File file = new File(dir);
if(file.isFile()){
fileNames.add(file.getPath());
}else {
File[] fs = file.listFiles();
if(fs != null){
for (File f : fs) {
if(f.isDirectory()){
appendFileNames(f.getPath(),fileNames);
}else if(f.isFile()){
fileNames.add(f.getPath());
}else {
log.warn("" + f.getPath());
}
}
}
}
}
} |
package burai.atoms.model;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Platform;
import burai.atoms.model.event.AtomEvent;
import burai.atoms.model.event.AtomEventListener;
import burai.atoms.model.event.CellEvent;
import burai.atoms.model.event.CellEventListener;
import burai.atoms.model.event.ModelEvent;
import burai.com.env.Environments;
import burai.com.parallel.Parallel;
public class BondsResolver implements AtomEventListener, CellEventListener {
private static final double THR_DENSITY = 0.50;
private static final double BOND_SCALE1 = 0.50;
private static final double BOND_SCALE2 = 1.15;
private static final double THR_ATOM_MOTION = 1.0e-3;
private static final double THR_ATOM_MOTION2 = THR_ATOM_MOTION * THR_ATOM_MOTION;
private static final int NUM_THREADS = Math.max(1, Environments.getNumCUPs() - 1);
private static final int NUM_ATOMS_TO_ASYNC = 16;
private static final int NUM_ATOMS_TO_PARALLEL = 64;
private static final int DIM_BONDS = 6;
private Cell cell;
boolean auto;
protected BondsResolver(Cell cell) {
if (cell == null) {
throw new IllegalArgumentException("cell is null.");
}
this.cell = cell;
this.cell.addListenerFirst(this);
Atom[] atoms = this.cell.listAtoms();
if (atoms != null) {
for (Atom atom : atoms) {
if (atom != null) {
atom.addListenerFirst(this);
}
}
}
this.auto = true;
}
protected void setAuto(boolean auto) {
this.auto = auto;
}
protected boolean isAuto() {
return this.auto;
}
protected void resolve() {
int natom = this.cell.numAtoms();
if (natom <= NUM_ATOMS_TO_ASYNC) {
this.resolveAll();
} else {
Platform.runLater(() -> {
this.resolveAll();
});
}
}
private void resolveAll() {
this.removeNotUsedBonds();
List<Atom> atoms = this.cell.getAtoms();
if (atoms == null || atoms.isEmpty()) {
return;
}
if (!this.isAbleToResolve()) {
return;
}
int natom = atoms.size();
int nbond = this.cell.numBonds();
List<Bond> bondsToAdd = new ArrayList<Bond>();
List<Bond> bondsToRemove = new ArrayList<Bond>();
if (NUM_THREADS < 2 || natom <= NUM_ATOMS_TO_PARALLEL) {
// serial calculation
for (int i = 0; i < natom; i++) {
Atom atom = atoms.get(i);
Bond[][] bondsBuffer = this.resolve(atom, i, atoms, nbond == 0);
if (bondsBuffer == null || bondsBuffer.length < 2) {
continue;
}
Bond[] bondsToAdd_ = bondsBuffer[0];
if (bondsToAdd_ != null && bondsToAdd_.length > 0) {
for (Bond bond : bondsToAdd_) {
if (bond == null) {
break;
}
bondsToAdd.add(bond);
}
}
Bond[] bondsToRemove_ = bondsBuffer[1];
if (bondsToRemove_ != null && bondsToRemove_.length > 0) {
for (Bond bond : bondsToRemove_) {
if (bond == null) {
break;
}
bondsToRemove.add(bond);
}
}
}
} else {
// parallel calculation
Integer[] iatom = new Integer[natom];
for (int i = 0; i < iatom.length; i++) {
iatom[i] = i;
}
Parallel<Integer, Object> parallel = new Parallel<Integer, Object>(iatom);
parallel.setNumThreads(NUM_THREADS);
parallel.forEach(i -> {
Atom atom = atoms.get(i);
Bond[][] bondsBuffer = this.resolve(atom, i, atoms, nbond == 0);
if (bondsBuffer == null || bondsBuffer.length < 2) {
return null;
}
Bond[] bondsToAdd_ = bondsBuffer[0];
if (bondsToAdd_ != null && bondsToAdd_.length > 0) {
synchronized (bondsToAdd) {
for (Bond bond : bondsToAdd_) {
if (bond == null) {
break;
}
bondsToAdd.add(bond);
}
}
}
Bond[] bondsToRemove_ = bondsBuffer[1];
if (bondsToRemove_ != null && bondsToRemove_.length > 0) {
synchronized (bondsToRemove) {
for (Bond bond : bondsToRemove_) {
if (bond == null) {
break;
}
bondsToRemove.add(bond);
}
}
}
return null;
});
}
for (Bond bond : bondsToAdd) {
this.cell.addBond(bond);
}
for (Bond bond : bondsToRemove) {
this.cell.removeBond(bond);
}
}
protected void resolve(Atom atom) {
List<Atom> atoms = this.cell.getAtoms();
if (atoms == null || atoms.isEmpty()) {
return;
}
if (!this.isAbleToResolve()) {
return;
}
Bond[][] bondsBuffer = this.resolve(atom, atoms.size(), atoms, false);
if (bondsBuffer == null || bondsBuffer.length < 2) {
return;
}
Bond[] bondsToAdd = bondsBuffer[0];
if (bondsToAdd != null && bondsToAdd.length > 0) {
for (Bond bond : bondsToAdd) {
if (bond == null) {
break;
}
this.cell.addBond(bond);
}
}
Bond[] bondsToRemove = bondsBuffer[1];
if (bondsToRemove != null && bondsToRemove.length > 0) {
for (Bond bond : bondsToRemove) {
if (bond == null) {
break;
}
this.cell.removeBond(bond);
}
}
}
private boolean isAbleToResolve() {
double ratom = (double) this.cell.numAtoms();
double volume = this.cell.getVolume();
if (volume <= 0.0) {
return false;
}
double density = ratom / volume;
if (density > THR_DENSITY) {
return false;
} else {
return true;
}
}
private Bond[][] resolve(Atom atom1, int maxAtom, List<Atom> atoms, boolean fromBeginning) {
if (atom1 == null) {
return null;
}
if (maxAtom < 1) {
return null;
}
if (atoms == null || atoms.size() < maxAtom) {
return null;
}
double x1 = atom1.getX();
double y1 = atom1.getY();
double z1 = atom1.getZ();
double rcov1 = atom1.getRadius();
List<Bond> bonds = null;
if (!fromBeginning) {
bonds = this.cell.pickBonds(atom1);
}
int numToAdd = 0;
int numToRemove = 0;
Bond[] bondsToAdd = null;
Bond[] bondsToRemove = null;
for (int i = 0; i < maxAtom; i++) {
Atom atom2 = atoms.get(i);
if (atom1 == atom2) {
continue;
}
double x2 = atom2.getX();
double y2 = atom2.getY();
double z2 = atom2.getZ();
double rcov2 = atom2.getRadius();
double rr = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2);
double rcov = rcov1 + rcov2;
double rrcov = rcov * rcov;
double rrmin = BOND_SCALE1 * BOND_SCALE1 * rrcov;
double rrmax = BOND_SCALE2 * BOND_SCALE2 * rrcov;
Bond bond = null;
if (!fromBeginning) {
bond = this.cell.pickBond(atom1, atom2, bonds);
}
if (rrmin <= rr && rr <= rrmax) {
if (bond == null) {
if (bondsToAdd == null || numToAdd >= bondsToAdd.length) {
Bond[] bondsTmp = new Bond[numToAdd + DIM_BONDS];
for (int j = 0; j < numToAdd; j++) {
bondsTmp[j] = bondsToAdd[j];
}
bondsToAdd = bondsTmp;
}
bondsToAdd[numToAdd] = new Bond(atom1, atom2);
numToAdd++;
}
} else {
if (bond != null) {
if (bondsToRemove == null || numToRemove >= bondsToRemove.length) {
Bond[] bondsTmp = new Bond[numToRemove + DIM_BONDS];
for (int j = 0; j < numToRemove; j++) {
bondsTmp[j] = bondsToRemove[j];
}
bondsToRemove = bondsTmp;
}
bondsToRemove[numToRemove] = bond;
numToRemove++;
}
}
}
Bond[][] bondsBuffer = new Bond[2][];
bondsBuffer[0] = bondsToAdd;
bondsBuffer[1] = bondsToRemove;
return bondsBuffer;
}
private void removeAllBondsLinkedWith(Atom atom) {
if (atom == null) {
throw new IllegalArgumentException("atom is null.");
}
Bond[] bonds = this.cell.listBonds();
if (bonds == null || bonds.length < 1) {
return;
}
for (Bond bond : bonds) {
Atom atom1 = bond.getAtom1();
Atom atom2 = bond.getAtom2();
if (atom == atom1 || atom == atom2) {
this.cell.removeBond(bond);
}
}
}
private void removeNotUsedBonds() {
Bond[] bonds = this.cell.listBonds();
if (bonds == null || bonds.length < 1) {
return;
}
List<Atom> atoms = this.cell.getAtoms();
if (atoms == null || atoms.isEmpty()) {
for (Bond bond : bonds) {
this.cell.removeBond(bond);
}
return;
}
for (Bond bond : bonds) {
Atom atom1 = bond.getAtom1();
Atom atom2 = bond.getAtom2();
boolean hasAtom1 = false;
boolean hasAtom2 = false;
for (Atom atom : atoms) {
if (hasAtom1 && hasAtom2) {
break;
} else if (!hasAtom1) {
hasAtom1 = (atom == atom1);
} else if (!hasAtom2) {
hasAtom2 = (atom == atom2);
}
}
if (!(hasAtom1 && hasAtom2)) {
this.cell.removeBond(bond);
}
}
}
@Override
public boolean isToBeFlushed() {
return false;
}
@Override
public void onModelDisplayed(ModelEvent event) {
// NOP
}
@Override
public void onModelNotDisplayed(ModelEvent event) {
// NOP
}
@Override
public void onLatticeMoved(CellEvent event) {
if (event == null) {
return;
}
if (this.cell != event.getSource()) {
return;
}
if (!this.auto) {
return;
}
this.resolve();
}
@Override
public void onAtomAdded(CellEvent event) {
if (event == null) {
return;
}
if (this.cell != event.getSource()) {
return;
}
Atom atom = event.getAtom();
if (atom == null) {
return;
}
atom.addListenerFirst(this);
if (!this.auto) {
return;
}
this.resolve(atom);
}
@Override
public void onAtomRemoved(CellEvent event) {
if (event == null) {
return;
}
if (this.cell != event.getSource()) {
return;
}
Atom atom = event.getAtom();
if (atom == null) {
return;
}
if (!this.auto) {
return;
}
this.removeAllBondsLinkedWith(atom);
}
@Override
public void onBondAdded(CellEvent event) {
// NOP
}
@Override
public void onBondRemoved(CellEvent event) {
// NOP
}
@Override
public void onAtomRenamed(AtomEvent event) {
if (event == null) {
return;
}
if (!this.auto) {
return;
}
String name1 = event.getOldName();
String name2 = event.getName();
if (name1 != null && name1.equals(name2)) {
return;
}
Object obj = event.getSource();
if (obj == null || !(obj instanceof Atom)) {
return;
}
Atom atom = (Atom) obj;
this.resolve(atom);
}
@Override
public void onAtomMoved(AtomEvent event) {
if (event == null) {
return;
}
if (!this.auto) {
return;
}
double dx = event.getDeltaX();
double dy = event.getDeltaY();
double dz = event.getDeltaZ();
double rr = dx * dx + dy * dy + dz * dz;
if (rr < THR_ATOM_MOTION2) {
return;
}
Object obj = event.getSource();
if (obj == null || !(obj instanceof Atom)) {
return;
}
Atom atom = (Atom) obj;
this.resolve(atom);
}
} |
package com.oauth.services.domain;
import lombok.*;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.sql.Timestamp;
@Entity
@Table(name = "user_audit")
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class UserAudit {
@Id
@Column(name = "id")
// @GeneratedValue(strategy=GenerationType.AUTO)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_name")
private String userName;
@Column(name = "user_type")
private String userType;
@Column(name = "school_id")
private Long schoolId;
@Column(name = "school_name")
private String schoolName;
@Column(name = "action_time")
private Timestamp actionTime;
@Column(name = "action_type")
private String actionType;
} |
package com.intellij.openapi.vcs.changes;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.ui.CommitHelper;
import com.intellij.openapi.vcs.checkin.CheckinEnvironment;
import com.intellij.openapi.vcs.checkin.CheckinHandler;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.readOnlyHandler.ReadonlyStatusHandlerImpl;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.peer.PeerFactory;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.EventDispatcher;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.MultiMap;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
/**
* @author max
*/
public class ChangeListManagerImpl extends ChangeListManager implements ProjectComponent, ChangeListOwner, JDOMExternalizable {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.ChangeListManagerImpl");
private Project myProject;
@SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"})
private static ScheduledExecutorService ourUpdateAlarm = ConcurrencyUtil.newSingleScheduledThreadExecutor("Change List Updater");
private ScheduledFuture<?> myCurrentUpdate = null;
private boolean myInitialized = false;
@SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"})
private boolean myDisposed = false;
private VirtualFileHolder myUnversionedFilesHolder;
private VirtualFileHolder myModifiedWithoutEditingHolder;
private VirtualFileHolder myIgnoredFilesHolder;
private DeletedFilesHolder myDeletedFilesHolder = new DeletedFilesHolder();
private SwitchedFileHolder mySwitchedFilesHolder;
private final List<LocalChangeList> myChangeLists = new ArrayList<LocalChangeList>();
private VcsException myUpdateException = null;
@SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"})
private LocalChangeListImpl myDefaultChangelist;
@SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"})
private EventDispatcher<ChangeListListener> myListeners = EventDispatcher.create(ChangeListListener.class);
private final Object myPendingUpdatesLock = new Object();
private boolean myUpdateInProgress = false;
private VcsDirtyScope myCurrentlyUpdatingScope = null;
@NonNls private static final String NODE_LIST = "list";
@NonNls private static final String NODE_IGNORED = "ignored";
@NonNls private static final String ATT_NAME = "name";
@NonNls private static final String ATT_COMMENT = "comment";
@NonNls private static final String NODE_CHANGE = "change";
@NonNls private static final String ATT_DEFAULT = "default";
@NonNls private static final String ATT_READONLY = "readonly";
@NonNls private static final String ATT_VALUE_TRUE = "true";
@NonNls private static final String ATT_CHANGE_TYPE = "type";
@NonNls private static final String ATT_CHANGE_BEFORE_PATH = "beforePath";
@NonNls private static final String ATT_CHANGE_AFTER_PATH = "afterPath";
@NonNls private static final String ATT_PATH = "path";
@NonNls private static final String ATT_MASK = "mask";
private List<CommitExecutor> myExecutors = new ArrayList<CommitExecutor>();
private final List<IgnoredFileBean> myFilesToIgnore = new ArrayList<IgnoredFileBean>();
public static final Key<Object> DOCUMENT_BEING_COMMITTED_KEY = new Key<Object>("DOCUMENT_BEING_COMMITTED");
private VcsListener myVcsListener = new VcsListener() {
public void directoryMappingChanged() {
VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty();
scheduleUpdate();
}
};
public static ChangeListManagerImpl getInstanceImpl(final Project project) {
return (ChangeListManagerImpl) project.getComponent(ChangeListManager.class);
}
public ChangeListManagerImpl(final Project project) {
myProject = project;
myUnversionedFilesHolder = new VirtualFileHolder(project);
myModifiedWithoutEditingHolder = new VirtualFileHolder(project);
myIgnoredFilesHolder = new VirtualFileHolder(project);
mySwitchedFilesHolder = new SwitchedFileHolder(project);
}
public void projectOpened() {
createDefaultChangelistIfNecessary();
StartupManager.getInstance(myProject).registerPostStartupActivity(new Runnable() {
public void run() {
myInitialized = true;
ProjectLevelVcsManager.getInstance(myProject).addVcsListener(myVcsListener);
}
});
}
private void createDefaultChangelistIfNecessary() {
if (myChangeLists.isEmpty()) {
final LocalChangeList list = LocalChangeList.createEmptyChangeList(myProject, VcsBundle.message("changes.default.changlist.name"));
myChangeLists.add(list);
setDefaultChangeList(list);
}
}
public void projectClosed() {
myDisposed = true;
ProjectLevelVcsManager.getInstance(myProject).removeVcsListener(myVcsListener);
cancelUpdates();
synchronized(myPendingUpdatesLock) {
waitForUpdateDone(null);
}
}
private void cancelUpdates() {
if (myCurrentUpdate != null) {
myCurrentUpdate.cancel(false);
myCurrentUpdate = null;
}
}
@NotNull @NonNls
public String getComponentName() {
return "ChangeListManager";
}
public void initComponent() {
}
public void disposeComponent() {
}
public boolean ensureUpToDate(boolean canBeCanceled) {
if (!myInitialized) return true;
final boolean ok = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
public void run() {
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setText(VcsBundle.message("commit.wait.util.synced.message"));
}
synchronized (myPendingUpdatesLock) {
scheduleUpdate(10, true);
waitForUpdateDone(indicator);
}
}
}, VcsBundle.message("commit.wait.util.synced.title"), canBeCanceled, myProject);
if (ok) {
ChangesViewManager.getInstance(myProject).refreshView();
}
return ok;
}
private void waitForUpdateDone(@Nullable final ProgressIndicator indicator) {
while (myCurrentUpdate != null && !myCurrentUpdate.isDone() || myUpdateInProgress) {
if (indicator != null && indicator.isCanceled()) break;
try {
myPendingUpdatesLock.wait(100);
}
catch (InterruptedException e) {
break;
}
}
}
private static class DisposedException extends RuntimeException {}
private void scheduleUpdate(int millis, final boolean updateUnversionedFiles) {
cancelUpdates();
myCurrentUpdate = ourUpdateAlarm.schedule(new Runnable() {
public void run() {
if (myDisposed) return;
if (!myInitialized) {
scheduleUpdate();
return;
}
updateImmediately(updateUnversionedFiles);
}
}, millis, TimeUnit.MILLISECONDS);
}
public void scheduleUpdate() {
scheduleUpdate(300, true);
}
public void scheduleUpdate(boolean updateUnversionedFiles) {
scheduleUpdate(300, updateUnversionedFiles);
}
private void updateImmediately(final boolean updateUnversionedFiles) {
try {
synchronized (myPendingUpdatesLock) {
myUpdateInProgress = true;
}
if (myDisposed) throw new DisposedException();
final VcsDirtyScopeManagerImpl dirtyScopeManager = ((VcsDirtyScopeManagerImpl)VcsDirtyScopeManager.getInstance(myProject));
final boolean wasEverythingDirty = dirtyScopeManager.isEverythingDirty();
final List<VcsDirtyScope> scopes = dirtyScopeManager.retrieveScopes();
final VirtualFileHolder unversionedHolder;
final VirtualFileHolder modifiedWithoutEditingHolder;
final VirtualFileHolder ignoredHolder;
final DeletedFilesHolder deletedHolder;
final SwitchedFileHolder switchedHolder;
if (wasEverythingDirty) {
myUpdateException = null;
}
if (updateUnversionedFiles) {
unversionedHolder = myUnversionedFilesHolder.copy();
deletedHolder = myDeletedFilesHolder.copy();
modifiedWithoutEditingHolder = myModifiedWithoutEditingHolder.copy();
ignoredHolder = myIgnoredFilesHolder.copy();
switchedHolder = mySwitchedFilesHolder.copy();
if (wasEverythingDirty) {
unversionedHolder.cleanAll();
deletedHolder.cleanAll();
modifiedWithoutEditingHolder.cleanAll();
ignoredHolder.cleanAll();
switchedHolder.cleanAll();
}
}
else {
unversionedHolder = myUnversionedFilesHolder;
deletedHolder = myDeletedFilesHolder;
modifiedWithoutEditingHolder = myModifiedWithoutEditingHolder;
ignoredHolder = myIgnoredFilesHolder;
switchedHolder = mySwitchedFilesHolder;
}
if (wasEverythingDirty) {
notifyStartProcessingChanges(null);
}
for (final VcsDirtyScope scope : scopes) {
final AbstractVcs vcs = scope.getVcs();
if (vcs == null) continue;
myCurrentlyUpdatingScope = scope;
ChangesViewManager.getInstance(myProject).updateProgressText(VcsBundle.message("changes.update.progress.message", vcs.getDisplayName()), false);
if (!wasEverythingDirty) {
notifyStartProcessingChanges(scope);
}
if (updateUnversionedFiles && !wasEverythingDirty) {
unversionedHolder.cleanScope(scope);
deletedHolder.cleanScope(scope);
modifiedWithoutEditingHolder.cleanScope(scope);
ignoredHolder.cleanScope(scope);
switchedHolder.cleanScope(scope);
}
try {
final ChangeProvider changeProvider = vcs.getChangeProvider();
if (changeProvider != null) {
try {
changeProvider.getChanges(scope, new ChangelistBuilder() {
public void processChange(final Change change) {
processChangeInList(change, null);
}
public void processChangeInList(final Change change, final ChangeList changeList) {
if (myDisposed) throw new DisposedException();
final String fileName = ChangesUtil.getFilePath(change).getName();
if (FileTypeManager.getInstance().isFileIgnored(fileName)) return;
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
if (isUnder(change, scope)) {
try {
synchronized (myChangeLists) {
if (changeList instanceof LocalChangeListImpl) {
((LocalChangeListImpl) changeList).addChange(change);
}
else {
for (LocalChangeList list : myChangeLists) {
if (list == myDefaultChangelist) continue;
if (((LocalChangeListImpl) list).processChange(change)) return;
}
myDefaultChangelist.processChange(change);
}
}
}
finally {
ChangesViewManager.getInstance(myProject).scheduleRefresh();
}
}
}
});
}
public void processUnversionedFile(VirtualFile file) {
if (file == null || !updateUnversionedFiles) return;
if (myDisposed) throw new DisposedException();
if (ProjectRootManager.getInstance(myProject).getFileIndex().isIgnored(file)) return;
if (scope.belongsTo(new FilePathImpl(file))) {
if (isIgnoredFile(file)) {
ignoredHolder.addFile(file);
}
else {
unversionedHolder.addFile(file);
}
ChangesViewManager.getInstance(myProject).scheduleRefresh();
}
}
public void processLocallyDeletedFile(FilePath file) {
if (!updateUnversionedFiles) return;
if (myDisposed) throw new DisposedException();
if (FileTypeManager.getInstance().isFileIgnored(file.getName())) return;
if (scope.belongsTo(file)) {
deletedHolder.addFile(file);
ChangesViewManager.getInstance(myProject).scheduleRefresh();
}
}
public void processModifiedWithoutCheckout(VirtualFile file) {
if (file == null || !updateUnversionedFiles) return;
if (myDisposed) throw new DisposedException();
if (ProjectRootManager.getInstance(myProject).getFileIndex().isIgnored(file)) return;
if (scope.belongsTo(PeerFactory.getInstance().getVcsContextFactory().createFilePathOn(file))) {
modifiedWithoutEditingHolder.addFile(file);
ChangesViewManager.getInstance(myProject).scheduleRefresh();
}
}
public void processIgnoredFile(VirtualFile file) {
if (file == null || !updateUnversionedFiles) return;
if (myDisposed) throw new DisposedException();
if (ProjectRootManager.getInstance(myProject).getFileIndex().isIgnored(file)) return;
if (scope.belongsTo(PeerFactory.getInstance().getVcsContextFactory().createFilePathOn(file))) {
ignoredHolder.addFile(file);
ChangesViewManager.getInstance(myProject).scheduleRefresh();
}
}
public void processSwitchedFile(final VirtualFile file, final String branch, final boolean recursive) {
if (file == null || !updateUnversionedFiles) return;
if (myDisposed) throw new DisposedException();
if (ProjectRootManager.getInstance(myProject).getFileIndex().isIgnored(file)) return;
if (scope.belongsTo(PeerFactory.getInstance().getVcsContextFactory().createFilePathOn(file))) {
switchedHolder.addFile(file, branch, recursive);
}
}
public boolean isUpdatingUnversionedFiles() {
return updateUnversionedFiles;
}
}, null); // TODO: make real indicator
}
catch (VcsException e) {
LOG.info(e);
if (myUpdateException == null) {
myUpdateException = e;
}
}
}
}
finally {
myCurrentlyUpdatingScope = null;
if (!myDisposed && !wasEverythingDirty) {
notifyDoneProcessingChanges();
}
}
}
if (wasEverythingDirty) {
notifyDoneProcessingChanges();
}
if (updateUnversionedFiles) {
boolean statusChanged = (!myUnversionedFilesHolder.equals(unversionedHolder)) ||
(!myDeletedFilesHolder.equals(deletedHolder)) ||
(!myModifiedWithoutEditingHolder.equals(modifiedWithoutEditingHolder)) ||
(!myIgnoredFilesHolder.equals(ignoredHolder)) ||
(!mySwitchedFilesHolder.equals(switchedHolder));
myUnversionedFilesHolder = unversionedHolder;
myDeletedFilesHolder = deletedHolder;
myModifiedWithoutEditingHolder = modifiedWithoutEditingHolder;
myIgnoredFilesHolder = ignoredHolder;
mySwitchedFilesHolder = switchedHolder;
if (statusChanged) {
myListeners.getMulticaster().unchangedFileStatusChanged();
}
}
}
catch (DisposedException e) {
// OK, we're finishing all the stuff now.
}
catch(Exception ex) {
LOG.error(ex);
}
finally {
myListeners.getMulticaster().changeListUpdateDone();
synchronized (myPendingUpdatesLock) {
myUpdateInProgress = false;
myPendingUpdatesLock.notifyAll();
}
}
}
private void notifyStartProcessingChanges(final VcsDirtyScope scope) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
synchronized (myChangeLists) {
for (LocalChangeList list : myChangeLists) {
if (myDisposed) throw new DisposedException();
((LocalChangeListImpl) list).startProcessingChanges(myProject, scope);
}
}
}
});
}
private void notifyDoneProcessingChanges() {
List<ChangeList> changedLists = new ArrayList<ChangeList>();
synchronized (myChangeLists) {
for (LocalChangeList list : myChangeLists) {
if (((LocalChangeListImpl) list).doneProcessingChanges()) {
changedLists.add(list);
}
}
}
for(ChangeList changeList: changedLists) {
myListeners.getMulticaster().changeListChanged(changeList);
}
}
private static boolean isUnder(final Change change, final VcsDirtyScope scope) {
final ContentRevision before = change.getBeforeRevision();
final ContentRevision after = change.getAfterRevision();
return before != null && scope.belongsTo(before.getFile()) || after != null && scope.belongsTo(after.getFile());
}
public List<LocalChangeList> getChangeListsCopy() {
synchronized (myChangeLists) {
List<LocalChangeList> copy = new ArrayList<LocalChangeList>(myChangeLists.size());
for (LocalChangeList list : myChangeLists) {
copy.add(list.clone());
}
return copy;
}
}
@NotNull
public List<LocalChangeList> getChangeLists() {
synchronized (myChangeLists) {
return myChangeLists;
}
}
public List<File> getAffectedPaths() {
List<File> files = new ArrayList<File>();
for (ChangeList list : myChangeLists) {
final Collection<Change> changes = list.getChanges();
for (Change change : changes) {
File beforeFile = null;
ContentRevision beforeRevision = change.getBeforeRevision();
if (beforeRevision != null) {
beforeFile = beforeRevision.getFile().getIOFile();
}
if (beforeFile != null) {
files.add(beforeFile);
}
ContentRevision afterRevision = change.getAfterRevision();
if (afterRevision != null) {
final File afterFile = afterRevision.getFile().getIOFile();
if (!afterFile.equals(beforeFile)) {
files.add(afterFile);
}
}
}
}
return files;
}
@NotNull
public List<VirtualFile> getAffectedFiles() {
List<VirtualFile> files = new ArrayList<VirtualFile>();
for (ChangeList list : myChangeLists) {
final Collection<Change> changes = list.getChanges();
for (Change change : changes) {
final ContentRevision afterRevision = change.getAfterRevision();
if (afterRevision != null) {
final VirtualFile vFile = afterRevision.getFile().getVirtualFile();
if (vFile != null) {
files.add(vFile);
}
}
}
}
return files;
}
List<VirtualFile> getUnversionedFiles() {
return new ArrayList<VirtualFile>(myUnversionedFilesHolder.getFiles());
}
List<VirtualFile> getModifiedWithoutEditing() {
return new ArrayList<VirtualFile>(myModifiedWithoutEditingHolder.getFiles());
}
List<VirtualFile> getIgnoredFiles() {
return new ArrayList<VirtualFile>(myIgnoredFilesHolder.getFiles());
}
List<FilePath> getDeletedFiles() {
return new ArrayList<FilePath>(myDeletedFilesHolder.getFiles());
}
MultiMap<String, VirtualFile> getSwitchedFilesMap() {
return mySwitchedFilesHolder.getBranchToFileMap();
}
VcsException getUpdateException() {
return myUpdateException;
}
public boolean isFileAffected(final VirtualFile file) {
synchronized (myChangeLists) {
for (ChangeList list : myChangeLists) {
for (Change change : list.getChanges()) {
final ContentRevision afterRevision = change.getAfterRevision();
if (afterRevision != null && afterRevision.getFile().getVirtualFile() == file) return true;
}
}
}
return myUnversionedFilesHolder.containsFile(file);
}
@Nullable
public LocalChangeList findChangeList(final String name) {
LocalChangeList result = null;
final List<LocalChangeList> changeLists = getChangeLists();
for(LocalChangeList changeList: changeLists) {
if (changeList.getName().equals(name)) {
result = changeList;
}
}
return result;
}
public LocalChangeList addChangeList(@NotNull String name, final String comment) {
LOG.assertTrue(findChangeList(name) == null, "Attempt to create duplicate changelist " + name);
final LocalChangeListImpl list = LocalChangeListImpl.createEmptyChangeListImpl(myProject, name);
list.setComment(comment);
synchronized (myChangeLists) {
myChangeLists.add(list);
}
myListeners.getMulticaster().changeListAdded(list);
// handle changelists created during the update process
if (myCurrentlyUpdatingScope != null) {
list.startProcessingChanges(myProject, myCurrentlyUpdatingScope);
}
return list;
}
public void removeChangeList(LocalChangeList list) {
Collection<Change> changes;
LocalChangeListImpl realList = findRealByCopy(list);
synchronized (myChangeLists) {
if (realList.isDefault()) throw new RuntimeException(new IncorrectOperationException("Cannot remove default changelist"));
changes = realList.getChanges();
for (Change change : changes) {
myDefaultChangelist.addChange(change);
}
}
myListeners.getMulticaster().changesMoved(changes, realList, myDefaultChangelist);
synchronized (myChangeLists) {
myChangeLists.remove(realList);
}
myListeners.getMulticaster().changeListRemoved(realList);
}
public void setDefaultChangeList(@NotNull LocalChangeList list) {
synchronized (myChangeLists) {
if (myDefaultChangelist != null) myDefaultChangelist.setDefault(false);
LocalChangeListImpl realList = findRealByCopy(list);
realList.setDefault(true);
myDefaultChangelist = realList;
}
myListeners.getMulticaster().defaultListChanged(list);
}
public LocalChangeList getDefaultChangeList() {
return myDefaultChangelist;
}
private LocalChangeListImpl findRealByCopy(LocalChangeList list) {
for (LocalChangeList changeList : myChangeLists) {
if (changeList.equals(list)) {
return (LocalChangeListImpl) changeList;
}
}
return (LocalChangeListImpl) list;
}
public LocalChangeList getChangeList(Change change) {
synchronized (myChangeLists) {
for (LocalChangeList list : myChangeLists) {
if (list.getChanges().contains(change)) return list;
}
return null;
}
}
@Nullable
public LocalChangeList getIdentityChangeList(Change change) {
synchronized (myChangeLists) {
for (LocalChangeList list : myChangeLists) {
for(Change oldChange: list.getChanges()) {
if (oldChange == change) {
return list;
}
}
}
return null;
}
}
@Nullable
public Change getChange(VirtualFile file) {
synchronized (myChangeLists) {
for (ChangeList list : myChangeLists) {
for (Change change : list.getChanges()) {
final ContentRevision afterRevision = change.getAfterRevision();
if (afterRevision != null) {
String revisionPath = FileUtil.toSystemIndependentName(afterRevision.getFile().getPath());
if (FileUtil.pathsEqual(revisionPath, file.getPath())) return change;
}
}
}
return null;
}
}
@Nullable
public Change getChange(final FilePath file) {
synchronized (myChangeLists) {
for (ChangeList list : myChangeLists) {
for (Change change : list.getChanges()) {
final ContentRevision afterRevision = change.getAfterRevision();
if (afterRevision != null && afterRevision.getFile().equals(file)) {
return change;
}
final ContentRevision beforeRevision = change.getBeforeRevision();
if (beforeRevision != null && beforeRevision.getFile().equals(file)) {
return change;
}
}
}
return null;
}
}
public boolean isUnversioned(VirtualFile file) {
return myUnversionedFilesHolder.containsFile(file);
}
@NotNull
public FileStatus getStatus(VirtualFile file) {
if (myUnversionedFilesHolder.containsFile(file)) return FileStatus.UNKNOWN;
if (myModifiedWithoutEditingHolder.containsFile(file)) return FileStatus.HIJACKED;
if (myIgnoredFilesHolder.containsFile(file)) return FileStatus.IGNORED;
final Change change = getChange(file);
if (change != null) {
return change.getFileStatus();
}
if (mySwitchedFilesHolder.containsFile(file)) return FileStatus.SWITCHED;
return FileStatus.NOT_CHANGED;
}
@NotNull
public Collection<Change> getChangesIn(VirtualFile dir) {
return getChangesIn(PeerFactory.getInstance().getVcsContextFactory().createFilePathOn(dir));
}
@NotNull
public Collection<Change> getChangesIn(final FilePath dirPath) {
synchronized (myChangeLists) {
List<Change> changes = new ArrayList<Change>();
for (ChangeList list : myChangeLists) {
for (Change change : list.getChanges()) {
final ContentRevision afterRevision = change.getAfterRevision();
if (afterRevision != null && afterRevision.getFile().isUnder(dirPath, false)) {
changes.add(change);
continue;
}
final ContentRevision beforeRevision = change.getBeforeRevision();
if (beforeRevision != null && beforeRevision.getFile().isUnder(dirPath, false)) {
changes.add(change);
}
}
}
return changes;
}
}
public void moveChangesTo(LocalChangeList list, final Change[] changes) {
MultiMap<LocalChangeList, Change> map = new MultiMap<LocalChangeList, Change>();
synchronized (myChangeLists) {
LocalChangeListImpl realList = findRealByCopy(list);
for (LocalChangeList existingList : myChangeLists) {
for (Change change : changes) {
if (((LocalChangeListImpl) existingList).removeChange(change)) {
realList.addChange(change);
map.putValue(existingList, change);
}
}
}
}
for(LocalChangeList fromList: map.keySet()) {
final List<Change> changesInList = map.get(fromList);
myListeners.getMulticaster().changesMoved(changesInList, fromList, list);
}
}
public void addUnversionedFiles(final LocalChangeList list, @NotNull final List<VirtualFile> files) {
final List<VcsException> exceptions = new ArrayList<VcsException>();
ChangesUtil.processVirtualFilesByVcs(myProject, files, new ChangesUtil.PerVcsProcessor<VirtualFile>() {
public void process(final AbstractVcs vcs, final List<VirtualFile> items) {
final CheckinEnvironment environment = vcs.getCheckinEnvironment();
if (environment != null) {
exceptions.addAll(environment.scheduleUnversionedFilesForAddition(items));
}
}
});
if (exceptions.size() > 0) {
StringBuilder message = new StringBuilder(VcsBundle.message("error.adding.files.prompt"));
for(VcsException ex: exceptions) {
message.append("\n").append(ex.getMessage());
}
Messages.showErrorDialog(myProject, message.toString(), VcsBundle.message("error.adding.files.title"));
}
for (VirtualFile file : files) {
VcsDirtyScopeManager.getInstance(myProject).fileDirty(file);
FileStatusManager.getInstance(myProject).fileStatusChanged(file);
}
if (!list.isDefault()) {
// find the changes for the added files and move them to the necessary changelist
ensureUpToDate(false);
List<Change> changesToMove = new ArrayList<Change>();
for(Change change: getDefaultChangeList().getChanges()) {
final ContentRevision afterRevision = change.getAfterRevision();
if (afterRevision != null) {
VirtualFile vFile = afterRevision.getFile().getVirtualFile();
if (files.contains(vFile)) {
changesToMove.add(change);
}
}
}
if (changesToMove.size() > 0) {
moveChangesTo(list, changesToMove.toArray(new Change[changesToMove.size()]));
}
}
ChangesViewManager.getInstance(myProject).scheduleRefresh();
}
public Project getProject() {
return myProject;
}
public void addChangeListListener(ChangeListListener listener) {
myListeners.addListener(listener);
}
public void removeChangeListListener(ChangeListListener listener) {
myListeners.removeListener(listener);
}
public void registerCommitExecutor(CommitExecutor executor) {
myExecutors.add(executor);
}
public void commitChanges(LocalChangeList changeList, List<Change> changes) {
doCommit(changeList, changes, false);
}
private boolean doCommit(final LocalChangeList changeList, final List<Change> changes, final boolean synchronously) {
return new CommitHelper(myProject, changeList, changes, changeList.getName(),
changeList.getComment(), new ArrayList<CheckinHandler>(), false, synchronously).doCommit();
}
public void commitChangesSynchronously(LocalChangeList changeList, List<Change> changes) {
doCommit(changeList, changes, true);
}
public boolean commitChangesSynchronouslyWithResult(final LocalChangeList changeList, final List<Change> changes) {
return doCommit(changeList, changes, true);
}
@SuppressWarnings({"unchecked"})
public void readExternal(Element element) throws InvalidDataException {
final List<Element> listNodes = (List<Element>)element.getChildren(NODE_LIST);
for (Element listNode : listNodes) {
readChangeList(listNode);
}
final List<Element> ignoredNodes = (List<Element>)element.getChildren(NODE_IGNORED);
for (Element ignoredNode: ignoredNodes) {
readFileToIgnore(ignoredNode);
}
if (myChangeLists.size() > 0 && myDefaultChangelist == null) {
setDefaultChangeList(myChangeLists.get(0));
}
}
private void readChangeList(final Element listNode) {
// workaround for loading incorrect settings (with duplicate changelist names)
final String changeListName = listNode.getAttributeValue(ATT_NAME);
LocalChangeList list = findChangeList(changeListName);
if (list == null) {
list = addChangeList(changeListName, listNode.getAttributeValue(ATT_COMMENT));
}
//noinspection unchecked
final List<Element> changeNodes = (List<Element>)listNode.getChildren(NODE_CHANGE);
for (Element changeNode : changeNodes) {
try {
((LocalChangeListImpl) list).addChange(readChange(changeNode));
}
catch (OutdatedFakeRevisionException e) {
// Do nothing. Just skip adding outdated revisions to the list.
}
}
if (ATT_VALUE_TRUE.equals(listNode.getAttributeValue(ATT_DEFAULT))) {
setDefaultChangeList(list);
}
if (ATT_VALUE_TRUE.equals(listNode.getAttributeValue(ATT_READONLY))) {
list.setReadOnly(true);
}
}
private void readFileToIgnore(final Element ignoredNode) {
IgnoredFileBean bean = new IgnoredFileBean();
String path = ignoredNode.getAttributeValue(ATT_PATH);
if (path != null) {
bean.setPath(path);
}
String mask = ignoredNode.getAttributeValue(ATT_MASK);
if (mask != null) {
bean.setMask(mask);
}
myFilesToIgnore.add(bean);
}
public void writeExternal(Element element) throws WriteExternalException {
synchronized (myChangeLists) {
for (LocalChangeList list : myChangeLists) {
Element listNode = new Element(NODE_LIST);
element.addContent(listNode);
if (list.isDefault()) {
listNode.setAttribute(ATT_DEFAULT, ATT_VALUE_TRUE);
}
if (list.isReadOnly()) {
listNode.setAttribute(ATT_READONLY, ATT_VALUE_TRUE);
}
listNode.setAttribute(ATT_NAME, list.getName());
listNode.setAttribute(ATT_COMMENT, list.getComment());
for (Change change : list.getChanges()) {
writeChange(listNode, change);
}
}
}
synchronized(myFilesToIgnore) {
for(IgnoredFileBean bean: myFilesToIgnore) {
Element fileNode = new Element(NODE_IGNORED);
element.addContent(fileNode);
String path = bean.getPath();
if (path != null) {
fileNode.setAttribute("path", path);
}
String mask = bean.getMask();
if (mask != null) {
fileNode.setAttribute("mask", mask);
}
}
}
}
private static void writeChange(final Element listNode, final Change change) {
Element changeNode = new Element(NODE_CHANGE);
listNode.addContent(changeNode);
changeNode.setAttribute(ATT_CHANGE_TYPE, change.getType().name());
final ContentRevision bRev = change.getBeforeRevision();
final ContentRevision aRev = change.getAfterRevision();
changeNode.setAttribute(ATT_CHANGE_BEFORE_PATH, bRev != null ? bRev.getFile().getPath() : "");
changeNode.setAttribute(ATT_CHANGE_AFTER_PATH, aRev != null ? aRev.getFile().getPath() : "");
}
private static Change readChange(Element changeNode) throws OutdatedFakeRevisionException {
String bRev = changeNode.getAttributeValue(ATT_CHANGE_BEFORE_PATH);
String aRev = changeNode.getAttributeValue(ATT_CHANGE_AFTER_PATH);
return new Change(StringUtil.isEmpty(bRev) ? null : new FakeRevision(bRev), StringUtil.isEmpty(aRev) ? null : new FakeRevision(aRev));
}
private static final class OutdatedFakeRevisionException extends Exception {}
public static class FakeRevision implements ContentRevision {
private final FilePath myFile;
public FakeRevision(String path) throws OutdatedFakeRevisionException {
final FilePath file = PeerFactory.getInstance().getVcsContextFactory().createFilePathOn(new File(path));
if (file == null) throw new OutdatedFakeRevisionException();
myFile = file;
}
@Nullable
public String getContent() { return null; }
@NotNull
public FilePath getFile() {
return myFile;
}
@NotNull
public VcsRevisionNumber getRevisionNumber() {
return VcsRevisionNumber.NULL;
}
}
public void reopenFiles(List<FilePath> paths) {
final ReadonlyStatusHandlerImpl readonlyStatusHandler = (ReadonlyStatusHandlerImpl)ReadonlyStatusHandlerImpl.getInstance(myProject);
final boolean savedOption = readonlyStatusHandler.SHOW_DIALOG;
readonlyStatusHandler.SHOW_DIALOG = false;
try {
readonlyStatusHandler.ensureFilesWritable(collectFiles(paths));
}
finally {
readonlyStatusHandler.SHOW_DIALOG = savedOption;
}
}
public List<CommitExecutor> getRegisteredExecutors() {
return Collections.unmodifiableList(myExecutors);
}
public void addFilesToIgnore(final IgnoredFileBean... filesToIgnore) {
synchronized(myFilesToIgnore) {
Collections.addAll(myFilesToIgnore, filesToIgnore);
}
updateIgnoredFiles();
}
public void setFilesToIgnore(final IgnoredFileBean... filesToIgnore) {
synchronized(myFilesToIgnore) {
myFilesToIgnore.clear();
Collections.addAll(myFilesToIgnore, filesToIgnore);
}
updateIgnoredFiles();
}
private void updateIgnoredFiles() {
List<VirtualFile> unversionedFiles = myUnversionedFilesHolder.getFiles();
List<VirtualFile> ignoredFiles = myIgnoredFilesHolder.getFiles();
for(VirtualFile file: unversionedFiles) {
if (isIgnoredFile(file)) {
myUnversionedFilesHolder.removeFile(file);
myIgnoredFilesHolder.addFile(file);
}
}
for(VirtualFile file: ignoredFiles) {
if (!isIgnoredFile(file)) {
// the file may have been reported as ignored by the VCS, so we can't directly move it to unversioned files
VcsDirtyScopeManager.getInstance(myProject).fileDirty(file);
}
}
FileStatusManager.getInstance(getProject()).fileStatusesChanged();
ChangesViewManager.getInstance(myProject).scheduleRefresh();
}
public IgnoredFileBean[] getFilesToIgnore() {
synchronized(myFilesToIgnore) {
return myFilesToIgnore.toArray(new IgnoredFileBean[myFilesToIgnore.size()]);
}
}
public boolean isIgnoredFile(@NotNull VirtualFile file) {
synchronized(myFilesToIgnore) {
if (myFilesToIgnore.size() == 0) {
return false;
}
String filePath = null;
// don't use VfsUtil.getRelativePath() here because it can't handle paths where one file is not a direct ancestor of another one
final VirtualFile baseDir = myProject.getBaseDir();
if (baseDir != null) {
filePath = FileUtil.getRelativePath(new File(baseDir.getPath()), new File(file.getPath()));
if (filePath != null) {
filePath = FileUtil.toSystemIndependentName(filePath);
}
if (file.isDirectory()) {
filePath += "/";
}
}
for(IgnoredFileBean bean: myFilesToIgnore) {
if (filePath != null) {
final String prefix = bean.getPath();
if ("./".equals(prefix)) {
// special case for ignoring the project base dir (IDEADEV-16056)
final String basePath = FileUtil.toSystemIndependentName(baseDir.getPath());
final String fileAbsPath = FileUtil.toSystemIndependentName(file.getPath());
if (StringUtil.startsWithIgnoreCase(fileAbsPath, basePath)) {
return true;
}
}
else if (prefix != null && StringUtil.startsWithIgnoreCase(filePath, FileUtil.toSystemIndependentName(prefix))) {
return true;
}
}
final Pattern pattern = bean.getPattern();
if (pattern != null && pattern.matcher(file.getName()).matches()) {
return true;
}
}
return false;
}
}
@Nullable
public String getSwitchedBranch(final VirtualFile file) {
return mySwitchedFilesHolder.getBranchForFile(file);
}
private static VirtualFile[] collectFiles(final List<FilePath> paths) {
final ArrayList<VirtualFile> result = new ArrayList<VirtualFile>();
for (FilePath path : paths) {
if (path.getVirtualFile() != null) {
result.add(path.getVirtualFile());
}
}
return result.toArray(new VirtualFile[result.size()]);
}
public void notifyChangeListRenamed(final LocalChangeList list, final String oldName) {
myListeners.getMulticaster().changeListRenamed(list, oldName);
}
public void notifyChangeListCommentChanged(final LocalChangeList list, final String oldComment) {
myListeners.getMulticaster().changeListCommentChanged(list, oldComment);
}
} |
package de.ddb.pdc.metadata;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
/**
* Implementation of the {@link MetaFetcher} interface.
*/
public class MetaFetcherImpl implements MetaFetcher {
private static final String URL =
"https:
private static final String APIURL =
"https://api.deutsche-digitale-bibliothek.de";
private static final String SEARCH = "/search?";
private static final String AUTH = "oauth_consumer_key=";
private static final String SORTROWS = "&sort=RELEVANCE&rows=";
private static final String QUERY = "&query=";
private static final String ITEM = "/items/";
private static final String AIP = "/aip?";
private RestTemplate restTemplate;
private String authKey;
/**
* Creates a new MetaFetcherImpl.
*
* @param restTemplate RestTemplate to use for issuing requests
* @param authKey authentication Key for the DDB API
*/
public MetaFetcherImpl(RestTemplate restTemplate, String authKey) {
this.restTemplate = restTemplate;
this.authKey = authKey;
}
/**
* {@inheritDoc}
*/
public DDBItem[] searchForItems(String query, int maxCount)
throws RestClientException {
String modifiedQuery = query.replace(" ", "+");
String url = APIURL + SEARCH + AUTH + authKey + SORTROWS + maxCount + QUERY
+ modifiedQuery;
ResultsOfJSON roj = restTemplate.getForObject(url, ResultsOfJSON.class);
return getDDBItems(roj);
}
/**
* {@inheritDoc}
*/
public void fetchMetadata(DDBItem ddbItem) throws RestClientException {
String url = APIURL + ITEM + ddbItem.getId() + AIP + AUTH + authKey;
ResultsOfJSON roj = restTemplate.getForObject(url, ResultsOfJSON.class);
fillDDBItemMetadataFromDDB(ddbItem, roj);
}
/**
* @param ddbItem filled with information
* @param roj store information of the ddb aip request
*/
private void fillDDBItemMetadataFromDDB(DDBItem ddbItem, ResultsOfJSON roj) {
RDFItem rdfitem = roj.getEdm().getRdf();
String publishedYear = (String) rdfitem.getProvidedCHO().get("issued");
int year = 8000;
try {
if (publishedYear != null) {
year = Integer.parseInt(publishedYear.split(",")[0]);
}
} catch (NumberFormatException e) {
year = 8000;
}
ddbItem.setPublishedYear(year);
// some Agent input are represented at ArrayList or LinkedHashMap
if (rdfitem.getAgent() instanceof ArrayList<?>) {
ArrayList<LinkedHashMap> alAgent = (ArrayList) rdfitem.getAgent();
for (int idx = 0; idx < alAgent.size(); idx++) {
String about = (String) alAgent.get(idx).get("@about");
if (about.startsWith("http")) {
String authorid = alAgent.get(idx).get("@about").toString()
.replace("http://d-nb.info/gnd/", "");
Author author = new Author(authorid);
ddbItem.setAuthor(author);
}
}
}
// till now no testdata where author in LinkedHashMap
if (rdfitem.getAgent() instanceof LinkedHashMap<?,?>) {
//LinkedHashMap lhmAgent = (LinkedHashMap) rdf.get("Agent");
}
ddbItem.setInstitute((String) rdfitem.getAggregation().get("provider"));
}
/**
* @param roj results of the ddb search query
* @return a list of ddbitems from roj
*/
private DDBItem[] getDDBItems(ResultsOfJSON roj) {
int maxResults = roj.getResults().size();
DDBItem[] ddbItems = new DDBItem[maxResults];
int idx = 0;
for (SearchResultItem rsi : roj.getResults()) {
DDBItem ddbItem = new DDBItem(rsi.getId());
ddbItem.setTitle(deleteMatchTags(rsi.getTitle()));
ddbItem.setSubtitle(deleteMatchTags(rsi.getSubtitle()));
ddbItem.setImageUrl(URL + rsi.getThumbnail());
ddbItem.setCategory(rsi.getCategory());
ddbItem.setMedia(rsi.getMedia());
ddbItem.setType(rsi.getType());
ddbItems[idx] = ddbItem;
idx++;
}
return ddbItems;
}
/**
* Deletes the "<match>...</match>" markers in metadata values of search
* result items. These are added by the DDB API to simplify highlighting
* of matching substrings, but we don't need or want them.
*/
public static String deleteMatchTags(String string) {
return string.replace("<match>", "").replace("</match>", "");
}
} |
package org.usfirst.frc.team1458.robot;
import com.team1458.turtleshell2.util.Logger;
import com.team1458.turtleshell2.util.PIDConstants;
import com.team1458.turtleshell2.util.TurtleMaths;
import com.team1458.turtleshell2.util.types.MotorValue;
/**
* Constants for Robot. All inner classes are defined as "static final" so
* static variables can be defined
*
* @author asinghani
*/
public class Constants {
public static boolean DEBUG = true;
public static final Logger.LogFormat LOGGER_MODE = Logger.LogFormat.PLAINTEXT;
public static final boolean LOGGER_PRETTY_PRINT = true;
public static final class DriverStation {
public static final double JOYSTICK_DEADBAND = 0.1;
public static final boolean USE_XBOX_CONTROLLER = false;
public static final boolean LOGISTIC_SCALE = false;
public static final class UsbPorts {
public static final int RIGHT_STICK = 0;
public static final int LEFT_STICK = 1;
public static final int XBOX_CONTROLLER = 2;
public static final int DEBUG_XBOX_CONTROLLER = 3;
}
}
public static final class Drive {
public static final double SLOW_SPEED = 0.5;
}
public static final class RightDrive {
public static final int MOTOR1 = TalonID.DILLON.id;
public static final int MOTOR2 = TalonID.ELSA.id;
public static final int MOTOR3 = TalonID.FITZ.id;
public static final int ENCODER_A = 2;
public static final int ENCODER_B = 3;
public static final double ENCODER_RATIO = 4 * Math.PI / 600;
// (Diameter * PI) / (Ticks Per Rotation)
// Wheel diameter = 4 inches
}
public static final class LeftDrive {
public static final int MOTOR1 = TalonID.ALLEN.id;
public static final int MOTOR2 = TalonID.BOB.id;
public static final int MOTOR3 = TalonID.CARTER.id;
public static final int ENCODER_A = 0;
public static final int ENCODER_B = 1;
public static final double ENCODER_RATIO = 4 * Math.PI / 600;
// (Diameter * PI) / (Ticks Per Rotation)
}
public static final class Intake {
public static final int MOTOR_PORT = TalonID.GRANT.id;
public static final MotorValue SPEED = new MotorValue(0.8);
public static final MotorValue REVERSE_SPEED = new MotorValue(-0.8);
}
public static final class Climber {
public static final int MOTOR_PORT = TalonID.HITAGI.id;
public static final MotorValue SPEED = new MotorValue(0.8);
public static final MotorValue SPEED_LOW = new MotorValue(0.3);
}
public static final class Shooter {
public static final MotorValue REVERSE_SPEED = new MotorValue(-0.20);
public static final boolean UBP = true;
public static final PIDConstants PID_CONSTANTS = new PIDConstants(0.00009, 0, 0.000001);
public static final double UBPS = 0.000175;
public static final int AGITATOR_PORT = TalonID.KAREN.id;
public static final MotorValue AGITATOR_SPEED = new MotorValue(0.6);
}
public static final class LeftShooter {
public static final int MOTOR_PORT = TalonID.JESSICA.id;
public static final int HALL_PORT = 4;
public static final double SPEED_RPM = 4850;
public static final boolean MOTOR_REVERSED = false;
public static final PIDConstants PID_CONSTANTS = new PIDConstants(0.001, 0, 0);
public static final MotorValue BASE_VALUE = new MotorValue(0);
public static final double MIN_SPEED = 3900; // Speed at manual farthest left option
public static final double MAX_SPEED = 5000; // Speed at manual farthest right option
// Inches
public static final TurtleMaths.AdvancedRangeShifter RPM_SHIFTER = new TurtleMaths.AdvancedRangeShifter(
new double[] { 72,84,96 }, new double[] { 4475,4600,4850 });
}
public static final class RightShooter {
public static final int MOTOR_PORT = TalonID.ISAAC.id;
public static final int HALL_PORT = 5;
public static final double SPEED_RPM = 4350;
public static final boolean MOTOR_REVERSED = true;
public static final PIDConstants PID_CONSTANTS = new PIDConstants(0.001, 0, 0);
public static final MotorValue BASE_VALUE = new MotorValue(0);
public static final double MIN_SPEED = 3400; // Speed at manual farthest left option
public static final double MAX_SPEED = 4500; // Speed at manual farthest right option
// Inches
public static final TurtleMaths.AdvancedRangeShifter RPM_SHIFTER = new TurtleMaths.AdvancedRangeShifter(
new double[] { 72,84,96 }, new double[] { 4000,4100,4350 });
}
public static final class ShooterVision {
public static final class Camera {
public static final double MOUNT_ANGLE = 20.0;
public static final double MOUNT_HEIGHT = 7.0;
public static final double HEIGHT_FOV = 41.1;
public static final double WIDTH_FOV = 54.8;
public static final int WIDTH_PX = 320;
public static final int HEIGHT_PX = 240;
public static final String URL = "http://localhost:5800/?action=stream";
}
public static final class VisionPID {
public static final PIDConstants PID_CONSTANTS = new PIDConstants(0.006, 0, 0);
public static final MotorValue SPEED = new MotorValue(0.5);
}
}
public static final class DriverVision {
public static final int CAMERA_WIDTH = 320;
public static final int CAMERA_HEIGHT = 240;
public static final String CAMERA_URL = "http://localhost:5801/?action=stream";
}
public static final class StraightDrivePID {
public static final PIDConstants PID_CONSTANTS = new PIDConstants(0, 0, 0);
public static final PIDConstants TURN_PID_CONSTANTS = new PIDConstants(0, 0, 0);
public static final double kLR = 0.00005;
public static final double TOLERANCE = 2;
public static final MotorValue SPEED = new MotorValue(0.65);
}
public static final class TurnPID {
public static final PIDConstants PID_CONSTANTS = new PIDConstants(0.01, 0.001, 0.002);
public static final double TOLERANCE = 3;
public static final MotorValue SPEED = new MotorValue(0.65);
}
public static enum TalonID {
ORIGINAL(60), ALLEN(10), BOB(11), CARTER(12), DILLON(13), ELSA(14), FITZ(15), GRANT(16), HITAGI(17), ISAAC(
18), JESSICA(19), KAREN(20), LISA(21);
public final int id;
TalonID(int id) {
this.id = id;
}
}
private Constants() {
throw new IllegalStateException("Constants cannot be initialized. Something very bad has happened.");
}
} |
package VASSAL.counters;
import VASSAL.build.GameModule;
import VASSAL.build.module.BasicCommandEncoder;
import VASSAL.build.module.Chatter;
import VASSAL.build.module.GameState;
import VASSAL.build.module.GlobalOptions;
import VASSAL.build.module.Map;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.module.map.boardPicker.Board;
import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone;
import VASSAL.build.module.properties.PropertyNameSource;
import VASSAL.command.AddPiece;
import VASSAL.command.ChangePiece;
import VASSAL.command.Command;
import VASSAL.command.RemovePiece;
import VASSAL.command.SetPersistentPropertyCommand;
import VASSAL.configure.ImageSelector;
import VASSAL.configure.StringConfigurer;
import VASSAL.i18n.Localization;
import VASSAL.i18n.PieceI18nData;
import VASSAL.i18n.Resources;
import VASSAL.i18n.TranslatablePiece;
import VASSAL.property.PersistentPropertyContainer;
import VASSAL.search.AbstractImageFinder;
import VASSAL.tools.SequenceEncoder;
import VASSAL.tools.image.ImageUtils;
import VASSAL.tools.imageop.ScaledImagePainter;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.InputEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
/**
* Basic class for representing a physical component of the game. Can be e.g. a counter, a card, or an overlay.
*
* Note like traits, BasicPiece implements GamePiece (via TranslatablePiece), but UNLIKE traits it is NOT a
* Decorator, and thus must be treated specially.
*/
public class BasicPiece extends AbstractImageFinder implements TranslatablePiece, StateMergeable, PropertyNameSource, PersistentPropertyContainer,
PropertyExporter {
public static final String ID = "piece;"; // NON-NLS
private static Highlighter highlighter;
/**
* Return information about the current location of the piece through getProperty():
*
* LocationName - Current Location Name of piece as displayed in Chat Window CurrentX - Current X position CurrentY -
* Current Y position CurrentMap - Current Map name or "" if not on a map CurrentBoard - Current Board name or "" if
* not on a map CurrentZone - If the current map has a multi-zoned grid, then return the name of the Zone the piece is
* in, or "" if the piece is not in any zone, or not on a map
*/
public static final String LOCATION_NAME = "LocationName"; // NON-NLS
public static final String CURRENT_MAP = "CurrentMap"; // NON-NLS
public static final String CURRENT_BOARD = "CurrentBoard"; // NON-NLS
public static final String CURRENT_ZONE = "CurrentZone"; // NON-NLS
public static final String CURRENT_X = "CurrentX"; // NON-NLS
public static final String CURRENT_Y = "CurrentY"; // NON-NLS
public static final String OLD_LOCATION_NAME = "OldLocationName"; // NON-NLS
public static final String OLD_MAP = "OldMap"; // NON-NLS
public static final String OLD_BOARD = "OldBoard"; // NON-NLS
public static final String OLD_ZONE = "OldZone"; // NON-NLS
public static final String OLD_X = "OldX"; // NON-NLS
public static final String OLD_Y = "OldY"; // NON-NLS
public static final String BASIC_NAME = "BasicName"; // NON-NLS
public static final String PIECE_NAME = "PieceName"; // NON-NLS
public static final String LOCALIZED_BASIC_NAME = "LocalizedBasicName"; //NON-NLS
public static final String LOCALIZED_PIECE_NAME = "LocalizedPieceName"; //NON-NLS
public static final String DECK_NAME = "DeckName"; // NON-NLS
public static final String DECK_POSITION = "DeckPosition"; // NON-NLS
public static final String CLICKED_X = "ClickedX"; // NON-NLS
public static final String CLICKED_Y = "ClickedY"; // NON-NLS
public static Font POPUP_MENU_FONT = new Font(Font.DIALOG, Font.PLAIN, 11);
protected JPopupMenu popup;
protected Rectangle imageBounds;
protected ScaledImagePainter imagePainter = new ScaledImagePainter();
private Map map;
private KeyCommand[] commands;
private Stack parent;
private Point pos = new Point(0, 0);
private String id;
/*
* A set of properties used as scratch-pad storage by various Traits and processes.
* These properties are ephemeral and not stored in the GameState.
*/
private java.util.Map<Object, Object> props;
/*
* A Set of properties that must be persisted in the GameState.
* Will be created as lazily as possible since pieces that don't move will not need them,
* The current code only supports String Keys and Values. Non-strings should be serialised
* before set and de-serialised after get.
*/
private java.util.Map<Object, Object> persistentProps;
/** @deprecated Moved into own traits, retained for backward compatibility */
@Deprecated
private char cloneKey;
/** @deprecated Moved into own traits, retained for backward compatibility */
@Deprecated
private char deleteKey;
/** @deprecated Replaced by #srcOp. */
@Deprecated
protected Image image; // BasicPiece's own image
protected String imageName; // BasicPiece image name
private String commonName; // BasicPiece's name for the piece (aka "BasicName" property in Vassal Module)
public BasicPiece() {
this(ID + ";;;;");
}
/** creates a BasicPiece by passing complete type information
* @param type serialized type information (data about the piece which does not
* change during the course of a game) ready to be processed by a {@link SequenceEncoder.Decoder} */
public BasicPiece(String type) {
mySetType(type);
}
/** Sets the type information for this piece. See {@link Decorator#myGetType}
* @param type a serialized configuration string to
* set the "type information" of this piece, which is
* information that doesn't change during the course of
* a single game (e.g. Image Files, Context Menu strings,
* etc). Typically ready to be processed e.g. by
* SequenceEncoder.decode() */
@Override
public void mySetType(String type) {
final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';');
st.nextToken();
cloneKey = st.nextChar('\0');
deleteKey = st.nextChar('\0');
imageName = st.nextToken();
commonName = st.nextToken();
imagePainter.setImageName(imageName);
imageBounds = null; // New image, clear the old imageBounds
commands = null;
}
/** @return The "type information" of a piece or trait is information
* that does not change during the course of a game. Image file
* names, context menu strings, etc., all should be reflected
* in the type. The type information is returned serialized string
* form, ready to be decoded by a SequenceEncoder#decode.
* @see BasicCommandEncoder */
@Override
public String getType() {
final SequenceEncoder se =
new SequenceEncoder(cloneKey > 0 ? String.valueOf(cloneKey) : "", ';');
return ID + se.append(deleteKey > 0 ? String.valueOf(deleteKey) : "")
.append(imageName)
.append(commonName).getValue();
}
/** @param map Each GamePiece belongs to a single {@link Map} */
@Override
public void setMap(Map map) {
if (map != this.map) {
commands = null;
this.map = map;
}
}
/** @return Each GamePiece belongs to a single {@link Map} */
@Override
public Map getMap() {
return getParent() == null ? map : getParent().getMap();
}
/**
* Properties can be associated with a piece -- many may be game-specific, but others
* are standard, such as the LocationName property exposed by BasicPiece -- and can
* be read through this interface. The properties may or may not need to be encoded in
* the piece's {@link #getState} method.
*
* A request to getProperty() that reaches the BasicPiece will have already checked for
* such a property key being available from any outer Decorator/Trait in the stack. Upon
* reaching BasicPiece, the search hierarchy for a matching property now becomes:
*
* (1) Specific named properties supported by BasicPiece. These include BASIC_NAME,
* PIECE_NAME, LOCATION_NAME, CURRENT_MAP, CURRENT_BOARD, CURRENT_ZONE, CURRENT_X,
* CURRENT_Y.
* (2) "Scratchpad" properties - see {@link #setProperty} for full details, but these are
* highly temporary properties intended to remain valid only during the execution of a
* single key command.
* (3) Persistent properties - see {@link #setPersistentProperty} for full details, but
* they are stored in the piece and "game state robust" - saved during save/load, and
* propagated to other players' clients in a multiplayer game.
* (4) The values of any visible "Global Property" in a Vassal module, checking the Zone
* level first, then the map level, and finally the module level.
*
* <br><br>Thus, when using this interface a piece's own properties are preferred to those of
* "Global Properties", and those in turn are searched Zone-first then Map, then Module.
* @param key String key of property to be returned
* @return Object containing new value of the specified property
*/
@Override
public Object getProperty(Object key) {
if (BASIC_NAME.equals(key)) {
return getName();
}
else if (LOCALIZED_BASIC_NAME.equals(key)) {
return getLocalizedName();
}
else
return getPublicProperty(key);
}
/**
* Properties (see {@link #getProperty}) visible in a masked (see {@link Obscurable}) piece, even when the piece is masked.
* @param key String key of property to be returned.
*/
public Object getPublicProperty(Object key) {
if (Properties.KEY_COMMANDS.equals(key)) {
return getKeyCommands();
}
else if (LOCATION_NAME.equals(key)) {
return getMap() == null ? "" : getMap().locationName(getPosition());
}
else if (PIECE_NAME.equals(key)) {
return Decorator.getOutermost(this).getName();
}
else if (LOCALIZED_PIECE_NAME.equals(key)) {
return Decorator.getOutermost(this).getLocalizedName();
}
else if (CURRENT_MAP.equals(key)) {
return getMap() == null ? "" : getMap().getConfigureName();
}
else if (DECK_NAME.equals(key)) {
return getParent() instanceof Deck ? ((Deck) getParent()).getDeckName() : "";
}
else if (DECK_POSITION.equals(key)) {
if (getParent() instanceof Deck) {
final Deck deck = (Deck) getParent();
final int size = deck.getPieceCount();
final int pos = deck.indexOf(Decorator.getOutermost(this));
return String.valueOf(size - pos);
}
else {
return "0";
}
}
else if (CURRENT_BOARD.equals(key)) {
if (getMap() != null) {
final Board b = getMap().findBoard(getPosition());
if (b != null) {
return b.getName();
}
}
return "";
}
else if (CURRENT_ZONE.equals(key)) {
if (getMap() != null) {
final Zone z = getMap().findZone(getPosition());
if (z != null) {
return z.getName();
}
}
return "";
}
else if (CURRENT_X.equals(key)) {
return String.valueOf(getPosition().x);
}
else if (CURRENT_Y.equals(key)) {
return String.valueOf(getPosition().y);
}
else if (Properties.VISIBLE_STATE.equals(key)) {
return "";
}
// Check for a property in the scratch-pad properties
Object prop = props == null ? null : props.get(key);
// Check for a persistent property
if (prop == null && persistentProps != null) {
prop = persistentProps.get(key);
}
// Check for higher level properties. Each level if it exists will check the higher level if required.
if (prop == null) {
final Map map = getMap();
final Zone zone = (map == null ? null : map.findZone(getPosition()));
if (zone != null) {
prop = zone.getProperty(key);
}
else if (map != null) {
prop = map.getProperty(key);
}
else {
prop = GameModule.getGameModule().getProperty(key);
}
}
return prop;
}
/**
* Returns the localized text for a specified property if a translation is available, otherwise the non-localized version.
* Searches the same hierarchy of properties as {@link #getProperty}.
* @param key String key of property to be returned
* @return localized text of property, if available, otherwise non-localized value
*/
@Override
public Object getLocalizedProperty(Object key) {
if (BASIC_NAME.equals(key)) {
return getLocalizedName();
}
else {
return getLocalizedPublicProperty(key);
}
}
/**
* Returns the localized text for a specified property if a translation is available, otherwise the non-localized version,
* but in both cases accounting for the unit's visibility (i.e. Mask/{@link Obscurable} Traits).
* Searches the same hierarchy of properties as {@link #getProperty}.
* @param key String key of property to be returned
* @return Returns localized text of property, if available, otherwise non-localized value, accounting for Mask status.
*/
public Object getLocalizedPublicProperty(Object key) {
if (List.of(
Properties.KEY_COMMANDS,
DECK_NAME,
CURRENT_X,
CURRENT_Y,
Properties.VISIBLE_STATE
).contains(key)) {
return getProperty(key);
}
else if (LOCATION_NAME.equals(key)) {
return getMap() == null ? "" : getMap().localizedLocationName(getPosition());
}
else if (PIECE_NAME.equals(key)) {
return Decorator.getOutermost(this).getName();
}
else if (BASIC_NAME.equals(key)) {
return getLocalizedName();
}
else if (CURRENT_MAP.equals(key)) {
return getMap() == null ? "" : getMap().getLocalizedConfigureName();
}
else if (DECK_POSITION.equals(key)) {
if (getParent() instanceof Deck) {
final Deck deck = (Deck) getParent();
final int size = deck.getPieceCount();
final int pos = deck.indexOf(Decorator.getOutermost(this));
return String.valueOf(size - pos);
}
else {
return "0";
}
}
else if (CURRENT_BOARD.equals(key)) {
if (getMap() != null) {
final Board b = getMap().findBoard(getPosition());
if (b != null) {
return b.getLocalizedName();
}
}
return "";
}
else if (CURRENT_ZONE.equals(key)) {
if (getMap() != null) {
final Zone z = getMap().findZone(getPosition());
if (z != null) {
return z.getLocalizedName();
}
}
return "";
}
// Check for a property in the scratch-pad properties
Object prop = props == null ? null : props.get(key);
// Check for a persistent property
if (prop == null && persistentProps != null) {
prop = persistentProps.get(key);
}
// Check for higher level properties. Each level if it exists will check the higher level if required.
if (prop == null) {
final Map map = getMap();
final Zone zone = (map == null ? null : map.findZone(getPosition()));
if (zone != null) {
prop = zone.getLocalizedProperty(key);
}
else if (map != null) {
prop = map.getLocalizedProperty(key);
}
else {
prop = GameModule.getGameModule().getLocalizedProperty(key);
}
}
return prop;
}
/**
* Properties can be associated with a piece -- many may be game-specific, but others
* are standard, such as the LocationName property exposed by BasicPiece -- and can
* be set through this interface. The properties may or may not need to be encoded in
* the piece's {@link #getState} method.
*
* A setProperty() call which reaches BasicPiece will already have passed through all of the outer
* Decorator/Traits on the way in without finding one able to match the property.
*
* <br><br><b>NOTE:</b> Properties outside the piece CANNOT be set by this method (e.g. Global
* Properties), even though they can be read by {@link #getProperty} -- in this the two methods are
* not perfect mirrors. This method ALSO does not set persistent properties (they can only be set
* by an explicit call to {@link #setPersistentProperty}).
*
* <br><br>BasicPiece <i>does</i>, however contain a "scratchpad" for temporary properties, and for
* any call to this method that does not match a known property (which is, currently, ANY call which
* reaches this method here in BasicPiece), a scratchpad property will be set. Scratchpad properties
* are NOT saved when the game is saved, and NO arrangement is made to pass their values to other
* players' machines. Thus they should only be used internally for highly temporary values during the
* execution of a single key command. Their one other use is to store the piece's Unique ID -- and
* although this value is obviously used over periods of time much longer than a single key command,
* this is possible because the value is immutable and is refreshed to the same value whenever the
* piece is re-created e.g. when loading a save.
*
* @param key String key of property to be changed
* @param val Object containing new value of the property
*/
@Override
public void setProperty(Object key, Object val) {
if (props == null) {
props = new HashMap<>();
}
if (val == null) {
props.remove(key);
}
else {
props.put(key, val);
}
}
/**
* Setting a persistent property writes a property value into the piece (creating a new entry in the piece's persistent
* property table if the specified key does not yet exist in it). Persistent properties are game-state-robust: they are
* saved/restored with saved games, and are passed via {@link Command} to other players' clients in a multiplayer game.
* The persistent property value can then be read from the piece via e.g. {@link #getProperty}. When reading back properties
* out of a piece, the piece's built-in properties are checked first, then scratchpad properties (see {@link #setProperty}),
* then external properties such as Global Properties. If <i>only</i> persistentProperties are to be searched, use
* {@link #getPersistentProperty} instead.
*
* <br><br>In practical terms, setPersistentProperty is used mainly to implement the "Old" properties of BasicPiece (e.g.
* "OldLocationName", "OldZone", "OldMap", "OldBoard", "OldX", "OldY"). A Persistent Property is indeed nearly identical
* with {@link DynamicProperty} in storage/retrieval characteristics, and simply lacks the in-module interface for setting
* values, etc. Module Designers are thus recommended to stick with Dynamic Property traits for these functions.
*
* @param key String key naming the persistent property to be set. If a corresponding persistent property does not exist it will be created.
* @param newValue New value for the persistent property
* @return a {@link Command} object which, when passed to another player's client via logfile, server, or saved game, will allow the
* result of the "set" operation to be replicated.
*/
@Override
public Command setPersistentProperty(Object key, Object newValue) {
if (persistentProps == null) {
persistentProps = new HashMap<>();
}
final Object oldValue = newValue == null ? persistentProps.remove(key) : persistentProps.put(key, newValue);
return Objects.equals(oldValue, newValue) ? null : new SetPersistentPropertyCommand(getId(), key, oldValue, newValue);
}
/**
* @param key String key naming the persistent property whose value is to be returned.
* @return the current value of a persistent property, or null if it doesn't exist.
*/
@Override
public Object getPersistentProperty(Object key) {
return persistentProps == null ? null : persistentProps.get(key);
}
/**
* @param s Name of a module preference to be read
* @return Value of the preference
*/
protected Object prefsValue(String s) {
return GameModule.getGameModule().getPrefs().getValue(s);
}
/**
* Draws the BasicPiece's image, if it has been set
* @param g target Graphics object
* @param x x-location of the center of the piece
* @param y y-location of the center of the piece
* @param obs the Component on which this piece is being drawn
* @param zoom the scaling factor.
*/
@Override
public void draw(Graphics g, int x, int y, Component obs, double zoom) {
if (imageBounds == null) {
imageBounds = boundingBox();
}
imagePainter.draw(g, x + (int) (zoom * imageBounds.x), y + (int) (zoom * imageBounds.y), zoom, obs);
}
/**
* @return the set of key commands that will populate the a BasicPiece's right-click menu.
* This will normally be an empty array in the present age of the world, but the ability to contain a
* clone and delete command is retained for compatibility with Modules Of Ancient Times.
* In the case of BasicPiece, this method also keeps track of whether move up/down/to-top/to-bottom commands are enabled.
*
* This method is chained from "outer" Decorator components of a larger logical game piece, in the process of generating
* the complete list of key commands to build the right-click menu -- this process is originated by calling <code>getKeyCommands()</code>
* on the piece's outermost Decorator/Trait.
*/
protected KeyCommand[] getKeyCommands() {
if (commands == null) {
final ArrayList<KeyCommand> l = new ArrayList<>();
final GamePiece target = Decorator.getOutermost(this);
if (cloneKey > 0) {
l.add(new KeyCommand(Resources.getString("Editor.Clone.clone"), KeyStroke.getKeyStroke(cloneKey, InputEvent.CTRL_DOWN_MASK), target));
}
if (deleteKey > 0) {
l.add(new KeyCommand(Resources.getString("Editor.Delete.delete"), KeyStroke.getKeyStroke(deleteKey, InputEvent.CTRL_DOWN_MASK), target));
}
commands = l.toArray(new KeyCommand[0]);
}
final GamePiece outer = Decorator.getOutermost(this);
// This code has no function that I can see? There is no way to add these Commands.
// boolean canAdjustPosition = outer.getMap() != null && outer.getParent() != null && outer.getParent().topPiece() != getParent().bottomPiece();
// enableCommand("Move up", canAdjustPosition);
// enableCommand("Move down", canAdjustPosition);
// enableCommand("Move to top", canAdjustPosition);
// enableCommand("Move to bottom", canAdjustPosition);
enableCommand(Resources.getString("Editor.Clone.clone"), outer.getMap() != null);
enableCommand(Resources.getString("Editor.Delete.delete"), outer.getMap() != null);
return commands;
}
/**
* @param name Name of internal-to-BasicPiece key command whose enabled status it to be set
* @param enable true to enable, false to disable.
*/
private void enableCommand(String name, boolean enable) {
for (final KeyCommand command : commands) {
if (name.equals(command.getName())) {
command.setEnabled(enable);
}
}
}
/**
* @param stroke KeyStroke to query if corresponding internal-to-BasicPiece command is enabled
* @return false if no Keystroke, true if not an internal-to-BasicPiece key command, and enabled status of key command otherwise.
*/
private boolean isEnabled(KeyStroke stroke) {
if (stroke == null) {
return false;
}
for (final KeyCommand command : commands) {
if (stroke.equals(command.getKeyStroke())) {
return command.isEnabled();
}
}
return true;
}
/**
* @return piece's position on its map.
*/
@Override
public Point getPosition() {
return getParent() == null ? new Point(pos) : getParent().getPosition();
}
/**
* @param p Sets the location of this piece on its {@link Map}
*/
@Override
public void setPosition(Point p) {
if (getMap() != null && getParent() == null) {
getMap().repaint(getMap().boundingBoxOf(Decorator.getOutermost(this)));
}
pos = p;
if (getMap() != null && getParent() == null) {
getMap().repaint(getMap().boundingBoxOf(Decorator.getOutermost(this)));
}
}
/**
* @return the parent {@link Stack} of which this piece is a member, or null if not a member of any Stack
*/
@Override
public Stack getParent() {
return parent;
}
/**
* @param s sets the {@link Stack} to which this piece belongs.
*/
@Override
public void setParent(Stack s) {
parent = s;
}
/**
* @return bounding box rectangle for BasicPiece's image, if an image has been specified.
*/
@Override
public Rectangle boundingBox() {
if (imageBounds == null) {
imageBounds = ImageUtils.getBounds(imagePainter.getImageSize());
}
return new Rectangle(imageBounds);
}
/**
* @return the Shape of this piece, for purposes of selecting it by clicking on it with the mouse. In the case
* of BasicPiece, this is equivalent to the boundingBox of the BasicPiece image, if one exists. Note that the
* shape should be defined in reference to the piece's location, which is ordinarily the center of the basic
* image.
*
* <br><br>For pieces that need a non-rectangular click volume, add a {@link NonRectangular} trait.
*/
@Override
public Shape getShape() {
return boundingBox();
}
/**
* @param c GamePiece to check if equal to this one
* @return Equality check with specified game piece
*/
public boolean equals(GamePiece c) {
return c == this;
}
/**
* @return the name of this GamePiece. This is the name typed by the module designer in the configuration box
* for the BasicPiece.
*/
@Override
public String getName() {
return commonName;
}
/**
* @return the localized name of this GamePiece. This is the translated version of the name typed by the module designer
* in the configuration box for the BasicPiece. It is used to fill the "BasicName" property.
*/
@Override
public String getLocalizedName() {
final String key = TranslatablePiece.PREFIX + getName();
return Localization.getInstance().translate(key, getName());
}
/**
* The primary way for the piece or trait to receive events. {@link KeyStroke} events are forward
* to this method if they are received while the piece is selected (or as the result of e.g. a Global
* Key Command being sent to the piece). The class implementing GamePiece can respond in any way it
* likes. Actual key presses by the player, selected items from the right-click Context Menu, keystrokes
* "applied on move" by a Map that the piece has just moved on, and Global Key Commands all send KeyStrokes
* (and NamedKeyStrokes) which are passed to pieces and traits through this interface.
*
* <br><br>In the case of BasicPiece, if a key command gets here, that means it has already been seen by any and all of
* its Traits ({@link Decorator}s), as BasicPiece is the innermost member of the Decorator stack. The key events
* processed here by BasicPiece include the "move up"/"move down"/"move-to-top"/"move-to-bottom" stack-adjustment
* commands, along with legacy support for cloning and deleting.
*
* @return a {@link Command} that, when executed, will make all changes to the game state (maps, pieces, other
* pieces, etc) to duplicate what the piece did in response to this event on another machine. Often a
* {@link ChangePiece} command, but for example if this keystroke caused the piece/trait to decide to fire
* off a Global Key Command, then the Command returned would include the <i>entire</i> results of that, appended
* as subcommands.
*
* @see VASSAL.build.module.map.ForwardToKeyBuffer
*/
@Override
public Command keyEvent(KeyStroke stroke) {
getKeyCommands();
if (!isEnabled(stroke)) {
return null;
}
Command comm = null;
final GamePiece outer = Decorator.getOutermost(this);
if (cloneKey != 0 && KeyStroke.getKeyStroke(cloneKey, InputEvent.CTRL_DOWN_MASK).equals(stroke)) {
final GamePiece newPiece = ((AddPiece) GameModule.getGameModule().decode(GameModule.getGameModule().encode(new AddPiece(outer)))).getTarget();
newPiece.setId(null);
GameModule.getGameModule().getGameState().addPiece(newPiece);
newPiece.setState(outer.getState());
comm = new AddPiece(newPiece);
if (getMap() != null) {
comm.append(getMap().placeOrMerge(newPiece, getPosition()));
KeyBuffer.getBuffer().remove(outer);
KeyBuffer.getBuffer().add(newPiece);
if (GlobalOptions.getInstance().autoReportEnabled() && !Boolean.TRUE.equals(outer.getProperty(Properties.INVISIBLE_TO_OTHERS))) {
final String name = outer.getLocalizedName();
final String loc = getMap().locationName(outer.getPosition());
final String s;
if (loc != null) {
s = Resources.getString("BasicPiece.clone_report_1", name, loc);
}
else {
s = Resources.getString("BasicPiece.clone_report_2", name);
}
final Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s);
report.execute();
comm = comm.append(report);
}
}
}
else if (deleteKey != 0 && KeyStroke.getKeyStroke(deleteKey, InputEvent.CTRL_DOWN_MASK).equals(stroke)) {
comm = new RemovePiece(outer);
if (getMap() != null && GlobalOptions.getInstance().autoReportEnabled() && !Boolean.TRUE.equals(outer.getProperty(Properties.INVISIBLE_TO_OTHERS))) {
final String name = outer.getLocalizedName();
final String loc = getMap().locationName(outer.getPosition());
final String s;
if (loc != null) {
s = Resources.getString("BasicPiece.delete_report_1", name, loc);
}
else {
s = Resources.getString("BasicPiece.delete_report_2", name);
}
final Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s);
comm = comm.append(report);
}
comm.execute();
}
else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveUpKey())) {
if (parent != null) {
final String oldState = parent.getState();
final int index = parent.indexOf(outer);
if (index < parent.getPieceCount() - 1) {
parent.insert(outer, index + 1);
comm = new ChangePiece(parent.getId(), oldState, parent.getState());
}
else {
getMap().getPieceCollection().moveToFront(parent);
}
}
else {
getMap().getPieceCollection().moveToFront(outer);
}
}
else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveDownKey())) {
if (parent != null) {
final String oldState = parent.getState();
final int index = parent.indexOf(outer);
if (index > 0) {
parent.insert(outer, index - 1);
comm = new ChangePiece(parent.getId(), oldState, parent.getState());
}
else {
getMap().getPieceCollection().moveToBack(parent);
}
}
else {
getMap().getPieceCollection().moveToBack(outer);
}
}
else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveTopKey())) {
parent = outer.getParent();
if (parent != null) {
final String oldState = parent.getState();
if (parent.indexOf(outer) < parent.getPieceCount() - 1) {
parent.insert(outer, parent.getPieceCount() - 1);
comm = new ChangePiece(parent.getId(), oldState, parent.getState());
}
else {
getMap().getPieceCollection().moveToFront(parent);
}
}
else {
getMap().getPieceCollection().moveToFront(outer);
}
}
else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveBottomKey())) {
parent = getParent();
if (parent != null) {
final String oldState = parent.getState();
if (parent.indexOf(outer) > 0) {
parent.insert(outer, 0);
comm = new ChangePiece(parent.getId(), oldState, parent.getState());
}
else {
getMap().getPieceCollection().moveToBack(parent);
}
}
else {
getMap().getPieceCollection().moveToBack(outer);
}
}
return comm;
}
/**
* @return The "state information" is information that can change during
* the course of a game. State information is saved when the game
* is saved and is transferred between players on the server. For
* example, the relative order of pieces in a stack is state
* information, but whether the stack is expanded is not.
*
* <br><br>In the case of BasicPiece, the state information includes the current
* map, x/y position, the unique Game Piece ID, and the keys and values
* of any persistent properties (see {@link #setPersistentProperty})
*/
@Override
public String getState() {
final SequenceEncoder se = new SequenceEncoder(';');
final String mapName = map == null ? "null" : map.getIdentifier(); // NON-NLS
se.append(mapName);
final Point p = getPosition();
se.append(p.x).append(p.y);
se.append(getGpId());
se.append(persistentProps == null ? 0 : persistentProps.size());
// Persistent Property values will always be String (for now).
if (persistentProps != null) {
persistentProps.forEach((key, val) -> {
se.append(key == null ? "" : key.toString());
se.append(val == null ? "" : val.toString());
});
}
return se.getValue();
}
/**
* @param s New state information serialized in string form, ready
* to be passed to a SequenceEncoder#decode. The "state information" is
* information that can change during the course of a game. State information
* is saved when the game is saved and is transferred between players on the
* server. For example, the relative order of pieces in a stack is state
* information, but whether the stack is expanded is not.
*
* <br><br>In the case of BasicPiece, the state information includes the current
* map, x/y position, the unique Game Piece ID, and the keys and values
* of any persistent properties (see {@link #setPersistentProperty})
*/
@Override
public void setState(String s) {
final GamePiece outer = Decorator.getOutermost(this);
final Map oldMap = getMap();
final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(s, ';');
final String mapId = st.nextToken();
Map newMap = null;
if (!"null".equals(mapId)) { // NON-NLS
newMap = Map.getMapById(mapId);
if (newMap == null) {
Decorator.reportDataError(this, Resources.getString("Error.not_found", "Map"), "mapId=" + mapId); // NON-NLS
}
}
final Point newPos = new Point(st.nextInt(0), st.nextInt(0));
setPosition(newPos);
if (newMap != oldMap) {
if (newMap != null) {
// This will remove from oldMap
// and set the map to newMap
newMap.addPiece(outer);
}
else { // oldMap can't possibly be null if we get to here
oldMap.removePiece(outer);
setMap(null);
}
}
setGpId(st.nextToken(""));
// Persistent Property values will always be String (for now).
// Create the HashMap as lazily as possible, no point in creating it for pieces that never move
if (persistentProps != null) {
persistentProps.clear();
}
final int propCount = st.nextInt(0);
for (int i = 0; i < propCount; i++) {
if (persistentProps == null) {
persistentProps = new HashMap<>();
}
final String key = st.nextToken("");
final String val = st.nextToken("");
persistentProps.put(key, val);
}
}
/**
* For BasicPiece, the "merge" of a new state simply involves copying in the
* new one in its entirety -- if any difference is detected.
* @param newState new serialized game state string
* @param oldState old serialized game state string
*/
@Override
public void mergeState(String newState, String oldState) {
if (!newState.equals(oldState)) {
setState(newState);
}
}
/**
* Each GamePiece must have a unique String identifier. These are managed by VASSAL internally and should never
* be changed by custom code.
* @return unique ID for this piece
* @see GameState#getNewPieceId
*/
@Override
public String getId() {
return id;
}
/**
* Each GamePiece must have a unique String identifier. These are managed by VASSAL internally and should never
* be changed by custom code.
* @param id sets unique ID for this piece
* @see GameState#getNewPieceId
*/
@Override
public void setId(String id) {
this.id = id;
}
/**
* @return the Highlighter instance for drawing selected pieces. Note that since this is a static method, all pieces in a
* module will always use the same Highlighter
*/
public static Highlighter getHighlighter() {
if (highlighter == null) {
highlighter = new ColoredBorder();
}
return highlighter;
}
/**
* @param h Set the Highlighter for all pieces
*/
public static void setHighlighter(Highlighter h) {
highlighter = h;
}
/**
* @return Description of what this kind of piece is. Appears in PieceDefiner list of traits.
*/
@Override
public String getDescription() {
return Resources.getString("Editor.BasicPiece.trait_description");
}
/**
* @return the unique gamepiece ID for this piece, as stored in the Property "scratchpad"
*/
public String getGpId() {
final String id = (String) getProperty(Properties.PIECE_ID);
return id == null ? "" : id;
}
/**
* @param id stores the unique gamepiece ID for this piece into the Property "scratchpad"
*/
public void setGpId(String id) {
setProperty(Properties.PIECE_ID, id == null ? "" : id);
}
/**
* @return the help file page for this type of piece.
*/
@Override
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("BasicPiece.html"); // NON-NLS
}
/**
* @return The configurer ({@link PieceEditor} for the BasicPiece, which generates the dialog for editing the
* BasicPiece's type information in the Editor window.
*/
@Override
public PieceEditor getEditor() {
return new Ed(this);
}
/**
* Test if this BasicPiece's Type and State are equal to another
* This method is intended to be used by Unit Tests to verify that a trait
* is unchanged after going through a process such as serialization/deserialization.
*
* @param o Object to compare this Decorator to
* @return true if the Class, type and state all match
*/
public boolean testEquals(Object o) {
// Check Class type
if (! (o instanceof BasicPiece)) return false;
final BasicPiece bp = (BasicPiece) o;
// Check Type
if (! Objects.equals(cloneKey, bp.cloneKey)) return false;
if (! Objects.equals(deleteKey, bp.deleteKey)) return false;
if (! Objects.equals(imageName, bp.imageName)) return false;
if (! Objects.equals(commonName, bp.commonName)) return false;
// Check State
final String mapName1 = this.map == null ? "null" : this.map.getIdentifier(); // NON-NLS
final String mapName2 = bp.map == null ? "null" : bp.map.getIdentifier(); // NON-NLS
if (! Objects.equals(mapName1, mapName2)) return false;
if (! Objects.equals(getPosition(), bp.getPosition())) return false;
if (! Objects.equals(getGpId(), bp.getGpId())) return false;
final int pp1 = persistentProps == null ? 0 : persistentProps.size();
final int pp2 = bp.persistentProps == null ? 0 : bp.persistentProps.size();
if (! Objects.equals(pp1, pp2)) return false;
if (persistentProps != null && bp.persistentProps != null) {
for (final Object key : persistentProps.keySet()) {
if (!Objects.equals(persistentProps.get(key), bp.persistentProps.get(key)))
return false;
}
}
return true;
}
/**
* The configurer ({@link PieceEditor} for the BasicPiece, which generates the dialog for editing the
* BasicPiece's type information in the Editor window.
*/
private static class Ed implements PieceEditor {
private TraitConfigPanel panel;
private KeySpecifier cloneKeyInput;
private KeySpecifier deleteKeyInput;
private StringConfigurer pieceName;
private ImageSelector picker;
private final String state;
/**
* @param p to create PieceEditor for
*/
private Ed(BasicPiece p) {
state = p.getState();
initComponents(p);
}
/**
* @param p initializes the editor dialog for the specified BasicPiece
*/
private void initComponents(BasicPiece p) {
panel = new TraitConfigPanel();
pieceName = new StringConfigurer(p.commonName);
panel.add("Editor.name_label", pieceName);
cloneKeyInput = new KeySpecifier(p.cloneKey);
if (p.cloneKey != 0) {
panel.add(new JLabel(Resources.getString("Editor.BasicPiece.to_clone")));
panel.add(cloneKeyInput);
}
deleteKeyInput = new KeySpecifier(p.deleteKey);
if (p.deleteKey != 0) {
panel.add(new JLabel(Resources.getString("Editor.BasicPiece.to_delete")));
panel.add(deleteKeyInput);
}
picker = new ImageSelector(p.imageName);
panel.add("Editor.image_label", picker);
}
/**
* @param p BasicPiece
*/
public void reset(BasicPiece p) {
}
/**
* @return the Component for the BasicPiece configurer
*/
@Override
public Component getControls() {
return panel;
}
/**
* @return the current state string for the BasicPiece
*/
@Override
public String getState() {
return state;
}
/**
* @return the type information string for the BasicPiece based on the current values of the configurer fields
*/
@Override
public String getType() {
final SequenceEncoder se = new SequenceEncoder(cloneKeyInput.getKey(), ';');
final String type = se.append(deleteKeyInput.getKey()).append(picker.getValueString()).append(pieceName.getValueString()).getValue();
return BasicPiece.ID + type;
}
}
/**
* @return String enumeration of type and state information.
*/
@Override
public String toString() {
return super.toString() + "[name=" + getName() + ",type=" + getType() + ",state=" + getState() + "]"; // NON-NLS
}
/**
* @return Object encapsulating the internationalization data for the BasicPiece
*/
@Override
public PieceI18nData getI18nData() {
final PieceI18nData data = new PieceI18nData(this);
data.add(commonName, Resources.getString("Editor.BasicPiece.basic_piece_name_description"));
return data;
}
/**
* @return Property names exposed by the Trait or Piece. In the case of BasicPiece, there are quite a few, mainly
* dealing with past and present location.
*/
@Override
public List<String> getPropertyNames() {
final ArrayList<String> l = new ArrayList<>();
l.add(LOCATION_NAME);
l.add(CURRENT_MAP);
l.add(CURRENT_BOARD);
l.add(CURRENT_ZONE);
l.add(CURRENT_X);
l.add(CURRENT_Y);
l.add(OLD_LOCATION_NAME);
l.add(OLD_MAP);
l.add(OLD_BOARD);
l.add(OLD_ZONE);
l.add(OLD_X);
l.add(OLD_Y);
l.add(BASIC_NAME);
l.add(PIECE_NAME);
l.add(DECK_NAME);
l.add(CLICKED_X);
l.add(CLICKED_Y);
return l;
}
/**
* See {@link AbstractImageFinder}
* Adds our image (if any) to the list of images
* @param s Collection to add image names to
*/
@Override
public void addLocalImageNames(Collection<String> s) {
if (imageName != null) s.add(imageName);
}
} |
package JSyndicateFSJNI;
// this is the Java interface to Syndicate
import JSyndicateFSJNI.struct.JSFSConfig;
import JSyndicateFSJNI.struct.JSFSFileInfo;
import JSyndicateFSJNI.struct.JSFSFillDir;
import JSyndicateFSJNI.struct.JSFSStat;
import JSyndicateFSJNI.struct.JSFSStatvfs;
import JSyndicateFSJNI.struct.JSFSUtimbuf;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JSyndicateFS {
public static final Log LOG = LogFactory.getLog(JSyndicateFS.class);
public static final String LIBRARY_FILE_NAME = "libjsyndicatefs.so";
public static final String LIBRARY_FILE_PATH_KEY = "JSyndicateFS.JSyndicateFSJNI.LibraryPath";
private static boolean isLibraryLoaded = false;
private static boolean isSyndicateInitialized = false;
static { loadLibrary(); }
protected static void loadLibrary() {
// check library is already loaded
if(isLibraryLoaded) return;
String libraryFilename = System.getProperty(LIBRARY_FILE_PATH_KEY, LIBRARY_FILE_NAME);
if((libraryFilename != null) && (!libraryFilename.isEmpty())) {
File jsfsDLL = new File(libraryFilename);
LOG.info("JSFS Library Load : " + jsfsDLL.getAbsolutePath());
if(jsfsDLL.exists() && jsfsDLL.canRead() && jsfsDLL.isFile()) {
try {
System.load(jsfsDLL.getAbsolutePath());
isLibraryLoaded = true;
} catch (Exception ex) {
isLibraryLoaded = false;
throw new UnsatisfiedLinkError("Invalid JSyndicateFSNative Library : " + libraryFilename);
}
} else {
isLibraryLoaded = false;
throw new UnsatisfiedLinkError("Invalid JSyndicateFSNative Library : " + libraryFilename);
}
} else {
isLibraryLoaded = false;
throw new UnsatisfiedLinkError("Invalid JSyndicateFSNative Library : Empty Path");
}
}
protected static void checkLibraryLoaded() {
if(!isLibraryLoaded) {
throw new UnsatisfiedLinkError("Invalid JSyndicateFSNative Library");
}
}
protected static void checkSyndicateInit() {
if(!isSyndicateInitialized) {
throw new IllegalStateException("Syndicate is not initialized");
}
}
public static int jsyndicatefs_init(JSFSConfig cfg) {
checkLibraryLoaded();
if(isSyndicateInitialized) {
throw new IllegalStateException("Syndicate is already initialized");
}
LOG.info("jsyndicatefs_init");
int ret = JSyndicateFSJNI.jsyndicatefs_init(cfg);
if(ret == 0)
isSyndicateInitialized = true;
else
isSyndicateInitialized = false;
return ret;
}
public static int jsyndicatefs_destroy() {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_destroy");
return JSyndicateFSJNI.jsyndicatefs_destroy();
}
public static int jsyndicatefs_getattr(String path, JSFSStat statbuf) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_getattr");
return JSyndicateFSJNI.jsyndicatefs_getattr(path, statbuf);
}
public static int jsyndicatefs_mknod(String path, int mode, long dev) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_mknod");
return JSyndicateFSJNI.jsyndicatefs_mknod(path, mode, dev);
}
public static int jsyndicatefs_mkdir(String path, int mode) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_mkdir");
return JSyndicateFSJNI.jsyndicatefs_mkdir(path, mode);
}
public static int jsyndicatefs_unlink(String path) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_unlink");
return JSyndicateFSJNI.jsyndicatefs_unlink(path);
}
public static int jsyndicatefs_rmdir(String path) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_rmdir");
return JSyndicateFSJNI.jsyndicatefs_rmdir(path);
}
public static int jsyndicatefs_rename(String path, String newpath) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_rename");
return JSyndicateFSJNI.jsyndicatefs_rename(path, newpath);
}
public static int jsyndicatefs_chmod(String path, int mode) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_chmod");
return JSyndicateFSJNI.jsyndicatefs_chmod(path, mode);
}
public static int jsyndicatefs_truncate(String path, long newsize) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_truncate");
return JSyndicateFSJNI.jsyndicatefs_truncate(path, newsize);
}
public static int jsyndicatefs_utime(String path, JSFSUtimbuf ubuf) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_utime");
return JSyndicateFSJNI.jsyndicatefs_utime(path, ubuf);
}
public static int jsyndicatefs_open(String path, JSFSFileInfo fi) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_open");
return JSyndicateFSJNI.jsyndicatefs_open(path, fi);
}
public static int jsyndicatefs_read(String path, byte[] buf, long size, long offset, JSFSFileInfo fi) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_read");
return JSyndicateFSJNI.jsyndicatefs_read(path, buf, size, offset, fi);
}
public static int jsyndicatefs_write(String path, byte[] buf, long size, long offset, JSFSFileInfo fi) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_write");
return JSyndicateFSJNI.jsyndicatefs_write(path, buf, size, offset, fi);
}
public static int jsyndicatefs_statfs(String path, JSFSStatvfs statv) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_statfs");
return JSyndicateFSJNI.jsyndicatefs_statfs(path, statv);
}
public static int jsyndicatefs_flush(String path, JSFSFileInfo fi) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_flush");
return JSyndicateFSJNI.jsyndicatefs_flush(path, fi);
}
public static int jsyndicatefs_release(String path, JSFSFileInfo fi) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_release");
return JSyndicateFSJNI.jsyndicatefs_release(path, fi);
}
public static int jsyndicatefs_fsync(String path, int datasync, JSFSFileInfo fi) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_fsync");
return JSyndicateFSJNI.jsyndicatefs_fsync(path, datasync, fi);
}
public static int jsyndicatefs_setxattr(String path, String name, byte[] value, long size, int flags) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_setxattr");
return JSyndicateFSJNI.jsyndicatefs_setxattr(path, name, value, size, flags);
}
public static int jsyndicatefs_getxattr(String path, String name, byte[] value, long size) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_getxattr");
return JSyndicateFSJNI.jsyndicatefs_getxattr(path, name, value, size);
}
public static int jsyndicatefs_listxattr(String path, byte[] list, long size) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_listxattr");
return JSyndicateFSJNI.jsyndicatefs_listxattr(path, list, size);
}
public static int jsyndicatefs_removexattr(String path, String name) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_removexattr");
return JSyndicateFSJNI.jsyndicatefs_removexattr(path, name);
}
public static int jsyndicatefs_opendir(String path, JSFSFileInfo fi) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_opendir");
return JSyndicateFSJNI.jsyndicatefs_opendir(path, fi);
}
public static int jsyndicatefs_readdir(String path, JSFSFillDir filler, long offset, JSFSFileInfo fi) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_readdir");
return JSyndicateFSJNI.jsyndicatefs_readdir(path, filler, offset, fi);
}
public static int jsyndicatefs_releasedir(String path, JSFSFileInfo fi) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_releasedir");
return JSyndicateFSJNI.jsyndicatefs_releasedir(path, fi);
}
public static int jsyndicatefs_fsyncdir(String path, int datasync, JSFSFileInfo fi) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_fsyncdir");
return JSyndicateFSJNI.jsyndicatefs_fsyncdir(path, datasync, fi);
}
public static int jsyndicatefs_access(String path, int mask) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_access");
return JSyndicateFSJNI.jsyndicatefs_access(path, mask);
}
public static int jsyndicatefs_create(String path, int mode, JSFSFileInfo fi) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_create");
return JSyndicateFSJNI.jsyndicatefs_create(path, mode, fi);
}
public static int jsyndicatefs_ftruncate(String path, long offset, JSFSFileInfo fi) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_ftruncate");
return JSyndicateFSJNI.jsyndicatefs_ftruncate(path, offset, fi);
}
public static int jsyndicatefs_fgetattr(String path, JSFSStat statbuf, JSFSFileInfo fi) {
checkLibraryLoaded();
checkSyndicateInit();
LOG.info("jsyndicatefs_fgetattr");
return JSyndicateFSJNI.jsyndicatefs_fgetattr(path, statbuf, fi);
}
} |
package de.lessvoid.nifty.effects.impl;
import java.util.logging.Logger;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.effects.EffectImpl;
import de.lessvoid.nifty.effects.EffectProperties;
import de.lessvoid.nifty.effects.Falloff;
import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.render.NiftyRenderEngine;
import de.lessvoid.nifty.tools.TargetElementResolver;
/**
* Move - move stuff around.
* @author void
*/
public class Move implements EffectImpl {
private Logger log = Logger.getLogger(Move.class.getName());
private static final String LEFT = "left";
private static final String RIGHT = "right";
private static final String TOP = "top";
private static final String BOTTOM = "bottom";
private String direction;
private long offset = 0;
private long startOffset = 0;
private int offsetDir = 0;
private float offsetY;
private float startOffsetY;
private int startOffsetX;
private float offsetX;
private boolean withTarget = false;
private boolean fromOffset = false;
private boolean toOffset = false;
public void activate(final Nifty nifty, final Element element, final EffectProperties parameter) {
String mode = parameter.getProperty("mode");
direction = parameter.getProperty("direction");
if (LEFT.equals(direction)) {
offset = element.getX() + element.getWidth();
} else if (RIGHT.equals(direction)) {
offset = nifty.getRenderEngine().getWidth() - element.getX();
} else if (TOP.equals(direction)) {
offset = element.getY() + element.getHeight();
} else if (BOTTOM.equals(direction)) {
offset = nifty.getRenderEngine().getHeight() - element.getY();
} else {
offset = 0;
}
if ("out".equals(mode)) {
startOffset = 0;
offsetDir = -1;
withTarget = false;
} else if ("in".equals(mode)) {
startOffset = offset;
offsetDir = 1;
withTarget = false;
} else if ("fromPosition".equals(mode)) {
withTarget = true;
} else if ("toPosition".equals(mode)) {
withTarget = true;
} else if ("fromOffset".equals(mode)) {
fromOffset = true;
startOffsetX = Integer.valueOf(parameter.getProperty("offsetX", "0"));
startOffsetY = Integer.valueOf(parameter.getProperty("offsetY", "0"));
offsetX = Math.abs(startOffsetX);
offsetY = Math.abs(startOffsetY);
} else if ("toOffset".equals(mode)) {
toOffset = true;
startOffsetX = 0;
startOffsetY = 0;
offsetX = Integer.valueOf(parameter.getProperty("offsetX", "0"));
offsetY = Integer.valueOf(parameter.getProperty("offsetY", "0"));
}
String target = parameter.getProperty("targetElement");
if (target != null) {
TargetElementResolver resolver = new TargetElementResolver(nifty.getCurrentScreen(), element);
Element targetElement = resolver.resolve(target);
if (targetElement == null) {
log.warning("move effect for element [" + element.getId() + "] was unable to find target element [" + target + "] at screen [" + nifty.getCurrentScreen().getScreenId() + "]");
return;
}
if ("fromPosition".equals(mode)) {
startOffsetX = targetElement.getX() - element.getX();
startOffsetY = targetElement.getY() - element.getY();
offsetX = -(targetElement.getX() - element.getX());
offsetY = -(targetElement.getY() - element.getY());
} else if ("toPosition".equals(mode)) {
startOffsetX = 0;
startOffsetY = 0;
offsetX = (targetElement.getX() - element.getX());
offsetY = (targetElement.getY() - element.getY());
}
}
}
public void execute(
final Element element,
final float normalizedTime,
final Falloff falloff,
final NiftyRenderEngine r) {
if (fromOffset || toOffset) {
float moveToX = startOffsetX + normalizedTime * offsetX;
float moveToY = startOffsetY + normalizedTime * offsetY;
r.moveTo(moveToX, moveToY);
} else if (withTarget) {
float moveToX = startOffsetX + normalizedTime * offsetX;
float moveToY = startOffsetY + normalizedTime * offsetY;
r.moveTo(moveToX, moveToY);
} else {
if (LEFT.equals(direction)) {
r.moveTo(-startOffset + offsetDir * normalizedTime * offset, 0);
} else if (RIGHT.equals(direction)) {
r.moveTo(startOffset - offsetDir * normalizedTime * offset, 0);
} else if (TOP.equals(direction)) {
r.moveTo(0, -startOffset + offsetDir * normalizedTime * offset);
} else if (BOTTOM.equals(direction)) {
r.moveTo(0, startOffset - offsetDir * normalizedTime * offset);
}
}
}
public void deactivate() {
}
} |
package cgeo.geocaching.utils;
import cgeo.geocaching.BuildConfig;
public class BranchDetectionHelper {
// should contain the version name of the last feature release
public static final String FEATURE_VERSION_NAME = "2022.01.22-RC";
private BranchDetectionHelper() {
// utility class
}
/**
* @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy)
*/
@SuppressWarnings("ConstantConditions") // BUILD_TYPE is detected as constant but can change depending on the build configuration
public static boolean isProductionBuild() {
return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly"));
}
} |
package org.jgrapes.io.test.net;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;
import javax.xml.ws.handler.HandlerResolver;
import org.jgrapes.core.AbstractComponent;
import org.jgrapes.core.Channel;
import org.jgrapes.core.EventPipeline;
import org.jgrapes.core.Components;
import org.jgrapes.core.annotation.Handler;
import org.jgrapes.core.events.Stop;
import org.jgrapes.core.internal.Common;
import org.jgrapes.io.NioDispatcher;
import org.jgrapes.io.test.WaitForTests;
import org.jgrapes.io.util.ByteBufferOutputStream;
import org.jgrapes.io.util.ManagedByteBuffer;
import org.jgrapes.net.Server;
import org.jgrapes.net.events.Accepted;
import org.jgrapes.net.events.Ready;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class BigReadTest {
private static boolean localLogging = false;
@BeforeClass
public static void enableLogging() throws FileNotFoundException {
Logger logger = Logger.getLogger("org.jgrapes");
if (logger.isLoggable(Level.FINE)) {
// Loggin already enabled
return;
}
localLogging = true;
System.setProperty("java.util.logging.SimpleFormatter.format",
"%1$tY-%1$tm-%1$td %5$s%n");
java.util.logging.Handler handler = new ConsoleHandler();
handler.setLevel(Level.FINEST);
handler.setFormatter(new SimpleFormatter());
logger.addHandler(handler);
logger.setUseParentHandlers(false);
logger.setLevel(Level.FINEST);
}
@AfterClass
public static void disableLogging() {
if (!localLogging) {
return;
}
System.setProperty("java.util.logging.SimpleFormatter.format",
"%1$tY-%1$tm-%1$td %5$s%n");
Logger logger = Logger.getLogger("org.jgrapes");
logger.setLevel(Level.INFO);
localLogging = false;
}
public class EchoServer extends AbstractComponent {
/**
* @throws IOException
*/
public EchoServer() throws IOException {
super(Server.DEFAULT_CHANNEL);
attach(new Server(null));
}
/**
* Sends a lot of data to make sure that the data cannot be sent
* with a single write. Only then will the selector generate write
* the ops that we want to test here.
*
* @param event
* @throws IOException
* @throws InterruptedException
*/
@Handler
public void onAcctepted(Accepted<ManagedByteBuffer> event)
throws IOException, InterruptedException {
try (ByteBufferOutputStream out = new ByteBufferOutputStream(
event.getConnection())) {
for (int i = 0; i < 1000000; i++) {
out.write(new String(i + ":Hello World!\n").getBytes());
}
}
}
}
@Test
public void test() throws IOException, InterruptedException,
ExecutionException {
EchoServer app = new EchoServer();
app.attach(new NioDispatcher());
WaitForTests wf = new WaitForTests
(app, Ready.class, Server.DEFAULT_CHANNEL.getMatchKey());
Components.start(app);
Ready readyEvent = (Ready) wf.get();
if (!(readyEvent.getListenAddress() instanceof InetSocketAddress)) {
fail();
}
InetSocketAddress serverAddr
= ((InetSocketAddress)readyEvent.getListenAddress());
// Watchdog
final Thread mainTread = Thread.currentThread();
(new Thread() {
@Override
public void run() {
try {
mainTread.join(5000);
if (mainTread.isAlive()) {
mainTread.interrupt();
}
} catch (InterruptedException e) {
}
}
}).start();
AtomicInteger expected = new AtomicInteger(0);
try (Socket client = new Socket(serverAddr.getAddress(),
serverAddr.getPort())) {
InputStream fromServer = client.getInputStream();
BufferedReader in = new BufferedReader(
new InputStreamReader(fromServer, "ascii"));
while (expected.get() < 1000000) {
String line = in.readLine();
String[] parts = line.split(":");
assertEquals(expected.get(),
Integer.parseInt(parts[0]));
assertEquals("Hello World!", parts[1]);
expected.incrementAndGet();
}
} catch (IOException e) {
e.printStackTrace();
}
assertEquals(1000000, expected.get());
Components.manager(app).fire(new Stop(), Channel.BROADCAST);
assertTrue(Components.awaitExhaustion(3000));
}
} |
package edu.wustl.common.vocab.med;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.wustl.common.dao.DAOFactory;
import edu.wustl.common.dao.JDBCDAO;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.query.util.global.Constants;
public final class MedLookUpManager
{
Map<String,List<String> > pvMap = null;
private static MedLookUpManager medLookUpManager = null;
private MedLookUpManager()
{
}
public static MedLookUpManager instance()
{
if(medLookUpManager == null)
{
medLookUpManager = new MedLookUpManager();
medLookUpManager.init();
}
return medLookUpManager;
}
private void init()
{
JDBCDAO dao = (JDBCDAO) DAOFactory.getInstance().getDAO(Constants.JDBC_DAO);
//List<List<String>> dataList = new ArrayList<List<String>>();
try
{
dao.openSession(null);
List<List<String>> dataList = dao.executeQuery("select synonym,id from MED_LOOKUP_TABLE", null, false, false, null);
if(!dataList.isEmpty())
{
pvMap = new HashMap<String, List<String>>();
String pvFilter;
for(int i=0; i < dataList.size(); i++)
{
pvFilter = dataList.get(i).get(0).substring(dataList.get(i).get(0).indexOf("^")+1) + "%";
if(pvMap.containsKey(pvFilter))
{
pvMap.get(pvFilter).add(dataList.get(i).get(1));
}
else
{
List<String> pvList = new ArrayList<String>();
pvList.add(dataList.get(i).get(1));
pvMap.put(pvFilter,pvList);
}
}
}
}
catch (DAOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<String> getPermissibleValues(String pvFilter)
{
List<String> pvList = null;
/*JDBCDAO dao = (JDBCDAO) DAOFactory.getInstance().getDAO(Constants.JDBC_DAO);
List<String> pvList = null;
try
{
dao.openSession(null);
List<List<String>> dataList = dao.executeQuery("select synonym,id from MED_LOOKUP_TABLE where synonym like '" + pvFilter + "'", null, false, false, null);
if(!dataList.isEmpty())
{
pvList = new ArrayList<String>();
for(int i=0; i < dataList.size(); i++)
{
pvList.add(dataList.get(i).get(1));
}
}
}
catch (DAOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}*/
if(pvMap != null)
{
pvList = pvMap.get(pvFilter);
}
return pvList;
}
} |
package com.intellij.ide.actions;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.DataConstantsEx;
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx;
import com.intellij.openapi.fileEditor.impl.EditorWindow;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManager;
import com.intellij.ui.content.ContentManagerUtil;
public class PinActiveTabAction extends ToggleAction {
/**
* @return selected editor or <code>null</code>
*/
private VirtualFile getFile(final DataContext context){
Project project = (Project)context.getData(DataConstants.PROJECT);
if(project == null){
return null;
}
// To provide file from editor manager, editor component should be active
if(!ToolWindowManager.getInstance(project).isEditorComponentActive()){
return null;
}
return (VirtualFile)context.getData(DataConstants.VIRTUAL_FILE);
}
/**
* @return selected content or <code>null</code>
*/
private Content getContent(final DataContext context){
ContentManager contentManager = ContentManagerUtil.getContentManagerFromContext(context, true);
if (contentManager == null){
return null;
}
return contentManager.getSelectedContent();
}
public boolean isSelected(AnActionEvent e) {
DataContext context = e.getDataContext();
VirtualFile file = getFile(context);
if(file != null){
// 1. Check editor
EditorWindow editorWindow = getEditorWindow(context);
if (!editorWindow.isFileOpen(file)) {
file = editorWindow.getSelectedFile();
if (file == null) return false;
}
return editorWindow.isFilePinned(file);
}
else{
// 2. Check content
final Content content = getContent(context);
if(content != null){
return content.isPinned();
}
else{
return false;
}
}
}
public void setSelected(AnActionEvent e, boolean state) {
DataContext context = e.getDataContext();
VirtualFile file = getFile(context);
if(file != null){
// 1. Check editor
EditorWindow editorWindow = getEditorWindow(context);
if (!editorWindow.isFileOpen(file)) {
file = editorWindow.getSelectedFile();
if (file == null) return;
}
editorWindow.setFilePinned(file, state);
}
else{
Content content = getContent(context); // at this point content cannot be null
content.setPinned(state);
}
}
private EditorWindow getEditorWindow(DataContext context) {
final Project project = (Project) context.getData(DataConstants.PROJECT);
final FileEditorManagerEx fileEditorManager = FileEditorManagerEx.getInstanceEx(project);
EditorWindow editorWindow = (EditorWindow) context.getData(DataConstantsEx.EDITOR_WINDOW);
if (editorWindow == null) {
editorWindow = fileEditorManager.getCurrentWindow();
}
return editorWindow;
}
public void update(AnActionEvent e){
super.update(e);
Presentation presentation = e.getPresentation();
DataContext context = e.getDataContext();
presentation.setEnabled(getFile(context) != null || getContent(context) != null);
if (ActionPlaces.EDITOR_TAB_POPUP.equals(e.getPlace())) {
presentation.setText(isSelected(e) ? "_Unpin Tab" : "_Pin Tab");
} else {
presentation.setText(isSelected(e) ? "Unpin _Active Tab" : "_Pin Active Tab");
}
}
} |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Login{
private String pName; //The players name
private int health; //The players health
private int cHealth; //The players current health
private int mana; // The players mana
private int cMana; //The players current mana
private int level; // The players level
private int xp; // The players expierience
private int str; //The players Strength rating
private int dex; //The players Dexterity rating
private int intel; //The players intelligence rating
private int clv; //The last time they visited the castle
private int turns; //The amount of turns the player has had.
private int mapSize; //The size of the map.
private int locationX; //The x location of the player
private int locationY; //The y location of the player
private int weapon; //The weapon the player has
private boolean map; //if the player has a map
/**
* Logins in a character
* @param charName The character name
* @throws IOException
* @throws NumberFormatException
*/
public Login(String charName) throws NumberFormatException, IOException{
pName = charName;
if (Exists(charName)){
update();
}
else {
System.out.println("How Large would you like the map?");
System.out.println("The input, x, will create a map with the size (x,x).");
mapSize = H.inputInt();
if(mapSize < 7) {
mapSize = 7;
H.pln("The minimum map size is 7");
H.pln("Your mapSize has been changed to 7");
}
System.out.println("No Character File Found");
System.out.println("Creating File");
File newChar = new File(charName+".txt");
newChar.createNewFile();
BufferedWriter news = new BufferedWriter(new FileWriter(newChar));
//Initializing the Stats variables
health = 100;
cHealth = 100;
mana = 100;
cMana = 100;
level = 0;
xp = 0;
str = 5;
dex = 5;
intel = 5;
clv = 0;
turns = 0;
locationX = mapSize/2;
locationY = 0;
weapon = 0;
map = false;
//Printing Stats to Text File
news.write(Integer.toString(health));
news.newLine();
news.write(Integer.toString(cHealth));
news.newLine();
news.write(Integer.toString(mana));
news.newLine();
news.write(Integer.toString(cMana));
news.newLine();
news.write(Integer.toString(level));
news.newLine();
news.write(Integer.toString(xp));
news.newLine();
news.write(Integer.toString(str));
news.newLine();
news.write(Integer.toString(dex));
news.newLine();
news.write(Integer.toString(intel));
news.newLine();
news.write(Integer.toString(clv));
news.newLine();
news.write(Integer.toString(turns));
news.newLine();
news.write(Integer.toString(mapSize));
news.newLine();
news.write(Integer.toString(locationX));
news.newLine();
news.write(Integer.toString(locationY));
news.newLine();
news.write(Integer.toString(weapon));
news.newLine();
news.write(Boolean.toString(map));
news.close();
}
}
/**
* Checks if the textfile exists so I can throw the io exception
* @param charName the name of the character to figure out if the file exists
* @return
*/
public boolean Exists(String charName){
File f = new File(charName+".txt");
return f.exists();
}
/**
* Saves the current stats
* @throws IOException
*/
public void saveStats(int health1, int cHealth1, int mana1, int cMana1, int level1, int xp1, int str1, int dex1, int intel1, int clv1, int turns1, int x, int y, int weapon1, boolean map1) throws IOException{
health = health1;
cHealth = cHealth1;
mana = mana1;
cMana = cMana1;
level = level1;
xp = xp1;
str = str1;
dex = dex1;
intel = intel1;
clv = clv1;
turns = turns1;
locationX = x;
locationY = y;
weapon = weapon1;
map = map1;
File oldSave = new File(pName+".txt");
oldSave.delete();
File newSave = new File(pName+".txt");
newSave.createNewFile();
BufferedWriter save = new BufferedWriter(new FileWriter(newSave));
save.write(Integer.toString(health));
save.newLine();
save.write(Integer.toString(cHealth));
save.newLine();
save.write(Integer.toString(mana));
save.newLine();
save.write(Integer.toString(cMana));
save.newLine();
save.write(Integer.toString(level));
save.newLine();
save.write(Integer.toString(xp));
save.newLine();
save.write(Integer.toString(str));
save.newLine();
save.write(Integer.toString(dex));
save.newLine();
save.write(Integer.toString(intel));
save.newLine();
save.write(Integer.toString(clv));
save.newLine();
save.write(Integer.toString(turns));
save.newLine();
save.write(Integer.toString(mapSize));
save.newLine();
save.write(Integer.toString(locationX));
save.newLine();
save.write(Integer.toString(locationY));
save.newLine();
save.write(Integer.toString(weapon));
save.newLine();
save.write(Boolean.toString(map));
save.close();
}
public void update() throws NumberFormatException, IOException {
BufferedReader input = new BufferedReader(new FileReader(pName+".txt"));
health = Integer.parseInt(input.readLine());
cHealth = Integer.parseInt(input.readLine());
mana = Integer.parseInt(input.readLine());
cMana = Integer.parseInt(input.readLine());
level = Integer.parseInt(input.readLine());
xp = Integer.parseInt(input.readLine());
str = Integer.parseInt(input.readLine());
dex = Integer.parseInt(input.readLine());
intel = Integer.parseInt(input.readLine());
clv = Integer.parseInt(input.readLine());
turns = Integer.parseInt(input.readLine());
mapSize = Integer.parseInt(input.readLine());
locationX = Integer.parseInt(input.readLine());
locationY = Integer.parseInt(input.readLine());
weapon = Integer.parseInt(input.readLine());
map = Boolean.parseBoolean(input.readLine());
input.close();
}
/**
* returns whether the player has a map
* @return map - If player has a map
*/
public boolean getMap() {
return map;
}
/**
* Returns Health
* @return Health - Maximum Health
*/
public int getHealth(){
return health;
}
/**
* Returns Current Health
* @return Current Health - Current Health of Player
*/
public int getCHealth(){
return cHealth;
}
/**
* Retrieves Mana Value
* @return Mana- The Maximum amount of mana
*/
public int getMana(){
return mana;
}
/**
* Retrieves Current Mana Value
* @return Current Mana - The Players Current Amount Of Mana
*/
public int getCMana(){
return cMana;
}
/**
* Retrieves the Players Level
* @return Level- The Current Players Level
*/
public int getLevel(){
return level;
}
/**
* Retrieves Experience Points
* @return Experience - How close you are to the next level
*/
public int getXp(){
return xp;
}
/**
* Retrieves Strength Rating
* @return Strength - The Strength Level
*/
public int getStr(){
return str;
}
/**
* Retrieves Dexterity Rating
* @return Dexterity - Retrieves Dexterity Rating
*/
public int getDex(){
return dex;
}
/**
* Retrieves Intelligence
* @return Intel - The Intelligence rating
*/
public int getIntel(){
return intel;
}
/**
* Retrieves the last time the player visited the castle
* @return Castle Last Visited- The last turn a player was at the castle
*/
public int getCLV(){
return clv;
}
/**
* Retrieves the amount of turns a player has went through
* @return Turns - The amount of turns
*/
public int getTurns(){
return turns;
}
/**
* Retrieves the size of the map
* @return mapSize - the size of the map
*/
public int getMapSize(){
return mapSize;
}
/**
* Retrieves the X start location
* @return locationX - the X location
*/
public int getLocationX() {
return locationX;
}
/**
* Retrieves the Y start location
* @return locationY - the Y location
*/
public int getLocationY() {
return locationY;
}
/**
* Retrieves the weapon the player has
* @return weapon - the weapon the player has
*/
public int getWeapon() {
return weapon;
}
} |
package com.tngtech.jgiven.impl;
import com.google.common.base.Stopwatch;
import java.util.concurrent.TimeUnit;
public class Timer {
Stopwatch timer;
public Timer() {
this.timer = Stopwatch.createStarted();
}
public void reset() {
this.timer.reset();
}
public long stop() {
timer.stop();
return timer.elapsed(TimeUnit.MILLISECONDS);
}
} |
package de.retest.recheck;
import java.util.List;
import org.aeonbits.owner.Config.LoadPolicy;
import org.aeonbits.owner.Config.LoadType;
import org.aeonbits.owner.Config.Sources;
import org.aeonbits.owner.ConfigCache;
import org.aeonbits.owner.ConfigFactory;
import org.aeonbits.owner.Reloadable;
import de.retest.recheck.configuration.ProjectRootFinderUtil;
import de.retest.recheck.persistence.FileOutputFormat;
@LoadPolicy( LoadType.MERGE )
@Sources( { "system:properties", "file:${projectroot}/.retest/retest.properties" } )
public interface RecheckProperties extends Reloadable {
/*
* Basic usage.
*/
static void init() {
ProjectRootFinderUtil.getProjectRoot().ifPresent(
projectRoot -> ConfigFactory.setProperty( "projectroot", projectRoot.toAbsolutePath().toString() ) );
}
static RecheckProperties getInstance() {
final RecheckProperties instance = ConfigCache.getOrCreate( RecheckProperties.class );
instance.reload();
return instance;
}
/*
* Various constants.
*/
static final String PROPERTY_VALUE_SEPARATOR = ";";
static final String ZIP_FOLDER_SEPARATOR = "/";
static final String SCREENSHOT_FOLDER_NAME = "screenshot";
static final String RECHECK_FOLDER_NAME = "recheck";
static final String DEFAULT_XML_FILE_NAME = "retest.xml";
static final String RETEST_FOLDER_NAME = ".retest";
static final String RETEST_PROPERTIES_FILE_NAME = "retest.properties";
static final String GOLDEN_MASTER_FILE_EXTENSION = ".recheck";
static final String TEST_REPORT_FILE_EXTENSION = ".report";
static final String AGGREGATED_TEST_REPORT_FILE_NAME = "tests" + TEST_REPORT_FILE_EXTENSION;
/*
* Properties, their key constants and related functionality.
*/
static final String IGNORE_ATTRIBUTES_PROPERTY_KEY = "de.retest.recheck.ignore.attributes";
@Key( IGNORE_ATTRIBUTES_PROPERTY_KEY )
@DefaultValue( "" )
@Separator( PROPERTY_VALUE_SEPARATOR )
List<String> ignoreAttributes();
static final String ELEMENT_MATCH_THRESHOLD_PROPERTY_KEY = "de.retest.recheck.elementMatchThreshold";
@Key( ELEMENT_MATCH_THRESHOLD_PROPERTY_KEY )
@DefaultValue( "0.3" )
double elementMatchThreshold();
static final String ROOT_ELEMENT_MATCH_THRESHOLD_PROPERTY_KEY = "de.retest.recheck.rootElementMatchThreshold";
@Key( ROOT_ELEMENT_MATCH_THRESHOLD_PROPERTY_KEY )
@DefaultValue( "0.8" )
double rootElementMatchThreshold();
static final String ROOT_ELEMENT_CONTAINED_CHILDREN_MATCH_THRESHOLD_PROPERTY_KEY =
"de.retest.recheck.rootElementContainedChildrenMatchThreshold";
@Key( ROOT_ELEMENT_CONTAINED_CHILDREN_MATCH_THRESHOLD_PROPERTY_KEY )
@DefaultValue( "0.5" )
double rootElementContainedChildrenMatchThreshold();
static final String REHUB_REPORT_UPLOAD_ENABLED_PROPERTY_KEY = "de.retest.recheck.rehub.reportUploadEnabled";
@Key( REHUB_REPORT_UPLOAD_ENABLED_PROPERTY_KEY )
@DefaultValue( "false" )
boolean rehubReportUploadEnabled();
static final String FILE_OUTPUT_FORMAT_PROPERTY_KEY = "de.retest.output.Format";
@Key( FILE_OUTPUT_FORMAT_PROPERTY_KEY )
FileOutputFormat fileOutputFormat();
default FileOutputFormat getReportOutputFormat() {
if ( rehubReportUploadEnabled() ) {
return FileOutputFormat.CLOUD;
}
final FileOutputFormat format = fileOutputFormat();
if ( format == null ) {
return FileOutputFormat.KRYO;
}
return format;
}
default FileOutputFormat getStateOutputFormat() {
final FileOutputFormat format = fileOutputFormat();
return format == FileOutputFormat.ZIP ? format : FileOutputFormat.PLAIN;
}
} |
package dk.itu.kelvin.util;
/**
* <h2>Minimal implementation for calculating hash values.</h2>
* <p>
* DynamicHashArray provides method {@link #hash(int)} for computing a
* {@code hash} from a specific key and returning it as an {@code integer}.
* The hash methods allow for different types of key, both primitive and Object
* respectively {@code int, long, float, double and Object}.
* If key is not an integer, the {@link #hash(int)} is called with
* {@code Type.hashcode(key)} as the parameter.
*
*
* @version 1.0.0
*/
public abstract class DynamicHashArray extends DynamicArray {
/**
* Primes to use for hashing keys.
*/
private static final int[] PRIMES = new int[] {
31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071,
262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393,
67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647
};
/**
* Initialize a hashing array structure with the specified values.
*
* @param capacity The initial capacity of the internal storage.
* @param upperLoadFactor The upper load factor of the internal storage.
* @param upperResizeFactor The upper resize factor of the internal storage.
* @param lowerLoadFactor The lower load factor of the internal storage.
* @param lowerResizeFactor The lower resize factor of the internal storage.
*/
public DynamicHashArray(
final int capacity,
final float upperLoadFactor,
final float upperResizeFactor,
final float lowerLoadFactor,
final float lowerResizeFactor
) {
super(
capacity,
upperLoadFactor,
upperResizeFactor,
lowerLoadFactor,
lowerResizeFactor
);
}
/**
* Compute the hash for the specified key.
*
* @param key The key for which to compute a hash.
* @return The computed hash.
*/
protected final int hash(final int key) {
int t = key & 0x7fffffff;
int log = (int) Math.log(this.capacity());
if (log < 26) {
t = t % PRIMES[log + 5];
}
return t % this.capacity();
}
/**
* Compute the hash for the specified key.
*
* @param key The key for which to compute a hash.
* @return The computed hash.
*/
protected final int hash(final long key) {
return this.hash(Long.hashCode(key));
}
/**
* Compute the hash for the specified key.
*
* @param key The key for which to compute a hash.
* @return The computed hash.
*/
protected final int hash(final float key) {
return this.hash(Float.floatToIntBits(key));
}
/**
* Compute the hash for the specified key.
*
* @param key The key for which to compute a hash.
* @return The computed hash.
*/
protected final int hash(final double key) {
return this.hash(Double.doubleToLongBits(key));
}
/**
* Compute the hash for the specified key.
*
* @param key The key for which to compute a hash.
* @return The computed hash.
*/
protected final int hash(final Object key) {
return this.hash(key.hashCode());
}
} |
package edu.hm.hafner.analysis;
import java.io.Serializable;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import edu.hm.hafner.util.PathUtil;
import edu.hm.hafner.util.TreeString;
import edu.hm.hafner.util.TreeStringBuilder;
import edu.umd.cs.findbugs.annotations.Nullable;
import static edu.hm.hafner.util.IntegerParser.*;
/**
* Creates new {@link Issue issues} using the builder pattern. All properties that have not been set in the builder will
* be set to their default value.
* <p>Example:</p>
* <blockquote><pre>
* Issue issue = new IssueBuilder()
* .setFileName("affected.file")
* .setLineStart(0)
* .setCategory("JavaDoc")
* .setMessage("Missing JavaDoc")
* .setSeverity(Severity.WARNING_LOW);
* </pre></blockquote>
*
* @author Ullrich Hafner
*/
@SuppressWarnings({"InstanceVariableMayNotBeInitialized", "JavaDocMethod", "PMD.TooManyFields"})
public class IssueBuilder {
private static final String EMPTY = StringUtils.EMPTY;
private static final String UNDEFINED = "-";
private static final TreeString UNDEFINED_TREE_STRING = TreeString.valueOf(UNDEFINED);
private static final TreeString EMPTY_TREE_STRING = TreeString.valueOf(StringUtils.EMPTY);
private final TreeStringBuilder fileNameBuilder = new TreeStringBuilder();
private final TreeStringBuilder packageNameBuilder = new TreeStringBuilder();
private final TreeStringBuilder messageBuilder = new TreeStringBuilder();
private int lineStart = 0;
private int lineEnd = 0;
private int columnStart = 0;
private int columnEnd = 0;
@Nullable
private LineRangeList lineRanges;
@Nullable
private String pathName;
private TreeString fileName = UNDEFINED_TREE_STRING;
private TreeString packageName = UNDEFINED_TREE_STRING;
@Nullable
private String directory;
@Nullable
private String category;
@Nullable
private String type;
@Nullable
private Severity severity;
private TreeString message = EMPTY_TREE_STRING;
private String description = EMPTY;
@Nullable
private String moduleName;
@Nullable
private String origin;
@Nullable
private String reference;
@Nullable
private String fingerprint;
@Nullable
private Serializable additionalProperties;
private UUID id = UUID.randomUUID();
/**
* Sets the unique ID of the issue. If not set then an ID will be generated.
*
* @param id
* the ID
*
* @return this
*/
public IssueBuilder setId(final UUID id) {
this.id = id;
return this;
}
/**
* Sets additional properties from the statical analysis tool. This object could be used to store tool specific
* information.
*
* @param additionalProperties
* the instance
*
* @return this
*/
public IssueBuilder setAdditionalProperties(@Nullable final Serializable additionalProperties) {
this.additionalProperties = additionalProperties;
return this;
}
public IssueBuilder setFingerprint(@Nullable final String fingerprint) {
this.fingerprint = fingerprint;
return this;
}
/**
* Sets the name of the affected file. This file name is a path relative to the path of the affected files (see
* {@link #setPathName(String)}).
*
* @param fileName
* the file name
*
* @return this
*/
public IssueBuilder setFileName(@Nullable final String fileName) {
this.fileName = internFileName(fileName);
return this;
}
TreeString internFileName(@Nullable final String unsafeFileName) {
if (unsafeFileName == null || StringUtils.isEmpty(unsafeFileName)) {
return UNDEFINED_TREE_STRING;
}
else {
return fileNameBuilder.intern(normalizeFileName(
new PathUtil().createAbsolutePath(directory, unsafeFileName)));
}
}
/**
* Sets the current work directory. This directory is used as prefix for all subsequent issue file names. If the
* path is set as well, then the final path of an issue is the concatenation of {@code path}, {@code directory}, and
* {@code fileName}. Note that this directory is not visible later on, the issue does only store the path in the
* {@code path} and {@code fileName} properties. I.e., the created issue will get a new file name that is composed
* of {@code directory} and {@code fileName}.
*
* @param directory
* the directory that contains all affected files
*
* @return this
*/
public IssueBuilder setDirectory(@Nullable final String directory) {
this.directory = directory;
return this;
}
/**
* Sets the path of the affected file. Note that this path is not the parent folder of the affected file. This path
* is the folder that contains all of the affected files of a {@link Report}. The path of an affected file is stored
* in the {@code path} and {@code fileName} properties so that issues can be tracked even if the root folder changes
* (due to different build environments).
*
* @param pathName
* the path that contains all affected files
*
* @return this
*/
public IssueBuilder setPathName(@Nullable final String pathName) {
this.pathName = pathName;
return this;
}
/**
* Sets the first line of this issue (lines start at 1; 0 indicates the whole file).
*
* @param lineStart
* the first line
*
* @return this
*/
public IssueBuilder setLineStart(final int lineStart) {
this.lineStart = lineStart;
return this;
}
/**
* Sets the first line of this issue (lines start at 1; 0 indicates the whole file).
*
* @param lineStart
* the first line
*
* @return this
*/
public IssueBuilder setLineStart(@Nullable final String lineStart) {
this.lineStart = parseInt(lineStart);
return this;
}
/**
* Sets the last line of this issue (lines start at 1).
*
* @param lineEnd
* the last line
*
* @return this
*/
public IssueBuilder setLineEnd(final int lineEnd) {
this.lineEnd = lineEnd;
return this;
}
/**
* Sets the last line of this issue (lines start at 1).
*
* @param lineEnd
* the last line
*
* @return this
*/
public IssueBuilder setLineEnd(@Nullable final String lineEnd) {
this.lineEnd = parseInt(lineEnd);
return this;
}
/**
* Sets the first column of this issue (columns start at 1, 0 indicates the whole line).
*
* @param columnStart
* the first column
*
* @return this
*/
public IssueBuilder setColumnStart(final int columnStart) {
this.columnStart = columnStart;
return this;
}
/**
* Sets the first column of this issue (columns start at 1, 0 indicates the whole line).
*
* @param columnStart
* the first column
*
* @return this
*/
public IssueBuilder setColumnStart(@Nullable final String columnStart) {
this.columnStart = parseInt(columnStart);
return this;
}
/**
* Sets the the last column of this issue (columns start at 1).
*
* @param columnEnd
* the last column
*
* @return this
*/
public IssueBuilder setColumnEnd(final int columnEnd) {
this.columnEnd = columnEnd;
return this;
}
/**
* Sets the the last column of this issue (columns start at 1).
*
* @param columnEnd
* the last column
*
* @return this
*/
public IssueBuilder setColumnEnd(@Nullable final String columnEnd) {
this.columnEnd = parseInt(columnEnd);
return this;
}
/**
* Sets the category of this issue (depends on the available categories of the static analysis tool). Examples for
* categories are "Deprecation", "Design", or "JavaDoc".
*
* @param category
* the category
*
* @return this
*/
public IssueBuilder setCategory(@Nullable final String category) {
this.category = category;
return this;
}
/**
* Sets the type of this issue (depends on the available types of the static analysis tool). The type typically is
* the associated rule of the static analysis tool that reported this issue.
*
* @param type
* the type
*
* @return this
*/
public IssueBuilder setType(@Nullable final String type) {
this.type = type;
return this;
}
/**
* Sets the name of the package or name space (or similar concept) that contains this issue.
*
* @param packageName
* the package or namespace name
*
* @return this
*/
public IssueBuilder setPackageName(@Nullable final String packageName) {
this.packageName = internPackageName(packageName);
return this;
}
TreeString internPackageName(@Nullable final String unsafePackageName) {
if (unsafePackageName == null || StringUtils.isBlank(unsafePackageName)) {
return UNDEFINED_TREE_STRING;
}
else {
return packageNameBuilder.intern(unsafePackageName);
}
}
/**
* Sets the name of the module or project (or similar concept) that contains this issue.
*
* @param moduleName
* the module name
*
* @return this
*/
public IssueBuilder setModuleName(@Nullable final String moduleName) {
this.moduleName = moduleName;
return this;
}
/**
* Sets the ID of the tool that did report this issue.
*
* @param origin
* the ID of the originating tool
*
* @return this
*/
public IssueBuilder setOrigin(@Nullable final String origin) {
this.origin = origin;
return this;
}
/**
* Sets a reference to the execution of the static analysis tool (build ID, timestamp, etc.).
*
* @param reference
* the reference
*
* @return this
*/
public IssueBuilder setReference(@Nullable final String reference) {
this.reference = reference;
return this;
}
/**
* Sets the severity of this issue.
*
* @param severity
* the severity
*
* @return this
*/
public IssueBuilder setSeverity(@Nullable final Severity severity) {
this.severity = severity;
return this;
}
/**
* Guesses a severity for the issues: converts a String severity to one of the predefined severities. If the
* provided String does not match (even partly) then the default severity will be returned.
*
* @param severityString
* the severity given as a string representation
*
* @return this
*/
public IssueBuilder guessSeverity(@Nullable final String severityString) {
severity = Severity.guessFromString(severityString);
return this;
}
/**
* Sets the detailed message for this issue.
*
* @param message
* the message
*
* @return this
*/
public IssueBuilder setMessage(@Nullable final String message) {
if (StringUtils.isBlank(message)) {
this.message = EMPTY_TREE_STRING;
}
else {
this.message = messageBuilder.intern(StringUtils.stripToEmpty(message));
}
return this;
}
/**
* Sets an additional description for this issue. Static analysis tools might provide some additional information
* about this issue. This description may contain valid HTML.
*
* @param description
* the description (as HTML content)
*
* @return this
*/
public IssueBuilder setDescription(@Nullable final String description) {
this.description = StringUtils.stripToEmpty(description);
return this;
}
/**
* Sets additional line ranges for this issue. Not that the primary range given by {@code lineStart} and {@code *
* lineEnd} is not included.
*
* @param lineRanges
* the additional line ranges
*
* @return this
*/
public IssueBuilder setLineRanges(final LineRangeList lineRanges) {
this.lineRanges = new LineRangeList(lineRanges);
return this;
}
/**
* Initializes this builder with an exact copy of all properties of the specified issue.
*
* @param copy
* the issue to copy the properties from
*
* @return the initialized builder
*/
public IssueBuilder copy(final Issue copy) {
fileName = copy.getFileNameTreeString();
lineStart = copy.getLineStart();
lineEnd = copy.getLineEnd();
columnStart = copy.getColumnStart();
columnEnd = copy.getColumnEnd();
lineRanges = new LineRangeList();
lineRanges.addAll(copy.getLineRanges());
category = copy.getCategory();
type = copy.getType();
severity = copy.getSeverity();
message = copy.getMessageTreeString();
description = copy.getDescription();
packageName = copy.getPackageNameTreeString();
moduleName = copy.getModuleName();
origin = copy.getOrigin();
reference = copy.getReference();
fingerprint = copy.getFingerprint();
additionalProperties = copy.getAdditionalProperties();
return this;
}
/**
* Creates a new {@link Issue} based on the specified properties.
*
* @return the created issue
*/
public Issue build() {
Issue issue = new Issue(pathName, fileName, lineStart, lineEnd, columnStart, columnEnd, lineRanges,
category, type, packageName, moduleName, severity,
message, description, origin, reference, fingerprint,
additionalProperties, id);
id = UUID.randomUUID(); // make sure that multiple invocations will create different IDs
return issue;
}
private static String normalizeFileName(@Nullable final String platformFileName) {
return defaultString(StringUtils.replace(
StringUtils.strip(platformFileName), "\\", "/"));
}
/**
* Creates a default String representation for undefined input parameters.
*
* @param string
* the string to check
*
* @return the valid string or a default string if the specified string is not valid
*/
private static String defaultString(@Nullable final String string) {
return StringUtils.defaultIfEmpty(string, UNDEFINED).intern();
}
/**
* Creates a new {@link Issue} based on the specified properties. The returned issue is wrapped in an {@link
* Optional}.
*
* @return the created issue
*/
public Optional<Issue> buildOptional() {
return Optional.of(build());
}
} |
package loci.formats.in;
import java.io.IOException;
import loci.common.RandomAccessInputStream;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.ImageTools;
import loci.formats.MetadataTools;
import loci.formats.codec.BitBuffer;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.TiffParser;
public class MRWReader extends FormatReader {
// -- Constants --
public static final String MRW_MAGIC_STRING = "MRM";
private static final int[] COLOR_MAP_1 = {0, 1, 1, 2};
private static final int[] COLOR_MAP_2 = {1, 2, 0, 1};
// -- Fields --
/** Offset to image data. */
private int offset;
private int sensorWidth, sensorHeight;
private int bayerPattern;
private int storageMethod;
private int dataSize;
private float[] wbg;
private byte[] fullImage;
// -- Constructor --
/** Constructs a new MRW reader. */
public MRWReader() {
super("Minolta MRW", "mrw");
domains = new String[] {FormatTools.GRAPHICS_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 4;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
return stream.readString(4).endsWith(MRW_MAGIC_STRING);
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
int nBytes = sensorWidth * sensorHeight;
if (dataSize == 12) nBytes *= 3;
else if (dataSize == 16) nBytes *= 4;
byte[] tmp = new byte[nBytes];
in.seek(offset);
in.read(tmp);
BitBuffer bb = new BitBuffer(tmp);
short[] s = new short[getSizeX() * getSizeY() * 3];
for (int row=0; row<getSizeY(); row++) {
boolean evenRow = (row % 2) == 0;
for (int col=0; col<getSizeX(); col++) {
boolean evenCol = (col % 2) == 0;
short val = (short) (bb.getBits(dataSize) & 0xffff);
int redOffset = row * getSizeX() + col;
int greenOffset = (getSizeY() + row) * getSizeX() + col;
int blueOffset = (2 * getSizeY() + row) * getSizeX() + col;
if (evenRow) {
if (evenCol) {
val = (short) (val * wbg[0]);
if (bayerPattern == 1) s[redOffset] = val;
else s[greenOffset] = val;
}
else {
val = (short) (val * wbg[1]);
if (bayerPattern == 1) s[greenOffset] = val;
else s[blueOffset] = val;
}
}
else {
if (evenCol) {
val = (short) (val * wbg[2]);
if (bayerPattern == 1) s[greenOffset] = val;
else s[redOffset] = val;
}
else {
val = (short) (val * wbg[3]);
if (bayerPattern == 1) s[blueOffset] = val;
else s[greenOffset] = val;
}
}
}
bb.skipBits(dataSize * (sensorWidth - getSizeX()));
}
int[] colorMap = bayerPattern == 1 ? COLOR_MAP_1 : COLOR_MAP_2;
if (fullImage == null) {
fullImage = new byte[FormatTools.getPlaneSize(this)];
fullImage = ImageTools.interpolate(s, fullImage, colorMap,
getSizeX(), getSizeY(), isLittleEndian());
}
RandomAccessInputStream stream = new RandomAccessInputStream(fullImage);
readPlane(stream, x, y, w, h, buf);
stream.close();
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
offset = 0;
sensorWidth = sensorHeight = 0;
bayerPattern = 0;
storageMethod = 0;
dataSize = 0;
wbg = null;
fullImage = null;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
in.skipBytes(4); // magic number
offset = in.readInt() + 8;
while (in.getFilePointer() < offset) {
String blockName = in.readString(4);
int len = in.readInt();
long fp = in.getFilePointer();
if (blockName.endsWith("PRD")) {
in.skipBytes(8);
sensorHeight = in.readShort();
sensorWidth = in.readShort();
core[0].sizeY = in.readShort();
core[0].sizeX = in.readShort();
dataSize = in.read();
in.skipBytes(1);
storageMethod = in.read();
in.skipBytes(4);
bayerPattern = in.read();
}
else if (blockName.endsWith("WBG")) {
wbg = new float[4];
byte[] wbScale = new byte[4];
in.read(wbScale);
for (int i=0; i<wbg.length; i++) {
float coeff = in.readShort();
wbg[i] = coeff / (64 << wbScale[i]);
}
}
else if (blockName.endsWith("TTW") &&
getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM)
{
byte[] b = new byte[len];
in.read(b);
RandomAccessInputStream ras = new RandomAccessInputStream(b);
TiffParser tp = new TiffParser(ras);
IFDList ifds = tp.getIFDs();
for (IFD ifd : ifds) {
Integer[] keys = (Integer[]) ifd.keySet().toArray(new Integer[0]);
// CTR FIXME - getIFDTagName is for debugging only!
for (int q=0; q<keys.length; q++) {
addGlobalMeta(IFD.getIFDTagName(keys[q].intValue()),
ifd.get(keys[q]));
}
}
IFDList exifIFDs = tp.getExifIFDs();
for (IFD exif : exifIFDs) {
for (Integer key : exif.keySet()) {
addGlobalMeta(IFD.getIFDTagName(key.intValue()), exif.get(key));
}
}
ras.close();
}
in.seek(fp + len);
}
core[0].pixelType = FormatTools.UINT16;
core[0].rgb = true;
core[0].littleEndian = false;
core[0].dimensionOrder = "XYCZT";
core[0].imageCount = 1;
core[0].sizeC = 3;
core[0].sizeZ = 1;
core[0].sizeT = 1;
core[0].interleaved = true;
core[0].bitsPerPixel = dataSize;
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
}
} |
package edu.uib.info310.search;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import edu.uib.info310.transformation.XslTransformer;
@Component
public class LastFMSearch {
private static final String similarArtistRequest = "http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist=";
private static final String artistEvents = "http://ws.audioscrobbler.com/2.0/?method=artist.getevents&artist=";
private static final String artistCorrection = "http://ws.audioscrobbler.com/2.0/?method=artist.getcorrection&artist=";
private static final String apiKey = "&api_key=a7123248beb0bbcb90a2e3a9ced3bee9";
private static final Logger LOGGER = LoggerFactory.getLogger(LastFMSearch.class);
public InputStream artistCorrection(String search_string) throws Exception {
URL lastFMRequest = new URL(artistCorrection + search_string + apiKey);
URLConnection lastFMConnection = lastFMRequest.openConnection();
return lastFMConnection.getInputStream();
}
private Document docBuilder(String artist) throws Exception{
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(artistCorrection(artist));
return doc;
}
public String correctArtist(String artist) throws Exception {
Document correction = docBuilder(artist);
NodeList nameList = correction.getElementsByTagName("name");
Node nameNode = nameList.item(0);
Element element = (Element) nameNode;
NodeList name = element.getChildNodes();
return (name.item(0)).getNodeValue();
}
public InputStream getArtistEvents (String artist) throws Exception {
String safeArtist = makeWebSafeString(artist);
URL lastFMRequest = new URL(artistEvents + safeArtist + apiKey);
URLConnection lastFMConnection = lastFMRequest.openConnection();
return lastFMConnection.getInputStream();
}
public InputStream getSimilarArtist(String artist) throws Exception {
String safeArtist = makeWebSafeString(artist);
URL lastFMRequest = new URL(similarArtistRequest + safeArtist + apiKey);
LOGGER.debug("LastFM request URL: " + lastFMRequest.toExternalForm());
URLConnection lastFMConnection = lastFMRequest.openConnection();
return lastFMConnection.getInputStream();
}
public static void main(String[] args) throws Exception {
File xsl = new File("src/main/resources/XSL/SimilarArtistLastFM.xsl");
LastFMSearch search = new LastFMSearch();
XslTransformer transform = new XslTransformer();
transform.setXml(search.getSimilarArtist("Iron & Wine"));
transform.setXsl(xsl);
File file = new File("log/rdf-artist.xml");
FileOutputStream fileOutputStream = new FileOutputStream(file);
transform.transform().writeTo(fileOutputStream);
// System.out.println(transform.transform());
System.out.println(search.correctArtist("beatles"));
}
public String makeWebSafeString(String unsafe){
try {
return URLEncoder.encode(unsafe, "UTF-8");
} catch (UnsupportedEncodingException e) {
return unsafe;
}
}
} |
// ProbeTool.java
package imagej.core.tools;
import java.util.ArrayList;
import imagej.data.DataObject;
import imagej.data.Dataset;
import imagej.data.event.DatasetDeletedEvent;
import imagej.data.event.DatasetRestructuredEvent;
import imagej.data.event.DatasetUpdatedEvent;
import imagej.display.Display;
import imagej.display.DisplayView;
import imagej.display.ImageCanvas;
import imagej.display.MouseCursor;
import imagej.display.event.mouse.MsMovedEvent;
import imagej.event.EventSubscriber;
import imagej.event.Events;
import imagej.event.StatusEvent;
import imagej.tool.BaseTool;
import imagej.tool.Tool;
import imagej.util.IntCoords;
import imagej.util.RealCoords;
import net.imglib2.RandomAccess;
import net.imglib2.img.Img;
import net.imglib2.type.numeric.RealType;
/**
* TODO
*
* @author Barry DeZonia
* @author Rick Lentz
* @author Grant Harris
* @author Curtis Rueden
*/
@Tool(name = "Probe", iconPath = "/tools/probe.png",
description = "Probe Pixel Tool", priority = ProbeTool.PRIORITY)
public class ProbeTool extends BaseTool {
// -- constants --
public static final int PRIORITY = 204;
// -- private instance variables --
private Dataset dataset;
private RandomAccess<? extends RealType<?>> randomAccess;
private long[] position;
private ArrayList<EventSubscriber<?>> subscribers;
// -- constructor --
public ProbeTool() {
subscribeToEvents();
}
// -- ITool methods --
@Override
public void onMouseMove(final MsMovedEvent evt) {
final Display display = evt.getDisplay();
final ImageCanvas canvas = display.getImageCanvas();
final IntCoords mousePos = new IntCoords(evt.getX(), evt.getY());
// mouse not in image ?
if (!canvas.isInImage(mousePos)) {
clearWorkingVariables();
Events.publish(new StatusEvent(""));
}
else { // mouse is over image
// CTR TODO - update tool to probe more than just the active view
final DisplayView activeView = display.getActiveView();
final DataObject dataObject = activeView.getDataObject();
final Dataset d = dataObject instanceof Dataset ?
(Dataset) dataObject : null;
setWorkingVariables(d);
final RealCoords coords = canvas.panelToImageCoords(mousePos);
final int cx = coords.getIntX();
final int cy = coords.getIntY();
final long[] planePos = activeView.getPlanePosition();
fillCurrentPosition(cx, cy, planePos);
randomAccess.setPosition(position);
final double doubleValue = randomAccess.get().getRealDouble();
final String statusMessage;
if (dataset.isInteger()) {
statusMessage =
String.format("x=%d, y=%d, value=%d", cx, cy, (long) doubleValue);
}
else {
statusMessage =
String.format("x=%d, y=%d, value=%f", cx, cy, doubleValue);
}
Events.publish(new StatusEvent(statusMessage));
}
}
@Override
public MouseCursor getCursor() {
return MouseCursor.CROSSHAIR;
}
// -- private interface --
private void clearWorkingVariables() {
position = null;
randomAccess = null;
dataset = null;
}
private void setWorkingVariables(final Dataset d) {
if (d != dataset) {
clearWorkingVariables();
dataset = d;
final Img<? extends RealType<?>> image = d.getImgPlus();
randomAccess = image.randomAccess();
position = new long[image.numDimensions()];
randomAccess.localize(position);
}
}
private void fillCurrentPosition(final long x, final long y,
final long[] planePos)
{
// TODO - FIXME - assumes x & y axes are first two
position[0] = x;
position[1] = y;
for (int i = 2; i < position.length; i++) {
position[i] = planePos[i - 2];
}
}
private void subscribeToEvents() {
subscribers = new ArrayList<EventSubscriber<?>>();
// it is possible that underlying data is changed in such a way that
// probe gets out of sync. force a resync
EventSubscriber<DatasetUpdatedEvent> updateSubscriber =
new EventSubscriber<DatasetUpdatedEvent>() {
@Override
public void onEvent(DatasetUpdatedEvent event) {
if (event.getObject() == dataset) {
clearWorkingVariables();
}
}
};
subscribers.add(updateSubscriber);
Events.subscribe(DatasetUpdatedEvent.class, updateSubscriber);
EventSubscriber<DatasetDeletedEvent> deleteSubscriber =
new EventSubscriber<DatasetDeletedEvent>() {
@Override
public void onEvent(DatasetDeletedEvent event) {
if (event.getObject() == dataset) {
clearWorkingVariables();
}
}
};
subscribers.add(deleteSubscriber);
Events.subscribe(DatasetDeletedEvent.class, deleteSubscriber);
EventSubscriber<DatasetRestructuredEvent> restructureSubscriber =
new EventSubscriber<DatasetRestructuredEvent>() {
@Override
public void onEvent(DatasetRestructuredEvent event) {
if (event.getObject() == dataset) {
clearWorkingVariables();
}
}
};
subscribers.add(restructureSubscriber);
Events.subscribe(DatasetRestructuredEvent.class, restructureSubscriber);
}
} |
// PCIReader.java
package loci.formats.in;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.services.DependencyException;
import loci.common.services.ServiceFactory;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.services.POIService;
import loci.formats.tiff.IFD;
import loci.formats.tiff.TiffParser;
public class PCIReader extends FormatReader {
// -- Constants --
public static final int PCI_MAGIC_BYTES = 0xd0cf11e0;
// -- Fields --
private HashMap<Integer, String> imageFiles;
private POIService poi;
private HashMap<Integer, Double> timestamps;
private String creationDate;
private int binning;
private Vector<Double> uniqueZ;
// -- Constructor --
/** Constructs a new SimplePCI reader. */
public PCIReader() {
super("Compix Simple-PCI", "cxd");
domains = new String[] {FormatTools.LM_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 4;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
return stream.readInt() == PCI_MAGIC_BYTES;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
String file = imageFiles.get(no);
RandomAccessInputStream s = poi.getDocumentStream(file);
TiffParser tp = new TiffParser(s);
// can be raw pixel data or an embedded TIFF file
if (tp.isValidHeader()) {
IFD ifd = tp.getFirstIFD();
tp.getSamples(ifd, buf, x, y, w, h);
}
else {
s.seek(0);
int planeSize = FormatTools.getPlaneSize(this);
s.skipBytes((int) (s.length() - planeSize));
readPlane(s, x, y, w, h, buf);
}
s.close();
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
imageFiles = null;
timestamps = null;
if (poi != null) poi.close();
poi = null;
binning = 0;
creationDate = null;
uniqueZ = null;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
imageFiles = new HashMap<Integer, String>();
timestamps = new HashMap<Integer, Double>();
uniqueZ = new Vector<Double>();
try {
ServiceFactory factory = new ServiceFactory();
poi = factory.getInstance(POIService.class);
}
catch (DependencyException de) {
throw new FormatException("POI library not found", de);
}
poi.initialize(Location.getMappedId(currentId));
double scaleFactor = 1;
Vector<String> allFiles = poi.getDocumentList();
if (allFiles.size() == 0) {
throw new FormatException(
"No files were found - the .cxd may be corrupt.");
}
double firstZ = 0d, secondZ = 0d;
for (String name : allFiles) {
int separator = name.lastIndexOf(File.separator);
String parent = name.substring(0, separator);
String relativePath = name.substring(separator + 1);
RandomAccessInputStream stream = poi.getDocumentStream(name);
stream.order(true);
if (relativePath.equals("Field Count")) {
core[0].imageCount = stream.readInt();
}
else if (relativePath.equals("File Has Image")) {
if (stream.readShort() == 0) {
throw new FormatException("This file does not contain image data.");
}
}
else if (relativePath.startsWith("Bitmap") ||
(relativePath.equals("Data") && parent.indexOf("Image") != -1))
{
imageFiles.put(imageFiles.size(), name);
if (getSizeX() != 0 && getSizeY() != 0) {
int bpp = FormatTools.getBytesPerPixel(getPixelType());
int plane = getSizeX() * getSizeY() * bpp;
if (getSizeC() == 0) {
core[0].sizeC = poi.getFileSize(name) / plane;
}
}
}
else if (relativePath.indexOf("Image_Depth") != -1) {
boolean firstBits = core[0].bitsPerPixel == 0;
int bits = (int) stream.readDouble();
core[0].bitsPerPixel = bits;
while (bits % 8 != 0 || bits == 0) bits++;
if (bits % 3 == 0) {
core[0].sizeC = 3;
bits /= 3;
core[0].bitsPerPixel /= 3;
}
bits /= 8;
core[0].pixelType = FormatTools.pixelTypeFromBytes(bits, false, false);
if (getSizeC() > 1 && firstBits) {
core[0].sizeC /= bits;
}
}
else if (relativePath.indexOf("Image_Height") != -1 && getSizeY() == 0) {
core[0].sizeY = (int) stream.readDouble();
}
else if (relativePath.indexOf("Image_Width") != -1 && getSizeX() == 0) {
core[0].sizeX = (int) stream.readDouble();
}
else if (relativePath.indexOf("Time_From_Start") != -1) {
timestamps.put(getTimestampIndex(parent), stream.readDouble());
}
else if (relativePath.indexOf("Position_Z") != -1) {
double zPos = stream.readDouble();
if (!uniqueZ.contains(zPos)) uniqueZ.add(zPos);
if (name.indexOf("Field 1/") != -1) firstZ = zPos;
else if (name.indexOf("Field 2/") != -1) secondZ = zPos;
}
else if (relativePath.equals("First Field Date & Time")) {
long date = (long) stream.readDouble() * 1000;
creationDate = DateTools.convertDate(date, DateTools.COBOL);
}
else if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM)
{
if (relativePath.equals("Binning")) {
binning = (int) stream.readDouble();
}
else if (relativePath.equals("Comments")) {
String comments = stream.readString((int) stream.length());
String[] lines = comments.split("\n");
for (String line : lines) {
int eq = line.indexOf("=");
if (eq != -1) {
String key = line.substring(0, eq).trim();
String value = line.substring(eq + 1).trim();
addGlobalMeta(key, value);
if (key.equals("factor")) {
if (value.indexOf(";") != -1) {
value = value.substring(0, value.indexOf(";"));
}
scaleFactor = Double.parseDouble(value.trim());
}
}
}
}
}
stream.close();
}
boolean zFirst = !new Double(firstZ).equals(new Double(secondZ));
if (getSizeC() == 0) core[0].sizeC = 1;
core[0].sizeZ = uniqueZ.size() == 0 ? 1 : uniqueZ.size();
core[0].sizeT = getImageCount() / getSizeZ();
core[0].rgb = getSizeC() > 1;
if (imageFiles.size() > getImageCount() && getSizeC() == 1) {
core[0].sizeC = imageFiles.size() / getImageCount();
core[0].imageCount *= getSizeC();
}
core[0].interleaved = false;
core[0].dimensionOrder = zFirst ? "XYCZT" : "XYCTZ";
core[0].littleEndian = true;
core[0].indexed = false;
core[0].falseColor = false;
core[0].metadataComplete = true;
// re-index image files
String[] files = imageFiles.values().toArray(new String[imageFiles.size()]);
for (String file : files) {
int separator = file.lastIndexOf(File.separator);
String parent = file.substring(0, separator);
imageFiles.put(getImageIndex(parent), file);
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
if (creationDate != null) {
store.setImageAcquiredDate(creationDate, 0);
}
else MetadataTools.setDefaultCreationDate(store, id, 0);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
store.setPixelsPhysicalSizeX(scaleFactor, 0);
store.setPixelsPhysicalSizeY(scaleFactor, 0);
for (int i=0; i<timestamps.size(); i++) {
Double timestamp = new Double(timestamps.get(i).doubleValue());
store.setPlaneDeltaT(timestamp, 0, i);
if (i == 2) {
double first = timestamps.get(1).doubleValue();
Double increment = new Double(timestamp.doubleValue() - first);
store.setPixelsTimeIncrement(increment, 0);
}
}
if (binning > 0) {
String instrumentID = MetadataTools.createLSID("Instrument", 0);
String detectorID = MetadataTools.createLSID("Detector", 0);
store.setInstrumentID(instrumentID, 0);
store.setDetectorID(detectorID, 0, 0);
store.setDetectorType(getDetectorType("Other"), 0, 0);
store.setImageInstrumentRef(instrumentID, 0);
for (int c=0; c<getEffectiveSizeC(); c++) {
store.setDetectorSettingsID(detectorID, 0, c);
store.setDetectorSettingsBinning(
getBinning(binning + "x" + binning), 0, c);
}
}
}
}
// -- Helper methods --
/** Get the image index from the image file name. */
private Integer getImageIndex(String path) {
int space = path.lastIndexOf(" ") + 1;
if (space >= path.length()) return null;
int end = path.indexOf(File.separator, space);
String field = path.substring(space, end);
String image = "1";
int imageIndex = path.indexOf("Image") + 5;
if (imageIndex >= 0) {
end = path.indexOf(File.separator, imageIndex);
if (end < 0) end = path.length();
image = path.substring(imageIndex, end);
}
try {
int channel = Integer.parseInt(image) - 1;
return getEffectiveSizeC() * (Integer.parseInt(field) - 1) + channel;
}
catch (NumberFormatException e) { }
return null;
}
private Integer getTimestampIndex(String path) {
int space = path.lastIndexOf(" ") + 1;
if (space >= path.length()) return null;
int end = path.indexOf(File.separator, space);
return Integer.parseInt(path.substring(space , end)) - 1;
}
} |
package imagej.data.lut;
import imagej.command.CommandInfo;
import imagej.data.Dataset;
import imagej.data.DatasetService;
import imagej.data.display.DatasetView;
import imagej.data.display.ImageDisplay;
import imagej.data.display.ImageDisplayService;
import imagej.data.table.ResultsTable;
import imagej.data.table.TableLoader;
import imagej.display.DisplayService;
import imagej.menu.MenuConstants;
import imagej.module.ModuleInfo;
import imagej.module.ModuleService;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.imglib2.RandomAccess;
import net.imglib2.display.ColorTable;
import net.imglib2.display.ColorTable8;
import net.imglib2.meta.Axes;
import net.imglib2.meta.AxisType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import org.scijava.MenuEntry;
import org.scijava.MenuPath;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.service.AbstractService;
import org.scijava.service.Service;
// Attribution: Much of this code was adapted from ImageJ 1.x LutLoader class
// courtesy of Wayne Rasband.
//TODO - DefaultRecentFileService, DefaultWindowService, and DefaultLUTService
//all build menus dynamically (see createInfo()). We may be able to abstract a
//helper class out of these that can be used by them and future services.
/**
* The DefaultLUTService loads {@link ColorTable}s from files (hosted locally or
* externally).
*
* @author Barry DeZonia
* @author Wayne Rasband
* @author Curtis Rueden
*/
@Plugin(type = Service.class)
public class DefaultLUTService extends AbstractService implements LUTService {
// -- Constants --
private static final int RAMP_WIDTH = 256;
private static final int RAMP_HEIGHT = 32;
/** 640K should be more than enough for any LUT! */
private static final int MAX_LUT_LENGTH = 640 * 1024;
// -- Parameters --
@Parameter
private LogService logService;
@Parameter
private ModuleService moduleService;
@Parameter
private DatasetService datasetService;
@Parameter
private DisplayService displayService;
@Parameter
private ImageDisplayService imageDisplayService;
// -- LUTService methods --
@Override
public boolean isLUT(final File file) {
return file.getAbsolutePath().toLowerCase().endsWith(".lut");
}
@Override
public ColorTable loadLUT(final File file) throws IOException {
final FileInputStream is = new FileInputStream(file);
final int length = (int) Math.min(file.length(), Integer.MAX_VALUE);
final ColorTable colorTable;
try {
colorTable = loadLUT(is, length);
}
finally {
is.close();
}
return colorTable;
}
@Override
public ColorTable loadLUT(final URL url) throws IOException {
final InputStream is = url.openStream();
final ColorTable colorTable;
try {
colorTable = loadLUT(is);
}
finally {
is.close();
}
return colorTable;
}
@Override
public ColorTable loadLUT(final InputStream is) throws IOException {
// read bytes from input stream, up to maximum LUT length
final byte[] bytes = new byte[MAX_LUT_LENGTH];
int length = 0;
while (true) {
final int r = is.read(bytes, length, bytes.length - length);
if (r < 0) break; // eof
length += r;
}
return loadLUT(new ByteArrayInputStream(bytes, 0, length), length);
}
@Override
public ColorTable loadLUT(final InputStream is, final int length)
throws IOException
{
ColorTable lut = null;
BufferedInputStream bufferedStr = null;
try {
bufferedStr = new BufferedInputStream(is);
bufferedStr.mark(length);
if (lut == null && length > 768) {
// attempt to read NIH Image LUT
lut = nihImageBinaryLUT(bufferedStr);
bufferedStr.reset();
}
if (lut == null && (length == 0 || length == 768 || length == 970)) {
// attempt to read raw LUT
lut = legacyBinaryLUT(bufferedStr);
bufferedStr.reset();
}
if (lut == null && length > 768) {
lut = legacyTextLUT(bufferedStr);
bufferedStr.reset();
}
if (lut == null) {
lut = modernLUT(bufferedStr);
// bufferedStr.reset();
}
}
finally {
if (bufferedStr != null) bufferedStr.close();
is.close();
}
return lut;
}
@Override
public ImageDisplay createDisplay(final String title,
final ColorTable colorTable)
{
final Dataset dataset =
datasetService.create(new UnsignedByteType(), new long[] { RAMP_WIDTH,
RAMP_HEIGHT }, title, new AxisType[] { Axes.X, Axes.Y });
rampFill(dataset);
// TODO - is this papering over a bug in the dataset/imgplus code?
if (dataset.getColorTableCount() == 0) dataset.initializeColorTables(1);
dataset.setColorTable(colorTable, 0);
// CTR FIXME: May not be safe.
return (ImageDisplay) displayService.createDisplay(dataset);
}
@Override
public void
applyLUT(final ColorTable colorTable, final ImageDisplay display)
{
final DatasetView view = imageDisplayService.getActiveDatasetView(display);
if (view == null) return;
final int channel = view.getIntPosition(Axes.CHANNEL);
view.setColorTable(colorTable, channel);
display.update();
}
// -- Service methods --
@Override
public void initialize() {
final Map<String, URL> luts = new LUTFinder().findLUTs();
final List<ModuleInfo> modules = new ArrayList<ModuleInfo>();
for (final String key : luts.keySet()) {
modules.add(createInfo(key, luts.get(key)));
}
// register the modules with the module service
moduleService.addModules(modules);
}
// -- private initialization code --
private ModuleInfo createInfo(final String key, final URL url) {
// set menu path
final String[] subPaths = key.split("/");
final MenuPath menuPath = new MenuPath();
menuPath.add(new MenuEntry(MenuConstants.IMAGE_LABEL));
menuPath.add(new MenuEntry("Lookup Tables"));
for (int i = 0; i < subPaths.length - 1; i++) {
menuPath.add(new MenuEntry(subPaths[i]));
}
final MenuEntry leaf =
new MenuEntry(tableName(subPaths[subPaths.length - 1]));
leaf.setWeight(50); // set menu position: TODO - do this properly
menuPath.add(leaf);
// hard code path to open as a preset
final HashMap<String, Object> presets = new HashMap<String, Object>();
presets.put("tableURL", url);
// and create the command info
final CommandInfo info =
new CommandInfo("imagej.core.commands.misc.ApplyLookupTable");
info.setPresets(presets);
info.setMenuPath(menuPath);
// use the default icon
// info.setIconPath(iconPath);
return info;
}
private String tableName(final String filename) {
final int ext = filename.lastIndexOf(".lut");
return filename.substring(0, ext);
}
// -- private modern LUT loading method --
private ColorTable modernLUT(final InputStream is) throws IOException {
// TODO : support some new more flexible format
return null;
}
// -- private legacy LUT loading methods --
// note: adapted from IJ1 LutLoader class
private ColorTable nihImageBinaryLUT(final InputStream is)
throws IOException
{
return oldBinaryLUT(false, is);
}
private ColorTable legacyBinaryLUT(final InputStream is) throws IOException {
return oldBinaryLUT(true, is);
}
private ColorTable legacyTextLUT(final BufferedInputStream is)
throws IOException
{
ResultsTable table = new TableLoader().valuesFromTextFile(is);
if (table == null) return null;
byte[] reds = new byte[256];
byte[] greens = new byte[256];
byte[] blues = new byte[256];
int cols = table.getColumnCount();
int rows = table.getRowCount();
if (cols < 3 || cols > 4 || rows < 256 || rows > 258) return null;
int x = cols == 4 ? 1 : 0;
int y = rows > 256 ? 1 : 0;
for (int r = 0; r < 256; r++) {
reds[r] = (byte) table.getValue(x + 0, y + r);
greens[r] = (byte) table.getValue(x + 1, y + r);
blues[r] = (byte) table.getValue(x + 2, y + r);
}
return new ColorTable8(reds, greens, blues);
}
private ColorTable oldBinaryLUT(final boolean raw, final InputStream is)
throws IOException
{
final DataInputStream f = new DataInputStream(is);
int nColors = 256;
if (!raw) {
// attempt to read 32 byte NIH Image LUT header
final int id = f.readInt();
if (id != 1229147980) { // 'ICOL'
// f.close(); // NO - this closes parent InputStream
return null;
}
f.readShort(); // version
nColors = f.readShort();
f.readShort(); // start
f.readShort(); // end
f.readLong(); // fill1
f.readLong(); // fill2
f.readInt(); // filler
}
final byte[] reds = new byte[256];
final byte[] greens = new byte[256];
final byte[] blues = new byte[256];
f.read(reds, 0, nColors);
f.read(greens, 0, nColors);
f.read(blues, 0, nColors);
if (nColors < 256) interpolate(reds, greens, blues, nColors);
// f.close(); // NO - this closes parent InputStream
return new ColorTable8(reds, greens, blues);
}
private void interpolate(final byte[] reds, final byte[] greens,
final byte[] blues, final int nColors)
{
final byte[] r = new byte[nColors];
final byte[] g = new byte[nColors];
final byte[] b = new byte[nColors];
System.arraycopy(reds, 0, r, 0, nColors);
System.arraycopy(greens, 0, g, 0, nColors);
System.arraycopy(blues, 0, b, 0, nColors);
final double scale = nColors / 256.0;
int i1, i2;
double fraction;
for (int i = 0; i < 256; i++) {
i1 = (int) (i * scale);
i2 = i1 + 1;
if (i2 == nColors) i2 = nColors - 1;
fraction = i * scale - i1;
// IJ.write(i+" "+i1+" "+i2+" "+fraction);
reds[i] =
(byte) ((1.0 - fraction) * (r[i1] & 255) + fraction * (r[i2] & 255));
greens[i] =
(byte) ((1.0 - fraction) * (g[i1] & 255) + fraction * (g[i2] & 255));
blues[i] =
(byte) ((1.0 - fraction) * (b[i1] & 255) + fraction * (b[i2] & 255));
}
}
// -- other helper methods --
private void rampFill(final Dataset dataset) {
final RandomAccess<? extends RealType<?>> accessor =
dataset.getImgPlus().randomAccess();
for (int x = 0; x < RAMP_WIDTH; x++) {
accessor.setPosition(x, 0);
for (int y = 0; y < RAMP_HEIGHT; y++) {
accessor.setPosition(y, 1);
accessor.get().setReal(x);
}
}
}
} |
package eu.bitwalker.useragentutils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Enum constants for most common browsers, including e-mail clients and bots.
* @author harald
*
*/
public enum Browser {
/**
* Outlook email client
*/
OUTLOOK( Manufacturer.MICROSOFT, null, 100, "Outlook", new String[] {"MSOffice"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, "MSOffice (([0-9]+))"), // before IE7
/**
* Microsoft Outlook 2007 identifies itself as MSIE7 but uses the html rendering engine of Word 2007.
* Example user agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 1.1.4322; MSOffice 12)
*/
OUTLOOK2007( Manufacturer.MICROSOFT, Browser.OUTLOOK, 107, "Outlook 2007", new String[] {"MSOffice 12"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
OUTLOOK2013( Manufacturer.MICROSOFT, Browser.OUTLOOK, 109, "Outlook 2013", new String[] {"Microsoft Outlook 15"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
OUTLOOK2010( Manufacturer.MICROSOFT, Browser.OUTLOOK, 108, "Outlook 2010", new String[] {"MSOffice 14", "Microsoft Outlook 14"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
/**
* Family of Internet Explorer browsers
*/
IE( Manufacturer.MICROSOFT, null, 1, "Internet Explorer", new String[] { "MSIE", "Trident", "IE " }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, "MSIE (([\\d]+)\\.([\\w]+))" ), // before Mozilla
/**
* Since version 7 Outlook Express is identifying itself. By detecting Outlook Express we can not
* identify the Internet Explorer version which is probably used for the rendering.
* Obviously this product is now called Windows Live Mail Desktop or just Windows Live Mail.
*/
OUTLOOK_EXPRESS7( Manufacturer.MICROSOFT, Browser.IE, 110, "Windows Live Mail", new String[] {"Outlook-Express/7.0"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.TRIDENT, null), // before IE7, previously known as Outlook Express. First released in 2006, offered with different name later
/**
* Since 2007 the mobile edition of Internet Explorer identifies itself as IEMobile in the user-agent.
* If previous versions have to be detected, use the operating system information as well.
*/
IEMOBILE11( Manufacturer.MICROSOFT, Browser.IE, 125, "IE Mobile 11", new String[] { "IEMobile/11" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE10( Manufacturer.MICROSOFT, Browser.IE, 124, "IE Mobile 10", new String[] { "IEMobile/10" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE9( Manufacturer.MICROSOFT, Browser.IE, 123, "IE Mobile 9", new String[] { "IEMobile/9" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE7( Manufacturer.MICROSOFT, Browser.IE, 121, "IE Mobile 7", new String[] { "IEMobile 7" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE6( Manufacturer.MICROSOFT, Browser.IE, 120, "IE Mobile 6", new String[] { "IEMobile 6" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE11( Manufacturer.MICROSOFT, Browser.IE, 95, "Internet Explorer 11", new String[] { "Trident/7", "IE 11." }, new String[] {"MSIE 7"}, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, "(?:Trident\\/7|IE)(?:\\.[0-9]*;)?(?:.*rv:| )(([0-9]+)\\.?([0-9]+))" ), // before Mozilla
IE10( Manufacturer.MICROSOFT, Browser.IE, 92, "Internet Explorer 10", new String[] { "MSIE 10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE9( Manufacturer.MICROSOFT, Browser.IE, 90, "Internet Explorer 9", new String[] { "MSIE 9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE8( Manufacturer.MICROSOFT, Browser.IE, 80, "Internet Explorer 8", new String[] { "MSIE 8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE7( Manufacturer.MICROSOFT, Browser.IE, 70, "Internet Explorer 7", new String[] { "MSIE 7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE6( Manufacturer.MICROSOFT, Browser.IE, 60, "Internet Explorer 6", new String[] { "MSIE 6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE5_5( Manufacturer.MICROSOFT, Browser.IE, 55, "Internet Explorer 5.5", new String[] { "MSIE 5.5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE5( Manufacturer.MICROSOFT, Browser.IE, 50, "Internet Explorer 5", new String[] { "MSIE 5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
/**
* Google Chrome browser
*/
CHROME( Manufacturer.GOOGLE, null, 1, "Chrome", new String[] { "Chrome", "CrMo", "CriOS" }, new String[] { "OPR/", "Web Preview" } , BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Chrome\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ), // before Mozilla
CHROME_MOBILE( Manufacturer.GOOGLE, Browser.CHROME, 100, "Chrome Mobile", new String[] { "CrMo","CriOS", "Mobile Safari" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "(?:CriOS|CrMo|Chrome)\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ),
CHROME40( Manufacturer.GOOGLE, Browser.CHROME, 45, "Chrome 40", new String[] { "Chrome/40" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME39( Manufacturer.GOOGLE, Browser.CHROME, 44, "Chrome 39", new String[] { "Chrome/39" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME38( Manufacturer.GOOGLE, Browser.CHROME, 43, "Chrome 38", new String[] { "Chrome/38" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME37( Manufacturer.GOOGLE, Browser.CHROME, 42, "Chrome 37", new String[] { "Chrome/37" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME36( Manufacturer.GOOGLE, Browser.CHROME, 41, "Chrome 36", new String[] { "Chrome/36" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME35( Manufacturer.GOOGLE, Browser.CHROME, 40, "Chrome 35", new String[] { "Chrome/35" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME34( Manufacturer.GOOGLE, Browser.CHROME, 39, "Chrome 34", new String[] { "Chrome/34" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME33( Manufacturer.GOOGLE, Browser.CHROME, 38, "Chrome 33", new String[] { "Chrome/33" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME32( Manufacturer.GOOGLE, Browser.CHROME, 37, "Chrome 32", new String[] { "Chrome/32" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME31( Manufacturer.GOOGLE, Browser.CHROME, 36, "Chrome 31", new String[] { "Chrome/31" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME30( Manufacturer.GOOGLE, Browser.CHROME, 35, "Chrome 30", new String[] { "Chrome/30" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME29( Manufacturer.GOOGLE, Browser.CHROME, 34, "Chrome 29", new String[] { "Chrome/29" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME28( Manufacturer.GOOGLE, Browser.CHROME, 33, "Chrome 28", new String[] { "Chrome/28" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME27( Manufacturer.GOOGLE, Browser.CHROME, 32, "Chrome 27", new String[] { "Chrome/27" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME26( Manufacturer.GOOGLE, Browser.CHROME, 31, "Chrome 26", new String[] { "Chrome/26" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME25( Manufacturer.GOOGLE, Browser.CHROME, 30, "Chrome 25", new String[] { "Chrome/25" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME24( Manufacturer.GOOGLE, Browser.CHROME, 29, "Chrome 24", new String[] { "Chrome/24" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME23( Manufacturer.GOOGLE, Browser.CHROME, 28, "Chrome 23", new String[] { "Chrome/23" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME22( Manufacturer.GOOGLE, Browser.CHROME, 27, "Chrome 22", new String[] { "Chrome/22" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME21( Manufacturer.GOOGLE, Browser.CHROME, 26, "Chrome 21", new String[] { "Chrome/21" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME20( Manufacturer.GOOGLE, Browser.CHROME, 25, "Chrome 20", new String[] { "Chrome/20" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME19( Manufacturer.GOOGLE, Browser.CHROME, 24, "Chrome 19", new String[] { "Chrome/19" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME18( Manufacturer.GOOGLE, Browser.CHROME, 23, "Chrome 18", new String[] { "Chrome/18" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME17( Manufacturer.GOOGLE, Browser.CHROME, 22, "Chrome 17", new String[] { "Chrome/17" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME16( Manufacturer.GOOGLE, Browser.CHROME, 21, "Chrome 16", new String[] { "Chrome/16" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME15( Manufacturer.GOOGLE, Browser.CHROME, 20, "Chrome 15", new String[] { "Chrome/15" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME14( Manufacturer.GOOGLE, Browser.CHROME, 19, "Chrome 14", new String[] { "Chrome/14" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME13( Manufacturer.GOOGLE, Browser.CHROME, 18, "Chrome 13", new String[] { "Chrome/13" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME12( Manufacturer.GOOGLE, Browser.CHROME, 17, "Chrome 12", new String[] { "Chrome/12" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME11( Manufacturer.GOOGLE, Browser.CHROME, 16, "Chrome 11", new String[] { "Chrome/11" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME10( Manufacturer.GOOGLE, Browser.CHROME, 15, "Chrome 10", new String[] { "Chrome/10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME9( Manufacturer.GOOGLE, Browser.CHROME, 10, "Chrome 9", new String[] { "Chrome/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME8( Manufacturer.GOOGLE, Browser.CHROME, 5, "Chrome 8", new String[] { "Chrome/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
OMNIWEB( Manufacturer.OTHER, null, 2, "Omniweb", new String[] { "OmniWeb" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null),
SAFARI( Manufacturer.APPLE, null, 1, "Safari", new String[] { "Safari" }, new String[] { "OPR/", "Web Preview","Googlebot-Mobile" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Version\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)" ), // before AppleWebKit
BLACKBERRY10( Manufacturer.BLACKBERRY, Browser.SAFARI, 10, "BlackBerry", new String[] { "BB10" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null),
MOBILE_SAFARI( Manufacturer.APPLE, Browser.SAFARI, 2, "Mobile Safari", new String[] { "Mobile Safari","Mobile/" }, new String[] { "Googlebot-Mobile" }, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null ), // before Safari
SILK( Manufacturer.AMAZON, Browser.SAFARI, 15, "Silk", new String[] { "Silk/" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Silk\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\-[\\w]+)?)" ),
SAFARI6( Manufacturer.APPLE, Browser.SAFARI, 6, "Safari 6", new String[] { "Version/6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI5( Manufacturer.APPLE, Browser.SAFARI, 3, "Safari 5", new String[] { "Version/5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI4( Manufacturer.APPLE, Browser.SAFARI, 4, "Safari 4", new String[] { "Version/4" }, new String[] { "Googlebot-Mobile" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
OPERA( Manufacturer.OPERA, null, 1, "Opera", new String[] { " OPR/", "Opera" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Opera\\/(([\\d]+)\\.([\\w]+))"), // before MSIE
OPERA_MINI( Manufacturer.OPERA, Browser.OPERA, 20, "Opera Mini", new String[] { "Opera Mini"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.PRESTO, null), // Opera for mobile devices
OPERA20( Manufacturer.OPERA, Browser.OPERA, 21, "Opera 20", new String[] { "OPR/20." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA19( Manufacturer.OPERA, Browser.OPERA, 19, "Opera 19", new String[] { "OPR/19." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA18( Manufacturer.OPERA, Browser.OPERA, 18, "Opera 18", new String[] { "OPR/18." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA17( Manufacturer.OPERA, Browser.OPERA, 17, "Opera 17", new String[] { "OPR/17." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA16( Manufacturer.OPERA, Browser.OPERA, 16, "Opera 16", new String[] { "OPR/16." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA15( Manufacturer.OPERA, Browser.OPERA, 15, "Opera 15", new String[] { "OPR/15." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA12( Manufacturer.OPERA, Browser.OPERA, 12, "Opera 12", new String[] { "Opera/12", "Version/12." }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"),
OPERA11( Manufacturer.OPERA, Browser.OPERA, 11, "Opera 11", new String[] { "Version/11." }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"),
OPERA10( Manufacturer.OPERA, Browser.OPERA, 10, "Opera 10", new String[] { "Opera/9.8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"),
OPERA9( Manufacturer.OPERA, Browser.OPERA, 5, "Opera 9", new String[] { "Opera/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, null),
KONQUEROR( Manufacturer.OTHER, null, 1, "Konqueror", new String[] { "Konqueror"}, null, BrowserType.WEB_BROWSER, RenderingEngine.KHTML, "Konqueror\\/(([0-9]+)\\.?([\\w]+)?(-[\\w]+)?)" ),
DOLFIN2( Manufacturer.SAMSUNG, null, 1, "Samsung Dolphin 2", new String[] { "Dolfin/2" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null ), // webkit based browser for the bada os
/*
* Apple WebKit compatible client. Can be a browser or an application with embedded browser using UIWebView.
*/
APPLE_WEB_KIT( Manufacturer.APPLE, null, 50, "Apple WebKit", new String[] { "AppleWebKit" }, new String[] { "OPR/", "Web Preview", "Googlebot-Mobile" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
APPLE_ITUNES( Manufacturer.APPLE, Browser.APPLE_WEB_KIT, 52, "iTunes", new String[] { "iTunes" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
APPLE_APPSTORE( Manufacturer.APPLE, Browser.APPLE_WEB_KIT, 53, "App Store", new String[] { "MacAppStore" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
ADOBE_AIR( Manufacturer.ADOBE, Browser.APPLE_WEB_KIT, 1, "Adobe AIR application", new String[] { "AdobeAIR" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
LOTUS_NOTES( Manufacturer.OTHER, null, 3, "Lotus Notes", new String[] { "Lotus-Notes" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, "Lotus-Notes\\/(([\\d]+)\\.([\\w]+))"), // before Mozilla
CAMINO( Manufacturer.OTHER, null, 5, "Camino", new String[] { "Camino" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Camino\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)" ), // using Gecko Engine
CAMINO2( Manufacturer.OTHER, Browser.CAMINO, 17, "Camino 2", new String[] { "Camino/2" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FLOCK( Manufacturer.OTHER, null, 4, "Flock", new String[]{"Flock"}, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Flock\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)"),
FIREFOX( Manufacturer.MOZILLA, null, 10, "Firefox", new String[] { "Firefox" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Firefox\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), // using Gecko Engine
FIREFOX3MOBILE( Manufacturer.MOZILLA, Browser.FIREFOX, 31, "Firefox 3 Mobile", new String[] { "Firefox/3.5 Maemo" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX_MOBILE( Manufacturer.MOZILLA, Browser.FIREFOX, 200, "Firefox Mobile", new String[] { "Mobile" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX_MOBILE23(Manufacturer.MOZILLA, FIREFOX_MOBILE, 223, "Firefox Mobile 23", new String[] { "Firefox/23" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX40( Manufacturer.MOZILLA, Browser.FIREFOX, 217, "Firefox 40", new String[] { "Firefox/40" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX39( Manufacturer.MOZILLA, Browser.FIREFOX, 216, "Firefox 39", new String[] { "Firefox/39" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX38( Manufacturer.MOZILLA, Browser.FIREFOX, 215, "Firefox 38", new String[] { "Firefox/38" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX37( Manufacturer.MOZILLA, Browser.FIREFOX, 214, "Firefox 37", new String[] { "Firefox/37" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX36( Manufacturer.MOZILLA, Browser.FIREFOX, 213, "Firefox 36", new String[] { "Firefox/36" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX35( Manufacturer.MOZILLA, Browser.FIREFOX, 212, "Firefox 35", new String[] { "Firefox/35" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX34( Manufacturer.MOZILLA, Browser.FIREFOX, 211, "Firefox 34", new String[] { "Firefox/34" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX33( Manufacturer.MOZILLA, Browser.FIREFOX, 210, "Firefox 33", new String[] { "Firefox/33" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX32( Manufacturer.MOZILLA, Browser.FIREFOX, 109, "Firefox 32", new String[] { "Firefox/32" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX31( Manufacturer.MOZILLA, Browser.FIREFOX, 310, "Firefox 31", new String[] { "Firefox/31" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX30( Manufacturer.MOZILLA, Browser.FIREFOX, 300, "Firefox 30", new String[] { "Firefox/30" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX29( Manufacturer.MOZILLA, Browser.FIREFOX, 290, "Firefox 29", new String[] { "Firefox/29" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX28( Manufacturer.MOZILLA, Browser.FIREFOX, 280, "Firefox 28", new String[] { "Firefox/28" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX27( Manufacturer.MOZILLA, Browser.FIREFOX, 108, "Firefox 27", new String[] { "Firefox/27" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX26( Manufacturer.MOZILLA, Browser.FIREFOX, 107, "Firefox 26", new String[] { "Firefox/26" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX25( Manufacturer.MOZILLA, Browser.FIREFOX, 106, "Firefox 25", new String[] { "Firefox/25" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX24( Manufacturer.MOZILLA, Browser.FIREFOX, 105, "Firefox 24", new String[] { "Firefox/24" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX23( Manufacturer.MOZILLA, Browser.FIREFOX, 104, "Firefox 23", new String[] { "Firefox/23" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX22( Manufacturer.MOZILLA, Browser.FIREFOX, 103, "Firefox 22", new String[] { "Firefox/22" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX21( Manufacturer.MOZILLA, Browser.FIREFOX, 102, "Firefox 21", new String[] { "Firefox/21" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX20( Manufacturer.MOZILLA, Browser.FIREFOX, 101, "Firefox 20", new String[] { "Firefox/20" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX19( Manufacturer.MOZILLA, Browser.FIREFOX, 100, "Firefox 19", new String[] { "Firefox/19" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX18( Manufacturer.MOZILLA, Browser.FIREFOX, 99, "Firefox 18", new String[] { "Firefox/18" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX17( Manufacturer.MOZILLA, Browser.FIREFOX, 98, "Firefox 17", new String[] { "Firefox/17" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX16( Manufacturer.MOZILLA, Browser.FIREFOX, 97, "Firefox 16", new String[] { "Firefox/16" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX15( Manufacturer.MOZILLA, Browser.FIREFOX, 96, "Firefox 15", new String[] { "Firefox/15" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX14( Manufacturer.MOZILLA, Browser.FIREFOX, 95, "Firefox 14", new String[] { "Firefox/14" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX13( Manufacturer.MOZILLA, Browser.FIREFOX, 94, "Firefox 13", new String[] { "Firefox/13" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX12( Manufacturer.MOZILLA, Browser.FIREFOX, 93, "Firefox 12", new String[] { "Firefox/12" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX11( Manufacturer.MOZILLA, Browser.FIREFOX, 92, "Firefox 11", new String[] { "Firefox/11" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX10( Manufacturer.MOZILLA, Browser.FIREFOX, 91, "Firefox 10", new String[] { "Firefox/10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX9( Manufacturer.MOZILLA, Browser.FIREFOX, 90, "Firefox 9", new String[] { "Firefox/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX8( Manufacturer.MOZILLA, Browser.FIREFOX, 80, "Firefox 8", new String[] { "Firefox/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX7( Manufacturer.MOZILLA, Browser.FIREFOX, 70, "Firefox 7", new String[] { "Firefox/7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX6( Manufacturer.MOZILLA, Browser.FIREFOX, 60, "Firefox 6", new String[] { "Firefox/6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX5( Manufacturer.MOZILLA, Browser.FIREFOX, 50, "Firefox 5", new String[] { "Firefox/5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX4( Manufacturer.MOZILLA, Browser.FIREFOX, 40, "Firefox 4", new String[] { "Firefox/4" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX3( Manufacturer.MOZILLA, Browser.FIREFOX, 30, "Firefox 3", new String[] { "Firefox/3" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX2( Manufacturer.MOZILLA, Browser.FIREFOX, 20, "Firefox 2", new String[] { "Firefox/2" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX1_5( Manufacturer.MOZILLA, Browser.FIREFOX, 15, "Firefox 1.5", new String[] { "Firefox/1.5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
/*
* Thunderbird email client, based on the same Gecko engine Firefox is using.
*/
THUNDERBIRD( Manufacturer.MOZILLA, null, 110, "Thunderbird", new String[] { "Thunderbird" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, "Thunderbird\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ), // using Gecko Engine
THUNDERBIRD12( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 185, "Thunderbird 12", new String[] { "Thunderbird/12" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD11( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 184, "Thunderbird 11", new String[] { "Thunderbird/11" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD10( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 183, "Thunderbird 10", new String[] { "Thunderbird/10" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD8( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 180, "Thunderbird 8", new String[] { "Thunderbird/8" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD7( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 170, "Thunderbird 7", new String[] { "Thunderbird/7" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD6( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 160, "Thunderbird 6", new String[] { "Thunderbird/6" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD3( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 130, "Thunderbird 3", new String[] { "Thunderbird/3" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD2( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 120, "Thunderbird 2", new String[] { "Thunderbird/2" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
SEAMONKEY( Manufacturer.OTHER, null, 15, "SeaMonkey", new String[]{"SeaMonkey"}, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "SeaMonkey\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)"), // using Gecko Engine
BOT( Manufacturer.OTHER, null,12, "Robot/Spider", new String[] {"Googlebot", "Web Preview", "bot", "spider", "crawler", "Feedfetcher", "Slurp", "Twiceler", "Nutch", "BecomeBot"}, null, BrowserType.ROBOT, RenderingEngine.OTHER, null),
BOT_MOBILE( Manufacturer.OTHER, Browser.BOT, 20 , "Mobil Robot/Spider", new String[] {"Googlebot-Mobile"}, null, BrowserType.ROBOT, RenderingEngine.OTHER, null),
MOZILLA( Manufacturer.MOZILLA, null, 1, "Mozilla", new String[] { "Mozilla", "Moozilla" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.OTHER, null), // rest of the mozilla browsers
CFNETWORK( Manufacturer.OTHER, null, 6, "CFNetwork", new String[] { "CFNetwork" }, null, BrowserType.UNKNOWN, RenderingEngine.OTHER, null ), // Mac OS X cocoa library
EUDORA( Manufacturer.OTHER, null, 7, "Eudora", new String[] { "Eudora", "EUDORA" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null ), // email client by Qualcomm
POCOMAIL( Manufacturer.OTHER, null, 8, "PocoMail", new String[] { "PocoMail" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null ),
THEBAT( Manufacturer.OTHER, null, 9, "The Bat!", new String[]{"The Bat"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null), // Email Client
NETFRONT( Manufacturer.OTHER, null, 10, "NetFront", new String[]{"NetFront"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.OTHER, null), // mobile device browser
EVOLUTION( Manufacturer.OTHER, null, 11, "Evolution", new String[]{"CamelHttpStream"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null),
LYNX( Manufacturer.OTHER, null, 13, "Lynx", new String[]{"Lynx"}, null, BrowserType.TEXT_BROWSER, RenderingEngine.OTHER, "Lynx\\/(([0-9]+)\\.([\\d]+)\\.?([\\w-+]+)?\\.?([\\w-+]+)?)"),
DOWNLOAD( Manufacturer.OTHER, null, 16, "Downloading Tool", new String[]{"cURL","wget", "ggpht.com", "Apache-HttpClient"}, null, BrowserType.TOOL, RenderingEngine.OTHER, null),
UNKNOWN( Manufacturer.OTHER, null, 14, "Unknown", new String[0], null, BrowserType.UNKNOWN, RenderingEngine.OTHER, null ),
@Deprecated
APPLE_MAIL( Manufacturer.APPLE, null, 51, "Apple Mail", new String[0], null, BrowserType.EMAIL_CLIENT, RenderingEngine.WEBKIT, null); // not detectable any longer.
/*
* An id for each browser version which is unique per manufacturer.
*/
private final short id;
private final String name;
private final String[] aliases;
private final String[] excludeList; // don't match when these values are in the agent-string
private final BrowserType browserType;
private final Manufacturer manufacturer;
private final RenderingEngine renderingEngine;
private final Browser parent;
private List<Browser> children;
private Pattern versionRegEx;
private static List<Browser> topLevelBrowsers;
private Browser(Manufacturer manufacturer, Browser parent, int versionId, String name, String[] aliases, String[] exclude, BrowserType browserType, RenderingEngine renderingEngine, String versionRegexString) {
this.id = (short) ( ( manufacturer.getId() << 8) + (byte) versionId);
this.name = name;
this.parent = parent;
this.children = new ArrayList<Browser>();
this.aliases = toLowerCase(aliases);
this.excludeList = toLowerCase(exclude);
this.browserType = browserType;
this.manufacturer = manufacturer;
this.renderingEngine = renderingEngine;
if (versionRegexString != null)
this.versionRegEx = Pattern.compile(versionRegexString);
if (this.parent == null)
addTopLevelBrowser(this);
else
this.parent.children.add(this);
}
private static String[] toLowerCase(String[] strArr) {
if (strArr == null) return null;
String[] res = new String[strArr.length];
for (int i=0; i<strArr.length; i++) {
res[i] = strArr[i].toLowerCase();
}
return res;
}
// create collection of top level browsers during initialization
private static void addTopLevelBrowser(Browser browser) {
if(topLevelBrowsers == null)
topLevelBrowsers = new ArrayList<Browser>();
topLevelBrowsers.add(browser);
}
public short getId() {
return id;
}
public String getName() {
return name;
}
private Pattern getVersionRegEx() {
if (this.versionRegEx == null) {
if (this.getGroup() != this)
return this.getGroup().getVersionRegEx();
else
return null;
}
return this.versionRegEx;
}
/**
* Detects the detailed version information of the browser. Depends on the userAgent to be available.
* Returns null if it can not detect the version information.
* @return Version
*/
public Version getVersion(String userAgentString) {
Pattern pattern = this.getVersionRegEx();
if (userAgentString != null && pattern != null) {
Matcher matcher = pattern.matcher(userAgentString);
if (matcher.find()) {
String fullVersionString = matcher.group(1);
String majorVersion = matcher.group(2);
String minorVersion = "0";
if (matcher.groupCount() > 2) // usually but not always there is a minor version
minorVersion = matcher.group(3);
return new Version (fullVersionString,majorVersion,minorVersion);
}
}
return null;
}
/**
* @return the browserType
*/
public BrowserType getBrowserType() {
return browserType;
}
/**
* @return the manufacturer
*/
public Manufacturer getManufacturer() {
return manufacturer;
}
/**
* @return the rendering engine
*/
public RenderingEngine getRenderingEngine() {
return renderingEngine;
}
/**
* @return top level browser family
*/
public Browser getGroup() {
if (this.parent != null) {
return parent.getGroup();
}
return this;
}
/*
* Checks if the given user-agent string matches to the browser.
* Only checks for one specific browser.
*/
public boolean isInUserAgentString(String agentString)
{
if (agentString == null) return false;
String agentStringLowerCase = agentString.toLowerCase();
for (String alias : aliases)
{
if (agentStringLowerCase.contains(alias))
return true;
}
return false;
}
/**
* Checks if the given user-agent does not contain one of the tokens which should not match.
* In most cases there are no excluding tokens, so the impact should be small.
* @param agentString
* @return
*/
private boolean containsExcludeToken(String agentString)
{
if (agentString == null) return false;
if (excludeList != null) {
String agentStringLowerCase = agentString.toLowerCase();
for (String exclude : excludeList) {
if (agentStringLowerCase.contains(exclude))
return true;
}
}
return false;
}
private Browser checkUserAgent(String agentString) {
if (this.isInUserAgentString(agentString)) {
if (this.children.size() > 0) {
for (Browser childBrowser : this.children) {
Browser match = childBrowser.checkUserAgent(agentString);
if (match != null) {
return match;
}
}
}
// if children didn't match we continue checking the current to prevent false positives
if (!this.containsExcludeToken(agentString)) {
return this;
}
}
return null;
}
/**
* Iterates over all Browsers to compare the browser signature with
* the user agent string. If no match can be found Browser.UNKNOWN will
* be returned.
* Starts with the top level browsers and only if one of those matches
* checks children browsers.
* Steps out of loop as soon as there is a match.
* @param agentString
* @return Browser
*/
public static Browser parseUserAgentString(String agentString)
{
return parseUserAgentString(agentString, topLevelBrowsers);
}
/**
* Iterates over the given Browsers (incl. children) to compare the browser
* signature with the user agent string.
* If no match can be found Browser.UNKNOWN will be returned.
* Steps out of loop as soon as there is a match.
* Be aware that if the order of the provided Browsers is incorrect or if the set is too limited it can lead to false matches!
* @param agentString
* @return Browser
*/
public static Browser parseUserAgentString(String agentString, List<Browser> browsers)
{
for (Browser browser : browsers) {
Browser match = browser.checkUserAgent(agentString);
if (match != null) {
return match; // either current operatingSystem or a child object
}
}
return Browser.UNKNOWN;
}
public static Browser valueOf(short id)
{
for (Browser browser : Browser.values())
{
if (browser.getId() == id)
return browser;
}
// same behavior as standard valueOf(string) method
throw new IllegalArgumentException(
"No enum const for id " + id);
}
} |
package frogcraftrebirth.common;
import frogcraftrebirth.api.FrogAPI;
import frogcraftrebirth.api.FrogRegistees;
import frogcraftrebirth.api.mps.MPSUpgradeManager;
import frogcraftrebirth.common.lib.AdvBlastFurnaceRecipe;
import frogcraftrebirth.common.lib.AdvChemRecRecipe;
import frogcraftrebirth.common.lib.CondenseTowerRecipe;
import frogcraftrebirth.common.lib.PyrolyzerRecipe;
import frogcraftrebirth.common.lib.recipes.FrogRecipeInputItemStack;
import frogcraftrebirth.common.lib.recipes.FrogRecipeInputOreDict;
import frogcraftrebirth.common.lib.recipes.FrogRecipeInputUniversalFluidCell;
import frogcraftrebirth.common.lib.recipes.FrogRecipeInputs;
import frogcraftrebirth.common.lib.util.FluidStackFactory;
import ic2.api.item.IC2Items;
import ic2.api.recipe.Recipes;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidUtil;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.oredict.OreDictionary;
import java.util.Arrays;
import java.util.Collections;
class FrogRecipes {
public static void init() {
initOreDict();
if (FrogConfig.modpackOptions.enableRecipes) {
FluidStackFactory fluidFactory = new FluidStackFactory();
// CaO + H2O -> Ca(OH)2
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputItemStack(new ItemStack(FrogRegistees.NON_METAL_DUST, 1,4)), new FrogRecipeInputUniversalFluidCell(new FluidStack(FluidRegistry.WATER, 1000))), Collections.singleton(new ItemStack(FrogRegistees.NON_METAL_DUST, 1,6)), ItemStack.EMPTY, 20, 100, 0, 1));
// Ca(OH)2 + CO2 -> CaCO3 + H2O
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputItemStack(new ItemStack(FrogRegistees.NON_METAL_DUST, 1,6)), new FrogRecipeInputUniversalFluidCell(new FluidStack(FrogFluids.carbonDioxide, 1000))), Arrays.asList(new ItemStack(FrogRegistees.NON_METAL_DUST, 1, 1), IC2Items.getItem("fluid_cell", "water")), ItemStack.EMPTY, 20, 10, 0, 0));
// N2 + 3H2 -> 2NH3
ItemStack hydrogenCells = IC2Items.getItem("fluid_cell", "ic2hydrogen");
hydrogenCells.setCount(3);
ItemStack ammoniaCell = FrogRecipeInputs.UNI_CELL.copy();
FluidUtil.getFluidHandler(ammoniaCell).fill(fluidFactory.create("ammonia", 1000), true);
ammoniaCell.setCount(2);
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputUniversalFluidCell(fluidFactory.create("nitrogen", 1000)), new FrogRecipeInputItemStack(hydrogenCells)), Collections.singleton(ammoniaCell), new ItemStack(FrogRegistees.REACTION_MODULE, 1, 2), 150, 128, 0, 2));
// CO2 + 2NH3 -> CO(NH2)2 + H2O
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputUniversalFluidCell(fluidFactory.create("carbon_dioxide", 1000)), new FrogRecipeInputItemStack(ammoniaCell.copy())), Arrays.asList(new ItemStack(FrogRegistees.NON_METAL_DUST, 1, 7), IC2Items.getItem("fluid_cell", "water")), ItemStack.EMPTY,50, 40, 0, 2));
// HNO3 + NH3 -> NH4NO3
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputUniversalFluidCell(fluidFactory.create("nitric_acid", 1000)), new FrogRecipeInputUniversalFluidCell(fluidFactory.create("ammonia", 1000))), Collections.singleton(new ItemStack(FrogRegistees.NON_METAL_DUST, 1, 0)), ItemStack.EMPTY, 10, 10, 0, 2));
//SO3+H2O->H2SO4
ItemStack sulfuricCell = FrogRecipeInputs.UNI_CELL.copy();
FluidUtil.getFluidHandler(sulfuricCell).fill(fluidFactory.create("sulfuric_acid", 1000), true);
sulfuricCell.setCount(1);
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputUniversalFluidCell(fluidFactory.create("sulfur_trioxide", 1000)), new FrogRecipeInputUniversalFluidCell(new FluidStack(FluidRegistry.WATER, 1000))), Collections.singleton(sulfuricCell), ItemStack.EMPTY, 1200, 128, 0, 1));
//2SO2+O2->2SO3
ItemStack so3Cell = FrogRecipeInputs.UNI_CELL.copy();
FluidUtil.getFluidHandler(so3Cell).fill(fluidFactory.create("sulfur_trioxide", 1000), true);
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputUniversalFluidCell(fluidFactory.create("sulfur_dioxide", 1000)), new FrogRecipeInputItemStack(IC2Items.getItem("fluid_cell", "ic2oxygen"))), Collections.singleton(so3Cell), new ItemStack(FrogRegistees.REACTION_MODULE, 1, 3), 300, 100, 0, 1));
FrogAPI.managerCT.add(new CondenseTowerRecipe(100, 75, fluidFactory.create("coal_tar", 25), new FluidStack[] { fluidFactory.create("benzene", 2), fluidFactory.create("ammonia", 3), fluidFactory.create("carbon_oxide", 5), fluidFactory.create("methane", 10), fluidFactory.create("ic2hydrogen", 5) }));
FrogAPI.managerCT.add(new CondenseTowerRecipe(10, 75, fluidFactory.create("ic2air", 12), new FluidStack[] { fluidFactory.create("argon", 1), fluidFactory.create("nitrogen", 7), fluidFactory.create("ic2oxygen", 2), fluidFactory.create("carbon_dioxide", 2) }));
FrogAPI.managerPyrolyzer.add(new PyrolyzerRecipe(IC2Items.getItem("dust", "coal"), new ItemStack(FrogRegistees.INFLAMMABLE, 1, 4), fluidFactory.create("coal_tar", 50), 80, 48));
FrogAPI.managerPyrolyzer.add(new PyrolyzerRecipe(new ItemStack(Blocks.COBBLESTONE), new ItemStack(FrogRegistees.NON_METAL_DUST, 1, 4), fluidFactory.create("carbon_dioxide", 50), 100, 64));
FrogAPI.managerPyrolyzer.add(new PyrolyzerRecipe(new ItemStack(Blocks.STONE), new ItemStack(FrogRegistees.NON_METAL_DUST, 1, 4), fluidFactory.create("carbon_dioxide", 50), 100, 64));
//C+O2=CO2
FrogAPI.FUEL_REG.regFuelByproduct(new ItemStack(Items.COAL, 1, 0), FrogFluids.carbonDioxide);
FrogAPI.FUEL_REG.regFuelByproduct(new ItemStack(Items.COAL, 1, 1), FrogFluids.carbonDioxide);
FrogAPI.FUEL_REG.regFuelByproduct("dustCoal", FrogFluids.carbonDioxide);
FrogAPI.FUEL_REG.regFuelByproduct("dustCharcoal", FrogFluids.carbonDioxide);
FrogAPI.FUEL_REG.regFuelByproduct("dustCarbon", FrogFluids.carbonDioxide);
//S+O2=SO2
FrogAPI.FUEL_REG.regFuelByproduct("dustSulfur", FrogFluids.sulfurDioxide);
// TODO implements 2CO+O2=2CO2 as a combustion furnace byproduct
// These recipes are used for matching GregTech style. By default, they should be disabled.
// Not all of recipes from old FrogCraft are implemented, due to the design guideline.
if (FrogConfig.compatibilityOptions.enableTechRebornCompatibility && Loader.isModLoaded("techreborn")) {
//Ca3(PO4)2 + 3SiO2 + 5 C == 3 CaSiO3 + 5CO + 2P
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputOreDict("dustPhosphor", 1), new FrogRecipeInputOreDict("dustSilica", 3), new FrogRecipeInputOreDict("dustCarbon", 5)), Arrays.asList(new ItemStack(FrogRegistees.NON_METAL_DUST, 3, 2), ItemStack.EMPTY, new ItemStack(FrogRegistees.INFLAMMABLE, 2, 2)), new ItemStack(FrogRegistees.REACTION_MODULE, 1, 0), 350, 128, 5, 0));
//CaSiO3=CaO+SiO2
FrogAPI.managerACR.add(new AdvChemRecRecipe(Collections.singleton(new FrogRecipeInputItemStack(new ItemStack(FrogRegistees.NON_METAL_DUST, 1, 2))), Arrays.asList(new ItemStack(FrogRegistees.NON_METAL_DUST, 1, 4), new ItemStack(FrogRegistees.NON_METAL_DUST, 1, 5)), new ItemStack(FrogRegistees.REACTION_MODULE, 1, 0), 400, 128, 0, 0));
//C->raw carbon fiber
//Mg+Br2=MgBr2
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputOreDict("dustMagnesium", 1), new FrogRecipeInputUniversalFluidCell(new FluidStack(FrogFluids.bromine, 1000))), Collections.singleton(new ItemStack(FrogRegistees.INTERMEDIATE, 1, 2)), ItemStack.EMPTY, 10, 30, 0, 1));
//Cl2+2K=2KCl
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputOreDict("potassium", 2), new FrogRecipeInputUniversalFluidCell(new FluidStack(FrogFluids.chlorine, 1000))), Collections.singleton(new ItemStack(FrogRegistees.INTERMEDIATE, 2, 3)), ItemStack.EMPTY, 10, 30, 0, 1));
}
// These recipes are added by FrogCraft: Rebirth.
// It is the existence of these recipes that makes FrogCraft: Rebirth still standing as one
// of the only few chemical engineering mods known in the community.
// H2SO4(l) + SO3(g) -> H2S2O7(l), i.e. oleum
ItemStack oleumCell = FrogRecipeInputs.UNI_CELL.copy();
FluidUtil.getFluidHandler(oleumCell).fill(new FluidStack(FrogFluids.oleum, 1000), true);
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputUniversalFluidCell(fluidFactory.create("sulfuric_acid", 1000)), new FrogRecipeInputUniversalFluidCell(fluidFactory.create("sulfur_trioxide", 1000))), Collections.singleton(oleumCell), ItemStack.EMPTY, 200, 10, 0, 1));
ItemStack sulfuricCell_2 = sulfuricCell.copy();
sulfuricCell_2.setCount(2);
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputUniversalFluidCell(fluidFactory.create("oleum", 1000)), new FrogRecipeInputUniversalFluidCell(new FluidStack(FluidRegistry.WATER, 1000))), Collections.singleton(sulfuricCell_2), ItemStack.EMPTY, 100, 10, 0,0));
// 2KCl + 2H2O -> 2KOH + H2(g) + Cl2(g), manufacturing potassium hydroxide
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputItemStack(new ItemStack(FrogRegistees.INTERMEDIATE, 2, 3)), new FrogRecipeInputUniversalFluidCell(new FluidStack(FluidRegistry.WATER, 2000))), Collections.emptyList(), new ItemStack(FrogRegistees.REACTION_MODULE, 1, 1), 600, 512, 0, 0));
// Saponification
// 2Al2O3 + 3C -> 4Al+ 3CO2, electrolysis
ItemStack co2Cell = FrogRecipeInputs.UNI_CELL.copy();
FluidUtil.getFluidHandler(co2Cell).fill(fluidFactory.create("carbon_dioxide", 1000), true);
co2Cell.setCount(3);
FrogAPI.managerACR.add(new AdvChemRecRecipe(Arrays.asList(new FrogRecipeInputItemStack(new ItemStack(FrogRegistees.INTERMEDIATE, 2, 0)), new FrogRecipeInputOreDict("dustCoal", 3)), Arrays.asList(new ItemStack(FrogRegistees.METAL_DUST, 4, 0), co2Cell), new ItemStack(FrogRegistees.REACTION_MODULE, 1, 1), 1200, 512, 3, 0));
// TiO2 + 2H2 -> Ti + 2H2O
FrogAPI.managerABF.add(new AdvBlastFurnaceRecipe(new FrogRecipeInputItemStack(new ItemStack(FrogRegistees.INTERMEDIATE, 1, 5)), FrogRecipeInputs.EMPTY, FluidRegistry.getFluidStack("ic2hydrogen", 2000), new ItemStack(FrogRegistees.METAL_INGOT, 1, 2), ItemStack.EMPTY, FrogFluids.argon, 300, 0));
// Temperary Aluminium smelting
FrogAPI.managerABF.add(new AdvBlastFurnaceRecipe(new FrogRecipeInputItemStack(new ItemStack(FrogRegistees.METAL_DUST, 1, 0)), FrogRecipeInputs.EMPTY, null, new ItemStack(FrogRegistees.METAL_INGOT, 1, 0), ItemStack.EMPTY, FrogFluids.argon, 200, 0));
}
}
public static void postInit() {
MPSUpgradeManager.INSTANCE.registerSolarUpgrade(IC2Items.getItem("te", "solar_generator"));
MPSUpgradeManager.INSTANCE.registerStorageUpgrade(IC2Items.getItem("upgrade", "energy_storage"), 10000);
MPSUpgradeManager.INSTANCE.registerVoltageUpgrades(IC2Items.getItem("upgrade", "transformer"), 1);
Recipes.advRecipes.addRecipe(new ItemStack(FrogRegistees.AMMONIA_COOLANT_60K), " T ", "TCT", " T ", 'T', "plateTin", 'C', FluidRegistry.getFluidStack("ammonia", 1000));
Recipes.advRecipes.addRecipe(new ItemStack(FrogRegistees.JINKELA), "KKK", "PPP", "NNN", 'K', "ingotPotassium", 'P', "ingotPhosphorus", 'N', FluidRegistry.getFluidStack("nitrogen", 1000));
Recipes.macerator.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE, 1, 0)), null, true, new ItemStack(FrogRegistees.ORE_CRUSHED, 3, 0));
Recipes.macerator.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE, 1, 1)), null, true, new ItemStack(FrogRegistees.ORE_CRUSHED, 3, 1));
Recipes.macerator.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE, 1, 2)), null, true, new ItemStack(FrogRegistees.ORE_CRUSHED, 3, 2));
NBTTagCompound oreWashingMetadata = new NBTTagCompound();
oreWashingMetadata.setInteger("amount", 500);
Recipes.oreWashing.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE_CRUSHED, 1, 0)), oreWashingMetadata, true, new ItemStack(FrogRegistees.ORE_PURIFIED, 1, 0), new ItemStack(FrogRegistees.ORE_DUST_TINY, 2, 0), new ItemStack(Blocks.SAND));
Recipes.oreWashing.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE_CRUSHED, 1, 1)), oreWashingMetadata, true, new ItemStack(FrogRegistees.ORE_PURIFIED, 1, 1), new ItemStack(FrogRegistees.ORE_DUST_TINY, 2, 1), IC2Items.getItem("dust", "stone"));
Recipes.oreWashing.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE_CRUSHED, 1, 2)), oreWashingMetadata, true, new ItemStack(FrogRegistees.ORE_PURIFIED, 1, 2), new ItemStack(FrogRegistees.ORE_DUST_TINY, 2, 2), IC2Items.getItem("dust", "stone"));
NBTTagCompound centrifugeMetadata = new NBTTagCompound();
centrifugeMetadata.setInteger("minHeat", 500);
Recipes.centrifuge.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE_DUST, 5, 0)), centrifugeMetadata, true, new ItemStack(FrogRegistees.INTERMEDIATE, 4, 3), new ItemStack(FrogRegistees.INTERMEDIATE, 1, 2));
Recipes.centrifuge.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE_DUST, 27, 1)), centrifugeMetadata, true, new ItemStack(FrogRegistees.INTERMEDIATE, 25, 0), new ItemStack(FrogRegistees.INTERMEDIATE, 1, 5), new ItemStack(FrogRegistees.INTERMEDIATE, 1, 6));
Recipes.centrifuge.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE_PURIFIED, 1, 0)), centrifugeMetadata, true, new ItemStack(FrogRegistees.ORE_DUST, 1, 0), new ItemStack(FrogRegistees.ORE_DUST_TINY, 1, 0));
Recipes.centrifuge.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE_PURIFIED, 1, 1)), centrifugeMetadata, true, new ItemStack(FrogRegistees.ORE_DUST, 1, 1), new ItemStack(FrogRegistees.ORE_DUST_TINY, 1, 1));
Recipes.centrifuge.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE_PURIFIED, 1, 2)), centrifugeMetadata, true, new ItemStack(FrogRegistees.ORE_DUST, 1, 2), new ItemStack(FrogRegistees.ORE_DUST_TINY, 1, 2));
Recipes.centrifuge.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE_CRUSHED, 1, 0)), centrifugeMetadata, true, new ItemStack(FrogRegistees.ORE_DUST, 1, 0), new ItemStack(FrogRegistees.ORE_DUST_TINY, 2, 0), IC2Items.getItem("dust", "small_lithium"));
Recipes.centrifuge.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE_CRUSHED, 1, 1)), centrifugeMetadata, true, new ItemStack(FrogRegistees.ORE_DUST, 1, 1), new ItemStack(FrogRegistees.ORE_DUST_TINY, 2, 1), IC2Items.getItem("dust", "stone"));
Recipes.centrifuge.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.ORE_CRUSHED, 1, 2)), centrifugeMetadata, true, new ItemStack(FrogRegistees.ORE_DUST, 1, 2), new ItemStack(FrogRegistees.ORE_DUST_TINY, 2, 2), IC2Items.getItem("dust", "stone"));
Recipes.compressor.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.INFLAMMABLE, 8, 4)), null, true, new ItemStack(FrogRegistees.INFLAMMABLE, 1, 0));
Recipes.compressor.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.METAL_PLATE, 9, 0)), null, true, new ItemStack(FrogRegistees.METAL_PLATE_DENSE, 1, 0));
Recipes.compressor.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.METAL_PLATE, 9, 1)), null, true, new ItemStack(FrogRegistees.METAL_PLATE_DENSE, 1, 1));
Recipes.compressor.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.METAL_PLATE, 9, 2)), null, true, new ItemStack(FrogRegistees.METAL_PLATE_DENSE, 1, 2));
Recipes.metalformerRolling.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.METAL_INGOT, 1, 0)), null, true, new ItemStack(FrogRegistees.METAL_PLATE, 1, 0));
Recipes.metalformerRolling.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.METAL_INGOT, 1, 1)), null, true, new ItemStack(FrogRegistees.METAL_PLATE, 1, 1));
Recipes.metalformerRolling.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.METAL_INGOT, 1, 2)), null, true, new ItemStack(FrogRegistees.METAL_PLATE, 1, 2));
Recipes.metalformerRolling.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.METAL_PLATE, 1, 0)), null, true, new ItemStack(FrogRegistees.METAL_CASING, 2, 0));
Recipes.metalformerRolling.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.METAL_PLATE, 1, 1)), null, true, new ItemStack(FrogRegistees.METAL_CASING, 2, 1));
Recipes.metalformerRolling.addRecipe(Recipes.inputFactory.forStack(new ItemStack(FrogRegistees.METAL_PLATE, 1, 2)), null, true, new ItemStack(FrogRegistees.METAL_CASING, 2, 2));
}
private static void initOreDict() {
OreDictionary.registerOre("oreCarnallite", new ItemStack(FrogRegistees.ORE, 1, 0));
OreDictionary.registerOre("oreDewalquite", new ItemStack(FrogRegistees.ORE, 1, 1));
OreDictionary.registerOre("oreFluorapatite", new ItemStack(FrogRegistees.ORE, 1, 2));
OreDictionary.registerOre("dustCarnallite", new ItemStack(FrogRegistees.ORE_DUST, 1, 0));
OreDictionary.registerOre("dustDewalquite", new ItemStack(FrogRegistees.ORE_DUST, 1, 1));
OreDictionary.registerOre("dustFluorapatite", new ItemStack(FrogRegistees.ORE_DUST, 1, 2));
OreDictionary.registerOre("dustTinyCarnallite", new ItemStack(FrogRegistees.ORE_DUST_TINY, 1, 0));
OreDictionary.registerOre("dustTinyDewalquite", new ItemStack(FrogRegistees.ORE_DUST_TINY, 1, 1));
OreDictionary.registerOre("dustTinyFluorapatite", new ItemStack(FrogRegistees.ORE_DUST_TINY, 1, 2));
OreDictionary.registerOre("dustVanadiumPentoxide", new ItemStack(FrogRegistees.INTERMEDIATE, 1, 6));
OreDictionary.registerOre("dustAluminium", new ItemStack(FrogRegistees.METAL_DUST, 1, 0));
OreDictionary.registerOre("dustMagnalium", new ItemStack(FrogRegistees.METAL_DUST, 1, 1));
OreDictionary.registerOre("dustTitanium", new ItemStack(FrogRegistees.METAL_DUST, 1, 2));
OreDictionary.registerOre("ingotAluminium", new ItemStack(FrogRegistees.METAL_INGOT, 1, 0));
OreDictionary.registerOre("ingotMagnalium", new ItemStack(FrogRegistees.METAL_INGOT, 1, 1));
OreDictionary.registerOre("ingotTitanium", new ItemStack(FrogRegistees.METAL_INGOT, 1, 2));
OreDictionary.registerOre("plateAluminium", new ItemStack(FrogRegistees.METAL_PLATE, 1, 0));
OreDictionary.registerOre("plateMagnalium", new ItemStack(FrogRegistees.METAL_PLATE, 1, 1));
OreDictionary.registerOre("plateTitanium", new ItemStack(FrogRegistees.METAL_PLATE, 1, 2));
}
} |
package gigaherz.survivalist.rack;
import gigaherz.common.BlockRegistered;
import gigaherz.survivalist.ConfigManager;
import gigaherz.survivalist.GuiHandler;
import gigaherz.survivalist.Survivalist;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.IItemHandler;
public class BlockRack extends BlockRegistered
{
public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL);
public BlockRack(String name)
{
super(name, Material.WOOD);
setUnlocalizedName(Survivalist.MODID + ".rack");
setCreativeTab(CreativeTabs.DECORATIONS);
setSoundType(SoundType.WOOD);
setDefaultState(blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH));
setHardness(1.0F);
setResistance(1.0F);
setLightOpacity(0);
}
@Override
public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList<ItemStack> list)
{
if (ConfigManager.instance.enableDryingRack)
{
super.getSubBlocks(itemIn, tab, list);
}
}
@Deprecated
@Override
public boolean isOpaqueCube(IBlockState state)
{
return false;
}
@Override
public boolean hasTileEntity(IBlockState state)
{
return true;
}
@Override
public TileEntity createTileEntity(World world, IBlockState state)
{
return new TileRack();
}
@Override
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, FACING);
}
@Deprecated
@Override
public IBlockState getStateFromMeta(int meta)
{
return getDefaultState().withProperty(FACING, EnumFacing.HORIZONTALS[meta & 3]);
}
@Override
public int getMetaFromState(IBlockState state)
{
return state.getValue(FACING).ordinal();
}
@Override
public IBlockState getStateForPlacement(World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer, EnumHand hand)
{
return getDefaultState().withProperty(FACING, placer.getHorizontalFacing());
}
@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ)
{
TileEntity tileEntity = worldIn.getTileEntity(pos);
if (!(tileEntity instanceof TileRack) || playerIn.isSneaking())
return false;
playerIn.openGui(Survivalist.instance, GuiHandler.GUI_RACK, worldIn, pos.getX(), pos.getY(), pos.getZ());
return true;
}
@Override
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
TileEntity tileentity = worldIn.getTileEntity(pos);
if (tileentity instanceof TileRack)
{
dropInventoryItems(worldIn, pos, ((TileRack) tileentity).inventory());
worldIn.updateComparatorOutputLevel(pos, this);
}
super.breakBlock(worldIn, pos, state);
}
private static void dropInventoryItems(World worldIn, BlockPos pos, IItemHandler inventory)
{
for (int i = 0; i < inventory.getSlots(); ++i)
{
ItemStack itemstack = inventory.getStackInSlot(i);
if (itemstack.getCount() > 0)
{
InventoryHelper.spawnItemStack(worldIn, (double) pos.getX(), (double) pos.getY(), (double) pos.getZ(), itemstack);
}
}
}
} |
package gr.gnostix.freeswitch;
import akka.actor.ActorRef;
import org.freeswitch.esl.client.inbound.Client;
import org.freeswitch.esl.client.inbound.InboundConnectionFailure;
public class EslConnection {
private Client conn = null;
private ActorRef eslMessageRouter;
private String ip;
private int port;
private String password;
public EslConnection(ActorRef eslMessageRouter, String ip, int port, String password) {
this.conn = new Client();
this.eslMessageRouter = eslMessageRouter;
this.ip = ip;
this.port = port;
this.password = password;
}
public ConectionStatus connectEsl() {
try {
conn.connect(ip, 8021, password, 10);
if (conn.canSend() == true)
{
System.out.println("conn.canSend() connected");
//conn.setEventSubscriptions("plain", "all");
conn.setEventSubscriptions( "plain", "CHANNEL_HANGUP_COMPLETE CHANNEL_ANSWER HEARTBEAT" );
conn.addEventListener(new MyEslEventListener(eslMessageRouter));
}
return new ConectionStatus(true, "all good");
//conn.setEventSubscriptions( "plain", "CHANNEL_HANGUP_COMPLETE CHANNEL_CALLSTATE CHANNEL_CREATE CHANNEL_EXECUTE CHANNEL_EXECUTE_COMPLETE CHANNEL_DESTROY" );
} catch (InboundConnectionFailure e) {
System.out.println("
//e.printStackTrace();
return new ConectionStatus(false, e.getMessage());
}
}
public ConectionStatus checkConnection(){
ConectionStatus status;
if (conn.canSend() == true) {
//System.out.println("connected");
status = new ConectionStatus(true, "all good");
} else {
status = connectEsl();
}
return status;
}
public void deinitConnection() {
conn.close();
conn = null;
}
} |
package org.xbill.DNS;
/**
* DNS Name Compression object.
* @see Message
* @see Name
*
* @author Brian Wellington
*/
public class Compression {
private static class Entry {
Name name;
int pos;
Entry next;
}
private static final int TABLE_SIZE = 17;
private Entry [] table;
private boolean verbose = Options.check("verbosecompression");
/**
* Creates a new Compression object.
*/
public
Compression() {
table = new Entry[TABLE_SIZE];
}
/**
* Adds a compression entry mapping a name to a position in a message.
* @param pos The position at which the name is added.
* @param name The name being added to the message.
*/
public void
add(int pos, Name name) {
int row = (name.hashCode() & 0x7FFFFFFF) % TABLE_SIZE;
Entry entry = new Entry();
entry.name = name;
entry.pos = pos;
entry.next = table[row];
table[row] = entry;
if (verbose)
System.err.println("Adding " + name + " at " + pos);
}
/**
* Retrieves the position of the given name, if it has been previously
* included in the message.
* @param name The name to find in the compression table.
* @return The position of the name, or -1 if not found.
*/
public int
get(Name name) {
int row = (name.hashCode() & 0x7FFFFFFF) % TABLE_SIZE;
int pos = -1;
for (Entry entry = table[row]; entry != null; entry = entry.next) {
if (entry.name.equals(name))
pos = entry.pos;
}
if (verbose)
System.err.println("Looking for " + name + ", found " + pos);
return pos;
}
} |
package kodkod.ast.operator;
/**
* Enumerates binary (&&, ||, =>, <=>) and nary (&&, ||) logical operators.
* @specfield op: (int->lone Formula) -> Formula
* @invariant all args: seq Formula, out: Formula | args->out in op => (out.children = args && out.op = this)
*/
public enum FormulaOperator {
/** Logical AND operator. */
AND { public String toString() { return "and"; } }, // [HASLab]
/** Logical OR operator. */
OR { public String toString() { return "or"; } }, // [HASLab]
/** Logical bi-implication operator. */
IFF { public String toString() { return "iff"; } }, // [HASLab]
/** Logical implication operator. */
IMPLIES { public String toString() { return "implies"; } }; // [HASLab]
static final int nary = (1<<AND.ordinal()) | (1<<OR.ordinal());
/**
* Returns true if this is an nary operator.
* @return true if this is an nary operator
*/
public final boolean nary() { return (nary & (1<<ordinal()))!=0; }
} |
package me.exz.omniocular.handler;
import me.exz.omniocular.util.LogHelper;
import me.exz.omniocular.util.NBTHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@SuppressWarnings({"CanBeFinal", "UnusedDeclaration"})
public class JSHandler {
private static final ScriptEngineManager manager = new ScriptEngineManager(null);
private static ScriptEngine engine = manager.getEngineByName("javascript");
public static HashSet<String> scriptSet = new HashSet<String>();
private static List<String> lastTips = new ArrayList<String>();
private static int lastHash;
public static List<String> getBody(Map<Pattern, Node> patternMap, NBTTagCompound n, String id) {
if (n.hashCode() != lastHash) {
lastHash = n.hashCode();
lastTips.clear();
//LogHelper.info(NBTHelper.NBT2json(n));
try {
String json = "var nbt=" + NBTHelper.NBT2json(n) + ";";
JSHandler.engine.eval(json);
} catch (ScriptException e) {
e.printStackTrace();
}
for (Map.Entry<Pattern, Node> entry : patternMap.entrySet()) {
Matcher matcher = entry.getKey().matcher(id);
if (matcher.matches()) {
Element item = (Element) entry.getValue();
// if (item.getElementsByTagName("head").getLength() > 0) {
// Node head = item.getElementsByTagName("head").item(0);
if (item.getElementsByTagName("line").getLength() > 0) {
String tip;
NodeList lines = item.getElementsByTagName("line");
for (int i = 0; i < lines.getLength(); i++) {
Node line = lines.item(i);
tip = "";
if (line.getAttributes().getNamedItem("displayname") != null && !line.getAttributes().getNamedItem("displayname").getTextContent().trim().isEmpty()) {
tip += "\u00A4\u00A4a\u00A4\u00A4b\u00A7f"+line.getAttributes().getNamedItem("displayname").getTextContent();
}
String functionContent = line.getTextContent();
String hash = "S" + NBTHelper.MD5(functionContent);
if (!JSHandler.scriptSet.contains(hash)) {
JSHandler.scriptSet.add(hash);
String script = "function " + hash + "()" + "{" + functionContent + "}";
try {
JSHandler.engine.eval(script);
} catch (Exception e) {
e.printStackTrace();
}
}
Invocable invoke = (Invocable) JSHandler.engine;
try {
tip += String.valueOf(invoke.invokeFunction(hash, ""));
} catch (Exception e) {
e.printStackTrace();
}
lastTips.add(tip);
}
}
}
}
}
return lastTips;
}
public static void initEngine() {
setSpecialChar();
try {
engine.eval("importClass(Packages.me.exz.omniocular.handler.JSHandler);");
engine.eval("function translate(t){return Packages.me.exz.omniocular.handler.JSHandler.translate(t)}");
engine.eval("function name(n){return Packages.me.exz.omniocular.handler.JSHandler.getDisplayName(n.hashCode)}");
} catch (ScriptException e) {
e.printStackTrace();
}
}
public static String translate(String t) {
return StatCollector.translateToLocal(t);
}
private static void setSpecialChar() {
String MCStyle = "\u00A7";
engine.put("BLACK", MCStyle + "0");
engine.put("DBLUE", MCStyle + "1");
engine.put("DGREEN", MCStyle + "2");
engine.put("DAQUA", MCStyle + "3");
engine.put("DRED", MCStyle + "4");
engine.put("DPURPLE", MCStyle + "5");
engine.put("GOLD", MCStyle + "6");
engine.put("GRAY", MCStyle + "7");
engine.put("DGRAY", MCStyle + "8");
engine.put("BLUE", MCStyle + "9");
engine.put("GREEN", MCStyle + "a");
engine.put("AQUA", MCStyle + "b");
engine.put("RED", MCStyle + "c");
engine.put("LPURPLE", MCStyle + "d");
engine.put("YELLOW", MCStyle + "e");
engine.put("WHITE", MCStyle + "f");
engine.put("OBF", MCStyle + "k");
engine.put("BOLD", MCStyle + "l");
engine.put("STRIKE", MCStyle + "m");
engine.put("UNDER", MCStyle + "n");
engine.put("ITALIC", MCStyle + "o");
engine.put("RESET", MCStyle + "r");
String WailaStyle = "\u00A4";
String WailaIcon = "\u00A5";
engine.put("TAB", WailaStyle + WailaStyle + "a");
engine.put("ALIGNRIGHT", WailaStyle + WailaStyle + "b");
engine.put("ALIGNCENTER", WailaStyle + WailaStyle + "c");
engine.put("HEART", WailaStyle + WailaIcon + "a");
engine.put("HHEART", WailaStyle + WailaIcon + "b");
engine.put("EHEART", WailaStyle + WailaIcon + "c");
LogHelper.info("Special Char loaded");
}
public static String getDisplayName(String hashCode) {
try {
NBTTagCompound nc = NBTHelper.mapNBT.get(Integer.valueOf(hashCode));
ItemStack is = ItemStack.loadItemStackFromNBT(nc);
return is.getDisplayName();
} catch (Exception e) {
return "__ERROR__";
}
}
} |
package cgeo.geocaching;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import android.app.Application;
import android.content.Context;
import android.util.Log;
import cgeo.geocaching.utils.CollectionUtils;
public class cgeoapplication extends Application {
private cgData storage = null;
private String action = null;
private Double lastLatitude = null;
private Double lastLongitude = null;
private cgGeo geo = null;
private boolean geoInUse = false;
private cgDirection dir = null;
private boolean dirInUse = false;
final private Map<UUID, cgSearch> searches = new HashMap<UUID, cgSearch>(); // information about searches
final private Map<String, cgCache> cachesCache = new HashMap<String, cgCache>(); // caching caches into memory
public boolean firstRun = true; // c:geo is just launched
public boolean warnedLanguage = false; // user was warned about different language settings on geocaching.com
private boolean databaseCleaned = false; // database was cleaned
public cgeoapplication() {
if (storage == null) {
storage = new cgData(this);
}
}
@Override
public void onLowMemory() {
Log.i(cgSettings.tag, "Cleaning applications cache.");
cachesCache.clear();
}
@Override
public void onTerminate() {
Log.d(cgSettings.tag, "Terminating c:geo...");
if (geo != null) {
geo.closeGeo();
geo = null;
}
if (dir != null) {
dir.closeDir();
dir = null;
}
if (storage != null) {
storage.clean();
storage.closeDb();
storage = null;
}
super.onTerminate();
}
public String backupDatabase() {
return storage.backupDatabase();
}
public static File isRestoreFile() {
return cgData.isRestoreFile();
}
public boolean restoreDatabase() {
return storage.restoreDatabase();
}
public void cleanGeo() {
if (geo != null) {
geo.closeGeo();
geo = null;
}
}
public void cleanDir() {
if (dir != null) {
dir.closeDir();
dir = null;
}
}
public boolean storageStatus() {
return storage.status();
}
public cgGeo startGeo(Context context, cgUpdateLoc geoUpdate, cgBase base, cgSettings settings, int time, int distance) {
if (geo == null) {
geo = new cgGeo(context, this, geoUpdate, base, settings, time, distance);
geo.initGeo();
Log.i(cgSettings.tag, "Location service started");
}
geo.replaceUpdate(geoUpdate);
geoInUse = true;
return geo;
}
public cgGeo removeGeo() {
if (geo != null) {
geo.replaceUpdate(null);
}
geoInUse = false;
(new removeGeoThread()).start();
return null;
}
private class removeGeoThread extends Thread {
@Override
public void run() {
try {
sleep(2500);
} catch (Exception e) {
// nothing
}
if (geoInUse == false && geo != null) {
geo.closeGeo();
geo = null;
Log.i(cgSettings.tag, "Location service stopped");
}
}
}
public cgDirection startDir(Context context, cgUpdateDir dirUpdate) {
if (dir == null) {
dir = new cgDirection(context, dirUpdate);
dir.initDir();
Log.i(cgSettings.tag, "Direction service started");
}
dir.replaceUpdate(dirUpdate);
dirInUse = true;
return dir;
}
public cgDirection removeDir() {
if (dir != null) {
dir.replaceUpdate(null);
}
dirInUse = false;
(new removeDirThread()).start();
return null;
}
private class removeDirThread extends Thread {
@Override
public void run() {
try {
sleep(2500);
} catch (Exception e) {
// nothing
}
if (dirInUse == false && dir != null) {
dir.closeDir();
dir = null;
Log.i(cgSettings.tag, "Direction service stopped");
}
}
}
public void cleanDatabase(boolean more) {
if (databaseCleaned) {
return;
}
if (storage == null) {
storage = new cgData(this);
}
storage.clean(more);
databaseCleaned = true;
}
public Boolean isThere(String geocode, String guid, boolean detailed, boolean checkTime) {
if (storage == null) {
storage = new cgData(this);
}
return storage.isThere(geocode, guid, detailed, checkTime);
}
public Boolean isOffline(String geocode, String guid) {
if (storage == null) {
storage = new cgData(this);
}
return storage.isOffline(geocode, guid);
}
public String getGeocode(String guid) {
if (storage == null) {
storage = new cgData(this);
}
return storage.getGeocodeForGuid(guid);
}
public String getCacheid(String geocode) {
if (storage == null) {
storage = new cgData(this);
}
return storage.getCacheidForGeocode(geocode);
}
public String getError(final UUID searchId) {
if (searchId == null || searches.containsKey(searchId) == false) {
return null;
}
return searches.get(searchId).error;
}
public boolean setError(final UUID searchId, String error) {
if (searchId == null || searches.containsKey(searchId) == false) {
return false;
}
searches.get(searchId).error = error;
return true;
}
public String getUrl(final UUID searchId) {
if (searchId == null || searches.containsKey(searchId) == false) {
return null;
}
return searches.get(searchId).url;
}
public boolean setUrl(final UUID searchId, String url) {
if (searchId == null || searches.containsKey(searchId) == false) {
return false;
}
searches.get(searchId).url = url;
return true;
}
public String[] getViewstates(final UUID searchId) {
if (searchId == null || searches.containsKey(searchId) == false) {
return null;
}
return searches.get(searchId).viewstates;
}
public boolean setViewstates(final UUID searchId, String[] viewstates) {
if (ArrayUtils.isEmpty(viewstates)) {
return false;
}
if (searchId == null || searches.containsKey(searchId) == false) {
return false;
}
searches.get(searchId).viewstates = viewstates;
return true;
}
public Integer getTotal(final UUID searchId) {
if (searchId == null || searches.containsKey(searchId) == false) {
return null;
}
return searches.get(searchId).totalCnt;
}
public Integer getCount(final UUID searchId) {
if (searchId == null || searches.containsKey(searchId) == false) {
return 0;
}
return searches.get(searchId).getCount();
}
public Integer getNotOfflineCount(final UUID searchId) {
if (searchId == null || searches.containsKey(searchId) == false) {
return 0;
}
int count = 0;
List<String> geocodes = searches.get(searchId).getGeocodes();
if (geocodes != null) {
for (String geocode : geocodes) {
if (isOffline(geocode, null) == false) {
count++;
}
}
}
return count;
}
public cgCache getCacheByGeocode(String geocode) {
return getCacheByGeocode(geocode, false, true, false, false, false, false);
}
public cgCache getCacheByGeocode(String geocode, boolean loadA, boolean loadW, boolean loadS, boolean loadL, boolean loadI, boolean loadO) {
if (StringUtils.isBlank(geocode)) {
return null;
}
cgCache cache = null;
if (cachesCache.containsKey(geocode)) {
cache = cachesCache.get(geocode);
} else {
if (storage == null) {
storage = new cgData(this);
}
cache = storage.loadCache(geocode, null, loadA, loadW, loadS, loadL, loadI, loadO);
if (cache != null && cache.detailed && loadA && loadW && loadS && loadL && loadI) {
putCacheInCache(cache);
}
}
return cache;
}
public cgTrackable getTrackableByGeocode(String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
cgTrackable trackable = null;
trackable = storage.loadTrackable(geocode);
return trackable;
}
public void removeCacheFromCache(String geocode) {
if (geocode != null && cachesCache.containsKey(geocode)) {
cachesCache.remove(geocode);
}
}
public void putCacheInCache(cgCache cache) {
if (cache == null || cache.geocode == null) {
return;
}
if (cachesCache.containsKey(cache.geocode)) {
cachesCache.remove(cache.geocode);
}
cachesCache.put(cache.geocode, cache);
}
public String[] geocodesInCache() {
if (storage == null) {
storage = new cgData(this);
}
return storage.allDetailedThere();
}
public cgWaypoint getWaypointById(Integer id) {
if (id == null || id == 0) {
return null;
}
if (storage == null) {
storage = new cgData(this);
}
return storage.loadWaypoint(id);
}
public List<Object> getBounds(String geocode) {
if (geocode == null) {
return null;
}
List<String> geocodeList = new ArrayList<String>();
geocodeList.add(geocode);
return getBounds(geocodeList);
}
public List<Object> getBounds(final UUID searchId) {
if (searchId == null || searches.containsKey(searchId) == false) {
return null;
}
if (storage == null) {
storage = new cgData(this);
}
final cgSearch search = searches.get(searchId);
final List<String> geocodeList = search.getGeocodes();
return getBounds(geocodeList);
}
public List<Object> getBounds(List<String> geocodes) {
if (geocodes == null || geocodes.isEmpty()) {
return null;
}
if (storage == null) {
storage = new cgData(this);
}
return storage.getBounds(geocodes.toArray());
}
public cgCache getCache(final UUID searchId) {
if (searchId == null || searches.containsKey(searchId) == false) {
return null;
}
cgSearch search = searches.get(searchId);
List<String> geocodeList = search.getGeocodes();
return getCacheByGeocode(geocodeList.get(0), true, true, true, true, true, true);
}
public List<cgCache> getCaches(final UUID searchId) {
return getCaches(searchId, null, null, null, null, false, true, false, false, false, true);
}
public List<cgCache> getCaches(final UUID searchId, boolean loadA, boolean loadW, boolean loadS, boolean loadL, boolean loadI, boolean loadO) {
return getCaches(searchId, null, null, null, null, loadA, loadW, loadS, loadL, loadI, loadO);
}
public List<cgCache> getCaches(final UUID searchId, Long centerLat, Long centerLon, Long spanLat, Long spanLon) {
return getCaches(searchId, centerLat, centerLon, spanLat, spanLon, false, true, false, false, false, true);
}
public List<cgCache> getCaches(final UUID searchId, Long centerLat, Long centerLon, Long spanLat, Long spanLon, boolean loadA, boolean loadW, boolean loadS, boolean loadL, boolean loadI, boolean loadO) {
if (searchId == null || searches.containsKey(searchId) == false) {
List<cgCache> cachesOut = new ArrayList<cgCache>();
final List<cgCache> cachesPre = storage.loadCaches(null , null, centerLat, centerLon, spanLat, spanLon, loadA, loadW, loadS, loadL, loadI, loadO);
if (cachesPre != null) {
cachesOut.addAll(cachesPre);
}
return cachesOut;
}
List<cgCache> cachesOut = new ArrayList<cgCache>();
cgSearch search = searches.get(searchId);
List<String> geocodeList = search.getGeocodes();
if (storage == null) {
storage = new cgData(this);
}
// The list of geocodes is sufficient. more parameters generate an overly complex select.
final List<cgCache> cachesPre = storage.loadCaches(geocodeList.toArray(), null, null, null, null, null, loadA, loadW, loadS, loadL, loadI, loadO);
if (cachesPre != null) {
cachesOut.addAll(cachesPre);
}
return cachesOut;
}
public cgSearch getBatchOfStoredCaches(boolean detailedOnly, Double latitude, Double longitude, String cachetype, int list) {
if (storage == null) {
storage = new cgData(this);
}
cgSearch search = new cgSearch();
List<String> geocodes = storage.loadBatchOfStoredGeocodes(detailedOnly, latitude, longitude, cachetype, list);
if (geocodes != null && geocodes.isEmpty() == false) {
for (String gccode : geocodes) {
search.addGeocode(gccode);
}
}
searches.put(search.getCurrentId(), search);
return search;
}
public List<cgDestination> getHistoryOfSearchedLocations() {
if (storage == null) {
storage = new cgData(this);
}
return storage.loadHistoryOfSearchedLocations();
}
public cgSearch getHistoryOfCaches(boolean detailedOnly, String cachetype) {
if (storage == null) {
storage = new cgData(this);
}
cgSearch search = new cgSearch();
List<String> geocodes = storage.loadBatchOfHistoricGeocodes(detailedOnly, cachetype);
if (geocodes != null && geocodes.isEmpty() == false) {
for (String gccode : geocodes) {
search.addGeocode(gccode);
}
}
searches.put(search.getCurrentId(), search);
return search;
}
public UUID getCachedInViewport(Long centerLat, Long centerLon, Long spanLat, Long spanLon, String cachetype) {
if (storage == null) {
storage = new cgData(this);
}
cgSearch search = new cgSearch();
List<String> geocodes = storage.getCachedInViewport(centerLat, centerLon, spanLat, spanLon, cachetype);
if (geocodes != null && geocodes.isEmpty() == false) {
for (String gccode : geocodes) {
search.addGeocode(gccode);
}
}
searches.put(search.getCurrentId(), search);
return search.getCurrentId();
}
public UUID getStoredInViewport(Long centerLat, Long centerLon, Long spanLat, Long spanLon, String cachetype) {
if (storage == null) {
storage = new cgData(this);
}
cgSearch search = new cgSearch();
List<String> geocodes = storage.getStoredInViewport(centerLat, centerLon, spanLat, spanLon, cachetype);
if (geocodes != null && geocodes.isEmpty() == false) {
for (String gccode : geocodes) {
search.addGeocode(gccode);
}
}
searches.put(search.getCurrentId(), search);
return search.getCurrentId();
}
public UUID getOfflineAll(String cachetype) {
if (storage == null) {
storage = new cgData(this);
}
cgSearch search = new cgSearch();
List<String> geocodes = storage.getOfflineAll(cachetype);
if (geocodes != null && geocodes.isEmpty() == false) {
for (String gccode : geocodes) {
search.addGeocode(gccode);
}
}
searches.put(search.getCurrentId(), search);
return search.getCurrentId();
}
public int getAllStoredCachesCount(boolean detailedOnly, String cachetype, Integer list) {
if (storage == null) {
storage = new cgData(this);
}
return storage.getAllStoredCachesCount(detailedOnly, cachetype, list);
}
public int getAllHistoricCachesCount(boolean detailedOnly, String cachetype) {
if (storage == null) {
storage = new cgData(this);
}
return storage.getAllHistoricCachesCount(detailedOnly, cachetype);
}
public void markStored(String geocode, int listId) {
if (storage == null) {
storage = new cgData(this);
}
storage.markStored(geocode, listId);
}
public boolean markDropped(String geocode) {
if (storage == null) {
storage = new cgData(this);
}
return storage.markDropped(geocode);
}
public boolean markFound(String geocode) {
if (storage == null) {
storage = new cgData(this);
}
return storage.markFound(geocode);
}
public boolean clearSearchedDestinations() {
if (storage == null) {
storage = new cgData(this);
}
return storage.clearSearchedDestinations();
}
public boolean saveSearchedDestination(cgDestination destination) {
if (storage == null) {
storage = new cgData(this);
}
return storage.saveSearchedDestination(destination);
}
public boolean saveWaypoints(String geocode, List<cgWaypoint> waypoints, boolean drop) {
if (storage == null) {
storage = new cgData(this);
}
return storage.saveWaypoints(geocode, waypoints, drop);
}
public boolean saveOwnWaypoint(int id, String geocode, cgWaypoint waypoint) {
if (storage == null) {
storage = new cgData(this);
}
return storage.saveOwnWaypoint(id, geocode, waypoint);
}
public boolean deleteWaypoint(int id) {
if (storage == null) {
storage = new cgData(this);
}
return storage.deleteWaypoint(id);
}
public boolean saveTrackable(cgTrackable trackable) {
if (storage == null) {
storage = new cgData(this);
}
final List<cgTrackable> list = new ArrayList<cgTrackable>();
list.add(trackable);
return storage.saveInventory("---", list);
}
public void addGeocode(final UUID searchId, String geocode) {
if (this.searches.containsKey(searchId) == false || StringUtils.isBlank(geocode)) {
return;
}
this.searches.get(searchId).addGeocode(geocode);
}
public UUID addSearch(final UUID searchId, List<cgCache> cacheList, Boolean newItem, int reason) {
if (this.searches.containsKey(searchId) == false) {
return null;
}
cgSearch search = this.searches.get(searchId);
return addSearch(search, cacheList, newItem, reason);
}
public UUID addSearch(final cgSearch search, final List<cgCache> cacheList, final boolean newItem, final int reason) {
if (CollectionUtils.isEmpty(cacheList)) {
return null;
}
final UUID searchId = search.getCurrentId();
searches.put(searchId, search);
if (storage == null) {
storage = new cgData(this);
}
if (newItem) {
// save only newly downloaded data
for (cgCache cache : cacheList) {
cache.reason = reason;
storeWithMerge(cache, false);
}
}
return searchId;
}
public boolean addCacheToSearch(cgSearch search, cgCache cache) {
if (search == null || cache == null) {
return false;
}
final UUID searchId = search.getCurrentId();
if (searches.containsKey(searchId) == false) {
searches.put(searchId, search);
}
final boolean status = storeWithMerge(cache, cache.reason >= 1);
if (status) {
search.addGeocode(cache.geocode);
}
return status;
}
/**
* Checks if Cache is already in Database and if so does a merge.
* @param cache The cache to be saved
* @param forceSave override the check and persist the new state.
* @return
*/
private boolean storeWithMerge(cgCache cache, boolean forceSave) {
boolean status;
cgCache oldCache = null;
if (forceSave || (oldCache = storage.loadCache(cache.geocode, cache.guid, false, true, true, true, true, true)) !=null ) { // if for offline, do not merge
status = storage.saveCache(cache);
} else {
cgCache mergedCache = cache.merge(storage,oldCache);
status = storage.saveCache(mergedCache);
}
return status;
}
public void dropStored(int listId) {
if (storage == null) {
storage = new cgData(this);
}
storage.dropStored(listId);
}
public List<cgTrackable> loadInventory(String geocode) {
return storage.loadInventory(geocode);
}
public Map<Integer,Integer> loadLogCounts(String geocode) {
return storage.loadLogCounts(geocode);
}
public List<cgImage> loadSpoilers(String geocode) {
return storage.loadSpoilers(geocode);
}
public cgWaypoint loadWaypoint(int id) {
return storage.loadWaypoint(id);
}
public void setAction(String act) {
action = act;
}
public String getAction() {
if (action == null) {
return "";
}
return action;
}
public boolean addLog(String geocode, cgLog log) {
if (StringUtils.isBlank(geocode)) {
return false;
}
if (log == null) {
return false;
}
List<cgLog> list = new ArrayList<cgLog>();
list.add(log);
return storage.saveLogs(geocode, list, false);
}
public void setLastLoc(Double lat, Double lon) {
lastLatitude = lat;
lastLongitude = lon;
}
public Double getLastLat() {
return lastLatitude;
}
public Double getLastLon() {
return lastLongitude;
}
public boolean saveLogOffline(String geocode, Date date, int logtype, String log) {
return storage.saveLogOffline(geocode, date, logtype, log);
}
public cgLog loadLogOffline(String geocode) {
return storage.loadLogOffline(geocode);
}
public void clearLogOffline(String geocode) {
storage.clearLogOffline(geocode);
}
public void saveVisitDate(String geocode) {
storage.saveVisitDate(geocode);
}
public void clearVisitDate(String geocode) {
storage.clearVisitDate(geocode);
}
public List<cgList> getLists() {
return storage.getLists(getResources());
}
public cgList getList(int id) {
return storage.getList(id, getResources());
}
public int createList(String title) {
return storage.createList(title);
}
public boolean removeList(int id) {
return storage.removeList(id);
}
public boolean removeSearchedDestinations(cgDestination destination) {
return storage.removeSearchedDestination(destination);
}
public void moveToList(String geocode, int listId) {
storage.moveToList(geocode, listId);
}
} |
package mytown.protection;
import com.esotericsoftware.reflectasm.FieldAccess;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import mytown.MyTown;
import mytown.entities.Resident;
import mytown.entities.Town;
import mytown.entities.flag.FlagType;
import mytown.proxies.DatasourceProxy;
import mytown.proxies.LocalizationProxy;
import mytown.util.BlockPos;
import mytown.util.ChunkPos;
import mytown.util.Formatter;
import mytown.util.Utils;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import java.lang.reflect.Field;
import java.util.List;
public class BotaniaProtection extends Protection {
private Class<? extends Item> clsTerraPick;
private Class<? extends Item> clsShardLaputa;
private Class<? extends Item> clsTerraFirmaRod;
private Class<? extends Item> clsHellsRod;
@SuppressWarnings("unchecked")
public BotaniaProtection() {
isHandlingEvents = true;
try {
clsTerraPick = (Class<? extends Item>) Class.forName("vazkii.botania.common.item.equipment.tool.ItemTerraPick");
clsShardLaputa = (Class<? extends Item>) Class.forName("vazkii.botania.common.item.ItemLaputaShard");
clsTerraFirmaRod = (Class<? extends Item>) Class.forName("vazkii.botania.common.item.rod.ItemTerraformRod");
clsHellsRod = (Class<? extends Item>) Class.forName("vazkii.botania.common.item.rod.ItemFireRod");
} catch (Exception e) {
MyTown.instance.log.error("Failed to load Botania classes!");
}
}
@SuppressWarnings("unchecked")
@SubscribeEvent
public void onPlayerBreaks(PlayerInteractEvent ev) {
try {
if (ev.action == PlayerInteractEvent.Action.LEFT_CLICK_BLOCK) {
if (ev.entityPlayer.getHeldItem() != null && clsTerraPick.isAssignableFrom(ev.entityPlayer.getHeldItem().getItem().getClass())) {
boolean isEnabled = ev.entityPlayer.getHeldItem().getTagCompound().getBoolean("enabled");
// Basically checking if pick is enabled for area mode
if (isEnabled) {
Resident res = DatasourceProxy.getDatasource().getOrMakeResident(ev.entityPlayer);
ForgeDirection direction = ForgeDirection.getOrientation(ev.face);
boolean doX = direction.offsetX == 0;
boolean doZ = direction.offsetZ == 0;
int level = getLevel(ev.entityPlayer.getHeldItem());
int range = Math.max(0, level - 1);
// DEV:
//MyTown.instance.log.info("Got range: " + range);
List<Town> towns = Utils.getTownsInRange(ev.world.provider.dimensionId, ev.x, ev.z, doX ? range : 0, doZ ? range : 0);
for (Town town : towns) {
boolean breakFlag = (Boolean) town.getValue(FlagType.modifyBlocks);
if (!breakFlag && town.checkPermission(res, FlagType.modifyBlocks)) {
ev.setCanceled(true);
res.sendMessage(FlagType.modifyBlocks.getLocalizedProtectionDenial());
return;
}
}
}
}
}
} catch (Exception e) {
MyTown.instance.log.error("Failed to call methods or some other nasty error!");
}
}
@SuppressWarnings("unchecked")
@Override
public boolean checkItemUsage(ItemStack itemStack, Resident res, BlockPos bp) {
if(clsShardLaputa.isAssignableFrom(itemStack.getItem().getClass())) {
int range = 14 + itemStack.getItemDamage();
//MyTown.instance.log.info("Got range: " + range);
List<ChunkPos> chunks = Utils.getChunksInBox(bp.x - range, bp.z - range, bp.x + range, bp.z + range);
for (ChunkPos chunk : chunks) {
Town town = Utils.getTownAtPosition(bp.dim, chunk.getX(), chunk.getZ());
if (town != null) {
if (!town.checkPermission(res, FlagType.modifyBlocks)) {
res.protectionDenial(FlagType.modifyBlocks.getLocalizedProtectionDenial(), Formatter.formatOwnerToString(town.getMayor()));
return true;
}
}
}
} else if(clsTerraFirmaRod.isAssignableFrom(itemStack.getItem().getClass())) {
int range = 16;
List<ChunkPos> chunks = Utils.getChunksInBox((int)res.getPlayer().posX - range, (int)res.getPlayer().posZ - range, (int)res.getPlayer().posX + range, (int)res.getPlayer().posZ + range);
for(ChunkPos chunk : chunks) {
Town town = Utils.getTownAtPosition(bp.dim, chunk.getX(), chunk.getZ());
if(town != null) {
if(!town.checkPermission(res, FlagType.modifyBlocks)) {
res.protectionDenial(FlagType.modifyBlocks.getLocalizedProtectionDenial(), Formatter.formatOwnerToString(town.getMayor()));
return true;
}
}
}
} else if(clsHellsRod.isAssignableFrom(itemStack.getItem().getClass())) {
int radius = 5;
float posX = bp.x + 0.5F, posY = bp.y + 1.0F, posZ = bp.z + 0.5F;
AxisAlignedBB boundingBox = AxisAlignedBB.getBoundingBox(posX, posY, posZ, posX, posY, posZ).expand(radius, radius, radius);
List<EntityLivingBase> entities = res.getPlayer().getEntityWorld().getEntitiesWithinAABB(EntityLivingBase.class, boundingBox);
for(EntityLivingBase entity : entities) {
//MyTown.instance.log.info("Got entity: " + entity.toString());
Town town = Utils.getTownAtPosition(entity.dimension, (int)entity.posX >> 4, (int)entity.posZ >> 4);
if(town != null) {
if (!town.checkPermission(res, FlagType.attackEntities, entity.dimension, (int) entity.posX, (int) entity.posY, (int) entity.posZ)) {
//MyTown.instance.log.info("Checking entity.");
for (Protection prot : Protections.instance.protections.values()) {
if (prot.protectedEntities.contains(entity.getClass())) {
res.protectionDenial(LocalizationProxy.getLocalization().getLocalization("mytown.protection.vanilla.animalCruelty"), Formatter.formatOwnersToString(town.getOwnersAtPosition(entity.dimension, (int) entity.posX, (int) entity.posY, (int) entity.posZ)));
return true;
}
}
}
}
}
}
return false;
}
/**
* @param stack
* @return
* @author Vazkii
*/
public int getLevel(ItemStack stack) {
int[] LEVELS = new int[]{
0, 10000, 1000000, 10000000, 100000000, 1000000000
};
int mana = stack.getTagCompound().getInteger("mana");
for (int i = LEVELS.length - 1; i > 0; i
if (mana >= LEVELS[i])
return i;
return 0;
}
} |
package cgeo.geocaching;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.geopoint.GeopointFormatter;
public class cgeowaypointadd extends AbstractActivity {
private String geocode = null;
private int id = -1;
private cgGeo geo = null;
private cgUpdateLoc geoUpdate = new update();
private ProgressDialog waitDialog = null;
private cgWaypoint waypoint = null;
private String type = "own";
private String prefix = "OWN";
private String lookup = "
/**
* number of waypoints that the corresponding cache has until now
*/
private int wpCount = 0;
private Handler loadWaypointHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
if (waypoint == null) {
if (waitDialog != null) {
waitDialog.dismiss();
waitDialog = null;
}
id = -1;
} else {
geocode = waypoint.geocode;
type = waypoint.type;
prefix = waypoint.prefix;
lookup = waypoint.lookup;
app.setAction(geocode);
((Button) findViewById(R.id.buttonLatitude)).setText(cgBase.formatLatitude(waypoint.latitude, true));
((Button) findViewById(R.id.buttonLongitude)).setText(cgBase.formatLongitude(waypoint.longitude, true));
((EditText) findViewById(R.id.name)).setText(Html.fromHtml(waypoint.name.trim()).toString());
((EditText) findViewById(R.id.note)).setText(Html.fromHtml(waypoint.note.trim()).toString());
if (waitDialog != null) {
waitDialog.dismiss();
waitDialog = null;
}
}
} catch (Exception e) {
if (waitDialog != null) {
waitDialog.dismiss();
waitDialog = null;
}
Log.e(cgSettings.tag, "cgeowaypointadd.loadWaypointHandler: " + e.toString());
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme();
setContentView(R.layout.waypoint_new);
setTitle("waypoint");
if (geo == null) {
geo = app.startGeo(this, geoUpdate, base, settings, 0, 0);
}
// get parameters
Bundle extras = getIntent().getExtras();
if (extras != null) {
geocode = extras.getString("geocode");
wpCount = extras.getInt("count", 0);
id = extras.getInt("waypoint");
}
if (StringUtils.isBlank(geocode) && id <= 0) {
showToast(res.getString(R.string.err_waypoint_cache_unknown));
finish();
return;
}
if (id <= 0) {
setTitle(res.getString(R.string.waypoint_add_title));
} else {
setTitle(res.getString(R.string.waypoint_edit_title));
}
if (geocode != null) {
app.setAction(geocode);
}
Button buttonLat = (Button) findViewById(R.id.buttonLatitude);
buttonLat.setOnClickListener(new coordDialogListener());
Button buttonLon = (Button) findViewById(R.id.buttonLongitude);
buttonLon.setOnClickListener(new coordDialogListener());
Button addWaypoint = (Button) findViewById(R.id.add_waypoint);
addWaypoint.setOnClickListener(new coordsListener());
List<String> wayPointNames = new ArrayList<String>(cgBase.waypointTypes.values());
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.name);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, wayPointNames);
textView.setAdapter(adapter);
if (id > 0) {
waitDialog = ProgressDialog.show(this, null, res.getString(R.string.waypoint_loading), true);
waitDialog.setCancelable(true);
(new loadWaypoint()).start();
}
}
@Override
public void onResume() {
super.onResume();
settings.load();
if (geo == null) {
geo = app.startGeo(this, geoUpdate, base, settings, 0, 0);
}
if (id > 0) {
if (waitDialog == null) {
waitDialog = ProgressDialog.show(this, null, res.getString(R.string.waypoint_loading), true);
waitDialog.setCancelable(true);
(new loadWaypoint()).start();
}
}
}
@Override
public void onDestroy() {
if (geo != null) {
geo = app.removeGeo();
}
super.onDestroy();
}
@Override
public void onStop() {
if (geo != null) {
geo = app.removeGeo();
}
super.onStop();
}
@Override
public void onPause() {
if (geo != null) {
geo = app.removeGeo();
}
super.onPause();
}
private class update extends cgUpdateLoc {
@Override
public void updateLoc(cgGeo geo) {
if (geo == null || geo.latitudeNow == null || geo.longitudeNow == null) {
return;
}
try {
Button bLat = (Button) findViewById(R.id.buttonLatitude);
Button bLon = (Button) findViewById(R.id.buttonLongitude);
bLat.setHint(cgBase.formatLatitude(geo.latitudeNow, false));
bLon.setHint(cgBase.formatLongitude(geo.longitudeNow, false));
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to update location.");
}
}
}
private class loadWaypoint extends Thread {
@Override
public void run() {
try {
waypoint = app.loadWaypoint(id);
loadWaypointHandler.sendMessage(new Message());
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeowaypoint.loadWaypoint.run: " + e.toString());
}
}
}
private class coordDialogListener implements View.OnClickListener {
public void onClick(View arg0) {
Geopoint gp = null;
if (waypoint != null && waypoint.latitude != null && waypoint.longitude != null)
gp = new Geopoint(waypoint.latitude, waypoint.longitude);
cgeocoords coordsDialog = new cgeocoords(cgeowaypointadd.this, settings, gp, geo);
coordsDialog.setCancelable(true);
coordsDialog.setOnCoordinateUpdate(new cgeocoords.CoordinateUpdate() {
@Override
public void update(Geopoint gp) {
((Button) findViewById(R.id.buttonLatitude)).setText(gp.format(GeopointFormatter.Format.LAT_DECMINUTE));
((Button) findViewById(R.id.buttonLongitude)).setText(gp.format(GeopointFormatter.Format.LON_DECMINUTE));
if (waypoint != null) {
waypoint.latitude = gp.getLatitude();
waypoint.longitude = gp.getLongitude();
}
}
});
coordsDialog.show();
}
}
private class coordsListener implements View.OnClickListener {
public void onClick(View arg0) {
List<Double> coords = new ArrayList<Double>();
Double latitude = null;
Double longitude = null;
final String bearingText = ((EditText) findViewById(R.id.bearing)).getText().toString();
final String distanceText = ((EditText) findViewById(R.id.distance)).getText().toString();
final String latText = ((Button) findViewById(R.id.buttonLatitude)).getText().toString();
final String lonText = ((Button) findViewById(R.id.buttonLongitude)).getText().toString();
if (StringUtils.isNotBlank(bearingText) && StringUtils.isNotBlank(distanceText)
&& StringUtils.isNotBlank(latText) && StringUtils.isNotBlank(lonText)) {
helpDialog(res.getString(R.string.err_point_no_position_given_title), res.getString(R.string.err_point_no_position_given));
return;
}
if (StringUtils.isNotBlank(latText) && StringUtils.isNotBlank(lonText)) {
// latitude & longitude
Map<String, Object> latParsed = cgBase.parseCoordinate(latText, "lat");
Map<String, Object> lonParsed = cgBase.parseCoordinate(lonText, "lon");
if (latParsed == null || latParsed.get("coordinate") == null || latParsed.get("string") == null) {
showToast(res.getString(R.string.err_parse_lat));
return;
}
if (lonParsed == null || lonParsed.get("coordinate") == null || lonParsed.get("string") == null) {
showToast(res.getString(R.string.err_parse_lon));
return;
}
latitude = (Double) latParsed.get("coordinate");
longitude = (Double) lonParsed.get("coordinate");
} else {
if (geo == null || geo.latitudeNow == null || geo.longitudeNow == null) {
showToast(res.getString(R.string.err_point_curr_position_unavailable));
return;
}
latitude = geo.latitudeNow;
longitude = geo.longitudeNow;
}
if (StringUtils.isNotBlank(bearingText) && StringUtils.isNotBlank(distanceText)) {
// bearing & distance
Double bearing = null;
try {
bearing = new Double(bearingText);
} catch (Exception e) {
// probably not a number
}
if (bearing == null) {
helpDialog(res.getString(R.string.err_point_bear_and_dist_title), res.getString(R.string.err_point_bear_and_dist));
return;
}
Double distance = null;
final Pattern patternA = Pattern.compile("^([0-9\\.\\,]+)[ ]*m$", Pattern.CASE_INSENSITIVE);
final Pattern patternB = Pattern.compile("^([0-9\\.\\,]+)[ ]*km$", Pattern.CASE_INSENSITIVE);
final Pattern patternC = Pattern.compile("^([0-9\\.\\,]+)[ ]*ft$", Pattern.CASE_INSENSITIVE); // ft - 0.3048m
final Pattern patternD = Pattern.compile("^([0-9\\.\\,]+)[ ]*yd$", Pattern.CASE_INSENSITIVE); // yd - 0.9144m
final Pattern patternE = Pattern.compile("^([0-9\\.\\,]+)[ ]*mi$", Pattern.CASE_INSENSITIVE); // mi - 1609.344m
Matcher matcherA = patternA.matcher(distanceText);
Matcher matcherB = patternB.matcher(distanceText);
Matcher matcherC = patternC.matcher(distanceText);
Matcher matcherD = patternD.matcher(distanceText);
Matcher matcherE = patternE.matcher(distanceText);
if (matcherA.find() && matcherA.groupCount() > 0) {
distance = (new Double(matcherA.group(1))) * 0.001;
} else if (matcherB.find() && matcherB.groupCount() > 0) {
distance = new Double(matcherB.group(1));
} else if (matcherC.find() && matcherC.groupCount() > 0) {
distance = (new Double(matcherC.group(1))) * 0.0003048;
} else if (matcherD.find() && matcherD.groupCount() > 0) {
distance = (new Double(matcherD.group(1))) * 0.0009144;
} else if (matcherE.find() && matcherE.groupCount() > 0) {
distance = (new Double(matcherE.group(1))) * 1.609344;
} else {
try {
if (settings.units == cgSettings.unitsImperial) {
distance = (new Double(distanceText)) * 1.609344; // considering it miles
} else {
distance = (new Double(distanceText)) * 0.001; // considering it meters
}
} catch (Exception e) {
// probably not a number
}
}
if (distance == null) {
showToast(res.getString(R.string.err_parse_dist));
return;
}
Double latParsed = null;
Double lonParsed = null;
Map<String, Double> coordsDst = cgBase.getRadialDistance(latitude, longitude, bearing, distance);
latParsed = coordsDst.get("latitude");
lonParsed = coordsDst.get("longitude");
if (latParsed == null || lonParsed == null) {
showToast(res.getString(R.string.err_point_location_error));
return;
}
coords.add(0, (Double) latParsed);
coords.add(1, (Double) lonParsed);
} else if (latitude != null && longitude != null) {
coords.add(0, latitude);
coords.add(1, longitude);
} else {
showToast(res.getString(R.string.err_point_location_error));
return;
}
String name = ((EditText) findViewById(R.id.name)).getText().toString().trim();
// if no name is given, just give the waypoint its number as name
if (name.length() == 0) {
name = res.getString(R.string.waypoint) + " " + String.valueOf(wpCount + 1);
}
final String note = ((EditText) findViewById(R.id.note)).getText().toString().trim();
final cgWaypoint waypoint = new cgWaypoint();
waypoint.type = type;
waypoint.geocode = geocode;
waypoint.prefix = prefix;
waypoint.lookup = lookup;
waypoint.name = name;
waypoint.latitude = coords.get(0);
waypoint.longitude = coords.get(1);
waypoint.latitudeString = cgBase.formatLatitude(coords.get(0), true);
waypoint.longitudeString = cgBase.formatLongitude(coords.get(1), true);
waypoint.note = note;
if (app.saveOwnWaypoint(id, geocode, waypoint)) {
app.removeCacheFromCache(geocode);
finish();
return;
} else {
showToast(res.getString(R.string.err_waypoint_add_failed));
}
}
}
public void goManual(View view) {
if (id >= 0) {
ActivityMixin.goManual(this, "c:geo-waypoint-edit");
} else {
ActivityMixin.goManual(this, "c:geo-waypoint-new");
}
}
} |
package org.jfree.chart.renderer.category;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.DataUtilities;
import org.jfree.data.Range;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
/**
* Renders stacked bars with 3D-effect, for use with the
* {@link org.jfree.chart.plot.CategoryPlot} class.
*/
public class StackedBarRenderer3D extends BarRenderer3D
implements Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -5832945916493247123L;
/** A flag that controls whether the bars display values or percentages. */
private boolean renderAsPercentages;
/**
* A flag that controls whether or not zero values are drawn by the
* renderer.
*
* @since 1.2.0
*/
private boolean ignoreZeroValues;
/**
* Creates a new renderer with no tool tip generator and no URL generator.
* <P>
* The defaults (no tool tip or URL generators) have been chosen to
* minimise the processing required to generate a default chart. If you
* require tool tips or URLs, then you can easily add the required
* generators.
*/
public StackedBarRenderer3D() {
this(false);
}
/**
* Constructs a new renderer with the specified '3D effect'.
*
* @param xOffset the x-offset for the 3D effect.
* @param yOffset the y-offset for the 3D effect.
*/
public StackedBarRenderer3D(double xOffset, double yOffset) {
super(xOffset, yOffset);
}
/**
* Creates a new renderer.
*
* @param renderAsPercentages a flag that controls whether the data values
* are rendered as percentages.
*
* @since 1.0.2
*/
public StackedBarRenderer3D(boolean renderAsPercentages) {
super();
this.renderAsPercentages = renderAsPercentages;
}
/**
* Constructs a new renderer with the specified '3D effect'.
*
* @param xOffset the x-offset for the 3D effect.
* @param yOffset the y-offset for the 3D effect.
* @param renderAsPercentages a flag that controls whether the data values
* are rendered as percentages.
*
* @since 1.0.2
*/
public StackedBarRenderer3D(double xOffset, double yOffset,
boolean renderAsPercentages) {
super(xOffset, yOffset);
this.renderAsPercentages = renderAsPercentages;
}
/**
* Returns <code>true</code> if the renderer displays each item value as
* a percentage (so that the stacked bars add to 100%), and
* <code>false</code> otherwise.
*
* @return A boolean.
*
* @since 1.0.2
*/
public boolean getRenderAsPercentages() {
return this.renderAsPercentages;
}
/**
* Sets the flag that controls whether the renderer displays each item
* value as a percentage (so that the stacked bars add to 100%), and sends
* a {@link RendererChangeEvent} to all registered listeners.
*
* @param asPercentages the flag.
*
* @since 1.0.2
*/
public void setRenderAsPercentages(boolean asPercentages) {
this.renderAsPercentages = asPercentages;
fireChangeEvent();
}
/**
* Returns the flag that controls whether or not zero values are drawn
* by the renderer.
*
* @return A boolean.
*
* @since 1.2.0
*/
public boolean getIgnoreZeroValues() {
return this.ignoreZeroValues;
}
/**
* Sets a flag that controls whether or not zero values are drawn by the
* renderer, and sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param ignore the new flag value.
*
* @since 1.2.0
*/
public void setIgnoreZeroValues(boolean ignore) {
this.ignoreZeroValues = ignore;
notifyListeners(new RendererChangeEvent(this));
}
/**
* Returns the range of values the renderer requires to display all the
* items from the specified dataset.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (or <code>null</code> if the dataset is empty).
*/
public Range findRangeBounds(CategoryDataset dataset) {
if (this.renderAsPercentages) {
return new Range(0.0, 1.0);
}
else {
return DatasetUtilities.findStackedRangeBounds(dataset);
}
}
/**
* Calculates the bar width and stores it in the renderer state.
*
* @param plot the plot.
* @param dataArea the data area.
* @param rendererIndex the renderer index.
* @param state the renderer state.
*/
protected void calculateBarWidth(CategoryPlot plot,
Rectangle2D dataArea,
int rendererIndex,
CategoryItemRendererState state) {
// calculate the bar width
CategoryAxis domainAxis = getDomainAxis(plot, rendererIndex);
CategoryDataset data = plot.getDataset(rendererIndex);
if (data != null) {
PlotOrientation orientation = plot.getOrientation();
double space = 0.0;
if (orientation == PlotOrientation.HORIZONTAL) {
space = dataArea.getHeight();
}
else if (orientation == PlotOrientation.VERTICAL) {
space = dataArea.getWidth();
}
double maxWidth = space * getMaximumBarWidth();
int columns = data.getColumnCount();
double categoryMargin = 0.0;
if (columns > 1) {
categoryMargin = domainAxis.getCategoryMargin();
}
double used = space * (1 - domainAxis.getLowerMargin()
- domainAxis.getUpperMargin()
- categoryMargin);
if (columns > 0) {
state.setBarWidth(Math.min(used / columns, maxWidth));
}
else {
state.setBarWidth(Math.min(used, maxWidth));
}
}
}
/**
* Returns a list containing the stacked values for the specified series
* in the given dataset, plus the supplied base value.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param category the category key (<code>null</code> not permitted).
* @param base the base value.
* @param asPercentages a flag that controls whether the values in the
* list are converted to percentages of the total.
*
* @return The value list.
*
* @since 1.2.0
*/
protected List createStackedValueList(CategoryDataset dataset,
Comparable category, double base, boolean asPercentages) {
List result = new ArrayList();
double posBase = base;
double negBase = base;
double total = 0.0;
if (asPercentages) {
total = DataUtilities.calculateColumnTotal(dataset,
dataset.getColumnIndex(category));
}
int baseIndex = -1;
int seriesCount = dataset.getRowCount();
for (int s = 0; s < seriesCount; s++) {
Number n = dataset.getValue(dataset.getRowKey(s), category);
if (n == null) {
continue;
}
double v = n.doubleValue();
if (asPercentages) {
v = v / total;
}
if ((v > 0.0) || (!this.ignoreZeroValues && v >= 0.0)) {
if (baseIndex < 0) {
result.add(new Object[] {null, new Double(base)});
baseIndex = 0;
}
posBase = posBase + v;
result.add(new Object[] {new Integer(s), new Double(posBase)});
}
else if (v < 0.0) {
if (baseIndex < 0) {
result.add(new Object[] {null, new Double(base)});
baseIndex = 0;
}
negBase = negBase + v; // '+' because v is negative
result.add(0, new Object[] {new Integer(-s),
new Double(negBase)});
baseIndex++;
}
}
return result;
}
/**
* Draws the visual representation of one data item from the chart (in
* fact, this method does nothing until it reaches the last item for each
* category, at which point it draws all the items for that category).
*
* @param g2 the graphics device.
* @param state the renderer state.
* @param dataArea the plot area.
* @param plot the plot.
* @param domainAxis the domain (category) axis.
* @param rangeAxis the range (value) axis.
* @param dataset the data.
* @param row the row index (zero-based).
* @param column the column index (zero-based).
* @param pass the pass index.
*/
public void drawItem(Graphics2D g2,
CategoryItemRendererState state,
Rectangle2D dataArea,
CategoryPlot plot,
CategoryAxis domainAxis,
ValueAxis rangeAxis,
CategoryDataset dataset,
int row,
int column,
int pass) {
// wait till we are at the last item for the row then draw the
// whole stack at once
if (row < dataset.getRowCount() - 1) {
return;
}
Comparable category = dataset.getColumnKey(column);
List values = createStackedValueList(dataset,
dataset.getColumnKey(column), getBase(),
this.renderAsPercentages);
Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX(),
dataArea.getY() + getYOffset(),
dataArea.getWidth() - getXOffset(),
dataArea.getHeight() - getYOffset());
PlotOrientation orientation = plot.getOrientation();
// handle rendering separately for the two plot orientations...
if (orientation == PlotOrientation.HORIZONTAL) {
drawStackHorizontal(values, category, g2, state, adjusted, plot,
domainAxis, rangeAxis, dataset);
}
else {
drawStackVertical(values, category, g2, state, adjusted, plot,
domainAxis, rangeAxis, dataset);
}
}
/**
* Draws a stack of bars for one category, with a horizontal orientation.
*
* @param values the value list.
* @param category the category.
* @param g2 the graphics device.
* @param state the state.
* @param dataArea the data area (adjusted for the 3D effect).
* @param plot the plot.
* @param domainAxis the domain axis.
* @param rangeAxis the range axis.
* @param dataset the dataset.
*
* @since 1.0.4
*/
protected void drawStackHorizontal(List values, Comparable category,
Graphics2D g2, CategoryItemRendererState state,
Rectangle2D dataArea, CategoryPlot plot,
CategoryAxis domainAxis, ValueAxis rangeAxis,
CategoryDataset dataset) {
int column = dataset.getColumnIndex(category);
double barX0 = domainAxis.getCategoryMiddle(column,
dataset.getColumnCount(), dataArea, plot.getDomainAxisEdge())
- state.getBarWidth() / 2.0;
double barW = state.getBarWidth();
// a list to store the series index and bar region, so we can draw
// all the labels at the end...
List itemLabelList = new ArrayList();
// draw the blocks
boolean inverted = rangeAxis.isInverted();
int blockCount = values.size() - 1;
for (int k = 0; k < blockCount; k++) {
int index = (inverted ? blockCount - k - 1 : k);
Object[] prev = (Object[]) values.get(index);
Object[] curr = (Object[]) values.get(index + 1);
int series = 0;
if (curr[0] == null) {
series = -((Integer) prev[0]).intValue();
}
else {
series = ((Integer) curr[0]).intValue();
if (series < 0) {
series = -((Integer) prev[0]).intValue();
}
}
double v0 = ((Double) prev[1]).doubleValue();
double vv0 = rangeAxis.valueToJava2D(v0, dataArea,
plot.getRangeAxisEdge());
double v1 = ((Double) curr[1]).doubleValue();
double vv1 = rangeAxis.valueToJava2D(v1, dataArea,
plot.getRangeAxisEdge());
Shape[] faces = createHorizontalBlock(barX0, barW, vv0, vv1,
inverted);
Paint fillPaint = getItemPaint(series, column);
Paint fillPaintDark = fillPaint;
if (fillPaintDark instanceof Color) {
fillPaintDark = ((Color) fillPaint).darker();
}
boolean drawOutlines = isDrawBarOutline();
Paint outlinePaint = fillPaint;
if (drawOutlines) {
outlinePaint = getItemOutlinePaint(series, column);
g2.setStroke(getItemOutlineStroke(series, column));
}
for (int f = 0; f < 6; f++) {
if (f == 5) {
g2.setPaint(fillPaint);
}
else {
g2.setPaint(fillPaintDark);
}
g2.fill(faces[f]);
if (drawOutlines) {
g2.setPaint(outlinePaint);
g2.draw(faces[f]);
}
}
itemLabelList.add(new Object[] {new Integer(series),
faces[5].getBounds2D(),
Boolean.valueOf(v0 < getBase())});
// add an item entity, if this information is being collected
EntityCollection entities = state.getEntityCollection();
if (entities != null) {
addItemEntity(entities, dataset, series, column, faces[5]);
}
}
for (int i = 0; i < itemLabelList.size(); i++) {
Object[] record = (Object[]) itemLabelList.get(i);
int series = ((Integer) record[0]).intValue();
Rectangle2D bar = (Rectangle2D) record[1];
boolean neg = ((Boolean) record[2]).booleanValue();
CategoryItemLabelGenerator generator
= getItemLabelGenerator(series, column);
if (generator != null && isItemLabelVisible(series, column)) {
drawItemLabel(g2, dataset, series, column, plot, generator,
bar, neg);
}
}
}
/**
* Creates an array of shapes representing the six sides of a block in a
* horizontal stack.
*
* @param x0 left edge of bar (in Java2D space).
* @param width the width of the bar (in Java2D units).
* @param y0 the base of the block (in Java2D space).
* @param y1 the top of the block (in Java2D space).
* @param inverted a flag indicating whether or not the block is inverted
* (this changes the order of the faces of the block).
*
* @return The sides of the block.
*/
private Shape[] createHorizontalBlock(double x0, double width, double y0,
double y1, boolean inverted) {
Shape[] result = new Shape[6];
Point2D p00 = new Point2D.Double(y0, x0);
Point2D p01 = new Point2D.Double(y0, x0 + width);
Point2D p02 = new Point2D.Double(p01.getX() + getXOffset(),
p01.getY() - getYOffset());
Point2D p03 = new Point2D.Double(p00.getX() + getXOffset(),
p00.getY() - getYOffset());
Point2D p0 = new Point2D.Double(y1, x0);
Point2D p1 = new Point2D.Double(y1, x0 + width);
Point2D p2 = new Point2D.Double(p1.getX() + getXOffset(),
p1.getY() - getYOffset());
Point2D p3 = new Point2D.Double(p0.getX() + getXOffset(),
p0.getY() - getYOffset());
GeneralPath bottom = new GeneralPath();
bottom.moveTo((float) p1.getX(), (float) p1.getY());
bottom.lineTo((float) p01.getX(), (float) p01.getY());
bottom.lineTo((float) p02.getX(), (float) p02.getY());
bottom.lineTo((float) p2.getX(), (float) p2.getY());
bottom.closePath();
GeneralPath top = new GeneralPath();
top.moveTo((float) p0.getX(), (float) p0.getY());
top.lineTo((float) p00.getX(), (float) p00.getY());
top.lineTo((float) p03.getX(), (float) p03.getY());
top.lineTo((float) p3.getX(), (float) p3.getY());
top.closePath();
GeneralPath back = new GeneralPath();
back.moveTo((float) p2.getX(), (float) p2.getY());
back.lineTo((float) p02.getX(), (float) p02.getY());
back.lineTo((float) p03.getX(), (float) p03.getY());
back.lineTo((float) p3.getX(), (float) p3.getY());
back.closePath();
GeneralPath front = new GeneralPath();
front.moveTo((float) p0.getX(), (float) p0.getY());
front.lineTo((float) p1.getX(), (float) p1.getY());
front.lineTo((float) p01.getX(), (float) p01.getY());
front.lineTo((float) p00.getX(), (float) p00.getY());
front.closePath();
GeneralPath left = new GeneralPath();
left.moveTo((float) p0.getX(), (float) p0.getY());
left.lineTo((float) p1.getX(), (float) p1.getY());
left.lineTo((float) p2.getX(), (float) p2.getY());
left.lineTo((float) p3.getX(), (float) p3.getY());
left.closePath();
GeneralPath right = new GeneralPath();
right.moveTo((float) p00.getX(), (float) p00.getY());
right.lineTo((float) p01.getX(), (float) p01.getY());
right.lineTo((float) p02.getX(), (float) p02.getY());
right.lineTo((float) p03.getX(), (float) p03.getY());
right.closePath();
result[0] = bottom;
result[1] = back;
if (inverted) {
result[2] = right;
result[3] = left;
}
else {
result[2] = left;
result[3] = right;
}
result[4] = top;
result[5] = front;
return result;
}
/**
* Draws a stack of bars for one category, with a vertical orientation.
*
* @param values the value list.
* @param category the category.
* @param g2 the graphics device.
* @param state the state.
* @param dataArea the data area (adjusted for the 3D effect).
* @param plot the plot.
* @param domainAxis the domain axis.
* @param rangeAxis the range axis.
* @param dataset the dataset.
*
* @since 1.0.4
*/
protected void drawStackVertical(List values, Comparable category,
Graphics2D g2, CategoryItemRendererState state,
Rectangle2D dataArea, CategoryPlot plot,
CategoryAxis domainAxis, ValueAxis rangeAxis,
CategoryDataset dataset) {
int column = dataset.getColumnIndex(category);
double barX0 = domainAxis.getCategoryMiddle(column,
dataset.getColumnCount(), dataArea, plot.getDomainAxisEdge())
- state.getBarWidth() / 2.0;
double barW = state.getBarWidth();
// a list to store the series index and bar region, so we can draw
// all the labels at the end...
List itemLabelList = new ArrayList();
// draw the blocks
boolean inverted = rangeAxis.isInverted();
int blockCount = values.size() - 1;
for (int k = 0; k < blockCount; k++) {
int index = (inverted ? blockCount - k - 1 : k);
Object[] prev = (Object[]) values.get(index);
Object[] curr = (Object[]) values.get(index + 1);
int series = 0;
if (curr[0] == null) {
series = -((Integer) prev[0]).intValue();
}
else {
series = ((Integer) curr[0]).intValue();
if (series < 0) {
series = -((Integer) prev[0]).intValue();
}
}
double v0 = ((Double) prev[1]).doubleValue();
double vv0 = rangeAxis.valueToJava2D(v0, dataArea,
plot.getRangeAxisEdge());
double v1 = ((Double) curr[1]).doubleValue();
double vv1 = rangeAxis.valueToJava2D(v1, dataArea,
plot.getRangeAxisEdge());
Shape[] faces = createVerticalBlock(barX0, barW, vv0, vv1,
inverted);
Paint fillPaint = getItemPaint(series, column);
Paint fillPaintDark = fillPaint;
if (fillPaintDark instanceof Color) {
fillPaintDark = ((Color) fillPaint).darker();
}
boolean drawOutlines = isDrawBarOutline();
Paint outlinePaint = fillPaint;
if (drawOutlines) {
outlinePaint = getItemOutlinePaint(series, column);
g2.setStroke(getItemOutlineStroke(series, column));
}
for (int f = 0; f < 6; f++) {
if (f == 5) {
g2.setPaint(fillPaint);
}
else {
g2.setPaint(fillPaintDark);
}
g2.fill(faces[f]);
if (drawOutlines) {
g2.setPaint(outlinePaint);
g2.draw(faces[f]);
}
}
itemLabelList.add(new Object[] {new Integer(series),
faces[5].getBounds2D(),
Boolean.valueOf(v0 < getBase())});
// add an item entity, if this information is being collected
EntityCollection entities = state.getEntityCollection();
if (entities != null) {
addItemEntity(entities, dataset, series, column, faces[5]);
}
}
for (int i = 0; i < itemLabelList.size(); i++) {
Object[] record = (Object[]) itemLabelList.get(i);
int series = ((Integer) record[0]).intValue();
Rectangle2D bar = (Rectangle2D) record[1];
boolean neg = ((Boolean) record[2]).booleanValue();
CategoryItemLabelGenerator generator
= getItemLabelGenerator(series, column);
if (generator != null && isItemLabelVisible(series, column)) {
drawItemLabel(g2, dataset, series, column, plot, generator,
bar, neg);
}
}
}
/**
* Creates an array of shapes representing the six sides of a block in a
* vertical stack.
*
* @param x0 left edge of bar (in Java2D space).
* @param width the width of the bar (in Java2D units).
* @param y0 the base of the block (in Java2D space).
* @param y1 the top of the block (in Java2D space).
* @param inverted a flag indicating whether or not the block is inverted
* (this changes the order of the faces of the block).
*
* @return The sides of the block.
*/
private Shape[] createVerticalBlock(double x0, double width, double y0,
double y1, boolean inverted) {
Shape[] result = new Shape[6];
Point2D p00 = new Point2D.Double(x0, y0);
Point2D p01 = new Point2D.Double(x0 + width, y0);
Point2D p02 = new Point2D.Double(p01.getX() + getXOffset(),
p01.getY() - getYOffset());
Point2D p03 = new Point2D.Double(p00.getX() + getXOffset(),
p00.getY() - getYOffset());
Point2D p0 = new Point2D.Double(x0, y1);
Point2D p1 = new Point2D.Double(x0 + width, y1);
Point2D p2 = new Point2D.Double(p1.getX() + getXOffset(),
p1.getY() - getYOffset());
Point2D p3 = new Point2D.Double(p0.getX() + getXOffset(),
p0.getY() - getYOffset());
GeneralPath right = new GeneralPath();
right.moveTo((float) p1.getX(), (float) p1.getY());
right.lineTo((float) p01.getX(), (float) p01.getY());
right.lineTo((float) p02.getX(), (float) p02.getY());
right.lineTo((float) p2.getX(), (float) p2.getY());
right.closePath();
GeneralPath left = new GeneralPath();
left.moveTo((float) p0.getX(), (float) p0.getY());
left.lineTo((float) p00.getX(), (float) p00.getY());
left.lineTo((float) p03.getX(), (float) p03.getY());
left.lineTo((float) p3.getX(), (float) p3.getY());
left.closePath();
GeneralPath back = new GeneralPath();
back.moveTo((float) p2.getX(), (float) p2.getY());
back.lineTo((float) p02.getX(), (float) p02.getY());
back.lineTo((float) p03.getX(), (float) p03.getY());
back.lineTo((float) p3.getX(), (float) p3.getY());
back.closePath();
GeneralPath front = new GeneralPath();
front.moveTo((float) p0.getX(), (float) p0.getY());
front.lineTo((float) p1.getX(), (float) p1.getY());
front.lineTo((float) p01.getX(), (float) p01.getY());
front.lineTo((float) p00.getX(), (float) p00.getY());
front.closePath();
GeneralPath top = new GeneralPath();
top.moveTo((float) p0.getX(), (float) p0.getY());
top.lineTo((float) p1.getX(), (float) p1.getY());
top.lineTo((float) p2.getX(), (float) p2.getY());
top.lineTo((float) p3.getX(), (float) p3.getY());
top.closePath();
GeneralPath bottom = new GeneralPath();
bottom.moveTo((float) p00.getX(), (float) p00.getY());
bottom.lineTo((float) p01.getX(), (float) p01.getY());
bottom.lineTo((float) p02.getX(), (float) p02.getY());
bottom.lineTo((float) p03.getX(), (float) p03.getY());
bottom.closePath();
result[0] = bottom;
result[1] = back;
result[2] = left;
result[3] = right;
result[4] = top;
result[5] = front;
if (inverted) {
result[0] = top;
result[4] = bottom;
}
return result;
}
/**
* Tests this renderer for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof StackedBarRenderer3D)) {
return false;
}
StackedBarRenderer3D that = (StackedBarRenderer3D) obj;
if (this.renderAsPercentages != that.getRenderAsPercentages()) {
return false;
}
if (this.ignoreZeroValues != that.ignoreZeroValues) {
return false;
}
return super.equals(obj);
}
} |
package net.darkmorford.jas.block;
import net.darkmorford.jas.JustAnotherSnad;
import net.darkmorford.jas.configuration.ConfigurationData;
import net.minecraft.block.*;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.EnumPlantType;
import net.minecraftforge.common.IPlantable;
import org.apache.logging.log4j.Level;
import java.util.Random;
import static net.darkmorford.jas.JustAnotherSnad.MODID;
public class BlockSnad extends BlockSand {
public BlockSnad() {
super();
setCreativeTab(CreativeTabs.MISC);
setHardness(0.5f);
setSoundType(SoundType.SAND);
setTickRandomly(true);
setUnlocalizedName("snad");
setRegistryName(MODID, "snad");
}
@Override
public void randomTick(World world, BlockPos position, IBlockState state, Random random) {
super.randomTick(world, position, state, random);
Block blockAbove = world.getBlockState(position.up()).getBlock();
if (blockAbove instanceof BlockReed || blockAbove instanceof BlockCactus) {
checkColumnOfPlant(world, position, random, blockAbove);
} else if (blockAbove instanceof IPlantable) {
blockAbove.randomTick(world, position.up(), world.getBlockState(position.up()), random);
}
}
private void checkColumnOfPlant(World world, BlockPos originalPosition, Random random, Block blockAbove) {
Block nextPlantBlock;
BlockPos nextPosition = originalPosition.up();
while ((nextPlantBlock = world.getBlockState(nextPosition).getBlock()).getClass().equals(blockAbove.getClass())) {
growthLoop(world, originalPosition, random, (IPlantable) blockAbove, nextPosition, nextPlantBlock);
nextPosition = nextPosition.up();
}
}
private void growthLoop(World world, BlockPos orignalPosition, Random random, IPlantable blockAbove, BlockPos nextPosition, Block nextPlantBlock) {
for (int growthAttempts = 0; growthAttempts < ConfigurationData.SNAD_SPEED_INCREASE_VALUE; growthAttempts++) {
if (growthAttempts == 0 || canSustainPlant(world.getBlockState(orignalPosition), world, orignalPosition, null, blockAbove)) {
nextPlantBlock.randomTick(world, nextPosition, world.getBlockState(nextPosition), random);
}
}
}
@Override
public boolean canSustainPlant(IBlockState state, IBlockAccess world, BlockPos position, EnumFacing facing, IPlantable plantable) {
BlockPos plantPosition = new BlockPos(position.getX(), position.getY() + 1, position.getZ());
EnumPlantType plantType = plantable.getPlantType(world, plantPosition);
switch (plantType) {
case Desert:
return true;
case Beach:
return ((world.getBlockState(new BlockPos(position.getX() - 1, position.getY(), position.getZ())).getMaterial() == Material.WATER) ||
(world.getBlockState(new BlockPos(position.getX() + 1, position.getY(), position.getZ())).getMaterial() == Material.WATER) ||
(world.getBlockState(new BlockPos(position.getX(), position.getY(), position.getZ() + 1)).getMaterial() == Material.WATER) ||
(world.getBlockState(new BlockPos(position.getX(), position.getY(), position.getZ() - 1)).getMaterial() == Material.WATER));
case Water:
return (world.getBlockState(position).getMaterial() == Material.WATER) && (world.getBlockState(position) == getDefaultState());
default: {
return false;
}
}
}
} |
package net.gemelen.blackjack.data;
import com.hazelcast.config.*;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import java.util.Map;
public class DataGrid {
private static final String SETTINGS_MAP = "casino";
private static final String PLAYERS_MAP = "casino";
private Map<String, String> casino;
private Map<Integer, PlayerRecordView> players;
public DataGrid() {
Config cfg = new Config();
MapConfig mc = new MapCOnfig();
mc.setName(SETTINGS_MAP);
mc.setBackupCount(1);
mc.setReadBackupData(true);
cfg.addMapConfig(mc);
MapConfig pc = new MapCOnfig();
pc.setName(PLAYERS_MAP);
pc.setBackupCount(1);
pc.setReadBackupData(true);
cfg.addMapConfig(pc);
HazelcastInstance grid = Hazelcast.newHazelcastInstance(cfg);
this.casino = grid.getMap("casino");
this.players = grid.getMap("players");
}
public Map<String, String> getCasino() {
return casino;
}
public Map<Integer, PlayerRecordView> getPlayers() {
return players;
}
} |
package net.openhft.chronicle.wire;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.ref.BinaryLongArrayReference;
import net.openhft.chronicle.bytes.ref.BinaryLongReference;
import net.openhft.chronicle.bytes.ref.TextLongArrayReference;
import net.openhft.chronicle.bytes.ref.TextLongReference;
import net.openhft.chronicle.core.values.LongArrayValues;
import net.openhft.chronicle.core.values.LongValue;
import org.jetbrains.annotations.NotNull;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* A selection of prebuilt wire types.
*/
public enum WireType implements Function<Bytes, Wire> {
TEXT {
@NotNull
@Override
public Wire apply(Bytes bytes) {
return new TextWire(bytes);
}
@Override
public Supplier<LongValue> newLongReference() {
return TextLongReference::new;
}
@Override
public Supplier<LongArrayValues> newLongArrayReference() {
return TextLongArrayReference::new;
}
}, BINARY {
@NotNull
@Override
public Wire apply(Bytes bytes) {
return new BinaryWire(bytes);
}
@Override
public String asString(WriteMarshallable marshallable) {
return asHexString(marshallable);
}
@Override
public <T> T fromString(CharSequence cs) {
return fromHexString(cs);
}
}, FIELDLESS_BINARY {
@NotNull
@Override
public Wire apply(Bytes bytes) {
return new BinaryWire(bytes, false, false, true, Integer.MAX_VALUE, "binary");
}
@Override
public String asString(WriteMarshallable marshallable) {
return asHexString(marshallable);
}
@Override
public <T> T fromString(CharSequence cs) {
return fromHexString(cs);
}
}, COMPRESSED_BINARY {
@NotNull
@Override
public Wire apply(Bytes bytes) {
return new BinaryWire(bytes, false, false, false, COMPRESSED_SIZE, "lzw");
}
@Override
public String asString(WriteMarshallable marshallable) {
return asHexString(marshallable);
}
@Override
public <T> T fromString(CharSequence cs) {
return fromHexString(cs);
}
}, JSON {
@NotNull
@Override
public Wire apply(Bytes bytes) {
return new JSONWire(bytes);
}
}, RAW {
@NotNull
@Override
public Wire apply(Bytes bytes) {
return new RawWire(bytes);
}
@Override
public String asString(WriteMarshallable marshallable) {
return asHexString(marshallable);
}
@Override
public <T> T fromString(CharSequence cs) {
return fromHexString(cs);
}
}, READ_ANY {
@Override
public Wire apply(@NotNull Bytes bytes) {
int code = bytes.readByte(0);
if (code >= ' ' && code < 127)
return TEXT.apply(bytes);
if (BinaryWireCode.isFieldCode(code))
return FIELDLESS_BINARY.apply(bytes);
return BINARY.apply(bytes);
}
};
static final ThreadLocal<Bytes> bytesTL = ThreadLocal.withInitial(Bytes::allocateElasticDirect);
private static final int COMPRESSED_SIZE = Integer.getInteger("WireType.compressedSize", 128);
public Supplier<LongValue> newLongReference() {
return BinaryLongReference::new;
}
public Supplier<LongArrayValues> newLongArrayReference() {
return BinaryLongArrayReference::new;
}
public String asString(WriteMarshallable marshallable) {
Bytes bytes = bytesTL.get();
Wire wire = apply(bytes);
wire.getValueOut().typedMarshallable(marshallable);
return bytes.toString();
}
public <T> T fromString(CharSequence cs) {
Bytes bytes = bytesTL.get();
bytes.appendUtf8(cs);
Wire wire = apply(bytes);
return wire.getValueIn().typedMarshallable();
}
String asHexString(WriteMarshallable marshallable) {
Bytes bytes = bytesTL.get();
Wire wire = apply(bytes);
wire.getValueOut().typedMarshallable(marshallable);
return bytes.toHexString();
}
<T> T fromHexString(CharSequence s) {
Wire wire = apply(Bytes.fromHexString(s.toString()));
return wire.getValueIn().typedMarshallable();
}
} |
package net.sf.jabref.model;
import java.util.Collection;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;
import java.util.TreeMap;
import net.sf.jabref.Globals;
import net.sf.jabref.JabRefPreferences;
import net.sf.jabref.util.Util;
public abstract class BibtexEntryType implements Comparable<BibtexEntryType> {
public abstract String getName();
private static final TreeMap<String, BibtexEntryType> ALL_TYPES = new TreeMap<>();
private static final TreeMap<String, BibtexEntryType> STANDARD_TYPES;
static {
// Put the standard entry types into the type map.
if (!Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_MODE)) {
ALL_TYPES.put("article", BibtexEntryTypes.ARTICLE);
ALL_TYPES.put("inbook", BibtexEntryTypes.INBOOK);
ALL_TYPES.put("book", BibtexEntryTypes.BOOK);
ALL_TYPES.put("booklet", BibtexEntryTypes.BOOKLET);
ALL_TYPES.put("incollection", BibtexEntryTypes.INCOLLECTION);
ALL_TYPES.put("conference", BibtexEntryTypes.CONFERENCE);
ALL_TYPES.put("inproceedings", BibtexEntryTypes.INPROCEEDINGS);
ALL_TYPES.put("proceedings", BibtexEntryTypes.PROCEEDINGS);
ALL_TYPES.put("manual", BibtexEntryTypes.MANUAL);
ALL_TYPES.put("mastersthesis", BibtexEntryTypes.MASTERSTHESIS);
ALL_TYPES.put("phdthesis", BibtexEntryTypes.PHDTHESIS);
ALL_TYPES.put("techreport", BibtexEntryTypes.TECHREPORT);
ALL_TYPES.put("unpublished", BibtexEntryTypes.UNPUBLISHED);
ALL_TYPES.put("patent", BibtexEntryTypes.PATENT);
ALL_TYPES.put("standard", BibtexEntryTypes.STANDARD);
ALL_TYPES.put("electronic", BibtexEntryTypes.ELECTRONIC);
ALL_TYPES.put("periodical", BibtexEntryTypes.PERIODICAL);
ALL_TYPES.put("misc", BibtexEntryTypes.MISC);
ALL_TYPES.put("other", BibtexEntryTypes.OTHER);
ALL_TYPES.put("ieeetranbstctl", BibtexEntryTypes.IEEETRANBSTCTL);
} else {
ALL_TYPES.put("article", BibLatexEntryTypes.ARTICLE);
ALL_TYPES.put("book", BibLatexEntryTypes.BOOK);
ALL_TYPES.put("inbook", BibLatexEntryTypes.INBOOK);
ALL_TYPES.put("bookinbook", BibLatexEntryTypes.BOOKINBOOK);
ALL_TYPES.put("suppbook", BibLatexEntryTypes.SUPPBOOK);
ALL_TYPES.put("booklet", BibLatexEntryTypes.BOOKLET);
ALL_TYPES.put("collection", BibLatexEntryTypes.COLLECTION);
ALL_TYPES.put("incollection", BibLatexEntryTypes.INCOLLECTION);
ALL_TYPES.put("suppcollection", BibLatexEntryTypes.SUPPCOLLECTION);
ALL_TYPES.put("manual", BibLatexEntryTypes.MANUAL);
ALL_TYPES.put("misc", BibLatexEntryTypes.MISC);
ALL_TYPES.put("online", BibLatexEntryTypes.ONLINE);
ALL_TYPES.put("patent", BibLatexEntryTypes.PATENT);
ALL_TYPES.put("periodical", BibLatexEntryTypes.PERIODICAL);
ALL_TYPES.put("suppperiodical", BibLatexEntryTypes.SUPPPERIODICAL);
ALL_TYPES.put("proceedings", BibLatexEntryTypes.PROCEEDINGS);
ALL_TYPES.put("inproceedings", BibLatexEntryTypes.INPROCEEDINGS);
ALL_TYPES.put("reference", BibLatexEntryTypes.REFERENCE);
ALL_TYPES.put("inreference", BibLatexEntryTypes.INREFERENCE);
ALL_TYPES.put("report", BibLatexEntryTypes.REPORT);
ALL_TYPES.put("set", BibLatexEntryTypes.SET);
ALL_TYPES.put("thesis", BibLatexEntryTypes.THESIS);
ALL_TYPES.put("unpublished", BibLatexEntryTypes.UNPUBLISHED);
ALL_TYPES.put("conference", BibLatexEntryTypes.CONFERENCE);
ALL_TYPES.put("electronic", BibLatexEntryTypes.ELECTRONIC);
ALL_TYPES.put("mastersthesis", BibLatexEntryTypes.MASTERSTHESIS);
ALL_TYPES.put("phdthesis", BibLatexEntryTypes.PHDTHESIS);
ALL_TYPES.put("techreport", BibLatexEntryTypes.TECHREPORT);
ALL_TYPES.put("www", BibLatexEntryTypes.WWW);
ALL_TYPES.put("ieeetranbstctl", BibLatexEntryTypes.IEEETRANBSTCTL);
}
// We need a record of the standard types, in case the user wants
// to remove a customized version. Therefore we clone the map.
STANDARD_TYPES = new TreeMap<>(ALL_TYPES);
}
@Override
public int compareTo(BibtexEntryType o) {
return getName().compareTo(o.getName());
}
public abstract String[] getOptionalFields();
public abstract String[] getRequiredFields();
public String[] getPrimaryOptionalFields() {
return getOptionalFields();
}
public String[] getSecondaryOptionalFields() {
return Util.getRemainder(getOptionalFields(), getPrimaryOptionalFields());
}
public abstract String describeRequiredFields();
public abstract boolean hasAllRequiredFields(BibtexEntry entry, BibtexDatabase database);
public String[] getUtilityFields() {
return new String[]{"search"};
}
public boolean isRequired(String field) {
String[] requiredFields = getRequiredFields();
if (requiredFields == null) {
return false;
}
for (String requiredField : requiredFields) {
if (requiredField.equals(field)) {
return true;
}
}
return false;
}
public boolean isOptional(String field) {
String[] optionalFields = getOptionalFields();
if (optionalFields == null) {
return false;
}
for (String optionalField : optionalFields) {
if (optionalField.equals(field)) {
return true;
}
}
return false;
}
public boolean isVisibleAtNewEntryDialog() {
return true;
}
/**
* This method returns the BibtexEntryType for the name of a type,
* or null if it does not exist.
*/
public static BibtexEntryType getType(String name) {
BibtexEntryType entryType = ALL_TYPES.get(name.toLowerCase(Locale.US));
if (entryType == null) {
return null;
} else {
return entryType;
}
}
/**
* This method returns the standard BibtexEntryType for the
* name of a type, or null if it does not exist.
*/
public static BibtexEntryType getStandardType(String name) {
BibtexEntryType entryType = STANDARD_TYPES.get(name.toLowerCase());
if (entryType == null) {
return null;
} else {
return entryType;
}
}
public static void addOrModifyCustomEntryType(CustomEntryType type) {
ALL_TYPES.put(type.getName().toLowerCase(Locale.US), type);
}
public static Set<String> getAllTypes() {
return ALL_TYPES.keySet();
}
public static Collection<BibtexEntryType> getAllValues() {
return ALL_TYPES.values();
}
/**
* Removes a customized entry type from the type map. If this type
* overrode a standard type, we reinstate the standard one.
*
* @param name The customized entry type to remove.
*/
public static void removeType(String name) {
String toLowerCase = name.toLowerCase();
ALL_TYPES.remove(toLowerCase);
if (STANDARD_TYPES.get(toLowerCase) != null) {
// In this case the user has removed a customized version
// of a standard type. We reinstate the standard type.
addOrModifyCustomEntryType((CustomEntryType) STANDARD_TYPES.get(toLowerCase));
}
}
/**
* Load all custom entry types from preferences. This method is
* called from JabRef when the program starts.
*/
public static void loadCustomEntryTypes(JabRefPreferences prefs) {
int number = 0;
CustomEntryType type;
while ((type = prefs.getCustomEntryType(number)) != null) {
addOrModifyCustomEntryType(type);
number++;
}
}
/**
* Iterate through all entry types, and store those that are
* custom defined to preferences. This method is called from
* JabRefFrame when the program closes.
*/
public static void saveCustomEntryTypes(JabRefPreferences prefs) {
Iterator<String> iterator = ALL_TYPES.keySet().iterator();
int number = 0;
while (iterator.hasNext()) {
Object o = ALL_TYPES.get(iterator.next());
if (o instanceof CustomEntryType) {
// Store this entry type.
prefs.storeCustomEntryType((CustomEntryType) o, number);
number++;
}
}
// Then, if there are more 'old' custom types defined, remove these
// from preferences. This is necessary if the number of custom types
// has decreased.
prefs.purgeCustomEntryTypes(number);
}
/**
* Get an array of the required fields in a form appropriate for the entry customization
* dialog - that is, the either-or fields together and separated by slashes.
*
* @return Array of the required fields in a form appropriate for the entry customization dialog.
*/
public String[] getRequiredFieldsForCustomization() {
return getRequiredFields();
}
} |
package nom.bdezonia.zorbage.algorithm;
import nom.bdezonia.zorbage.type.algebra.Algebra;
import nom.bdezonia.zorbage.type.storage.IndexedDataSource;
/**
*
* @author Barry DeZonia
*
*/
public class Find {
private Find() {}
/**
*
* @param algebra
* @param a
* @param value
* @return
*/
public static <T extends Algebra<T,U>, U>
long compute(T algebra, U value, IndexedDataSource<U> a)
{
return compute(algebra, value, 0, a.size(), a);
}
/**
*
* @param algebra
* @param a
* @param value
* @param start
* @param count
* @return
*/
public static <T extends Algebra<T,U>, U>
long compute(T algebra, U value, long start, long count, IndexedDataSource<U> a)
{
U tmp = algebra.construct();
for (long i = 0; i < count; i++) {
a.get(start+i, tmp);
if (algebra.isEqual().call(tmp, value))
return start + i;
}
return start + count;
}
} |
package etomica.modules.dcvgcmd;
import etomica.api.IAtomSet;
import etomica.api.IAtomPositioned;
import etomica.api.IVector;
import etomica.EtomicaInfo;
import etomica.potential.Potential1;
import etomica.potential.PotentialSoft;
import etomica.space.Space;
import etomica.space.Tensor;
/**
* 1-D potential that has a WCA form in the Z direction.
*/
public class P1WCAWall extends Potential1 implements PotentialSoft {
private static final long serialVersionUID = 1L;
protected final IVector[] gradient;
protected double sigma;
protected double epsilon;
protected double cutoff;
protected int wallDim;
public P1WCAWall(Space space, int wallDim) {
this(space, wallDim, 1.0, 1.0);
}
public P1WCAWall(Space space, int wallDim, double sigma, double epsilon) {
super(space);
setSigma(sigma);
setEpsilon(epsilon);
setWallDim(wallDim);
gradient = new IVector[1];
gradient[0] = space.makeVector();
}
public static EtomicaInfo getEtomicaInfo() {
EtomicaInfo info = new EtomicaInfo(
"WCA LJ Potential in the Z-Coordinate");
return info;
}
public double getRange() {
return cutoff;
}
public double energy(IAtomSet atom) {
IVector dimensions = boundary.getDimensions();
double rz = ((IAtomPositioned)atom.getAtom(0)).getPosition().x(wallDim);
double dzHalf = 0.5 * dimensions.x(wallDim);
return energy(dzHalf + rz) + energy(dzHalf - rz);
}
private double energy(double r) {
if (r > cutoff) {
return 0;
}
double rr = sigma / r;
double r2 = rr * rr;
double r6 = r2 * r2 * r2;
return 4 * epsilon * r6 * (r6 - 1.0) + epsilon;
}
private double gradient(double r) {
if (r > cutoff) {
return 0;
}
double rr = sigma / r;
double r2 = rr * rr;
double r6 = r2 * r2 * r2;
return -48 * epsilon * r6 * (r6 - 0.5);
}
public IVector[] gradient(IAtomSet atom) {
IVector dimensions = boundary.getDimensions();
double rz = ((IAtomPositioned)atom.getAtom(0)).getPosition().x(wallDim);
double dzHalf = 0.5 * dimensions.x(wallDim);
double gradz = gradient(rz + dzHalf) - gradient(dzHalf - rz);
gradient[0].setX(wallDim, gradz);
return gradient;
}
public IVector[] gradient(IAtomSet atom, Tensor pressureTensor) {
return gradient(atom);
}
public double virial(IAtomSet atoms) {
return 0.0;
}
/**
* Returns the radius.
*
* @return double
*/
public double getSigma() {
return sigma;
}
/**
* Sets the radius.
*
* @param radius
* The radius to set
*/
public void setSigma(double radius) {
this.sigma = radius;
cutoff = radius * Math.pow(2, 1. / 6.);
}
/**
* @return Returns the epsilon.
*/
public double getEpsilon() {
return epsilon;
}
/**
* @param epsilon
* The epsilon to set.
*/
public void setEpsilon(double epsilon) {
this.epsilon = epsilon;
}
public int getWallDim() {
return wallDim;
}
public void setWallDim(int wallDim) {
this.wallDim = wallDim;
}
} |
package imagej.command;
import imagej.Cancelable;
import imagej.module.AbstractModule;
import imagej.module.ModuleException;
import java.util.Map;
import org.scijava.Context;
import org.scijava.Contextual;
import org.scijava.InstantiableException;
import org.scijava.plugin.PluginInfo;
import org.scijava.util.ClassUtils;
import org.scijava.util.Log;
/**
* Module class for working with a {@link Command} instance.
*
* @author Curtis Rueden
* @author Johannes Schindelin
* @author Grant Harris
*/
public class CommandModule extends AbstractModule implements Cancelable,
Contextual
{
/** The metadata describing the command. */
private final CommandInfo info;
/** The command instance handled by this module. */
private final Command command;
/** Creates a command module for the given {@link PluginInfo}. */
public CommandModule(final CommandInfo info) throws ModuleException {
super();
this.info = info;
command = instantiateCommand();
assignPresets();
}
/**
* Creates a command module for the given {@link CommandInfo}, around the
* specified {@link Command} instance.
*/
public CommandModule(final CommandInfo info, final Command command) {
super();
this.info = info;
this.command = command;
assignPresets();
}
// -- CommandModule methods --
/** Gets the command instance handled by this module. */
public Command getCommand() {
return command;
}
// -- Module methods --
/**
* Computes a preview of the command's results. For this method to do
* anything, the command must implement the {@link Previewable} interface.
*/
@Override
public void preview() {
if (!(command instanceof Previewable)) return; // cannot preview
final Previewable previewPlugin = (Previewable) command;
previewPlugin.preview();
}
/**
* Cancels the command, undoing the effects of any {@link #preview()} calls.
* For this method to do anything, the command must implement the
* {@link Previewable} interface.
*/
@Override
public void cancel() {
if (!(command instanceof Previewable)) return; // nothing to cancel
final Previewable previewPlugin = (Previewable) command;
previewPlugin.cancel();
}
@Override
public CommandInfo getInfo() {
return info;
}
@Override
public Object getDelegateObject() {
return command;
}
@Override
public Object getInput(final String name) {
final CommandModuleItem<?> item = info.getInput(name);
return ClassUtils.getValue(item.getField(), command);
}
@Override
public Object getOutput(final String name) {
final CommandModuleItem<?> item = info.getOutput(name);
return ClassUtils.getValue(item.getField(), command);
}
@Override
public void setInput(final String name, final Object value) {
final CommandModuleItem<?> item = info.getInput(name);
ClassUtils.setValue(item.getField(), command, value);
}
@Override
public void setOutput(final String name, final Object value) {
final CommandModuleItem<?> item = info.getOutput(name);
ClassUtils.setValue(item.getField(), command, value);
}
// -- Object methods --
@Override
public String toString() {
return command.getClass().getName();
}
// -- Runnable methods --
@Override
public void run() {
try {
command.run();
}
catch (final Throwable t) {
Log.error(t);
}
}
// -- Cancelable methods --
@Override
public boolean isCanceled() {
if (!(command instanceof Cancelable)) return false;
return ((Cancelable) command).isCanceled();
}
@Override
public String getCancelReason() {
if (!(command instanceof Cancelable)) return null;
return ((Cancelable) command).getCancelReason();
}
// -- Contextual methods --
@Override
public Context getContext() {
if (!(command instanceof Contextual)) return null;
return ((Contextual) command).getContext();
}
@Override
public void setContext(final Context context) {
if (!(command instanceof Contextual)) return; // ignore context injection
((Contextual) command).setContext(context);
}
// -- Helper methods --
private Command instantiateCommand() throws ModuleException {
try {
return info.createInstance();
}
catch (final InstantiableException exc) {
throw new ModuleException(exc);
}
}
private void assignPresets() {
final Map<String, Object> presets = info.getPresets();
for (final String name : presets.keySet()) {
final Object value = presets.get(name);
setInput(name, value);
setResolved(name, true);
}
}
} |
package urteam.security;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
@Configuration
public class CSRFHandlerConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CSRFHandlerInterceptor());
}
}
class CSRFHandlerInterceptor extends HandlerInterceptorAdapter {
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
final ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
modelAndView.addObject("token", token.getToken());
}
}
} |
package com.db.event;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Vector;
import com.db.logging.LoggerManager;
import com.db.util.JobThreadPool;
import com.db.util.MethodInvoker;
/**
* This class is used to delegate events to listeners on separate threads.
* Each listener has its own thread that it receives and processes events on.
*
* @author Dave Longley
*/
public class ThreadedEventDelegate
{
/**
* A thread that monitors the event queue for new events and dispatches them.
*/
protected Thread mEventDispatchThread;
/**
* A thread pool for threads that process events.
*/
protected JobThreadPool mProcessEventsThreadPool;
/**
* A map of listener to EventProcessor.
*/
protected HashMap<Object, EventProcessor> mListenerToEventProcessor;
/**
* Constructs a new threaded event delegate.
*/
public ThreadedEventDelegate()
{
// no event dispatch thread yet
mEventDispatchThread = null;
// create the process events thread pool
mProcessEventsThreadPool = new JobThreadPool(1);
// set 5 minute time limit on threads
mProcessEventsThreadPool.setJobThreadExpireTime(300000);
// create listener to event processor map
mListenerToEventProcessor = new HashMap<Object, EventProcessor>();
}
/**
* Stops the event dispatch thread.
*
* @exception Throwable thrown if an exception occurs.
*/
@Override
protected void finalize() throws Throwable
{
// stop the event dispatch thread
if(mEventDispatchThread != null)
{
mEventDispatchThread.interrupt();
mEventDispatchThread = null;
}
// terminate all process events threads
mProcessEventsThreadPool.terminateAllThreads(1000);
super.finalize();
}
/**
* Dispatches any available events for processing. Tells EventProcessors
* to process their events.
*/
public void dispatchEvents()
{
try
{
// keep dispatching until interrupted
while(!Thread.currentThread().isInterrupted())
{
// lock while iterating over event processors
synchronized(this)
{
// go through each event processor
for(EventProcessor ep: mListenerToEventProcessor.values())
{
// lock on the event processor
synchronized(ep)
{
// if the event processor is not processing events and has
// events to process, then process events on a process
// events thread from the thread pool
if(!ep.isProcessing() && ep.hasEvents())
{
// create process events job
MethodInvoker job = new MethodInvoker(
ep, "processEvents");
// indicate that the event processor is now in use
ep.setProcessing(true);
// run the job via the process events thread pool
mProcessEventsThreadPool.runJob(job);
}
}
}
}
// sleep for just a moment
Thread.sleep(1);
}
}
catch(InterruptedException e)
{
// ensure interrupted state remains flipped
Thread.currentThread().interrupt();
}
}
/**
* Adds a listener to this event delegate if it has not been added yet.
*
* @param listener the listener to add.
* @param methodName the name of the listener method to call to handle
* an event.
*/
public synchronized void addListener(Object listener, String methodName)
{
if(listener == null)
{
throw new IllegalArgumentException(
"Cannot add a 'null' listener.");
}
if(methodName == null)
{
throw new IllegalArgumentException(
"Cannot add a listener with a 'null' method name.");
}
if(!hasListener(listener))
{
// create an EventProcessor
EventProcessor ep = new EventProcessor(listener, methodName);
// add the listener to EventProcessor mapping
mListenerToEventProcessor.put(listener, ep);
// set the number of thread available in the process events thread pool
mProcessEventsThreadPool.setPoolSize(mListenerToEventProcessor.size());
// if the event dispatch thread hasn't started, start it
if(mEventDispatchThread == null)
{
MethodInvoker mi = new MethodInvoker(this, "dispatchEvents");
mEventDispatchThread = mi;
mi.backgroundExecute();
}
}
}
/**
* Removes a listener.
*
* @param listener the listener to remove.
*/
public synchronized void removeListener(Object listener)
{
if(hasListener(listener))
{
// remove listener to EventProcessor mapping
mListenerToEventProcessor.remove(listener);
// if there are no more listeners, stop the event dispatch thread
if(mListenerToEventProcessor.size() == 0)
{
mEventDispatchThread.interrupt();
mEventDispatchThread = null;
}
// set the number of thread available in the process events thread pool
mProcessEventsThreadPool.setPoolSize(
Math.max(1, mListenerToEventProcessor.size()));
}
}
/**
* Returns true if the passed listener is already listening for
* events fired by this delegate, false if not.
*
* @param listener the listener to check for.
*
* @return true if the listener is already listening to this delegate,
* false if not.
*/
public synchronized boolean hasListener(Object listener)
{
boolean rval = false;
if(mListenerToEventProcessor.get(listener) != null)
{
rval = true;
}
return rval;
}
/**
* Fires an event to all listeners.
*
* @param event the event to fire.
*/
public synchronized void fireEvent(Object event)
{
// add the event to all of the event processors
for(EventProcessor ep: mListenerToEventProcessor.values())
{
ep.addEvent(event);
}
}
/**
* An EventProcessor is an object that is used to process events. Each
* EventProcessor has an associated listener object that has method(s)
* that are called to process events. Each listener object has one or
* more methods with a given method name that can be invoked and passed
* a single event object.
*
* A listener object may overload its method name for different event
* classes allowing it to use a different method implementation for each
* event type. A map is maintained that stores the pre-determined method
* that should be called for each type of event.
*
* An event queue is used to store all of the events that haven't yet been
* processed. Whenever it is time to process an event, the event is removed
* from the queue and processed via the appropriate method on the listener.
*
* Events are always processed in the same order that they are added.
*
* The EventProcessor has a flag that can be flipped externally to indicate
* that event processing has started. This is done externally so that the
* event processing can occur, whilst maintaining event order, in a separate
* process. Once processing has completed, the flag is switched back by
* the EventProcessor.
*
* @author Dave Longley
*/
public class EventProcessor
{
/**
* The listener.
*/
protected Object mListener;
/**
* The name of the listener method used to process events.
*/
protected String mMethodName;
/**
* A mapping of event class to method. This map stores pre-determined
* methods on the listener that should be called based on event type.
*/
protected HashMap<Class, Method> mEventClassToMethod;
/**
* The queue that stores the events to be processed by the listener.
*/
protected Vector<Object> mEventQueue;
/**
* Set to true if this EventProcessor is currently processing events,
* false if not.
*/
protected boolean mIsProcessing;
/**
* Creates a new EventProcessor with the given listener and method name.
*
* @param listener the listener for this event processor.
* @param methodName the name of the listener method(s) to use to
* process events.
*/
public EventProcessor(Object listener, String methodName)
{
// store listener and method name
mListener = listener;
mMethodName = methodName;
// create event class to method map
mEventClassToMethod = new HashMap<Class, Method>();
// create event queue
mEventQueue = new Vector<Object>();
// not processing
mIsProcessing = false;
}
/**
* Processes all events in the passed queue.
*
* @param queue the event queue with the events to process.
*/
protected void processEvents(Vector<Object> queue)
{
// process all of the events in the passed queue
for(Object event: queue)
{
// proceed if thread is not interrupted
if(!Thread.currentThread().isInterrupted())
{
// get the method for the event class
Class eventClass = event.getClass();
Method method = mEventClassToMethod.get(eventClass);
if(method == null)
{
// find the method
method = MethodInvoker.findMethod(
mListener, mMethodName, event);
if(method != null)
{
// add a new class to method map entry
mEventClassToMethod.put(eventClass, method);
}
}
if(method != null)
{
// process event, synchronize on the listener
MethodInvoker mi = new MethodInvoker(
mListener, method, event);
mi.execute(mListener);
}
else
{
// no appropriate method found, log error
LoggerManager.getLogger("dbevent").error(getClass(),
"could not find method '" +
MethodInvoker.getSignature(mMethodName, event) +
"' in class '" + mListener.getClass().getName() + "'");
}
}
else
{
// break, thread interrupted
break;
}
}
}
/**
* Adds an event to the event queue for processing.
*
* @param event the event to add to the event queue for processing.
*/
public void addEvent(Object event)
{
// synchronize on the event queue
synchronized(mEventQueue)
{
mEventQueue.add(event);
}
}
/**
* Processes all events in the event queue.
*/
public void processEvents()
{
// create a temporary event queue
Vector<Object> queue = new Vector<Object>();
// synchronize on the event queue
synchronized(mEventQueue)
{
// move all events into the temporary queue for processing
queue.addAll(mEventQueue);
// clear the event queue
mEventQueue.clear();
}
// process the events in the temporary queue
processEvents(queue);
// no longer processing events
mIsProcessing = false;
}
/**
* Sets whether or not this EventProcessor is processing events.
*
* @param processing true if this EventProcessor is processing events,
* false if not.
*/
public synchronized void setProcessing(boolean processing)
{
mIsProcessing = processing;
}
/**
* Returns true if this EventProcessor is currently processing events,
* false if not.
*
* @return true if this EventProcessor is currently processing events,
* false if not.
*/
public synchronized boolean isProcessing()
{
return mIsProcessing;
}
/**
* Returns true if this EventProcessor has events to process.
*
* @return true if this EventProcessor has events to process, false
* if not.
*/
public synchronized boolean hasEvents()
{
return !mEventQueue.isEmpty();
}
}
} |
package org.jboss.as.clustering.jgroups.subsystem;
import static org.jboss.as.clustering.jgroups.subsystem.TransportResourceDefinition.Attribute.DIAGNOSTICS_SOCKET_BINDING;
import static org.jboss.as.clustering.jgroups.subsystem.TransportResourceDefinition.Attribute.MACHINE;
import static org.jboss.as.clustering.jgroups.subsystem.TransportResourceDefinition.Attribute.RACK;
import static org.jboss.as.clustering.jgroups.subsystem.TransportResourceDefinition.Attribute.SITE;
import static org.jboss.as.clustering.jgroups.subsystem.TransportResourceDefinition.Attribute.SOCKET_BINDING;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.jboss.as.clustering.controller.CommonUnaryRequirement;
import org.jboss.as.clustering.jgroups.ClassLoaderThreadFactory;
import org.jboss.as.clustering.jgroups.JChannelFactory;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.network.ClientMapping;
import org.jboss.as.network.SocketBinding;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jgroups.protocols.TP;
import org.jgroups.stack.DiagnosticsHandler;
import org.jgroups.util.DefaultThreadFactory;
import org.wildfly.clustering.jgroups.spi.TransportConfiguration;
import org.wildfly.clustering.service.CompositeDependency;
import org.wildfly.clustering.service.ServiceConfigurator;
import org.wildfly.clustering.service.ServiceNameProvider;
import org.wildfly.clustering.service.ServiceSupplierDependency;
import org.wildfly.clustering.service.SimpleSupplierDependency;
import org.wildfly.clustering.service.SupplierDependency;
/**
* @author Paul Ferraro
*/
public class TransportConfigurationServiceConfigurator<T extends TP> extends AbstractProtocolConfigurationServiceConfigurator<T, TransportConfiguration<T>> implements TransportConfiguration<T> {
private final ServiceNameProvider provider;
private final SupplierDependency<ThreadPoolFactory> threadPoolFactory;
private volatile SupplierDependency<SocketBinding> socketBinding;
private volatile SupplierDependency<SocketBinding> diagnosticsSocketBinding;
private volatile Topology topology = null;
public TransportConfigurationServiceConfigurator(PathAddress address) {
super(address.getLastElement().getValue());
this.provider = new SingletonProtocolServiceNameProvider(address);
this.threadPoolFactory = new ServiceSupplierDependency<>(new ThreadPoolServiceNameProvider(address, ThreadPoolResourceDefinition.DEFAULT.getPathElement()));
}
@Override
public ServiceName getServiceName() {
return this.provider.getServiceName();
}
@Override
public TransportConfiguration<T> get() {
return this;
}
@Override
public <B> ServiceBuilder<B> register(ServiceBuilder<B> builder) {
return super.register(new CompositeDependency(this.threadPoolFactory, this.socketBinding, this.diagnosticsSocketBinding).register(builder));
}
@Override
public ServiceConfigurator configure(OperationContext context, ModelNode model) throws OperationFailedException {
this.socketBinding = new ServiceSupplierDependency<>(CommonUnaryRequirement.SOCKET_BINDING.getServiceName(context, SOCKET_BINDING.resolveModelAttribute(context, model).asString()));
String diagnosticsSocketBinding = DIAGNOSTICS_SOCKET_BINDING.resolveModelAttribute(context, model).asStringOrNull();
this.diagnosticsSocketBinding = (diagnosticsSocketBinding != null) ? new ServiceSupplierDependency<>(CommonUnaryRequirement.SOCKET_BINDING.getServiceName(context, diagnosticsSocketBinding)) : new SimpleSupplierDependency<>(null);
ModelNode machine = MACHINE.resolveModelAttribute(context, model);
ModelNode rack = RACK.resolveModelAttribute(context, model);
ModelNode site = SITE.resolveModelAttribute(context, model);
if (site.isDefined() || rack.isDefined() || machine.isDefined()) {
this.topology = new Topology() {
@Override
public String getMachine() {
return machine.asStringOrNull();
}
@Override
public String getRack() {
return rack.asStringOrNull();
}
@Override
public String getSite() {
return site.asStringOrNull();
}
};
}
return super.configure(context, model);
}
@Override
public Map<String, SocketBinding> getSocketBindings() {
Map<String, SocketBinding> bindings = new TreeMap<>();
SocketBinding binding = this.getSocketBinding();
for (String serviceName : Set.of("jgroups.udp.mcast_sock", "jgroups.udp.sock", "jgroups.tcp.server", "jgroups.nio.server", "jgroups.tunnel.ucast_sock")) {
bindings.put(serviceName, binding);
}
bindings.put("jgroups.tp.diag.mcast_sock", this.diagnosticsSocketBinding.get());
return bindings;
}
@Override
public void accept(T protocol) {
SocketBinding binding = this.getSocketBinding();
InetSocketAddress socketAddress = binding.getSocketAddress();
protocol.setBindAddress(socketAddress.getAddress());
protocol.setBindPort(socketAddress.getPort());
List<ClientMapping> clientMappings = binding.getClientMappings();
if (!clientMappings.isEmpty()) {
// JGroups cannot select a client mapping based on the source address, so just use the first one
ClientMapping mapping = clientMappings.get(0);
try {
protocol.setExternalAddr(InetAddress.getByName(mapping.getDestinationAddress()));
protocol.setExternalPort(mapping.getDestinationPort());
} catch (UnknownHostException e) {
throw new IllegalArgumentException(e);
}
}
protocol.setThreadFactory(new ClassLoaderThreadFactory(new DefaultThreadFactory("jgroups", false, true), JChannelFactory.class.getClassLoader()));
protocol.setThreadPool(this.threadPoolFactory.get().apply(protocol.getThreadFactory()));
SocketBinding diagnosticsBinding = this.diagnosticsSocketBinding.get();
if (diagnosticsBinding != null) {
DiagnosticsHandler handler = new DiagnosticsHandler(protocol.getLog(), protocol.getSocketFactory(), protocol.getThreadFactory());
InetSocketAddress address = diagnosticsBinding.getSocketAddress();
handler.setBindAddress(address.getAddress());
if (diagnosticsBinding.getMulticastAddress() != null) {
handler.setMcastAddress(diagnosticsBinding.getMulticastAddress());
handler.setPort(diagnosticsBinding.getMulticastPort());
} else {
handler.setPort(diagnosticsBinding.getPort());
}
try {
protocol.setDiagnosticsHandler(handler);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
@Override
public Topology getTopology() {
return this.topology;
}
@Override
public SocketBinding getSocketBinding() {
return this.socketBinding.get();
}
} |
package com.mongodb.rhino;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.bson.types.ObjectId;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import com.mongodb.rhino.util.JSONException;
import com.mongodb.rhino.util.JSONTokener;
/**
* Direct conversion between native Rhino objects and JSON.
* <p>
* This class can be used directly in Rhino.
*
* @author Tal Liron
*/
public class JSON
{
// Static operations
/**
* Recursively convert from JSON into native Rhino types.
* <p>
* Creates JavaScript objects, arrays and primitives.
*
* @param json
* The JSON string
* @return A Rhino object or array
* @throws JSONException
*/
public static Object from( String json ) throws JSONException
{
return from( json, false );
}
/**
* Recursively convert from JSON into native Rhino types.
* <p>
* Creates JavaScript objects, arrays and primitives.
* <p>
* Can also optionally recognize and create JavaScript date and MongoDB
* ObjectId objects.
*
* @param json
* The JSON string
* @param convertSpecial
* Whether to convert special "$" objects
* @return A Rhino object or array
* @throws JSONException
*/
public static Object from( String json, boolean convertSpecial ) throws JSONException
{
JSONTokener tokener = new JSONTokener( json );
Object object = tokener.createNative();
if( convertSpecial )
{
object = convertSpecial( object );
}
return object;
}
/**
* Recursively convert from native Rhino to JSON.
* <p>
* Recognizes JavaScript objects, arrays and primitives.
* <p>
* Special support for JavaScript dates: converts to {"$date": timestamp} in
* JSON.
* <p>
* Special support for MongoDB ObjectId: converts to {"$oid": "objectid"} in
* JSON.
* <p>
* Also recognizes JVM types: java.util.Map, java.util.Collection,
* java.util.Date.
*
* @param object
* A Rhino native object
* @return The JSON string
* @see JSON#convertSpecial(Object)
*/
public static String to( Object object )
{
return to( object, false );
}
/**
* Recursively convert from native Rhino to JSON.
* <p>
* Recognizes JavaScript objects, arrays and primitives.
* <p>
* Special support for JavaScript dates: converts to {"$date": timestamp} in
* JSON.
* <p>
* Special support for MongoDB ObjectId: converts to {"$oid": "objectid"} in
* JSON.
* <p>
* Also recognizes JVM types: java.util.Map, java.util.Collection,
* java.util.Date.
*
* @param object
* A Rhino native object
* @param indent
* Whether to indent the JSON for human readability
* @return The JSON string
*/
public static String to( Object object, boolean indent )
{
StringBuilder s = new StringBuilder();
encode( s, object, indent, indent ? 0 : -1 );
return s.toString();
}
public static Object convertSpecial( Object object )
{
if( object instanceof NativeArray )
{
NativeArray array = (NativeArray) object;
int length = (int) array.getLength();
for( int i = 0; i < length; i++ )
{
Object value = ScriptableObject.getProperty( array, i );
Object converted = convertSpecial( value );
if( converted != value )
ScriptableObject.putProperty( array, i, converted );
}
}
else if( object instanceof ScriptableObject )
{
ScriptableObject scriptable = (ScriptableObject) object;
Object oid = ScriptableObject.getProperty( scriptable, "$oid" );
if( oid != Scriptable.NOT_FOUND )
{
// Convert special $oid format to MongoDB ObjectId
return new ObjectId( oid.toString() );
}
Object date = ScriptableObject.getProperty( scriptable, "$date" );
if( date != Scriptable.NOT_FOUND )
{
// Convert special $date format to Rhino date
// (The NativeDate class is private in Rhino, but we can access
// it like a regular object.)
Context context = Context.getCurrentContext();
Scriptable scope = ScriptRuntime.getTopCallScope( context );
Scriptable nativeDate = context.newObject( scope, "Date", new Object[]
{
date
} );
return nativeDate;
}
Object[] ids = scriptable.getAllIds();
for( Object id : ids )
{
String key = id.toString();
Object value = ScriptableObject.getProperty( scriptable, key );
Object converted = convertSpecial( value );
if( converted != value )
ScriptableObject.putProperty( scriptable, key, converted );
}
}
return object;
}
// Private
private static void encode( StringBuilder s, Object object, boolean indent, int depth )
{
if( indent )
indent( s, depth );
if( object == null )
{
s.append( "null" );
}
else if( object instanceof Number )
{
s.append( object );
}
else if( object instanceof Boolean )
{
s.append( object );
}
else if( object instanceof Date )
{
HashMap<String, Long> map = new HashMap<String, Long>();
map.put( "$date", ( (Date) object ).getTime() );
encode( s, map, depth );
}
else if( object instanceof ObjectId )
{
HashMap<String, String> map = new HashMap<String, String>();
map.put( "$oid", ( (ObjectId) object ).toStringMongod() );
encode( s, map, depth );
}
else if( object instanceof Collection )
{
encode( s, (Collection<?>) object, depth );
}
else if( object instanceof Map )
{
encode( s, (Map<?, ?>) object, depth );
}
else if( object instanceof NativeArray )
{
encode( s, (NativeArray) object, depth );
}
else if( object instanceof ScriptableObject )
{
ScriptableObject scriptable = (ScriptableObject) object;
if( scriptable.getClassName().equals( "Date" ) )
{
// (The NativeDate class is private in Rhino, but we can access
// it like a regular object.)
Object time = ScriptableObject.callMethod( scriptable, "getTime", null );
if( time instanceof Number )
{
encode( s, new Date( ( (Number) time ).longValue() ), false, depth );
return;
}
}
encode( s, scriptable, depth );
}
else
{
s.append( '\"' );
s.append( escape( object.toString() ) );
s.append( '\"' );
}
}
private static void encode( StringBuilder s, Collection<?> collection, int depth )
{
s.append( '[' );
Iterator<?> i = collection.iterator();
if( i.hasNext() )
{
if( depth > -1 )
s.append( '\n' );
while( true )
{
Object value = i.next();
encode( s, value, true, depth > -1 ? depth + 1 : -1 );
if( i.hasNext() )
{
s.append( ',' );
if( depth > -1 )
s.append( '\n' );
}
else
break;
}
if( depth > -1 )
s.append( '\n' );
}
if( depth > -1 )
indent( s, depth );
s.append( ']' );
}
private static void encode( StringBuilder s, Map<?, ?> map, int depth )
{
s.append( '{' );
Iterator<?> i = map.entrySet().iterator();
if( i.hasNext() )
{
if( depth > -1 )
s.append( '\n' );
while( true )
{
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) i.next();
String key = entry.getKey().toString();
Object value = entry.getValue();
if( depth > -1 )
indent( s, depth + 1 );
s.append( '\"' );
s.append( escape( key ) );
s.append( "\":" );
if( depth > -1 )
s.append( ' ' );
encode( s, value, false, depth > -1 ? depth + 1 : -1 );
if( i.hasNext() )
{
s.append( ',' );
if( depth > -1 )
s.append( '\n' );
}
else
break;
}
if( depth > -1 )
s.append( '\n' );
}
if( depth > -1 )
indent( s, depth );
s.append( '}' );
}
private static void encode( StringBuilder s, NativeArray array, int depth )
{
s.append( '[' );
long length = array.getLength();
if( length > 0 )
{
if( depth > -1 )
s.append( '\n' );
for( int i = 0; i < length; i++ )
{
Object value = ScriptableObject.getProperty( array, i );
encode( s, value, true, depth > -1 ? depth + 1 : -1 );
if( i < length - 1 )
{
s.append( ',' );
if( depth > -1 )
s.append( '\n' );
}
}
if( depth > -1 )
s.append( '\n' );
}
if( depth > -1 )
indent( s, depth );
s.append( ']' );
}
private static void encode( StringBuilder s, ScriptableObject object, int depth )
{
s.append( '{' );
Object[] ids = object.getAllIds();
if( ids.length > 0 )
{
if( depth > -1 )
s.append( '\n' );
int length = ids.length;
for( int i = 0; i < length; i++ )
{
String key = ids[i].toString();
Object value = ScriptableObject.getProperty( object, key );
if( depth > -1 )
indent( s, depth + 1 );
s.append( '\"' );
s.append( escape( key ) );
s.append( "\":" );
if( depth > -1 )
s.append( ' ' );
encode( s, value, false, depth > -1 ? depth + 1 : -1 );
if( i < length - 1 )
{
s.append( ',' );
if( depth > -1 )
s.append( '\n' );
}
}
if( depth > -1 )
s.append( '\n' );
}
if( depth > -1 )
indent( s, depth );
s.append( '}' );
}
private static void indent( StringBuilder s, int depth )
{
for( int i = 0; i < depth; i++ )
s.append( " " );
}
private static String escape( String string )
{
string = string.replaceAll( "\\\\", "\\\\\\" );
string = string.replaceAll( "\\n", "\\\\n" );
string = string.replaceAll( "\\r", "\\\\r" );
string = string.replaceAll( "\\\"", "\\\\\"" );
return string;
}
} |
package forklift.consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.jms.JMSException;
import javax.jms.Message;
import forklift.classloader.RunAsClassLoader;
public class MessageRunnable implements Runnable {
private static final Logger log = LoggerFactory.getLogger(MessageRunnable.class);
private Message jmsMsg;
private ClassLoader classLoader;
private Object handler;
private List<Method> onMessage;
private List<Method> onValidate;
MessageRunnable(Message jmsMsg, ClassLoader classLoader, Object handler, List<Method> onMessage, List<Method> onValidate) {
this.jmsMsg = jmsMsg;
this.classLoader = classLoader;
if (this.classLoader == null)
this.classLoader = Thread.currentThread().getContextClassLoader();
this.handler = handler;
this.onMessage = onMessage;
this.onValidate = onValidate;
}
@Override
public void run() {
RunAsClassLoader.run(classLoader, () -> {
try {
boolean error = false;
final List<String> allErrors = new ArrayList<>();
try {
// Validate the class.
for (Method m : onValidate) {
if (m.getReturnType() == List.class) {
allErrors.addAll((List<String>)m.invoke(handler));
} else if (m.getReturnType() == Boolean.class) {
error = error || !((Boolean)m.invoke(handler)).booleanValue();
} else {
allErrors.add("Return type of " + m.getReturnType() + " is not supported for OnValidate methods");
error = true;
}
if (error || allErrors.size() > 0)
error = true;
}
// Run the message if there are no errors.
if (!error) {
for (Method m : onMessage) {
// Send the message to each handler.
m.invoke(handler, new Object[] {});
}
}
} catch (Throwable e) {
error = true;
allErrors.add(e.getMessage());
}
if (error) {
// TODO audit all errors
}
} finally {
// We've done all we can do to process this message, ack it from the queue, and move forward.
try {
jmsMsg.acknowledge();
} catch (JMSException e) {
}
}
});
}
} |
package com.gdxjam.ai.formation;
import com.badlogic.gdx.ai.fma.FormationMember;
import com.badlogic.gdx.ai.fma.SoftRoleSlotAssignmentStrategy.SlotCostProvider;
import com.badlogic.gdx.math.Vector2;
import com.gdxjam.components.Components;
import com.gdxjam.components.SquadComponent;
import com.gdxjam.components.SquadMemberComponent;
public class DistanceSlotCostProvider implements SlotCostProvider<Vector2> {
@Override
public float getCost(FormationMember<Vector2> member, int slotNumber) {
SquadMemberComponent squadMemberComp = (SquadMemberComponent) member;
SquadComponent squadComp = Components.SQUAD.get(squadMemberComp.squad);
Vector2 targetPosition = squadComp.formation.getSlot(slotNumber).member.getTargetLocation().getPosition();
// The cost is the square distance between current position and target position
return squadMemberComp.body.getPosition().dst2(targetPosition);
}
} |
package org.lwjgl.demo.stb;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.*;
import org.lwjgl.openal.AL;
import org.lwjgl.openal.ALContext;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GLUtil;
import org.lwjgl.stb.STBVorbisInfo;
import org.lwjgl.system.libffi.Closure;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import static java.lang.Math.*;
import static org.lwjgl.demo.util.IOUtil.*;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.openal.AL10.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.stb.STBEasyFont.*;
import static org.lwjgl.stb.STBVorbis.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* STB Vorbis demo.
*
* <p>Playback will pause while handling window events. In a real application, this can be fixed by running the decoder in a different thread.</p>
*/
public final class Vorbis {
private Vorbis() {
}
public static void main(String[] args) {
String filePath;
if ( args.length == 0 ) {
System.out.println("Use 'ant demo -Dclass=org.lwjgl.demo.stb.Vorbis -Dargs=<path>' to load a different Ogg Vorbis file.\n");
filePath = "demo/phero.ogg";
} else
filePath = args[0];
ALContext al = ALContext.create();
int source = alGenSources();
IntBuffer buffers = BufferUtils.createIntBuffer(2);
alGenBuffers(buffers);
Decoder decoder = null;
Renderer renderer = null;
try {
decoder = new Decoder(filePath);
renderer = new Renderer(decoder, "STB Vorbis Demo");
long window = renderer.window;
if ( !decoder.play(source, buffers) ) {
System.err.println("Playback failed.");
glfwSetWindowShouldClose(window, GL_TRUE);
}
while ( glfwWindowShouldClose(window) == GL_FALSE ) {
if ( !renderer.paused && !decoder.update(source, true) ) {
System.err.println("Playback failed.");
glfwSetWindowShouldClose(window, GL_TRUE);
}
float progress = decoder.getProgress();
float time = decoder.getProgressTime(progress);
renderer.render(progress, time);
}
} finally {
if ( renderer != null )
renderer.destroy();
if ( decoder != null )
stb_vorbis_close(decoder.handle);
alDeleteBuffers(buffers);
alDeleteSources(source);
AL.destroy(al);
}
}
private static class Decoder {
private static final int BUFFER_SIZE = 1024 * 4;
final ByteBuffer vorbis;
final long handle;
final int channels;
final int sampleRate;
final int format;
final int lengthSamples;
final float lengthSeconds;
final ByteBuffer pcm;
int samplesLeft;
Decoder(String filePath) {
try {
vorbis = ioResourceToByteBuffer(filePath, 256 * 1024);
} catch (IOException e) {
throw new RuntimeException(e);
}
IntBuffer error = BufferUtils.createIntBuffer(1);
handle = stb_vorbis_open_memory(vorbis, error, null);
if ( handle == NULL )
throw new RuntimeException("Failed to open Ogg Vorbis file. Error: " + error.get(0));
STBVorbisInfo info = Decoder.getInfo(handle);
this.channels = info.getChannels();
this.sampleRate = info.getSampleRate();
this.format = getFormat(channels);
this.lengthSamples = stb_vorbis_stream_length_in_samples(handle);
this.lengthSeconds = stb_vorbis_stream_length_in_seconds(handle);
this.pcm = BufferUtils.createByteBuffer(BUFFER_SIZE * 2);
samplesLeft = lengthSamples;
}
private static STBVorbisInfo getInfo(long decoder) {
System.out.println("stream length, samples: " + stb_vorbis_stream_length_in_samples(decoder));
System.out.println("stream length, seconds: " + stb_vorbis_stream_length_in_seconds(decoder));
System.out.println();
STBVorbisInfo info = new STBVorbisInfo();
stb_vorbis_get_info(decoder, info.buffer());
System.out.println("channels = " + info.getChannels());
System.out.println("sampleRate = " + info.getSampleRate());
System.out.println("maxFrameSize = " + info.getMaxFrameSize());
System.out.println("setupMemoryRequired = " + info.getSetupMemoryRequired());
System.out.println("setupTempMemoryRequired() = " + info.getSetupTempMemoryRequired());
System.out.println("tempMemoryRequired = " + info.getTempMemoryRequired());
return info;
}
private static int getFormat(int channels) {
switch ( channels ) {
case 1:
return AL_FORMAT_MONO16;
case 2:
return AL_FORMAT_STEREO16;
default:
throw new UnsupportedOperationException("Unsupported number of channels: " + channels);
}
}
private boolean stream(int buffer) {
int samples = 0;
while ( samples < BUFFER_SIZE ) {
pcm.position(samples * 2);
int samplesPerChannel = stb_vorbis_get_samples_short_interleaved(handle, channels, pcm, BUFFER_SIZE - samples);
if ( samplesPerChannel == 0 )
break;
samples += samplesPerChannel * channels;
}
if ( samples == 0 )
return false;
pcm.position(0);
alBufferData(buffer, format, pcm, samples * 2, sampleRate);
samplesLeft -= samples / channels;
return true;
}
float getProgress() {
return 1.0f - samplesLeft / (float)(lengthSamples);
}
float getProgressTime(float progress) {
return progress * lengthSeconds;
}
void rewind() {
stb_vorbis_seek_start(handle);
samplesLeft = lengthSamples;
}
void skip(int direction) {
seek(min(max(0, stb_vorbis_get_sample_offset(handle) + direction * sampleRate), lengthSamples));
}
void skipTo(float offset0to1) {
seek(round(lengthSamples * offset0to1));
}
private void seek(int sample_number) {
stb_vorbis_seek(handle, sample_number);
samplesLeft = lengthSamples - sample_number;
}
boolean play(int source, IntBuffer buffers) {
for ( int i = 0; i < buffers.limit(); i++ ) {
if ( !stream(buffers.get(i)) )
return false;
}
alSourceQueueBuffers(source, buffers);
alSourcePlay(source);
return true;
}
boolean update(int source, boolean loop) {
int processed = alGetSourcei(source, AL_BUFFERS_PROCESSED);
for ( int i = 0; i < processed; i++ ) {
int buffer = alSourceUnqueueBuffers(source);
if ( !stream(buffer) ) {
boolean shouldExit = true;
if ( loop ) {
rewind();
shouldExit = !stream(buffer);
}
if ( shouldExit )
return false;
}
alSourceQueueBuffers(source, buffer);
}
if ( processed == 2 )
alSourcePlay(source);
return true;
}
}
private static class Renderer {
private static final int WIDTH = 640;
private static final int HEIGHT = 320;
private final GLFWErrorCallback errorCallback;
private final GLFWFramebufferSizeCallback framebufferSizeCallback;
private final GLFWKeyCallback keyCallback;
private final GLFWCursorPosCallback cursorPosCallback;
private final GLFWMouseButtonCallback mouseButtonCallback;
private final Closure debugProc;
private final long window;
private final ByteBuffer charBuffer;
private boolean paused;
private double cursorX, cursorY;
private boolean buttonPressed;
Renderer(final Decoder decoder, String title) {
glfwSetCallback(errorCallback = errorCallbackPrint(System.err));
if ( glfwInit() != GL11.GL_TRUE )
throw new IllegalStateException("Unable to initialize GLFW");
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
window = glfwCreateWindow(WIDTH, HEIGHT, title, NULL, NULL);
if ( window == NULL )
throw new RuntimeException("Failed to create the GLFW window");
glfwSetCallback(window, framebufferSizeCallback = new GLFWFramebufferSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
glViewport(0, 0, width, height);
}
});
glfwSetCallback(window, keyCallback = new GLFWKeyCallback() {
@Override
public void invoke(long window, int key, int scancode, int action, int mods) {
if ( action == GLFW_RELEASE )
return;
switch ( key ) {
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GL_TRUE);
break;
case GLFW_KEY_HOME:
decoder.rewind();
break;
case GLFW_KEY_LEFT:
decoder.skip(-1);
break;
case GLFW_KEY_RIGHT:
decoder.skip(1);
break;
case GLFW_KEY_SPACE:
paused = !paused;
break;
}
}
});
glfwSetCallback(window, mouseButtonCallback = new GLFWMouseButtonCallback() {
@Override
public void invoke(long window, int button, int action, int mods) {
if ( button != GLFW_MOUSE_BUTTON_LEFT )
return;
buttonPressed = action == GLFW_PRESS;
if ( !buttonPressed )
return;
seek(decoder);
}
});
glfwSetCallback(window, cursorPosCallback = new GLFWCursorPosCallback() {
@Override
public void invoke(long window, double xpos, double ypos) {
cursorX = xpos - WIDTH * 0.5f;
cursorY = ypos - HEIGHT * 0.5f;
if ( buttonPressed )
seek(decoder);
}
});
// Center window
GLFWvidmode vidmode = new GLFWvidmode(glfwGetVideoMode(glfwGetPrimaryMonitor()));
glfwSetWindowPos(
window,
(vidmode.getWidth() - WIDTH) / 2,
(vidmode.getHeight() - HEIGHT) / 2
);
// Create context
glfwMakeContextCurrent(window);
GL.createCapabilities();
debugProc = GLUtil.setupDebugMessageCallback();
glfwSwapInterval(1);
glfwShowWindow(window);
glfwInvoke(window, null, framebufferSizeCallback);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
charBuffer = BufferUtils.createByteBuffer(256 * 270);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 16, charBuffer);
glClearColor(43f / 255f, 43f / 255f, 43f / 255f, 0f); // BG color
}
private void seek(Decoder decoder) {
if ( cursorX < -254.0 || 254.0 < cursorX )
return;
if ( cursorY < -30.0 || 30.0 < cursorY )
return;
decoder.skipTo((float)((cursorX + 254.0) / 508.0));
}
void render(float progress, float time) {
glfwPollEvents();
glClear(GL_COLOR_BUFFER_BIT);
// Progress bar
glPushMatrix();
glTranslatef(WIDTH * 0.5f, HEIGHT * 0.5f, 0.0f);
glBegin(GL_QUADS);
{
glColor3f(0.5f * 43f / 255f, 0.5f * 43f / 255f, 0.5f * 43f / 255f);
glVertex2f(-256.0f, -32.0f);
glVertex2f(256.0f, -32.0f);
glVertex2f(256.0f, 32.0f);
glVertex2f(-256.0f, 32.0f);
glColor3f(0.5f, 0.5f, 0.0f);
glVertex2f(-254.0f, -30.0f);
glVertex2f(-254.0f + progress * 508.0f, -30.0f);
glVertex2f(-254.0f + progress * 508.0f, 30.0f);
glVertex2f(-254.0f, 30.0f);
}
glEnd();
glPopMatrix();
glColor3f(169f / 255f, 183f / 255f, 198f / 255f); // Text color
// Progress text
int minutes = (int)floor(time / 60.0f);
int seconds = (int)floor((time - minutes * 60.0f));
int quads = stb_easy_font_print(WIDTH * 0.5f - 13, HEIGHT * 0.5f - 4, String.format("%02d:%02d", minutes, seconds), null, charBuffer);
glDrawArrays(GL_QUADS, 0, quads * 4);
// HUD
quads = stb_easy_font_print(4, 4, "Press HOME to rewind", null, charBuffer);
glDrawArrays(GL_QUADS, 0, quads * 4);
quads = stb_easy_font_print(4, 20, "Press LEFT/RIGHT or LMB to seek", null, charBuffer);
glDrawArrays(GL_QUADS, 0, quads * 4);
quads = stb_easy_font_print(4, 36, "Press SPACE to pause/resume", null, charBuffer);
glDrawArrays(GL_QUADS, 0, quads * 4);
glfwSwapBuffers(window);
}
void destroy() {
glfwDestroyWindow(window);
if ( debugProc != null )
debugProc.release();
releaseAllCallbacks(window);
glfwTerminate();
errorCallback.release();
}
}
} |
package hudson.widgets;
import jenkins.model.Jenkins;
import hudson.model.Queue.Item;
import hudson.model.Queue.Task;
import java.util.LinkedList;
import java.util.List;
/**
* Displays the build history on the side panel.
*
* <p>
* This widget enhances {@link HistoryWidget} by groking the notion
* that {@link #owner} can be in the queue toward the next build.
*
* @author Kohsuke Kawaguchi
*/
public class BuildHistoryWidget<T> extends HistoryWidget<Task,T> {
/**
* @param owner
* The parent model object that owns this widget.
*/
public BuildHistoryWidget(Task owner, Iterable<T> baseList,Adapter<? super T> adapter) {
super(owner,baseList, adapter);
}
/**
* Returns the first queue item if the owner is scheduled for execution in the queue.
*/
public Item getQueuedItem() {
return Jenkins.getInstance().getQueue().getItem(owner);
}
/**
* Returns the queue item if the owner is scheduled for execution in the queue, in REVERSE ORDER
*/
public List<Item> getQueuedItems() {
LinkedList<Item> list = new LinkedList<Item>();
for (Item item : Jenkins.getInstance().getQueue().getApproximateItemsQuickly()) {
if (item.task == owner) {
list.addFirst(item);
}
}
return list;
}
} |
package org.sikuli.script;
import org.junit.* ;
import static org.junit.Assert.* ;
import java.util.List;
import java.io.*;
public class VDictTest
{
@Test
public void test_vdict_init()
{
VDictProxy dict = new VDictProxy();
assertTrue(dict.size() == 0);
assertTrue(dict.empty() == true);
}
@Test(expected=FileNotFoundException.class)
public void test_vdict_insert_not_exist_file() throws FileNotFoundException
{
VDictProxy dict = new VDictProxy();
dict.insert("not-exist-file.png", 1);
}
@Test
public void test_vdict_insert() throws FileNotFoundException
{
VDictProxy<Integer> dict = new VDictProxy();
assertTrue(dict.size() == 0);
assertTrue(dict.empty() == true);
dict.insert("test-res/1.png", 100);
assertTrue(dict.size() == 1);
assertTrue(dict.empty() == false);
int val = dict.lookup("test-res/1.png" );
assertTrue(val == 100);
}
@Test
public void test_vdict_lookup() throws FileNotFoundException
{
VDictProxy<Integer> dict = new VDictProxy();
dict.insert("test-res/1.png", 100);
Integer val = dict.lookup("test-res/2.png" );
assertTrue(val == null);
assertTrue(dict.lookup_similar("test-res/1.png", 0.8) == 100 );
}
@Test
public void test_vdict_lookup_obj() throws FileNotFoundException
{
VDictProxy<String> dict = new VDictProxy();
dict.insert("test-res/1.png", "hello world");
String r = dict.lookup_similar("test-res/1.png", 0.8);
assertEquals(r, "hello world");
}
@Test
public void test_vdict_erase() throws FileNotFoundException
{
VDictProxy<Integer> dict = new VDictProxy();
dict.insert("test-res/1.png", 100);
assertTrue(dict.lookup_similar("test-res/1.png", 0.8) == 100 );
dict.erase("test-res/1.png");
assertTrue(dict.size() == 0);
assertTrue(dict.lookup_similar("test-res/1.png", 0.8) == null );
}
@Test
public void test_vdict_lookup_n() throws FileNotFoundException
{
VDictProxy<Integer> dict = new VDictProxy();
dict.insert("test-res/1.png", 1);
dict.insert("test-res/2a.png", 2);
dict.insert("test-res/2b.png", 3);
List<Integer> vals;
assertTrue(dict.lookup_similar_n("test-res/big.png", 0.8, 1).size()==0);
assertTrue(dict.lookup_similar_n("test-res/2.png", 0.8, 1).size()==1);
vals = dict.lookup_similar_n("test-res/2.png", 0.8, 2);
assertTrue(vals.size()==2);
assertTrue(vals.get(0) == 2);
assertTrue(vals.get(1) == 3);
vals = dict.lookup_similar_n("test-res/2.png", 0.8, 0);//all
assertTrue(vals.size()==2);
assertTrue(vals.get(0) == 2);
assertTrue(vals.get(1) == 3);
}
} |
package com.arinerron.forux.core;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Window {
private Game game = null;
protected JFrame frame = null;
private List<Screen> screens = new ArrayList<>();
private Dimension frameSize = new Dimension(20, 20);
private BufferedImage image = null;
private int fps = 20;
private JPanel panel;
private int currentScreen = -1;
protected Window(Game game) {
this.game = game;
this.frame = new JFrame(this.getGame().getName());
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.setBackground(Color.BLACK);
this.frame.setLocationRelativeTo(null);
// this.fps = ((1000 / this.getGame().getSettings().getInt("max_fps")));
this.panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
if(Window.this.getImage() != null)
g.drawImage(Window.this.getImage(), 0, 0, null); // later: center and size the image properly.
}
};
this.frame.add(panel);
Screen screen = new Screen(this) {
public void onDraw(Graphics g) {}
public void onStart() {}
public void onStop() {}
};
this.addScreen(screen);
this.currentScreen = 0; // black screen
}
public Game getGame() {
return this.game;
}
public void setVisible(boolean visible) { // will start game if !running
if(!this.getGame().isRunning())
this.getGame().start();
this.frame.setVisible(visible);
}
public void setSize(int width, int height) {
panel.setPreferredSize(new Dimension(width, height));
this.frame.pack();
}
public void setFullscreen(boolean fullscreen) {
if (fullscreen)
this.frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
else
this.frame.setExtendedState(JFrame.NORMAL);
}
public void setLocation(int x, int y) {
this.frame.setLocation(x, y);
}
public void setFrameSize(int width, int height) {
this.frameSize = new Dimension(width, height);
}
protected void setImage(BufferedImage image) {
boolean update = this.getImage() == image;
this.image = image;
if(update)
panel.repaint();
}
public boolean addScreen(Screen screen) {
if(!this.getScreens().contains(screen)) {
screen.setID(this.getScreens().size());
this.screens.add(screen);
return true;
}
return false;
}
public boolean removeScreen(Screen screen) {
if(this.getScreens().contains(screen)) {
this.screens.remove(screen);
return true;
}
return false;
}
public boolean removeScreen(int id) {
Screen remove = null;
for(Screen screen : this.getScreens())
if(screen.getID() == id)
remove = screen;
if(remove != null) {
this.screens.remove(remove);
return true;
}
return false;
}
/*
* Later:
* public void getScreen(int id);
*
*/
public int getScreenCount() {
return this.getScreens().size();
}
public Screen getCurrentScreen() {
return this.getScreens().get(this.currentScreen);
}
public boolean setCurrentScreen(Screen screen) {
return setCurrentScreen(screen.getID());
}
public boolean setCurrentScreen(int id) {
for(int i = 0; i < this.getScreens().size(); i++)
if(this.getScreens().get(i).getID() == id) {
this.getCurrentScreen().onStop();
this.currentScreen = i;
this.getGame().getClock().index();
this.getCurrentScreen().onStart();
this.getGame().getEventHandler().onScreenSet(this.getScreens().get(i));
return true;
}
return false;
}
public boolean isVisible() {
return this.frame.isVisible();
}
public Dimension getSize() {
return this.frame.getSize();
}
public boolean isFullscreen() {
return this.frame.getExtendedState() == JFrame.MAXIMIZED_BOTH;
}
public Point getLocation() {
return this.frame.getLocation();
}
public List<Screen> getScreens() {
return this.screens;
}
public Dimension getFrameSize() {
return this.frameSize;
}
public BufferedImage getImage() {
return this.image;
}
} |
package org.commcare.xml;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.commcare.suite.model.ComputedDatum;
import org.commcare.suite.model.EntityDatum;
import org.commcare.suite.model.FormIdDatum;
import org.commcare.suite.model.QueryPrompt;
import org.commcare.suite.model.RemoteQueryDatum;
import org.commcare.suite.model.SessionDatum;
import org.javarosa.core.util.OrderedHashtable;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.javarosa.xpath.XPathParseTool;
import org.javarosa.xpath.expr.XPathExpression;
import org.javarosa.xpath.parser.XPathSyntaxException;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* @author ctsims
*/
public class SessionDatumParser extends CommCareElementParser<SessionDatum> {
public SessionDatumParser(KXmlParser parser) {
super(parser);
}
@Override
public SessionDatum parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException {
if ("query".equals(parser.getName())) {
return parseRemoteQueryDatum();
}
if ((!"datum".equals(this.parser.getName())) && !("form".equals(this.parser.getName()))) {
throw new InvalidStructureException("Expected <datum> or <form> data in <session> block, instead found " + this.parser.getName() + ">", this.parser);
}
String id = parser.getAttributeValue(null, "id");
String calculate = parser.getAttributeValue(null, "function");
SessionDatum datum;
if (calculate == null) {
String nodeset = parser.getAttributeValue(null, "nodeset");
String shortDetail = parser.getAttributeValue(null, "detail-select");
String longDetail = parser.getAttributeValue(null, "detail-confirm");
String inlineDetail = parser.getAttributeValue(null, "detail-inline");
String persistentDetail = parser.getAttributeValue(null, "detail-persistent");
String value = parser.getAttributeValue(null, "value");
String autoselect = parser.getAttributeValue(null, "autoselect");
if (nodeset == null) {
throw new InvalidStructureException("Expected @nodeset in " + id + " <datum> definition", this.parser);
}
datum = new EntityDatum(id, nodeset, shortDetail, longDetail, inlineDetail,
persistentDetail, value, autoselect);
} else {
if ("form".equals(this.parser.getName())) {
datum = new FormIdDatum(calculate);
} else {
datum = new ComputedDatum(id, calculate);
}
}
while (parser.next() == KXmlParser.TEXT) ;
return datum;
}
private RemoteQueryDatum parseRemoteQueryDatum()
throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException {
OrderedHashtable<String, QueryPrompt> userQueryPrompts = new OrderedHashtable<>();
this.checkNode("query");
// The 'template' argument specifies whether the query result should follow a specific xml structure.
// Currently only 'case' is supported; asserting the casedb xml structure
String xpathTemplateType = parser.getAttributeValue(null, "template");
boolean useCaseTemplate = "case".equals(xpathTemplateType);
String queryUrlString = parser.getAttributeValue(null, "url");
String queryResultStorageInstance = parser.getAttributeValue(null, "storage-instance");
if (queryUrlString == null || queryResultStorageInstance == null) {
String errorMsg = "<query> element missing 'url' or 'storage-instance' attribute";
throw new InvalidStructureException(errorMsg, parser);
}
URL queryUrl;
try {
queryUrl = new URL(queryUrlString);
} catch (MalformedURLException e) {
String errorMsg =
"<query> element has invalid 'url' attribute (" + queryUrlString + ").";
throw new InvalidStructureException(errorMsg, parser);
}
boolean defaultSearch = "true".equals(parser.getAttributeValue(null, "default_search"));
Multimap<String, XPathExpression> hiddenQueryValues = ArrayListMultimap.create();
while (nextTagInBlock("query")) {
String tagName = parser.getName();
if ("data".equals(tagName)) {
hiddenQueryValues.putAll(parseQueryData());
} else if ("prompt".equals(tagName)) {
String key = parser.getAttributeValue(null, "key");
userQueryPrompts.put(key, new QueryPromptParser(parser).parse());
}
}
return new RemoteQueryDatum(queryUrl, queryResultStorageInstance,
hiddenQueryValues, userQueryPrompts, useCaseTemplate, defaultSearch);
}
private Multimap<String, XPathExpression> parseQueryData() throws InvalidStructureException {
String tagName = parser.getName();
if (!"data".equals(tagName)) {
throw new InvalidStructureException("Expected a 'data' element", this.parser);
}
Multimap<String, XPathExpression> hiddenQueryValues = ArrayListMultimap.create();
String key = parser.getAttributeValue(null, "key");
String ref = parser.getAttributeValue(null, "ref");
try {
hiddenQueryValues.put(key, XPathParseTool.parseXPath(ref));
} catch (XPathSyntaxException e) {
String errorMessage = "'ref' value is not a valid xpath expression: " + ref;
throw new InvalidStructureException(errorMessage, this.parser);
}
return hiddenQueryValues;
}
} |
package org.deviceconnect.android.deviceplugin.sphero;
import android.app.Service;
import org.deviceconnect.android.message.DConnectMessageServiceProvider;
/**
* SpheroService.
*
* @param <T> Service
* @author NTT DOCOMO, INC.
*/
public class SpheroDeviceProvider<T extends Service> extends DConnectMessageServiceProvider<Service> {
@SuppressWarnings("unchecked")
@Override
protected Class<Service> getServiceClass() {
Class<? extends Service> clazz = (Class<? extends Service>) SpheroDeviceService.class;
return (Class<Service>) clazz;
}
} |
package org.bitcoinj.core;
import org.bitcoinj.store.FlatDB;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.OutputStream;
import static com.google.common.base.Preconditions.checkState;
public abstract class AbstractManager extends Message {
private static final Logger log = LoggerFactory.getLogger(AbstractManager.class);
/**
* The Context.
*/
protected Context context;
/**
* The Default file name.
* The default value is the name of the derived class + ".dat"
*/
protected String defaultFileName;
/**
* The Default magic message.
* The default value is the name of the derived class.
*/
protected String defaultMagicMessage;
/**
* The Magic message.
* The default value is the name of the derived class.
*/
protected String magicMessage;
/**
* The Format version. The default value is 1.
*/
protected int formatVersion;
/**
* The constant defaultExtension.
*/
public static String defaultExtension = ".dat";
/**
* The Filename.
*/
public String filename;
/**
* Instantiates a new AbstractManager.
*
* @param context the context
*/
public AbstractManager(Context context) {
super(context.getParams());
this.context = context;
this.formatVersion = 1;
String fullClassName = this.getClass().getCanonicalName();
this.defaultMagicMessage = fullClassName.substring(fullClassName.lastIndexOf('.')+1);
this.magicMessage = defaultMagicMessage;
this.defaultFileName = this.magicMessage.toLowerCase() + defaultExtension;
}
/**
* Instantiates a new Abstract manager.
*
* @param params the params
* @param payload the payload
* @param cursor the cursor
*/
public AbstractManager(NetworkParameters params, byte [] payload, int cursor) {
super(params, payload, cursor);
this.context = Context.get();
this.formatVersion = 1;
String fullClassName = this.getClass().getCanonicalName();
this.defaultMagicMessage = fullClassName.substring(fullClassName.lastIndexOf('.')+1);
this.magicMessage = defaultMagicMessage;
this.defaultFileName = fullClassName + defaultExtension;
}
/**
* Calculates size in bytes of this object.
*
* @return the size
*/
public abstract int calculateMessageSizeInBytes();
/**
* Check and remove. Called to check the validity of all objects
* and remove the expired objects.
*/
public abstract void checkAndRemove();
/**
* Clear. Removes all objects and settings.
*/
public abstract void clear();
/**
* Loads a payload into the object
*
* @param payload the payload
* @param offset the offset
*/
public void load(byte [] payload, int offset)
{
this.protocolVersion = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT);
this.payload = payload;
this.cursor = this.offset = offset;
this.length = payload.length;
if (this.length == UNKNOWN_LENGTH)
checkState(false, "Length field has not been set in constructor for %s after %s parse. " +
"Refer to Message.parseLite() for detail of required Length field contract.",
getClass().getSimpleName(), /*parseLazy ? "lite" :*/ "full");
parse();
}
/**
* Create empty abstract manager.
*
* @return the abstract manager
*/
public abstract AbstractManager createEmpty();
/**
* Gets default file name.
*
* @return the default file name
*/
public String getDefaultFileName() {
return defaultFileName;
}
/**
* Gets magic message with the version number.
*
* @return the magic message
*/
public String getMagicMessage() {
return magicMessage + "-" + formatVersion;
}
/**
* Gets default magic message.
*
* @return the default magic message
*/
public String getDefaultMagicMessage() { return defaultMagicMessage; }
/**
* Gets format version.
*
* @return the format version
*/
public int getFormatVersion() {
return formatVersion;
}
/**
* Save.
*
* @throws NullPointerException the null pointer exception
*/
public void save() throws NullPointerException {
if(filename != null) {
//save in a separate thread
new Thread(new Runnable() {
@Override
public void run() {
long start = Utils.currentTimeMillis();
FlatDB<AbstractManager> flatDB = new FlatDB<AbstractManager>(context, filename, true);
flatDB.dump(AbstractManager.this);
long end = Utils.currentTimeMillis();
log.info(AbstractManager.class.getCanonicalName() + " Save time: " + (end - start) + "ms");
}
}).start();
} else throw new NullPointerException("filename is not set");
}
/**
* Sets filename to which the object data will be saved.
*
* @param filename the filename
*/
public void setFilename(String filename) {
this.filename = filename;
}
} |
package com.jetbrains.jsonSchema;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.json.JsonFileType;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.ZipperUpdater;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileContentsChangedAdapter;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.impl.BulkVirtualFileListenerAdapter;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiTreeAnyChangeAbstractAdapter;
import com.intellij.util.Alarm;
import com.intellij.util.concurrency.SequentialTaskExecutor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.messages.Topic;
import com.jetbrains.jsonSchema.ide.JsonSchemaService;
import com.jetbrains.jsonSchema.impl.JsonSchemaServiceImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.ExecutorService;
/**
* @author Irina.Chernushina on 3/30/2016.
*/
public class JsonSchemaVfsListener extends BulkVirtualFileListenerAdapter {
public static final Topic<Runnable> JSON_SCHEMA_CHANGED = Topic.create("JsonSchemaVfsListener.Json.Schema.Changed", Runnable.class);
public static final Topic<Runnable> JSON_DEPS_CHANGED = Topic.create("JsonSchemaVfsListener.Json.Deps.Changed", Runnable.class);
public static void startListening(@NotNull Project project, @NotNull JsonSchemaService service, @NotNull MessageBusConnection connection) {
final MyUpdater updater = new MyUpdater(project, service);
connection.subscribe(VirtualFileManager.VFS_CHANGES, new JsonSchemaVfsListener(updater));
PsiManager.getInstance(project).addPsiTreeChangeListener(new PsiTreeAnyChangeAbstractAdapter() {
@Override
protected void onChange(@Nullable PsiFile file) {
if (file != null) updater.onFileChange(file.getViewProvider().getVirtualFile());
}
});
}
private JsonSchemaVfsListener(@NotNull MyUpdater updater) {
super(new VirtualFileContentsChangedAdapter() {
@NotNull private final MyUpdater myUpdater = updater;
@Override
protected void onFileChange(@NotNull final VirtualFile schemaFile) {
myUpdater.onFileChange(schemaFile);
}
@Override
protected void onBeforeFileChange(@NotNull VirtualFile schemaFile) {
myUpdater.onFileChange(schemaFile);
}
});
}
private static class MyUpdater {
@NotNull private final Project myProject;
private final ZipperUpdater myUpdater;
@NotNull private final JsonSchemaService myService;
private final Set<VirtualFile> myDirtySchemas = ContainerUtil.newConcurrentSet();
private final Runnable myRunnable;
private final ExecutorService myTaskExecutor = SequentialTaskExecutor.createSequentialApplicationPoolExecutor(
"JsonVfsUpdaterExecutor");
protected MyUpdater(@NotNull Project project, @NotNull JsonSchemaService service) {
myProject = project;
myUpdater = new ZipperUpdater(200, Alarm.ThreadToUse.POOLED_THREAD, project);
myService = service;
myRunnable = () -> {
if (myProject.isDisposed()) return;
Collection<VirtualFile> scope = new HashSet<>(myDirtySchemas);
if (scope.stream().anyMatch(f -> service.possiblyHasReference(f.getName()))) {
myProject.getMessageBus().syncPublisher(JSON_DEPS_CHANGED).run();
}
myDirtySchemas.removeAll(scope);
if (scope.isEmpty()) return;
Collection<VirtualFile> finalScope = ContainerUtil.filter(scope, file -> myService.isApplicableToFile(file)
&& ((JsonSchemaServiceImpl)myService).isMappedSchema(file, false));
if (finalScope.isEmpty()) return;
if (myProject.isDisposed()) return;
myProject.getMessageBus().syncPublisher(JSON_SCHEMA_CHANGED).run();
final DaemonCodeAnalyzer analyzer = DaemonCodeAnalyzer.getInstance(project);
final PsiManager psiManager = PsiManager.getInstance(project);
final Editor[] editors = EditorFactory.getInstance().getAllEditors();
Arrays.stream(editors).filter(editor -> editor instanceof EditorEx)
.map(editor -> ((EditorEx)editor).getVirtualFile())
.filter(file -> file != null && file.isValid())
.forEach(file -> {
final Collection<VirtualFile> schemaFiles = ((JsonSchemaServiceImpl)myService).getSchemasForFile(file, false, true);
if (schemaFiles.stream().anyMatch(finalScope::contains)) {
ReadAction.nonBlocking(() -> Optional.ofNullable(file.isValid() ? psiManager.findFile(file) : null).ifPresent(analyzer::restart)).submit(myTaskExecutor);
}
});
};
}
protected void onFileChange(@NotNull final VirtualFile schemaFile) {
if (JsonFileType.DEFAULT_EXTENSION.equals(schemaFile.getExtension())) {
myDirtySchemas.add(schemaFile);
myUpdater.queue(myRunnable);
}
}
}
} |
package com.awsomeman.javatext;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import com.awsomeman.javatext.actions.Exit;
import com.awsomeman.javatext.actions.Help;
import com.awsomeman.javatext.actions.Open;
import com.awsomeman.javatext.actions.Save;
import com.awsomeman.javatext.actions.SaveAs;
import com.awsomeman.javatext.actions.Settings;
public class JavaText extends JFrame {
private static final long serialVersionUID = 1L;
public static String currentFile = "Untitled";
public static JTextArea textArea = new JTextArea();
final UndoManager undo = new UndoManager();
Document doc = textArea.getDocument();
public static JavaText frame = new JavaText();
public static JFileChooser dialog = new JFileChooser(System.getProperty("user.dir"));
public static boolean changed = false;
private JPanel contentPane;
Open o;
Save s;
SaveAs sa;
Exit e;
Settings set;
Help h;
public JavaText() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
setTitle("JavaText - " + currentFile);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
JMenu settingsMenu = new JMenu("Settings");
JMenu helpMenu = new JMenu("Help");
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(settingsMenu);
menuBar.add(helpMenu);
JMenuItem openMenuItem = new JMenuItem("Open");
JMenuItem saveMenuItem = new JMenuItem("Save");
JMenuItem saveAsMenuItem = new JMenuItem("Save As");
JMenuItem exitMenuItem = new JMenuItem("Exit");
JMenuItem cutMenuItem = new JMenuItem(new DefaultEditorKit.CutAction());
JMenuItem copyMenuItem = new JMenuItem(new DefaultEditorKit.CopyAction());
JMenuItem pasteMenuItem = new JMenuItem(new DefaultEditorKit.PasteAction());
JMenuItem optionsMenuItem = new JMenuItem("Options");
JMenuItem helpMenuItem = new JMenuItem("Help");
cutMenuItem.setText("Cut");
copyMenuItem.setText("Copy");
pasteMenuItem.setText("Paste");
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.add(saveAsMenuItem);
fileMenu.add(exitMenuItem);
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
settingsMenu.add(optionsMenuItem);
helpMenu.add(helpMenuItem);
o = new Open();
s = new Save();
sa = new SaveAs();
e = new Exit();
set = new Settings();
h = new Help();
openMenuItem.addActionListener(Open.Open);
saveMenuItem.addActionListener(Save.Save);
saveAsMenuItem.addActionListener(SaveAs.SaveAs);
exitMenuItem.addActionListener(Exit.Exit);
optionsMenuItem.addActionListener(Settings.Settings);
helpMenuItem.addActionListener(Help.Help);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
textArea.setLineWrap(true);
textArea.setFont(new Font("Arial", Font.PLAIN, 14));
contentPane.add(textArea, BorderLayout.CENTER);
StyleContext sc = new StyleContext();
Style style = sc.addStyle("yourStyle", null);
try {
doc.insertString(doc.getLength(), "JavaText\n\nCreated by: 12AwsomeMan34 and MCRocks999", style);
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
doc.addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
textArea.getActionMap().put("Undo",
new AbstractAction("Undo") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
try {
if (undo.canUndo()) {
undo.undo();
}
} catch (CannotUndoException e) {
}
}
});
textArea.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
textArea.getActionMap().put("Redo",
new AbstractAction("Redo") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
try {
if (undo.canRedo()) {
undo.redo();
}
} catch (CannotRedoException e) {
}
}
});
textArea.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
JScrollPane scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
contentPane.add(scrollPane, BorderLayout.CENTER);
}
public void keyListener() {
@SuppressWarnings("unused")
KeyListener k = new KeyAdapter() {
public void keyPressed(KeyEvent e) {
changed = true;
Save.Save.setEnabled(true);
SaveAs.SaveAs.setEnabled(true);
}
};
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Initializing...");
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Initialized successfully.");
}
});
}
} |
package org.deeplearning4j.spark.impl.paramavg;
import lombok.Data;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.broadcast.Broadcast;
import org.apache.spark.input.PortableDataStream;
import org.apache.spark.storage.StorageLevel;
import org.deeplearning4j.nn.graph.ComputationGraph;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.optimize.api.IterationListener;
import org.deeplearning4j.spark.api.Repartition;
import org.deeplearning4j.spark.api.RepartitionStrategy;
import org.deeplearning4j.spark.api.TrainingMaster;
import org.deeplearning4j.spark.api.WorkerConfiguration;
import org.deeplearning4j.spark.api.stats.SparkTrainingStats;
import org.deeplearning4j.spark.api.worker.*;
import org.deeplearning4j.spark.impl.graph.SparkComputationGraph;
import org.deeplearning4j.spark.impl.graph.dataset.DataSetToMultiDataSetFn;
import org.deeplearning4j.spark.impl.multilayer.SparkDl4jMultiLayer;
import org.deeplearning4j.spark.impl.paramavg.aggregator.ParameterAveragingAggregationTuple;
import org.deeplearning4j.spark.impl.paramavg.aggregator.ParameterAveragingElementAddFunction;
import org.deeplearning4j.spark.impl.paramavg.aggregator.ParameterAveragingElementCombineFunction;
import org.deeplearning4j.spark.impl.paramavg.stats.ParameterAveragingTrainingMasterStats;
import org.deeplearning4j.spark.util.SparkUtils;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.api.MultiDataSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
/**
* ParameterAveragingTrainingMaster: A {@link TrainingMaster} implementation for training networks on Spark.
* This is standard parameter averaging with a configurable averaging period.
*
* @author Alex Black
*/
@Data
public class ParameterAveragingTrainingMaster implements TrainingMaster<ParameterAveragingTrainingResult, ParameterAveragingTrainingWorker> {
private static final Logger log = LoggerFactory.getLogger(ParameterAveragingTrainingMaster.class);
private static final int COALESCE_THRESHOLD = 3;
private boolean saveUpdater;
private Integer numWorkers;
private int rddDataSetNumExamples;
private int batchSizePerWorker;
private int averagingFrequency;
private int prefetchNumBatches;
private boolean collectTrainingStats;
private ParameterAveragingTrainingMasterStats.ParameterAveragingTrainingMasterStatsHelper stats;
private Collection<IterationListener> listeners;
private int iterationCount = 0;
private Repartition repartition;
private RepartitionStrategy repartitionStrategy;
private StorageLevel storageLevel;
private ParameterAveragingTrainingMaster(Builder builder) {
this.saveUpdater = builder.saveUpdater;
this.numWorkers = builder.numWorkers;
this.rddDataSetNumExamples = builder.rddDataSetNumExamples;
this.batchSizePerWorker = builder.batchSizePerWorker;
this.averagingFrequency = builder.averagingFrequency;
this.prefetchNumBatches = builder.prefetchNumBatches;
this.repartition = builder.repartition;
this.repartitionStrategy = builder.repartitionStrategy;
this.storageLevel = builder.storageLevel;
}
public ParameterAveragingTrainingMaster(boolean saveUpdater, Integer numWorkers, int rddDataSetNumExamples, int batchSizePerWorker,
int averagingFrequency, int prefetchNumBatches) {
this(saveUpdater, numWorkers, rddDataSetNumExamples, batchSizePerWorker, averagingFrequency, prefetchNumBatches,
Repartition.Always, RepartitionStrategy.Balanced, false);
}
/**
* @param saveUpdater If true: save (and average) the updater state when doing parameter averaging
* @param numWorkers Number of workers (executors * threads per executor) for the cluster
* @param rddDataSetNumExamples Number of examples in each DataSet object in the {@code RDD<DataSet>}
* @param batchSizePerWorker Number of examples to use per worker per fit
* @param averagingFrequency Frequency (in number of minibatches) with which to average parameters
* @param prefetchNumBatches Number of batches to asynchronously prefetch (0: disable)
* @param collectTrainingStats If true: collect training statistics for debugging/optimization purposes
*/
public ParameterAveragingTrainingMaster(boolean saveUpdater, Integer numWorkers, int rddDataSetNumExamples, int batchSizePerWorker,
int averagingFrequency, int prefetchNumBatches, Repartition repartition,
RepartitionStrategy repartitionStrategy, boolean collectTrainingStats) {
this(saveUpdater, numWorkers, rddDataSetNumExamples, batchSizePerWorker, averagingFrequency, prefetchNumBatches,
repartition, repartitionStrategy, StorageLevel.MEMORY_ONLY_SER(), collectTrainingStats);
}
public ParameterAveragingTrainingMaster(boolean saveUpdater, Integer numWorkers, int rddDataSetNumExamples, int batchSizePerWorker,
int averagingFrequency, int prefetchNumBatches, Repartition repartition,
RepartitionStrategy repartitionStrategy, StorageLevel storageLevel, boolean collectTrainingStats) {
if (numWorkers <= 0)
throw new IllegalArgumentException("Invalid number of workers: " + numWorkers + " (must be >= 1)");
if (rddDataSetNumExamples <= 0)
throw new IllegalArgumentException("Invalid rdd data set size: " + rddDataSetNumExamples + " (must be >= 1)");
this.saveUpdater = saveUpdater;
this.numWorkers = numWorkers;
this.rddDataSetNumExamples = rddDataSetNumExamples;
this.batchSizePerWorker = batchSizePerWorker;
this.averagingFrequency = averagingFrequency;
this.prefetchNumBatches = prefetchNumBatches;
this.collectTrainingStats = collectTrainingStats;
this.repartition = repartition;
this.repartitionStrategy = repartitionStrategy;
this.storageLevel = storageLevel;
if (collectTrainingStats)
stats = new ParameterAveragingTrainingMasterStats.ParameterAveragingTrainingMasterStatsHelper();
}
@Override
public ParameterAveragingTrainingWorker getWorkerInstance(SparkDl4jMultiLayer network) {
NetBroadcastTuple tuple = new NetBroadcastTuple(network.getNetwork().getLayerWiseConfigurations(),
network.getNetwork().params(),
network.getNetwork().getUpdater().getStateViewArray());
if (collectTrainingStats) stats.logBroadcastStart();
Broadcast<NetBroadcastTuple> broadcast = network.getSparkContext().broadcast(tuple);
if (collectTrainingStats) stats.logBroadcastEnd();
WorkerConfiguration configuration = new WorkerConfiguration(false, batchSizePerWorker, averagingFrequency, prefetchNumBatches, collectTrainingStats);
return new ParameterAveragingTrainingWorker(broadcast, saveUpdater, configuration);
}
@Override
public ParameterAveragingTrainingWorker getWorkerInstance(SparkComputationGraph graph) {
NetBroadcastTuple tuple = new NetBroadcastTuple(graph.getNetwork().getConfiguration(),
graph.getNetwork().params(),
graph.getNetwork().getUpdater().getStateViewArray());
if (collectTrainingStats) stats.logBroadcastStart();
Broadcast<NetBroadcastTuple> broadcast = graph.getSparkContext().broadcast(tuple);
if (collectTrainingStats) stats.logBroadcastEnd();
WorkerConfiguration configuration = new WorkerConfiguration(true, batchSizePerWorker, averagingFrequency, prefetchNumBatches, collectTrainingStats);
return new ParameterAveragingTrainingWorker(broadcast, saveUpdater, configuration);
}
private int numObjectsEachWorker() {
return batchSizePerWorker * averagingFrequency / rddDataSetNumExamples;
}
private int getNumDataSetObjectsPerSplit() {
int dataSetObjectsPerSplit;
if (rddDataSetNumExamples == 1) {
dataSetObjectsPerSplit = numWorkers * batchSizePerWorker * averagingFrequency;
} else {
int numDataSetObjsReqEachWorker = numObjectsEachWorker();
if (numDataSetObjsReqEachWorker < 1) {
//In this case: more examples in a DataSet object than we actually require
//For example, 100 examples in DataSet, with batchSizePerWorker=50 and averagingFrequency=1
numDataSetObjsReqEachWorker = 1;
}
dataSetObjectsPerSplit = numDataSetObjsReqEachWorker * numWorkers;
}
return dataSetObjectsPerSplit;
}
@Override
public void executeTraining(SparkDl4jMultiLayer network, JavaRDD<DataSet> trainingData) {
if (numWorkers == null) numWorkers = network.getSparkContext().defaultParallelism();
if (collectTrainingStats) stats.logFitStart();
//For "vanilla" parameter averaging training, we need to split the full data set into batches of size N, such that we can process the specified
// number of minibatches between averagings
//But to do that, wee need to know: (a) the number of examples, and (b) the number of workers
if (storageLevel != null) trainingData.persist(storageLevel);
if (collectTrainingStats) stats.logCountStart();
long totalDataSetObjectCount = trainingData.count();
if (collectTrainingStats) stats.logCountEnd();
int dataSetObjectsPerSplit = getNumDataSetObjectsPerSplit();
if (collectTrainingStats) stats.logSplitStart();
JavaRDD<DataSet>[] splits = SparkUtils.balancedRandomSplit((int) totalDataSetObjectCount, dataSetObjectsPerSplit, trainingData);
if (collectTrainingStats) stats.logSplitEnd();
int splitNum = 1;
for (JavaRDD<DataSet> split : splits) {
doIteration(network, split, splitNum++, splits.length);
}
if (collectTrainingStats) stats.logFitEnd((int) totalDataSetObjectCount);
}
@Override
public void executeTraining(SparkDl4jMultiLayer network, JavaPairRDD<String, PortableDataStream> trainingData) {
if (numWorkers == null) numWorkers = network.getSparkContext().defaultParallelism();
int origNumPartitions = trainingData.partitions().size();
if (origNumPartitions >= COALESCE_THRESHOLD * numWorkers) {
log.info("Coalesing PortableDataStreams from {} to {} partitions", origNumPartitions, numWorkers);
trainingData = trainingData.coalesce(numWorkers);
}
if (collectTrainingStats) stats.logCountStart();
long totalDataSetObjectCount = trainingData.count();
if (collectTrainingStats) stats.logCountEnd();
int dataSetObjectsPerSplit = getNumDataSetObjectsPerSplit();
if (collectTrainingStats) stats.logSplitStart();
JavaPairRDD<String, PortableDataStream>[] splits = SparkUtils.balancedRandomSplit((int) totalDataSetObjectCount, dataSetObjectsPerSplit, trainingData);
if (collectTrainingStats) stats.logSplitEnd();
int splitNum = 1;
for (JavaPairRDD<String, PortableDataStream> split : splits) {
JavaRDD<PortableDataStream> streams = split.values();
doIterationPDS(network, null, streams, splitNum++, splits.length);
}
if (collectTrainingStats) stats.logFitEnd((int) totalDataSetObjectCount);
}
@Override
public void executeTrainingPaths(SparkDl4jMultiLayer network, JavaRDD<String> trainingDataPaths) {
if (numWorkers == null) numWorkers = network.getSparkContext().defaultParallelism();
if (collectTrainingStats) stats.logFitStart();
if (collectTrainingStats) stats.logCountStart();
long totalDataSetObjectCount = trainingDataPaths.count();
if (collectTrainingStats) stats.logCountEnd();
int dataSetObjectsPerSplit = getNumDataSetObjectsPerSplit();
if (collectTrainingStats) stats.logSplitStart();
JavaRDD<String>[] splits = SparkUtils.balancedRandomSplit((int) totalDataSetObjectCount, dataSetObjectsPerSplit, trainingDataPaths);
if (collectTrainingStats) stats.logSplitEnd();
int splitNum = 1;
for (JavaRDD<String> split : splits) {
doIterationPaths(network, null, split, splitNum++, splits.length);
}
if (collectTrainingStats) stats.logFitEnd((int) totalDataSetObjectCount);
}
@Override
public void executeTraining(SparkComputationGraph graph, JavaRDD<DataSet> trainingData) {
if (numWorkers == null) numWorkers = graph.getSparkContext().defaultParallelism();
JavaRDD<MultiDataSet> mdsTrainingData = trainingData.map(new DataSetToMultiDataSetFn());
executeTrainingMDS(graph, mdsTrainingData);
}
@Override
public void executeTrainingMDS(SparkComputationGraph graph, JavaRDD<MultiDataSet> trainingData) {
if (numWorkers == null) numWorkers = graph.getSparkContext().defaultParallelism();
if (collectTrainingStats) stats.logFitStart();
//For "vanilla" parameter averaging training, we need to split the full data set into batches of size N, such that we can process the specified
// number of minibatches between averagings
//But to do that, we need to know: (a) the number of examples, and (b) the number of workers
if (storageLevel != null) trainingData.persist(storageLevel);
if (collectTrainingStats) stats.logCountStart();
long totalDataSetObjectCount = trainingData.count();
if (collectTrainingStats) stats.logCountEnd();
int dataSetObjectsPerSplit = getNumDataSetObjectsPerSplit();
if (collectTrainingStats) stats.logSplitStart();
JavaRDD<MultiDataSet>[] splits = SparkUtils.balancedRandomSplit((int) totalDataSetObjectCount, dataSetObjectsPerSplit, trainingData);
if (collectTrainingStats) stats.logSplitEnd();
int splitNum = 1;
for (JavaRDD<MultiDataSet> split : splits) {
doIteration(graph, split, splitNum++, splits.length);
}
if (collectTrainingStats) stats.logFitEnd((int) totalDataSetObjectCount);
}
@Override
public void executeTraining(SparkComputationGraph graph, JavaPairRDD<String, PortableDataStream> trainingData) {
if (numWorkers == null) numWorkers = graph.getSparkContext().defaultParallelism();
if (collectTrainingStats) stats.logFitStart();
//For "vanilla" parameter averaging training, we need to split the full data set into batches of size N, such that we can process the specified
// number of minibatches between averagings
//But to do that, we need to know: (a) the number of examples, and (b) the number of workers
int origNumPartitions = trainingData.partitions().size();
if (origNumPartitions >= COALESCE_THRESHOLD * numWorkers) {
log.info("Coalesing streams from {} to {} partitions", origNumPartitions, numWorkers);
trainingData = trainingData.coalesce(numWorkers);
}
if (collectTrainingStats) stats.logCountStart();
long totalDataSetObjectCount = trainingData.count();
if (collectTrainingStats) stats.logCountEnd();
int dataSetObjectsPerSplit = getNumDataSetObjectsPerSplit();
if (collectTrainingStats) stats.logSplitStart();
JavaPairRDD<String, PortableDataStream>[] splits = SparkUtils.balancedRandomSplit((int) totalDataSetObjectCount, dataSetObjectsPerSplit, trainingData, new Random().nextLong());
if (collectTrainingStats) stats.logSplitEnd();
int splitNum = 1;
for (JavaPairRDD<String, PortableDataStream> split : splits) {
JavaRDD<PortableDataStream> streams = split.values();
doIterationPDS(null, graph, streams, splitNum++, splits.length);
}
if (collectTrainingStats) stats.logFitEnd((int) totalDataSetObjectCount);
}
@Override
public void executeTrainingMDS(SparkComputationGraph graph, JavaPairRDD<String, PortableDataStream> trainingData) {
if (numWorkers == null) numWorkers = graph.getSparkContext().defaultParallelism();
if (collectTrainingStats) stats.logFitStart();
if (collectTrainingStats) stats.logCountStart();
long totalDataSetObjectCount = trainingData.count();
if (collectTrainingStats) stats.logCountEnd();
int dataSetObjectsPerSplit = getNumDataSetObjectsPerSplit();
if (collectTrainingStats) stats.logSplitStart();
JavaPairRDD<String, PortableDataStream>[] splits = SparkUtils.balancedRandomSplit((int) totalDataSetObjectCount, dataSetObjectsPerSplit, trainingData, new Random().nextLong());
if (collectTrainingStats) stats.logSplitEnd();
int splitNum = 1;
for (JavaPairRDD<String, PortableDataStream> split : splits) {
JavaRDD<PortableDataStream> streams = split.values();
if (collectTrainingStats) stats.logRepartitionStart();
streams = SparkUtils.repartition(streams, repartition, repartitionStrategy, numObjectsEachWorker(), numWorkers);
if (collectTrainingStats && repartition != Repartition.Never) stats.logRepartitionEnd();
doIterationPDS_MDS(graph, streams, splitNum++, splits.length);
}
if (collectTrainingStats) stats.logFitEnd((int) totalDataSetObjectCount);
}
@Override
public void executeTrainingPaths(SparkComputationGraph network, JavaRDD<String> trainingDataPaths) {
if (numWorkers == null) numWorkers = network.getSparkContext().defaultParallelism();
if (collectTrainingStats) stats.logFitStart();
if (collectTrainingStats) stats.logCountStart();
long totalDataSetObjectCount = trainingDataPaths.count();
if (collectTrainingStats) stats.logCountEnd();
int dataSetObjectsPerSplit = getNumDataSetObjectsPerSplit();
if (collectTrainingStats) stats.logSplitStart();
JavaRDD<String>[] splits = SparkUtils.balancedRandomSplit((int) totalDataSetObjectCount, dataSetObjectsPerSplit, trainingDataPaths);
if (collectTrainingStats) stats.logSplitEnd();
int splitNum = 1;
for (JavaRDD<String> split : splits) {
doIterationPaths(null, network, split, splitNum++, splits.length);
}
if (collectTrainingStats) stats.logFitEnd((int) totalDataSetObjectCount);
}
@Override
public void executeTrainingPathsMDS(SparkComputationGraph network, JavaRDD<String> trainingMultiDataPaths) {
if (numWorkers == null) numWorkers = network.getSparkContext().defaultParallelism();
if (collectTrainingStats) stats.logFitStart();
if (collectTrainingStats) stats.logCountStart();
long totalDataSetObjectCount = trainingMultiDataPaths.count();
if (collectTrainingStats) stats.logCountEnd();
int dataSetObjectsPerSplit = getNumDataSetObjectsPerSplit();
if (collectTrainingStats) stats.logSplitStart();
JavaRDD<String>[] splits = SparkUtils.balancedRandomSplit((int) totalDataSetObjectCount, dataSetObjectsPerSplit, trainingMultiDataPaths);
if (collectTrainingStats) stats.logSplitEnd();
int splitNum = 1;
for (JavaRDD<String> split : splits) {
doIterationPathsMDS(network, split, splitNum++, splits.length);
}
if (collectTrainingStats) stats.logFitEnd((int) totalDataSetObjectCount);
}
@Override
public void setCollectTrainingStats(boolean collectTrainingStats) {
this.collectTrainingStats = collectTrainingStats;
if (collectTrainingStats) {
if (this.stats == null)
this.stats = new ParameterAveragingTrainingMasterStats.ParameterAveragingTrainingMasterStatsHelper();
} else {
this.stats = null;
}
}
@Override
public boolean getIsCollectTrainingStats() {
return collectTrainingStats;
}
@Override
public SparkTrainingStats getTrainingStats() {
if (stats != null) return stats.build();
return null;
}
private void doIteration(SparkDl4jMultiLayer network, JavaRDD<DataSet> split, int splitNum, int numSplits) {
log.info("Starting training of split {} of {}. workerMiniBatchSize={}, averagingFreq={}, Configured for {} workers",
splitNum, numSplits, batchSizePerWorker, averagingFrequency, numWorkers);
if (collectTrainingStats) stats.logMapPartitionsStart();
JavaRDD<DataSet> splitData = split;
if (collectTrainingStats) stats.logRepartitionStart();
splitData = SparkUtils.repartition(splitData, repartition, repartitionStrategy, numObjectsEachWorker(), numWorkers);
int nPartitions = splitData.partitions().size();
if (collectTrainingStats && repartition != Repartition.Never) stats.logRepartitionEnd();
FlatMapFunction<Iterator<DataSet>, ParameterAveragingTrainingResult> function = new ExecuteWorkerFlatMap<>(getWorkerInstance(network));
JavaRDD<ParameterAveragingTrainingResult> result = splitData.mapPartitions(function);
processResults(network, null, result, splitNum, numSplits);
if (collectTrainingStats) stats.logMapPartitionsEnd(nPartitions);
}
private void doIterationPDS(SparkDl4jMultiLayer network, SparkComputationGraph graph, JavaRDD<PortableDataStream> split, int splitNum, int numSplits) {
log.info("Starting training of split {} of {}. workerMiniBatchSize={}, averagingFreq={}, Configured for {} workers",
splitNum, numSplits, batchSizePerWorker, averagingFrequency, numWorkers);
if (collectTrainingStats) stats.logMapPartitionsStart();
JavaRDD<PortableDataStream> splitData = split;
if (collectTrainingStats) stats.logRepartitionStart();
splitData = SparkUtils.repartition(splitData, repartition, repartitionStrategy, numObjectsEachWorker(), numWorkers);
int nPartitions = splitData.partitions().size();
if (collectTrainingStats && repartition != Repartition.Never) stats.logRepartitionEnd();
FlatMapFunction<Iterator<PortableDataStream>, ParameterAveragingTrainingResult> function;
if (network != null) function = new ExecuteWorkerPDSFlatMap<>(getWorkerInstance(network));
else function = new ExecuteWorkerPDSFlatMap<>(getWorkerInstance(graph));
JavaRDD<ParameterAveragingTrainingResult> result = splitData.mapPartitions(function);
processResults(network, graph, result, splitNum, numSplits);
if (collectTrainingStats) stats.logMapPartitionsEnd(nPartitions);
}
private void doIterationPaths(SparkDl4jMultiLayer network, SparkComputationGraph graph, JavaRDD<String> split, int splitNum, int numSplits) {
log.info("Starting training of split {} of {}. workerMiniBatchSize={}, averagingFreq={}, Configured for {} workers",
splitNum, numSplits, batchSizePerWorker, averagingFrequency, numWorkers);
if (collectTrainingStats) stats.logMapPartitionsStart();
JavaRDD<String> splitData = split;
if (collectTrainingStats) stats.logRepartitionStart();
splitData = SparkUtils.repartition(splitData, repartition, repartitionStrategy, numObjectsEachWorker(), numWorkers);
int nPartitions = splitData.partitions().size();
if (collectTrainingStats && repartition != Repartition.Never) stats.logRepartitionEnd();
FlatMapFunction<Iterator<String>, ParameterAveragingTrainingResult> function;
if (network != null) function = new ExecuteWorkerPathFlatMap<>(getWorkerInstance(network));
else function = new ExecuteWorkerPathFlatMap<>(getWorkerInstance(graph));
JavaRDD<ParameterAveragingTrainingResult> result = splitData.mapPartitions(function);
processResults(network, graph, result, splitNum, numSplits);
if (collectTrainingStats) stats.logMapPartitionsEnd(nPartitions);
}
private void doIterationPathsMDS(SparkComputationGraph graph, JavaRDD<String> split, int splitNum, int numSplits) {
log.info("Starting training of split {} of {}. workerMiniBatchSize={}, averagingFreq={}, Configured for {} workers",
splitNum, numSplits, batchSizePerWorker, averagingFrequency, numWorkers);
if (collectTrainingStats) stats.logMapPartitionsStart();
JavaRDD<String> splitData = split;
if (collectTrainingStats) stats.logRepartitionStart();
splitData = SparkUtils.repartition(splitData, repartition, repartitionStrategy, numObjectsEachWorker(), numWorkers);
int nPartitions = splitData.partitions().size();
if (collectTrainingStats && repartition != Repartition.Never) stats.logRepartitionEnd();
FlatMapFunction<Iterator<String>, ParameterAveragingTrainingResult> function
= new ExecuteWorkerPathMDSFlatMap<>(getWorkerInstance(graph));
JavaRDD<ParameterAveragingTrainingResult> result = splitData.mapPartitions(function);
processResults(null, graph, result, splitNum, numSplits);
if (collectTrainingStats) stats.logMapPartitionsEnd(nPartitions);
}
private void doIteration(SparkComputationGraph graph, JavaRDD<MultiDataSet> split, int splitNum, int numSplits) {
log.info("Starting training of split {} of {}. workerMiniBatchSize={}, averagingFreq={}, Configured for {} workers",
splitNum, numSplits, batchSizePerWorker, averagingFrequency, numWorkers);
if (collectTrainingStats) stats.logMapPartitionsStart();
JavaRDD<MultiDataSet> splitData = split;
splitData = SparkUtils.repartition(splitData, repartition, repartitionStrategy, numObjectsEachWorker(), numWorkers);
int nPartitions = split.partitions().size();
FlatMapFunction<Iterator<MultiDataSet>, ParameterAveragingTrainingResult> function = new ExecuteWorkerMultiDataSetFlatMap<>(getWorkerInstance(graph));
JavaRDD<ParameterAveragingTrainingResult> result = splitData.mapPartitions(function);
processResults(null, graph, result, splitNum, numSplits);
if (collectTrainingStats) stats.logMapPartitionsEnd(nPartitions);
}
private void doIterationPDS_MDS(SparkComputationGraph graph, JavaRDD<PortableDataStream> split, int splitNum, int numSplits) {
log.info("Starting training of split {} of {}. workerMiniBatchSize={}, averagingFreq={}, Configured for {} workers",
splitNum, numSplits, batchSizePerWorker, averagingFrequency, numWorkers);
if (collectTrainingStats) stats.logMapPartitionsStart();
JavaRDD<PortableDataStream> splitData = split;
if (collectTrainingStats) stats.logRepartitionStart();
splitData = SparkUtils.repartition(splitData, repartition, repartitionStrategy, numObjectsEachWorker(), numWorkers);
int nPartitions = splitData.partitions().size();
if (collectTrainingStats && repartition != Repartition.Never) stats.logRepartitionEnd();
FlatMapFunction<Iterator<PortableDataStream>, ParameterAveragingTrainingResult> function = new ExecuteWorkerPDSMDSFlatMap<>(getWorkerInstance(graph));
JavaRDD<ParameterAveragingTrainingResult> result = splitData.mapPartitions(function);
processResults(null, graph, result, splitNum, numSplits);
if (collectTrainingStats) stats.logMapPartitionsEnd(nPartitions);
}
private void processResults(SparkDl4jMultiLayer network, SparkComputationGraph graph, JavaRDD<ParameterAveragingTrainingResult> results, int splitNum, int totalSplits) {
//Need to do parameter averaging, and where necessary also do averaging of the updaters
//Let's do all of this in ONE step, such that we don't have extra synchronization costs
if (collectTrainingStats) stats.logAggregateStartTime();
ParameterAveragingAggregationTuple tuple = results.aggregate(null,
new ParameterAveragingElementAddFunction(),
new ParameterAveragingElementCombineFunction());
INDArray params = tuple.getParametersSum();
int aggCount = tuple.getAggregationsCount();
SparkTrainingStats aggregatedStats = tuple.getSparkTrainingStats();
if (collectTrainingStats) stats.logAggregationEndTime();
if (collectTrainingStats) stats.logProcessParamsUpdaterStart();
params.divi(aggCount);
INDArray updaterState = tuple.getUpdaterStateSum();
if (updaterState != null) updaterState.divi(aggCount); //May be null if all SGD updaters, for example
if (network != null) {
MultiLayerNetwork net = network.getNetwork();
net.setParameters(params);
if (updaterState != null) net.getUpdater().setStateViewArray(null, updaterState, false);
network.setScore(tuple.getScoreSum() / tuple.getAggregationsCount());
} else {
ComputationGraph g = graph.getNetwork();
g.setParams(params);
if (updaterState != null) g.getUpdater().setStateViewArray(updaterState);
graph.setScore(tuple.getScoreSum() / tuple.getAggregationsCount());
}
if (collectTrainingStats) {
stats.logProcessParamsUpdaterEnd();
stats.addWorkerStats(aggregatedStats);
}
log.info("Completed training of split {} of {}", splitNum, totalSplits);
if (listeners != null) {
if (network != null) {
MultiLayerNetwork net = network.getNetwork();
net.setScore(network.getScore());
for (IterationListener il : listeners) {
il.iterationDone(net, iterationCount);
}
} else {
ComputationGraph g = graph.getNetwork();
g.setScore(graph.getScore());
for (IterationListener il : listeners) {
il.iterationDone(g, iterationCount);
}
}
}
iterationCount++;
}
public static class Builder {
private boolean saveUpdater;
private Integer numWorkers;
private int rddDataSetNumExamples;
private int batchSizePerWorker = 16;
private int averagingFrequency = 5;
private int prefetchNumBatches = 0;
private Repartition repartition = Repartition.Always;
private RepartitionStrategy repartitionStrategy = RepartitionStrategy.Balanced;
private StorageLevel storageLevel = StorageLevel.MEMORY_ONLY_SER();
/**
* Same as {@link #Builder(Integer, int)} but automatically set number of workers based on JavaSparkContext.defaultParallelism()
*
* @param rddDataSetNumExamples Number of examples in each DataSet object in the {@code RDD<DataSet>}
*/
public Builder(int rddDataSetNumExamples) {
this(null, rddDataSetNumExamples);
}
/**
* Create a builder, where the following number of workers (Spark executors * number of threads per executor) are
* being used.<br>
* Note: this should match the configuration of the cluster.<br>
* <p>
* It is also necessary to specify how many examples are in each DataSet that appears in the {@code RDD<DataSet>}
* or {@code JavaRDD<DataSet>} used for training.<br>
* Two most common cases here:<br>
* (a) Preprocessed data pipelines will often load binary DataSet objects with N > 1 examples in each; in this case,
* rddDataSetNumExamples should be set to N <br>
* (b) "In line" data pipelines (for example, CSV String -> record reader -> DataSet just before training) will
* typically have exactly 1 example in each DataSet object. In this case, rddDataSetNumExamples should be set to 1
*
* @param numWorkers Number of Spark execution threads in the cluster. May be null. If null: number of workers will
* be obtained from JavaSparkContext.defaultParallelism(), which should provide the number of cores
* in the cluster.
* @param rddDataSetNumExamples Number of examples in each DataSet object in the {@code RDD<DataSet>}
*/
public Builder(Integer numWorkers, int rddDataSetNumExamples) {
if (numWorkers != null && numWorkers <= 0)
throw new IllegalArgumentException("Invalid number of workers: " + numWorkers + " (must be >= 1)");
if (rddDataSetNumExamples <= 0)
throw new IllegalArgumentException("Invalid rdd data set size: " + rddDataSetNumExamples + " (must be >= 1)");
this.numWorkers = numWorkers;
this.rddDataSetNumExamples = rddDataSetNumExamples;
}
/**
* Batch size (in number of examples) per worker, for each fit(DataSet) call.
*
* @param batchSizePerWorker Size of each minibatch to use for each worker
* @return
*/
public Builder batchSizePerWorker(int batchSizePerWorker) {
this.batchSizePerWorker = batchSizePerWorker;
return this;
}
/**
* Frequency with which to average worker parameters.<br>
* <b>Note</b>: Too high or too low can be bad for different reasons.<br>
* - Too low (such as 1) can result in a lot of network traffic<br>
* - Too high (>> 20 or so) can result in accuracy issues or problems with network convergence
*
* @param averagingFrequency Frequency (in number of minibatches of size 'batchSizePerWorker') to average parameters
*/
public Builder averagingFrequency(int averagingFrequency) {
if (averagingFrequency <= 0)
throw new IllegalArgumentException("Ivalid input: averaging frequency must be >= 1");
this.averagingFrequency = averagingFrequency;
return this;
}
/**
* Set the number of minibatches to asynchronously prefetch in the worker.
* <p>
* Default: 0 (no prefetching)
*
* @param prefetchNumBatches Number of minibatches (DataSets of size batchSizePerWorker) to fetch
*/
public Builder workerPrefetchNumBatches(int prefetchNumBatches) {
this.prefetchNumBatches = prefetchNumBatches;
return this;
}
/**
* Set whether the updater (i.e., historical state for momentum, adagrad, etc should be saved).
* <b>NOTE</b>: This can <b>double</b> (or more) the amount of network traffic in each direction, but might
* improve network training performance (and can be more stable for certain updaters such as adagrad).<br>
* <p>
* This is <b>enabled</b> by default.
*
* @param saveUpdater If true: retain the updater state (default). If false, don't retain (updaters will be
* reinitalized in each worker after averaging).
*/
public Builder saveUpdater(boolean saveUpdater) {
this.saveUpdater = saveUpdater;
return this;
}
/**
* Set if/when repartitioning should be conducted for the training data.<br>
* Default value: always repartition (if required to guarantee correct number of partitions and correct number
* of examples in each partition).
*
* @param repartition Setting for repartitioning
*/
public Builder repartionData(Repartition repartition) {
this.repartition = repartition;
return this;
}
/**
* Used in conjunction with {@link #repartionData(Repartition)} (which defines <i>when</i> repartitioning should be
* conducted), repartitionStrategy defines <i>how</i> the repartitioning should be done. See {@link RepartitionStrategy}
* for details
*
* @param repartitionStrategy Repartitioning strategy to use
*/
public Builder repartitionStrategy(RepartitionStrategy repartitionStrategy) {
this.repartitionStrategy = repartitionStrategy;
return this;
}
/**
* Set the storage level for {@code RDD<DataSet>}s.<br>
* Default: StorageLevel.MEMORY_ONLY_SER() - i.e., store in memory, in serialized form<br>
* To use no RDD persistence, use {@code null}<br>
* <p>
* <b>Note</b>: Spark's StorageLevel.MEMORY_ONLY() and StorageLevel.MEMORY_AND_DISK() can be problematic when
* it comes to off-heap data (which DL4J/ND4J uses extensively). Spark does not account for off-heap memory
* when deciding if/when to drop blocks to ensure enough free memory; consequently, for DataSet RDDs that are
* larger than the total amount of (off-heap) memory, this can lead to OOM issues. Put another way: Spark counts
* the on-heap size of DataSet and INDArray objects only (which is negligible) resulting in a significant
* underestimate of the true DataSet object sizes. More DataSets are thus kept in memory than we can really afford.
*
* @param storageLevel Storage level to use for DataSet RDDs
*/
public Builder storageLevel(StorageLevel storageLevel) {
this.storageLevel = storageLevel;
return this;
}
public ParameterAveragingTrainingMaster build() {
return new ParameterAveragingTrainingMaster(this);
}
}
} |
package com.buddycloud.model;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONObject;
import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.webkit.MimeTypeMap;
import com.buddycloud.http.BuddycloudHTTPHelper;
import com.buddycloud.preferences.Preferences;
import com.buddycloud.utils.FileUtils;
public class MediaModel extends AbstractModel<JSONObject, JSONObject, String> {
private static MediaModel instance;
public static final String ENDPOINT = "/media";
public static final String AVATAR = "/avatar";
private MediaModel() {}
public static MediaModel getInstance() {
if (instance == null) {
instance = new MediaModel();
}
return instance;
}
@Override
public void getFromServer(Context context, final ModelCallback<JSONObject> callback, String... p) {
}
private static String url(Context context, String channel) {
String apiAddress = Preferences.getPreference(context, Preferences.API_ADDRESS);
return apiAddress + "/" + channel + ENDPOINT;
}
private static String avatarUrl(Context context, String channel) {
String apiAddress = Preferences.getPreference(context, Preferences.API_ADDRESS);
return apiAddress + "/" + channel + ENDPOINT + AVATAR;
}
@Override
public void save(Context context, JSONObject object,
ModelCallback<JSONObject> callback, String... p) {
try {
postMedia(context, callback, p);
} catch (Exception e) {
callback.error(e);
}
}
public void saveAvatar(Context context, JSONObject object,
ModelCallback<JSONObject> callback, String... p) {
try {
postAvatar(context, callback, p);
} catch (Exception e) {
callback.error(e);
}
}
private void postAvatar(Context context, ModelCallback<JSONObject> callback,
String... p) throws FileNotFoundException, Exception, IOException,
UnsupportedEncodingException {
postMediaGeneral(context, callback, p[0], avatarUrl(context, p[1]), false);
}
private void postMedia(Context context, ModelCallback<JSONObject> callback,
String... p) throws FileNotFoundException, Exception, IOException,
UnsupportedEncodingException {
postMediaGeneral(context, callback, p[0], url(context, p[1]), true);
}
private void postMediaGeneral(Context context,
final ModelCallback<JSONObject> callback, String imageUri,
String url, boolean post) throws IOException {
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentResolver cr = context.getContentResolver();
final Uri streamUri = Uri.parse(imageUri);
String streamType = cr.getType(streamUri);
String fileName = streamUri.getLastPathSegment();
if (streamType == null) {
streamType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
FilenameUtils.getExtension(fileName));
}
InputStream is = context.getContentResolver().openInputStream(streamUri);
String realPath = FileUtils.getRealPathFromURI(context, streamUri);
ModelCallback<JSONObject> tempCallback = null;
File mediaFile = null;
if (realPath == null) {
File tempDir = context.getCacheDir();
final File tempFile = File.createTempFile("buddycloud-tmp-",
MimeTypeMap.getSingleton().getExtensionFromMimeType(streamType),
tempDir);
IOUtils.copy(is, new FileOutputStream(tempFile));
tempCallback = new ModelCallback<JSONObject>() {
@Override
public void success(JSONObject response) {
tempFile.delete();
callback.success(response);
}
@Override
public void error(Throwable throwable) {
tempFile.delete();
callback.error(throwable);
}
};
mediaFile = tempFile;
} else {
mediaFile = new File(realPath);
tempCallback = callback;
}
reqEntity.addPart("data", new FileBody(mediaFile));
reqEntity.addPart("filename", new StringBody(fileName));
reqEntity.addPart("content-type", new StringBody(streamType));
reqEntity.addPart("title", new StringBody("Android upload"));
if (post) {
BuddycloudHTTPHelper.post(url, reqEntity, context, tempCallback);
} else {
BuddycloudHTTPHelper.put(url, reqEntity, context, tempCallback);
}
}
@Override
public JSONObject getFromCache(Context context, String... p) {
// TODO Auto-generated method stub
return null;
}
@Override
public void fill(Context context, ModelCallback<Void> callback, String... p) {
// TODO Auto-generated method stub
}
@Override
public void delete(Context context, ModelCallback<Void> callback, String... p) {
// TODO Auto-generated method stub
}
} |
package org.jboss.msc.resolver;
import java.util.Collection;
import java.util.LinkedHashMap;
/**
* An ordered set of service definitions that should be processed as one.
*
* @author Jason T. Greene
*/
public final class ServiceBatch {
private LinkedHashMap<String, ServiceDefinition> definitions;
/**
* Add a service definition to the batch.
*
* @param definition
* @return this batch
*/
public ServiceBatch add(ServiceDefinition definition) {
definitions.put(definition.getName(), definition);
return this;
}
/**
* Add a list of service definitions to the batch, in the order of the list.
*
* @param definitions add a list of service definitions to the batch, in the
* order of the list
* @return this batch
*/
public ServiceBatch add(ServiceDefinition... definitions) {
for (ServiceDefinition d : definitions)
this.definitions.put(d.getName(), d);
return this;
}
/**
* Add a collection of service definitions to the batch, in the order of the
* collection (if ordered).
*
* @param definitions add a list of service definitions to the batch, in the
* order of the list
* @return this batch
*/
public ServiceBatch add(Collection<ServiceDefinition> definitions) {
for (ServiceDefinition d : definitions)
this.definitions.put(d.getName(), d);
return this;
}
LinkedHashMap<String, ServiceDefinition> definitionMap() {
return definitions;
}
} |
package com.worizon.junit.rpc;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.Before;
import org.junit.Test;
import com.worizon.jsonrpc.IDGenerator;
import com.worizon.jsonrpc.JsonRpcException;
import com.worizon.jsonrpc.RemoteException;
import com.worizon.jsonrpc.Rpc;
import com.worizon.jsonrpc.annotations.LocalException;
import com.worizon.jsonrpc.annotations.LocalExceptions;
import com.worizon.jsonrpc.annotations.Remote;
import com.worizon.jsonrpc.annotations.RemoteParams;
import com.worizon.jsonrpc.annotations.RemoteProcName;
import com.worizon.net.HttpRequest;
import com.worizon.net.HttpRequestBuilder;
import com.worizon.test.TestServer;
public class RpcTest {
@Before
public void setUp(){
IDGenerator.getInstance().reset();
}
@Test
public void testRemoteParam(){
Map.Entry<String, Object> pair = Rpc.RemoteParam("paramName", "paramValue");
assertThat( pair.getKey(), is("paramName") );
assertThat( (String)pair.getValue(), is("paramValue") );
}
interface NonRemoteInterface{};
@Test(expected = IllegalArgumentException.class)
public void testNonRemoteInterface() throws MalformedURLException{
HttpRequestBuilder builder = new HttpRequestBuilder().endpoint("http://localhost:8080/rpc");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
NonRemoteInterface remote = proxy.createProxy(NonRemoteInterface.class);
}
@Remote
interface My1RemoteInterface{
public Void test();
};
@Test
public void testNonAnotattedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat( request.toString(), is("{\"method\":\"test\",\"jsonrpc\":\"2.0\",\"id\":1}") );
return "{\"jsonrpc\": \"2.0\", \"result\":{} , \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
My1RemoteInterface remote = proxy.createProxy(My1RemoteInterface.class);
remote.test();
}
@Remote
interface My2RemoteInterface{
@RemoteParams({"x","y","z"})
public void test(int x, int y);
};
@Test(expected=IllegalArgumentException.class)
public void testAnnottedParamsNumberMismath() throws Exception{
HttpRequestBuilder builder = new HttpRequestBuilder();
Rpc.Proxy proxy = new Rpc.Proxy(builder);
My2RemoteInterface remote = proxy.createProxy(My2RemoteInterface.class);
remote.test(1,2);
}
@Remote
interface My3RemoteInterface{
@RemoteParams({"params"})
public Void test( Map<String, Object> params );
}
@Test
public void testRemoteInterfaceWithHashMapParamAnnotatedWithParamsName() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"test\",\"params\":{\"x\":1,\"y\":\"test string\"},\"jsonrpc\":\"2.0\",\"id\":1}") );
return "{\"jsonrpc\": \"2.0\", \"result\":{} , \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
My3RemoteInterface remote = proxy.createProxy( My3RemoteInterface.class);
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("x", 1);
params.put("y","test string");
remote.test(params);
}
@Remote
interface My4RemoteInterface{
@RemoteParams({"params"})
public Void test( List<Object> params );
}
@Test
public void testRemoteInterfaceWithListParamAnnotatedWithParamsName() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat( request.toString(), is("{\"method\":\"test\",\"params\":[1,\"test string\"],\"jsonrpc\":\"2.0\",\"id\":1}") );
return "{\"jsonrpc\": \"2.0\", \"result\":{} , \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
My4RemoteInterface remote = proxy.createProxy( My4RemoteInterface.class);
List<Object> params = new ArrayList<Object>();
params.add(1);
params.add("test string");
remote.test(params);
}
@Remote
interface My5RemoteInterface{
@RemoteParams({"x","y"})
public int sum( int x, int y);
}
@Test
public void testRemoteInterfaceWithNamedParameters() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"sum\",\"params\":{\"x\":5,\"y\":4},\"jsonrpc\":\"2.0\",\"id\":1}") );
return "{\"jsonrpc\": \"2.0\", \"result\":9 , \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
My5RemoteInterface remote = proxy.createProxy(My5RemoteInterface.class);
assertEquals(9, remote.sum(5, 4));
}
@Remote
interface My6RemoteInterface{
public int sum( int x, int y);
}
@Test
public void testRemoteInterfaceWithNumberedParameters() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"sum\",\"params\":[5,4],\"jsonrpc\":\"2.0\",\"id\":1}") );
return "{\"jsonrpc\": \"2.0\", \"result\":9 , \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
My6RemoteInterface remote = proxy.createProxy(My6RemoteInterface.class);
assertEquals(9, remote.sum(5, 4));
}
class A{
int x;
int y;
B b = null;
public A(int x, int y){this.x = x; this.y = y;}
}
class B{
String z;
float f;
public B(String z, float f){this.z = z; this.f = f;}
public boolean equals( Object obj ){
B b = (B)obj;
return b.z.equals(z) && b.f == b.f;
}
}
@Remote
interface My7RemoteInterface{
@RemoteParams({"a"})
public B op( A a );// A object -> Remote operation op -> B object
}
@Test
public void testRemoteInterfaceWithNamedObjectParameters() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(),is("{\"method\":\"op\",\"params\":{\"a\":{\"x\":2,\"y\":3}},\"jsonrpc\":\"2.0\",\"id\":1}") );
return "{\"jsonrpc\": \"2.0\", \"result\": {\"z\":\"test\",\"f\":23.45}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
My7RemoteInterface remote = proxy.createProxy(My7RemoteInterface.class);
A a = new A(2,3);
B expected = new B("test",23.45f);
assertEquals(expected, remote.op(a));
}
@Remote
interface My8RemoteInterface{
public B op( A a );// A object -> Remote operation op -> B object
}
@Test
public void testRemoteInterfaceWithNnumberedObjectParameters() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[{\"x\":2,\"y\":3}],\"jsonrpc\":\"2.0\",\"id\":1}") );
return "{\"jsonrpc\": \"2.0\", \"result\": {\"z\":\"test\",\"f\":23.45}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
My8RemoteInterface remote = proxy.createProxy(My8RemoteInterface.class);
A a = new A(2,3);
B expected = new B("test",23.45f);
assertEquals(expected, remote.op(a));
}
@Remote
interface My9RemoteInterface{
@RemoteProcName("dummy")
public Void op();
}
@Test
public void testRemoteInterfaceProcName() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"dummy\",\"jsonrpc\":\"2.0\",\"id\":1}") );
return "{\"jsonrpc\": \"2.0\", \"result\": null, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
My9RemoteInterface remote = proxy.createProxy(My9RemoteInterface.class);
remote.op();
}
@Remote
interface My10RemoteInterface{
public Void op();// A object -> Remote operation op -> B object
}
@Test
public void testJsonRpcExceptionParseError() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\":-32700,\"message\":\"Parse error\"}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
try{
proxy.createProxy(My10RemoteInterface.class).op();
fail();
}catch(JsonRpcException ex){
assertThat(ex.getCode(), is(-32700));
assertThat(ex.getMessage(), is("Parse error"));
}
}
@Test
public void testJsonRpcExceptionInvalidRequest() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\":-32600,\"message\":\"Invalid request\"}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
try{
proxy.createProxy(My10RemoteInterface.class).op();
assertTrue(false);
}catch(JsonRpcException ex){
assertThat(ex.getCode(), is(-32600));
assertThat(ex.getMessage(), is("Invalid request"));
}
}
@Test
public void testJsonRpcExceptionMethodNotFound() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\":-32601,\"message\":\"Method not found\"}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
try{
proxy.createProxy(My10RemoteInterface.class).op();
fail();
}catch(JsonRpcException ex){
assertThat(ex.getCode(), is(-32601));
assertThat(ex.getMessage(), is("Method not found"));
}
}
@Test
public void testJsonRpcExceptionInvalidParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\":-32602,\"message\":\"Invalid params\"}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
try{
proxy.createProxy(My10RemoteInterface.class).op();
fail();
}catch(JsonRpcException ex){
assertThat(ex.getCode(), is(-32602));
assertThat(ex.getMessage(), is("Invalid params"));
}
}
@Test
public void testJsonRpcExceptionInternalError() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform((String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\":-32603,\"message\":\"Internal error\"}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
try{
proxy.createProxy(My10RemoteInterface.class).op();
fail();
}catch(JsonRpcException ex){
assertThat(ex.getCode(), is(-32603));
assertThat(ex.getMessage(), is("Internal error"));
}
}
@Test
public void testRemoteException() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\":-5,\"message\":\"Domain error\"}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
try{
proxy.createProxy(My10RemoteInterface.class).op();
fail();
}catch(RemoteException ex){
assertThat(ex.getCode(), is(-5));
assertThat(ex.getMessage(), is("Domain error"));
}
}
public static class MyDummyException extends RuntimeException{
public MyDummyException(){
super();
}
public MyDummyException(String message){
super(message);
}
}
@Remote
@LocalExceptions({@LocalException(code=-5,exception=MyDummyException.class)})
interface My11RemoteInterface{
public Void op();
}
@Test
public void testRemoteExceptionMapedLocalException() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\":-5,\"message\":\"Domain error\"}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
try{
proxy.createProxy(My11RemoteInterface.class).op();
fail();
}catch(MyDummyException ex){
assertThat(ex.getMessage(), is("Domain error"));
}
}
@Remote
@LocalExceptions({@LocalException(code=-5,exception=MyDummyException.class)})
interface My12RemoteInterface{
public Void op();// A object -> Remote operation op -> B object
}
@Test
public void testRemoteExceptionMapedLocalExceptionFailure() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\":-6,\"message\":\"Domain error\"}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Proxy proxy = new Rpc.Proxy(builder);
try{
proxy.createProxy(My12RemoteInterface.class).op();
fail();
}catch(RemoteException ex){
assertThat(ex.getCode(), is(-6));
assertThat(ex.getMessage(), is("Domain error"));
}
}
@Remote
interface My13RemoteInterface{
public Void op();
}
@Test
public void testCall1() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": {}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
rpc.callVoid("op");
}
@Test
public void testCall2() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\":-6,\"message\":\"Domain error\"}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
try{
rpc.call("op" ,Void.class);
fail();
}catch(RemoteException ex){
assertThat(ex.getCode(), is(-6));
assertThat(ex.getMessage(), is("Domain error"));
}
}
@Test
public void testCall3() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\":-6,\"message\":\"Domain exception\"}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
try{
rpc.addRuntimeExceptionMapping(-6, ArithmeticException.class);
rpc.call("op" ,Void.class);
fail();
}catch(ArithmeticException ex){
assertThat(ex.getMessage(), is("Domain exception"));
}
}
@Test
public void testCallVoid() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":{},\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": {}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
rpc.callVoid("op");
}
@Test
public void testCallVoidOrderedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[1.5,\"test\"],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": {}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
rpc.callVoid("op",1.5,"test");
}
@Test
public void testCallVoidNamedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":{\"p1\":1.5,\"p2\":\"test\"},\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": {}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
rpc.callVoid("op",Rpc.RemoteParam("p1", 1.5),Rpc.RemoteParam("p2", "test"));
}
@Test
public void testCallVoidNamedParamsWithException() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":{\"v1\":1.5,\"v2\":\"test\"},\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": {}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
try{
rpc.callVoid("op",Rpc.RemoteParam("v1", 1.5),"test");
fail();
}catch(IllegalArgumentException iae){
assertThat(iae.getMessage(),is("Must pass ALL parameters as named parameters or NONE."));
}
}
@Test
public void testCallInteger() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": 10, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
int result = rpc.callInteger("op");
assertThat( result, is(10) );
}
@Test
public void testCallIntegerOrderedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[false,\"test\"],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": 10, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
int result = rpc.callInteger("op",false,"test");
assertThat( result, is(10) );
}
@Test
public void testCallIntegerNamedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":{\"p1\":false,\"p2\":\"test\"},\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": 10, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
int result = rpc.callInteger("op",Rpc.RemoteParam("p1", false),Rpc.RemoteParam("p2", "test"));
assertThat( result, is(10) );
}
@Test
public void testCallIntegerArray() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": [10,34,23], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
int[] result = rpc.callIntegerArray("op");
assertThat(result, is(new int[]{10,34,23}));
}
@Test
public void testCallIntegerArrayParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"mult10\",\"params\":[true,[1,2,3]],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": [10,20,30], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
int[] result = rpc.callIntegerArray("mult10",true,new int[]{1,2,3});
assertThat(result, is(new int[]{10,20,30}));
}
@Test
public void testCallDouble() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": 1000000, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
double result = rpc.callDouble("op");
assertThat( result, is(1000000d) );
}
@Test
public void testCallDoubleOrderedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[true],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": 1000000, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
double result = rpc.callDouble("op",true);
assertThat( result, is(1000000d) );
}
@Test
public void testCallDoubleNamedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":{\"p1\":true},\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": 1000000, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
double result = rpc.callDouble("op",Rpc.RemoteParam("p1", true));
assertThat( result, is(1000000d) );
}
@Test
public void testCallDoubleArray() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": [10.1,34.4,23.5], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
double[] result = rpc.callDoubleArray("op");
assertThat( result, is(new double[]{10.1,34.4,23.5}));
}
@Test
public void testCallDoubleArrayParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[null],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": [10.1,34.4,23.5], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
double[] result = rpc.callDoubleArray("op", new Object[]{null});
assertThat(result, is(new double[]{10.1,34.4,23.5}));
}
@Test
public void testCallFloat() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": 34.5677, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
float result = rpc.callFloat("op");
assertThat( result, is(34.5677f) );
}
@Test
public void testCallFloatOrderedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat( request.toString(), is("{\"method\":\"op\",\"params\":[true],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": 65.3482374, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
float result = rpc.callFloat("op",true);
assertThat( result, is(65.3482374f) );
}
@Test
public void testCallFloatNamedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":{\"p1\":true},\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": 65.3482374, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
float result = rpc.callFloat("op",Rpc.RemoteParam("p1", true));
assertThat( result, is(65.3482374f) );
}
@Test
public void testCallFloatArray() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": [10.1,34.4,23.5], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
float[] result = rpc.callFloatArray("op");
assertThat(result, is(new float[]{10.1f,34.4f,23.5f}));
}
@Test
public void testCallFloatArrayParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[null],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": [10.1,34.4,23.5], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
float[] result = rpc.callFloatArray("op", new Object[]{null});
assertThat(result, is(new float[]{10.1f,34.4f,23.5f}));
}
@Test
public void testCallString() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": \"foobar\", \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
String result = rpc.callString("op");
assertThat(result, is("foobar"));
}
@Test
public void testCallStringOrderedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[true],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": \"foobar\", \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
String result = rpc.callString("op",true);
assertThat(result, is("foobar"));
}
@Test
public void testCallStringNamedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":{\"p1\":true},\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": \"foobar\", \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
String result = rpc.callString("op",Rpc.RemoteParam("p1", true));
assertThat(result, is("foobar"));
}
@Test
public void testCallStringArray() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": [\"foo\",\"bar\",\"dummy\"], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
String[] result = rpc.callStringArray("op");
assertThat(result, is(new String[]{"foo","bar","dummy"}));
}
@Test
public void testCallStringArrayParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[{\"a\":1,\"b\":\"baz\"}],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": [\"foo\",\"bar\",\"dummy\"], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
Map<String,Object> params = new LinkedHashMap<String, Object>();
params.put("a",1);
params.put("b","baz");
String[] result = rpc.callStringArray("op", params);
assertThat(result, is(new String[]{"foo","bar","dummy"}));
}
@Test
public void testCallBoolean() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": true, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
boolean result = rpc.callBoolean("op");
assertThat( result , is(true) );
}
@Test
public void testCallBooleanOrderedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[1,2,3,\"foo\"],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": false, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
boolean result = rpc.callBoolean("op",1,2,3, "foo" );
assertThat( result, is(false));
}
@Test
public void testCallBooleanNamedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":{\"p1\":1,\"p2\":2,\"p3\":3,\"p4\":\"foo\"},\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": false, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
boolean result = rpc.callBoolean("op",Rpc.RemoteParam("p1", 1),Rpc.RemoteParam("p2", 2),Rpc.RemoteParam("p3", 3),Rpc.RemoteParam("p4", "foo"));
assertThat( result, is(false) );
}
@Test
public void testCallBooleanArray() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": [true,true,false], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
boolean[] result = rpc.callBooleanArray("op");
assertThat(result, is(new boolean[]{true,true,false}));
}
@Test
public void testCallBooleanArrayParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[5],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": [true,true,false], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
boolean[] result = rpc.callBooleanArray("op", 5);
assertThat(result, is(new boolean[]{true,true,false}));
}
@Test
public void testCallShort() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform((String)EasyMock.anyObject()))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": 10, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
short result = rpc.callShort("op");
assertThat( result, is((short)10) );
}
@Test
public void testCallShortOrderedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[false,\"test\"],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": 10, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
short result = rpc.callShort("op",false,"test");
assertThat( result, is((short)10) );
}
@Test
public void testCallShortNamedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":{\"p1\":false,\"p2\":\"test\"},\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": 10, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
short result = rpc.callShort("op",Rpc.RemoteParam("p1", false),Rpc.RemoteParam("p2", "test"));
assertThat( result, is((short)10) );
}
@Test
public void testCallShortArray() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": [10,34,23], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
short[] result = rpc.callShortArray("op");
assertThat(result, is(new short[]{10,34,23}));
}
@Test
public void testCallShortArrayParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"mult10\",\"params\":[true,false],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": [10,20,30], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
short[] result = rpc.callShortArray("mult10",true,false);
assertThat(result, is(new short[]{10,20,30}));
}
@Test
public void testCallLong() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": 10, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
long result = rpc.callLong("op");
assertThat( result, is(10L) );
}
@Test
public void testCallLongOrderedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[false,\"test\"],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": 10, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
long result = rpc.callLong("op",false,"test");
assertThat( result, is(10L) );
}
@Test
public void testCallLongNamedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is(not("{\"method\":\"op\",\"params\":[false,\"test\"],\"jsonrpc\":\"2.0\",\"id\":1}")));
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":{\"p1\":false,\"p2\":\"test\"},\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": 10, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
long result = rpc.callLong("op",Rpc.RemoteParam("p1", false),Rpc.RemoteParam("p2", "test"));
assertThat( result, is(10L) );
}
@Test
public void testCallLongArray() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": [10,34,23], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
long[] result = rpc.callLongArray("op");
assertThat(result, is(new long[]{10,34,23}));
}
@Test
public void testCallLongArrayParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"mult10\",\"params\":[true,false],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": [10,20,30], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
long[] result = rpc.callLongArray("mult10",true,false);
assertThat(result, is(new long[]{10,20,30}));
}
@Test
public void testCallChar() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": \"a\", \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
char result = rpc.callChar("op");
//System.out.println(String.format("%04x", (int) result));
assertThat( result, is((char)0x61) );
assertThat( result, is('a') );
}
@Test
public void testCallCharOrderedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[false,\"test\"],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": \"a\", \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
char result = rpc.callChar("op",false,"test");
assertThat( result, is('a') );
}
@Test
public void testCallCharNamedParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":{\"p1\":false,\"p2\":\"test\"},\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": \"a\", \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
char result = rpc.callChar("op",Rpc.RemoteParam("p1", false),Rpc.RemoteParam("p2", "test"));
assertThat( result, is('a') );
}
@Test
public void testCallCharArray() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"result\": [\"a\",\"b\",\"c\"], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
char[] result = rpc.callCharArray("op");
assertThat( result, is(new char[]{'a','b','c'}));
}
@Test
public void testCallCharArrayParams() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":[1,{\"x\":2,\"y\":3,\"b\":{\"z\":\"bar\",\"f\":5.6}}],\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": [\"a\",\"b\",\"c\"], \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
A a = new A(2,3);
a.b = new B("bar",5.6f);
char[] result = rpc.callCharArray("op",1,a);
assertThat(result, is(new char[]{'a','b','c'}));
}
@Test
public void testCallTimeout() throws Exception{
TestServer server = new TestServer(4444);
server.setIdleTime(5000);
final HttpRequest request = (HttpRequest)server.createTestRequester(new HttpRequest(), "perform");
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost:4444/rpc")
.readTimeout(1000)
.requestRetries(0);
Rpc.Sync rpc = new Rpc.Sync(builder);
try{
rpc.callVoid("test");
fail();
}catch(SocketTimeoutException ste){
assertThat( ste.getMessage(), is("Read timed out"));
server.finish();
}
}
public static class MyRemoteException extends RuntimeException{
public MyRemoteException(){
super();
}
public MyRemoteException(String message){
super(message);
}
}
@Test
public void testAddRuntimeExceptionMapping() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
EasyMock.expect(request.perform( (String)EasyMock.anyObject() ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\":-10,\"message\":\"Remote exception\"}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Sync rpc = new Rpc.Sync(builder);
try{
rpc.addRuntimeExceptionMapping(-10, MyRemoteException.class);
rpc.callVoid("test");
fail();
}catch(MyRemoteException ex){
assertThat(ex.getMessage(), is("Remote exception"));
}
}
@Test
public void testCallMultiThread() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), startsWith("{\"method\":\"op\",\"params\":{},\"jsonrpc\":\"2.0\",\"id\":"));
return "{\"jsonrpc\": \"2.0\", \"result\": {}, \"id\": 2}";
}
}).times(5);
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
final Rpc.Sync rpc = new Rpc.Sync(builder);
Thread threads[] = new Thread[5];
for(int i=0; i<5; i++){
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
try{
rpc.callVoid("op");
}catch(Exception ex){
}
}
});
threads[i].start();
}
for(Thread t: threads)
t.join();
}
@Test
public void testCallVoidAsync() throws Exception{
final HttpRequest request = EasyMock.createNiceMock(HttpRequest.class);
final Capture<String> requestCapture = new Capture<String>();
EasyMock.expect(request.perform( EasyMock.capture(requestCapture) ))
.andAnswer(new IAnswer<String>() {
public String answer() throws Throwable{
String request = requestCapture.getValue();
assertThat(request.toString(), is("{\"method\":\"op\",\"params\":{},\"jsonrpc\":\"2.0\",\"id\":1}"));
return "{\"jsonrpc\": \"2.0\", \"result\": {}, \"id\": 2}";
}
});
EasyMock.replay(request);
HttpRequestBuilder builder = new HttpRequestBuilder(){
@Override
protected HttpRequest newInstance(){
return request;
}
}.endpoint("http://localhost");
Rpc.Async rpc = new Rpc.Async(builder);
rpc.callVoid("op");
}
} |
package hudson.tasks.junit;
import hudson.FilePath.FileCallable;
import hudson.Launcher;
import hudson.Util;
import hudson.matrix.MatrixAggregatable;
import hudson.matrix.MatrixAggregator;
import hudson.matrix.MatrixBuild;
import hudson.model.Action;
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.Result;
import hudson.remoting.VirtualChannel;
import hudson.tasks.Publisher;
import hudson.tasks.test.TestResultAggregator;
import hudson.tasks.test.TestResultProjectAction;
import hudson.util.FormFieldValidator;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
/**
* Generates HTML report from JUnit test result XML files.
*
* @author Kohsuke Kawaguchi
*/
public class JUnitResultArchiver extends Publisher implements Serializable, MatrixAggregatable {
* {@link FileSet} "includes" string, like "foo/bar/*.xml"
*/
private final String testResults;
public JUnitResultArchiver(String testResults) {
this.testResults = testResults;
}
private static final class RecordResult implements Serializable {
final TestResult tr;
final String afile;
final long lastModified;
RecordResult(TestResult tr, String afile, long lastModified) {
this.tr = tr;
this.afile = afile;
this.lastModified = lastModified;
}
private static final long serialVersionUID = 1L;
}
public boolean perform(Build build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
RecordResult result;
listener.getLogger().println("Recording test results");
try {
final long buildTime = build.getTimestamp().getTimeInMillis();
result = build.getProject().getWorkspace().act(new FileCallable<RecordResult>() {
public RecordResult invoke(File ws, VirtualChannel channel) throws IOException {
FileSet fs = new FileSet();
Project p = new Project();
fs.setProject(p);
fs.setDir(ws);
fs.setIncludes(testResults);
DirectoryScanner ds = fs.getDirectoryScanner(p);
String[] files = ds.getIncludedFiles();
if(files.length==0) {
// no test result. Most likely a configuration error or fatal problem
throw new AbortException("No test report files were found. Configuration error?");
}
File oneFile = new File(ds.getBasedir(),files[0]);
return new RecordResult(new TestResult(buildTime,ds),files[0],oneFile.lastModified());
}
});
} catch (AbortException e) {
listener.getLogger().println(e.getMessage());
build.setResult(Result.FAILURE);
return true;
}
TestResultAction action = new TestResultAction(build, result.tr, listener);
TestResult r = action.getResult();
if(r.getPassCount()==0 && r.getFailCount()==0) {
listener.getLogger().println("Test reports were found but none of them are new. Did tests run?");
listener.getLogger().printf("For example, %s is %s old\n",result.afile,
Util.getTimeSpanString(result.lastModified-build.getTimestamp().getTimeInMillis()));
// no test result. Most likely a configuration error or fatal problem
build.setResult(Result.FAILURE);
} else {
build.getActions().add(action);
}
if(r.getFailCount()>0)
build.setResult(Result.UNSTABLE);
return true;
}
public String getTestResults() {
return testResults;
}
public Action getProjectAction(hudson.model.Project project) {
return new TestResultProjectAction(project);
}
public MatrixAggregator createAggregator(MatrixBuild build, Launcher launcher, BuildListener listener) {
return new TestResultAggregator(build,launcher,listener);
}
public Descriptor<Publisher> getDescriptor() {
return DescriptorImpl.DESCRIPTOR;
}
private static final long serialVersionUID = 1L;
public static class DescriptorImpl extends Descriptor<Publisher> {
public static final Descriptor<Publisher> DESCRIPTOR = new DescriptorImpl();
public DescriptorImpl() {
super(JUnitResultArchiver.class);
}
public String getDisplayName() {
return "Publish JUnit test result report";
}
public String getHelpFile() {
return "/help/tasks/junit/report.html";
}
/**
* Performs on-the-fly validation on the file mask wildcard.
*/
public void doCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator.WorkspaceFileMask(req,rsp).process();
}
public Publisher newInstance(StaplerRequest req) {
return new JUnitResultArchiver(req.getParameter("junitreport_includes"));
}
}
} |
package edu.umd.cs.findbugs;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MethodGen;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.JavaClassAndMethod;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.bcp.FieldVariable;
import edu.umd.cs.findbugs.classfile.ClassDescriptor;
import edu.umd.cs.findbugs.classfile.FieldDescriptor;
import edu.umd.cs.findbugs.classfile.MethodDescriptor;
import edu.umd.cs.findbugs.util.ClassName;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
import edu.umd.cs.findbugs.xml.XMLAttributeList;
import edu.umd.cs.findbugs.xml.XMLOutput;
/**
* An instance of a bug pattern.
* A BugInstance consists of several parts:
* <p/>
* <ul>
* <li> the type, which is a string indicating what kind of bug it is;
* used as a key for the FindBugsMessages resource bundle
* <li> the priority; how likely this instance is to actually be a bug
* <li> a list of <em>annotations</em>
* </ul>
* <p/>
* The annotations describe classes, methods, fields, source locations,
* and other relevant context information about the bug instance.
* Every BugInstance must have at least one ClassAnnotation, which
* describes the class in which the instance was found. This is the
* "primary class annotation".
* <p/>
* <p> BugInstance objects are built up by calling a string of <code>add</code>
* methods. (These methods all "return this", so they can be chained).
* Some of the add methods are specialized to get information automatically from
* a BetterVisitor or DismantleBytecode object.
*
* @author David Hovemeyer
* @see BugAnnotation
*/
public class BugInstance implements Comparable<BugInstance>, XMLWriteableWithMessages, Serializable, Cloneable {
private static final long serialVersionUID = 1L;
private String type;
private int priority;
private ArrayList<BugAnnotation> annotationList;
private int cachedHashCode;
private @CheckForNull BugDesignation userDesignation;
private BugProperty propertyListHead, propertyListTail;
private String uniqueId;
private String oldInstanceHash;
private String instanceHash;
private int instanceOccurrenceNum;
private int instanceOccurrenceMax;
/*
* The following fields are used for tracking Bug instances across multiple versions of software.
* They are meaningless in a BugCollection for just one version of software.
*/
private long firstVersion = 0;
private long lastVersion = -1;
private boolean introducedByChangeOfExistingClass;
private boolean removedByChangeOfPersistingClass;
/**
* This value is used to indicate that the cached hashcode
* is invalid, and should be recomputed.
*/
private static final int INVALID_HASH_CODE = 0;
/**
* This value is used to indicate whether BugInstances should be reprioritized very low,
* when the BugPattern is marked as experimental
*/
private static boolean adjustExperimental = false;
/**
* Constructor.
*
* @param type the bug type
* @param priority the bug priority
*/
public BugInstance(String type, int priority) {
this.type = type;
this.priority = priority < Detector.HIGH_PRIORITY
? Detector.HIGH_PRIORITY : priority;
annotationList = new ArrayList<BugAnnotation>(4);
cachedHashCode = INVALID_HASH_CODE;
if (adjustExperimental && isExperimental())
this.priority = Detector.EXP_PRIORITY;
}
//@Override
@Override
public Object clone() {
BugInstance dup;
try {
dup = (BugInstance) super.clone();
// Do deep copying of mutable objects
for (int i = 0; i < dup.annotationList.size(); ++i) {
dup.annotationList.set(i, (BugAnnotation) dup.annotationList.get(i).clone());
}
dup.propertyListHead = dup.propertyListTail = null;
for (Iterator<BugProperty> i = propertyIterator(); i.hasNext(); ) {
dup.addProperty((BugProperty) i.next().clone());
}
return dup;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
/**
* Create a new BugInstance.
* This is the constructor that should be used by Detectors.
*
* @param detector the Detector that is reporting the BugInstance
* @param type the bug type
* @param priority the bug priority
*/
public BugInstance(Detector detector, String type, int priority) {
this(type, priority);
if (detector != null) {
// Adjust priority if required
DetectorFactory factory =
DetectorFactoryCollection.instance().getFactoryByClassName(detector.getClass().getName());
if (factory != null) {
this.priority += factory.getPriorityAdjustment();
if (this.priority < 0)
this.priority = 0;
}
}
if (adjustExperimental && isExperimental())
this.priority = Detector.EXP_PRIORITY;
}
public static void setAdjustExperimental(boolean adjust) {
adjustExperimental = adjust;
}
/**
* Get the bug type.
*/
public String getType() {
return type;
}
/**
* Get the BugPattern.
*/
public BugPattern getBugPattern() {
return I18N.instance().lookupBugPattern(getType());
}
/**
* Get the bug priority.
*/
public int getPriority() {
return priority;
}
/**
* Get a string describing the bug priority and type.
* e.g. "High Priority Correctness"
* @return a string describing the bug priority and type
*/
public String getPriorityTypeString()
{
String priorityString = getPriorityString();
//then get the category and put everything together
String categoryString = I18N.instance().getBugCategoryDescription(this.getBugPattern().getCategory());
return priorityString + " Priority " + categoryString;
//TODO: internationalize the word "Priority"
}
public String getPriorityTypeAbbreviation()
{
String priorityString = getPriorityAbbreviation();
return priorityString + " " + getBugPattern().getCategoryAbbrev();
}
public String getPriorityString() {
//first, get the priority
int value = this.getPriority();
String priorityString;
if (value == Detector.HIGH_PRIORITY)
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_high", "High");
else if (value == Detector.NORMAL_PRIORITY)
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_normal", "Normal");
else if (value == Detector.LOW_PRIORITY)
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_low", "Low");
else if (value == Detector.EXP_PRIORITY)
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_experimental", "Experimental");
else
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_ignore", "Ignore"); // This probably shouldn't ever happen, but what the hell, let's be complete
return priorityString;
}
public String getPriorityAbbreviation() {
return getPriorityString().substring(0,1);
}
/**
* Set the bug priority.
*/
public void setPriority(int p) {
priority = Math.max(Detector.HIGH_PRIORITY, Math.min(Detector.IGNORE_PRIORITY, p));
}
public void raisePriority() {
priority = Math.max(Detector.HIGH_PRIORITY, Math.min(Detector.IGNORE_PRIORITY, priority-1));
}
public void lowerPriority() {
priority = Math.max(Detector.HIGH_PRIORITY, Math.min(Detector.IGNORE_PRIORITY, priority+1));
}
public void lowerPriorityALot() {
priority = Math.max(Detector.HIGH_PRIORITY, Math.min(Detector.IGNORE_PRIORITY, priority+2));
}
/**
* Is this bug instance the result of an experimental detector?
*/
public boolean isExperimental() {
BugPattern pattern = I18N.instance().lookupBugPattern(type);
return (pattern != null) && pattern.isExperimental();
}
/**
* Get the primary class annotation, which indicates where the bug occurs.
*/
public ClassAnnotation getPrimaryClass() {
return (ClassAnnotation) findAnnotationOfType(ClassAnnotation.class);
}
/**
* Get the primary method annotation, which indicates where the bug occurs.
*/
public MethodAnnotation getPrimaryMethod() {
return (MethodAnnotation) findAnnotationOfType(MethodAnnotation.class);
}
/**
* Get the primary method annotation, which indicates where the bug occurs.
*/
public FieldAnnotation getPrimaryField() {
return (FieldAnnotation) findAnnotationOfType(FieldAnnotation.class);
}
public BugInstance lowerPriorityIfDeprecated() {
MethodAnnotation m = getPrimaryMethod();
if (m != null && AnalysisContext.currentXFactory().getDeprecated().contains(XFactory.createXMethod(m)))
priority++;
FieldAnnotation f = getPrimaryField();
if (f != null && AnalysisContext.currentXFactory().getDeprecated().contains(XFactory.createXField(f)))
priority++;
return this;
}
/**
* Find the first BugAnnotation in the list of annotations
* that is the same type or a subtype as the given Class parameter.
*
* @param cls the Class parameter
* @return the first matching BugAnnotation of the given type,
* or null if there is no such BugAnnotation
*/
private BugAnnotation findAnnotationOfType(Class<? extends BugAnnotation> cls) {
for (Iterator<BugAnnotation> i = annotationIterator(); i.hasNext();) {
BugAnnotation annotation = i.next();
if (cls.isAssignableFrom(annotation.getClass()))
return annotation;
}
return null;
}
public LocalVariableAnnotation getPrimaryLocalVariableAnnotation() {
for (BugAnnotation annotation : annotationList)
if (annotation instanceof LocalVariableAnnotation)
return (LocalVariableAnnotation) annotation;
return null;
}
/**
* Get the primary source line annotation.
* There is guaranteed to be one (unless some Detector constructed
* an invalid BugInstance).
*
* @return the source line annotation
*/
public SourceLineAnnotation getPrimarySourceLineAnnotation() {
// Highest priority: return the first top level source line annotation
for (BugAnnotation annotation : annotationList) {
if (annotation instanceof SourceLineAnnotation)
return (SourceLineAnnotation) annotation;
}
// Next: Try primary method, primary field, primary class
SourceLineAnnotation srcLine;
if ((srcLine = inspectPackageMemberSourceLines(getPrimaryMethod())) != null)
return srcLine;
if ((srcLine = inspectPackageMemberSourceLines(getPrimaryField())) != null)
return srcLine;
if ((srcLine = inspectPackageMemberSourceLines(getPrimaryClass())) != null)
return srcLine;
// Last resort: throw exception
throw new IllegalStateException("BugInstance must contain at least one class, method, or field annotation");
}
public String getInstanceKey() {
StringBuffer buf = new StringBuffer(type);
for (BugAnnotation annotation : annotationList) {
if (annotation instanceof SourceLineAnnotation) {
// do nothing
} else {
buf.append(":");
buf.append(annotation.format("hash", null));
}
}
return buf.toString();
}
/**
* If given PackageMemberAnnotation is non-null, return its
* SourceLineAnnotation.
*
* @param packageMember
* a PackageMemberAnnotation
* @return the PackageMemberAnnotation's SourceLineAnnotation, or null if
* there is no SourceLineAnnotation
*/
private SourceLineAnnotation inspectPackageMemberSourceLines(PackageMemberAnnotation packageMember) {
return (packageMember != null) ? packageMember.getSourceLines() : null;
}
/**
* Get an Iterator over all bug annotations.
*/
public Iterator<BugAnnotation> annotationIterator() {
return annotationList.iterator();
}
/**
* Get the abbreviation of this bug instance's BugPattern.
* This is the same abbreviation used by the BugCode which
* the BugPattern is a particular species of.
*/
public String getAbbrev() {
BugPattern pattern = I18N.instance().lookupBugPattern(getType());
return pattern != null ? pattern.getAbbrev() : "<unknown bug pattern>";
}
/** set the user designation object. This will clobber any
* existing annotationText (or any other BugDesignation field). */
public void setUserDesignation(BugDesignation bd) {
userDesignation = bd;
}
/** return the user designation object, which may be null.
*
* A previous calls to getSafeUserDesignation(), setAnnotationText(),
* or setUserDesignation() will ensure it will be non-null
* [barring an intervening setUserDesignation(null)].
* @see #getNonnullUserDesignation() */
@Nullable public BugDesignation getUserDesignation() {
return userDesignation;
}
/** return the user designation object, creating one if
* necessary. So calling
* <code>getSafeUserDesignation().setDesignation("HARMLESS")</code>
* will always work without the possibility of a NullPointerException.
* @see #getUserDesignation() */
@NonNull public BugDesignation getNonnullUserDesignation() {
if (userDesignation == null)
userDesignation = new BugDesignation();
return userDesignation;
}
/** Get the user designation key.
* E.g., "MOSTLY_HARMLESS", "CRITICAL", "NOT_A_BUG", etc.
*
* If the user designation object is null,returns UNCLASSIFIED.
*
* To set the user designation key, call
* <code>getSafeUserDesignation().setDesignation("HARMLESS")</code>.
*
* @see I18N#getUserDesignation(String key)
* @return the user designation key
*/
@NonNull public String getUserDesignationKey() {
BugDesignation userDesignation = this.userDesignation;
if (userDesignation == null) return BugDesignation.UNCLASSIFIED;
return userDesignation.getDesignationKey();
}
/**
* Set the user annotation text.
*
* @param annotationText the user annotation text
*/
public void setAnnotationText(String annotationText) {
getNonnullUserDesignation().setAnnotationText(annotationText);
}
/**
* Get the user annotation text.
*
* @return the user annotation text
*/
@NonNull public String getAnnotationText() {
BugDesignation userDesignation = this.userDesignation;
if (userDesignation == null) return "";
String s = userDesignation.getAnnotationText();
if (s == null) return "";
return s;
}
/**
* Determine whether or not the annotation text contains
* the given word.
*
* @param word the word
* @return true if the annotation text contains the word, false otherwise
*/
public boolean annotationTextContainsWord(String word) {
return getTextAnnotationWords().contains(word);
}
/**
* Get set of words in the text annotation.
*/
public Set<String> getTextAnnotationWords() {
HashSet<String> result = new HashSet<String>();
StringTokenizer tok = new StringTokenizer(getAnnotationText(), " \t\r\n\f.,:;-");
while (tok.hasMoreTokens()) {
result.add(tok.nextToken());
}
return result;
}
/**
* Get the BugInstance's unique id.
*
* @return the unique id, or null if no unique id has been assigned
*
* Deprecated, since it isn't persistent
*/
@Deprecated
public String getUniqueId() {
return uniqueId;
}
/**
* Set the unique id of the BugInstance.
*
* @param uniqueId the unique id
*
* * Deprecated, since it isn't persistent
*/
@Deprecated
void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
}
private class BugPropertyIterator implements Iterator<BugProperty> {
private BugProperty prev, cur;
private boolean removed;
/* (non-Javadoc)
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return findNext() != null;
}
/* (non-Javadoc)
* @see java.util.Iterator#next()
*/
public BugProperty next() {
BugProperty next = findNext();
if (next == null)
throw new NoSuchElementException();
prev = cur;
cur = next;
removed = false;
return cur;
}
/* (non-Javadoc)
* @see java.util.Iterator#remove()
*/
public void remove() {
if (cur == null || removed)
throw new IllegalStateException();
if (prev == null) {
propertyListHead = cur.getNext();
} else {
prev.setNext(cur.getNext());
}
if (cur == propertyListTail) {
propertyListTail = prev;
}
removed = true;
}
private BugProperty findNext() {
return cur == null ? propertyListHead : cur.getNext();
}
}
/**
* Get value of given property.
*
* @param name name of the property to get
* @return the value of the named property, or null if
* the property has not been set
*/
public String getProperty(String name) {
BugProperty prop = lookupProperty(name);
return prop != null ? prop.getValue() : null;
}
/**
* Get value of given property, returning given default
* value if the property has not been set.
*
* @param name name of the property to get
* @param defaultValue default value to return if propery is not set
* @return the value of the named property, or the default
* value if the property has not been set
*/
public String getProperty(String name, String defaultValue) {
String value = getProperty(name);
return value != null ? value : defaultValue;
}
/**
* Get an Iterator over the properties defined in this BugInstance.
*
* @return Iterator over properties
*/
public Iterator<BugProperty> propertyIterator() {
return new BugPropertyIterator();
}
/**
* Set value of given property.
*
* @param name name of the property to set
* @param value the value of the property
* @return this object, so calls can be chained
*/
public BugInstance setProperty(String name, String value) {
BugProperty prop = lookupProperty(name);
if (prop != null) {
prop.setValue(value);
} else {
prop = new BugProperty(name, value);
addProperty(prop);
}
return this;
}
/**
* Look up a property by name.
*
* @param name name of the property to look for
* @return the BugProperty with the given name,
* or null if the property has not been set
*/
public BugProperty lookupProperty(String name) {
BugProperty prop = propertyListHead;
while (prop != null) {
if (prop.getName().equals(name))
break;
prop = prop.getNext();
}
return prop;
}
/**
* Delete property with given name.
*
* @param name name of the property to delete
* @return true if a property with that name was deleted,
* or false if there is no such property
*/
public boolean deleteProperty(String name) {
BugProperty prev = null;
BugProperty prop = propertyListHead;
while (prop != null) {
if (prop.getName().equals(name))
break;
prev = prop;
prop = prop.getNext();
}
if (prop != null) {
if (prev != null) {
// Deleted node in interior or at tail of list
prev.setNext(prop.getNext());
} else {
// Deleted node at head of list
propertyListHead = prop.getNext();
}
if (prop.getNext() == null) {
// Deleted node at end of list
propertyListTail = prev;
}
return true;
} else {
// No such property
return false;
}
}
private void addProperty(BugProperty prop) {
if (propertyListTail != null) {
propertyListTail.setNext(prop);
propertyListTail = prop;
} else {
propertyListHead = propertyListTail = prop;
}
prop.setNext(null);
}
/**
* Add a Collection of BugAnnotations.
*
* @param annotationCollection Collection of BugAnnotations
*/
public BugInstance addAnnotations(Collection<? extends BugAnnotation> annotationCollection) {
for (BugAnnotation annotation : annotationCollection) {
add(annotation);
}
return this;
}
public BugInstance addClassAndMethod(MethodDescriptor methodDescriptor) {
addClass(methodDescriptor.getClassName());
add(MethodAnnotation.fromMethodDescriptor(methodDescriptor));
return this;
}
/**
* Add a class annotation and a method annotation for the class and method
* which the given visitor is currently visiting.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addClassAndMethod(PreorderVisitor visitor) {
addClass(visitor);
addMethod(visitor);
return this;
}
/**
* Add class and method annotations for given method.
*
* @param methodAnnotation the method
* @return this object
*/
public BugInstance addClassAndMethod(MethodAnnotation methodAnnotation) {
addClass(methodAnnotation.getClassName());
addMethod(methodAnnotation);
return this;
}
/**
* Add class and method annotations for given method.
*
* @param methodGen the method
* @param sourceFile source file the method is defined in
* @return this object
*/
public BugInstance addClassAndMethod(MethodGen methodGen, String sourceFile) {
addClass(methodGen.getClassName());
addMethod(methodGen, sourceFile);
return this;
}
/**
* Add class and method annotations for given class and method.
*
* @param javaClass the class
* @param method the method
* @return this object
*/
public BugInstance addClassAndMethod(JavaClass javaClass, Method method) {
addClass(javaClass.getClassName());
addMethod(javaClass, method);
return this;
}
/**
* Add a class annotation. If this is the first class annotation added,
* it becomes the primary class annotation.
*
* @param className the name of the class
* @param sourceFileName the source file of the class
* @return this object
* @deprecated use addClass(String) instead
*/
public BugInstance addClass(String className, String sourceFileName) {
ClassAnnotation classAnnotation = new ClassAnnotation(className);
add(classAnnotation);
return this;
}
/**
* Add a class annotation. If this is the first class annotation added,
* it becomes the primary class annotation.
*
* @param className the name of the class
* @return this object
*/
public BugInstance addClass(String className) {
className = ClassName.toDottedClassName(className);
ClassAnnotation classAnnotation = new ClassAnnotation(className);
add(classAnnotation);
return this;
}
/**
* Add a class annotation. If this is the first class annotation added,
* it becomes the primary class annotation.
*
* @param classDescriptor the class to add
* @return this object
*/
public BugInstance addClass(ClassDescriptor classDescriptor) {
add(ClassAnnotation.fromClassDescriptor(classDescriptor));
return this;
}
/**
* Add a class annotation. If this is the first class annotation added,
* it becomes the primary class annotation.
*
* @param jclass the JavaClass object for the class
* @return this object
*/
public BugInstance addClass(JavaClass jclass) {
addClass(jclass.getClassName());
return this;
}
/**
* Add a class annotation for the class that the visitor is currently visiting.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addClass(PreorderVisitor visitor) {
String className = visitor.getDottedClassName();
addClass(className);
return this;
}
/**
* Add a class annotation for the superclass of the class the visitor
* is currently visiting.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addSuperclass(PreorderVisitor visitor) {
String className = visitor.getSuperclassName();
addClass(className);
return this;
}
public BugInstance addType(String typeDescriptor) {
TypeAnnotation typeAnnotation = new TypeAnnotation(typeDescriptor);
add(typeAnnotation);
return this;
}
public BugInstance addFoundAndExpectedType(String foundType, String expectedType) {
add( new TypeAnnotation(foundType)).describe(TypeAnnotation.FOUND_ROLE);
add( new TypeAnnotation(expectedType)).describe(TypeAnnotation.EXPECTED_ROLE);
return this;
}
public BugInstance addTypeOfNamedClass(String typeName) {
TypeAnnotation typeAnnotation = new TypeAnnotation("L" + typeName.replace('.','/')+";");
add(typeAnnotation);
return this;
}
/**
* Add a field annotation.
*
* @param className name of the class containing the field
* @param fieldName the name of the field
* @param fieldSig type signature of the field
* @param isStatic whether or not the field is static
* @return this object
*/
public BugInstance addField(String className, String fieldName, String fieldSig, boolean isStatic) {
addField(new FieldAnnotation(className, fieldName, fieldSig, isStatic));
return this;
}
/**
* Add a field annotation
*
* @param fieldAnnotation the field annotation
* @return this object
*/
public BugInstance addField(FieldAnnotation fieldAnnotation) {
add(fieldAnnotation);
return this;
}
/**
* Add a field annotation for a FieldVariable matched in a ByteCodePattern.
*
* @param field the FieldVariable
* @return this object
*/
public BugInstance addField(FieldVariable field) {
return addField(field.getClassName(), field.getFieldName(), field.getFieldSig(), field.isStatic());
}
/**
* Add a field annotation for an XField.
*
* @param xfield the XField
* @return this object
*/
public BugInstance addField(XField xfield) {
return addField(xfield.getClassName(), xfield.getName(), xfield.getSignature(), xfield.isStatic());
}
/**
* Add a field annotation for a FieldDescriptor.
*
* @param fieldDescriptor the FieldDescriptor
* @return this object
*/
public BugInstance addField(FieldDescriptor fieldDescriptor) {
FieldAnnotation fieldAnnotation = FieldAnnotation.fromFieldDescriptor(fieldDescriptor);
add(fieldAnnotation);
return this;
}
/**
* Add a field annotation for the field which has just been accessed
* by the method currently being visited by given visitor.
* Assumes that a getfield/putfield or getstatic/putstatic
* has just been seen.
*
* @param visitor the DismantleBytecode object
* @return this object
*/
public BugInstance addReferencedField(DismantleBytecode visitor) {
FieldAnnotation f = FieldAnnotation.fromReferencedField(visitor);
addField(f);
return this;
}
/**
* Add a field annotation for the field referenced by the FieldAnnotation parameter
*/
public BugInstance addReferencedField(FieldAnnotation fa) {
addField(fa);
return this;
}
/**
* Add a field annotation for the field which is being visited by
* given visitor.
*
* @param visitor the visitor
* @return this object
*/
public BugInstance addVisitedField(PreorderVisitor visitor) {
FieldAnnotation f = FieldAnnotation.fromVisitedField(visitor);
addField(f);
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
*
* @param className name of the class containing the method
* @param methodName name of the method
* @param methodSig type signature of the method
* @param isStatic true if the method is static, false otherwise
* @return this object
*/
public BugInstance addMethod(String className, String methodName, String methodSig, boolean isStatic) {
addMethod(MethodAnnotation.fromForeignMethod(className, methodName, methodSig, isStatic));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param methodGen the MethodGen object for the method
* @param sourceFile source file method is defined in
* @return this object
*/
public BugInstance addMethod(MethodGen methodGen, String sourceFile) {
String className = methodGen.getClassName();
MethodAnnotation methodAnnotation =
new MethodAnnotation(className, methodGen.getName(), methodGen.getSignature(), methodGen.isStatic());
addMethod(methodAnnotation);
addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(methodGen, sourceFile));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param javaClass the class the method is defined in
* @param method the method
* @return this object
*/
public BugInstance addMethod(JavaClass javaClass, Method method) {
MethodAnnotation methodAnnotation =
new MethodAnnotation(javaClass.getClassName(), method.getName(), method.getSignature(), method.isStatic());
SourceLineAnnotation methodSourceLines = SourceLineAnnotation.forEntireMethod(
javaClass,
method);
methodAnnotation.setSourceLines(methodSourceLines);
addMethod(methodAnnotation);
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param classAndMethod JavaClassAndMethod identifying the method to add
* @return this object
*/
public BugInstance addMethod(JavaClassAndMethod classAndMethod) {
return addMethod(classAndMethod.getJavaClass(), classAndMethod.getMethod());
}
/**
* Add a method annotation for the method which the given visitor is currently visiting.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addMethod(PreorderVisitor visitor) {
MethodAnnotation methodAnnotation = MethodAnnotation.fromVisitedMethod(visitor);
addMethod(methodAnnotation);
addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(visitor));
return this;
}
/**
* Add a method annotation for the method which has been called
* by the method currently being visited by given visitor.
* Assumes that the visitor has just looked at an invoke instruction
* of some kind.
*
* @param visitor the DismantleBytecode object
* @return this object
*/
public BugInstance addCalledMethod(DismantleBytecode visitor) {
return addMethod(MethodAnnotation.fromCalledMethod(visitor)).describe("METHOD_CALLED");
}
/**
* Add a method annotation.
*
* @param className name of class containing called method
* @param methodName name of called method
* @param methodSig signature of called method
* @param isStatic true if called method is static, false if not
* @return this object
*/
public BugInstance addCalledMethod(String className, String methodName, String methodSig, boolean isStatic) {
return addMethod(MethodAnnotation.fromCalledMethod(className, methodName, methodSig, isStatic)).describe("METHOD_CALLED");
}
/**
* Add a method annotation for the method which is called by given
* instruction.
*
* @param methodGen the method containing the call
* @param inv the InvokeInstruction
* @return this object
*/
public BugInstance addCalledMethod(MethodGen methodGen, InvokeInstruction inv) {
ConstantPoolGen cpg = methodGen.getConstantPool();
String className = inv.getClassName(cpg);
String methodName = inv.getMethodName(cpg);
String methodSig = inv.getSignature(cpg);
addMethod(className, methodName, methodSig, inv.getOpcode() == Constants.INVOKESTATIC);
describe("METHOD_CALLED");
return this;
}
/**
* Add a MethodAnnotation from an XMethod.
*
* @param xmethod the XMethod
* @return this object
*/
public BugInstance addMethod(XMethod xmethod) {
addMethod(MethodAnnotation.fromXMethod(xmethod));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
*
* @param methodAnnotation the method annotation
* @return this object
*/
public BugInstance addMethod(MethodAnnotation methodAnnotation) {
add(methodAnnotation);
return this;
}
/**
* Add an integer annotation.
*
* @param value the integer value
* @return this object
*/
public BugInstance addInt(int value) {
add(new IntAnnotation(value));
return this;
}
/**
* Add a String annotation.
*
* @param value the String value
* @return this object
*/
public BugInstance addString(String value) {
add(new StringAnnotation(value));
return this;
}
/**
* Add a source line annotation.
*
* @param sourceLine the source line annotation
* @return this object
*/
public BugInstance addSourceLine(SourceLineAnnotation sourceLine) {
add(sourceLine);
return this;
}
/**
* Add a source line annotation for instruction whose PC is given
* in the method that the given visitor is currently visiting.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param visitor a BytecodeScanningDetector that is currently visiting the method
* @param pc bytecode offset of the instruction
* @return this object
*/
public BugInstance addSourceLine(BytecodeScanningDetector visitor, int pc) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstruction(visitor.getClassContext(), visitor, pc);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for instruction whose PC is given
* in the method that the given visitor is currently visiting.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param classContext the ClassContext
* @param visitor a PreorderVisitor that is currently visiting the method
* @param pc bytecode offset of the instruction
* @return this object
*/
public BugInstance addSourceLine(ClassContext classContext, PreorderVisitor visitor, int pc) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstruction(classContext, visitor, pc);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for the given instruction in the given method.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param classContext the ClassContext
* @param methodGen the method being visited
* @param sourceFile source file the method is defined in
* @param handle the InstructionHandle containing the visited instruction
* @return this object
*/
public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, @NonNull InstructionHandle handle) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation describing a range of instructions.
*
* @param classContext the ClassContext
* @param methodGen the method
* @param sourceFile source file the method is defined in
* @param start the start instruction in the range
* @param end the end instruction in the range (inclusive)
* @return this object
*/
public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, InstructionHandle start, InstructionHandle end) {
// Make sure start and end are really in the right order.
if (start.getPosition() > end.getPosition()) {
InstructionHandle tmp = start;
start = end;
end = tmp;
}
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstructionRange(classContext, methodGen, sourceFile, start, end);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add source line annotation for given Location in a method.
*
* @param classContext the ClassContext
* @param method the Method
* @param location the Location in the method
* @return this BugInstance
*/
public BugInstance addSourceLine(ClassContext classContext, Method method, Location location) {
MethodGen methodGen = classContext.getMethodGen(method);
return addSourceLine(
classContext,
methodGen,
classContext.getJavaClass().getSourceFileName(),
location.getHandle());
}
/**
* Add a source line annotation describing the
* source line numbers for a range of instructions in the method being
* visited by the given visitor.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param visitor a BetterVisitor which is visiting the method
* @param startPC the bytecode offset of the start instruction in the range
* @param endPC the bytecode offset of the end instruction in the range
* @return this object
*/
public BugInstance addSourceLineRange(BytecodeScanningDetector visitor, int startPC, int endPC) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstructionRange(visitor.getClassContext(), visitor, startPC, endPC);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation describing the
* source line numbers for a range of instructions in the method being
* visited by the given visitor.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param classContext the ClassContext
* @param visitor a BetterVisitor which is visiting the method
* @param startPC the bytecode offset of the start instruction in the range
* @param endPC the bytecode offset of the end instruction in the range
* @return this object
*/
public BugInstance addSourceLineRange(ClassContext classContext, PreorderVisitor visitor, int startPC, int endPC) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstructionRange(classContext, visitor, startPC, endPC);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for instruction currently being visited
* by given visitor.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param visitor a BytecodeScanningDetector visitor that is currently visiting the instruction
* @return this object
*/
public BugInstance addSourceLine(BytecodeScanningDetector visitor) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstruction(visitor);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a non-specific source line annotation.
* This will result in the entire source file being displayed.
*
* @param className the class name
* @param sourceFile the source file name
* @return this object
*/
public BugInstance addUnknownSourceLine(String className, String sourceFile) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.createUnknown(className, sourceFile);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Format a string describing this bug instance.
*
* @return the description
*/
public String getMessageWithoutPrefix() {
BugPattern bugPattern = I18N.instance().lookupBugPattern(type);
String pattern, shortPattern;
if (bugPattern == null)
shortPattern = pattern = "Error: missing bug pattern for key " + type;
else {
pattern = bugPattern.getLongDescription();
shortPattern = bugPattern.getShortDescription();
}
try {
FindBugsMessageFormat format = new FindBugsMessageFormat(pattern);
return format.format(annotationList.toArray(new BugAnnotation[annotationList.size()]), getPrimaryClass());
} catch (RuntimeException e) {
AnalysisContext.logError("Error generating bug msg ", e);
return shortPattern + " [Error generating customized description]";
}
}
/**
* Format a string describing this bug instance.
*
* @return the description
*/
public String getMessage() {
String pattern = I18N.instance().getMessage(type);
FindBugsMessageFormat format = new FindBugsMessageFormat(pattern);
try {
return format.format(annotationList.toArray(new BugAnnotation[annotationList.size()]), getPrimaryClass());
} catch (RuntimeException e) {
AnalysisContext.logError("Error generating bug msg ", e);
BugPattern bugPattern = I18N.instance().lookupBugPattern(type);
if (bugPattern == null)
return "Error: missing bug pattern for key " + type;
return bugPattern.getShortDescription() + " [Error generating customized description]";
}
}
/**
* Format a string describing this bug pattern, with the priority and type at the beginning.
* e.g. "(High Priority Correctness) Guaranteed null pointer dereference..."
*/
public String getMessageWithPriorityType() {
return "(" + this.getPriorityTypeString() + ") " + this.getMessage();
}
public String getMessageWithPriorityTypeAbbreviation() {
return this.getPriorityTypeAbbreviation() + " "+ this.getMessage();
}
/**
* Add a description to the most recently added bug annotation.
*
* @param description the description to add
* @return this object
*/
public BugInstance describe(String description) {
annotationList.get(annotationList.size() - 1).setDescription(description);
return this;
}
/**
* Convert to String.
* This method returns the "short" message describing the bug,
* as opposed to the longer format returned by getMessage().
* The short format is appropriate for the tree view in a GUI,
* where the annotations are listed separately as part of the overall
* bug instance.
*/
@Override
public String toString() {
return I18N.instance().getShortMessage(type);
}
public void writeXML(XMLOutput xmlOutput) throws IOException {
writeXML(xmlOutput, false);
}
public void writeXML(XMLOutput xmlOutput, boolean addMessages) throws IOException {
XMLAttributeList attributeList = new XMLAttributeList()
.addAttribute("type", type)
.addAttribute("priority", String.valueOf(priority));
BugPattern pattern = getBugPattern();
if (pattern != null) {
// The bug abbreviation and pattern category are
// emitted into the XML for informational purposes only.
// (The information is redundant, but might be useful
// for processing tools that want to make sense of
// bug instances without looking at the plugin descriptor.)
attributeList.addAttribute("abbrev", pattern.getAbbrev());
attributeList.addAttribute("category", pattern.getCategory());
}
if (addMessages) {
// Add a uid attribute, if we have a unique id.
if (getUniqueId() != null) {
attributeList.addAttribute("uid", getUniqueId());
}
attributeList.addAttribute("instanceHash", getInstanceHash());
attributeList.addAttribute("instanceOccurrenceNum", Integer.toString(getInstanceOccurrenceNum()));
attributeList.addAttribute("instanceOccurrenceMax", Integer.toString(getInstanceOccurrenceMax()));
}
if (firstVersion > 0) attributeList.addAttribute("first", Long.toString(firstVersion));
if (lastVersion >= 0) attributeList.addAttribute("last", Long.toString(lastVersion));
if (introducedByChangeOfExistingClass)
attributeList.addAttribute("introducedByChange", "true");
if (removedByChangeOfPersistingClass)
attributeList.addAttribute("removedByChange", "true");
xmlOutput.openTag(ELEMENT_NAME, attributeList);
if (userDesignation != null) {
userDesignation.writeXML(xmlOutput);
}
if (addMessages) {
BugPattern bugPattern = getBugPattern();
xmlOutput.openTag("ShortMessage");
xmlOutput.writeText(bugPattern != null ? bugPattern.getShortDescription() : this.toString());
xmlOutput.closeTag("ShortMessage");
xmlOutput.openTag("LongMessage");
xmlOutput.writeText(this.getMessageWithoutPrefix());
xmlOutput.closeTag("LongMessage");
}
boolean foundSourceAnnotation = false;
for (BugAnnotation annotation : annotationList) {
if (annotation instanceof SourceLineAnnotation)
foundSourceAnnotation = true;
annotation.writeXML(xmlOutput, addMessages);
}
if (!foundSourceAnnotation && addMessages) {
SourceLineAnnotation synth = getPrimarySourceLineAnnotation();
if (synth != null) {
synth.setSynthetic(true);
synth.writeXML(xmlOutput, addMessages);
}
}
if (propertyListHead != null) {
BugProperty prop = propertyListHead;
while (prop != null) {
prop.writeXML(xmlOutput);
prop = prop.getNext();
}
}
xmlOutput.closeTag(ELEMENT_NAME);
}
private static final String ELEMENT_NAME = "BugInstance";
private static final String USER_ANNOTATION_ELEMENT_NAME = "UserAnnotation";
public BugInstance addOptionalAnnotation(@CheckForNull BugAnnotation annotation) {
if (annotation == null) return this;
return add(annotation);
}
public BugInstance add(BugAnnotation annotation) {
if (annotation == null)
throw new IllegalStateException("Missing BugAnnotation!");
// Add to list
annotationList.add(annotation);
// This object is being modified, so the cached hashcode
// must be invalidated
cachedHashCode = INVALID_HASH_CODE;
return this;
}
private void addSourceLinesForMethod(MethodAnnotation methodAnnotation, SourceLineAnnotation sourceLineAnnotation) {
if (sourceLineAnnotation != null) {
// Note: we don't add the source line annotation directly to
// the bug instance. Instead, we stash it in the MethodAnnotation.
// It is much more useful there, and it would just be distracting
// if it were displayed in the UI, since it would compete for attention
// with the actual bug location source line annotation (which is much
// more important and interesting).
methodAnnotation.setSourceLines(sourceLineAnnotation);
}
}
@Override
public int hashCode() {
if (cachedHashCode == INVALID_HASH_CODE) {
int hashcode = type.hashCode() + priority;
Iterator<BugAnnotation> i = annotationIterator();
while (i.hasNext())
hashcode += i.next().hashCode();
if (hashcode == INVALID_HASH_CODE)
hashcode = INVALID_HASH_CODE+1;
cachedHashCode = hashcode;
}
return cachedHashCode;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof BugInstance))
return false;
BugInstance other = (BugInstance) o;
if (!type.equals(other.type) || priority != other.priority)
return false;
if (annotationList.size() != other.annotationList.size())
return false;
int numAnnotations = annotationList.size();
for (int i = 0; i < numAnnotations; ++i) {
BugAnnotation lhs = annotationList.get(i);
BugAnnotation rhs = other.annotationList.get(i);
if (!lhs.equals(rhs))
return false;
}
return true;
}
public int compareTo(BugInstance other) {
int cmp;
cmp = type.compareTo(other.type);
if (cmp != 0)
return cmp;
cmp = priority - other.priority;
if (cmp != 0)
return cmp;
// Compare BugAnnotations lexicographically
int pfxLen = Math.min(annotationList.size(), other.annotationList.size());
for (int i = 0; i < pfxLen; ++i) {
BugAnnotation lhs = annotationList.get(i);
BugAnnotation rhs = other.annotationList.get(i);
cmp = lhs.compareTo(rhs);
if (cmp != 0)
return cmp;
}
// All elements in prefix were the same,
// so use number of elements to decide
return annotationList.size() - other.annotationList.size();
}
/**
* @param firstVersion The firstVersion to set.
*/
public void setFirstVersion(long firstVersion) {
this.firstVersion = firstVersion;
if (lastVersion >= 0 && firstVersion > lastVersion)
throw new IllegalArgumentException(
firstVersion + ".." + lastVersion);
}
/**
* @return Returns the firstVersion.
*/
public long getFirstVersion() {
return firstVersion;
}
/**
* @param lastVersion The lastVersion to set.
*/
public void setLastVersion(long lastVersion) {
if (lastVersion >= 0 && firstVersion > lastVersion)
throw new IllegalArgumentException(
firstVersion + ".." + lastVersion);
this.lastVersion = lastVersion;
}
/**
* @return Returns the lastVersion.
*/
public long getLastVersion() {
return lastVersion;
}
/**
* @param introducedByChangeOfExistingClass The introducedByChangeOfExistingClass to set.
*/
public void setIntroducedByChangeOfExistingClass(boolean introducedByChangeOfExistingClass) {
this.introducedByChangeOfExistingClass = introducedByChangeOfExistingClass;
}
/**
* @return Returns the introducedByChangeOfExistingClass.
*/
public boolean isIntroducedByChangeOfExistingClass() {
return introducedByChangeOfExistingClass;
}
/**
* @param removedByChangeOfPersistingClass The removedByChangeOfPersistingClass to set.
*/
public void setRemovedByChangeOfPersistingClass(boolean removedByChangeOfPersistingClass) {
this.removedByChangeOfPersistingClass = removedByChangeOfPersistingClass;
}
/**
* @return Returns the removedByChangeOfPersistingClass.
*/
public boolean isRemovedByChangeOfPersistingClass() {
return removedByChangeOfPersistingClass;
}
/**
* @param instanceHash The instanceHash to set.
*/
public void setInstanceHash(String instanceHash) {
this.instanceHash = instanceHash;
}
/**
* @param oldInstanceHash The oldInstanceHash to set.
*/
public void setOldInstanceHash(String oldInstanceHash) {
this.oldInstanceHash = oldInstanceHash;
}
/**
* @return Returns the instanceHash.
*/
public String getInstanceHash() {
if (instanceHash != null) return instanceHash;
MessageDigest digest = null;
try { digest = MessageDigest.getInstance("MD5");
} catch (Exception e2) {
// OK, we won't digest
}
instanceHash = getInstanceKey();
if (digest != null) {
byte [] data = digest.digest(instanceHash.getBytes());
String tmp = new BigInteger(1,data).toString(16);
instanceHash = tmp;
}
return instanceHash;
}
public boolean isInstanceHashConsistent() {
return oldInstanceHash == null || instanceHash.equals(oldInstanceHash);
}
/**
* @param instanceOccurrenceNum The instanceOccurrenceNum to set.
*/
public void setInstanceOccurrenceNum(int instanceOccurrenceNum) {
this.instanceOccurrenceNum = instanceOccurrenceNum;
}
/**
* @return Returns the instanceOccurrenceNum.
*/
public int getInstanceOccurrenceNum() {
return instanceOccurrenceNum;
}
/**
* @param instanceOccurrenceMax The instanceOccurrenceMax to set.
*/
public void setInstanceOccurrenceMax(int instanceOccurrenceMax) {
this.instanceOccurrenceMax = instanceOccurrenceMax;
}
/**
* @return Returns the instanceOccurrenceMax.
*/
public int getInstanceOccurrenceMax() {
return instanceOccurrenceMax;
}
}
// vim:ts=4 |
package org.jpmml.xgboost;
import org.jpmml.converter.HasOptions;
public interface HasXGBoostOptions extends HasOptions {
String OPTION_BYTE_ORDER = "byte_order";
String OPTION_CHARSET = "charset";
String OPTION_COMPACT = "compact";
String OPTION_NTREE_LIMIT = "ntree_limit";
} |
package com.team687.frc2017.utilities;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.team687.frc2017.Constants;
/**
* Pose transformation unit testing
*
* @author tedlin
*
*/
@RunWith(Parameterized.class)
public class TransformTest {
private static final double kEpsilon = 1E-9;
@SuppressWarnings("rawtypes")
@Parameters
public static Collection testCases() {
// consists of {x, y, theta (in radians), left speed, and right speed
return Arrays.asList(new double[][] { { 10, 10, 0.687 * Math.PI, 120, 90 } });
}
private double m_x;
private double m_y;
private double m_theta;
private double m_leftSpeed;
private double m_rightSpeed;
private double m_diffVelocity;
private double m_sigmaVelocity;
private double m_angularVelocity;
private double m_radius;
private double m_dt = 0.02; // in seconds
public TransformTest(double[] rawVal) {
m_x = rawVal[0];
m_y = rawVal[1];
m_theta = rawVal[2];
m_leftSpeed = rawVal[3];
m_rightSpeed = rawVal[4];
m_diffVelocity = m_rightSpeed - m_leftSpeed;
m_sigmaVelocity = m_rightSpeed + m_leftSpeed;
m_angularVelocity = m_diffVelocity / Constants.kDrivetrainWidth;
if (m_diffVelocity == 0) {
m_radius = Double.POSITIVE_INFINITY;
} else {
m_radius = (Constants.kDrivetrainWidth * m_sigmaVelocity) / (2 * m_diffVelocity);
}
System.out.println("Curvature radius: " + m_radius);
System.out.println("Angular velocity: " + m_angularVelocity);
}
@Test
public void findNewPoseTest() {
double[][] origPos = { { 1, 0, 0, m_x }, { 0, 1, 0, m_y }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } };
double[][] currentPose = { { Math.cos(m_theta), -Math.sin(m_theta), 0, 0 },
{ Math.sin(m_theta), Math.cos(m_theta), 0, 0 }, { 0, 0, 1, m_theta }, { 0, 0, 0, 1 } };
// instantaneous center of curvature
double[][] ICC = { { 1, 0, 0, 0 }, { 0, 1, 0, m_radius }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } };
double[][] rotateICC = { { Math.cos(m_angularVelocity * m_dt), -Math.sin(m_angularVelocity * m_dt), 0, 0 },
{ Math.sin(m_angularVelocity * m_dt), Math.cos(m_angularVelocity * m_dt), 0, 0 },
{ 0, 0, 1, m_angularVelocity * m_dt }, { 0, 0, 0, 1 } };
double[][] translateOut = { { 1, 0, 0, 0 }, { 0, 1, 0, -m_radius }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } };
Matrix RT_P = new Matrix(origPos);
Matrix PT_P = new Matrix(currentPose);
Matrix PT_ICC = new Matrix(ICC);
Matrix ICCT_ICC = new Matrix(rotateICC);
Matrix ICCT_N = new Matrix(translateOut);
System.out.println("RT_P");
RT_P.show();
System.out.println("PT_P");
PT_P.show();
System.out.println("PT_ICC");
PT_ICC.show();
System.out.println("ICCT_ICC");
ICCT_ICC.show();
System.out.println("ICCT_N");
ICCT_N.show();
// find new pose
Matrix B = RT_P.multiplyBy(PT_P);
Matrix C = B.multiplyBy(PT_ICC);
Matrix D = C.multiplyBy(ICCT_ICC);
Matrix RT_N = D.multiplyBy(ICCT_N);
System.out.println("RT_N");
RT_N.show();
double newX = (m_radius * Math.cos(m_theta) * Math.sin(m_angularVelocity * m_dt))
+ (m_radius * Math.sin(m_theta) * Math.cos(m_angularVelocity * m_dt)) + m_x
- (m_radius * Math.sin(m_theta));
System.out.println("New X: " + newX);
double newY = (m_radius * Math.sin(m_theta) * Math.sin(m_angularVelocity * m_dt))
- (m_radius * Math.cos(m_theta) * Math.cos(m_angularVelocity * m_dt)) + m_y
+ (m_radius * Math.cos(m_theta));
System.out.println("New Y: " + newY);
double newTheta = m_theta + (m_angularVelocity * m_dt);
System.out.println("New Theta: " + newTheta);
assertEquals(RT_N.getData()[0][3], newX, kEpsilon);
assertEquals(RT_N.getData()[1][3], newY, kEpsilon);
assertEquals(RT_N.getData()[2][3], newTheta, kEpsilon);
}
} |
package dr.inference.mcmc;
import dr.inference.loggers.LogColumn;
import dr.inference.loggers.Loggable;
import dr.inference.loggers.Logger;
import dr.inference.markovchain.MarkovChain;
import dr.inference.markovchain.MarkovChainDelegate;
import dr.inference.markovchain.MarkovChainListener;
import dr.inference.model.Likelihood;
import dr.inference.model.Model;
import dr.inference.operators.*;
import dr.inference.prior.Prior;
import dr.util.Identifiable;
import dr.util.NumberFormatter;
import dr.xml.Spawnable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
/**
* An MCMC analysis that estimates parameters of a probabilistic model.
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @version $Id: MCMC.java,v 1.41 2005/07/11 14:06:25 rambaut Exp $
*/
public class MCMC implements Identifiable, Spawnable, Loggable {
public final static String LOAD_DUMP_FILE = "load.dump.file";
public final static String SAVE_DUMP_FILE = "save.dump.file";
public final static String DUMP_STATE = "dump.state";
public final static String DUMP_EVERY = "dump.every";
// Experimental
public final static boolean TEST_CLONING = false;
public MCMC(String id) {
this.id = id;
}
/**
* Must be called before calling chain.
*
* @param options the options for this MCMC analysis
* @param schedule operator schedule to be used in chain.
* @param likelihood the likelihood for this MCMC
* @param loggers an array of loggers to record output of this MCMC run
*/
public void init(
MCMCOptions options,
Likelihood likelihood,
OperatorSchedule schedule,
Logger[] loggers) {
init(options, likelihood, Prior.UNIFORM_PRIOR, schedule, loggers, new MarkovChainDelegate[0]);
}
/**
* Must be called before calling chain.
*
* @param options the options for this MCMC analysis
* @param schedule operator schedule to be used in chain.
* @param likelihood the likelihood for this MCMC
* @param loggers an array of loggers to record output of this MCMC run
* @param delegates an array of delegates to handle tasks related to the MCMC
*/
public void init(
MCMCOptions options,
Likelihood likelihood,
OperatorSchedule schedule,
Logger[] loggers,
MarkovChainDelegate[] delegates) {
init(options, likelihood, Prior.UNIFORM_PRIOR, schedule, loggers, delegates);
}
/**
* Must be called before calling chain.
*
* @param options the options for this MCMC analysis
* @param prior the prior disitrbution on the model parameters.
* @param schedule operator schedule to be used in chain.
* @param likelihood the likelihood for this MCMC
* @param loggers an array of loggers to record output of this MCMC run
*/
public void init(
MCMCOptions options,
Likelihood likelihood,
Prior prior,
OperatorSchedule schedule,
Logger[] loggers) {
init(options, likelihood, prior, schedule, loggers, new MarkovChainDelegate[0]);
}
/**
* Must be called before calling chain.
*
* @param options the options for this MCMC analysis
* @param prior the prior disitrbution on the model parameters.
* @param schedule operator schedule to be used in chain.
* @param likelihood the likelihood for this MCMC
* @param loggers an array of loggers to record output of this MCMC run
* @param delegates an array of delegates to handle tasks related to the MCMC
*/
public void init(
MCMCOptions options,
Likelihood likelihood,
Prior prior,
OperatorSchedule schedule,
Logger[] loggers,
MarkovChainDelegate[] delegates) {
MCMCCriterion criterion = new MCMCCriterion();
criterion.setTemperature(options.getTemperature());
mc = new MarkovChain(prior, likelihood, schedule, criterion,
options.getFullEvaluationCount(), options.minOperatorCountForFullEvaluation(),
options.getEvaluationTestThreshold(),
options.useCoercion());
this.options = options;
this.loggers = loggers;
this.schedule = schedule;
//initialize transients
currentState = 0;
for(MarkovChainDelegate delegate : delegates) {
delegate.setup(options, schedule, mc);
}
this.delegates = delegates;
dumpStateFile = System.getProperty(LOAD_DUMP_FILE);
String fileName = System.getProperty(SAVE_DUMP_FILE, null);
if (System.getProperty(DUMP_STATE) != null) {
long debugWriteState = Long.parseLong(System.getProperty(DUMP_STATE));
mc.addMarkovChainListener(new DebugChainListener(this, debugWriteState, false, fileName));
}
if (System.getProperty(DUMP_EVERY) != null) {
long debugWriteEvery = Long.parseLong(System.getProperty(DUMP_EVERY));
mc.addMarkovChainListener(new DebugChainListener(this, debugWriteEvery, true, fileName));
}
}
/**
* Must be called before calling chain.
*
* @param chainlength chain length
* @param likelihood the likelihood for this MCMC
* @param operators an array of MCMC operators
* @param loggers an array of loggers to record output of this MCMC run
*/
public void init(long chainlength,
Likelihood likelihood,
MCMCOperator[] operators,
Logger[] loggers) {
MCMCOptions options = new MCMCOptions(chainlength);
MCMCCriterion criterion = new MCMCCriterion();
criterion.setTemperature(1);
OperatorSchedule schedule = new SimpleOperatorSchedule();
for (MCMCOperator operator : operators) schedule.addOperator(operator);
init(options, likelihood, Prior.UNIFORM_PRIOR, schedule, loggers);
}
public MarkovChain getMarkovChain() {
return mc;
}
public Logger[] getLoggers() {
return loggers;
}
public MCMCOptions getOptions() {
return options;
}
public OperatorSchedule getOperatorSchedule() {
return schedule;
}
public void run() {
chain();
}
/**
* This method actually initiates the MCMC analysis.
*/
public void chain() {
stopping = false;
currentState = 0;
timer.start();
if (loggers != null) {
for (Logger logger : loggers) {
logger.startLogging();
}
}
if (!stopping) {
if (dumpStateFile != null) {
double[] savedLnL = new double[1];
long loadedState = DebugUtils.readStateFromFile(new File(dumpStateFile), getOperatorSchedule(), savedLnL);
mc.setCurrentLength(loadedState);
double lnL = mc.evaluate();
DebugUtils.writeStateToFile(new File("tmp.dump"), loadedState, lnL, getOperatorSchedule());
//first perform a simple check for equality of two doubles
//when this test fails, go over the digits
if (lnL != savedLnL[0]) {
//15 is the floor value for the number of decimal digits when representing a double
//checking for 15 identical digits below
String originalString = Double.toString(savedLnL[0]);
String restoredString = Double.toString(lnL);
//System.out.println(lnL + " " + originalString);
//System.out.println(savedLnL[0] + " " + restoredString);
//assume values will be nearly identical
int digits = 0;
for (int i = 0; i < Math.max(originalString.length(), restoredString.length()); i++) {
if (originalString.charAt(i) == restoredString.charAt(i)) {
if (!(originalString.charAt(i) == '-' || originalString.charAt(i) == '.')) {
digits++;
}
}
}
//System.out.println("digits = " + digits);
if (digits < 15) {
throw new RuntimeException("Dumped lnL does not match loaded state: stored lnL: " + savedLnL[0] +
", recomputed lnL: " + lnL + " (difference " + (savedLnL[0] - lnL) + ")");
}
}
//convert to BigDecimal to fix to 16 digits; solves issue with log likelihood mismatch at the last digit
//BigDecimal original = new BigDecimal(savedLnL[0], MathContext.DECIMAL64);
//BigDecimal restored = new BigDecimal(lnL, MathContext.DECIMAL64);
/*if (Math.abs(original.doubleValue() - restored.doubleValue()) > 1E-9) {
throw new RuntimeException("Dumped lnL does not match loaded state: stored lnL: " + original.doubleValue() +
", recomputed lnL: " + restored.doubleValue() + " (difference " + (original.doubleValue() - restored.doubleValue()) + ")");
}*/
// for (Likelihood likelihood : Likelihood.CONNECTED_LIKELIHOOD_SET) {
// System.err.println(likelihood.getId() + ": " + likelihood.getLogLikelihood());
}
mc.addMarkovChainListener(chainListener);
for(MarkovChainDelegate delegate : delegates) {
mc.addMarkovChainDelegate(delegate);
}
long chainLength = getChainLength();
final long coercionDelay = getCoercionDelay();
if (coercionDelay > 0) {
// Run the chain for coercionDelay steps with coercion disabled
mc.runChain(coercionDelay, true);
chainLength -= coercionDelay;
// reset operator acceptance levels
//GB: we are now restoring these; commenting out for now
/*for (int i = 0; i < schedule.getOperatorCount(); i++) {
schedule.getOperator(i).reset();
}*/
}
mc.runChain(chainLength, false);
mc.terminateChain();
mc.removeMarkovChainListener(chainListener);
for(MarkovChainDelegate delegate : delegates) {
mc.removeMarkovChainDelegate(delegate);
}
}
timer.stop();
}
@Override
public LogColumn[] getColumns() {
return new LogColumn[] { new LogColumn() {
@Override
public void setLabel(String label) {
}
@Override
public String getLabel() {
return "time";
}
@Override
public void setMinimumWidth(int minimumWidth) {
}
@Override
public int getMinimumWidth() {
return 0;
}
@Override
public String getFormatted() {
return Double.toString(getTimer().toSeconds());
}
} };
}
private final MarkovChainListener chainListener = new MarkovChainListener() {
// for receiving messages from subordinate MarkovChain
/**
* Called to update the current model keepEvery states.
*/
public void currentState(long state, Model currentModel) {
currentState = state;
if (loggers != null) {
for (Logger logger : loggers) {
logger.log(state);
}
}
}
/**
* Called when a new new best posterior state is found.
*/
public void bestState(long state, Model bestModel) {
currentState = state;
}
/**
* cleans up when the chain finishes (possibly early).
*/
public void finished(long chainLength) {
currentState = chainLength;
if (loggers != null) {
for (Logger logger : loggers) {
logger.log(currentState);
logger.stopLogging();
}
}
// OperatorAnalysisPrinter class can do the job now
if (showOperatorAnalysis) {
showOperatorAnalysis(System.out);
}
if (operatorAnalysisFile != null) {
try {
PrintStream out = new PrintStream(new FileOutputStream(operatorAnalysisFile));
showOperatorAnalysis(out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// How should premature finish be flagged?
}
};
/**
* Writes ano operator analysis to the provided print stream
*
* @param out the print stream to write operator analysis to
*/
private void showOperatorAnalysis(PrintStream out) {
out.println();
out.println("Operator analysis");
out.println(formatter.formatToFieldWidth("Operator", 50) +
formatter.formatToFieldWidth("Tuning", 9) +
formatter.formatToFieldWidth("Count", 11) +
formatter.formatToFieldWidth("Time", 9) +
formatter.formatToFieldWidth("Time/Op", 9) +
formatter.formatToFieldWidth("Pr(accept)", 11) +
(options.useCoercion() ? "" : " Performance suggestion"));
for (int i = 0; i < schedule.getOperatorCount(); i++) {
final MCMCOperator op = schedule.getOperator(i);
if (op instanceof JointOperator) {
JointOperator jointOp = (JointOperator) op;
for (int k = 0; k < jointOp.getNumberOfSubOperators(); k++) {
out.println(formattedOperatorName(jointOp.getSubOperatorName(k))
+ formattedParameterString(jointOp.getSubOperator(k))
+ formattedCountString(op)
+ formattedTimeString(op)
+ formattedTimePerOpString(op)
+ formattedProbString(jointOp)
+ (options.useCoercion() ? "" : formattedDiagnostics(jointOp, MCMCOperator.Utils.getAcceptanceProbability(jointOp)))
);
}
} else {
out.println(formattedOperatorName(op.getOperatorName())
+ formattedParameterString(op)
+ formattedCountString(op)
+ formattedTimeString(op)
+ formattedTimePerOpString(op)
+ formattedProbString(op)
+ (options.useCoercion() ? "" : formattedDiagnostics(op, MCMCOperator.Utils.getAcceptanceProbability(op)))
);
}
}
out.println();
}
private String formattedOperatorName(String operatorName) {
return formatter.formatToFieldWidth(operatorName, 50);
}
private String formattedParameterString(MCMCOperator op) {
String pString = " ";
if (op instanceof CoercableMCMCOperator && ((CoercableMCMCOperator) op).getMode() != CoercionMode.COERCION_OFF) {
pString = formatter.formatToFieldWidth(formatter.formatDecimal(((CoercableMCMCOperator) op).getRawParameter(), 3), 8);
}
return pString;
}
private String formattedCountString(MCMCOperator op) {
final int count = op.getCount();
return formatter.formatToFieldWidth(Integer.toString(count), 10) + " ";
}
private String formattedTimeString(MCMCOperator op) {
final long time = op.getTotalEvaluationTime();
return formatter.formatToFieldWidth(Long.toString(time), 8) + " ";
}
private String formattedTimePerOpString(MCMCOperator op) {
final double time = op.getMeanEvaluationTime();
return formatter.formatToFieldWidth(formatter.formatDecimal(time, 2), 8) + " ";
}
private String formattedProbString(MCMCOperator op) {
final double acceptanceProb = MCMCOperator.Utils.getAcceptanceProbability(op);
return formatter.formatToFieldWidth(formatter.formatDecimal(acceptanceProb, 4), 11) + " ";
}
private String formattedDiagnostics(MCMCOperator op, double acceptanceProb) {
String message = "good";
if (acceptanceProb < op.getMinimumGoodAcceptanceLevel()) {
if (acceptanceProb < (op.getMinimumAcceptanceLevel() / 10.0)) {
message = "very low";
} else if (acceptanceProb < op.getMinimumAcceptanceLevel()) {
message = "low";
} else message = "slightly low";
} else if (acceptanceProb > op.getMaximumGoodAcceptanceLevel()) {
double reallyHigh = 1.0 - ((1.0 - op.getMaximumAcceptanceLevel()) / 10.0);
if (acceptanceProb > reallyHigh) {
message = "very high";
} else if (acceptanceProb > op.getMaximumAcceptanceLevel()) {
message = "high";
} else message = "slightly high";
}
String performacsMsg;
if (op instanceof GibbsOperator) {
performacsMsg = "none (Gibbs operator)";
} else {
final String suggestion = op.getPerformanceSuggestion();
performacsMsg = message + "\t" + suggestion;
}
return performacsMsg;
}
/**
* @return the prior of this MCMC analysis.
*/
public Prior getPrior() {
return mc.getPrior();
}
/**
* @return the likelihood function.
*/
public Likelihood getLikelihood() {
return mc.getLikelihood();
}
/**
* @return the timer.
*/
public dr.util.Timer getTimer() {
return timer;
}
/**
* @return the length of this analysis.
*/
public final long getChainLength() {
return options.getChainLength();
}
/**
* @return the current state of the MCMC analysis.
*/
public final long getCurrentState() {
return currentState;
}
/**
* @return the progress (0 to 1) of the MCMC analysis.
*/
public final double getProgress() {
return (double) currentState / (double) options.getChainLength();
}
/**
* @return true if this MCMC is currently adapting the operators.
*/
public final boolean isAdapting() {
return isAdapting;
}
/**
* Requests that the MCMC chain stop prematurely.
*/
public void pleaseStop() {
stopping = true;
mc.pleaseStop();
}
/**
* @return true if Markov chain is stopped
*/
public boolean isStopped() {
return mc.isStopped();
}
public boolean getSpawnable() {
return spawnable;
}
private boolean spawnable = true;
public void setSpawnable(boolean spawnable) {
this.spawnable = spawnable;
}
protected long getCoercionDelay() {
long delay = options.getCoercionDelay();
if (delay < 0) {
delay = (long)(options.getChainLength() / 100);
}
if (options.useCoercion()) return delay;
for (int i = 0; i < schedule.getOperatorCount(); i++) {
MCMCOperator op = schedule.getOperator(i);
if (op instanceof CoercableMCMCOperator) {
if (((CoercableMCMCOperator) op).getMode() == CoercionMode.COERCION_ON) return delay;
}
}
return -1;
}
public void setShowOperatorAnalysis(boolean soa) {
showOperatorAnalysis = soa;
}
public void setOperatorAnalysisFile(File operatorAnalysisFile) {
this.operatorAnalysisFile = operatorAnalysisFile;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
// PRIVATE TRANSIENTS
private String dumpStateFile = null;
//private FileLogger operatorLogger = null;
protected final boolean isAdapting = true;
protected boolean stopping = false;
protected boolean showOperatorAnalysis = true;
protected File operatorAnalysisFile = null;
protected final dr.util.Timer timer = new dr.util.Timer();
protected long currentState = 0;
//private int stepsPerReport = 1000;
protected final NumberFormatter formatter = new NumberFormatter(8);
/**
* this markov chain does most of the work.
*/
protected MarkovChain mc;
/**
* the options of this MCMC analysis
*/
protected MCMCOptions options;
protected Logger[] loggers;
protected OperatorSchedule schedule;
private MarkovChainDelegate[] delegates;
private String id = null;
} |
package jenkins.slaves;
import hudson.AbortException;
import hudson.Extension;
import hudson.model.Computer;
import hudson.remoting.Channel;
import hudson.remoting.ChannelBuilder;
import hudson.slaves.SlaveComputer;
import jenkins.AgentProtocol;
import jenkins.model.Jenkins;
import jenkins.security.ChannelConfigurator;
import org.jenkinsci.remoting.engine.JnlpServer3Handshake;
import org.jenkinsci.remoting.nio.NioChannelHub;
import javax.inject.Inject;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Master-side implementation for JNLP3-connect protocol.
*
* <p>@see {@link org.jenkinsci.remoting.engine.JnlpProtocol3} for more details.
*
* @author Akshay Dayal
* @since 1.XXX
*/
@Extension
public class JnlpSlaveAgentProtocol3 extends AgentProtocol {
@Inject
NioChannelSelector hub;
@Override
public String getName() {
return "JNLP3-connect";
}
@Override
public void handle(Socket socket) throws IOException, InterruptedException {
new Handler(hub.getHub(), socket).run();
}
static class Handler extends JnlpServer3Handshake {
private SlaveComputer computer;
private PrintWriter logw;
private OutputStream log;
public Handler(NioChannelHub hub, Socket socket) throws IOException {
super(hub, Computer.threadPoolForRemoting, socket);
}
protected void run() throws IOException, InterruptedException {
try {
Channel channel = connect();
computer.setChannel(channel, log,
new Channel.Listener() {
@Override
public void onClosed(Channel channel, IOException cause) {
if (cause != null)
LOGGER.log(Level.WARNING,
Thread.currentThread().getName() + " for + " +
getNodeName() + " terminated", cause);
try {
socket.close();
} catch (IOException e) {
// Do nothing.
}
}
});
} catch (AbortException e) {
logw.println(e.getMessage());
logw.println("Failed to establish the connection with the agent");
throw e;
} catch (IOException e) {
logw.println("Failed to establish the connection with the agent " + getNodeName());
e.printStackTrace(logw);
throw e;
}
}
@Override
public ChannelBuilder createChannelBuilder(String nodeName) {
log = computer.openLogFile();
logw = new PrintWriter(log,true);
logw.println("JNLP agent connected from " + socket.getInetAddress());
ChannelBuilder cb = super.createChannelBuilder(nodeName).withHeaderStream(log);
for (ChannelConfigurator cc : ChannelConfigurator.all()) {
cc.onChannelBuilding(cb, computer);
}
return cb;
}
@Override
protected String getNodeSecret(String nodeName) throws Failure {
computer = (SlaveComputer) Jenkins.getInstance().getComputer(nodeName);
if (computer == null) {
throw new Failure("Agent trying to register for invalid node: " + nodeName);
}
return computer.getJnlpMac();
}
}
private static final Logger LOGGER = Logger.getLogger(JnlpSlaveAgentProtocol3.class.getName());
} |
package org.innovateuk.ifs.assessment.controller;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.application.form.Form;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.resource.QuestionResource;
import org.innovateuk.ifs.application.resource.SectionResource;
import org.innovateuk.ifs.application.resource.SectionType;
import org.innovateuk.ifs.assessment.model.AssessmentFeedbackApplicationDetailsModelPopulator;
import org.innovateuk.ifs.assessment.model.AssessmentFeedbackModelPopulator;
import org.innovateuk.ifs.assessment.model.AssessmentFeedbackNavigationModelPopulator;
import org.innovateuk.ifs.assessment.resource.AssessmentResource;
import org.innovateuk.ifs.assessment.resource.AssessorFormInputResponseResource;
import org.innovateuk.ifs.assessment.service.AssessmentService;
import org.innovateuk.ifs.assessment.service.AssessorFormInputResponseService;
import org.innovateuk.ifs.assessment.viewmodel.AssessmentFeedbackApplicationDetailsViewModel;
import org.innovateuk.ifs.assessment.viewmodel.AssessmentFeedbackViewModel;
import org.innovateuk.ifs.assessment.viewmodel.AssessmentNavigationViewModel;
import org.innovateuk.ifs.category.resource.ResearchCategoryResource;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.file.controller.viewmodel.FileDetailsViewModel;
import org.innovateuk.ifs.form.resource.FormInputResource;
import org.innovateuk.ifs.form.resource.FormInputResponseResource;
import org.innovateuk.ifs.form.resource.FormInputType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.validation.BindingResult;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.lang.String.format;
import static java.util.Arrays.stream;
import static java.util.Collections.singletonList;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.is;
import static org.innovateuk.ifs.application.builder.ApplicationResourceBuilder.newApplicationResource;
import static org.innovateuk.ifs.application.builder.QuestionResourceBuilder.newQuestionResource;
import static org.innovateuk.ifs.application.builder.SectionResourceBuilder.newSectionResource;
import static org.innovateuk.ifs.assessment.builder.AssessmentResourceBuilder.newAssessmentResource;
import static org.innovateuk.ifs.assessment.builder.AssessorFormInputResponseResourceBuilder.newAssessorFormInputResponseResource;
import static org.innovateuk.ifs.category.builder.ResearchCategoryResourceBuilder.newResearchCategoryResource;
import static org.innovateuk.ifs.commons.error.Error.fieldError;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource;
import static org.innovateuk.ifs.form.builder.FormInputResourceBuilder.newFormInputResource;
import static org.innovateuk.ifs.form.builder.FormInputResponseResourceBuilder.newFormInputResponseResource;
import static org.innovateuk.ifs.form.resource.FormInputType.*;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleToMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(MockitoJUnitRunner.class)
@TestPropertySource(locations = "classpath:application.properties")
public class AssessmentFeedbackControllerTest extends BaseControllerMockMVCTest<AssessmentFeedbackController> {
@Mock
private AssessmentService assessmentService;
@Mock
private AssessorFormInputResponseService assessorFormInputResponseService;
@Spy
@InjectMocks
private AssessmentFeedbackModelPopulator assessmentFeedbackModelPopulator;
@Spy
@InjectMocks
private AssessmentFeedbackNavigationModelPopulator assessmentFeedbackNavigationModelPopulator;
@Spy
@InjectMocks
private AssessmentFeedbackApplicationDetailsModelPopulator assessmentFeedbackApplicationDetailsModelPopulator;
@Override
protected AssessmentFeedbackController supplyControllerUnderTest() {
return new AssessmentFeedbackController();
}
@Test
public void getQuestion() throws Exception {
Long applicationId = 1L;
CompetitionResource competitionResource = setupCompetitionResource();
AssessmentResource assessmentResource = setupAssessment(competitionResource.getId(), applicationId);
SectionResource sectionResource = setupSection(SectionType.GENERAL);
QuestionResource questionResource = setupQuestion(assessmentResource.getId());
QuestionResource previousQuestionResource = newQuestionResource()
.withShortName("Previous question")
.withSection(sectionResource.getId())
.build();
QuestionResource nextQuestionResource = newQuestionResource()
.withShortName("Next question")
.withSection(sectionResource.getId())
.build();
setupQuestionNavigation(questionResource.getId(), of(previousQuestionResource), of(nextQuestionResource));
List<FormInputResource> applicationFormInputs = setupApplicationFormInputs(questionResource.getId(), TEXTAREA);
setupApplicantResponses(applicationId, applicationFormInputs);
List<FormInputResource> assessmentFormInputs = setupAssessmentFormInputs(questionResource.getId(), TEXTAREA, ASSESSOR_SCORE);
List<AssessorFormInputResponseResource> assessorResponses = setupAssessorResponses(assessmentResource.getId(),
questionResource.getId(), assessmentFormInputs);
Form expectedForm = new Form();
expectedForm.setFormInput(simpleToMap(assessorResponses, assessorFormInputResponseResource ->
String.valueOf(assessorFormInputResponseResource.getFormInput()), AssessorFormInputResponseResource::getValue));
AssessmentNavigationViewModel expectedNavigation = new AssessmentNavigationViewModel(assessmentResource.getId(),
of(previousQuestionResource), of(nextQuestionResource));
AssessmentFeedbackViewModel expectedViewModel = new AssessmentFeedbackViewModel(
assessmentResource.getId(),
3,
50,
applicationId,
"Application name",
questionResource.getId(),
"1",
"Market opportunity",
"1. What is the business opportunity that this project addresses?",
50,
"Applicant response",
assessmentFormInputs,
true,
false,
false,
null,
null);
mockMvc.perform(get("/{assessmentId}/question/{questionId}", assessmentResource.getId(), questionResource.getId()))
.andExpect(status().isOk())
.andExpect(model().attribute("form", expectedForm))
.andExpect(model().attribute("model", expectedViewModel))
.andExpect(model().attribute("navigation", expectedNavigation))
.andExpect(view().name("assessment/application-question"));
InOrder inOrder = inOrder(questionService, formInputService, assessorFormInputResponseService, assessmentService,
competitionService, formInputResponseService, categoryServiceMock);
inOrder.verify(questionService).getByIdAndAssessmentId(questionResource.getId(), assessmentResource.getId());
inOrder.verify(formInputService).findApplicationInputsByQuestion(questionResource.getId());
inOrder.verify(assessorFormInputResponseService).getAllAssessorFormInputResponsesByAssessmentAndQuestion(
assessmentResource.getId(), questionResource.getId());
inOrder.verify(assessmentService).getById(assessmentResource.getId());
inOrder.verify(competitionService).getById(competitionResource.getId());
inOrder.verify(formInputService).findApplicationInputsByQuestion(questionResource.getId());
applicationFormInputs.forEach(formInput -> inOrder.verify(formInputResponseService).getByFormInputIdAndApplication(formInput.getId(), applicationId));
inOrder.verify(formInputService).findAssessmentInputsByQuestion(questionResource.getId());
inOrder.verify(questionService).getPreviousQuestion(questionResource.getId());
inOrder.verify(questionService).getNextQuestion(questionResource.getId());
inOrder.verifyNoMoreInteractions();
}
@Test
public void getQuestion_withAppendix() throws Exception {
Long applicationId = 1L;
CompetitionResource competitionResource = setupCompetitionResource();
AssessmentResource assessmentResource = setupAssessment(competitionResource.getId(), applicationId);
SectionResource sectionResource = setupSection(SectionType.GENERAL);
QuestionResource questionResource = setupQuestion(assessmentResource.getId());
QuestionResource previousQuestionResource = newQuestionResource()
.withShortName("Previous question")
.withSection(sectionResource.getId())
.build();
QuestionResource nextQuestionResource = newQuestionResource()
.withShortName("Next question")
.withSection(sectionResource.getId())
.build();
setupQuestionNavigation(questionResource.getId(), of(previousQuestionResource), of(nextQuestionResource));
List<FormInputResource> applicationFormInputs = setupApplicationFormInputs(questionResource.getId(), TEXTAREA, FILEUPLOAD);
setupApplicantResponses(applicationId, applicationFormInputs);
List<FormInputResource> assessmentFormInputs = setupAssessmentFormInputs(questionResource.getId(), TEXTAREA, ASSESSOR_SCORE);
List<AssessorFormInputResponseResource> assessorResponses = setupAssessorResponses(assessmentResource.getId(),
questionResource.getId(), assessmentFormInputs);
Form expectedForm = new Form();
expectedForm.setFormInput(simpleToMap(assessorResponses, assessorFormInputResponseResource ->
String.valueOf(assessorFormInputResponseResource.getFormInput()), AssessorFormInputResponseResource::getValue));
AssessmentNavigationViewModel expectedNavigation = new AssessmentNavigationViewModel(assessmentResource.getId(),
of(previousQuestionResource), of(nextQuestionResource));
FileDetailsViewModel expectedFileDetailsViewModel = new FileDetailsViewModel(applicationFormInputs.get(1).getId(),
"File 1",
1024L);
AssessmentFeedbackViewModel expectedViewModel = new AssessmentFeedbackViewModel(assessmentResource.getId(),
3,
50,
applicationId,
"Application name",
questionResource.getId(),
"1",
"Market opportunity",
"1. What is the business opportunity that this project addresses?",
50,
"Applicant response",
assessmentFormInputs,
true,
false,
true,
expectedFileDetailsViewModel,
null);
mockMvc.perform(get("/{assessmentId}/question/{questionId}", assessmentResource.getId(), questionResource.getId()))
.andExpect(status().isOk())
.andExpect(model().attribute("form", expectedForm))
.andExpect(model().attribute("model", expectedViewModel))
.andExpect(model().attribute("navigation", expectedNavigation))
.andExpect(view().name("assessment/application-question"));
InOrder inOrder = inOrder(questionService, formInputService, assessorFormInputResponseService, assessmentService,
competitionService, formInputResponseService, categoryServiceMock);
inOrder.verify(questionService).getByIdAndAssessmentId(questionResource.getId(), assessmentResource.getId());
inOrder.verify(formInputService).findApplicationInputsByQuestion(questionResource.getId());
inOrder.verify(assessorFormInputResponseService).getAllAssessorFormInputResponsesByAssessmentAndQuestion(
assessmentResource.getId(), questionResource.getId());
inOrder.verify(assessmentService).getById(assessmentResource.getId());
inOrder.verify(competitionService).getById(competitionResource.getId());
inOrder.verify(formInputService).findApplicationInputsByQuestion(questionResource.getId());
applicationFormInputs.forEach(formInput -> inOrder.verify(formInputResponseService).getByFormInputIdAndApplication(formInput.getId(), applicationId));
inOrder.verify(formInputService).findAssessmentInputsByQuestion(questionResource.getId());
inOrder.verify(questionService).getPreviousQuestion(questionResource.getId());
inOrder.verify(questionService).getNextQuestion(questionResource.getId());
inOrder.verifyNoMoreInteractions();
}
@Test
public void nextQuestionIsNotNavigable() throws Exception {
Long applicationId = 1L;
CompetitionResource competitionResource = setupCompetitionResource();
AssessmentResource assessmentResource = setupAssessment(competitionResource.getId(), applicationId);
SectionResource sectionResource = setupSection(SectionType.GENERAL);
SectionResource financeSectionResource = setupSection(SectionType.FINANCE);
QuestionResource questionResource = setupQuestion(assessmentResource.getId());
QuestionResource previousQuestionResource = newQuestionResource()
.withShortName("Previous question")
.withSection(sectionResource.getId())
.build();
QuestionResource nextQuestionResource = newQuestionResource()
.withShortName("Next question")
.withSection(financeSectionResource.getId())
.build();
setupQuestionNavigation(questionResource.getId(), of(previousQuestionResource), of(nextQuestionResource));
List<FormInputResource> applicationFormInputs = setupApplicationFormInputs(questionResource.getId(), TEXTAREA);
setupApplicantResponses(applicationId, applicationFormInputs);
List<FormInputResource> assessmentFormInputs = setupAssessmentFormInputs(questionResource.getId(), TEXTAREA, ASSESSOR_SCORE);
List<AssessorFormInputResponseResource> assessorResponses = setupAssessorResponses(assessmentResource.getId(),
questionResource.getId(), assessmentFormInputs);
Form expectedForm = new Form();
expectedForm.setFormInput(simpleToMap(assessorResponses, assessorFormInputResponseResource ->
String.valueOf(assessorFormInputResponseResource.getFormInput()), AssessorFormInputResponseResource::getValue));
AssessmentNavigationViewModel expectedNavigation = new AssessmentNavigationViewModel(assessmentResource.getId(), of(previousQuestionResource), empty());
mockMvc.perform(get("/{assessmentId}/question/{questionId}", assessmentResource.getId(), questionResource.getId()))
.andExpect(status().isOk())
.andExpect(model().attribute("form", expectedForm))
.andExpect(model().attributeExists("model"))
.andExpect(model().attribute("navigation", expectedNavigation))
.andExpect(view().name("assessment/application-question"))
.andReturn();
}
@Test
public void getQuestion_applicationDetailsQuestion() throws Exception {
LocalDate now = LocalDate.now();
ApplicationResource applicationResource = newApplicationResource()
.withName("Application name")
.withStartDate(now)
.withDurationInMonths(20L)
.build();
CompetitionResource competitionResource = setupCompetitionResource();
AssessmentResource assessmentResource = setupAssessment(competitionResource.getId(), applicationResource.getId());
SectionResource sectionResource = setupSection(SectionType.GENERAL);
QuestionResource questionResource = newQuestionResource()
.withShortName("Application details")
.build();
QuestionResource nextQuestionResource = newQuestionResource()
.withShortName("Next question")
.withSection(sectionResource.getId())
.build();
when(questionService.getByIdAndAssessmentId(questionResource.getId(), assessmentResource.getId()))
.thenReturn(questionResource);
when(applicationService.getById(applicationResource.getId())).thenReturn(applicationResource);
setupQuestionNavigation(questionResource.getId(), empty(), of(nextQuestionResource));
AssessmentNavigationViewModel expectedNavigation = new AssessmentNavigationViewModel(assessmentResource.getId(),
empty(), of(nextQuestionResource));
List<FormInputResource> applicationFormInputs = setupApplicationFormInputs(questionResource.getId(), APPLICATION_DETAILS);
setupApplicantResponses(applicationResource.getId(), applicationFormInputs);
setupInvites();
Form expectedForm = new Form();
AssessmentFeedbackApplicationDetailsViewModel expectedViewModel = new AssessmentFeedbackApplicationDetailsViewModel(
applicationResource.getId(),
"Application name",
now,
20L,
3,
50,
"Application details"
);
mockMvc.perform(get("/{assessmentId}/question/{questionId}", assessmentResource.getId(), questionResource.getId()))
.andExpect(status().isOk())
.andExpect(model().attribute("form", expectedForm))
.andExpect(model().attribute("model", expectedViewModel))
.andExpect(model().attribute("navigation", expectedNavigation))
.andExpect(view().name("assessment/application-details"));
InOrder inOrder = inOrder(questionService, formInputService, assessmentService, applicationService, sectionService);
inOrder.verify(questionService).getByIdAndAssessmentId(questionResource.getId(), assessmentResource.getId());
inOrder.verify(formInputService).findApplicationInputsByQuestion(questionResource.getId());
inOrder.verify(assessmentService).getById(assessmentResource.getId());
inOrder.verify(applicationService).getById(applicationResource.getId());
inOrder.verify(questionService).getPreviousQuestion(questionResource.getId());
inOrder.verify(questionService).getNextQuestion(questionResource.getId());
inOrder.verify(sectionService).getById(nextQuestionResource.getSection());
inOrder.verifyNoMoreInteractions();
verifyZeroInteractions(formInputResponseService, assessorFormInputResponseService);
}
@Test
public void getQuestion_scopeQuestion() throws Exception {
Long applicationId = 1L;
CompetitionResource competitionResource = setupCompetitionResource();
AssessmentResource assessmentResource = setupAssessment(competitionResource.getId(), applicationId);
SectionResource sectionResource = setupSection(SectionType.GENERAL);
QuestionResource questionResource = setupQuestion(assessmentResource.getId());
QuestionResource previousQuestionResource = newQuestionResource()
.withShortName("Previous question")
.withSection(sectionResource.getId())
.build();
QuestionResource nextQuestionResource = newQuestionResource()
.withShortName("Next question")
.withSection(sectionResource.getId())
.build();
setupQuestionNavigation(questionResource.getId(), of(previousQuestionResource), of(nextQuestionResource));
List<FormInputResource> applicationFormInputs = setupApplicationFormInputs(questionResource.getId(), TEXTAREA);
setupApplicantResponses(applicationId, applicationFormInputs);
List<FormInputResource> assessmentFormInputs = setupAssessmentFormInputs(questionResource.getId(), TEXTAREA,
ASSESSOR_SCORE, ASSESSOR_RESEARCH_CATEGORY, ASSESSOR_APPLICATION_IN_SCOPE);
List<AssessorFormInputResponseResource> assessorResponses = setupAssessorResponses(assessmentResource.getId(),
questionResource.getId(), assessmentFormInputs);
Form expectedForm = new Form();
expectedForm.setFormInput(simpleToMap(assessorResponses, assessorFormInputResponseResource ->
String.valueOf(assessorFormInputResponseResource.getFormInput()), AssessorFormInputResponseResource::getValue));
AssessmentNavigationViewModel expectedNavigation = new AssessmentNavigationViewModel(assessmentResource.getId(),
of(previousQuestionResource), of(nextQuestionResource));
List<ResearchCategoryResource> researchCategoryResources = setupResearchCategories();
AssessmentFeedbackViewModel expectedViewModel = new AssessmentFeedbackViewModel(assessmentResource.getId(),
3,
50,
applicationId,
"Application name",
questionResource.getId(),
"1",
"Market opportunity",
"1. What is the business opportunity that this project addresses?",
50,
"Applicant response",
assessmentFormInputs,
true,
true,
false,
null,
researchCategoryResources);
mockMvc.perform(get("/{assessmentId}/question/{questionId}", assessmentResource.getId(),
questionResource.getId()))
.andExpect(status().isOk())
.andExpect(model().attribute("form", expectedForm))
.andExpect(model().attribute("model", expectedViewModel))
.andExpect(model().attribute("navigation", expectedNavigation))
.andExpect(view().name("assessment/application-question"));
InOrder inOrder = inOrder(questionService, formInputService, assessorFormInputResponseService, assessmentService,
competitionService, formInputResponseService, categoryServiceMock);
inOrder.verify(questionService).getByIdAndAssessmentId(questionResource.getId(), assessmentResource.getId());
inOrder.verify(formInputService).findApplicationInputsByQuestion(questionResource.getId());
inOrder.verify(assessorFormInputResponseService).getAllAssessorFormInputResponsesByAssessmentAndQuestion(assessmentResource.getId(), questionResource.getId());
inOrder.verify(assessmentService).getById(assessmentResource.getId());
inOrder.verify(competitionService).getById(competitionResource.getId());
inOrder.verify(formInputService).findApplicationInputsByQuestion(questionResource.getId());
applicationFormInputs.forEach(formInput -> inOrder.verify(formInputResponseService).getByFormInputIdAndApplication(formInput.getId(), applicationId));
inOrder.verify(formInputService).findAssessmentInputsByQuestion(questionResource.getId());
inOrder.verify(categoryServiceMock).getResearchCategories();
inOrder.verify(questionService).getPreviousQuestion(questionResource.getId());
inOrder.verify(questionService).getNextQuestion(questionResource.getId());
inOrder.verifyNoMoreInteractions();
}
@Test
public void updateFormInputResponse() throws Exception {
Long assessmentId = 1L;
String value = "Feedback";
Long formInputId = 1L;
when(assessorFormInputResponseService.updateFormInputResponse(assessmentId, formInputId, value)).thenReturn(serviceSuccess());
mockMvc.perform(post("/{assessmentId}/formInput/{formInputId}", assessmentId, formInputId)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("value", value))
.andExpect(status().isOk())
.andExpect(jsonPath("success", is("true")))
.andReturn();
verify(assessorFormInputResponseService, only()).updateFormInputResponse(assessmentId, formInputId, value);
}
@Test
public void updateFormInputResponse_exceedsCharacterSizeLimit() throws Exception {
Long assessmentId = 1L;
String value = "This is the feedback";
Long formInputId = 2L;
when(assessorFormInputResponseService.updateFormInputResponse(assessmentId, formInputId, value))
.thenReturn(serviceFailure(fieldError("value", "Feedback", "validation.field.too.many.characters", "", "5000", "0")));
when(messageSource.getMessage("validation.field.too.many.characters", new Object[]{"", "5000", "0"}, Locale.UK))
.thenReturn("This field cannot contain more than 5000 characters");
MvcResult result = mockMvc.perform(post("/{assessmentId}/formInput/{formInputId}", assessmentId, formInputId)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("value", value))
.andExpect(status().isOk())
.andExpect(jsonPath("success", is("true")))
.andReturn();
verify(assessorFormInputResponseService, only()).updateFormInputResponse(assessmentId, formInputId, value);
String content = result.getResponse().getContentAsString();
String jsonExpectedContent = "{\"success\":\"true\"}";
assertEquals(jsonExpectedContent, content);
}
@Test
public void updateFormInputResponse_exceedWordLimit() throws Exception {
Long assessmentId = 1L;
String value = "This is the feedback";
Long formInputId = 2L;
when(assessorFormInputResponseService.updateFormInputResponse(assessmentId, formInputId, value))
.thenReturn(serviceFailure(fieldError("value", "Feedback", "validation.field.max.word.count", "", 100)));
when(messageSource.getMessage("validation.field.max.word.count", new Object[]{"", "100"}, Locale.UK))
.thenReturn("Maximum word count exceeded. Please reduce your word count to 100.");
MvcResult result = mockMvc.perform(post("/{assessmentId}/formInput/{formInputId}", assessmentId, formInputId)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("value", value))
.andExpect(status().isOk())
.andExpect(jsonPath("success", is("true")))
.andReturn();
verify(assessorFormInputResponseService, only()).updateFormInputResponse(assessmentId, formInputId, value);
String content = result.getResponse().getContentAsString();
String jsonExpectedContent = "{\"success\":\"true\"}";
assertEquals(jsonExpectedContent, content);
}
@Test
public void save() throws Exception {
long assessmentId = 1L;
long questionId = 2L;
List<FormInputResource> formInputs = setupAssessmentFormInputs(questionId, ASSESSOR_SCORE, TEXTAREA);
Long formInputIdScore = formInputs.get(0).getId();
Long formInputIdFeedback = formInputs.get(1).getId();
String formInputScoreField = format("formInput[%s]", formInputIdScore);
String formInputFeedbackField = format("formInput[%s]", formInputIdFeedback);
when(assessorFormInputResponseService.updateFormInputResponse(assessmentId, formInputIdScore, "10")).thenReturn(serviceSuccess());
when(assessorFormInputResponseService.updateFormInputResponse(assessmentId, formInputIdFeedback, "Feedback")).thenReturn(serviceSuccess());
mockMvc.perform(post("/{assessmentId}/question/{questionId}", assessmentId, questionId)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param(formInputScoreField, "10")
.param(formInputFeedbackField, "Feedback"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(format("/%s", assessmentId)))
.andReturn();
verify(assessorFormInputResponseService).updateFormInputResponse(assessmentId, formInputIdScore, "10");
verify(assessorFormInputResponseService).updateFormInputResponse(assessmentId, formInputIdFeedback, "Feedback");
}
@Test
public void save_exceedsCharacterSizeLimit() throws Exception {
Long applicationId = 1L;
CompetitionResource competitionResource = setupCompetitionResource();
AssessmentResource assessmentResource = setupAssessment(competitionResource.getId(), applicationId);
QuestionResource questionResource = setupQuestion(assessmentResource.getId());
setupQuestionNavigation(questionResource.getId(), empty(), empty());
List<FormInputResource> formInputs = setupAssessmentFormInputs(questionResource.getId(), ASSESSOR_SCORE, TEXTAREA);
Long formInputIdScore = formInputs.get(0).getId();
Long formInputIdFeedback = formInputs.get(1).getId();
String formInputScoreField = format("formInput[%s]", formInputIdScore);
String formInputFeedbackField = format("formInput[%s]", formInputIdFeedback);
when(assessorFormInputResponseService.updateFormInputResponse(assessmentResource.getId(), formInputIdScore, "10"))
.thenReturn(serviceSuccess());
when(assessorFormInputResponseService.updateFormInputResponse(assessmentResource.getId(), formInputIdFeedback, "Feedback"))
.thenReturn(serviceFailure(fieldError("value", "Feedback", "validation.field.too.many.characters", "", "5000", "0")));
// For re-display of question view following the invalid data entry
List<FormInputResource> applicationFormInputs = setupApplicationFormInputs(questionResource.getId(), TEXTAREA);
setupApplicantResponses(applicationId, applicationFormInputs);
MvcResult result = mockMvc.perform(post("/{assessmentId}/question/{questionId}",
assessmentResource.getId(), questionResource.getId())
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param(formInputScoreField, "10")
.param(formInputFeedbackField, "Feedback"))
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andExpect(model().attributeHasFieldErrors("form"))
.andExpect(view().name("assessment/application-question"))
.andReturn();
verify(assessorFormInputResponseService).updateFormInputResponse(assessmentResource.getId(), formInputIdScore, "10");
verify(assessorFormInputResponseService).updateFormInputResponse(assessmentResource.getId(), formInputIdFeedback, "Feedback");
Form form = (Form) result.getModelAndView().getModel().get("form");
assertEquals("10", form.getFormInput(formInputIdScore.toString()));
assertEquals("Feedback", form.getFormInput(formInputIdFeedback.toString()));
BindingResult bindingResult = form.getBindingResult();
assertEquals(0, bindingResult.getGlobalErrorCount());
assertEquals(1, bindingResult.getFieldErrorCount());
assertTrue(bindingResult.hasFieldErrors(formInputFeedbackField));
assertEquals("validation.field.too.many.characters", bindingResult.getFieldError(formInputFeedbackField).getCode());
assertEquals("5000", bindingResult.getFieldError(formInputFeedbackField).getArguments()[1]);
assertEquals("0", bindingResult.getFieldError(formInputFeedbackField).getArguments()[2]);
}
@Test
public void save_exceedWordLimit() throws Exception {
Long applicationId = 1L;
CompetitionResource competitionResource = setupCompetitionResource();
AssessmentResource assessmentResource = setupAssessment(competitionResource.getId(), applicationId);
QuestionResource questionResource = setupQuestion(assessmentResource.getId());
setupQuestionNavigation(questionResource.getId(), empty(), empty());
List<FormInputResource> formInputs = setupAssessmentFormInputs(questionResource.getId(), ASSESSOR_SCORE, TEXTAREA);
Long formInputIdScore = formInputs.get(0).getId();
Long formInputIdFeedback = formInputs.get(1).getId();
String formInputScoreField = format("formInput[%s]", formInputIdScore);
String formInputFeedbackField = format("formInput[%s]", formInputIdFeedback);
when(assessorFormInputResponseService.updateFormInputResponse(assessmentResource.getId(), formInputIdScore, "10"))
.thenReturn(serviceSuccess());
when(assessorFormInputResponseService.updateFormInputResponse(assessmentResource.getId(), formInputIdFeedback, "Feedback"))
.thenReturn(serviceFailure(fieldError("value", "Feedback", "validation.field.max.word.count", "", 100)));
// For re-display of question view following the invalid data entry
List<FormInputResource> applicationFormInputs = setupApplicationFormInputs(questionResource.getId(), TEXTAREA);
setupApplicantResponses(applicationId, applicationFormInputs);
MvcResult result = mockMvc.perform(post("/{assessmentId}/question/{questionId}",
assessmentResource.getId(), questionResource.getId())
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param(formInputScoreField, "10")
.param(formInputFeedbackField, "Feedback"))
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andExpect(model().attributeHasFieldErrors("form"))
.andExpect(view().name("assessment/application-question"))
.andReturn();
verify(assessorFormInputResponseService).updateFormInputResponse(assessmentResource.getId(), formInputIdScore, "10");
verify(assessorFormInputResponseService).updateFormInputResponse(assessmentResource.getId(), formInputIdFeedback, "Feedback");
Form form = (Form) result.getModelAndView().getModel().get("form");
assertEquals("10", form.getFormInput(formInputIdScore.toString()));
assertEquals("Feedback", form.getFormInput(formInputIdFeedback.toString()));
BindingResult bindingResult = form.getBindingResult();
assertEquals(0, bindingResult.getGlobalErrorCount());
assertEquals(1, bindingResult.getFieldErrorCount());
assertTrue(bindingResult.hasFieldErrors(formInputFeedbackField));
assertEquals("validation.field.max.word.count", bindingResult.getFieldError(formInputFeedbackField).getCode());
assertEquals("100", bindingResult.getFieldError(formInputFeedbackField).getArguments()[1]);
}
private CompetitionResource setupCompetitionResource() {
LocalDate now = LocalDate.now();
CompetitionResource competitionResource = newCompetitionResource()
.withAssessorAcceptsDate(now.atStartOfDay().minusDays(2))
.withAssessorDeadlineDate(LocalDateTime.now().plusDays(4))
.build();
when(competitionService.getById(competitionResource.getId())).thenReturn(competitionResource);
return competitionResource;
}
private SectionResource setupSection(SectionType sectionType) {
SectionResource sectionResource = newSectionResource()
.withType(sectionType)
.build();
when(sectionService.getById(sectionResource.getId())).thenReturn(sectionResource);
return sectionResource;
}
private QuestionResource setupQuestion(long assessmentId) {
QuestionResource questionResource = newQuestionResource()
.withQuestionNumber("1")
.withShortName("Market opportunity")
.withName("1. What is the business opportunity that this project addresses?")
.withAssessorMaximumScore(50)
.build();
when(questionService.getByIdAndAssessmentId(questionResource.getId(), assessmentId))
.thenReturn(questionResource);
return questionResource;
}
private void setupQuestionNavigation(long questionId, Optional<QuestionResource> previous, Optional<QuestionResource> next) {
when(questionService.getPreviousQuestion(questionId)).thenReturn(previous);
when(questionService.getNextQuestion(questionId)).thenReturn(next);
}
private List<FormInputResource> setupApplicationFormInputs(Long questionId, FormInputType... formInputTypes) {
List<FormInputResource> formInputs = stream(formInputTypes).map(formInputType ->
newFormInputResource()
.withType(formInputType)
.build()
).collect(toList());
when(formInputService.findApplicationInputsByQuestion(questionId)).thenReturn(formInputs);
return formInputs;
}
private List<FormInputResource> setupAssessmentFormInputs(Long questionId, FormInputType... formInputTypes) {
List<FormInputResource> formInputs = stream(formInputTypes).map(formInputType ->
newFormInputResource()
.withType(formInputType)
.build()
).collect(toList());
when(formInputService.findAssessmentInputsByQuestion(questionId)).thenReturn(formInputs);
return formInputs;
}
private List<FormInputResponseResource> setupApplicantResponses(Long applicationId, List<FormInputResource> formInputs) {
List<FormInputResponseResource> applicantResponses = formInputs.stream().map(formInput -> {
if (formInput.getType() == FILEUPLOAD) {
return newFormInputResponseResource()
.withFormInputs(formInput.getId())
.withValue("Applicant response")
.withFileName("File 1")
.withFilesizeBytes(1024L)
.build();
} else {
return newFormInputResponseResource()
.withFormInputs(formInput.getId())
.withValue("Applicant response")
.build();
}
}
).collect(Collectors.toList());
applicantResponses.forEach(formInputResponse -> when(formInputResponseService.getByFormInputIdAndApplication(
formInputResponse.getFormInput(), applicationId)).thenReturn(restSuccess(singletonList(formInputResponse))));
return applicantResponses;
}
private List<AssessorFormInputResponseResource> setupAssessorResponses(Long assessmentId, Long questionId, List<FormInputResource> formInputs) {
List<AssessorFormInputResponseResource> assessorResponses = formInputs.stream().map(formInput ->
newAssessorFormInputResponseResource()
.withFormInput(formInput.getId())
.withValue("Assessor response")
.build()
).collect(toList());
when(assessorFormInputResponseService.getAllAssessorFormInputResponsesByAssessmentAndQuestion(assessmentId, questionId)).thenReturn(assessorResponses);
return assessorResponses;
}
private AssessmentResource setupAssessment(long competitionId, long applicationId) {
AssessmentResource assessmentResource = newAssessmentResource()
.withApplication(applicationId)
.withApplicationName("Application name")
.withCompetition(competitionId)
.build();
when(assessmentService.getById(assessmentResource.getId())).thenReturn(assessmentResource);
return assessmentResource;
}
private List<ResearchCategoryResource> setupResearchCategories() {
List<ResearchCategoryResource> categories = newResearchCategoryResource()
.withName("Research category")
.build(1);
when(categoryServiceMock.getResearchCategories()).thenReturn(categories);
return categories;
}
} |
package agreementMaker.userInterface;
public class Help {
public static String getHelpMenuString() {
String result = "";
result += "HELP\n\n";
result+="This Help is just a brief introduction to the AgreementMaker. Can be useful to watch the video available on the distribution website.\n\n";
result += "1) Load source and target ontologies.\n\n";
result += "First open source and target ontologies by clicking on File->Open Source/Target Ontology, and selecting filepath and format.\n";
result += "OAEI-2007 example ontologies contained in the AM distribution are OWL-N3.\n";
result += "OAEI-2008 example ontologies contained in the AM distribution are OWL-RDF/XML.\n";
result += "GEOSPATIAL are XML ontologies\n";
result += "\n";
result += "2) Browse ontologies\n\n";
result += "Click on a concept node to select it. Click everywhere in the canvas to deselect all. In the description panel on the right is possible to visualize additional informations.\n";
result += "In a OWL ontology following informations are available: localname, label, comment, seeAlso, isDefinedBy, properties, and individuals\n";
result += "Class and Property hierarchy are displayed in the canvas.\n";
result += "In a XML ontology: localname = tag id, label = tag label, comment = tag exp, seeAlso = tag seeAlso, and isDefBy = tag isDefBy, no properties or individuals.\n";
result += "All xml concepts are displayed as a unique class hierarchy.\n";
result += "Concepts with multiple ancestors will be duplicated and shown more then once, but they will be aligned once.\n";
result+= "\n";
result += "3)Run matchers to perform matchings.\n\n";
result += "All matchers are available in the matchers selection menu. Click on details button to view a brief description of the selected matcher, not always available.\n";
result += "To run the selected matcher click on the Match button.Common parameters like threshold and number of relations has to be set before the match operations. Default values are automatically selected.\n";
result += "Any matcher will perform the similarity between each source concept with each target concept building a similarity matrix.\n";
result += "Alignments will be selected from the matrix if their similarity is higher then the threshold, and if they satisfy the maximal number or relations for source and target.\n";
result += "This process is done for classes and matrix if the matcher align both.\n";
result += "Each matcher will be saved in a new row of the table of the control panel. From there is possible to modify parameters after the execution.Is it also possible to delete matchers.\n";
result += "Some matchers can run just with common parameters, Some other need more parameters that will be required by the proper panel.\n";
result += "Some matchers requires other matching result in input, so is not possible to run them without having run other matcher first.\n";
result += "Matchers that can run first are Base_similarity or Parametric String matcher, while DSI and SSC must run after selecting the output of a previous one.\n";
result += "\n";
result += "4) Manual mappings.\n\n";
result += "Is it possible to add new mappings or edit mappings generated by any matcher.\n";
result += "Select source nodes and target nodes that needs to be aligned using left click and optionally shift or ctrl for multiple selections.\n";
result += "A popup menu will appear which allow the user to create a standard mapping 100% similarity or to create any kind of mapping inserting the required similiraty value.\n";
result += "Is it also possible to modify the similarity or to delete a previous generated mapping.\n";
result += "If no matchers are selected in the table, then all manual changes will be applied only to the User Manual Matcher.\n If any other matcher is selected then manual changes will be applied to all of them.\n";
result += "Is it also possible to create an empty matcher to allow the user to have different set of manual mappings.\n";
result += "\n";
result += "5) Combine matchings.\n\n";
result += "Matchings can be combined with the 'Manual Combination Matcher'. Select serveral matchings from the matchers table and run the matcher.\n";
result += "A new similarity matrix will be built from the matrices of the matchers in input.Different operations are available to calculate a new similarity for each pair of source and target nodes.\n";
result += "Maximum, Minimun, average or weighted average of the similarity of each matcher in input for each source and target node.\n";
result += "An automatic quality based combination technique is being studied, but is not ready yet.\n";
result+= "\n";
result += "6) Evaluate matchings with a reference file.\n\n";
result += "A reference file is a set of mappings given by a domain expert which includes all correct alignments for a source and target ontology.\n";
result += "All sample ontologies in the distribution have a reference file (e.g. WeaponsA and WeaponsB have the reference file WeaponsAB),\n";
result += "Evaluating a matching means comparing the sets of alignments found with perfect set of alignments of the reference.Different measure are given.\n";
result += "Recall = #correct / #found . Precision = #correct/#reference_mappings, F-Measure = (2*Precision+recall) / Precision * Recall\n";
result += "Changing threshold will affect these measures significantly, increasing it increases precision and decreases recall and vice-versa.\n";
result += "To evaluate a matcher select it, run reference evaluation selecting the reference file with the corresponding format.If the reference file contains 0 alignments it probably means that the wrong format has been chosen.\n";
result += "Is it also possible to visualize reference alignments in the canvas running the reference alignment matcher.\n";
result += "\n";
result += "7) Save alignments into a file.\n\n";
result += "It is possible to save the alignments into an XML, DOC or TXT file. XLS it the better for visualizing them.\n";
result += "Just select matchings to be saved, click save and select filename, destionation and extension. Remember to not put any dot or wrong characters in the name.\n";
return result;
}
} |
package edu.umd.cs.findbugs;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantDouble;
import org.apache.bcel.classfile.ConstantFloat;
import org.apache.bcel.classfile.ConstantInteger;
import org.apache.bcel.classfile.ConstantLong;
import org.apache.bcel.classfile.ConstantString;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.AnalysisFeatures;
import edu.umd.cs.findbugs.ba.ClassMember;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.visitclass.Constants2;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.LVTHelper;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
/**
* tracks the types and numbers of objects that are currently on the operand stack
* throughout the execution of method. To use, a detector should instantiate one for
* each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method.
* at any point you can then inspect the stack and see what the types of objects are on
* the stack, including constant values if they were pushed. The types described are of
* course, only the static types.
* There are some outstanding opcodes that have yet to be implemented, I couldn't
* find any code that actually generated these, so i didn't put them in because
* I couldn't test them:
* <ul>
* <li>dup2_x2</li>
* <li>jsr_w</li>
* <li>wide</li>
* </ul>
*/
public class OpcodeStack implements Constants2
{
private static final boolean DEBUG
= SystemProperties.getBoolean("ocstack.debug");
private static final boolean DEBUG2 = DEBUG;
private List<Item> stack;
private List<Item> lvValues;
private List<Integer> lastUpdate;
private boolean top;
private boolean seenTransferOfControl = false;
private boolean useIterativeAnalysis
= AnalysisContext.currentAnalysisContext().getBoolProperty(AnalysisFeatures.INTERATIVE_OPCODE_STACK_ANALYSIS);
public static class ItemBase {
public ItemBase() {};
}
public static class Item extends ItemBase
{
public static final int SIGNED_BYTE = 1;
public static final int RANDOM_INT = 2;
public static final int LOW_8_BITS_CLEAR = 3;
public static final int HASHCODE_INT = 4;
public static final int INTEGER_SUM = 5;
public static final int AVERAGE_COMPUTED_USING_DIVISION = 6;
public static final int FLOAT_MATH = 7;
public static final int RANDOM_INT_REMAINDER = 8;
public static final int HASHCODE_INT_REMAINDER = 9;
public static final int FILE_SEPARATOR_STRING = 10;
public static final int MATH_ABS = 11;
public static final int MASKED_NON_NEGATIVE = 12;
public static final int NASTY_FLOAT_MATH = 13;
private static final int IS_INITIAL_PARAMETER_FLAG=1;
private static final int COULD_BE_ZERO_FLAG = 2;
private static final int IS_NULL_FLAG = 4;
public static final Object UNKNOWN = null;
private int specialKind;
private String signature;
private Object constValue = UNKNOWN;
private @CheckForNull ClassMember source;
private int flags;
// private boolean isNull = false;
private int registerNumber = -1;
// private boolean isInitialParameter = false;
// private boolean couldBeZero = false;
private Object userValue = null;
private int fieldLoadedFromRegister = -1;
public int getSize() {
if (signature.equals("J") || signature.equals("D")) return 2;
return 1;
}
public boolean isWide() {
return getSize() == 2;
}
private static boolean equals(Object o1, Object o2) {
if (o1 == o2) return true;
if (o1 == null || o2 == null) return false;
return o1.equals(o2);
}
@Override
public int hashCode() {
int r = 42 + specialKind;
if (signature != null)
r+= signature.hashCode();
r *= 31;
if (constValue != null)
r+= constValue.hashCode();
r *= 31;
if (source != null)
r+= source.hashCode();
r *= 31;
r += flags;
r *= 31;
r += registerNumber;
return r;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Item)) return false;
Item that = (Item) o;
return equals(this.signature, that.signature)
&& equals(this.constValue, that.constValue)
&& equals(this.source, that.source)
&& this.specialKind == that.specialKind
&& this.registerNumber == that.registerNumber
&& this.flags == that.flags
&& this.userValue == that.userValue
&& this.fieldLoadedFromRegister == that.fieldLoadedFromRegister;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer("< ");
buf.append(signature);
switch(specialKind) {
case SIGNED_BYTE:
buf.append(", byte_array_load");
break;
case RANDOM_INT:
buf.append(", random_int");
break;
case LOW_8_BITS_CLEAR:
buf.append(", low8clear");
break;
case HASHCODE_INT:
buf.append(", hashcode_int");
break;
case INTEGER_SUM:
buf.append(", int_sum");
break;
case AVERAGE_COMPUTED_USING_DIVISION:
buf.append(", averageComputingUsingDivision");
break;
case FLOAT_MATH:
buf.append(", floatMath");
break;
case NASTY_FLOAT_MATH:
buf.append(", nastyFloatMath");
break;
case HASHCODE_INT_REMAINDER:
buf.append(", hashcode_int_rem");
break;
case RANDOM_INT_REMAINDER:
buf.append(", random_int_rem");
break;
case FILE_SEPARATOR_STRING:
buf.append(", file_separator_string");
break;
case MATH_ABS:
buf.append(", Math.abs");
break;
case MASKED_NON_NEGATIVE:
buf.append(", masked_non_negative");
break;
case 0 :
break;
default:
buf.append(", #" + specialKind);
break;
}
if (constValue != UNKNOWN) {
buf.append(", ");
buf.append(constValue);
}
if (source instanceof XField) {
buf.append(", ");
if (fieldLoadedFromRegister != -1)
buf.append(fieldLoadedFromRegister).append(':');
buf.append(source);
}
if (source instanceof XMethod) {
buf.append(", return value from ");
buf.append(source);
}
if (isInitialParameter()) {
buf.append(", IP");
}
if (isNull()) {
buf.append(", isNull");
}
if (registerNumber != -1) {
buf.append(", r");
buf.append(registerNumber);
}
if (isCouldBeZero()) buf.append(", cbz");
buf.append(" >");
return buf.toString();
}
public static Item merge(Item i1, Item i2) {
if (i1 == null) return i2;
if (i2 == null) return i1;
if (i1.equals(i2)) return i1;
Item m = new Item();
m.flags = i1.flags & i2.flags;
m.setCouldBeZero(i1.isCouldBeZero() || i2.isCouldBeZero());
if (equals(i1.signature,i2.signature))
m.signature = i1.signature;
if (equals(i1.constValue,i2.constValue))
m.constValue = i1.constValue;
if (equals(i1.source,i2.source)) {
m.source = i1.source;
}
if (i1.registerNumber == i2.registerNumber)
m.registerNumber = i1.registerNumber;
if (i1.fieldLoadedFromRegister == i2.fieldLoadedFromRegister)
m.fieldLoadedFromRegister = i1.fieldLoadedFromRegister;
if (i1.specialKind == i2.specialKind)
m.specialKind = i1.specialKind;
else if (i1.specialKind == NASTY_FLOAT_MATH || i2.specialKind == NASTY_FLOAT_MATH)
m.specialKind = NASTY_FLOAT_MATH;
else if (i1.specialKind == FLOAT_MATH || i2.specialKind == FLOAT_MATH)
m.specialKind = FLOAT_MATH;
if (DEBUG) System.out.println("Merge " + i1 + " and " + i2 + " gives " + m);
return m;
}
public Item(String signature, int constValue) {
this(signature, (Object)(Integer)constValue);
}
public Item(String signature) {
this(signature, UNKNOWN);
}
public Item(Item it) {
this.signature = it.signature;
this.constValue = it.constValue;
this.source = it.source;
this.registerNumber = it.registerNumber;
this.userValue = it.userValue;
this.flags = it.flags;
this.specialKind = it.specialKind;
}
public Item(Item it, int reg) {
this(it);
this.registerNumber = reg;
}
public Item(String signature, FieldAnnotation f) {
this.signature = signature;
if (f != null)
source = XFactory.createXField(f);
fieldLoadedFromRegister = -1;
}
public Item(String signature, FieldAnnotation f, int fieldLoadedFromRegister) {
this.signature = signature;
if (f != null)
source = XFactory.createXField(f);
this.fieldLoadedFromRegister = fieldLoadedFromRegister;
}
public int getFieldLoadedFromRegister() {
return fieldLoadedFromRegister;
}
public Item(String signature, Object constantValue) {
this.signature = signature;
constValue = constantValue;
if (constantValue instanceof Integer) {
int value = (Integer) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) setCouldBeZero(true);
}
else if (constantValue instanceof Long) {
long value = (Long) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) setCouldBeZero(true);
}
}
public Item() {
signature = "Ljava/lang/Object;";
constValue = null;
setNull(true);
}
public JavaClass getJavaClass() throws ClassNotFoundException {
String baseSig;
if (isPrimitive())
return null;
if (isArray()) {
baseSig = getElementSignature();
} else {
baseSig = signature;
}
if (baseSig.length() == 0)
return null;
baseSig = baseSig.substring(1, baseSig.length() - 1);
baseSig = baseSig.replace('/', '.');
return Repository.lookupClass(baseSig);
}
public boolean isArray() {
return signature.startsWith("[");
}
public String getElementSignature() {
if (!isArray())
return signature;
else {
int pos = 0;
int len = signature.length();
while (pos < len) {
if (signature.charAt(pos) != '[')
break;
pos++;
}
return signature.substring(pos);
}
}
public boolean isNonNegative() {
if (specialKind == MASKED_NON_NEGATIVE) return true;
if (constValue instanceof Number) {
double value = ((Number) constValue).doubleValue();
return value >= 0;
}
return false;
}
public boolean isPrimitive() {
return !signature.startsWith("L");
}
public int getRegisterNumber() {
return registerNumber;
}
public String getSignature() {
return signature;
}
/**
* Returns a constant value for this Item, if known.
* NOTE: if the value is a constant Class object, the constant value returned is the name of the class.
*/
public Object getConstant() {
return constValue;
}
/** Use getXField instead */
@Deprecated
public FieldAnnotation getFieldAnnotation() {
return FieldAnnotation.fromXField(getXField());
}
public XField getXField() {
if (source instanceof XField) return (XField) source;
return null;
}
/**
* @param specialKind The specialKind to set.
*/
public void setSpecialKind(int specialKind) {
this.specialKind = specialKind;
}
/**
* @return Returns the specialKind.
*/
public int getSpecialKind() {
return specialKind;
}
/**
* attaches a detector specified value to this item
*
* @param value the custom value to set
*/
public void setUserValue(Object value) {
userValue = value;
}
/**
*
* @return if this value is the return value of a method, give the method
* invoked
*/
public @CheckForNull XMethod getReturnValueOf() {
if (source instanceof XMethod) return (XMethod) source;
return null;
}
public boolean couldBeZero() {
return isCouldBeZero();
}
public boolean mustBeZero() {
Object value = getConstant();
return value instanceof Number && ((Number)value).intValue() == 0;
}
/**
* gets the detector specified value for this item
*
* @return the custom value
*/
public Object getUserValue() {
return userValue;
}
public boolean valueCouldBeNegative() {
return (getSpecialKind() == Item.RANDOM_INT
|| getSpecialKind() == Item.SIGNED_BYTE
|| getSpecialKind() == Item.HASHCODE_INT
|| getSpecialKind() == Item.RANDOM_INT_REMAINDER || getSpecialKind() == Item.HASHCODE_INT_REMAINDER);
}
/**
* @param isInitialParameter The isInitialParameter to set.
*/
private void setInitialParameter(boolean isInitialParameter) {
setFlag(isInitialParameter, IS_INITIAL_PARAMETER_FLAG);
}
/**
* @return Returns the isInitialParameter.
*/
public boolean isInitialParameter() {
return (flags & IS_INITIAL_PARAMETER_FLAG) != 0;
}
/**
* @param couldBeZero The couldBeZero to set.
*/
private void setCouldBeZero(boolean couldBeZero) {
setFlag(couldBeZero, COULD_BE_ZERO_FLAG);
}
/**
* @return Returns the couldBeZero.
*/
private boolean isCouldBeZero() {
return (flags & COULD_BE_ZERO_FLAG) != 0;
}
/**
* @param isNull The isNull to set.
*/
private void setNull(boolean isNull) {
setFlag(isNull, IS_NULL_FLAG);
}
private void setFlag(boolean value, int flagBit) {
if (value)
flags |= flagBit;
else
flags &= ~flagBit;
}
/**
* @return Returns the isNull.
*/
public boolean isNull() {
return (flags & IS_NULL_FLAG) != 0;
}
}
@Override
public String toString() {
if (isTop())
return "TOP";
return stack.toString() + "::" + lvValues.toString();
}
public OpcodeStack()
{
stack = new ArrayList<Item>();
lvValues = new ArrayList<Item>();
lastUpdate = new ArrayList<Integer>();
}
boolean needToMerge = true;
boolean reachOnlyByBranch = false;
public static String getExceptionSig(DismantleBytecode dbc, CodeException e) {
if (e.getCatchType() == 0) return "Ljava/lang/Throwable;";
Constant c = dbc.getConstantPool().getConstant(e.getCatchType());
if (c instanceof ConstantClass)
return "L"+((ConstantClass)c).getBytes(dbc.getConstantPool())+";";
return "Ljava/lang/Throwable;";
}
public void mergeJumps(DismantleBytecode dbc) {
if (!needToMerge) return;
needToMerge = false;
boolean stackUpdated = false;
if (!isTop() && (convertJumpToOneZeroState == 3 || convertJumpToZeroOneState == 3)) {
pop();
Item top = new Item("I");
top.setCouldBeZero(true);
push(top);
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
stackUpdated = true;
}
List<Item> jumpEntry = null;
if (jumpEntryLocations.get(dbc.getPC()))
jumpEntry = jumpEntries.get(dbc.getPC());
if (jumpEntry != null) {
reachOnlyByBranch = false;
List<Item> jumpStackEntry = jumpStackEntries.get(dbc.getPC());
if (DEBUG2) {
System.out.println("XXXXXXX " + reachOnlyByBranch);
System.out.println("merging lvValues at jump target " + dbc.getPC() + " -> " + Integer.toString(System.identityHashCode(jumpEntry),16) + " " + jumpEntry);
System.out.println(" current lvValues " + lvValues);
System.out.println(" merging stack entry " + jumpStackEntry);
System.out.println(" current stack values " + stack);
}
if (isTop()) {
lvValues = new ArrayList<Item>(jumpEntry);
if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry);
else stack.clear();
setTop(false);
return;
}
if (reachOnlyByBranch) {
setTop(false);
lvValues = new ArrayList<Item>(jumpEntry);
if (!stackUpdated) {
if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry);
else stack.clear();
}
}
else {
setTop(false);
mergeLists(lvValues, jumpEntry, false);
if (!stackUpdated && jumpStackEntry != null) mergeLists(stack, jumpStackEntry, false);
}
if (DEBUG)
System.out.println(" merged lvValues " + lvValues);
}
else if (reachOnlyByBranch && !stackUpdated) {
stack.clear();
boolean foundException = false;
for(CodeException e : dbc.getCode().getExceptionTable()) {
if (e.getHandlerPC() == dbc.getPC()) {
push(new Item(getExceptionSig(dbc, e)));
foundException = true;
}
}
if (!foundException) {
setTop(true);
}
else reachOnlyByBranch = false;
}
}
int convertJumpToOneZeroState = 0;
int convertJumpToZeroOneState = 0;
private void setLastUpdate(int reg, int pc) {
while (lastUpdate.size() <= reg) lastUpdate.add(0);
lastUpdate.set(reg, pc);
}
public int getLastUpdate(int reg) {
if (lastUpdate.size() <= reg) return 0;
return lastUpdate.get(reg);
}
public int getNumLastUpdates() {
return lastUpdate.size();
}
public void sawOpcode(DismantleBytecode dbc, int seen) {
int register;
String signature;
Item it, it2, it3;
Constant cons;
if (dbc.isRegisterStore())
setLastUpdate(dbc.getRegisterOperand(), dbc.getPC());
mergeJumps(dbc);
needToMerge = true;
try
{
if (isTop()) {
return;
}
switch (seen) {
case ICONST_1:
convertJumpToOneZeroState = 1;
break;
case GOTO:
if (convertJumpToOneZeroState == 1 && dbc.getBranchOffset() == 4)
convertJumpToOneZeroState = 2;
else
convertJumpToOneZeroState = 0;
break;
case ICONST_0:
if (convertJumpToOneZeroState == 2)
convertJumpToOneZeroState = 3;
else convertJumpToOneZeroState = 0;
break;
default:convertJumpToOneZeroState = 0;
}
switch (seen) {
case ICONST_0:
convertJumpToZeroOneState = 1;
break;
case GOTO:
if (convertJumpToZeroOneState == 1 && dbc.getBranchOffset() == 4)
convertJumpToZeroOneState = 2;
else
convertJumpToZeroOneState = 0;
break;
case ICONST_1:
if (convertJumpToZeroOneState == 2)
convertJumpToZeroOneState = 3;
else convertJumpToZeroOneState = 0;
break;
default:convertJumpToZeroOneState = 0;
}
switch (seen) {
case ALOAD:
pushByLocalObjectLoad(dbc, dbc.getRegisterOperand());
break;
case ALOAD_0:
case ALOAD_1:
case ALOAD_2:
case ALOAD_3:
pushByLocalObjectLoad(dbc, seen - ALOAD_0);
break;
case DLOAD:
pushByLocalLoad("D", dbc.getRegisterOperand());
break;
case DLOAD_0:
case DLOAD_1:
case DLOAD_2:
case DLOAD_3:
pushByLocalLoad("D", seen - DLOAD_0);
break;
case FLOAD:
pushByLocalLoad("F", dbc.getRegisterOperand());
break;
case FLOAD_0:
case FLOAD_1:
case FLOAD_2:
case FLOAD_3:
pushByLocalLoad("F", seen - FLOAD_0);
break;
case ILOAD:
pushByLocalLoad("I", dbc.getRegisterOperand());
break;
case ILOAD_0:
case ILOAD_1:
case ILOAD_2:
case ILOAD_3:
pushByLocalLoad("I", seen - ILOAD_0);
break;
case LLOAD:
pushByLocalLoad("J", dbc.getRegisterOperand());
break;
case LLOAD_0:
case LLOAD_1:
case LLOAD_2:
case LLOAD_3:
pushByLocalLoad("J", seen - LLOAD_0);
break;
case GETSTATIC:
{
FieldAnnotation field = FieldAnnotation.fromReferencedField(dbc);
Item i = new Item(dbc.getSigConstantOperand(), field, Integer.MAX_VALUE);
if (field.getFieldName().equals("separator") && field.getClassName().equals("java.io.File")) {
i.setSpecialKind(Item.FILE_SEPARATOR_STRING);
}
push(i);
break;
}
case LDC:
case LDC_W:
case LDC2_W:
cons = dbc.getConstantRefOperand();
pushByConstant(dbc, cons);
break;
case INSTANCEOF:
pop();
push(new Item("I"));
break;
case IFEQ:
case IFNE:
case IFLT:
case IFLE:
case IFGT:
case IFGE:
case IFNONNULL:
case IFNULL:
seenTransferOfControl = true;
{
Item top = pop();
// if we see a test comparing a special negative value with 0,
// reset all other such values on the opcode stack
if (top.valueCouldBeNegative()
&& (seen == IFLT || seen == IFLE || seen == IFGT || seen == IFGE)) {
int specialKind = top.getSpecialKind();
for(Item item : stack) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0);
for(Item item : lvValues) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0);
}
}
addJumpValue(dbc.getBranchTarget());
break;
case LOOKUPSWITCH:
case TABLESWITCH:
seenTransferOfControl = true;
reachOnlyByBranch = true;
pop();
addJumpValue(dbc.getBranchTarget());
int pc = dbc.getBranchTarget() - dbc.getBranchOffset();
for(int offset : dbc.getSwitchOffsets())
addJumpValue(offset+pc);
break;
case ARETURN:
case DRETURN:
case FRETURN:
case IRETURN:
case LRETURN:
seenTransferOfControl = true;
reachOnlyByBranch = true;
pop();
break;
case MONITORENTER:
case MONITOREXIT:
case POP:
case PUTSTATIC:
pop();
break;
case IF_ACMPEQ:
case IF_ACMPNE:
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPLE:
case IF_ICMPGT:
case IF_ICMPGE:
seenTransferOfControl = true;
pop(2);
addJumpValue(dbc.getBranchTarget());
break;
case POP2:
it = pop();
if (it.getSize() == 1) pop();
break;
case PUTFIELD:
pop(2);
break;
case IALOAD:
case SALOAD:
pop(2);
push(new Item("I"));
break;
case DUP:
handleDup();
break;
case DUP2:
handleDup2();
break;
case DUP_X1:
handleDupX1();
break;
case DUP_X2:
handleDupX2();
break;
case DUP2_X1:
handleDup2X1();
break;
case DUP2_X2:
handleDup2X2();
break;
case IINC:
register = dbc.getRegisterOperand();
it = getLVValue( register );
it2 = new Item("I", dbc.getIntConstant());
pushByIntMath( IADD, it2, it);
pushByLocalStore(register);
break;
case ATHROW:
pop();
seenTransferOfControl = true;
reachOnlyByBranch = true;
break;
case CHECKCAST:
{
String castTo = dbc.getClassConstantOperand();
if (castTo.charAt(0) != '[') castTo = "L" + castTo + ";";
it = new Item(pop());
it.signature = castTo;
push(it);
break;
}
case NOP:
break;
case RET:
case RETURN:
seenTransferOfControl = true;
reachOnlyByBranch = true;
break;
case GOTO:
case GOTO_W: //It is assumed that no stack items are present when
seenTransferOfControl = true;
reachOnlyByBranch = true;
addJumpValue(dbc.getBranchTarget());
stack.clear();
top = true;
break;
case SWAP:
handleSwap();
break;
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
push(new Item("I", (seen-ICONST_0)));
break;
case LCONST_0:
case LCONST_1:
push(new Item("J", (long)(seen-LCONST_0)));
break;
case DCONST_0:
case DCONST_1:
push(new Item("D", (double)(seen-DCONST_0)));
break;
case FCONST_0:
case FCONST_1:
case FCONST_2:
push(new Item("F", (float)(seen-FCONST_0)));
break;
case ACONST_NULL:
push(new Item());
break;
case ASTORE:
case DSTORE:
case FSTORE:
case ISTORE:
case LSTORE:
pushByLocalStore(dbc.getRegisterOperand());
break;
case ASTORE_0:
case ASTORE_1:
case ASTORE_2:
case ASTORE_3:
pushByLocalStore(seen - ASTORE_0);
break;
case DSTORE_0:
case DSTORE_1:
case DSTORE_2:
case DSTORE_3:
pushByLocalStore(seen - DSTORE_0);
break;
case FSTORE_0:
case FSTORE_1:
case FSTORE_2:
case FSTORE_3:
pushByLocalStore(seen - FSTORE_0);
break;
case ISTORE_0:
case ISTORE_1:
case ISTORE_2:
case ISTORE_3:
pushByLocalStore(seen - ISTORE_0);
break;
case LSTORE_0:
case LSTORE_1:
case LSTORE_2:
case LSTORE_3:
pushByLocalStore(seen - LSTORE_0);
break;
case GETFIELD:
{
Item item = pop();
int reg = item.getRegisterNumber();
push(new Item(dbc.getSigConstantOperand(),
FieldAnnotation.fromReferencedField(dbc), reg));
}
break;
case ARRAYLENGTH:
pop();
push(new Item("I"));
break;
case BALOAD:
{
pop(2);
Item v = new Item("I");
v.setSpecialKind(Item.SIGNED_BYTE);
push(v);
break;
}
case CALOAD:
pop(2);
push(new Item("I"));
break;
case DALOAD:
pop(2);
push(new Item("D"));
break;
case FALOAD:
pop(2);
push(new Item("F"));
break;
case LALOAD:
pop(2);
push(new Item("J"));
break;
case AASTORE:
case BASTORE:
case CASTORE:
case DASTORE:
case FASTORE:
case IASTORE:
case LASTORE:
case SASTORE:
pop(3);
break;
case BIPUSH:
case SIPUSH:
push(new Item("I", (Integer)dbc.getIntConstant()));
break;
case IADD:
case ISUB:
case IMUL:
case IDIV:
case IAND:
case IOR:
case IXOR:
case ISHL:
case ISHR:
case IREM:
case IUSHR:
it = pop();
it2 = pop();
pushByIntMath(seen, it2, it);
break;
case INEG:
it = pop();
if (it.getConstant() instanceof Integer) {
push(new Item("I", ( Integer)(-(Integer) it.getConstant())));
} else {
push(new Item("I"));
}
break;
case LNEG:
it = pop();
if (it.getConstant() instanceof Long) {
push(new Item("J", ( Long)(-(Long) it.getConstant())));
} else {
push(new Item("J"));
}
break;
case FNEG:
it = pop();
if (it.getConstant() instanceof Float) {
push(new Item("F", ( Float)(-(Float) it.getConstant())));
} else {
push(new Item("F"));
}
break;
case DNEG:
it = pop();
if (it.getConstant() instanceof Double) {
push(new Item("D", ( Double)(-(Double) it.getConstant())));
} else {
push(new Item("D"));
}
break;
case LADD:
case LSUB:
case LMUL:
case LDIV:
case LAND:
case LOR:
case LXOR:
case LSHL:
case LSHR:
case LREM:
case LUSHR:
it = pop();
it2 = pop();
pushByLongMath(seen, it2, it);
break;
case LCMP:
handleLcmp();
break;
case FCMPG:
case FCMPL: handleFcmp(seen);
break;
case DCMPG:
case DCMPL:
handleDcmp(seen);
break;
case FADD:
case FSUB:
case FMUL:
case FDIV:
case FREM:
it = pop();
it2 = pop();
pushByFloatMath(seen, it, it2);
break;
case DADD:
case DSUB:
case DMUL:
case DDIV:
case DREM:
it = pop();
it2 = pop();
pushByDoubleMath(seen, it, it2);
break;
case I2B:
it = pop();
if (it.getConstant() != null) {
it =new Item("I", (byte)constantToInt(it));
} else {
it = new Item("I");
}
it.setSpecialKind(Item.SIGNED_BYTE);
push(it);
break;
case I2C:
it = pop();
if (it.getConstant() != null) {
it = new Item("I", (char)constantToInt(it));
} else {
it = new Item("I");
}
it.setSpecialKind(Item.MASKED_NON_NEGATIVE);
push(it);
break;
case I2L:
case D2L:
case F2L:{
it = pop();
Item newValue;
if (it.getConstant() != null) {
newValue = new Item("J", constantToLong(it));
} else {
newValue = new Item("J");
}
newValue.setSpecialKind(it.getSpecialKind());
push(newValue);
}
break;
case I2S:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", (short)constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2I:
case D2I:
case F2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I",constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2F:
case D2F:
case I2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", (Float)(constantToFloat(it))));
} else {
push(new Item("F"));
}
break;
case F2D:
case I2D:
case L2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", constantToDouble(it)));
} else {
push(new Item("D"));
}
break;
case NEW:
pushBySignature("L" + dbc.getClassConstantOperand() + ";");
break;
case NEWARRAY:
pop();
signature = "[" + BasicType.getType((byte)dbc.getIntConstant()).getSignature();
pushBySignature(signature);
break;
// According to the VM Spec 4.4.1, anewarray and multianewarray
// can refer to normal class/interface types (encoded in
// "internal form"), or array classes (encoded as signatures
// beginning with "[").
case ANEWARRAY:
pop();
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
signature = "[L" + signature + ";";
}
pushBySignature(signature);
break;
case MULTIANEWARRAY:
int dims = dbc.getIntConstant();
while ((dims
pop();
}
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
dims = dbc.getIntConstant();
signature = "";
while ((dims
signature += "[";
signature += "L" + signature + ";";
}
pushBySignature(signature);
break;
case AALOAD:
pop();
it = pop();
pushBySignature(it.getElementSignature());
break;
case JSR:
push(new Item(""));
break;
case INVOKEINTERFACE:
case INVOKESPECIAL:
case INVOKESTATIC:
case INVOKEVIRTUAL:
processMethodCall(dbc, seen);
break;
default:
throw new UnsupportedOperationException("OpCode " + OPCODE_NAMES[seen] + " not supported " );
}
}
catch (RuntimeException e) {
//If an error occurs, we clear the stack and locals. one of two things will occur.
//Either the client will expect more stack items than really exist, and so they're condition check will fail,
//or the stack will resync with the code. But hopefully not false positives
String msg = "Error procssing opcode " + OPCODE_NAMES[seen] + " @ " + dbc.getPC() + " in " + dbc.getFullyQualifiedMethodName();
AnalysisContext.logError(msg , e);
if (DEBUG)
e.printStackTrace();
clear();
}
finally {
if (exceptionHandlers.get(dbc.getNextPC()))
push(new Item("Ljava/lang/Throwable;"));
if (DEBUG) {
System.out.println(dbc.getNextPC() + "pc : " + OPCODE_NAMES[seen] + " stack depth: " + getStackDepth());
System.out.println(this);
}
}
}
/**
* @param it
* @return
*/
private int constantToInt(Item it) {
return ((Number)it.getConstant()).intValue();
}
/**
* @param it
* @return
*/
private float constantToFloat(Item it) {
return ((Number)it.getConstant()).floatValue();
}
/**
* @param it
* @return
*/
private double constantToDouble(Item it) {
return ((Number)it.getConstant()).doubleValue();
}
/**
* @param it
* @return
*/
private long constantToLong(Item it) {
return ((Number)it.getConstant()).longValue();
}
/**
* @param opcode TODO
*
*/
private void handleDcmp(int opcode) {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
double d = (Double) it.getConstant();
double d2 = (Double) it.getConstant();
if (Double.isNaN(d) || Double.isNaN(d2)) {
if (opcode == DCMPG)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(-1)));
}
if (d2 < d)
push(new Item("I", (Integer) (-1) ));
else if (d2 > d)
push(new Item("I", (Integer)1));
else
push(new Item("I", (Integer)0));
} else {
push(new Item("I"));
}
}
/**
* @param opcode TODO
*
*/
private void handleFcmp(int opcode) {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
float f = (Float) it.getConstant();
float f2 = (Float) it.getConstant();
if (Float.isNaN(f) || Float.isNaN(f2)) {
if (opcode == FCMPG)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(-1)));
}
if (f2 < f)
push(new Item("I", (Integer)(-1)));
else if (f2 > f)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(0)));
} else {
push(new Item("I"));
}
}
private void handleLcmp() {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
long l = (Long) it.getConstant();
long l2 = (Long) it.getConstant();
if (l2 < l)
push(new Item("I", (Integer)(-1)));
else if (l2 > l)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(0)));
} else {
push(new Item("I"));
}
}
private void handleSwap() {
Item i1 = pop();
Item i2 = pop();
push(i1);
push(i2);
}
private void handleDup() {
Item it;
it = pop();
push(it);
push(it);
}
private void handleDupX1() {
Item it;
Item it2;
it = pop();
it2 = pop();
push(it);
push(it2);
push(it);
}
private void handleDup2() {
Item it, it2;
it = pop();
if (it.getSize() == 2) {
push(it);
push(it);
}
else {
it2 = pop();
push(it2);
push(it);
push(it2);
push(it);
}
}
private void handleDup2X1() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it2);
push(it);
push(it3);
push(it2);
push(it);
}
}
private void handleDup2X2() {
String signature;
Item it = pop();
Item it2 = pop();
if (it.isWide()) {
if (it2.isWide()) {
push(it);
push(it2);
push(it);
} else {
Item it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
} else {
Item it3 = pop();
if (it3.isWide()) {
push(it2);
push(it);
push(it3);
push(it2);
push(it);
} else {
Item it4 = pop();
push(it2);
push(it);
push(it4);
push(it3);
push(it2);
push(it);
}
}
}
private void handleDupX2() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it2.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
}
private void processMethodCall(DismantleBytecode dbc, int seen) {
String clsName = dbc.getClassConstantOperand();
String methodName = dbc.getNameConstantOperand();
String signature = dbc.getSigConstantOperand();
String appenderValue = null;
Item sbItem = null;
//TODO: stack merging for trinaries kills the constant.. would be nice to maintain.
if ("java/lang/StringBuffer".equals(clsName)
|| "java/lang/StringBuilder".equals(clsName)) {
if ("<init>".equals(methodName)) {
if ("(Ljava/lang/String;)V".equals(signature)) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("()V".equals(signature)) {
appenderValue = "";
}
} else if ("toString".equals(methodName) && getStackDepth() >= 1) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("append".equals(methodName) && signature.indexOf("II)") == -1 && getStackDepth() >= 2) {
sbItem = getStackItem(1);
Item i = getStackItem(0);
Object sbVal = sbItem.getConstant();
Object sVal = i.getConstant();
if ((sbVal != null) && (sVal != null)) {
appenderValue = sbVal + sVal.toString();
} else if (sbItem.registerNumber >= 0) {
OpcodeStack.Item item = getLVValue(sbItem.registerNumber);
if (item != null)
item.constValue = null;
}
}
}
pushByInvoke(dbc, seen != INVOKESTATIC);
if (appenderValue != null && getStackDepth() > 0) {
Item i = this.getStackItem(0);
i.constValue = appenderValue;
if (sbItem != null) {
i.registerNumber = sbItem.registerNumber;
i.source = sbItem.source;
i.userValue = sbItem.userValue;
if (sbItem.registerNumber >= 0)
setLVValue(sbItem.registerNumber, i );
}
return;
}
if ((clsName.equals("java/util/Random") || clsName.equals("java/security/SecureRandom")) && methodName.equals("nextInt") && signature.equals("()I")) {
Item i = pop();
i.setSpecialKind(Item.RANDOM_INT);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
if (clsName.equals("java/lang/Math") && methodName.equals("abs")) {
Item i = pop();
i.setSpecialKind(Item.MATH_ABS);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
else if (seen == INVOKEVIRTUAL && methodName.equals("hashCode") && signature.equals("()I")
|| seen == INVOKESTATIC && clsName.equals("java/lang/System") && methodName.equals("identityHashCode") && signature.equals("(Ljava/lang/Object;)I")) {
Item i = pop();
i.setSpecialKind(Item.HASHCODE_INT);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
} else if (!signature.endsWith(")V")) {
Item i = pop();
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
}
private void mergeLists(List<Item> mergeInto, List<Item> mergeFrom, boolean errorIfSizesDoNotMatch) {
// merge stacks
int intoSize = mergeInto.size();
int fromSize = mergeFrom.size();
if (errorIfSizesDoNotMatch && intoSize != fromSize) {
if (DEBUG2) {
System.out.println("Bad merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
} else {
if (DEBUG2) {
if (intoSize == fromSize)
System.out.println("Merging items");
else
System.out.println("Bad merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
for (int i = 0; i < Math.min(intoSize, fromSize); i++)
mergeInto.set(i, Item.merge(mergeInto.get(i), mergeFrom.get(i)));
if (DEBUG2) {
System.out.println("merged items: " + mergeInto);
}
}
}
public void clear() {
stack.clear();
lvValues.clear();
}
BitSet exceptionHandlers = new BitSet();
private Map<Integer, List<Item>> jumpEntries = new HashMap<Integer, List<Item>>();
private Map<Integer, List<Item>> jumpStackEntries = new HashMap<Integer, List<Item>>();
private BitSet jumpEntryLocations = new BitSet();
private void addJumpValue(int target) {
if (DEBUG)
System.out.println("Set jump entry at " + methodName + ":" + target + "pc to " + stack + " : " + lvValues );
List<Item> atTarget = jumpEntries.get(target);
if (atTarget == null) {
if (DEBUG)
System.out.println("Was null");
jumpEntries.put(target, new ArrayList<Item>(lvValues));
jumpEntryLocations.set(target);
if (stack.size() > 0) {
jumpStackEntries.put(target, new ArrayList<Item>(stack));
}
return;
}
mergeLists(atTarget, lvValues, false);
List<Item> stackAtTarget = jumpStackEntries.get(target);
if (stack.size() > 0 && stackAtTarget != null)
mergeLists(stackAtTarget, stack, false);
if (DEBUG)
System.out.println("merge target for " + methodName + ":" + target + "pc is " + atTarget);
}
private String methodName;
DismantleBytecode v;
public int resetForMethodEntry(final DismantleBytecode v) {
this.v = v;
methodName = v.getMethodName();
setTop(false);
jumpEntries.clear();
jumpStackEntries.clear();
jumpEntryLocations.clear();
lastUpdate.clear();
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
reachOnlyByBranch = false;
int result= resetForMethodEntry0(v);
Code code = v.getMethod().getCode();
if (code == null) return result;
if (useIterativeAnalysis) {
// FIXME: Be clever
if (DEBUG)
System.out.println(" --- Iterative analysis");
DismantleBytecode branchAnalysis = new DismantleBytecode() {
@Override
public void sawOpcode(int seen) {
OpcodeStack.this.sawOpcode(this, seen);
}
// perhaps we don't need this
// @Override
// public void sawBranchTo(int pc) {
// addJumpValue(pc);
};
branchAnalysis.setupVisitorForClass(v.getThisClass());
branchAnalysis.doVisitMethod(v.getMethod());
if (!jumpEntries.isEmpty()) {
resetForMethodEntry0(v);
if (DEBUG) {
System.out.println("Found dataflow for jumps in " + v.getMethodName());
for (Integer pc : jumpEntries.keySet()) {
List<Item> list = jumpEntries.get(pc);
System.out.println(pc + " -> " + Integer.toString(System.identityHashCode(list),16) + " " + list);
}
}
branchAnalysis.doVisitMethod(v.getMethod());
}
if (DEBUG && !jumpEntries.isEmpty()) {
System.out.println("Found dataflow for jumps in " + v.getMethodName());
for (Integer pc : jumpEntries.keySet()) {
List<Item> list = jumpEntries.get(pc);
System.out.println(pc + " -> " + Integer.toString(System.identityHashCode(list),16) + " " + list);
}
}
resetForMethodEntry0(v);
if (DEBUG)
System.out.println(" --- End of Iterative analysis");
}
return result;
}
private int resetForMethodEntry0(PreorderVisitor v) {
if (DEBUG) System.out.println("
stack.clear();
lvValues.clear();
top = false;
reachOnlyByBranch = false;
seenTransferOfControl = false;
String className = v.getClassName();
String signature = v.getMethodSig();
exceptionHandlers.clear();
Method m = v.getMethod();
Code code = m.getCode();
if (code != null)
{
CodeException[] exceptionTable = code.getExceptionTable();
if (exceptionTable != null)
for(CodeException ex : exceptionTable)
exceptionHandlers.set(ex.getHandlerPC());
}
if (DEBUG) System.out.println(" --- " + className
+ " " + m.getName() + " " + signature);
Type[] argTypes = Type.getArgumentTypes(signature);
int reg = 0;
if (!m.isStatic()) {
Item it = new Item("L" + className+";");
it.setInitialParameter(true);
it.registerNumber = reg;
setLVValue( reg, it);
reg += it.getSize();
}
for (Type argType : argTypes) {
Item it = new Item(argType.getSignature());
it.registerNumber = reg;
it.setInitialParameter(true);
setLVValue(reg, it);
reg += it.getSize();
}
return reg;
}
public int getStackDepth() {
return stack.size();
}
public Item getStackItem(int stackOffset) {
if (stackOffset < 0 || stackOffset >= stack.size()) {
AnalysisContext.logError("Can't get stack offset " + stackOffset
+ " from " + stack.toString() +" in "
+ v.getFullyQualifiedMethodName(), new IllegalArgumentException());
return new Item("Lfindbugs/OpcodeStackError;");
}
int tos = stack.size() - 1;
int pos = tos - stackOffset;
try {
return stack.get(pos);
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException(
"Requested item at offset " + stackOffset + " in a stack of size " + stack.size()
+", made request for position " + pos);
}
}
private Item pop() {
return stack.remove(stack.size()-1);
}
private void pop(int count)
{
while ((count
pop();
}
private void push(Item i) {
stack.add(i);
}
private void pushByConstant(DismantleBytecode dbc, Constant c) {
if (c instanceof ConstantClass)
push(new Item("Ljava/lang/Class;", ((ConstantClass)c).getConstantValue(dbc.getConstantPool())));
else if (c instanceof ConstantInteger)
push(new Item("I", (Integer)(((ConstantInteger) c).getBytes())));
else if (c instanceof ConstantString) {
int s = ((ConstantString) c).getStringIndex();
push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s)));
}
else if (c instanceof ConstantFloat)
push(new Item("F", (Float)(((ConstantFloat) c).getBytes())));
else if (c instanceof ConstantDouble)
push(new Item("D", (Double)(((ConstantDouble) c).getBytes())));
else if (c instanceof ConstantLong)
push(new Item("J", (Long)(((ConstantLong) c).getBytes())));
else
throw new UnsupportedOperationException("Constant type not expected" );
}
private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) {
Method m = dbc.getMethod();
LocalVariableTable lvt = m.getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC());
if (lv != null) {
String signature = lv.getSignature();
pushByLocalLoad(signature, register);
return;
}
}
pushByLocalLoad("", register);
}
private void pushByIntMath(int seen, Item lhs, Item rhs) {
if (DEBUG) System.out.println("pushByIntMath: " + rhs.getConstant() + " " + lhs.getConstant() );
Item newValue = new Item("I");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Integer lhsValue = (Integer) lhs.getConstant();
Integer rhsValue = (Integer) rhs.getConstant();
if (seen == IADD)
newValue = new Item("I",lhsValue + rhsValue);
else if (seen == ISUB)
newValue = new Item("I",lhsValue - rhsValue);
else if (seen == IMUL)
newValue = new Item("I", lhsValue * rhsValue);
else if (seen == IDIV)
newValue = new Item("I", lhsValue / rhsValue);
else if (seen == IAND) {
newValue = new Item("I", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} else if (seen == IOR)
newValue = new Item("I",lhsValue | rhsValue);
else if (seen == IXOR)
newValue = new Item("I",lhsValue ^ rhsValue);
else if (seen == ISHL) {
newValue = new Item("I",lhsValue << rhsValue);
if (rhsValue >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == ISHR)
newValue = new Item("I",lhsValue >> rhsValue);
else if (seen == IREM)
newValue = new Item("I", lhsValue % rhsValue);
else if (seen == IUSHR)
newValue = new Item("I", lhsValue >>> rhsValue);
} else if (rhs.getConstant() != null && seen == ISHL && (Integer) rhs.getConstant() >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == IAND) {
int value = (Integer) lhs.getConstant();
if (value == 0)
newValue = new Item("I", 0);
else if ((value & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (value >= 0)
newValue.specialKind = Item.MASKED_NON_NEGATIVE;
} else if (rhs.getConstant() != null && seen == IAND) {
int value = (Integer) rhs.getConstant();
if (value == 0)
newValue = new Item("I", 0);
else if ((value & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (value >= 0)
newValue.specialKind = Item.MASKED_NON_NEGATIVE;
}
} catch (RuntimeException e) {
// ignore it
}
if (lhs.specialKind == Item.INTEGER_SUM && rhs.getConstant() != null ) {
int rhsValue = (Integer) rhs.getConstant();
if (seen == IDIV && rhsValue ==2 || seen == ISHR && rhsValue == 1)
newValue.specialKind = Item.AVERAGE_COMPUTED_USING_DIVISION;
}
if (seen == IADD && newValue.specialKind == 0 && lhs.getConstant() == null && rhs.getConstant() == null )
newValue.specialKind = Item.INTEGER_SUM;
if (seen == IREM && lhs.specialKind == Item.HASHCODE_INT)
newValue.specialKind = Item.HASHCODE_INT_REMAINDER;
if (seen == IREM && lhs.specialKind == Item.RANDOM_INT)
newValue.specialKind = Item.RANDOM_INT_REMAINDER;
if (DEBUG) System.out.println("push: " + newValue);
push(newValue);
}
private void pushByLongMath(int seen, Item lhs, Item rhs) {
Item newValue = new Item("J");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Long lhsValue = ((Long) lhs.getConstant());
if (seen == LSHL) {
newValue =new Item("J", lhsValue << ((Number) rhs.getConstant()).intValue());
if (((Number) rhs.getConstant()).intValue() >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LSHR)
newValue =new Item("J", lhsValue >> ((Number) rhs.getConstant()).intValue());
else if (seen == LUSHR)
newValue =new Item("J", lhsValue >>> ((Number) rhs.getConstant()).intValue());
else {
Long rhsValue = ((Long) rhs.getConstant());
if (seen == LADD)
newValue = new Item("J", lhsValue + rhsValue);
else if (seen == LSUB)
newValue = new Item("J", lhsValue - rhsValue);
else if (seen == LMUL)
newValue = new Item("J", lhsValue * rhsValue);
else if (seen == LDIV)
newValue =new Item("J", lhsValue / rhsValue);
else if (seen == LAND) {
newValue = new Item("J", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LOR)
newValue = new Item("J", lhsValue | rhsValue);
else if (seen == LXOR)
newValue =new Item("J", lhsValue ^ rhsValue);
else if (seen == LREM)
newValue =new Item("J", lhsValue % rhsValue);
}
}
else if (rhs.getConstant() != null && seen == LSHL && ((Integer) rhs.getConstant()) >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == LAND && (((Long) lhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (rhs.getConstant() != null && seen == LAND && (((Long) rhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} catch (RuntimeException e) {
// ignore it
}
push(newValue);
}
private void pushByFloatMath(int seen, Item it, Item it2) {
Item result;
int specialKind = Item.FLOAT_MATH;
if ((it.getConstant() instanceof Float) && it2.getConstant() instanceof Float) {
if (seen == FADD)
result =new Item("F", ((Float) it2.getConstant()) + ((Float) it.getConstant()));
else if (seen == FSUB)
result =new Item("F", ((Float) it2.getConstant()) - ((Float) it.getConstant()));
else if (seen == FMUL)
result =new Item("F", ((Float) it2.getConstant()) * ((Float) it.getConstant()));
else if (seen == FDIV)
result =new Item("F", ((Float) it2.getConstant()) / ((Float) it.getConstant()));
else if (seen == FREM)
result =new Item("F", ((Float) it2.getConstant()) % ((Float) it.getConstant()));
else result =new Item("F");
} else {
result =new Item("F");
if (seen == DDIV)
specialKind = Item.NASTY_FLOAT_MATH;
}
result.setSpecialKind(specialKind);
push(result);
}
private void pushByDoubleMath(int seen, Item it, Item it2) {
Item result;
int specialKind = Item.FLOAT_MATH;
if ((it.getConstant() instanceof Double) && it2.getConstant() instanceof Double) {
if (seen == DADD)
result = new Item("D", ((Double) it2.getConstant()) + ((Double) it.getConstant()));
else if (seen == DSUB)
result = new Item("D", ((Double) it2.getConstant()) - ((Double) it.getConstant()));
else if (seen == DMUL)
result = new Item("D", ((Double) it2.getConstant()) * ((Double) it.getConstant()));
else if (seen == DDIV)
result = new Item("D", ((Double) it2.getConstant()) / ((Double) it.getConstant()));
else if (seen == DREM)
result = new Item("D", ((Double) it2.getConstant()) % ((Double) it.getConstant()));
else
result = new Item("D");
} else {
result = new Item("D");
if (seen == DDIV)
specialKind = Item.NASTY_FLOAT_MATH;
}
result.setSpecialKind(specialKind);
push(result);
}
private void pushByInvoke(DismantleBytecode dbc, boolean popThis) {
String signature = dbc.getSigConstantOperand();
pop(PreorderVisitor.getNumberArguments(signature)+(popThis ? 1 : 0));
pushBySignature(Type.getReturnType(signature).getSignature());
}
private String getStringFromIndex(DismantleBytecode dbc, int i) {
ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i);
return name.getBytes();
}
private void pushBySignature(String s) {
if ("V".equals(s))
return;
push(new Item(s, (Object) null));
}
private void pushByLocalStore(int register) {
Item it = pop();
if (it.getRegisterNumber() != register) {
for(Item i : lvValues) if (i != null) {
if (i.registerNumber == register) i.registerNumber = -1;
if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1;
}
for(Item i : stack) if (i != null) {
if (i.registerNumber == register) i.registerNumber = -1;
if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1;
}
}
setLVValue( register, it );
}
private void pushByLocalLoad(String signature, int register) {
Item it = getLVValue(register);
if (it == null) {
Item item = new Item(signature);
item.registerNumber = register;
push(item);
}
else if (it.getRegisterNumber() >= 0)
push(it);
else {
push(new Item(it, register));
}
}
private void setLVValue(int index, Item value ) {
int addCount = index - lvValues.size() + 1;
while ((addCount
lvValues.add(null);
if (!useIterativeAnalysis && seenTransferOfControl)
value = Item.merge(value, lvValues.get(index) );
lvValues.set(index, value);
}
private Item getLVValue(int index) {
if (index >= lvValues.size())
return null;
return lvValues.get(index);
}
/**
* @param top The top to set.
*/
private void setTop(boolean top) {
if (top) {
if (!this.top)
this.top = true;
} else if (this.top)
this.top = false;
}
/**
* @return Returns the top.
*/
private boolean isTop() {
if (top)
return true;
return false;
}
}
// vim:ts=4 |
package com.ecyrd.jspwiki.util;
import java.util.Date;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.WikiEngine;
public final class MailUtil
{
private static final String JAVA_COMP_ENV = "java:comp/env";
private static final String FALSE = "false";
private static final String TRUE = "true";
private static boolean useJndi = false;
public static final String PROP_MAIL_AUTH = "mail.smtp.auth";
protected static final Logger log = Logger.getLogger(MailUtil.class);
protected static final String DEFAULT_MAIL_JNDI_NAME = "mail/Session";
protected static final String DEFAULT_MAIL_HOST = "localhost";
protected static final String DEFAULT_MAIL_PORT = "25";
protected static final String DEFAULT_MAIL_TIMEOUT = "5000";
protected static final String PROP_MAIL_JNDI_NAME = "jspwiki.mail.jndiname";
protected static final String PROP_MAIL_HOST = "mail.smtp.host";
protected static final String PROP_MAIL_PORT = "mail.smtp.port";
protected static final String PROP_MAIL_ACCOUNT = "mail.smtp.account";
protected static final String PROP_MAIL_PASSWORD = "mail.smtp.password";
protected static final String PROP_MAIL_TIMEOUT = "mail.smtp.timeout";
protected static final String PROP_MAIL_CONNECTION_TIMEOUT = "mail.smtp.connectiontimeout";
protected static final String PROP_MAIL_TRANSPORT = "smtp";
protected static final String PROP_MAIL_SENDER = "mail.from";
protected static final String PROP_MAIL_STARTTLS = "mail.smtp.starttls.enable";
/**
* Private constructor prevents instantiation.
*/
private MailUtil()
{
}
public static void sendMessage( WikiEngine engine, String to, String subject, String content )
throws AddressException, MessagingException
{
String from = engine.getWikiProperties().getProperty( PROP_MAIL_SENDER ).trim();
sendMessage( engine, to, from, subject, content );
}
public static void sendMessage(WikiEngine engine, String to, String from, String subject, String content)
throws MessagingException
{
Properties props = engine.getWikiProperties();
String jndiName = props.getProperty( PROP_MAIL_JNDI_NAME, DEFAULT_MAIL_JNDI_NAME ).trim();
Session session = null;
if (useJndi)
{
// Try getting the Session from the JNDI factory first
try
{
session = getJNDIMailSession(jndiName);
useJndi = true;
}
catch (NamingException e)
{
// Oops! JNDI factory must not be set up
}
}
// JNDI failed; so, get the Session from the standalone factory
if ( session == null )
{
session = getStandaloneMailSession( props );
}
try
{
// Create and address the message
MimeMessage msg = new MimeMessage( session );
msg.setFrom( new InternetAddress( from ) );
msg.setRecipients( Message.RecipientType.TO, InternetAddress.parse( to, false ) );
msg.setSubject( subject );
msg.setText( content, "UTF-8" );
msg.setSentDate( new Date() );
// Send and log it
Transport.send( msg );
if ( log.isInfoEnabled() )
{
log.info( "Sent e-mail to=" + to + ", subject=\"" + subject
+ "\", jndi=" + ( useJndi ? TRUE : FALSE ) );
}
}
catch ( MessagingException e )
{
log.error( e );
throw e;
}
}
/**
* Returns a stand-alone JavaMail Session by looking up the correct
* mail account, password and host from a supplied set of properties.
* If the JavaMail property {@value #PROP_MAIL_ACCOUNT} is set to
* a value that is non-<code>null</code> and of non-zero length, the
* Session will be initialized with an instance of
* {@link javax.mail.Authenticator}.
* @param props the properties that contain mail session properties
* @return the initialized JavaMail Session
*/
protected static Session getStandaloneMailSession( Properties props )
{
// Read the JSPWiki settings from the properties
String host = props.getProperty( PROP_MAIL_HOST, DEFAULT_MAIL_HOST );
String port = props.getProperty( PROP_MAIL_PORT, DEFAULT_MAIL_PORT );
String account = props.getProperty( PROP_MAIL_ACCOUNT );
String password = props.getProperty( PROP_MAIL_PASSWORD );
boolean starttls = TextUtil.getBooleanProperty( props, PROP_MAIL_STARTTLS, true);
boolean useAuthentication = account != null && account.length() > 0;
Properties mailProps = new Properties();
// Set JavaMail properties
mailProps.put( PROP_MAIL_HOST, host );
mailProps.put( PROP_MAIL_PORT, port );
mailProps.put( PROP_MAIL_TIMEOUT, DEFAULT_MAIL_TIMEOUT );
mailProps.put( PROP_MAIL_CONNECTION_TIMEOUT, DEFAULT_MAIL_TIMEOUT );
mailProps.put( PROP_MAIL_STARTTLS, starttls ? TRUE : FALSE );
// Add SMTP authentication if required
Session session = null;
if ( useAuthentication )
{
mailProps.put( PROP_MAIL_AUTH, TRUE );
SmtpAuthenticator auth = new SmtpAuthenticator( account, password );
session = Session.getInstance( mailProps, auth );
}
else
{
session = Session.getInstance( mailProps );
}
if ( log.isDebugEnabled() )
{
String mailServer = host + ":" + port + ", auth=" + ( useAuthentication ? TRUE : FALSE );
log.debug( "JavaMail session obtained from standalone mail factory: " + mailServer );
}
return session;
}
/**
* Returns a JavaMail Session instance from a JNDI container-managed factory.
* @param jndiName the JNDI name for the resource. If <code>null</code>, the default value
* of <code>mail/Session</code> will be used
* @return the initialized JavaMail Session
* @throws NamingException if the Session cannot be obtained; for example, if the factory is not configured
*/
protected static Session getJNDIMailSession( String jndiName ) throws NamingException
{
Session session = null;
try
{
Context initCtx = new InitialContext();
Context ctx = (Context) initCtx.lookup( JAVA_COMP_ENV );
session = (Session) ctx.lookup( jndiName );
}
catch( NamingException e )
{
log.warn( "JavaMail initialization error: " + e.getMessage() );
throw e;
}
if ( log.isDebugEnabled() )
{
log.debug( "JavaMail session obtained from JNDI mail factory: " + jndiName );
}
return session;
}
/**
* Simple {@link javax.mail.Authenticator} subclass that authenticates a user to
* an SMTP server.
* @author Christoph Sauer
*/
protected static class SmtpAuthenticator extends Authenticator
{
private static final String BLANK = "";
private final String m_pass;
private final String m_login;
/**
* Constructs a new SmtpAuthenticator with a supplied username and password.
* @param login the user name
* @param pass the password
*/
public SmtpAuthenticator(String login, String pass)
{
super();
m_login = login == null ? BLANK : login;
m_pass = pass == null ? BLANK : pass;
}
/**
* Returns the password used to authenticate to the SMTP server.
*/
public PasswordAuthentication getPasswordAuthentication()
{
if ( BLANK.equals(m_pass) )
{
return null;
}
return new PasswordAuthentication( m_login, m_pass );
}
}
} |
package lucee.runtime.listener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.TimeZone;
import org.osgi.framework.Version;
import lucee.commons.io.SystemUtil;
import lucee.commons.io.log.Log;
import lucee.commons.io.res.Resource;
import lucee.commons.io.res.type.ftp.FTPConnectionData;
import lucee.commons.io.res.util.ResourceUtil;
import lucee.commons.lang.ExceptionUtil;
import lucee.commons.lang.StringUtil;
import lucee.runtime.Mapping;
import lucee.runtime.MappingImpl;
import lucee.runtime.Page;
import lucee.runtime.PageContext;
import lucee.runtime.PageContextImpl;
import lucee.runtime.PageSource;
import lucee.runtime.config.Config;
import lucee.runtime.config.ConfigPro;
import lucee.runtime.config.ConfigWeb;
import lucee.runtime.config.ConfigWebPro;
import lucee.runtime.config.ConfigWebUtil;
import lucee.runtime.db.ApplicationDataSource;
import lucee.runtime.db.ClassDefinition;
import lucee.runtime.db.DBUtil;
import lucee.runtime.db.DBUtil.DataSourceDefintion;
import lucee.runtime.db.DataSource;
import lucee.runtime.db.DataSourceImpl;
import lucee.runtime.db.ParamSyntax;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.ApplicationException;
import lucee.runtime.exp.PageException;
import lucee.runtime.net.mail.Server;
import lucee.runtime.net.mail.ServerImpl;
import lucee.runtime.net.s3.Properties;
import lucee.runtime.net.s3.PropertiesImpl;
import lucee.runtime.op.Caster;
import lucee.runtime.op.Decision;
import lucee.runtime.orm.ORMConfigurationImpl;
import lucee.runtime.osgi.OSGiUtil;
import lucee.runtime.tag.Query;
import lucee.runtime.tag.listener.TagListener;
import lucee.runtime.type.Array;
import lucee.runtime.type.ArrayImpl;
import lucee.runtime.type.Collection;
import lucee.runtime.type.Collection.Key;
import lucee.runtime.type.KeyImpl;
import lucee.runtime.type.Struct;
import lucee.runtime.type.StructImpl;
import lucee.runtime.type.dt.TimeSpan;
import lucee.runtime.type.dt.TimeSpanImpl;
import lucee.runtime.type.scope.CookieImpl;
import lucee.runtime.type.scope.Scope;
import lucee.runtime.type.scope.Undefined;
import lucee.runtime.type.util.CollectionUtil;
import lucee.runtime.type.util.KeyConstants;
import lucee.runtime.type.util.ListUtil;
import lucee.transformer.library.ClassDefinitionImpl;
public final class AppListenerUtil {
public static final Collection.Key ACCESS_KEY_ID = KeyImpl.getInstance("accessKeyId");
public static final Collection.Key AWS_SECRET_KEY = KeyImpl.getInstance("awsSecretKey");
public static final Collection.Key SECRET_KEY = KeyImpl.getInstance("secretKey");
public static final Collection.Key DEFAULT_LOCATION = KeyImpl.getInstance("defaultLocation");
public static final Collection.Key ACL = KeyConstants._acl;
public static final Collection.Key CONNECTION_STRING = KeyConstants._connectionString;
public static final Collection.Key BLOB = KeyImpl.getInstance("blob");
public static final Collection.Key CLOB = KeyImpl.getInstance("clob");
public static final Collection.Key CONNECTION_LIMIT = KeyImpl.getInstance("connectionLimit");
public static final Collection.Key CONNECTION_TIMEOUT = KeyImpl.getInstance("connectionTimeout");
public static final Collection.Key IDLE_TIMEOUT = KeyImpl.getInstance("idleTimeout");
public static final Collection.Key LIVE_TIMEOUT = KeyImpl.getInstance("liveTimeout");
public static final Collection.Key META_CACHE_TIMEOUT = KeyImpl.getInstance("metaCacheTimeout");
public static final Collection.Key ALLOW = KeyImpl.getInstance("allow");
public static final Collection.Key DISABLE_UPDATE = KeyImpl.getInstance("disableUpdate");
private static final TimeSpan FIVE_MINUTES = new TimeSpanImpl(0, 0, 5, 0);
private static final TimeSpan ONE_MINUTE = new TimeSpanImpl(0, 0, 1, 0);
public static Page getApplicationPage(PageContext pc, PageSource requestedPage, String filename, int mode, int type) throws PageException {
Resource res = requestedPage.getPhyscalFile();
if (res != null) {
PageSource ps = ((ConfigPro) pc.getConfig()).getApplicationPageSource(pc, res.getParent(), filename, mode, null);
if (ps != null) {
Page p = ps.loadPage(pc, false, null);
if (p != null) return p;
}
}
Page p;
if (mode == ApplicationListener.MODE_CURRENT) p = getApplicationPageCurrent(pc, requestedPage, filename);
else if (mode == ApplicationListener.MODE_ROOT) p = getApplicationPageRoot(pc, filename);
else p = getApplicationPageCurr2Root(pc, requestedPage, filename);
if (res != null && p != null)
((ConfigPro) pc.getConfig()).putApplicationPageSource(requestedPage.getPhyscalFile().getParent(), p.getPageSource(), filename, mode, isCFC(type));
return p;
}
private static boolean isCFC(int type) {
if (type == ApplicationListener.TYPE_CLASSIC) return false;
return true;
}
public static Page getApplicationPageCurrent(PageContext pc, PageSource requestedPage, String filename) throws PageException {
PageSource ps = requestedPage.getRealPage(filename);
return ps.loadPage(pc, false, null);
}
public static Page getApplicationPageRoot(PageContext pc, String filename) throws PageException {
PageSource ps = ((PageContextImpl) pc).getPageSource("/".concat(filename));
return ps.loadPage(pc, false, null);
}
public static Page getApplicationPageCurr2Root(PageContext pc, PageSource requestedPage, String filename) throws PageException {
PageSource ps = requestedPage.getRealPage(filename);
Page p = ps.loadPage(pc, false, null);
if (p != null) return p;
Array arr = lucee.runtime.type.util.ListUtil.listToArrayRemoveEmpty(requestedPage.getRealpathWithVirtual(), "/");
// Config config = pc.getConfig();
for (int i = arr.size() - 1; i > 0; i
StringBuilder sb = new StringBuilder("/");
for (int y = 1; y < i; y++) {
sb.append((String) arr.get(y, ""));
sb.append('/');
}
sb.append(filename);
ps = ((PageContextImpl) pc).getPageSource(sb.toString());
p = ps.loadPage(pc, false, null);
if (p != null) return p;
}
return null;
}
public static String toStringMode(int mode) {
if (mode == ApplicationListener.MODE_CURRENT) return "curr";
if (mode == ApplicationListener.MODE_ROOT) return "root";
if (mode == ApplicationListener.MODE_CURRENT2ROOT) return "curr2root";
if (mode == ApplicationListener.MODE_CURRENT_OR_ROOT) return "currorroot";
return "curr2root";
}
public static String toStringType(ApplicationListener listener) {
if (listener instanceof NoneAppListener) return "none";
else if (listener instanceof MixedAppListener) return "mixed";
else if (listener instanceof ClassicAppListener) return "classic";
else if (listener instanceof ModernAppListener) return "modern";
return "";
}
public static DataSource[] toDataSources(Config config, Object o, DataSource[] defaultValue, Log log) {
try {
return toDataSources(config, o, log);
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
return defaultValue;
}
}
public static DataSource[] toDataSources(Config config, Object o, Log log) throws PageException {
Struct sct = Caster.toStruct(o);
Iterator<Entry<Key, Object>> it = sct.entryIterator();
Entry<Key, Object> e;
java.util.List<DataSource> dataSources = new ArrayList<DataSource>();
while (it.hasNext()) {
e = it.next();
dataSources.add(toDataSource(config, e.getKey().getString().trim(), Caster.toStruct(e.getValue()), log));
}
return dataSources.toArray(new DataSource[dataSources.size()]);
}
public static DataSource toDataSource(Config config, String name, Struct data, Log log) throws PageException {
String user = Caster.toString(data.get(KeyConstants._username, null), null);
String pass = Caster.toString(data.get(KeyConstants._password, ""), "");
if (StringUtil.isEmpty(user)) {
user = null;
pass = null;
}
else {
user = translateValue(user);
pass = translateValue(pass);
}
// listener
TagListener listener = null;
{
Object o = data.get(KeyConstants._listener, null);
if (o != null) listener = Query.toTagListener(o, null);
}
TimeZone timezone = null;
Object obj = data.get(KeyConstants._timezone, null);
if (obj != null) timezone = Caster.toTimeZone(obj, null);
// first check for {class:... , connectionString:...}
Object oConnStr = data.get(CONNECTION_STRING, null);
if (oConnStr != null) {
String className = Caster.toString(data.get(KeyConstants._class));
if ("com.microsoft.jdbc.sqlserver.SQLServerDriver".equals(className)) {
className = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
}
ClassDefinition cd = new ClassDefinitionImpl(className, Caster.toString(data.get(KeyConstants._bundleName, null), null),
Caster.toString(data.get(KeyConstants._bundleVersion, null), null), ThreadLocalPageContext.getConfig().getIdentification());
try {
int idle = Caster.toIntValue(data.get(IDLE_TIMEOUT, null), -1);
if (idle == -1) idle = Caster.toIntValue(data.get(CONNECTION_TIMEOUT, null), 1);
return ApplicationDataSource.getInstance(config, name, cd, Caster.toString(oConnStr), user, pass, listener, Caster.toBooleanValue(data.get(BLOB, null), false),
Caster.toBooleanValue(data.get(CLOB, null), false), Caster.toIntValue(data.get(CONNECTION_LIMIT, null), -1), idle,
Caster.toIntValue(data.get(LIVE_TIMEOUT, null), 60), Caster.toIntValue(data.get("minIdle", null), 60), Caster.toIntValue(data.get("maxIdle", null), 60),
Caster.toIntValue(data.get("maxTotal", null), 60), Caster.toLongValue(data.get(META_CACHE_TIMEOUT, null), 60000L), timezone,
Caster.toIntValue(data.get(ALLOW, null), DataSource.ALLOW_ALL), Caster.toBooleanValue(data.get(KeyConstants._storage, null), false),
Caster.toBooleanValue(data.get(KeyConstants._readonly, null), false), Caster.toBooleanValue(data.get(KeyConstants._validate, null), false),
Caster.toBooleanValue(data.get("requestExclusive", null), false), Caster.toBooleanValue(data.get("alwaysResetConnections", null), false),
readliteralTimestampWithTSOffset(data), log);
}
catch (Exception cnfe) {
throw Caster.toPageException(cnfe);
}
}
// then for {type:... , host:... , ...}
String type = Caster.toString(data.get(KeyConstants._type));
DataSourceDefintion dbt = DBUtil.getDataSourceDefintionForType(config, type, null);
if (dbt == null) throw new ApplicationException("no datasource type [" + type + "] found");
try {
int idle = Caster.toIntValue(data.get(IDLE_TIMEOUT, null), -1);
if (idle == -1) idle = Caster.toIntValue(data.get(CONNECTION_TIMEOUT, null), 1);
return new DataSourceImpl(config, name, dbt.classDefinition, Caster.toString(data.get(KeyConstants._host)), dbt.connectionString,
Caster.toString(data.get(KeyConstants._database)), Caster.toIntValue(data.get(KeyConstants._port, null), -1), user, pass, listener,
Caster.toIntValue(data.get(CONNECTION_LIMIT, null), -1), idle, Caster.toIntValue(data.get(LIVE_TIMEOUT, null), 1),
Caster.toIntValue(data.get("minIdle", null), 0), Caster.toIntValue(data.get("maxIdle", null), 0), Caster.toIntValue(data.get("maxTotal", null), 0),
Caster.toLongValue(data.get(META_CACHE_TIMEOUT, null), 60000L), Caster.toBooleanValue(data.get(BLOB, null), false),
Caster.toBooleanValue(data.get(CLOB, null), false), DataSource.ALLOW_ALL, Caster.toStruct(data.get(KeyConstants._custom, null), null, false),
Caster.toBooleanValue(data.get(KeyConstants._readonly, null), false), true, Caster.toBooleanValue(data.get(KeyConstants._storage, null), false), timezone, "",
ParamSyntax.toParamSyntax(data, ParamSyntax.DEFAULT), readliteralTimestampWithTSOffset(data), Caster.toBooleanValue(data.get("alwaysSetTimeout", null), false),
Caster.toBooleanValue(data.get("requestExclusive", null), false), Caster.toBooleanValue(data.get("alwaysResetConnections", null), false), log);
}
catch (Exception cnfe) {
throw Caster.toPageException(cnfe);
}
}
private static String translateValue(String str) {
if (str == null) return null;
str = str.trim();
if (str.startsWith("{env:") && str.endsWith("}")) {
String tmp = str.substring(5, str.length() - 1);
return SystemUtil.getSystemPropOrEnvVar(tmp, "");
}
return str;
}
private static boolean readliteralTimestampWithTSOffset(Struct data) {
Boolean literalTimestampWithTSOffset = Caster.toBoolean(data.get("literalTimestampWithTSOffset", null), null);
if (literalTimestampWithTSOffset == null) literalTimestampWithTSOffset = Caster.toBoolean(data.get("timestampWithTSOffset", null), null);
if (literalTimestampWithTSOffset == null) literalTimestampWithTSOffset = Caster.toBoolean(data.get("fulltimestamp", null), null);
return literalTimestampWithTSOffset == null ? false : literalTimestampWithTSOffset;
}
public static Mapping[] toMappings(ConfigWeb cw, Object o, Mapping[] defaultValue, Resource source) {
try {
return toMappings(cw, o, source);
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
return defaultValue;
}
}
public static Mapping[] toMappings(ConfigWeb cw, Object o, Resource source) throws PageException {
Struct sct = Caster.toStruct(o);
Iterator<Entry<Key, Object>> it = sct.entryIterator();
Entry<Key, Object> e;
java.util.List<Mapping> mappings = new ArrayList<Mapping>();
ConfigWebPro config = (ConfigWebPro) cw;
String virtual;
while (it.hasNext()) {
e = it.next();
virtual = translateMappingVirtual(e.getKey().getString());
MappingData md = toMappingData(e.getValue(), source);
mappings.add(config.getApplicationMapping("application", virtual, md.physical, md.archive, md.physicalFirst, false, !md.physicalMatch, !md.archiveMatch));
}
return ConfigWebUtil.sort(mappings.toArray(new Mapping[mappings.size()]));
}
private static MappingData toMappingData(Object value, Resource source) throws PageException {
MappingData md = new MappingData();
if (Decision.isStruct(value)) {
Struct map = Caster.toStruct(value);
// allowRelPath
boolean allowRelPath = Caster.toBooleanValue(map.get("allowRelPath", null), true);
// physical
String physical = Caster.toString(map.get("physical", null), null);
if (!StringUtil.isEmpty(physical, true)) {
translateMappingPhysical(md, physical.trim(), source, allowRelPath, false);
}
// archive
String archive = Caster.toString(map.get("archive", null), null);
if (!StringUtil.isEmpty(archive, true)) {
translateMappingPhysical(md, archive.trim(), source, allowRelPath, true);
}
if (archive == null && physical == null) throw new ApplicationException("you must define archive or/and physical!");
// primary
md.physicalFirst = true;
// primary is only of interest when both values exists
if (archive != null && physical != null) {
String primary = Caster.toString(map.get("primary", null), null);
if (primary != null && primary.trim().equalsIgnoreCase("archive")) md.physicalFirst = false;
}
// only an archive
else if (archive != null) md.physicalFirst = false;
}
// simple value == only a physical path
else {
md.physicalFirst = true;
translateMappingPhysical(md, Caster.toString(value).trim(), source, true, false);
}
return md;
}
private static void translateMappingPhysical(MappingData md, String path, Resource source, boolean allowRelPath, boolean isArchive) {
if (source == null || !allowRelPath) {
if (isArchive) md.archive = path;
else md.physical = path;
return;
}
source = source.getParentResource().getRealResource(path);
if (source.exists()) {
if (isArchive) {
md.archive = source.getAbsolutePath();
md.archiveMatch = true;
}
else {
md.physical = source.getAbsolutePath();
md.physicalMatch = true;
}
return;
}
if (isArchive) md.archive = path;
else md.physical = path;
}
private static String translateMappingVirtual(String virtual) {
virtual = virtual.replace('\\', '/');
if (!StringUtil.startsWith(virtual, '/')) virtual = "/".concat(virtual);
return virtual;
}
public static Mapping[] toCustomTagMappings(ConfigWeb cw, Object o, Resource source) throws PageException {
return toMappings(cw, "custom", o, false, source);
}
public static Mapping[] toCustomTagMappings(ConfigWeb cw, Object o, Resource source, Mapping[] defaultValue) {
try {
return toMappings(cw, "custom", o, false, source);
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
return defaultValue;
}
}
public static Mapping[] toComponentMappings(ConfigWeb cw, Object o, Resource source) throws PageException {
return toMappings(cw, "component", o, true, source);
}
public static Mapping[] toComponentMappings(ConfigWeb cw, Object o, Resource source, Mapping[] defaultValue) {
try {
return toMappings(cw, "component", o, true, source);
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
return defaultValue;
}
}
private static Mapping[] toMappings(ConfigWeb cw, String type, Object o, boolean useStructNames, Resource source) throws PageException {
ConfigWebPro config = (ConfigWebPro) cw;
Array array;
if (o instanceof String) {
array = ListUtil.listToArrayRemoveEmpty(Caster.toString(o), ',');
}
else if (o instanceof Struct) {
Struct sct = (Struct) o;
if (useStructNames) {
Iterator<Entry<Key, Object>> it = sct.entryIterator();
List<Mapping> list = new ArrayList<Mapping>();
Entry<Key, Object> e;
String virtual;
while (it.hasNext()) {
e = it.next();
virtual = e.getKey().getString();
if (virtual.length() == 0) virtual = "/";
if (!virtual.startsWith("/")) virtual = "/" + virtual;
if (!virtual.equals("/") && virtual.endsWith("/")) virtual = virtual.substring(0, virtual.length() - 1);
MappingData md = toMappingData(e.getValue(), source);
list.add(config.getApplicationMapping(type, virtual, md.physical, md.archive, md.physicalFirst, true, !md.physicalMatch, !md.archiveMatch));
}
return list.toArray(new Mapping[list.size()]);
}
array = new ArrayImpl();
Iterator<Object> it = sct.valueIterator();
while (it.hasNext()) {
array.append(it.next());
}
}
else {
array = Caster.toArray(o);
}
MappingImpl[] mappings = new MappingImpl[array.size()];
for (int i = 0; i < mappings.length; i++) {
MappingData md = toMappingData(array.getE(i + 1), source);
mappings[i] = (MappingImpl) config.getApplicationMapping(type, "/" + i, md.physical, md.archive, md.physicalFirst, true, !md.physicalMatch, !md.archiveMatch);
}
return mappings;
}
public static String toLocalMode(int mode, String defaultValue) {
if (Undefined.MODE_LOCAL_OR_ARGUMENTS_ALWAYS == mode) return "modern";
if (Undefined.MODE_LOCAL_OR_ARGUMENTS_ONLY_WHEN_EXISTS == mode) return "classic";
return defaultValue;
}
public static int toLocalMode(Object oMode, int defaultValue) {
if (oMode == null) return defaultValue;
if (Decision.isBoolean(oMode)) {
if (Caster.toBooleanValue(oMode, false)) return Undefined.MODE_LOCAL_OR_ARGUMENTS_ALWAYS;
return Undefined.MODE_LOCAL_OR_ARGUMENTS_ONLY_WHEN_EXISTS;
}
String strMode = Caster.toString(oMode, null);
if ("always".equalsIgnoreCase(strMode) || "modern".equalsIgnoreCase(strMode)) return Undefined.MODE_LOCAL_OR_ARGUMENTS_ALWAYS;
if ("update".equalsIgnoreCase(strMode) || "classic".equalsIgnoreCase(strMode)) return Undefined.MODE_LOCAL_OR_ARGUMENTS_ONLY_WHEN_EXISTS;
return defaultValue;
}
public static int toLocalMode(String strMode) throws ApplicationException {
int lm = toLocalMode(strMode, -1);
if (lm != -1) return lm;
throw new ApplicationException("invalid localMode definition [" + strMode + "] for tag application, valid values are [classic,modern,true,false]");
}
public static String toSessionType(short type, String defaultValue) {
if (type == Config.SESSION_TYPE_APPLICATION) return "cfml";
if (type == Config.SESSION_TYPE_JEE) return "jee";
return defaultValue;
}
public static short toSessionType(String str, short defaultValue) {
if (!StringUtil.isEmpty(str, true)) {
str = str.trim().toLowerCase();
if ("cfml".equals(str)) return Config.SESSION_TYPE_APPLICATION;
if ("j2ee".equals(str)) return Config.SESSION_TYPE_JEE;
if ("cfm".equals(str)) return Config.SESSION_TYPE_APPLICATION;
if ("application".equals(str)) return Config.SESSION_TYPE_APPLICATION;
if ("jee".equals(str)) return Config.SESSION_TYPE_JEE;
if ("j".equals(str)) return Config.SESSION_TYPE_JEE;
if ("c".equals(str)) return Config.SESSION_TYPE_APPLICATION;
}
return defaultValue;
}
public static short toSessionType(String str) throws ApplicationException {
short undefined = (short) -1;
short type = toSessionType(str, undefined);
if (type != undefined) return type;
throw new ApplicationException("invalid sessionType definition [" + str + "] for tag application, valid values are [application,jee]");
}
public static Properties toS3(Struct sct) {
String host = Caster.toString(sct.get(KeyConstants._host, null), null);
if (StringUtil.isEmpty(host)) host = Caster.toString(sct.get(KeyConstants._server, null), null);
String sk = Caster.toString(sct.get(AWS_SECRET_KEY, null), null);
if (StringUtil.isEmpty(sk)) sk = Caster.toString(sct.get(SECRET_KEY, null), null);
return toS3(Caster.toString(sct.get(ACCESS_KEY_ID, null), null), sk, Caster.toString(sct.get(DEFAULT_LOCATION, null), null), host,
Caster.toString(sct.get(ACL, null), null), Caster.toTimespan(sct.get(KeyConstants._cache, null), null));
}
private static Properties toS3(String accessKeyId, String awsSecretKey, String defaultLocation, String host, String acl, TimeSpan cache) {
PropertiesImpl s3 = new PropertiesImpl();
if (!StringUtil.isEmpty(accessKeyId)) s3.setAccessKeyId(accessKeyId);
if (!StringUtil.isEmpty(awsSecretKey)) s3.setSecretAccessKey(awsSecretKey);
if (!StringUtil.isEmpty(defaultLocation)) s3.setDefaultLocation(defaultLocation);
if (!StringUtil.isEmpty(host)) s3.setHost(host);
if (!StringUtil.isEmpty(acl)) s3.setACL(acl);
if (cache != null) s3.setCache(cache.getMillis());
return s3;
}
public static void setORMConfiguration(PageContext pc, ApplicationContext ac, Struct sct) throws PageException {
if (sct == null) sct = new StructImpl();
ConfigPro config = (ConfigPro) pc.getConfig();
PageSource curr = pc.getCurrentTemplatePageSource();
Resource res = curr == null ? null : curr.getResourceTranslated(pc).getParentResource();
ac.setORMConfiguration(ORMConfigurationImpl.load(config, ac, sct, res, config.getORMConfig()));
// datasource
Object o = sct.get(KeyConstants._datasource, null);
if (o != null) {
o = toDefaultDatasource(config, o, ThreadLocalPageContext.getLog(pc, "application"));
if (o != null) ac.setORMDataSource(o);
}
}
/**
* translate int definition of script protect to string definition
*
* @param scriptProtect
* @return
*/
public static String translateScriptProtect(int scriptProtect) {
if (scriptProtect == ApplicationContext.SCRIPT_PROTECT_NONE) return "none";
if (scriptProtect == ApplicationContext.SCRIPT_PROTECT_ALL) return "all";
Array arr = new ArrayImpl();
if ((scriptProtect & ApplicationContext.SCRIPT_PROTECT_CGI) > 0) arr.appendEL("cgi");
if ((scriptProtect & ApplicationContext.SCRIPT_PROTECT_COOKIE) > 0) arr.appendEL("cookie");
if ((scriptProtect & ApplicationContext.SCRIPT_PROTECT_FORM) > 0) arr.appendEL("form");
if ((scriptProtect & ApplicationContext.SCRIPT_PROTECT_URL) > 0) arr.appendEL("url");
try {
return ListUtil.arrayToList(arr, ",");
}
catch (PageException e) {
return "none";
}
}
/**
* translate string definition of script protect to int definition
*
* @param strScriptProtect
* @return
*/
public static int translateScriptProtect(String strScriptProtect) {
strScriptProtect = strScriptProtect.toLowerCase().trim();
if ("none".equals(strScriptProtect)) return ApplicationContext.SCRIPT_PROTECT_NONE;
if ("no".equals(strScriptProtect)) return ApplicationContext.SCRIPT_PROTECT_NONE;
if ("false".equals(strScriptProtect)) return ApplicationContext.SCRIPT_PROTECT_NONE;
if ("all".equals(strScriptProtect)) return ApplicationContext.SCRIPT_PROTECT_ALL;
if ("true".equals(strScriptProtect)) return ApplicationContext.SCRIPT_PROTECT_ALL;
if ("yes".equals(strScriptProtect)) return ApplicationContext.SCRIPT_PROTECT_ALL;
String[] arr = ListUtil.listToStringArray(strScriptProtect, ',');
String item;
int scriptProtect = 0;
for (int i = 0; i < arr.length; i++) {
item = arr[i].trim();
if ("cgi".equals(item) && (scriptProtect & ApplicationContext.SCRIPT_PROTECT_CGI) == 0) scriptProtect += ApplicationContext.SCRIPT_PROTECT_CGI;
else if ("cookie".equals(item) && (scriptProtect & ApplicationContext.SCRIPT_PROTECT_COOKIE) == 0) scriptProtect += ApplicationContext.SCRIPT_PROTECT_COOKIE;
else if ("form".equals(item) && (scriptProtect & ApplicationContext.SCRIPT_PROTECT_FORM) == 0) scriptProtect += ApplicationContext.SCRIPT_PROTECT_FORM;
else if ("url".equals(item) && (scriptProtect & ApplicationContext.SCRIPT_PROTECT_URL) == 0) scriptProtect += ApplicationContext.SCRIPT_PROTECT_URL;
}
return scriptProtect;
}
public static String translateLoginStorage(int loginStorage) {
if (loginStorage == Scope.SCOPE_SESSION) return "session";
return "cookie";
}
public static int translateLoginStorage(String strLoginStorage, int defaultValue) {
strLoginStorage = strLoginStorage.toLowerCase().trim();
if (strLoginStorage.equals("session")) return Scope.SCOPE_SESSION;
if (strLoginStorage.equals("cookie")) return Scope.SCOPE_COOKIE;
return defaultValue;
}
public static int translateLoginStorage(String strLoginStorage) throws ApplicationException {
int ls = translateLoginStorage(strLoginStorage, -1);
if (ls != -1) return ls;
throw new ApplicationException("invalid loginStorage definition [" + strLoginStorage + "], valid values are [session,cookie]");
}
public static Object toDefaultDatasource(Config config, Object o, Log log) throws PageException {
if (Decision.isStruct(o)) {
Struct sct = (Struct) o;
// fix for Jira ticket LUCEE-1931
if (sct.size() == 1) {
Key[] keys = CollectionUtil.keys(sct);
if (keys.length == 1 && keys[0].equalsIgnoreCase(KeyConstants._name)) {
return Caster.toString(sct.get(KeyConstants._name));
}
}
try {
return AppListenerUtil.toDataSource(config, "__default__", sct, log);
}
catch (PageException pe) {
// again try fix for Jira ticket LUCEE-1931
String name = Caster.toString(sct.get(KeyConstants._name, null), null);
if (!StringUtil.isEmpty(name)) return name;
throw pe;
}
catch (Exception e) {
throw Caster.toPageException(e);
}
}
return Caster.toString(o);
}
public static String toWSType(short wstype, String defaultValue) {
if (ApplicationContext.WS_TYPE_AXIS1 == wstype) return "Axis1";
if (ApplicationContext.WS_TYPE_JAX_WS == wstype) return "JAX-WS";
if (ApplicationContext.WS_TYPE_CXF == wstype) return "CXF";
return defaultValue;
}
public static short toWSType(String wstype, short defaultValue) {
if (wstype == null) return defaultValue;
wstype = wstype.trim();
if ("axis".equalsIgnoreCase(wstype) || "axis1".equalsIgnoreCase(wstype)) return ApplicationContext.WS_TYPE_AXIS1;
/*
* if("jax".equalsIgnoreCase(wstype) || "jaxws".equalsIgnoreCase(wstype) ||
* "jax-ws".equalsIgnoreCase(wstype)) return ApplicationContextPro.WS_TYPE_JAX_WS;
* if("cxf".equalsIgnoreCase(wstype)) return ApplicationContextPro.WS_TYPE_CXF;
*/
return defaultValue;
}
public static int toCachedWithinType(String type, int defaultValue) {
if (StringUtil.isEmpty(type, true)) return defaultValue;
type = type.trim().toLowerCase();
if ("function".equalsIgnoreCase(type)) return Config.CACHEDWITHIN_FUNCTION;
if ("udf".equalsIgnoreCase(type)) return Config.CACHEDWITHIN_FUNCTION;
if ("include".equalsIgnoreCase(type)) return Config.CACHEDWITHIN_INCLUDE;
if ("query".equalsIgnoreCase(type)) return Config.CACHEDWITHIN_QUERY;
if ("resource".equalsIgnoreCase(type)) return Config.CACHEDWITHIN_RESOURCE;
if ("http".equalsIgnoreCase(type)) return Config.CACHEDWITHIN_HTTP;
if ("file".equalsIgnoreCase(type)) return Config.CACHEDWITHIN_FILE;
if ("webservice".equalsIgnoreCase(type)) return Config.CACHEDWITHIN_WEBSERVICE;
return defaultValue;
}
public static String toCachedWithinType(int type, String defaultValue) {
if (type == Config.CACHEDWITHIN_FUNCTION) return "function";
if (type == Config.CACHEDWITHIN_INCLUDE) return "include";
if (type == Config.CACHEDWITHIN_QUERY) return "query";
if (type == Config.CACHEDWITHIN_RESOURCE) return "resource";
if (type == Config.CACHEDWITHIN_HTTP) return "http";
if (type == Config.CACHEDWITHIN_FILE) return "file";
if (type == Config.CACHEDWITHIN_WEBSERVICE) return "webservice";
return defaultValue;
}
public static short toWSType(String wstype) throws ApplicationException {
String str = "";
KeyImpl cs = new KeyImpl(str) {
@Override
public String getString() {
return null;
}
};
short wst = toWSType(wstype, (short) -1);
if (wst != -1) return wst;
throw new ApplicationException("invalid webservice type [" + wstype + "], valid values are [axis1]");
// throw new ApplicationException("invalid webservice type ["+wstype+"], valid values are
// [axis1,jax-ws,cxf]");
}
static private class MappingData {
public boolean archiveMatch;
public boolean physicalMatch;
private String physical;
private String archive;
private boolean physicalFirst;
}
public static SessionCookieData toSessionCookie(ConfigWeb config, Struct data) {
if (data == null) return SessionCookieDataImpl.DEFAULT;
return new SessionCookieDataImpl(Caster.toBooleanValue(data.get(KeyConstants._httponly, null), SessionCookieDataImpl.DEFAULT.isHttpOnly()),
Caster.toBooleanValue(data.get(KeyConstants._secure, null), SessionCookieDataImpl.DEFAULT.isSecure()),
toTimespan(data.get(KeyConstants._timeout, null), SessionCookieDataImpl.DEFAULT.getTimeout()),
Caster.toString(data.get(KeyConstants._domain, null), SessionCookieDataImpl.DEFAULT.getDomain()),
Caster.toBooleanValue(data.get(DISABLE_UPDATE, null), SessionCookieDataImpl.DEFAULT.isDisableUpdate()),
SessionCookieDataImpl.toSamesite(Caster.toString(data.get(KeyConstants._SameSite, null), null), SessionCookieDataImpl.DEFAULT.getSamesite()),
Caster.toString(data.get(KeyConstants._path, null), SessionCookieDataImpl.DEFAULT.getPath())
);
}
public static AuthCookieData toAuthCookie(ConfigWeb config, Struct data) {
if (data == null) return AuthCookieDataImpl.DEFAULT;
return new AuthCookieDataImpl(toTimespan(data.get(KeyConstants._timeout, null), AuthCookieDataImpl.DEFAULT.getTimeout()),
Caster.toBooleanValue(data.get(DISABLE_UPDATE, null), AuthCookieDataImpl.DEFAULT.isDisableUpdate()));
}
private static TimeSpan toTimespan(Object obj, TimeSpan defaultValue) {
if (!(obj instanceof TimeSpan)) {
Double tmp = Caster.toDouble(obj, null);
if (tmp != null && tmp.doubleValue() <= 0d) return TimeSpanImpl.fromMillis(CookieImpl.NEVER * 1000);
}
return Caster.toTimespan(obj, defaultValue);
}
public static Server[] toMailServers(Config config, Array data, Server defaultValue) {
List<Server> list = new ArrayList<Server>();
if (data != null) {
Iterator<Object> it = data.valueIterator();
Struct sct;
Server se;
while (it.hasNext()) {
sct = Caster.toStruct(it.next(), null);
if (sct == null) continue;
se = toMailServer(config, sct, null);
if (se != null) list.add(se);
}
}
return list.toArray(new Server[list.size()]);
}
public static Server toMailServer(Config config, Struct data, Server defaultValue) {
String hostName = Caster.toString(data.get(KeyConstants._host, null), null);
if (StringUtil.isEmpty(hostName, true)) hostName = Caster.toString(data.get(KeyConstants._server, null), null);
if (StringUtil.isEmpty(hostName, true)) return defaultValue;
int port = Caster.toIntValue(data.get(KeyConstants._port, null), 25);
String username = Caster.toString(data.get(KeyConstants._username, null), null);
if (StringUtil.isEmpty(username, true)) username = Caster.toString(data.get(KeyConstants._user, null), null);
String password = ConfigWebUtil.decrypt(Caster.toString(data.get(KeyConstants._password, null), null));
username = translateValue(username);
password = translateValue(password);
TimeSpan lifeTimespan = Caster.toTimespan(data.get("lifeTimespan", null), null);
if (lifeTimespan == null) lifeTimespan = Caster.toTimespan(data.get("life", null), FIVE_MINUTES);
TimeSpan idleTimespan = Caster.toTimespan(data.get("idleTimespan", null), null);
if (idleTimespan == null) idleTimespan = Caster.toTimespan(data.get("idle", null), ONE_MINUTE);
Object value = data.get("tls", null);
if (value == null) value = data.get("useTls", null);
boolean tls = Caster.toBooleanValue(value, false);
value = data.get("ssl", null);
if (value == null) value = data.get("useSsl", null);
boolean ssl = Caster.toBooleanValue(value, false);
return new ServerImpl(-1, hostName, port, username, password, lifeTimespan.getMillis(), idleTimespan.getMillis(), tls, ssl, false, ServerImpl.TYPE_LOCAL); // MUST improve
// store
// connection
// somehow
}
public static FTPConnectionData toFTP(Struct sct) {
// username
Object o = sct.get(KeyConstants._username, null);
if (o == null) o = sct.get(KeyConstants._user, null);
String user = Caster.toString(o, null);
if (StringUtil.isEmpty(user)) user = null;
// password
o = sct.get(KeyConstants._password, null);
if (o == null) o = sct.get(KeyConstants._pass, null);
String pass = Caster.toString(o, null);
if (StringUtil.isEmpty(pass)) pass = user != null ? "" : null;
user = translateValue(user);
pass = translateValue(pass);
// host
o = sct.get(KeyConstants._host, null);
if (o == null) o = sct.get(KeyConstants._server, null);
String host = Caster.toString(o, null);
if (StringUtil.isEmpty(host)) host = null;
// port
o = sct.get(KeyConstants._port, null);
int port = Caster.toIntValue(o, 0);
return new FTPConnectionData(host, user, pass, port);
}
public static java.util.List<Resource> loadResources(Config config, ApplicationContext ac, Object obj, boolean onlyDir) {
Resource res;
if (!Decision.isArray(obj)) {
String list = Caster.toString(obj, null);
if (!StringUtil.isEmpty(list)) {
obj = ListUtil.listToArray(list, ',');
}
}
if (Decision.isArray(obj)) {
Array arr = Caster.toArray(obj, null);
java.util.List<Resource> list = new ArrayList<Resource>();
Iterator<Object> it = arr.valueIterator();
while (it.hasNext()) {
try {
String path = Caster.toString(it.next(), null);
if (path == null) continue;
res = toResourceExisting(config, ac, path, onlyDir);
if (res != null) list.add(res);
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
}
return list;
}
return null;
}
public static Resource toResourceExisting(Config config, ApplicationContext ac, Object obj, boolean onlyDir) {
// Resource root = config.getRootDirectory();
String path = Caster.toString(obj, null);
if (StringUtil.isEmpty(path, true)) return null;
path = path.trim();
Resource res;
PageContext pc = ThreadLocalPageContext.get();
// first check relative to application . cfc
if (pc != null) {
if (ac == null) ac = pc.getApplicationContext();
// abs path
if (path.startsWith("/")) {
ConfigWebPro cwi = (ConfigWebPro) config;
PageSource ps = cwi.getPageSourceExisting(pc, ac == null ? null : ac.getMappings(), path, false, false, true, false);
if (ps != null) {
res = ps.getResource();
if (res != null && (!onlyDir || res.isDirectory())) return res;
}
}
// real path
else {
Resource src = ac != null ? ac.getSource() : null;
if (src != null) {
res = src.getParentResource().getRealResource(path);
if (res != null && (!onlyDir || res.isDirectory())) return res;
}
// happens when this is called from within the application . cfc (init)
else {
res = ResourceUtil.toResourceNotExisting(pc, path);
if (res != null && (!onlyDir || res.isDirectory())) return res;
}
}
}
// then in the webroot
res = config.getRootDirectory().getRealResource(path);
if (res != null && (!onlyDir || res.isDirectory())) return res;
// then absolute
res = ResourceUtil.toResourceNotExisting(config, path);
if (res != null && (!onlyDir || res.isDirectory())) return res;
return null;
}
public static int toVariableUsage(String str) throws ApplicationException {
int i = toVariableUsage(str, 0);
if (i != 0) return i;
throw new ApplicationException("variable usage [" + str + "] is invalid, valid values are [ignore,warn,error]");
}
public static int toVariableUsage(String str, int defaultValue) {
if (str == null) return defaultValue;
str = str.trim().toLowerCase();
if ("ignore".equals(str)) return ConfigPro.QUERY_VAR_USAGE_IGNORE;
if ("warn".equals(str)) return ConfigPro.QUERY_VAR_USAGE_WARN;
if ("warning".equals(str)) return ConfigPro.QUERY_VAR_USAGE_WARN;
if ("error".equals(str)) return ConfigPro.QUERY_VAR_USAGE_ERROR;
Boolean b = Caster.toBoolean(str, null);
if (b != null) {
return b.booleanValue() ? ConfigPro.QUERY_VAR_USAGE_ERROR : ConfigPro.QUERY_VAR_USAGE_IGNORE;
}
return defaultValue;
}
public static String toVariableUsage(int i, String defaultValue) {
if (ConfigPro.QUERY_VAR_USAGE_IGNORE == i) return "ignore";
if (ConfigPro.QUERY_VAR_USAGE_WARN == i) return "warn";
if (ConfigPro.QUERY_VAR_USAGE_ERROR == i) return "error";
return defaultValue;
}
public static String toClassName(Struct sct) {
if (sct == null) return null;
String className = Caster.toString(sct.get("class", null), null);
if (StringUtil.isEmpty(className)) className = Caster.toString(sct.get("classname", null), null);
if (StringUtil.isEmpty(className)) className = Caster.toString(sct.get("class-name", null), null);
if (StringUtil.isEmpty(className)) return null;
return className;
}
public static String toBundleName(Struct sct) {
if (sct == null) return null;
String name = Caster.toString(sct.get("bundlename", null), null);
if (StringUtil.isEmpty(name)) name = Caster.toString(sct.get("bundle-name", null), null);
if (StringUtil.isEmpty(name)) name = Caster.toString(sct.get("name", null), null);
if (StringUtil.isEmpty(name)) return null;
return name;
}
public static Version toBundleVersion(Struct sct) {
if (sct == null) return null;
Version version = OSGiUtil.toVersion(Caster.toString(sct.get("bundleversion", null), null), null);
if (version == null) version = OSGiUtil.toVersion(Caster.toString(sct.get("bundle-version", null), null), null);
if (version == null) version = OSGiUtil.toVersion(Caster.toString(sct.get("version", null), null), null);
return version;
}
public static boolean getPreciseMath(PageContext pc, Config config) {
pc = ThreadLocalPageContext.get(pc);
if (pc != null) return ((ApplicationContextSupport) pc.getApplicationContext()).getPreciseMath();
config = ThreadLocalPageContext.getConfig(config);
if (config != null) return ((ConfigPro) config).getPreciseMath();
return false;
}
} |
package net.katsuster.ememu.riscv.core;
import net.katsuster.ememu.generic.*;
import java.math.*;
import java.util.concurrent.locks.*;
public class ExecStageRVI extends Stage64 {
/**
* RVI
*
* @param c CPU
*/
public ExecStageRVI(RV64 c) {
super(c);
}
@Override
public RV64 getCore() {
return (RV64)super.getCore();
}
/**
* CSR
*
* @param n
* @return
*/
public long getCSR(int n) {
return getCore().getCSR(n);
}
/**
* CSR
*
* @param n
* @param val
*/
public void setCSR(int n, long val) {
getCore().setCSR(n, val);
}
/**
* CSR
*
* @param n
* @return
*/
public String getCSRName(int n) {
return getCore().getCSRName(n);
}
/**
* Fence pred, succ
*
* @param n pred succ
* @return pred succ
*/
public String getPredName(int n) {
StringBuffer result = new StringBuffer();
if ((n & 8) != 0) {
result.append("i");
}
if ((n & 4) != 0) {
result.append("o");
}
if ((n & 2) != 0) {
result.append("r");
}
if ((n & 1) != 0) {
result.append("w");
}
return result.toString();
}
public void waitInt() {
RV64 c = getCore();
synchronized (c) {
while (!c.isRaisedInterrupt() &&
!c.isRaisedInternalInterrupt() &&
!c.shouldHalt()) {
try {
c.wait(1000);
} catch (InterruptedException ex) {
//do nothing
}
}
}
}
/**
* AUIPC (Add upper immediate to pc)
*
* @param inst 32bit
* @param exec true false
*/
public void executeAuipc(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int imm20 = inst.getImm20U();
long imm = BitOp.signExt64((imm20 << 12) & 0xffffffffL, 32);
if (!exec) {
printDisasm(inst, "auipc",
String.format("%s, 0x%x", getRegName(rd), imm));
return;
}
setReg(rd, getPC() + imm);
}
/**
* LUI (Load upper immediate)
*
* @param inst 32bit
* @param exec true false
*/
public void executeLui(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int imm20 = inst.getImm20U();
long imm = BitOp.signExt64((imm20 << 12) & 0xffffffffL, 31);
if (!exec) {
printDisasm(inst, "lui",
String.format("%s, 0x%x", getRegName(rd), imm));
return;
}
setReg(rd, imm);
}
/**
* JAL (Jump and link)
*
* @param inst 32bit
* @param exec true false
*/
public void executeJal(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
long off = BitOp.signExt64(inst.getImm20J(), 20);
long t;
if (!exec) {
printDisasm(inst, "jal",
String.format("%s, 0x%x", getRegName(rd),
off + getPC()));
return;
}
t = getPC() + 4;
jumpRel((int)off);
setReg(rd, t);
}
/**
* JALR (Jump and link register)
*
* @param inst 32bit
* @param exec true false
*/
public void executeJalr(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
long off = BitOp.signExt64(inst.getImm12I(), 12);
long t;
if (!exec) {
printDisasm(inst, "jalr",
String.format("%s, %d(%s) # 0x%x", getRegName(rd),
off, getRegName(rs1), getReg(rs1) + off));
return;
}
t = getPC() + 4;
setPC((getReg(rs1) + off) & ~0x1L);
setReg(rd, t);
}
/**
* BEQ (Branch if equal)
*
* @param inst 32bit
* @param exec true false
*/
public void executeBeq(InstructionRV32 inst, boolean exec) {
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
int off = BitOp.signExt32(inst.getImm13B(), 13);
if (!exec) {
printDisasm(inst, "beq",
String.format("%s, %s, 0x%x", getRegName(rs1),
getRegName(rs2), getPC() + off));
return;
}
if (getReg(rs1) == getReg(rs2)) {
jumpRel(off);
}
}
/**
* BNE (Branch if not equal)
*
* @param inst 32bit
* @param exec true false
*/
public void executeBne(InstructionRV32 inst, boolean exec) {
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
int off = BitOp.signExt32(inst.getImm13B(), 13);
if (!exec) {
printDisasm(inst, "bne",
String.format("%s, %s, 0x%x", getRegName(rs1),
getRegName(rs2), getPC() + off));
return;
}
if (getReg(rs1) != getReg(rs2)) {
jumpRel(off);
}
}
/**
* BLT (Branch if less than)
*
* @param inst 32bit
* @param exec true false
*/
public void executeBlt(InstructionRV32 inst, boolean exec) {
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
int off = BitOp.signExt32(inst.getImm13B(), 13);
if (!exec) {
printDisasm(inst, "blt",
String.format("%s, %s, 0x%x", getRegName(rs1),
getRegName(rs2), getPC() + off));
return;
}
if (getReg(rs1) < getReg(rs2)) {
jumpRel(off);
}
}
/**
* BGE (Branch if greater than or equal)
*
* @param inst 32bit
* @param exec true false
*/
public void executeBge(InstructionRV32 inst, boolean exec) {
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
int off = BitOp.signExt32(inst.getImm13B(), 13);
if (!exec) {
printDisasm(inst, "bge",
String.format("%s, %s, 0x%x", getRegName(rs1),
getRegName(rs2), getPC() + off));
return;
}
if (getReg(rs1) >= getReg(rs2)) {
jumpRel(off);
}
}
/**
* BLTU (Branch if less than, unsigned)
*
* @param inst 32bit
* @param exec true false
*/
public void executeBltu(InstructionRV32 inst, boolean exec) {
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
int off = BitOp.signExt32(inst.getImm13B(), 13);
if (!exec) {
printDisasm(inst, "bltu",
String.format("%s, %s, 0x%x", getRegName(rs1),
getRegName(rs2), getPC() + off));
return;
}
if (IntegerExt.compareUint64(getReg(rs1), getReg(rs2)) < 0) {
jumpRel(off);
}
}
/**
* BGEU (Branch if greater than or equal, unsigned)
*
* @param inst 32bit
* @param exec true false
*/
public void executeBgeu(InstructionRV32 inst, boolean exec) {
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
int off = BitOp.signExt32(inst.getImm13B(), 13);
if (!exec) {
printDisasm(inst, "bgeu",
String.format("%s, %s, 0x%x", getRegName(rs1),
getRegName(rs2), getPC() + off));
return;
}
if (IntegerExt.compareUint64(getReg(rs1), getReg(rs2)) >= 0) {
jumpRel(off);
}
}
/**
* LBU (Load byte, unsigned)
*
* @param inst 32bit
* @param exec true false
*/
public void executeLbu(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int imm12 = inst.getImm12I();
long off = BitOp.signExt64(imm12, 12);
long vaddr, paddr;
byte val;
if (!exec) {
printDisasm(inst, "lbu",
String.format("%s, %d(%s) # 0x%x",
getRegName(rd), off, getRegName(rs1), imm12));
return;
}
vaddr = getReg(rs1) + off;
//paddr = getMMU().translate(vaddr, 1, false, getPriv(), true);
paddr = vaddr;
//if (getMMU().isFault()) {
// getMMU().clearFault();
// return;
if (!tryRead(paddr, 1)) {
//raiseException(ARMv5.EXCEPT_ABT_DATA,
// String.format("ldrd [%08x]", paddr));
return;
}
val = read8(paddr);
setReg(rd, val & 0xffL);
}
/**
* LW (Load word)
*
* @param inst 32bit
* @param exec true false
*/
public void executeLw(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int imm12 = inst.getImm12I();
long off = BitOp.signExt64(imm12, 12);
long vaddr, paddr;
int val;
if (!exec) {
printDisasm(inst, "lw",
String.format("%s, %d(%s) # 0x%x",
getRegName(rd), off, getRegName(rs1), imm12));
return;
}
vaddr = getReg(rs1) + off;
//paddr = getMMU().translate(vaddr, 4, false, getPriv(), true);
paddr = vaddr;
//if (getMMU().isFault()) {
// getMMU().clearFault();
// return;
if (!tryRead(paddr, 4)) {
//raiseException(ARMv5.EXCEPT_ABT_DATA,
// String.format("ldrd [%08x]", paddr));
return;
}
val = read32(paddr);
setReg(rd, BitOp.signExt64(val & 0xffffffffL, 32));
}
/**
* SB (Store byte)
*
* @param inst 32bit
* @param exec true false
*/
public void executeSb(InstructionRV32 inst, boolean exec) {
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
int offraw = inst.getImm12S();
long off = BitOp.signExt64(offraw, 12);
long vaddr, paddr;
if (!exec) {
printDisasm(inst, "sb",
String.format("%s, %d(%s) # 0x%x",
getRegName(rs2), off, getRegName(rs1), offraw));
return;
}
vaddr = getReg(rs1) + off;
//paddr = getMMU().translate(vaddr, 1, false, getPriv(), true);
paddr = vaddr;
//if (getMMU().isFault()) {
// getMMU().clearFault();
// return;
if (!tryWrite(paddr, 1)) {
//raiseException(ARMv5.EXCEPT_ABT_DATA,
// String.format("ldrd [%08x]", paddr));
return;
}
write8(paddr, (byte)getReg(rs2));
}
/**
* SW (Store word)
*
* @param inst 32bit
* @param exec true false
*/
public void executeSw(InstructionRV32 inst, boolean exec) {
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
int offraw = inst.getImm12S();
long off = BitOp.signExt64(offraw, 12);
long vaddr, paddr;
if (!exec) {
printDisasm(inst, "sw",
String.format("%s, %d(%s) # 0x%x",
getRegName(rs2), off, getRegName(rs1), offraw));
return;
}
vaddr = getReg(rs1) + off;
//paddr = getMMU().translate(vaddr, 4, false, getPriv(), true);
paddr = vaddr;
//if (getMMU().isFault()) {
// getMMU().clearFault();
// return;
if (!tryWrite(paddr, 4)) {
//raiseException(ARMv5.EXCEPT_ABT_DATA,
// String.format("ldrd [%08x]", paddr));
return;
}
write32(paddr, (int)getReg(rs2));
}
/**
* SD (Store double word)
*
* @param inst 32bit
* @param exec true false
*/
public void executeSd(InstructionRV32 inst, boolean exec) {
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
int offraw = inst.getImm12S();
long off = BitOp.signExt64(offraw, 12);
long vaddr, paddr;
if (!exec) {
printDisasm(inst, "sd",
String.format("%s, %d(%s) # 0x%x",
getRegName(rs2), off, getRegName(rs1), offraw));
return;
}
vaddr = getReg(rs1) + off;
//paddr = getMMU().translate(vaddr, 4, false, getPriv(), true);
paddr = vaddr;
//if (getMMU().isFault()) {
// getMMU().clearFault();
// return;
if (!tryWrite(paddr, 8)) {
//raiseException(ARMv5.EXCEPT_ABT_DATA,
// String.format("ldrd [%08x]", paddr));
return;
}
write64(paddr, getReg(rs2));
}
/**
* ADDI (Add immediate)
*
* @param inst 32bit
* @param exec true false
*/
public void executeAddi(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int imm12 = inst.getImm12I();
long imm = BitOp.signExt64(imm12, 12);
if (!exec) {
printDisasm(inst, "addi",
String.format("%s, %s, %d # 0x%x", getRegName(rd),
getRegName(rs1), imm, imm12));
return;
}
setReg(rd, getReg(rs1) + imm);
}
/**
* XORI (Exclusive-or immediate)
*
* @param inst 32bit
* @param exec true false
*/
public void executeXori(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int imm12 = inst.getImm12I();
long imm = BitOp.signExt64(imm12, 12);
if (!exec) {
printDisasm(inst, "xori",
String.format("%s, %s, %d # 0x%x", getRegName(rd),
getRegName(rs1), imm, imm12));
return;
}
setReg(rd, getReg(rs1) ^ imm);
}
/**
* ORI (Or immediate)
*
* @param inst 32bit
* @param exec true false
*/
public void executeOri(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int imm12 = inst.getImm12I();
long imm = BitOp.signExt64(imm12, 12);
if (!exec) {
printDisasm(inst, "ori",
String.format("%s, %s, %d # 0x%x", getRegName(rd),
getRegName(rs1), imm, imm12));
return;
}
setReg(rd, getReg(rs1) | imm);
}
/**
* ANDI (And immediate)
*
* @param inst 32bit
* @param exec true false
*/
public void executeAndi(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int imm12 = inst.getImm12I();
long imm = BitOp.signExt64(imm12, 12);
if (!exec) {
printDisasm(inst, "andi",
String.format("%s, %s, %d # 0x%x", getRegName(rd),
getRegName(rs1), imm, imm12));
return;
}
setReg(rd, getReg(rs1) & imm);
}
/**
* SLLI (Shift left logical immediate)
*
* @param inst 32bit
* @param exec true false
*/
public void executeSlli(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int shamt = inst.getField(20, 6);
if (!exec) {
printDisasm(inst, "slli",
String.format("%s, %s, 0x%x # %d", getRegName(rd),
getRegName(rs1), shamt, shamt));
return;
}
setReg(rd, getReg(rs1) << shamt);
}
/**
* SRLI (Shift right logical immediate)
*
* @param inst 32bit
* @param exec true false
*/
public void executeSrli(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int shamt = inst.getField(20, 6);
if (!exec) {
printDisasm(inst, "srli",
String.format("%s, %s, 0x%x # %d", getRegName(rd),
getRegName(rs1), shamt, shamt));
return;
}
setReg(rd, getReg(rs1) >>> shamt);
}
/**
* SRAI (Shift right arithmetic immediate)
*
* @param inst 32bit
* @param exec true false
*/
public void executeSrai(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int shamt = inst.getField(20, 6);
if (!exec) {
printDisasm(inst, "srai",
String.format("%s, %s, 0x%x # %d", getRegName(rd),
getRegName(rs1), shamt, shamt));
return;
}
setReg(rd, getReg(rs1) >> shamt);
}
/**
* ADD (Add)
*
* @param inst 32bit
* @param exec true false
*/
public void executeAdd(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
if (!exec) {
printDisasm(inst, "add",
String.format("%s, %s, %s", getRegName(rd),
getRegName(rs1), getRegName(rs2)));
return;
}
setReg(rd, getReg(rs1) + getReg(rs2));
}
/**
* SUB (Subtract)
*
* @param inst 32bit
* @param exec true false
*/
public void executeSub(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
if (!exec) {
printDisasm(inst, "sub",
String.format("%s, %s, %s", getRegName(rd),
getRegName(rs1), getRegName(rs2)));
return;
}
setReg(rd, getReg(rs1) - getReg(rs2));
}
/**
* SLL (Shift left logical)
*
* @param inst 32bit
* @param exec true false
*/
public void executeSll(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
if (!exec) {
printDisasm(inst, "sll",
String.format("%s, %s, %s", getRegName(rd),
getRegName(rs1), getRegName(rs2)));
return;
}
setReg(rd, getReg(rs1) << getReg(rs2));
}
/**
* XOR (Exclusive-or)
*
* @param inst 32bit
* @param exec true false
*/
public void executeXor(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
if (!exec) {
printDisasm(inst, "xor",
String.format("%s, %s, %s", getRegName(rd),
getRegName(rs1), getRegName(rs2)));
return;
}
setReg(rd, getReg(rs1) ^ getReg(rs2));
}
/**
* Fence (Fence memory and I/O)
*
* @param inst 32bit
* @param exec true false
*/
public void executeFence(InstructionRV32 inst, boolean exec) {
int imm = inst.getImm12I();
int succ = BitOp.getField32(imm, 0, 4);
int pred = BitOp.getField32(imm, 4, 4);
if (!exec) {
printDisasm(inst, "fence",
String.format("%s, %s", getPredName(pred),
getPredName(succ)));
return;
}
}
/**
* CSRRW (Control and status register read and write)
*
* @param inst 32bit
* @param exec true false
*/
public void executeCsrrw(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int csr = inst.getImm12I();
long t;
if (!exec) {
printDisasm(inst, "csrrw",
String.format("%s, %s, %s", getRegName(rd),
getCSRName(csr), getRegName(rs1)));
return;
}
t = getCSR(csr);
setCSR(csr, getReg(rs1));
setReg(rd, t);
}
/**
* CSRRS (Control and status register read and set)
*
* @param inst 32bit
* @param exec true false
*/
public void executeCsrrs(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int csr = inst.getImm12I();
long t;
if (!exec) {
printDisasm(inst, "csrrs",
String.format("%s, %s, %s", getRegName(rd),
getCSRName(csr), getRegName(rs1)));
return;
}
t = getCSR(csr);
setCSR(csr, t | getReg(rs1));
setReg(rd, t);
}
/**
* WFI ()
*
* @param inst 32bit
* @param exec true false
*/
public void executeWfi(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int imm12 = inst.getImm12I();
long imm = BitOp.signExt64(imm12, 12);
long v;
if (!exec) {
printDisasm(inst, "wfi", "");
return;
}
waitInt();
}
/**
* LD (Load doubleword)
*
* @param inst 32bit
* @param exec true false
*/
public void executeLd(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int imm12 = inst.getImm12I();
long off = BitOp.signExt64(imm12, 12);
long vaddr, paddr;
long val;
if (!exec) {
printDisasm(inst, "ld",
String.format("%s, %d(%s) # 0x%x",
getRegName(rd), off, getRegName(rs1), imm12));
return;
}
vaddr = getReg(rs1) + off;
//paddr = getMMU().translate(vaddr, 8, false, getPriv(), true);
paddr = vaddr;
//if (getMMU().isFault()) {
// getMMU().clearFault();
// return;
if (!tryRead(paddr, 8)) {
//raiseException(ARMv5.EXCEPT_ABT_DATA,
// String.format("ldrd [%08x]", paddr));
return;
}
val = read64(paddr);
setReg(rd, val);
}
/**
* ADDIW (Add word immediate)
*
* @param inst 32bit
* @param exec true false
*/
public void executeAddiw(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int imm12 = inst.getImm12I();
long imm = BitOp.signExt64(imm12, 12);
long v;
if (!exec) {
printDisasm(inst, "addiw",
String.format("%s, %s, %d # 0x%x", getRegName(rd),
getRegName(rs1), imm, imm12));
return;
}
v = getReg(rs1) + imm;
setReg(rd, BitOp.signExt64(v & 0xffffffffL, 32));
}
/**
* SRLIW (Shift right logical word immediate)
*
* @param inst 32bit
* @param exec true false
*/
public void executeSrliw(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int shamt = inst.getField(20, 6);
long v;
if (!exec) {
printDisasm(inst, "srliw",
String.format("%s, %s, 0x%x # %d", getRegName(rd),
getRegName(rs1), shamt, shamt));
return;
}
v = (getReg(rs1) & 0xffffffffL) >>> shamt;
setReg(rd, BitOp.signExt64(v & 0xffffffffL, 32));
}
/**
* SRAIW (Shift right arithmetic word immediate)
*
* @param inst 32bit
* @param exec true false
*/
public void executeSraiw(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int shamt = inst.getField(20, 6);
long v;
if (!exec) {
printDisasm(inst, "sraiw",
String.format("%s, %s, 0x%x # %d", getRegName(rd),
getRegName(rs1), shamt, shamt));
return;
}
v = (int)getReg(rs1) >> shamt;
setReg(rd, BitOp.signExt64(v & 0xffffffffL, 32));
}
/**
* ADDW (Add word)
*
* @param inst 32bit
* @param exec true false
*/
public void executeAddw(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
long v;
if (!exec) {
printDisasm(inst, "addw",
String.format("%s, %s, %s", getRegName(rd),
getRegName(rs1), getRegName(rs2)));
return;
}
v = getReg(rs1) + getReg(rs2);
setReg(rd, BitOp.signExt64(v & 0xffffffffL, 32));
}
/**
* SUBW (subtract word)
*
* @param inst 32bit
* @param exec true false
*/
public void executeSubw(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
long v;
if (!exec) {
printDisasm(inst, "subw",
String.format("%s, %s, %s", getRegName(rd),
getRegName(rs1), getRegName(rs2)));
return;
}
v = getReg(rs1) - getReg(rs2);
setReg(rd, BitOp.signExt64(v & 0xffffffffL, 32));
}
/**
* SRLW (shift right logical word)
*
* @param inst 32bit
* @param exec true false
*/
public void executeSrlw(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
long v;
if (!exec) {
printDisasm(inst, "srlw",
String.format("%s, %s, %s", getRegName(rd),
getRegName(rs1), getRegName(rs2)));
return;
}
v = (getReg(rs1) & 0xffffffffL) >>> getReg(rs2);
setReg(rd, BitOp.signExt64(v & 0xffffffffL, 32));
}
/**
* MUL (Multiply)
*
* @param inst 32bit
* @param exec true false
*/
public void executeMul(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
if (!exec) {
printDisasm(inst, "mul",
String.format("%s, %s, %s", getRegName(rd),
getRegName(rs1), getRegName(rs2)));
return;
}
setReg(rd, getReg(rs1) * getReg(rs2));
}
/**
* DIVU (Divide, Unsigned)
*
* @param inst 32bit
* @param exec true false
*/
public void executeDivu(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
BigInteger dividend, divisor;
if (!exec) {
printDisasm(inst, "divu",
String.format("%s, %s, %s", getRegName(rd),
getRegName(rs1), getRegName(rs2)));
return;
}
dividend = BitOp.toUnsignedBigInt(getReg(rs1));
divisor = BitOp.toUnsignedBigInt(getReg(rs2));
setReg(rd, dividend.divide(divisor).longValue());
}
/**
* DIVUW (Divide word, Unsigned)
*
* @param inst 32bit
* @param exec true false
*/
public void executeDivuw(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
long dividend, divisor;
if (!exec) {
printDisasm(inst, "divuw",
String.format("%s, %s, %s", getRegName(rd),
getRegName(rs1), getRegName(rs2)));
return;
}
dividend = getReg(rs1) & 0xffffffffL;
divisor = getReg(rs2) & 0xffffffffL;
setReg(rd, BitOp.signExt64(dividend / divisor, 32));
}
/**
* AMOSWAP.W (Atomic memory operation: Swap word)
*
* @param inst 32bit
* @param exec true false
*/
public void executeAmoswapw(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
int aq = (inst.getFunct7R() >> 1) & 1;
int rl = inst.getFunct7R() & 1;
long vaddr, paddr;
int t, valRs2;
Lock l;
if (!exec) {
String name = "amoswap.w";
if (aq != 0) {
name += ".aq";
}
if (rl != 0) {
name += ".rl";
}
printDisasm(inst, name,
String.format("%s, %s, (%s)", getRegName(rd),
getRegName(rs2), getRegName(rs1)));
return;
}
vaddr = getReg(rs1);
//paddr = getMMU().translate(vaddr, 4, false, getPriv(), true);
paddr = vaddr;
//if (getMMU().isFault()) {
// getMMU().clearFault();
// return;
valRs2 = (int)getReg(rs2);
l = getWriteLock();
l.lock();
try {
if (!tryRead(paddr, 4)) {
//raiseException(ARMv5.EXCEPT_ABT_DATA,
// String.format("ldrd [%08x]", paddr));
return;
}
t = read32(paddr);
write32(paddr, valRs2);
} finally {
l.unlock();
}
setReg(rd, BitOp.signExt64(t & 0xffffffffL, 32));
}
/**
* AMOADD.W (Atomic memory operation: Add word)
*
* @param inst 32bit
* @param exec true false
*/
public void executeAmoaddw(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
int aq = (inst.getFunct7R() >> 1) & 1;
int rl = inst.getFunct7R() & 1;
long vaddr, paddr;
int t, valRs2;
Lock l;
if (!exec) {
String name = "amoadd.w";
if (aq != 0) {
name += ".aq";
}
if (rl != 0) {
name += ".rl";
}
printDisasm(inst, name,
String.format("%s, %s, (%s)", getRegName(rd),
getRegName(rs2), getRegName(rs1)));
return;
}
vaddr = getReg(rs1);
//paddr = getMMU().translate(vaddr, 4, false, getPriv(), true);
paddr = vaddr;
//if (getMMU().isFault()) {
// getMMU().clearFault();
// return;
valRs2 = (int)getReg(rs2);
l = getWriteLock();
l.lock();
try {
if (!tryRead(paddr, 4)) {
//raiseException(ARMv5.EXCEPT_ABT_DATA,
// String.format("ldrd [%08x]", paddr));
return;
}
t = read32(paddr);
write32(paddr, t + valRs2);
} finally {
l.unlock();
}
setReg(rd, BitOp.signExt64(t & 0xffffffffL, 32));
}
/**
* AMOAND.W (Atomic memory operation: and word)
*
* @param inst 32bit
* @param exec true false
*/
public void executeAmoandw(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
int aq = (inst.getFunct7R() >> 1) & 1;
int rl = inst.getFunct7R() & 1;
long vaddr, paddr;
int t, valRs2;
Lock l;
if (!exec) {
String name = "amoand.w";
if (aq != 0) {
name += ".aq";
}
if (rl != 0) {
name += ".rl";
}
printDisasm(inst, name,
String.format("%s, %s, (%s)", getRegName(rd),
getRegName(rs2), getRegName(rs1)));
return;
}
vaddr = getReg(rs1);
//paddr = getMMU().translate(vaddr, 4, false, getPriv(), true);
paddr = vaddr;
//if (getMMU().isFault()) {
// getMMU().clearFault();
// return;
valRs2 = (int)getReg(rs2);
l = getWriteLock();
l.lock();
try {
if (!tryRead(paddr, 4)) {
//raiseException(ARMv5.EXCEPT_ABT_DATA,
// String.format("ldrd [%08x]", paddr));
return;
}
t = read32(paddr);
write32(paddr, t & valRs2);
} finally {
l.unlock();
}
setReg(rd, BitOp.signExt64(t & 0xffffffffL, 32));
}
/**
* AMOOR.W (Atomic memory operation: OR word)
*
* @param inst 32bit
* @param exec true false
*/
public void executeAmoorw(InstructionRV32 inst, boolean exec) {
int rd = inst.getRd();
int rs1 = inst.getRs1();
int rs2 = inst.getRs2();
int aq = (inst.getFunct7R() >> 1) & 1;
int rl = inst.getFunct7R() & 1;
long vaddr, paddr;
int t, valRs2;
Lock l;
if (!exec) {
String name = "amoor.w";
if (aq != 0) {
name += ".aq";
}
if (rl != 0) {
name += ".rl";
}
printDisasm(inst, name,
String.format("%s, %s, (%s)", getRegName(rd),
getRegName(rs2), getRegName(rs1)));
return;
}
vaddr = getReg(rs1);
//paddr = getMMU().translate(vaddr, 4, false, getPriv(), true);
paddr = vaddr;
//if (getMMU().isFault()) {
// getMMU().clearFault();
// return;
valRs2 = (int)getReg(rs2);
l = getWriteLock();
l.lock();
try {
if (!tryRead(paddr, 4)) {
//raiseException(ARMv5.EXCEPT_ABT_DATA,
// String.format("ldrd [%08x]", paddr));
return;
}
t = read32(paddr);
write32(paddr, t | valRs2);
} finally {
l.unlock();
}
setReg(rd, BitOp.signExt64(t & 0xffffffffL, 32));
}
/**
* 32bit
*
* @param decinst
* @param exec true false
*/
public void execute(Opcode decinst, boolean exec) {
InstructionRV32 inst = (InstructionRV32) decinst.getInstruction();
switch (decinst.getIndex()) {
case INS_RV32I_AUIPC:
executeAuipc(inst, exec);
break;
case INS_RV32I_LUI:
executeLui(inst, exec);
break;
case INS_RV32I_JAL:
executeJal(inst, exec);
break;
case INS_RV32I_JALR:
executeJalr(inst, exec);
break;
case INS_RV32I_BEQ:
executeBeq(inst, exec);
break;
case INS_RV32I_BNE:
executeBne(inst, exec);
break;
case INS_RV32I_BLT:
executeBlt(inst, exec);
break;
case INS_RV32I_BGE:
executeBge(inst, exec);
break;
case INS_RV32I_BLTU:
executeBltu(inst, exec);
break;
case INS_RV32I_BGEU:
executeBgeu(inst, exec);
break;
case INS_RV32I_LBU:
executeLbu(inst, exec);
break;
case INS_RV32I_LW:
executeLw(inst, exec);
break;
case INS_RV32I_SB:
executeSb(inst, exec);
break;
case INS_RV32I_SW:
executeSw(inst, exec);
break;
case INS_RV64I_SD:
executeSd(inst, exec);
break;
case INS_RV32I_ADDI:
executeAddi(inst, exec);
break;
case INS_RV32I_XORI:
executeXori(inst, exec);
break;
case INS_RV32I_ORI:
executeOri(inst, exec);
break;
case INS_RV32I_ANDI:
executeAndi(inst, exec);
break;
case INS_RV32I_SLLI:
case INS_RV64I_SLLI:
executeSlli(inst, exec);
break;
case INS_RV32I_SRLI:
case INS_RV64I_SRLI:
executeSrli(inst, exec);
break;
case INS_RV32I_SRAI:
case INS_RV64I_SRAI:
executeSrai(inst, exec);
break;
case INS_RV32I_ADD:
executeAdd(inst, exec);
break;
case INS_RV32I_SUB:
executeSub(inst, exec);
break;
case INS_RV32I_SLL:
executeSll(inst, exec);
break;
case INS_RV32I_XOR:
executeXor(inst, exec);
break;
case INS_RV32I_FENCE:
executeFence(inst, exec);
break;
case INS_RV32I_CSRRW:
executeCsrrw(inst, exec);
break;
case INS_RV32I_CSRRS:
executeCsrrs(inst, exec);
break;
case INS_RV32I_WFI:
executeWfi(inst, exec);
break;
case INS_RV64I_LD:
executeLd(inst, exec);
break;
case INS_RV64I_ADDIW:
executeAddiw(inst, exec);
break;
case INS_RV64I_SRLIW:
executeSrliw(inst, exec);
break;
case INS_RV64I_SRAIW:
executeSraiw(inst, exec);
break;
case INS_RV64I_ADDW:
executeAddw(inst, exec);
break;
case INS_RV64I_SUBW:
executeSubw(inst, exec);
break;
case INS_RV64I_SRLW:
executeSrlw(inst, exec);
break;
case INS_RV32M_MUL:
executeMul(inst, exec);
break;
case INS_RV32M_DIVU:
executeDivu(inst, exec);
break;
case INS_RV64M_DIVUW:
executeDivuw(inst, exec);
break;
case INS_RV32A_AMOSWAP_W:
executeAmoswapw(inst, exec);
break;
case INS_RV32A_AMOADD_W:
executeAmoaddw(inst, exec);
break;
case INS_RV32A_AMOAND_W:
executeAmoandw(inst, exec);
break;
case INS_RV32A_AMOOR_W:
executeAmoorw(inst, exec);
break;
default:
throw new IllegalArgumentException("Unknown RV32I instruction " +
decinst.getIndex());
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.